Code-Doc — Adaptive Codebase Documentation
A hybrid documentation generator that combines language-native extractors for API-level accuracy
with LLM agents for synthesis, architecture narratives, and developer guides. Zero-config default —
just point at a repo.
Delegation Model
Scout orchestrates. Analysts write to files. Doc Writers fan out.
- You are the Scout — handle detection, planning, synthesis, and coordination
- Analyst agents (
task(agent_type='explore')) read code and write full analysis to
{project}/.codedoc/ files. They return only compact summaries (max 15 lines) to you.
You hold summaries, not full analysis — this prevents context overflow.
- Doc Writer agents (
task(agent_type='general-purpose')) each read assigned .codedoc/
files and produce one output document
- Reviewer agents (
task(agent_type='explore')) validate generated docs
- All agents are stateless — provide complete context in each spawn
The .codedoc/ directory is transient — created at analysis start, consumed by doc writers,
and cleaned up before handoff. Never commit it. Prefer adding .codedoc/ to
.git/info/exclude for the local run; only modify project .gitignore if the user explicitly
approves that as part of the documentation plan or commit proposal.
Analyst Output Protocol
Every analyst agent must:
- Write full analysis to their assigned
.codedoc/{name}-analysis.md file
- Cite source paths for material claims and include confidence (
high/medium/low) where evidence is incomplete or inferred
- Return ONLY a compact summary to you (max 15 lines):
- File written path
- Key stats (counts, patterns found)
- Notable findings or anomalies
- Lowest-confidence claims needing synthesis/reviewer attention
Secret Redaction Rules
Generated docs must never expose secret values, tokens, credentials, private URLs, or production-only
connection strings. For config/security/env docs, document only variable names, purpose, expected
format, safe defaults, and source file paths. Redact observed values as <redacted> and flag
suspected secrets for user handling instead of copying them into .codedoc/ or final docs.
Workflow
Step 1 — Scout & Detect
Accept the repository path (defaults to cwd). Scan the codebase:
- Detect project type, languages, frameworks, and libraries
- Identify architecture patterns, entry points, and module boundaries
- Detect monorepo structure if present
--with-build flag (optional) — enables build-assisted analysis for resolved types
Monorepo handling: If workspace patterns detected (pnpm-workspace.yaml, lerna.json,
packages/*/package.json, etc.), list sub-projects and let user choose unified (single doc set)
or per-project (separate docs per package). Per-project repeats Steps 2–8 for each.
Step 2 — Assess Existing Docs
Inventory existing documentation and classify:
| Level |
Action |
| No docs |
Fresh generation |
| Partial |
Fill gaps, preserve existing |
| Comprehensive |
Augment-only — propose additions, never overwrite. Preserve <!-- human --> blocks entirely. |
README protection default: Do not blindly overwrite an existing human README. Generate or rewrite
README.md only when it is missing, tiny/template-like, already code-doc-generated, or explicitly approved
by the user. Otherwise preserve it, generate supporting docs, and optionally propose a small
link section for user approval.
Step 3 — Propose Doc Plan
Present the plan to the user for confirmation before proceeding.
Core targets (generated by default, except protected README):
| Document |
Purpose |
Generation rule |
README.md |
Project overview, quick start |
Protected core target: generate/rewrite only if missing, tiny/template-like, already code-doc-generated, or explicitly approved; otherwise preserve and optionally propose a small link/index patch |
docs/architecture-guide.md |
System design, component relationships |
Always generated |
docs/developer-guide.md |
Setup, development workflow |
Always generated |
docs/codebase-context.md |
LLM-optimized codebase summary |
Always generated |
Artifact catalog (scout recommends based on codebase analysis):
| Document |
Purpose |
Condition |
docs/navigation.md |
Entry points, capability-to-file map, "how do I add X" guides |
Codebase has >10 source files |
docs/patterns.md |
Naming conventions, code patterns, anti-hallucination index, inconsistencies |
Always recommended |
docs/config.md |
Env vars, config files, feature flags with defaults and locations |
process.env/config file usage detected |
docs/errors.md |
Error taxonomy, throw/catch mapping, unhandled gaps |
Custom error classes or >5 distinct throw sites |
docs/flows.md |
Request lifecycle, state machines, event propagation |
HTTP middleware, state enums, or event emitters detected |
docs/boundaries.md |
Layer rules, module contracts, import violations |
Multi-directory architecture with >3 top-level modules |
docs/inventory.md |
Utility registry — "before you write it, we have it" |
utils/, lib/, helpers/, or shared/ directories |
docs/security.md |
Route auth matrix, input validation audit, concerns |
Auth middleware, route definitions, or secrets handling |
Scout recommendation process:
- After detection (Step 1), evaluate each catalog artifact's condition against the codebase
- Recommend artifacts whose conditions are met, with a one-line justification per selection
- Optionally propose up to 3 custom artifacts not in the catalog — each requires a name,
purpose, and justification explaining why this codebase warrants it
- Present the full doc plan (core targets, including README decision, + recommended artifacts) to the user for confirmation
Example scout output:
Core: README.md (protected target; conditional writer), architecture-guide.md, developer-guide.md, codebase-context.md
Recommended artifacts:
✅ navigation.md — 47 source files across 8 directories
✅ patterns.md — always recommended
✅ config.md — 12 process.env references found
✅ flows.md — Express middleware chain + 3 state enums detected
⬚ errors.md — only 2 throw sites, insufficient for standalone doc
⬚ boundaries.md — flat directory structure
⬚ inventory.md — no utils/lib/helpers directories
⬚ security.md — no auth middleware detected
Custom: (none proposed)
Wait for user confirmation before proceeding.
Step 4 — Analyze
Always delegate analysis to sub-agents. Do not attempt to analyze the codebase yourself.
- Create analysis directory:
mkdir -p {project}/.codedoc
- Run native extractors first (if available): TypeDoc, Sphinx, godoc, javadoc, rustdoc, DocFX.
Save output to
.codedoc/native-extractors/. This provides ground-truth for signatures and types.
Also write .codedoc/native-extractors/report.md listing each extractor considered with status
(attempted, ran, failed, or skipped), command, output path, and failure/skip reason.
Treat .codedoc/native-extractors/* as transient unless explicitly exported in the confirmed plan;
before cleanup, copy extractor status/transparency into persisted synthesis/handoff data.
- Spawn analyst agents in parallel based on the confirmed doc plan:
| Agent |
Condition |
Output File |
| Architecture Analyst |
Always |
.codedoc/architecture-analysis.md |
| Catalog Artifact Analyst (×N) |
One per selected artifact from Step 3 |
.codedoc/{artifact-name}-analysis.md |
| Custom Artifact Analyst (×M) |
One per approved custom artifact |
.codedoc/{custom-name}-analysis.md |
For example, if Step 3 selected navigation, patterns, config, and flows, spawn 5 analysts:
Architecture + Navigation + Patterns + Config + Flows.
Each analyst is spawned with a complete stateless prompt containing:
- Confirmed doc plan, selected artifact/custom artifact, and assigned
.codedoc/{name}-analysis.md path
- Update mode (
Fresh, Regenerate, or Augment), protected paths, README protection decision, and approved/non-approved output locations relevant to their scope
- Project context: repository path, framework/language detections, monorepo scope, entry points, file/include/exclude scope, and synthesis questions to answer
- Native extractor context:
.codedoc/native-extractors/ output path plus report/status summary when available; prefer extractor evidence for signatures/types
- Secret redaction rules and any known sensitive files/values to avoid copying into analysis
- Citation/confidence protocol: cite source paths for material claims, mark inferred or incomplete claims
high/medium/low, and list evidence gaps
- Source/path evidence requirements: verify referenced files exist, distinguish observed code facts from inferred architecture, and include path evidence for APIs, flows, config, and dependencies
- Output/report structure: overview, key findings, source inventory, relationships/flows, risks/anomalies, evidence table, and low-confidence items requiring synthesis/reviewer attention
They write full analysis and return a compact summary.
Step 5 — Synthesize
Read .codedoc/ files selectively (not all at once) and build a unified model:
- Unify data models — merge native extractor types with analyst findings
- Correlate cross-cutting concerns — trace flows across components
- Detect inconsistencies between analyst outputs
- Identify documentation-worthy flows and key paths
- Include native extractor transparency from
.codedoc/native-extractors/report.md, including
statuses, commands, output paths, and failure/skip reasons, so this evidence survives cleanup
- Write synthesis to
{project}/.codedoc/synthesis.md
Step 6 — User Checkpoint
Present synthesis summary: architecture pattern, component count, data flows, API endpoints,
key findings, and any inconsistencies. User confirms, aborts, or requests re-analysis of a
specific area.
Step 7 — Generate
Fan out documentation generation to parallel doc writer agents.
Each writer is spawned via task(agent_type='general-purpose') with a complete stateless prompt containing:
- Confirmed doc plan and assigned output file path
- Update mode (
Fresh, Regenerate, or Augment) and merge/preservation instructions
- Protected paths, README protection decision, and whether README writing was explicitly approved
- Target audience, tone/style, terminology preferences, and desired depth
- Frontmatter/metadata schema and required version/hash/timestamp values
- Secret redaction rules and any project-specific sensitive files or values to avoid
- Source/path citation expectations for material claims and API details
- No-placeholder rule: no TODO/TBD/filler sections; omit or mark low-confidence with evidence instead
- Relevant
.codedoc/ analysis files, native extractor report/status summary, and synthesis summary
Spawn the README writer only if README is missing, tiny/template-like, already code-doc-generated, or
explicitly approved. If README is protected, preserve it and optionally propose a small link/index
patch for user approval. Architecture, Developer Guide, and Codebase Context writers always spawn.
Optional writers spawn based on the doc plan from Step 3.
All generated docs must include frontmatter (the Accuracy reviewer will flag missing fields as 🔴 BLOCKER):
---
codedoc_version: 1
generated: "<ISO 8601 timestamp>"
project_hash: "<short git hash from `git rev-parse --short HEAD`, or `uncommitted`/`no-git` when unavailable>"
---
Update mode (re-generation):
IF existing docs detected, READ references/update-merge.md for archive, human block preservation, and augmentation logic.
| Mode |
Condition |
Behavior |
| Fresh |
No existing docs |
Generate approved targets; still apply README protection if a README exists |
| Regenerate |
Existing code-doc output (codedoc_version frontmatter) |
Archive to .docs-archive/v{N}/, regenerate, merge <!-- human --> blocks |
| Augment |
Existing human docs (no frontmatter, high quality) |
Preserve entirely, add only to docs/codedoc/ subdirectory |
Step 8 — Review & Handoff
Spawn 3 reviewer agents (task(agent_type='explore')) in parallel. Each reviewer is spawned with a complete stateless prompt containing:
- Confirmed doc plan, generated/modified doc paths, update mode (
Fresh, Regenerate, or Augment), protected paths, README decision, and approved output scope
- Frontmatter/metadata expectations, including
codedoc_version, generated, project_hash, and augmentation_mode: true where relevant
- Secret redaction rules and the requirement to flag leaked values without repeating the secret value
- Native extractor report/status summary, synthesis summary, and relevant
.codedoc/ analysis file paths or excerpts needed for the review focus
- Citation/confidence protocol: require path/source evidence for challenged claims, confidence labels for uncertain findings, and no unsupported reviewer assertions
- Source/path evidence requirements: verify cited source paths and generated doc paths exist, cross-check API/signature claims against native extractor output where available, and distinguish missing evidence from false claims
- Output/report structure: verdict, blocker/warning/info findings, affected docs, challenged claims, evidence paths/sources, confidence, recommended fixes, and explicit pass/fail on their focus area
| Reviewer |
Focus |
| Accuracy |
Cross-reference against native extractor output, verify code paths exist, confirm every generated doc has valid frontmatter (codedoc_version, generated, project_hash) |
| Completeness |
All planned sections populated, no TODO placeholders |
| Clarity |
Writing quality, consistent terminology, actionable instructions |
Each reviewer finding must include: severity, affected doc, claim being challenged, evidence
path/source, confidence (high/medium/low), and recommended fix.
Severity: 🔴 BLOCKER (must fix) · 🟠 WARNING (should fix) · 🟡 INFO (optional).
Fix all 🔴s. User decides on 🟠s. Maximum 2 fix iterations.
If blockers remain after 2 iterations, summarize unresolved items and recommend adding a
## Known Issues section. Do not append Known Issues or proceed with degraded docs until the
user explicitly approves.
After review is ready:
- Persist native extractor transparency from
.codedoc/native-extractors/report.md into the
synthesis/handoff notes before cleanup; .codedoc/native-extractors/* paths are transient unless
the confirmed plan explicitly exported them
- Clean transient analysis artifacts first:
rm -rf {project}/.codedoc
- Re-check git state with
git status --short and verify .codedoc/ is absent
- Present a Documentation Handoff Contract:
- Generated/modified documentation files
- Any archive paths (
.docs-archive/) and whether they are excluded from the proposed commit
- Any
.gitignore change and why it is needed
- Native extractor transparency: attempted/ran/failed/skipped extractors, commands, output paths, and reasons
- Review result summary and unresolved warnings
- Proposed commit message:
docs: generate codebase documentation via code-doc
- Ask the user what to do next
Commit policy:
- Never run
git add, git commit, or git add . automatically.
- If the user declines a commit, leave the generated docs uncommitted and report changed paths.
- If the user explicitly approves a commit:
- Stage only approved pathspecs, never broad
git add .
- Exclude
.codedoc/ always
- Exclude
.docs-archive/ by default unless the user explicitly approves archiving it
- Run
git diff --cached --stat (or equivalent status summary) and confirm staged scope is correct
- Commit with the approved message
- Report the commit hash and changed files
Sub-Agent Summary
| Role |
Agent Type |
Model |
| Analyst |
explore |
Haiku |
| Doc Writer |
general-purpose |
Sonnet |
| Reviewer |
explore |
Sonnet |
Designed for multi-agent orchestration. Requires: git, native extractors per language (optional).
1---2name: code-doc3description: Generates comprehensive documentation for any codebase via hybrid analysis (native extractors + LLM agents). Triggers on phrases like "document this codebase", "generate documentation", "create docs for this repo", "write documentation", "document the code", "generate codebase docs", "create architecture docs", "write a developer guide", "document this project".4---56# Code-Doc — Adaptive Codebase Documentation78A hybrid documentation generator that combines language-native extractors for API-level accuracy9with LLM agents for synthesis, architecture narratives, and developer guides. Zero-config default —10just point at a repo.1112---1314## Delegation Model1516**Scout orchestrates. Analysts write to files. Doc Writers fan out.**1718- **You are the Scout** — handle detection, planning, synthesis, and coordination19- **Analyst agents** (`task(agent_type='explore')`) read code and write full analysis to20 `{project}/.codedoc/` files. They return only compact summaries (max 15 lines) to you.21 You hold summaries, not full analysis — this prevents context overflow.22- **Doc Writer agents** (`task(agent_type='general-purpose')`) each read assigned `.codedoc/`23 files and produce one output document24- **Reviewer agents** (`task(agent_type='explore')`) validate generated docs25- All agents are stateless — provide complete context in each spawn2627The `.codedoc/` directory is transient — created at analysis start, consumed by doc writers,28and cleaned up before handoff. Never commit it. Prefer adding `.codedoc/` to29`.git/info/exclude` for the local run; only modify project `.gitignore` if the user explicitly30approves that as part of the documentation plan or commit proposal.3132### Analyst Output Protocol3334Every analyst agent must:35361. Write full analysis to their assigned `.codedoc/{name}-analysis.md` file372. Cite source paths for material claims and include confidence (`high`/`medium`/`low`) where evidence is incomplete or inferred383. Return ONLY a compact summary to you (max 15 lines):39 - File written path40 - Key stats (counts, patterns found)41 - Notable findings or anomalies42 - Lowest-confidence claims needing synthesis/reviewer attention4344### Secret Redaction Rules4546Generated docs must never expose secret values, tokens, credentials, private URLs, or production-only47connection strings. For config/security/env docs, document only variable names, purpose, expected48format, safe defaults, and source file paths. Redact observed values as `<redacted>` and flag49suspected secrets for user handling instead of copying them into `.codedoc/` or final docs.5051---5253## Workflow5455### Step 1 — Scout & Detect5657Accept the repository path (defaults to cwd). Scan the codebase:58591. Detect project type, languages, frameworks, and libraries602. Identify architecture patterns, entry points, and module boundaries613. Detect monorepo structure if present624. `--with-build` flag (optional) — enables build-assisted analysis for resolved types6364**Monorepo handling:** If workspace patterns detected (`pnpm-workspace.yaml`, `lerna.json`,65`packages/*/package.json`, etc.), list sub-projects and let user choose **unified** (single doc set)66or **per-project** (separate docs per package). Per-project repeats Steps 2–8 for each.6768---6970### Step 2 — Assess Existing Docs7172Inventory existing documentation and classify:7374| Level | Action |75|-------|--------|76| **No docs** | Fresh generation |77| **Partial** | Fill gaps, preserve existing |78| **Comprehensive** | Augment-only — propose additions, never overwrite. Preserve `<!-- human -->` blocks entirely. |7980**README protection default:** Do not blindly overwrite an existing human README. Generate or rewrite81`README.md` only when it is missing, tiny/template-like, already code-doc-generated, or explicitly approved82by the user. Otherwise preserve it, generate supporting docs, and optionally propose a small83link section for user approval.8485---8687### Step 3 — Propose Doc Plan8889Present the plan to the user for confirmation before proceeding.9091**Core targets** (generated by default, except protected README):9293| Document | Purpose | Generation rule |94|----------|---------|-----------------|95| `README.md` | Project overview, quick start | Protected core target: generate/rewrite only if missing, tiny/template-like, already code-doc-generated, or explicitly approved; otherwise preserve and optionally propose a small link/index patch |96| `docs/architecture-guide.md` | System design, component relationships | Always generated |97| `docs/developer-guide.md` | Setup, development workflow | Always generated |98| `docs/codebase-context.md` | LLM-optimized codebase summary | Always generated |99100**Artifact catalog** (scout recommends based on codebase analysis):101102| Document | Purpose | Condition |103|----------|---------|-----------|104| `docs/navigation.md` | Entry points, capability-to-file map, "how do I add X" guides | Codebase has >10 source files |105| `docs/patterns.md` | Naming conventions, code patterns, anti-hallucination index, inconsistencies | Always recommended |106| `docs/config.md` | Env vars, config files, feature flags with defaults and locations | `process.env`/config file usage detected |107| `docs/errors.md` | Error taxonomy, throw/catch mapping, unhandled gaps | Custom error classes or >5 distinct throw sites |108| `docs/flows.md` | Request lifecycle, state machines, event propagation | HTTP middleware, state enums, or event emitters detected |109| `docs/boundaries.md` | Layer rules, module contracts, import violations | Multi-directory architecture with >3 top-level modules |110| `docs/inventory.md` | Utility registry — "before you write it, we have it" | `utils/`, `lib/`, `helpers/`, or `shared/` directories |111| `docs/security.md` | Route auth matrix, input validation audit, concerns | Auth middleware, route definitions, or secrets handling |112113**Scout recommendation process:**1141151. After detection (Step 1), evaluate each catalog artifact's condition against the codebase1162. Recommend artifacts whose conditions are met, with a one-line justification per selection1173. Optionally propose up to **3 custom artifacts** not in the catalog — each requires a name,118 purpose, and justification explaining why this codebase warrants it1194. Present the full doc plan (core targets, including README decision, + recommended artifacts) to the user for confirmation120121Example scout output:122123```124Core: README.md (protected target; conditional writer), architecture-guide.md, developer-guide.md, codebase-context.md125126Recommended artifacts:127 ✅ navigation.md — 47 source files across 8 directories128 ✅ patterns.md — always recommended129 ✅ config.md — 12 process.env references found130 ✅ flows.md — Express middleware chain + 3 state enums detected131 ⬚ errors.md — only 2 throw sites, insufficient for standalone doc132 ⬚ boundaries.md — flat directory structure133 ⬚ inventory.md — no utils/lib/helpers directories134 ⬚ security.md — no auth middleware detected135136Custom: (none proposed)137```138139Wait for user confirmation before proceeding.140141---142143### Step 4 — Analyze144145**Always delegate analysis to sub-agents.** Do not attempt to analyze the codebase yourself.1461471. Create analysis directory: `mkdir -p {project}/.codedoc`1482. Run **native extractors** first (if available): TypeDoc, Sphinx, godoc, javadoc, rustdoc, DocFX.149 Save output to `.codedoc/native-extractors/`. This provides ground-truth for signatures and types.150 Also write `.codedoc/native-extractors/report.md` listing each extractor considered with status151 (`attempted`, `ran`, `failed`, or `skipped`), command, output path, and failure/skip reason.152 Treat `.codedoc/native-extractors/*` as transient unless explicitly exported in the confirmed plan;153 before cleanup, copy extractor status/transparency into persisted synthesis/handoff data.1543. **Spawn analyst agents** in parallel based on the confirmed doc plan:155156| Agent | Condition | Output File |157|-------|-----------|-------------|158| Architecture Analyst | Always | `.codedoc/architecture-analysis.md` |159| Catalog Artifact Analyst (×N) | One per selected artifact from Step 3 | `.codedoc/{artifact-name}-analysis.md` |160| Custom Artifact Analyst (×M) | One per approved custom artifact | `.codedoc/{custom-name}-analysis.md` |161162For example, if Step 3 selected `navigation`, `patterns`, `config`, and `flows`, spawn 5 analysts:163Architecture + Navigation + Patterns + Config + Flows.164165Each analyst is spawned with a complete stateless prompt containing:166- Confirmed doc plan, selected artifact/custom artifact, and assigned `.codedoc/{name}-analysis.md` path167- Update mode (`Fresh`, `Regenerate`, or `Augment`), protected paths, README protection decision, and approved/non-approved output locations relevant to their scope168- Project context: repository path, framework/language detections, monorepo scope, entry points, file/include/exclude scope, and synthesis questions to answer169- Native extractor context: `.codedoc/native-extractors/` output path plus report/status summary when available; prefer extractor evidence for signatures/types170- Secret redaction rules and any known sensitive files/values to avoid copying into analysis171- Citation/confidence protocol: cite source paths for material claims, mark inferred or incomplete claims `high`/`medium`/`low`, and list evidence gaps172- Source/path evidence requirements: verify referenced files exist, distinguish observed code facts from inferred architecture, and include path evidence for APIs, flows, config, and dependencies173- Output/report structure: overview, key findings, source inventory, relationships/flows, risks/anomalies, evidence table, and low-confidence items requiring synthesis/reviewer attention174175They write full analysis and return a compact summary.176177---178179### Step 5 — Synthesize180181Read `.codedoc/` files selectively (not all at once) and build a unified model:1821831. Unify data models — merge native extractor types with analyst findings1842. Correlate cross-cutting concerns — trace flows across components1853. Detect inconsistencies between analyst outputs1864. Identify documentation-worthy flows and key paths1875. Include native extractor transparency from `.codedoc/native-extractors/report.md`, including188 statuses, commands, output paths, and failure/skip reasons, so this evidence survives cleanup1896. Write synthesis to `{project}/.codedoc/synthesis.md`190191---192193### Step 6 — User Checkpoint194195Present synthesis summary: architecture pattern, component count, data flows, API endpoints,196key findings, and any inconsistencies. User confirms, aborts, or requests re-analysis of a197specific area.198199---200201### Step 7 — Generate202203Fan out documentation generation to parallel doc writer agents.204205Each writer is spawned via `task(agent_type='general-purpose')` with a complete stateless prompt containing:206- Confirmed doc plan and assigned output file path207- Update mode (`Fresh`, `Regenerate`, or `Augment`) and merge/preservation instructions208- Protected paths, README protection decision, and whether README writing was explicitly approved209- Target audience, tone/style, terminology preferences, and desired depth210- Frontmatter/metadata schema and required version/hash/timestamp values211- Secret redaction rules and any project-specific sensitive files or values to avoid212- Source/path citation expectations for material claims and API details213- No-placeholder rule: no TODO/TBD/filler sections; omit or mark low-confidence with evidence instead214- Relevant `.codedoc/` analysis files, native extractor report/status summary, and synthesis summary215216Spawn the README writer only if README is missing, tiny/template-like, already code-doc-generated, or217explicitly approved. If README is protected, preserve it and optionally propose a small link/index218patch for user approval. Architecture, Developer Guide, and Codebase Context writers always spawn.219Optional writers spawn based on the doc plan from Step 3.220221All generated docs **must** include frontmatter (the Accuracy reviewer will flag missing fields as 🔴 BLOCKER):222223```yaml224---225codedoc_version: 1226generated: "<ISO 8601 timestamp>"227project_hash: "<short git hash from `git rev-parse --short HEAD`, or `uncommitted`/`no-git` when unavailable>"228---229```230231**Update mode** (re-generation):232233IF existing docs detected, READ `references/update-merge.md` for archive, human block preservation, and augmentation logic.234235| Mode | Condition | Behavior |236|------|-----------|----------|237| **Fresh** | No existing docs | Generate approved targets; still apply README protection if a README exists |238| **Regenerate** | Existing code-doc output (`codedoc_version` frontmatter) | Archive to `.docs-archive/v{N}/`, regenerate, merge `<!-- human -->` blocks |239| **Augment** | Existing human docs (no frontmatter, high quality) | Preserve entirely, add only to `docs/codedoc/` subdirectory |240241---242243### Step 8 — Review & Handoff244245Spawn 3 reviewer agents (`task(agent_type='explore')`) in parallel. Each reviewer is spawned with a complete stateless prompt containing:246- Confirmed doc plan, generated/modified doc paths, update mode (`Fresh`, `Regenerate`, or `Augment`), protected paths, README decision, and approved output scope247- Frontmatter/metadata expectations, including `codedoc_version`, `generated`, `project_hash`, and `augmentation_mode: true` where relevant248- Secret redaction rules and the requirement to flag leaked values without repeating the secret value249- Native extractor report/status summary, synthesis summary, and relevant `.codedoc/` analysis file paths or excerpts needed for the review focus250- Citation/confidence protocol: require path/source evidence for challenged claims, confidence labels for uncertain findings, and no unsupported reviewer assertions251- Source/path evidence requirements: verify cited source paths and generated doc paths exist, cross-check API/signature claims against native extractor output where available, and distinguish missing evidence from false claims252- Output/report structure: verdict, blocker/warning/info findings, affected docs, challenged claims, evidence paths/sources, confidence, recommended fixes, and explicit pass/fail on their focus area253254255| Reviewer | Focus |256|----------|-------|257| **Accuracy** | Cross-reference against native extractor output, verify code paths exist, confirm every generated doc has valid frontmatter (`codedoc_version`, `generated`, `project_hash`) |258| **Completeness** | All planned sections populated, no TODO placeholders |259| **Clarity** | Writing quality, consistent terminology, actionable instructions |260261Each reviewer finding must include: severity, affected doc, claim being challenged, evidence262path/source, confidence (`high`/`medium`/`low`), and recommended fix.263264Severity: 🔴 BLOCKER (must fix) · 🟠 WARNING (should fix) · 🟡 INFO (optional).265Fix all 🔴s. User decides on 🟠s. Maximum 2 fix iterations.266267If blockers remain after 2 iterations, summarize unresolved items and recommend adding a268`## Known Issues` section. Do not append Known Issues or proceed with degraded docs until the269user explicitly approves.270271After review is ready:2722731. Persist native extractor transparency from `.codedoc/native-extractors/report.md` into the274 synthesis/handoff notes before cleanup; `.codedoc/native-extractors/*` paths are transient unless275 the confirmed plan explicitly exported them2762. Clean transient analysis artifacts first: `rm -rf {project}/.codedoc`2773. Re-check git state with `git status --short` and verify `.codedoc/` is absent2784. Present a **Documentation Handoff Contract**:279 - Generated/modified documentation files280 - Any archive paths (`.docs-archive/`) and whether they are excluded from the proposed commit281 - Any `.gitignore` change and why it is needed282 - Native extractor transparency: attempted/ran/failed/skipped extractors, commands, output paths, and reasons283 - Review result summary and unresolved warnings284 - Proposed commit message: `docs: generate codebase documentation via code-doc`2855. Ask the user what to do next286287**Commit policy:**288289- Never run `git add`, `git commit`, or `git add .` automatically.290- If the user declines a commit, leave the generated docs uncommitted and report changed paths.291- If the user explicitly approves a commit:292 1. Stage only approved pathspecs, never broad `git add .`293 2. Exclude `.codedoc/` always294 3. Exclude `.docs-archive/` by default unless the user explicitly approves archiving it295 4. Run `git diff --cached --stat` (or equivalent status summary) and confirm staged scope is correct296 5. Commit with the approved message297 6. Report the commit hash and changed files298299---300301## Sub-Agent Summary302303| Role | Agent Type | Model |304|------|-----------|-------|305| Analyst | `explore` | Haiku |306| Doc Writer | `general-purpose` | Sonnet |307| Reviewer | `explore` | Sonnet |308309---310311_Designed for multi-agent orchestration. Requires: `git`, native extractors per language (optional)._