| name | agent-docs-architect |
| description | Decompose a large or complex codebase into agent-readable layered documentation — a top-level architecture map, per-domain deep docs, and distributed CLAUDE.md files in subfolders so agents read only the slice relevant to their current task. Use this whenever the user complains that "the project is too big for the agent's context", "agents get lost in the codebase", "docs don't fit", "agents waste tokens loading the wrong files", or asks to "decompose / map / structure / document the project for AI", "split docs by layer / domain", "set up per-area CLAUDE.md", "build a doc index for agents", "make the codebase agent-friendly", or considers RAG/LightRAG-style solutions for source-code documentation. Triggers on Russian phrasings too — "разложить проект", "документация для агентов", "агенты теряются в коде", "сделать карту проекта", "слишком большой проект". NOT a replacement for the `context-map` skill (which captures project memory — decisions/issues/gotchas); this is the layer above, focused on architectural decomposition + agent-readable layered docs + a maintenance discipline so the docs don't rot. The skill produces `agent-docs/` with a MAP, per-domain docs, optional distributed CLAUDE.md files, and either an instruction-based or hook-based update policy. |
| metadata | {"short-description":"Decompose a complex project into layered agent-readable docs","version":"0.1"} |
Agent Docs Architect
You're invoked when a project is too large or too tangled for an agent to navigate effectively. Your job has three parts:
- Decompose — discover the project's real shape (domains, entry points, neighbors) instead of trusting a single big README.
- Document — generate layered docs (
agent-docs/MAP.md + per-domain deep docs + optional distributed CLAUDE.md files) so a future agent reads only the relevant slice.
- Sustain — wire up a maintenance discipline (instruction-based or hook-based) so the docs do not drift the moment the user starts shipping again.
The output is opinionated: it is for agents, not for humans onboarding. That changes everything — tone is terse, structure is predictable, every doc has a clear "when to read me" trigger, and every doc lists its neighbors so the agent can keep navigating without re-reading the index every time.
Why this skill exists (read before you start)
LLM agents in large repos fail in two ways:
- They load too much into context (whole docs/, whole modules) and waste tokens or run out of room.
- They load the wrong slice, hallucinate, and then "fix" things that aren't broken.
A flat README does not solve (1) or (2). A vector RAG on code is brittle because code changes hourly and the index goes stale. The cheapest, most durable fix is a small static index that tells the agent which file to read next, plus domain docs short enough to load fully, plus rules attached to the folders the agent is editing. That is what this skill produces.
Keep this in mind while working: every line you write should be load-bearing for an agent's future decision. Cut anything that just sounds nice.
Output language
All generated docs default to English regardless of conversation language, because future agents may run in any locale and English is the safest lingua franca for tooling. Conversation with the user stays in the session language. If the project has a strong non-English domain vocabulary (e.g., a Russian product), keep those terms verbatim — translating them loses precision.
Modes
Infer the mode from context. If unsure, ask.
- init (default first run): full discover → decompose → document → sustain flow. No prior
agent-docs/ exists.
- update: refresh an existing
agent-docs/ after code changes. Targets a domain (/agent-docs-architect update auth) or "all".
- audit: report staleness, missing domains, drift between docs and code. No writes.
- add-domain: a new major area appeared (e.g., a fresh subsystem). Register it without re-doing the rest.
- sustain-only: project already has good docs; just wire up the maintenance discipline (rules + optional hooks).
If a context-map-*/ folder already exists, do not overwrite it — it serves a different purpose (project memory: decisions, issues, gotchas). Generate agent-docs/ alongside it and add a cross-reference from MAP.md to the context map.
Phase 1: Discover
Goal: build an accurate picture of the project's real shape in under 90 seconds of tool calls. Do not read full files yet — you're surveying.
Steps:
- Read the root:
ls the repo root, find package.json, pyproject.toml, requirements.txt, go.mod, Cargo.toml, pom.xml, Gemfile, composer.json, mix.exs. Note the primary languages and frameworks.
- Map the directory tree to depth 3 (depth 4 for monorepos). Use
find or Glob. Note which top-level directories look like domains vs. tooling.
- Find existing agent context:
CLAUDE.md, AGENTS.md, GEMINI.md, .cursor/rules/, .github/copilot-instructions.md, context-map-*/, docs/, top-level README.md. Read these — they often already encode the user's mental model of the project.
- Locate entry points:
main.py, index.ts, app/main.py, server.py, framework-specific entry files (pages/, app/ for Next.js, cmd/ for Go, etc.).
- Detect monorepo signals:
pnpm-workspace.yaml, lerna.json, turbo.json, a top-level apps/ + packages/ layout, multiple package.json files.
- Sample 3–5 existing source files from areas that look important — just enough to confirm conventions (FastAPI vs Flask? React vs Vue? what does a typical handler look like?). Do not deep-read.
Output a short Discovery report (8–15 bullets) and show it to the user before proceeding. This is where the user catches you misreading the project. Cheap to fix here, expensive later.
If the project is genuinely small (< 30 source files, single language, no frameworks) — say so and propose a single agent-docs/MAP.md instead of the full layered structure. Don't force complexity where there is none.
Phase 2: Decompose
Goal: produce a proposed list of domains and confirm with the user before generating docs.
A "domain" is a unit the agent should read as a whole when working there. Good signs:
- It has a clear root path (or set of paths).
- It has a 1-line responsibility you can state without "and".
- A change to it usually doesn't require simultaneous changes elsewhere.
- An agent can understand it well enough to work in it after reading one domain doc.
Bad signs (split or merge):
- "Utilities" or "Helpers" — too vague, split by what they help with.
- A domain that spans 5+ unrelated subfolders — likely 2+ domains hiding.
- A domain you can't describe without using "all", "various", "stuff" — sharpen or split.
Typical decomposition sizes:
- Small project: 3–5 domains.
- Medium (most cases): 6–12 domains.
- Large monorepo: 10–25 domains. If you're going past 25, you're either too granular or the project really is that big.
For each proposed domain, write one line: name — root path(s) — one-line responsibility. Present the list and ask the user to edit. Accept their edits literally — they know the project, you don't.
Cross-cutting concerns (auth, deploy, logging, request flow, conventions) get a separate cross-cutting.md instead of being forced into a domain. List them at this stage too.
Phase 3: Document
Goal: generate agent-docs/ with the structure below. Be terse. Aim for every domain doc < 200 lines; if a domain doc grows past that, split the domain.
For projects with ≥ 5 domains: dispatch domain-writer subagents in parallel. Each subagent reads its assigned domain's code and writes one doc independently — wall-clock for 18 domains drops from ~60–120 min serial to ~5–15 min parallel. The full dispatch pattern, master prompt template, and tech-lead review checklist live in references/subagent-orchestration.md. Read it before dispatching.
After subagents finish, run scripts/lint_docs.py for the deterministic structural checks (required headers, banned phrases, bidirectional Neighbors, table column conformance, MAP.md ↔ domains/ consistency), then do a tech-lead review pass on flagged items. Only the lead Claude (not subagents) writes MAP.md, cross-cutting.md, and the _meta/ files — they need every domain output as input.
For projects with < 5 domains, dispatch overhead exceeds gain — write docs inline in the lead.
Structure
agent-docs/
├── MAP.md # the index. always read first.
├── cross-cutting.md # things that span domains
├── domains/
│ ├── <domain-1>.md
│ ├── <domain-2>.md
│ └── ...
└── _meta/
├── last-verified.json # per-doc last-verified date + commit SHA
└── conventions.md # project-wide conventions (one place, referenced from each domain doc)
Templates for each file live in references/:
references/map-template.md
references/domain-doc-template.md
references/cross-cutting-template.md
references/distributed-claude-md-template.md
Read them when writing the corresponding doc. They encode the format that makes the docs agent-friendly (predictable headers, tables, "when to read me" triggers).
Writing rules for agent docs
-
Lead with "when to read me". Each domain doc starts with one paragraph: "Read this when you're working in <path> or touching <concern>. Skip it if you're only working in <other-domain>." This is the single most valuable line in the doc.
-
Tables beat prose for file lists, entry points, neighbors. Agents parse tables reliably.
-
No prose paragraphs longer than 5 lines. If a topic needs more, split it under a subheading.
-
Always include "Neighbors": which domains this one depends on, which depend on it. This lets the agent navigate without going back to MAP.md every time.
-
Gotchas section is mandatory even if short. Non-obvious constraints, past bugs, counter-intuitive behavior. Agents are dramatically better when warned upfront than when forced to discover via failure.
-
Last-verified line at the top: **Last verified**: YYYY-MM-DD @ <commit SHA>. The agent (and the audit mode) uses this to know how stale the doc is.
-
No marketing language. "Beautifully crafted", "robust", "scalable" — delete on sight. Agents don't care; they want facts.
-
Link with relative paths, always. ../domains/auth.md, not absolute URLs. Repo-local.
Distributed CLAUDE.md (optional, recommended for medium+ projects)
After the domain docs are written, optionally generate small CLAUDE.md files inside each domain root. Each one is ~15–30 lines and contains:
- Pointer to the relevant
agent-docs/domains/<name>.md.
- Local-only conventions (3–7 bullets).
- Local-only foot-guns (2–5 bullets).
- An "after editing here, update X" rule.
This means: when an agent runs in backend/app/auth/, Claude Code auto-loads backend/app/auth/CLAUDE.md, which points it to exactly the right domain doc. No need to load MAP.md first. Template in references/distributed-claude-md-template.md.
Ask the user once: "Generate distributed CLAUDE.md files per domain, or stick with root-only?" Default to per-domain for projects with 6+ domains.
Root CLAUDE.md stanza
Append (don't replace) a stanza to the existing root CLAUDE.md (or create one if absent). Template in references/root-claude-md-stanza.md. The stanza:
- Points to
agent-docs/MAP.md as the entry point.
- States the navigation rule: "read MAP.md first, then the relevant domain doc, then the code".
- States the maintenance rule chosen in Phase 4.
Always show the diff to the user before writing. Never silently edit CLAUDE.md.
Phase 4: Sustain
Goal: ensure docs do not rot. The single biggest failure mode of agent docs is that they're accurate the day they were written and lies six weeks later.
Instructions and reminders alone catch maybe 70–90% of misses; agents drift. "Беспрекословно" requires a CI/pre-commit gate the agent can't bypass without an explicit, documented escape hatch. Policy C below is that gate, and it is the default.
The three policies stack: C uses A's instructions to document the escape hatch, and pairs cleanly with B for in-session reminders. Skip A or B only if the user explicitly opts out.
Policy C: CI/pre-commit gate (default, recommended)
scripts/check_agent_docs_freshness.py (shipped in this skill) is a small zero-dep script that, given a base ref, computes which domains had code changes and which domain docs were updated in the same change set. If they don't match, it fails with the exact fix command. Escape hatch: [skip-agent-docs] or [skip-agent-docs: dom1,dom2] in any commit message in the change set.
Install:
- Copy the script from
<skill>/scripts/check_agent_docs_freshness.py into the project's scripts/.
- Generate the GitHub Actions workflow (
.github/workflows/agent-docs-gate.yml) — template in references/ci-gate-setup.md.
- Wire up a local pre-commit hook (pre-commit framework / husky / raw
.git/hooks) — pick by detecting which the project uses; full options in references/ci-gate-setup.md.
- Append the escape-hatch documentation to root
CLAUDE.md so the agent knows the correct way to skip trivial changes.
- Tell the user to add the new CI job to required status checks in repo settings — without this step the gate runs but doesn't block merge.
Realistic coverage with C active: ≥ 99%. The remaining ≤ 1% is users invoking the escape hatch incorrectly.
Policy A: Instructions (always layered on top of C)
Append to root CLAUDE.md:
"When you change entry points, public API, architecture, or domain boundaries in a domain — update the corresponding agent-docs/domains/<name>.md in the same PR. When in doubt, run /agent-docs-architect update <name> or ask."
Plus the escape-hatch stanza from Policy C. Pros: catches the careful agent before reaching the gate. Cons: alone, ~50–70% coverage.
Policy B: In-session Stop-hook reminder (optional)
Emit a settings.json patch via the update-config skill that:
- Records changed file paths on
PostToolUse (Edit/Write) into .agent-docs-changed.
- On
Stop, surfaces a one-liner: "Touched domains: auth, apps. Run /agent-docs-architect update auth apps."
Template + settings patch in references/hooks-setup.md. Always show the user the proposed settings.json diff and let them apply it via /update-config. Do not write to settings.json directly from this skill.
Adds intermediate coverage between A and C — useful when the user wants to see "you should update X" inside the same session, not just at PR time. Stacks well with C; not a substitute.
Default install at Phase 4
Unless the user explicitly opts out:
- Install Policy C (CI gate + pre-commit + escape-hatch docs).
- Install Policy A (instructions stanza in root CLAUDE.md, already part of Phase 3 anyway).
- Offer Policy B; install on confirmation.
Either way: install the update and audit modes
Both rely on _meta/last-verified.json. When a domain doc is regenerated, update its entry. When audit runs, it:
- Reads
_meta/last-verified.json.
- For each domain, lists files modified after
last-verified (using git log --since=<date> -- <domain root>).
- If a domain has ≥ 5 changed files or the changes touch entry points listed in the doc → report as stale.
Periodic audit catches drift the CI gate let through (trivial-skip flag overused, escape hatch abused, manual git operations bypassing hooks).
Phase 5: Verify
Goal: prove the docs actually work before declaring done. This step is what separates useful docs from "looks fine" docs.
Pick two questions that an agent might realistically have about this project. Examples:
- "How does auth work end-to-end?"
- "Where would I add a new API route?"
- "What happens when a user uploads a file?"
For each:
- Start from
MAP.md.
- Follow the doc trail (MAP → domain doc → cross-cutting if needed).
- Count: how many files did you read? Can you answer the question? If yes → good.
- If you read more than 3 files and still can't answer → the doc has a gap. Fix it before finishing.
Report the two trials to the user as a sanity check.
Subagent orchestration (Phase 3 + multi-domain update)
Phase 3 is the most parallelizable part of this skill. The independence is structural: each domain doc is written from its own code root, with its own template, and the only cross-doc constraint (Neighbors bidirectionality) is enforced after-the-fact by the linter. So when there are ≥ 5 domains to document or refresh:
- The lead Claude writes
_meta/domain-paths.json and _meta/conventions.md first (these are inputs the subagents need).
- The lead dispatches one Agent call per domain in a single turn (parallel tool_use blocks in one message). Each subagent receives the writer master prompt from
references/subagent-orchestration.md with placeholders filled.
- As subagents return reports, the lead captures them but does not read the full docs yet.
- After all subagents finish, the lead runs
scripts/lint_docs.py for the deterministic checks.
- The lead reads the lint output + the subagent reports and resolves flags:
- Auto-fixable items (banned phrases, asymmetric Neighbors, missing canonical table headers) → fix inline.
- Judgment calls (file claimed by two domains, doc near 200-line limit, gaps the subagent flagged) → surface to the user.
- The lead writes MAP.md, cross-cutting.md,
_meta/last-verified.json — these need every domain output as input and can't be parallelized.
- The lead generates distributed
CLAUDE.md files (these are tiny, ~20 lines each — inline is fine).
- The lead proposes the root CLAUDE.md stanza + ci-gate-setup files (Phase 4 install).
The full master prompt for the writer subagent — including required sections, banned phrases, the structured report format, and constraints — lives in references/subagent-orchestration.md. Read that file before dispatching any subagent. The prompt is self-contained (subagents have no memory of the conversation) so getting it right is the difference between 18 useful docs and 18 docs that all subtly miss the same thing.
For update <domain> invoked on multiple domains, the same pattern applies with the update master prompt (also in subagent-orchestration.md). The key difference: the update prompt requires preserving handwritten content (## Notes, user-written gotchas) — never silently delete it.
When NOT to dispatch subagents:
- Phase 1 (Discover) and Phase 2 (Decompose) — these need the holistic view.
- < 5 domains — dispatch overhead exceeds gain.
- Single-domain
update — one Agent call is bureaucracy.
audit — script-driven, no judgment calls per domain.
add-domain — single-shot.
When the user asks for update <domain>
- Read the current
agent-docs/domains/<domain>.md.
- Compare its entry points, file list, and conventions against the current code in the domain root.
- Rewrite the doc preserving handwritten notes (the user may have added context the skill can't infer — keep anything under
## Notes or ## Gotchas unless clearly wrong).
- Update
_meta/last-verified.json.
- Show diff. Apply on approval.
When the user asks for audit
- Run the staleness check described in Phase 4.
- Output a report: which domains are stale, what likely changed, and what the agent should run to fix it.
- Do not auto-fix without permission.
When the user asks for add-domain <name> <path>
- Confirm the path is not already covered by an existing domain.
- Create
agent-docs/domains/<name>.md from references/domain-doc-template.md.
- Append a row to the MAP.md domains table.
- If distributed CLAUDE.md is enabled, generate the local CLAUDE.md.
- Update
_meta/last-verified.json.
What this skill does NOT do
- It does not replace the
context-map skill. Context-map is project memory (decisions, known issues, gotchas-as-history). This skill is architectural decomposition + agent navigation. Both can coexist; MAP.md should cross-reference the context map if it exists.
- It does not generate human-onboarding docs. The target reader is an LLM agent. If the user asks for human-readable architecture docs, suggest a separate flow (e.g., a
docs/architecture.md written for humans, with diagrams).
- It does not set up vector RAG, embeddings, LightRAG, or any external retrieval service. Those are heavier solutions for a problem most codebases don't have. If the user explicitly asks for RAG and the layered-docs approach genuinely doesn't fit, say so — don't try to fake it.
- It does not silently edit
CLAUDE.md, settings.json, .gitignore, or package.json. Every write to those files goes through a visible diff and explicit user approval.
Failure modes to watch for
- Over-decomposition: 40 domains for a 10k-line project. If a domain's doc is < 30 lines, merge it.
- Under-decomposition: 2 domains for a 200k-line monorepo. If a domain's doc grows past 200 lines, split.
- Doc-as-marketing: writing "the auth module elegantly handles..." is a smell. Replace with "auth module: stores sessions in Redis at key
sess:<uid>. RLS in policies.sql. JWT validation in middleware/auth.py:verify_token()."
- Forgetting verify: skipping Phase 5 leaves the user with docs that look right but break on first real agent question.
- Touching code while documenting: this skill writes docs and doc-config. It does not refactor code. If you notice a real bug while reading, flag it and stop — don't fix.
- Dispatching subagents with thin prompts: subagents have zero memory of this conversation. A 3-line prompt produces a 3-line doc. Always use the master prompt from
references/subagent-orchestration.md with placeholders fully filled.
- Skipping the lint pass after subagents: parallel subagents independently produce subtly-inconsistent docs (asymmetric Neighbors, varying banned-phrase tolerance, off-by-one tables). The linter catches this in seconds; reading 18 docs by hand misses things.
- Installing Policy C without telling the user about required status checks: the workflow runs but doesn't block merge until the user adds it to branch protection in repo settings. Easy to miss; surface this step explicitly.
Reference files
references/map-template.md — agent-docs/MAP.md structure.
references/domain-doc-template.md — per-domain doc structure (read this for every doc you write or dispatch).
references/cross-cutting-template.md — agent-docs/cross-cutting.md structure.
references/distributed-claude-md-template.md — per-folder CLAUDE.md template.
references/root-claude-md-stanza.md — text to append to the project root CLAUDE.md.
references/maintenance-rules.md — update, audit, add-domain mode mechanics + _meta/ schemas.
references/hooks-setup.md — Policy B (in-session Stop-hook reminders).
references/ci-gate-setup.md — Policy C (CI + pre-commit gate + escape hatch). Default; read this for Phase 4 install.
references/subagent-orchestration.md — master prompts for writer and update subagents + tech-lead review checklist. Read before dispatching Phase 3 subagents.
Bundled scripts
scripts/check_agent_docs_freshness.py — copied into the project's scripts/ at Phase 4 install. The CI/pre-commit gate. Zero deps, just stdlib + git.
scripts/lint_docs.py — invoked by the lead after writer subagents return. Read-only structural checks: required headers, banned phrases, table conformance, bidirectional Neighbors, MAP.md ↔ domains/ consistency. Exits 1 on errors so it can also be wired into CI for the post-init project, not just at generation time.