Rules Generator
Analyze a directory and generate .claude/rules/ files for Claude Code domain memory.
Core Concept
Generalized agents fail because they're "amnesiacs with a tool belt." Each session starts with no grounded sense of where we are.
Solution: Domain Memory - persistent structured representation containing:
- Goals - What we're trying to achieve, requirements, constraints
- State - What's passing/failing, what's been tried, what broke
- Scaffolding - How to run, test, extend the system
Rules files distill domain knowledge into quick-reference format.
When to Use
User asks to:
- "Analyze frontend/ and create rules"
- "Set up Claude rules for the backend"
- "Create domain memory for e2e/"
Workflow
1. Check Existing Documentation
Read root CLAUDE.md and target directory CLAUDE.md. Pull down what's already documented. We don't want to duplicate everything, but the main CLAUDE.md still have to keep core overview of the application.
2. Detect Concerns
Scan the target directory to detect which concerns exist. Only generate rule files for concerns that are actually present.
3. Mine Domain Memory
Check planning board and tasks under /.tasks/ for decisions, gotchas, and patterns related to each detected concern.
Globpattern: ".task-board/done/*.md"
Use tasks older than #150
4. Generate Rule Files
Create focused .md files only for detected concerns.
Concern Detection Matrix
Scan for these patterns to detect which concerns exist:
| Concern |
Detection Signals |
Rule File |
| auth |
**/auth/**, AuthContext, AuthProvider, login, logout, session, token, OAuth, EasyAuth |
auth.md |
| data |
**/models/**, cosmosdb, database, mongoose, prisma, orm, migrations, Container |
data.md |
| api |
**/routes/**, **/controllers/**, router.get, router.post, express.Router, endpoints |
api.md |
| validation |
**/validators/**, zod, yup, joi, schema, .parse(, .safeParse( |
validation.md |
| state |
useQuery, useMutation, QueryClient, zustand, redux, recoil, Context.Provider |
state.md |
| components |
**/ui/**, **/components/**, .tsx files with Props interfaces, forwardRef |
components.md |
| styling |
tokens.css, theme, tailwind, styled-components, css modules, design system files |
styling.md |
| charts |
d3, recharts, chart.js, victory, **/charts/**, <svg, useEffect with DOM manipulation |
charts.md |
| forms |
**/forms/**, useForm, handleSubmit, <input, <form, form validation patterns |
forms.md |
| calculations |
**/calculation*, pure functions returning numbers, financial formulas, Math. heavy files |
calculations.md |
| llm |
openai, langchain, anthropic, agent, tool calls, completion, langfuse |
llm.md |
| errors |
**/errors/**, AppError, ErrorBoundary, errorHandler, custom error classes |
errors.md |
| testing |
*.spec.ts, *.test.ts, fixtures, beforeEach, describe(, it(, expect( |
testing.md |
| middleware |
**/middleware/**, app.use(, request/response interceptors, next() |
middleware.md |
| services |
**/services/**, business logic classes, dependency injection patterns |
services.md |
| onboarding |
wizard, onboarding, setup, multi-step flows, Step*.tsx |
onboarding.md |
| integrations |
Third-party SDK imports, API clients, webhooks, external service calls |
integrations.md |
Detection Algorithm
For each concern in matrix:
1. Glob for folder patterns (**/auth/**, **/models/**, etc.)
2. Grep for keyword patterns (AuthContext, useQuery, etc.)
3. If matches found → concern is DETECTED
4. If no matches → skip this concern
Threshold: A concern is detected if:
- At least 1 folder pattern matches, OR
- At least 3 keyword matches across files
Rule File Format
# [Concern] Rules
## Stack
[One line: key libs/frameworks for this concern]
## Structure
- `/path` - Purpose
- `/path` - Purpose
## Patterns
- Established pattern 1
- Established pattern 2
## Decisions
- Choice X because Y
## Gotchas
- Problem → Solution
## Commands
- `pnpm <command>` - What it does
Not every file needs all sections - include only what's relevant.
Example: Detected Concerns → Generated Files
Target: backend/
Detection results:
- ✅ auth →
middleware/auth.ts, routes/authRoutes.ts
- ✅ data →
config/cosmosdb.ts, models/*.ts
- ✅ api →
routes/*.ts, controllers/*.ts
- ✅ validation →
validators/*.ts, zod imports
- ✅ services →
services/*.ts
- ✅ calculations →
services/calculationService.ts
- ✅ llm →
services/importAgentService.ts, openai imports
- ✅ errors →
errors/AppError.ts, middleware/errorHandler.ts
- ✅ middleware →
middleware/*.ts
- ❌ components → not found
- ❌ styling → not found
- ❌ charts → not found
Generated files:
backend/.claude/rules/
├── auth.md
├── data.md
├── api.md
├── validation.md
├── services.md
├── calculations.md
├── llm.md
├── errors.md
└── middleware.md
Target: components/
Detection results:
- ✅ components →
ui/**, cards/**, layout/**
- ✅ styling →
styles/tokens.css
- ✅ charts →
charts/*.tsx, d3 imports
- ✅ forms →
forms/*.tsx
- ✅ errors →
system/ErrorBoundary
- ❌ auth → not found
- ❌ data → not found
- ❌ api → not found
Generated files:
components/.claude/rules/
├── components.md
├── styling.md
├── charts.md
├── forms.md
└── errors.md
Target: e2e/
Detection results:
- ✅ testing →
*.spec.ts, fixtures
- ✅ auth → login helpers, auth fixtures
- ❌ everything else → not found
Generated files:
e2e/.claude/rules/
├── testing.md
└── auth.md
Content Guidelines
What to Include
| Section |
Source |
| Stack |
package.json deps for this concern |
| Structure |
Folder layout for this concern only |
| Patterns |
Code analysis + task-board history |
| Decisions |
Task-board "decided to..." entries |
| Gotchas |
Task-board "had issues with..." entries |
| Commands |
package.json scripts for this concern |
What NOT to Include
- Anything in root
CLAUDE.md (no duplication)
- Generic patterns (only project-specific)
- Obvious things (React uses JSX, etc.)
Example Rule Files
backend/.claude/rules/data.md
# Data Rules
## Stack
CosmosDB (NoSQL), @azure/cosmos SDK
## Structure
- `/config/cosmosdb.ts` - Connection, container getters
- `/models/` - Document type definitions
## Patterns
- Containers: `users` (partition: /id), `portfolios` (partition: /userId)
- Documents are denormalized (snapshots store full account data)
- Use singleton pattern for database instance
## Decisions
- Denormalized snapshots for historical accuracy (accounts change over time)
- Co-locate user data by userId partition for fast queries
## Gotchas
- Date strings "dd.MM.yyyy" don't sort correctly in CosmosDB
- Always sort dates in JS using `compareDatesAsc` from dateUtils.ts
- Zod strips unknown fields - add to schema or they're dropped
## Commands
- `pnpm --filter backend seed` - Seed demo data
- `pnpm --filter backend seed:reset` - Reset database
components/.claude/rules/charts.md
# Charts Rules
## Stack
D3.js for all visualizations
## Structure
- `/charts/AreaChart` - Single line/area
- `/charts/StackedAreaChart` - Multiple stacked areas
- `/charts/DonutChart` - Pie/donut charts
## Patterns
- SVG-based, responsive via viewBox
- Data prop: `{ date: string, value: number }[]`
- Colors from design tokens (--muted-sage, --pale-blue, etc.)
- Tooltips via D3 mouse events
## Gotchas
- D3 selections in useEffect with cleanup
- Don't mix D3 DOM manipulation with React state
- Mobile: increase touch targets for tooltips
e2e/.claude/rules/testing.md
# Testing Rules
## Stack
Playwright
## Structure
- `/tests/*.spec.ts` - Test files
- `/tests/fixtures.ts` - Shared helpers, constants
## Patterns
- `PROTECTED_PAGES` array for auth-required pages
- `login()` helper handles demo authentication
- `clearAuthState()` between tests
## Decisions
- Integration + E2E only, no unit tests
- Sanity checks over comprehensive coverage
- Test user flows, not implementation details
## Gotchas
- Demo login has rate limiting (5 req/min)
- Always clearAuthState() in beforeEach
- Mobile tests use fixtures/mobile-viewports.ts
## Commands
- `pnpm test:e2e` - Run all tests
- `pnpm test:e2e --ui` - Interactive mode
Best Practices
- Detect first - Only create files for concerns that exist
- Mine task-board - Decisions and gotchas are gold
- No duplication - If root CLAUDE.md has it, skip it
- Be specific - "Port 3000" not "default port"
- Keep short - Each file <50 lines
- Update on discovery - Rules are living documentation
1---2name: rule-making-skill3description: Analyze a specific directory (e.g. frontend/, backend/, e2e/) and generate .claude/rules/ markdown files for it. Use when asked to create rules, analyze a folder for Claude Code, or set up domain memory for a specific part of the codebase.4---56# Rules Generator78Analyze a directory and generate `.claude/rules/` files for Claude Code domain memory.910## Core Concept1112Generalized agents fail because they're "amnesiacs with a tool belt." Each session starts with no grounded sense of where we are.1314**Solution: Domain Memory** - persistent structured representation containing:151. **Goals** - What we're trying to achieve, requirements, constraints162. **State** - What's passing/failing, what's been tried, what broke173. **Scaffolding** - How to run, test, extend the system1819Rules files distill domain knowledge into quick-reference format.2021## When to Use2223User asks to:24- "Analyze frontend/ and create rules"25- "Set up Claude rules for the backend"26- "Create domain memory for e2e/"2728---2930## Workflow3132### 1. Check Existing Documentation3334Read root CLAUDE.md and target directory CLAUDE.md. Pull down what's already documented. We don't want to duplicate everything, but the main CLAUDE.md still have to keep core overview of the application.3536### 2. Detect Concerns3738Scan the target directory to detect which concerns exist. Only generate rule files for concerns that are actually present.3940### 3. Mine Domain Memory4142Check planning board and tasks under `/.tasks/` for decisions, gotchas, and patterns related to each detected concern.4344Globpattern: ".task-board/done/*.md"4546Use tasks older than #1504748### 4. Generate Rule Files4950Create focused `.md` files only for detected concerns.5152---5354## Concern Detection Matrix5556Scan for these patterns to detect which concerns exist:5758| Concern | Detection Signals | Rule File |59|---------|-------------------|-----------|60| **auth** | `**/auth/**`, `AuthContext`, `AuthProvider`, `login`, `logout`, `session`, `token`, `OAuth`, `EasyAuth` | `auth.md` |61| **data** | `**/models/**`, `cosmosdb`, `database`, `mongoose`, `prisma`, `orm`, `migrations`, `Container` | `data.md` |62| **api** | `**/routes/**`, `**/controllers/**`, `router.get`, `router.post`, `express.Router`, `endpoints` | `api.md` |63| **validation** | `**/validators/**`, `zod`, `yup`, `joi`, `schema`, `.parse(`, `.safeParse(` | `validation.md` |64| **state** | `useQuery`, `useMutation`, `QueryClient`, `zustand`, `redux`, `recoil`, `Context.Provider` | `state.md` |65| **components** | `**/ui/**`, `**/components/**`, `.tsx` files with `Props` interfaces, `forwardRef` | `components.md` |66| **styling** | `tokens.css`, `theme`, `tailwind`, `styled-components`, `css modules`, design system files | `styling.md` |67| **charts** | `d3`, `recharts`, `chart.js`, `victory`, `**/charts/**`, `<svg`, `useEffect` with DOM manipulation | `charts.md` |68| **forms** | `**/forms/**`, `useForm`, `handleSubmit`, `<input`, `<form`, form validation patterns | `forms.md` |69| **calculations** | `**/calculation*`, pure functions returning numbers, financial formulas, `Math.` heavy files | `calculations.md` |70| **llm** | `openai`, `langchain`, `anthropic`, `agent`, `tool calls`, `completion`, `langfuse` | `llm.md` |71| **errors** | `**/errors/**`, `AppError`, `ErrorBoundary`, `errorHandler`, custom error classes | `errors.md` |72| **testing** | `*.spec.ts`, `*.test.ts`, `fixtures`, `beforeEach`, `describe(`, `it(`, `expect(` | `testing.md` |73| **middleware** | `**/middleware/**`, `app.use(`, request/response interceptors, `next()` | `middleware.md` |74| **services** | `**/services/**`, business logic classes, dependency injection patterns | `services.md` |75| **onboarding** | `wizard`, `onboarding`, `setup`, multi-step flows, `Step*.tsx` | `onboarding.md` |76| **integrations** | Third-party SDK imports, API clients, webhooks, external service calls | `integrations.md` |7778### Detection Algorithm7980```81For each concern in matrix:82 1. Glob for folder patterns (**/auth/**, **/models/**, etc.)83 2. Grep for keyword patterns (AuthContext, useQuery, etc.)84 3. If matches found → concern is DETECTED85 4. If no matches → skip this concern86```8788**Threshold**: A concern is detected if:89- At least 1 folder pattern matches, OR90- At least 3 keyword matches across files9192---9394## Rule File Format9596```markdown97# [Concern] Rules9899## Stack100[One line: key libs/frameworks for this concern]101102## Structure103- `/path` - Purpose104- `/path` - Purpose105106## Patterns107- Established pattern 1108- Established pattern 2109110## Decisions111- Choice X because Y112113## Gotchas114- Problem → Solution115116## Commands117- `pnpm <command>` - What it does118```119120**Not every file needs all sections** - include only what's relevant.121122---123124## Example: Detected Concerns → Generated Files125126### Target: `backend/`127128**Detection results:**129- ✅ auth → `middleware/auth.ts`, `routes/authRoutes.ts`130- ✅ data → `config/cosmosdb.ts`, `models/*.ts`131- ✅ api → `routes/*.ts`, `controllers/*.ts`132- ✅ validation → `validators/*.ts`, zod imports133- ✅ services → `services/*.ts`134- ✅ calculations → `services/calculationService.ts`135- ✅ llm → `services/importAgentService.ts`, openai imports136- ✅ errors → `errors/AppError.ts`, `middleware/errorHandler.ts`137- ✅ middleware → `middleware/*.ts`138- ❌ components → not found139- ❌ styling → not found140- ❌ charts → not found141142**Generated files:**143```144backend/.claude/rules/145├── auth.md146├── data.md147├── api.md148├── validation.md149├── services.md150├── calculations.md151├── llm.md152├── errors.md153└── middleware.md154```155156### Target: `components/`157158**Detection results:**159- ✅ components → `ui/**`, `cards/**`, `layout/**`160- ✅ styling → `styles/tokens.css`161- ✅ charts → `charts/*.tsx`, d3 imports162- ✅ forms → `forms/*.tsx`163- ✅ errors → `system/ErrorBoundary`164- ❌ auth → not found165- ❌ data → not found166- ❌ api → not found167168**Generated files:**169```170components/.claude/rules/171├── components.md172├── styling.md173├── charts.md174├── forms.md175└── errors.md176```177178### Target: `e2e/`179180**Detection results:**181- ✅ testing → `*.spec.ts`, fixtures182- ✅ auth → login helpers, auth fixtures183- ❌ everything else → not found184185**Generated files:**186```187e2e/.claude/rules/188├── testing.md189└── auth.md190```191192---193194## Content Guidelines195196### What to Include197198| Section | Source |199|---------|--------|200| Stack | `package.json` deps for this concern |201| Structure | Folder layout for this concern only |202| Patterns | Code analysis + task-board history |203| Decisions | Task-board "decided to..." entries |204| Gotchas | Task-board "had issues with..." entries |205| Commands | `package.json` scripts for this concern |206207### What NOT to Include208209- Anything in root `CLAUDE.md` (no duplication)210- Generic patterns (only project-specific)211- Obvious things (React uses JSX, etc.)212213---214215## Example Rule Files216217### `backend/.claude/rules/data.md`218```markdown219# Data Rules220221## Stack222CosmosDB (NoSQL), @azure/cosmos SDK223224## Structure225- `/config/cosmosdb.ts` - Connection, container getters226- `/models/` - Document type definitions227228## Patterns229- Containers: `users` (partition: /id), `portfolios` (partition: /userId)230- Documents are denormalized (snapshots store full account data)231- Use singleton pattern for database instance232233## Decisions234- Denormalized snapshots for historical accuracy (accounts change over time)235- Co-locate user data by userId partition for fast queries236237## Gotchas238- Date strings "dd.MM.yyyy" don't sort correctly in CosmosDB239- Always sort dates in JS using `compareDatesAsc` from dateUtils.ts240- Zod strips unknown fields - add to schema or they're dropped241242## Commands243- `pnpm --filter backend seed` - Seed demo data244- `pnpm --filter backend seed:reset` - Reset database245```246247### `components/.claude/rules/charts.md`248```markdown249# Charts Rules250251## Stack252D3.js for all visualizations253254## Structure255- `/charts/AreaChart` - Single line/area256- `/charts/StackedAreaChart` - Multiple stacked areas257- `/charts/DonutChart` - Pie/donut charts258259## Patterns260- SVG-based, responsive via viewBox261- Data prop: `{ date: string, value: number }[]`262- Colors from design tokens (--muted-sage, --pale-blue, etc.)263- Tooltips via D3 mouse events264265## Gotchas266- D3 selections in useEffect with cleanup267- Don't mix D3 DOM manipulation with React state268- Mobile: increase touch targets for tooltips269```270271### `e2e/.claude/rules/testing.md`272```markdown273# Testing Rules274275## Stack276Playwright277278## Structure279- `/tests/*.spec.ts` - Test files280- `/tests/fixtures.ts` - Shared helpers, constants281282## Patterns283- `PROTECTED_PAGES` array for auth-required pages284- `login()` helper handles demo authentication285- `clearAuthState()` between tests286287## Decisions288- Integration + E2E only, no unit tests289- Sanity checks over comprehensive coverage290- Test user flows, not implementation details291292## Gotchas293- Demo login has rate limiting (5 req/min)294- Always clearAuthState() in beforeEach295- Mobile tests use fixtures/mobile-viewports.ts296297## Commands298- `pnpm test:e2e` - Run all tests299- `pnpm test:e2e --ui` - Interactive mode300```301302---303304## Best Practices3053061. **Detect first** - Only create files for concerns that exist3072. **Mine task-board** - Decisions and gotchas are gold3083. **No duplication** - If root CLAUDE.md has it, skip it3094. **Be specific** - "Port 3000" not "default port"3105. **Keep short** - Each file <50 lines3116. **Update on discovery** - Rules are living documentation