Annotate Project

You are tasked with generating CLAUDE.md files across a brownfield project. You will map the project structure, auto-detect its architecture, analyze each architectural layer, and batch-write compact CLAUDE.md files at the root and relevant subdirectories.

Initial Setup:

Use the current working directory as the target project by default. If the user provides a specific directory path as an argument, use that instead.

Steps to follow:

  1. Read any directly mentioned files first:
    • If the user mentions specific files (existing CLAUDE.md, architecture docs, READMEs), read them FULLY first
    • IMPORTANT: Use the Read tool WITHOUT limit/offset parameters to read entire files
    • CRITICAL: Read these files yourself in the main context before spawning any sub-tasks
    • This ensures you have full context before decomposing the work
  2. Pass 1 — Map the project (parallel locator agents):

    • Spawn the following agents in parallel using the Agent tool:

    Agent A — Project tree mapping:

    • subagent_type: codebase-locator
    • Prompt: "Map the full project tree structure for [target directory]. List all directories and their contents, respecting .gitignore. Focus on source code directories, configuration files, and build artifacts. Return a complete tree view."

    Agent B — Architecture and conventions:

    • subagent_type: codebase-locator
    • Prompt: "Identify the architectural layers, folder roles, and framework conventions in [target directory]. Determine: What architecture pattern is used (clean architecture, MVC, monorepo, microservices, hexagonal, etc.)? What are the main layers/modules? What frameworks and languages are present? What build system is used?"
    • While agents run, read .gitignore yourself to understand exclusion rules
  3. Wait for Pass 1 and determine CLAUDE.md targets:
    • IMPORTANT: Wait for ALL agents from Pass 1 to complete before proceeding
    • Synthesize the tree structure and architecture findings
    • Auto-detect the architecture pattern (clean architecture, MVC, monorepo, microservices, etc.)
    • Apply the CLAUDE.md Depth Rules (see below) to determine which folders need CLAUDE.md files
    • Present the proposed CLAUDE.md locations to the user:
      ## Proposed CLAUDE.md Locations
      
      Architecture detected: [pattern name]
      
      ### Will create CLAUDE.md in:
      - `/` (root)  Project overview (compact)
      - `/src/core/`  Core domain layer
      - `/src/services/`  Service layer
      - [etc.]
      
      ### Will skip:
      - `/src/core/entities/`  Entity grouping, same pattern as parent
      - [etc.]
      
      Does this look right? Should I add or remove any locations?
      
    • Wait for user confirmation before proceeding to Pass 2
    • Adjust the target list based on user feedback
  4. Pass 2 — Analyze each layer (parallel analyzer agents):

    • For each confirmed target folder, spawn agents in parallel:

    For each target folder, spawn TWO agents:

    Analyzer agent:

    • subagent_type: codebase-analyzer
    • Prompt: "Analyze [folder path] in detail. Determine: 1) What is this layer's responsibility? 2) What are its dependencies (what does it import/use)? 3) Who consumes it (what imports/uses it)? 4) What are the key architectural boundaries and constraints? 5) What is the module structure — list DIRECTORIES with their roles, base types, and naming conventions. Use architectural annotations (e.g., 'one repo per entity', 'one controller per resource') instead of listing individual filenames. The structure should remain valid when non-architectural files are added. 6) What naming conventions are used (prefixes, suffixes, base classes)?"

    Pattern finder agent:

    • subagent_type: codebase-pattern-finder
    • Prompt: "Find all distinct code patterns used in [folder path]. For each pattern found: 1) Name the pattern with a descriptive heading (e.g., 'Repository Boundary (CRITICAL: Plain Types, NOT Result<T>)'). 2) Provide an IDIOMATIC code example — a generalized, representative version that shows the pattern's essential shape (constructor, key method signatures, return types, error handling). Do NOT copy-paste a single file verbatim; instead synthesize the typical usage across the layer. 3) Add inline comments highlighting important conventions (e.g., '// DB int → boolean', '// throws on error — service wraps in Result'). 4) If the pattern involves a boundary between layers, show both sides. 5) Identify any repeatable workflows for adding new elements to this layer — backend entities (repositories, services, controllers) AND frontend elements (components, services, pages/routes, directives). For example: creating a new repository requires extending BaseRepository + registering in factory; adding a new Angular component requires extending BaseComponent + adding to routes + creating the template. Return these as step-by-step checklists. Return patterns with full code block examples."
    • Spawn 1 analyzer + 1 pattern finder per folder, all in parallel
    • For the root CLAUDE.md, use findings from ALL folders to create the overview
  5. Wait for Pass 2 and synthesize:
    • IMPORTANT: Wait for ALL agents from Pass 2 to complete before proceeding
    • Compile all agent findings per folder
    • Draft CLAUDE.md content in this order — subfolder files first, root last:
    • Subfolder: Use the Subfolder CLAUDE.md Template (detailed, max 100 lines)
    • Root folder (LAST): Use the Root CLAUDE.md Template (compact overview). Draft root only after all subfolder files are finalized — this ensures the deduplication rule can be applied and cross-layer checklists can accurately reference subfolder content
    • Enforce the 100-line limit on subfolder files — code examples are essential but keep them concise
    • If the pattern-finder identified repeatable "add new entity" workflows, include them as <important if="you are adding a new [entity] to this layer"> conditional sections
    • If testing patterns were detected, include them as <important if="you are writing or modifying tests for this layer"> conditional sections
    • Conditional sections are optional — only include when the pattern-finder found clear evidence of a repeatable workflow
    • Conditions must be narrow and action-specific (NOT "you are writing code" — too broad)
    • Do NOT include conventions enforceable by linters, formatters, or pre-commit hooks (e.g., naming conventions, import ordering, indentation) — these add noise without value
    • Do NOT include patterns easily discoverable from existing code — LLMs are in-context learners and will follow patterns after a few file reads. Only document conventions that are surprising, non-obvious, or span multiple layers
    • If a pattern section would contain only prose or comments with no code example, either expand it with a real idiomatic example or omit it and reference the source file (e.g., "see BaseModalComponent for the modal pattern")
    • Before writing, verify: no root conditional block duplicates content from a subfolder CLAUDE.md. If a layer has its own subfolder file, remove its summary from root
    • For cross-layer vertical-slice checklists in root, each step should reference the relevant subfolder CLAUDE.md ("see Data layer CLAUDE.md") rather than inlining the full procedure
    • If an existing root CLAUDE.md was found:
    • Review its content
    • Redistribute any detailed layer-specific content to the appropriate subfolder CLAUDE.md files
    • Rewrite the root as a compact overview
  6. Self-review pass — verify every drafted file before writing:
    Walk through each drafted CLAUDE.md and check every item below. Fix violations in-place before proceeding to writing.

    Dependencies — for each listed dependency, ask: "does this library impose patterns, constraints, or conventions on the code?" If the answer is no (utility libraries like lodash, moment, xlsx, FontAwesome), remove it. Only frameworks and libraries that shape how you write code survive.

    Module Structure — count top-level entries. If more than 7, group related directories on one line (e.g., guards/, interceptors/, pipes/ — cross-cutting plumbing). Target 4-7 entries.

    Pattern sections — every pattern H2 must contain a fenced code block with an idiomatic example. If a section is prose-only or comment-only, either expand it with a real code example or replace the section with a one-line file reference (e.g., "see TradeDeskMapping.cs for the mapping pattern").

    Root deduplication — for each root conditional block, verify it is NOT summarizing a layer that has its own subfolder CLAUDE.md. If it is, remove the block. For cross-layer vertical-slice checklists, verify each step references the relevant subfolder file ("see X CLAUDE.md") rather than inlining the procedure.

    Frontend/UI conditional coverage — for each frontend/UI layer, list every repeatable workflow the pattern-finder reported (components, services, pages/routes, directives, pipes, hooks, stores — whatever was detected). Then compare that list against the drafted <important if> conditional sections. Any workflow on the list without a matching conditional is a gap — draft and add the missing section before proceeding.

    After fixing all violations, re-scan the corrected drafts to confirm every check passes. Only proceed to writing when all checks are clean. Present a brief summary of what was fixed:

    1
    2
    3
    4
    5
    ## Self-review results
    - [file]: removed 2 utility deps (moment, xlsx-js-style)
    - [file]: grouped Module Structure from 11  6 entries
    - [file]: added "Adding a New Service" conditional
    - Root: no violations found
    
  7. Pass 3 — Write all CLAUDE.md files:
    • Write ALL files at once using the Write tool
    • Do NOT ask for confirmation before each file — batch mode
    • After writing, present a summary:
      ## CLAUDE.md Files Created
      
      | File | Lines | Description |
      |------|-------|-------------|
      | CLAUDE.md | 45 | Root project overview |
      | src/core/CLAUDE.md | 78 | Core domain layer |
      | src/services/CLAUDE.md | 65 | Service layer |
      | [etc.] | | |
      
      Total: [N] files created/updated
      
      Please review the files and let me know if you'd like any adjustments.
      
  8. Handle follow-up adjustments:
    • If the user requests changes to specific files, edit them directly using the Edit tool
    • If the user wants additional folders annotated, run a targeted Pass 2 (analyzer + pattern finder) for those folders, then write
    • If the user wants a file removed, note that they can delete it themselves

Root CLAUDE.md Template (compact):

# Project Overview
[1-2 sentences: what it is, tech stack]

# Architecture
[monorepo structure tree + dependency flow diagram]
[process architecture if applicable]

# Commands
[key commands table — always bare, never wrapped in <important if>]

# Business Context
[1-2 sentences if applicable]

The sections above (Overview, Architecture, Commands, Business Context) are foundational — they stay bare because they're relevant to virtually every task.

Cross-cutting patterns and domain-specific conventions go in <important if> blocks with narrow, action-specific conditions. Do NOT group unrelated rules under a single broad condition like "you are writing or modifying code". Instead, shard by trigger.

Root conditional blocks are for cross-cutting conventions that don't belong to any single layer. Layer-specific recipes (like "adding a new controller" or "adding a new repository") belong in the subfolder CLAUDE.md, not the root.

Deduplication rule: If a layer has its own subfolder CLAUDE.md, do NOT add a root conditional block summarizing that layer's conventions. The subfolder file is the authoritative guide — the agent will see it when working in that directory. Root conditionals that mirror subfolder content waste attention budget and create staleness risk.

Root MAY include cross-layer vertical-slice checklists (e.g., "adding a new domain entity end-to-end") that reference multiple subfolder CLAUDE.md files — but each step should point to the relevant subfolder for details, not inline them.

Good root conditions — things that span multiple layers:

<important if="you are writing or modifying tests">
- Unit: xUnit + NSubstitute / Jest + Testing Library
- Integration: WebApplicationFactory / Supertest
- Test fixtures in `__fixtures__/` or `tests/Fixtures/`
</important>

<important if="you are adding or modifying database migrations">
- Never modify existing migrations — always create new ones
- Run `dotnet ef migrations add` / `turbo db:migrate` after schema changes
</important>

<important if="you are adding or modifying environment configuration">
- All config via `IOptions<T>` pattern / environment variables
- Secrets in user-secrets locally, Key Vault in production
</important>

Each block should contain only rules that share the same trigger condition. If a codebase has 3 distinct convention areas, that's 3 blocks — not 1 block with a broad condition. Layer-specific checklists (adding a controller, adding a repository) go in the subfolder CLAUDE.md using <important if="you are adding a new [entity] to this layer">.

Root CLAUDE.md Reference Examples

Example A — Node.js monorepo:

# CLAUDE.md

Express API + React frontend in a Turborepo monorepo.

## Project map

- `apps/api/` - Express REST API
- `apps/web/` - React SPA
- `packages/db/` - Prisma schema and client
- `packages/ui/` - Shared component library
- `packages/config/` - Shared configuration

## Commands

| Command | What it does |
|---|---|
| `turbo build` | Build all packages |
| `turbo test` | Run all tests |
| `turbo lint` | Lint all packages |
| `turbo dev` | Start dev server |
| `turbo db:generate` | Regenerate Prisma client after schema changes |
| `turbo db:migrate` | Run database migrations |

<important if="you are adding or modifying API routes">
- All routes go in `apps/api/src/routes/`
- Use Zod for request validation — see `apps/api/src/routes/connections.ts` for the pattern
- Error responses follow RFC 7807 format
- Authentication via JWT middleware
</important>

<important if="you are writing or modifying tests">
- API: Jest + Supertest, Frontend: Vitest + Testing Library
- Test fixtures in `__fixtures__/` directories
- Use `createTestClient()` helper for API integration tests
- Mock database with `prismaMock` from `packages/db/test`
</important>

<important if="you are working with client-side state, stores, or data fetching">
- Zustand for global client state
- React Query for server state
- URL state via `nuqs`
</important>

Example B — .NET Clean Architecture:

# CLAUDE.md

ASP.NET Core 8 Web API with Clean Architecture (CQRS + MediatR).

## Project map

- `src/Api/` - ASP.NET Core controllers, middleware, DI setup
- `src/Application/` - MediatR handlers, validators, DTOs
- `src/Domain/` - Entities, value objects, domain events
- `src/Infrastructure/` - EF Core, external services, file storage
- `tests/` - Unit and integration tests

## Commands

| Command | What it does |
|---|---|
| `dotnet build` | Build solution |
| `dotnet test` | Run all tests |
| `dotnet run --project src/Api` | Start API locally |
| `dotnet ef migrations add <Name> -p src/Infrastructure` | Create EF migration |
| `dotnet ef database update -p src/Infrastructure` | Apply migrations |

<important if="you are adding a new API endpoint">
- Add controller in `Api/Controllers/` inheriting `BaseApiController`
- Add command/query + handler + validator in `Application/Features/`
- See `Application/Features/Orders/Commands/CreateOrder/` for the pattern
</important>

<important if="you are adding or modifying EF Core migrations or database schema">
- Entities configured via `IEntityTypeConfiguration<T>` in `Infrastructure/Persistence/Configurations/`
- Always create a migration after schema changes — never modify existing migrations
</important>

<important if="you are writing or modifying tests">
- Unit tests: xUnit + NSubstitute, one test class per handler
- Integration tests: `WebApplicationFactory<Program>` with test database
- See `tests/Application.IntegrationTests/TestBase.cs` for setup
</important>

What makes these examples good:

  • Bare sections (Overview, Project map, Commands) are relevant to nearly every task — no wrapper needed
  • Each <important if> has a narrow trigger — "adding a new API endpoint" not "writing backend code"
  • No linter territory — formatting rules, naming conventions left to tooling (eslint/prettier, .editorconfig/analyzers)
  • No code snippets — uses file path references ("see Application/Features/Orders/...") since this is a root file and patterns are better shown in subfolder CLAUDE.md files
  • All commands kept — commands are foundational reference
  • Same structure, different ecosystems — the pattern works identically for Node.js and .NET

Subfolder CLAUDE.md Template (max 100 lines):

# [Layer/Component Name]

## Responsibility
[1-2 sentences: what this layer does, where it sits in architecture]

## Dependencies
[List only architectural dependencies — frameworks and libraries that shape how you write code in this layer.
Do NOT list utility libraries discoverable from package.json/imports (e.g., lodash, moment, xlsx).
A dependency is worth listing if it imposes patterns, constraints, or conventions on the code.]
- **[dep]**: Why it's used

## Consumers
- **[consumer]**: How it uses this layer

## Module Structure
[Compact directory tree — aim for 4-7 top-level entries, not 15.
Group related files on one line (e.g., "Service.ts, Handler.ts").
Use architectural annotations for directories (e.g., "# One repo per entity", "# Domain schemas").
DO NOT enumerate individual files inside directories — describe the convention.
When a layer has many directories (10+), group related concerns on one line
(e.g., "guards/, interceptors/, pipes/ — infrastructure plumbing") rather than listing each separately.
The structure must stay valid when non-architectural files are added.]

## [Pattern Name] ([Key Constraint or Characterization])
[Each distinct pattern gets its own H2 section — NOT a generic "## Key Patterns" umbrella.
Include a fenced code block with an idiomatic, generalized example showing:
- Constructor / dependencies
- Key method signatures and return types
- Error handling / wrapping conventions
- Inline comments for important conventions (e.g., "// throws on error — service wraps in Result")
If a pattern spans a layer boundary, show both sides briefly.
Multiple patterns = multiple H2 sections.]

## [Additional Pattern Name]
[Second pattern with code block if applicable]

## Architectural Boundaries
- **NO [X]**: [Why]
- **NO [Y]**: [Why]

<important if="you are adding a new [entity type] to this layer">
## Adding a New [Entity Type]
[Step-by-step checklist inferred from existing code:
1. Create file following naming convention
2. Extend/implement base class or interface
3. Register in factory/container/index
4. Add related artifacts (schema, test, migration)]
</important>

<important if="you are writing or modifying tests for this layer">
## Testing Conventions
[Test patterns, helpers, fixture locations, mocking approach — if detectable from code]
</important>

Conditional sections are OPTIONAL — only include them if the pattern-finder agent detects testable patterns or clear "add new entity" workflows. Conditions must be narrow and action-specific. These sections contain checklists/recipes, not code examples (those stay in the unconditional pattern sections). Conditional sections do NOT count toward the 100-line budget for unconditional content.

Reference Examples

Below are examples of well-formed subfolder CLAUDE.md files to calibrate output quality. Examples use TypeScript and C# but the structure applies to any language — adapt code blocks, naming conventions, and tooling to whatever the project actually uses.

Example 1 — Database layer (~80 lines):

# Database Layer Architecture

## Responsibility
SQLite persistence with better-sqlite3, repository pattern (plain types), QueryQueue concurrency, type transformations.

## Dependencies
- **better-sqlite3**: Native SQLite (requires rebuild for Electron)
- **@redis-ui/core**: Domain types
- **p-queue**: Query serialization

## Consumers
- **@redis-ui/services**: Repositories via RepositoryFactory
- **Main process**: DatabaseManager initialization

## Module Structure
```
src/
├── DatabaseManager.ts, QueryQueue.ts   # Singleton, concurrency
├── BaseRepository.ts, RepositoryFactory.ts
├── schema.ts
└── repositories/                        # One repo per entity
```

## Repository Boundary (CRITICAL: Plain Types, NOT Result<T>)

```typescript
export class ConnectionRepository extends BaseRepository<ConnectionDB, Connection, ConnectionId> {
  protected toApplication(db: ConnectionDB): Connection {
    return {
      id: ConnectionId.create(db.id),
      host: db.host,
      port: db.port,
      sslEnabled: Boolean(db.ssl_enabled),     // DB int → boolean
      createdAt: new Date(db.created_at),      // timestamp → Date
    };
  }

  async findById(id: ConnectionId): Promise<Connection | null> {
    return this.queue.enqueueRead((db) => {
      const row = db.prepare('SELECT * FROM connections WHERE id = ?').get(id);
      return row ? this.toApplication(row) : null;
    });
  }
}

// Service: Wraps repository in Result<T>
async createConnection(input: CreateInput): Promise<Result<Connection>> {
  try {
    const connection = await this.connectionRepo.create(input);
    return Result.ok(connection);
  } catch (error) {
    return Result.fail(new InfrastructureError(error.message));
  }
}
```

## QueryQueue Pattern (Write Serialization)

```typescript
export class QueryQueue {
  private writeQueue = new PQueue({ concurrency: 1 }) // Single writer
  private readQueue = new PQueue({ concurrency: 5 })  // Multiple readers

  async enqueueWrite<T>(op: (db: Database) => T): Promise<T> {
    return this.writeQueue.add(() => op(this.db))
  }
}
```

## Architectural Boundaries
- **NO Result<T> in repos**: Services wrap with Result
- **NO unqueued DB ops**: Always use QueryQueue
- **NO raw SQL in services**: Use repositories

<important if="you are adding a new repository to this layer">
## Adding a New Repository
1. Create `XRepository.ts` extending `BaseRepository<XDB, X, XId>`
2. Implement `toApplication()` and `toDatabase()` type mappers
3. Register in `RepositoryFactory`
4. Add table schema in `schema.ts`
</important>

Example 2 — Schemas layer (~70 lines):

# Schemas Layer Architecture

## Responsibility
Zod validation schemas for dual-layer validation (preload UX + main security), type inference via z.infer<>.

## Dependencies
- **zod**: Runtime validation

## Consumers
- **@redis-ui/ipc**: Main process validation (security)
- **Preload**: Fail-fast validation (UX)
- **TypeScript**: Type inference

## Module Structure
```
src/
├── connection.ts, backup.ts    # Domain schemas
└── __tests__/                  # Validation tests
```

## Complete Schema Pattern (Types + Validation + Composition)

```typescript
export const createConnectionSchema = z.object({
  name: z.string().min(1).max(255),
  host: z.string().min(1),
  port: z.number().int().min(1).max(65535),
  password: z.string().optional(),
  database: z.number().int().min(0).max(15).default(0),
})

// Type inference
export type CreateConnectionInput = z.infer<typeof createConnectionSchema>

// Update schema (partial + ID required)
export const updateConnectionSchema = createConnectionSchema.partial().extend({
  id: z.string().min(1)
})
```

## Dual-Validation Flow

```
Renderer input → Preload (Zod parse, fail fast) → IPC → Main (Zod parse again, security)
```

## Architectural Boundaries
- **NO any types**: Use z.unknown()
- **NO skipping validation**: Always validate at boundaries
- **NO business logic**: Structure validation only

Example 3 — .NET Application layer (~65 lines):

# Application Layer (CQRS + MediatR)

## Responsibility
Command/query handlers orchestrating domain logic via MediatR pipeline. Sits between API controllers and Domain layer.

## Dependencies
- **MediatR**: Command/query dispatch
- **FluentValidation**: Request validation via pipeline behavior
- **AutoMapper**: Domain ↔ DTO mapping

## Consumers
- **API Controllers**: Send commands/queries via `IMediator`
- **Integration tests**: Direct handler invocation

## Module Structure
```
Application/
├── Common/
│   ├── Behaviors/          # MediatR pipeline (validation, logging)
│   └── Mappings/           # AutoMapper profiles
├── Features/               # One folder per aggregate
│   └── Orders/
│       ├── Commands/       # CreateOrder/, UpdateOrder/ (handler + validator + DTO)
│       └── Queries/        # GetOrder/, ListOrders/
└── DependencyInjection.cs  # Service registration
```

## Handler Pattern (Command with Validation)

```csharp
public record CreateOrderCommand(string CustomerId, List<LineItemDto> Items)
    : IRequest<Result<OrderDto>>;

public class CreateOrderValidator : AbstractValidator<CreateOrderCommand> {
    public CreateOrderValidator(IOrderRepository repo) {
        RuleFor(x => x.CustomerId).NotEmpty();
        RuleFor(x => x.Items).NotEmpty();
    }
}

public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, Result<OrderDto>> {
    public async Task<Result<OrderDto>> Handle(
        CreateOrderCommand request, CancellationToken ct) {
        var order = Order.Create(request.CustomerId, request.Items); // Domain factory
        await _repo.AddAsync(order, ct);
        await _unitOfWork.SaveChangesAsync(ct);
        return Result.Ok(_mapper.Map<OrderDto>(order));
    }
}
```

## Architectural Boundaries
- **NO domain logic in handlers**: Handlers orchestrate, domain objects contain logic
- **NO direct DbContext access**: Use repository abstractions
- **NO cross-feature references**: Features are independent vertical slices

<important if="you are adding a new feature or command/query handler">
## Adding a New Feature
1. Create folder under `Features/{Aggregate}/{Commands|Queries}/`
2. Add `Command`/`Query` record implementing `IRequest<Result<TDto>>`
3. Add `Validator` extending `AbstractValidator<TCommand>`
4. Add `Handler` implementing `IRequestHandler<TCommand, Result<TDto>>`
5. Add AutoMapper profile in `Common/Mappings/` if new DTO
</important>

What makes these examples good:

  • Module Structure: Compact, uses architectural annotations ("One repo per entity", "One folder per aggregate"), groups related files on one line — stays valid when files are added
  • Patterns as H2 sections: Each pattern has a descriptive name, NOT a generic "## Key Patterns" umbrella
  • Code examples are idiomatic: Generalized to show the pattern's shape (constructor, method signatures, return types, error handling, inline convention comments) — works for any language (TypeScript, C#, Python, Go, etc.)
  • Cross-boundary patterns: Repository example shows both the repo side (throws) and the service side (wraps in Result); .NET example shows handler ↔ domain boundary
  • Concise: All fit well within 100 lines
  • Conditional blocks: Wrap scenario-specific recipes (like "Adding a New Repository" or "Adding a New Feature"), NOT core pattern documentation. Conditions are narrow ("adding a new repository" not "writing code"). Only included when the pattern-finder detected a clear, repeatable workflow

CLAUDE.md Depth Rules:

CREATE CLAUDE.md when:

  • Folder represents a distinct architectural layer (core, services, database, redis, ipc)
  • Folder contains unique organizational logic not captured by parent
  • Subfolder has different patterns/constraints than parent (e.g., database/repositories/ vs database/)
  • Folder has its own responsibility (e.g., database/migrations/)

SKIP CLAUDE.md when:

  • Folder only groups entities/DTOs by domain boundary following the same pattern
  • Folder content is fully described by parent CLAUDE.md
  • Folder is a simple grouping without unique constraints

Important notes:

  • Always use parallel Agent calls to maximize efficiency and minimize context usage
  • File reading: Always read mentioned files FULLY (no limit/offset) before spawning sub-tasks
  • Critical ordering: Follow the numbered steps exactly
    • ALWAYS read mentioned files first before spawning sub-tasks (step 1)
    • ALWAYS wait for all agents in a pass to complete before proceeding to the next step
    • NEVER write CLAUDE.md files with placeholder values — all content must come from agent findings
    • NEVER proceed to Pass 2 without user confirmation of target locations
  • .gitignore compliance: Skip directories excluded by .gitignore (node_modules, dist, build, .git, vendor, etc.)
  • Batch output mode: Write all CLAUDE.md files at once in Pass 3, do not ask for per-file confirmation
  • Existing CLAUDE.md handling: If a CLAUDE.md already exists at any target location, replace it entirely using the Write tool
  • Line budget: Subfolder CLAUDE.md files must not exceed 100 lines — code examples in Key Patterns are mandatory, keep them idiomatic and concise
  • No frontmatter: CLAUDE.md files are pure markdown, no YAML frontmatter
  • Keep the main agent focused on synthesis, not deep file reading — delegate analysis to sub-agents
Edit

Pub: 18 Mar 2026 17:41 UTC

Views: 20