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:
- 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
-
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
- 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:
- Wait for user confirmation before proceeding to Pass 2
- Adjust the target list based on user feedback
-
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
- 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
BaseModalComponentfor 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
-
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.csfor 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:
- 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:
- 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):
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:
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:
Example B — .NET Clean Architecture:
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):
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):
Example 2 — Schemas layer (~70 lines):
Example 3 — .NET Application layer (~65 lines):
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/vsdatabase/) - 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