Explain Project
Generate a comprehensive technical overview document for a project, written for a brilliant reader who lacks computer science training.
Target reader: A top-quintile intelligence mechanical engineer. Sharp, process-oriented, comfortable with measurements and thresholds, experienced with quality systems and structured problem-solving. Has never taken a CS class.
Output: A styled Word document (.docx) with all accessibility annotations baked in — sidebars, glossary, inline definitions, footnotes, developer section labels, and optionally generated images.
Inputs
One required argument (either a local path OR a GitHub URL):
- Project directory path -- a local directory containing the codebase to document
- OR GitHub URL -- a public repo URL (e.g.,
https://github.com/owner/repo). The skill will clone it to a temp directory, analyze it, and output the document to the user's Downloads folder.
Optional flags:
--style PATH -- Path to a markdown style guide for Word formatting (default: $DOC_STYLE_GUIDE env var if set; author's default: ~/.claude/styles/CFA_Word_Style_Guide.md)
--style-json PATH -- Path to image style JSON for Nano Banana Pro (default: $IMAGE_STYLE_JSON env var if set; author's default: ~/dev/brand-assets/clients/cfa/styles/clean-style-sanitized.json)
--generate-images -- Generate diagrams via Google Gemini and insert them (default: OFF — costs money)
--update -- Incremental update mode: reads the existing document, diffs the codebase against the last generation (via git log since the commit hash in the document's freshness metadata), generates only changed sections, and preserves the user's manual refinements to unchanged sections
--output PATH -- Output file path (default: {project-dir}/docs/{project-name}-overview.docx, or ~/Downloads/{repo-name}-overview.docx for GitHub URLs)
Parse from the user's message. If neither a path nor URL is provided, ask.
Detecting Previous Documents
Before starting a fresh generation, check for existing documents matching docs/*-overview*.docx in the project directory. If found:
- Read the existing document to understand what it covers
- Check git log for changes since the document was last generated (use the freshness metadata commit hash if available, otherwise file modification date)
- Offer the user a choice: update (incremental, preserves manual edits) vs regenerate (full fresh generation)
In --update mode:
- Parse the existing document's section structure
- Diff the codebase to identify what changed (new files, modified stages, config changes)
- Generate only the sections affected by codebase changes
- Preserve the user's manual refinements to unchanged sections
- Update the Document Freshness metadata block with current values
Handling GitHub URLs
When the input is a GitHub URL (contains github.com):
Clone the repo using worktree isolation:
isolation: worktree
Use git clone --depth 1 "{url}" . inside the worktree. Worktree auto-cleanup replaces manual /tmp directory management — no explicit cleanup step needed.
Set output path to Downloads:
~/Downloads/{repo-name}-overview.docx
Analyze and generate using the same Phase 1-5 process as for local projects.
Note: Only public repos are supported (no authentication). For private repos, clone manually first and provide the local path. Worktree cleanup is automatic because this skill is read-only and makes no commits.
Process
Phase 1: Deep Project Analysis
Dispatch this entire phase to an isolated Explore subagent:
context: fork
agent: Explore
Inject project git context before analysis:
- Recent commits:
!git log --oneline -20``
- Top contributors:
!git shortlog -sn --no-merges | head -10``
The Explore subagent builds comprehensive understanding:
Project identity: Read README, CLAUDE.md, package.json/pyproject.toml, and top-level docs
Architecture: Map the directory structure, identify major components, entry points, and data flow
Pipeline/stages: Identify processing stages, their order, inputs/outputs, and dependencies
Data models: Read model definitions, schemas, configuration files
Products/outputs: What does the system produce? What consumes the output?
Testing: Test suite structure, coverage, evaluation approach
Infrastructure: What hardware/services does it depend on? How does it deploy?
Technical vocabulary: Catalog every CS/ML/domain term the project uses
Runtime artifacts: If the project produces output artifacts (reports, logs, dashboards, metrics files), read them. Look for:
- Latest pipeline output in
output/ or similar directories (statistics, counts, timing)
- Log files with timing data, cache hit rates, throughput numbers
- Metrics or evaluation result files from recent runs
- Configuration files with active thresholds, weights, and feature flags
Ground the document in production reality, not code-reading estimates. Every production number cited in the document should trace back to an actual output artifact, not a guess derived from reading the code.
Return all findings to the parent skill for Phase 2 document planning.
Phase 2: Document Planning
IMPORTANT: Read the structure template at $DOC_STRUCTURE_TEMPLATE (author's default: ~/dev/info/technical-document-structure-template.md) before planning. If this file is absent, proceed without the structure template and note that in the output. It contains a complexity table that maps project size to expected document depth. Not every section applies to every project.
Select Key Concept Sidebars (2-3): Choose the foundational concepts THIS project relies on most. These will be the first things the reader sees.
Plan the "Why This Approach" section (if warranted): Identify 2-4 reasonable objections a skeptic would raise. What simpler approaches would people suggest? Why do they fail? Skip for simple projects where the approach is obvious. Where available, include:
- Actual benchmark data from evaluation runs (precision, recall, F1 from test sets)
- Specific evaluation results that justify design decisions
- A cost/benefit table for the overall system vs. simpler alternatives (time to build, accuracy gained, maintenance burden)
Design the worked example: Choose a concrete, realistic input that will be traced through every stage. It should exercise the system's most important capabilities.
Map the stage/component walkthrough: List every processing stage or major component with:
- What it transforms (input → output)
- Why it matters (consequence of skipping)
- How the worked example changes at this stage
Plan images (3-5): Identify where diagrams would most help.
Always generate:
- Data flow diagram — stages with their inputs and outputs, showing the transformation pipeline end to end
- System architecture — infrastructure topology showing hardware, services, and their connections
Generate if applicable:
- Worked example transformation — showing how the running example changes at key stages
- Dashboard/UI mockup — conceptual layout of any interactive output the system produces
- Conceptual visualization of the novel/hardest technique
Never generate:
- Screenshots of code (not useful for the target reader)
- Class diagrams or UML (too developer-focused for the ME audience)
Build the glossary list: Every CS/ML term that will appear in the document, with draft definitions at the right depth. Plan bookmark names for each entry (convention: _glossary_ + lowercase_underscored_name). The glossary will be the hyperlink target for first-occurrence terms in the body text.
Present this plan to the user before writing. Format as a brief outline showing:
- Proposed sidebar topics
- "Why not just..." questions (if any)
- Worked example selection
- Stage/component list with one-line descriptions
- Image locations
- Glossary term count
Phase 3: Document Generation
Write each section following the proven patterns:
Executive Summary:
- Key Concept Sidebars (2-3) at the top — these are pedagogical gateways for the most foundational concepts only; all other terms use the glossary hyperlink mechanism
- What goes in → what comes out (one sentence)
- Problem context (why the status quo fails)
- What the system does (high-level, naming major phases)
- Production numbers table (if available)
- Validation summary
Why This Approach (if warranted):
- 2-4 subsections, each a skeptic's question
- 3-column comparison tables where applicable
- Concrete data and failure modes, not abstract arguments
- Include actual benchmark data when available (e.g., evaluation precision/recall)
- Include a cost/benefit summary table for the overall system vs. alternatives
Worked Example:
- Show the actual input (raw data, article text, etc.)
- Explain why this example demonstrates the system's capabilities
- Prefer real examples from production output when available — they are automatically accurate and carry more weight with the reader
- If a fabricated example is necessary, state explicitly: "This is a representative example constructed to illustrate the process" — never present fabricated data as production output
Stage-by-Stage / Component Walkthrough:
For each stage or component, follow this template:
**What happens:** [concrete transformation]
**Why it matters:** [consequence of skipping]
**Our example becomes:** [running example after this stage]
**Technical details:** [developer-oriented, preceded by "Technical Reference" label]
Products/Applications (if applicable):
- What uses the pipeline output
- How end users interact with it
Second Worked Example (if the system has a distinct "use" phase):
- Trace a realistic query/request through the system
- Show intermediate results at each step
Quality and Validation:
- Testing summary table
- Evaluation approach
- Quality metrics and regression gates
Technical Architecture:
- Preceded by "Technical Reference" label
- Infrastructure, models, caching, concurrency
How to Evaluate This System (if appropriate):
- Decision-maker-oriented questions with pointers to answers
Known Limitations and Coverage Gaps:
This is a standard section for every document — the ME reader treats this as the specification sheet. Every product has specs AND limitations. Include:
- What the system does not cover (explicit scope boundaries)
- What data it excludes and why
- Edge cases it handles poorly or not at all
- Known accuracy limitations (false positive rates, failure modes)
- Scale or performance boundaries
Current Operational State / Config Snapshot (if the project has a production deployment):
Auto-populate from actual config files and latest run output:
- Current deployment topology (what runs where)
- Latest run metrics (pair counts, timing, cache hit rates — sourced from output artifacts)
- Active configuration snapshot (key thresholds, weights, enabled features — pulled from config files)
- Known issues or operational constraints
What's Next / Roadmap (if applicable):
- Planned improvements and known gaps
Technical Glossary:
- Dependency-ordered, not alphabetical
- Every term annotated inline at first use in the body
- Every entry bookmarked as a hyperlink target
- First body-text occurrence of each term hyperlinked to its glossary entry
- Key Concept sidebar boxes (2-3) for the most foundational concepts remain as pedagogical gateways; the hyperlinked glossary handles all other terms
Phase 3.5: Verification Against Runtime Data
Dispatch this entire phase to an isolated Explore subagent:
context: fork
agent: Explore
Before assembling the final document, verify every factual claim against the actual project state:
Config verification: Read config files (YAML, JSON, .env) and confirm that every threshold, weight, or setting mentioned in the document matches the current config values. Flag any discrepancies.
Production numbers verification: Cross-reference every number cited in the document (article counts, pair counts, timing, accuracy metrics) against actual pipeline output, logs, or metrics files. Every production number must be sourced from actual output, not estimated from code.
Feature state verification: For every feature described in the document, check the production config to determine whether it is enabled or disabled. Features that are disabled in config must not be described as part of the standard processing flow (see Writing Guidelines: "Available vs Active Features").
Staleness check: Run git log --since against the date the document was last generated (or the date of the output artifacts used for production numbers). Flag any changes that would invalidate document claims.
Flag for review: Present any stale, incorrect, or unverifiable claims to the user before proceeding to assembly. Do not silently correct — the user needs to see what changed.
Phase 4: Document Assembly
Write the complete content as a JSON file following the doc-builder schema, then invoke the CLI tool:
python -m doc_builder create \
--content "{content_json}" \
--output "{output_path}" \
[--generate-images] \
[--style-json "{style_json}"]
The CLI tool is at $DOC_BUILDER_PATH (or python -m doc_builder if on PYTHONPATH; author's default: ~/dev/tools/doc-builder) and handles:
- Word document creation with proper CFA styling
- Sidebar callout box formatting (red left border, light grey background)
- Glossary appendix formatting (dependency-ordered, bold red terms)
- Tables with navy headers and alternating row stripes
- Image placeholders (teal left border) or generated images (square text wrap)
- Developer section labeling (italic "Technical Reference" labels)
- Footnote creation
Document Freshness Metadata: Include a metadata block at the end of the document (or as a document property) with:
- Generated: date of document generation (ISO 8601)
- Git commit: the HEAD commit hash at generation time
- Pipeline run: version or run ID used for production numbers (if applicable)
This metadata supports the --update mode (enables diff detection) and tells readers how current the document is. Do not add a field asserting that claims were re-checked against runtime data at some point after generation — no mechanism ever performs that check, so the field would be a claim nobody backs.
Phase 5: Review
After generating the document:
- Report the document structure (section count, page estimate, glossary entries, images)
- Glossary hyperlink coverage check: Verify that every glossary term has at least one body-text hyperlink pointing to it. Report any gaps (terms defined in the glossary but never hyperlinked from the body text). These gaps mean the reader has no navigation path to that definition.
- Ask if the user wants to review before finalizing
- If
--generate-images was used, note which images were generated
Writing Guidelines
Voice and Tone
- Match the project's existing documentation tone if it has any
- Default to direct, conversational, confident — not academic or hedging
- Use "the system" not "our system" or "we"
Depth Calibration
- Right depth: The ME can follow WHY each technical choice was made and WHAT it accomplishes
- Too shallow: Useless ("vector search is a type of search")
- Too deep: CS-explaining-CS ("high-dimensional dense representations via transformer neural networks")
- The test: could the ME explain this system to a colleague after reading?
Accessibility Rules (baked in from the start)
- Every technical term gets an inline definition at first use AND a hyperlink to the glossary — the inline definition is the primary explanation, the glossary hyperlink is the navigation path for readers who need to revisit the definition later
- Replace developer jargon — code class names become plain language
- Remove mathematical formulas — replace with plain descriptions of what they accomplish
- Physical-world analogies — paint samples for embeddings, ingredient lists for TF-IDF, book indexes for inverted indexes, quality inspection for cross-encoders
- Consequence-based reasoning — "if you skip this, here's what breaks" earns trust with engineers
- Each document is self-contained — never assume the reader has read another document
Available vs Active Features
- Check the actual production config (YAML, JSON, .env) to determine which features are enabled vs disabled
- Describe the active production configuration as the primary path — this is what the system actually does today
- Document disabled-but-available features in a clearly labeled "Available Extensions" section, separate from the standard processing flow. Do not weave disabled features into stage descriptions as though they are part of normal operation.
- The test: if someone reads the stage walkthrough and cross-checks against the running config, do they match?
What NOT to include
- Code snippets (unless they're configuration examples essential for operators)
- API documentation (that belongs in separate docs)
- Installation/setup instructions (that's README territory)
- Changelog/version history
Lessons Learned
The "Why Not Just..." section is the single strongest trust-builder. Invest time here. Use data, not assertions.
Worked examples make or break the document. Choose examples that exercise the system's most interesting capabilities. Trace them ALL the way through — don't stop halfway.
Tables are the visual language of the target reader. Use 3-column comparison tables, scoring tables with concrete numbers, and threshold tables with rationale columns.
Sidebars determine first impressions. If the reader can't follow the executive summary because they don't know what an LLM or embedding is, they'll disengage. Gate with sidebars.
Developer sections need explicit labels. Port numbers, concurrency tuning, caching internals — label these "Technical Reference" so the target reader knows to skip.
Dashboard/UI descriptions need mockup images. Text descriptions of interactive tools are insufficient. Even a conceptual mockup helps more than no visual.
The glossary is the safety net, not the primary mechanism. Inline annotations at first use are the primary mechanism. The glossary catches terms the reader needs to revisit.
Production numbers earn credibility. "137,000 atoms" and "sub-second retrieval" are more convincing than "a lot of knowledge" and "fast responses."
Scope the document to the project's complexity. A 200-line bookmark validator doesn't need 25 pages. A 16-stage ML pipeline does. Let the project dictate depth.
Glossary terms must be navigable via hyperlinks. The glossary is only useful if readers can get to it from the body text. Every glossary term's first body-text occurrence should be an internal hyperlink to the glossary entry. This replaces the "see glossary" parenthetical pattern — hyperlinks are cleaner and less verbose. The doc-builder tool should generate bookmarks on glossary entries and hyperlinks on first occurrences automatically.
TOC is mandatory for documents over 5 pages. Every document with more than ~5 pages of content needs a Table of Contents. Include H2 and H3 scope (add H4 if the document uses it for meaningful content). The doc-builder should generate a TOC field automatically.
Never embed images inside heading paragraphs. When docx-js or the doc-builder places an anchored image, it must be in its own paragraph — not sharing a <w:p> with a heading. Images in heading paragraphs break outline view, corrupt TOC entries, and cause the heading text to render as part of the image float. Always create a separate body paragraph for the image, placed before or after the heading.
Each numbered list needs an independent numbering ID. In OOXML, paragraphs sharing the same numId are treated as a single continuous list. If the document has 3 separate numbered lists (e.g., classification steps, workflow steps, scoring criteria), each needs its own numId with a startOverride. Without this, the second list continues from the first (numbering as 5, 6, 7 instead of 1, 2, 3). The doc-builder should assign unique numbering references per list group.
Features described as active must be verified against config. Documents that describe disabled features as part of the standard processing flow mislead readers and erode trust when cross-checked against the running system. Always read the production config to determine what is actually enabled before writing stage descriptions.
Production numbers fabricated from code analysis are the #1 source of document inaccuracy. Code tells you what the system can do; output artifacts tell you what it did do. Always source counts, timing, accuracy metrics, and threshold values from actual pipeline output, logs, or config files — never estimate them by reading the code.
Error Handling
- No local path or GitHub URL provided: ask the user (see Inputs) rather than assuming a target.
- GitHub URL clone fails (private repo, network error, invalid URL): report the failure and ask the user to clone manually and provide a local path instead (see "Handling GitHub URLs" — only public repos are supported).
$DOC_STRUCTURE_TEMPLATE file is absent: proceed without it and note the omission in the output (see Phase 2) rather than blocking generation.
- Phase 3.5 verification finds stale, incorrect, or unverifiable claims against runtime data: flag them for user review before assembly — never silently correct or silently proceed (see Phase 3.5 step 5).
doc_builder CLI is missing or the assembly command fails: report the error with the exact command attempted; do not fall back to a plain-markdown substitute, since the accessibility formatting (sidebars, glossary hyperlinks) would be lost.
--generate-images is ON but Gemini generation fails for an image: fall back to a placeholder for that image (consistent with the default OFF behavior) and note it in the Phase 5 report.
1---2name: explain-project3description: Generate a comprehensive, annotated technical overview document for any project/repo, written for a smart non-CS reader. Analyzes the codebase, writes a deep-dive document following a proven structure template, and produces a styled Word document with sidebars, glossary, inline annotations, and optional generated images. Use when a project needs an explanatory document that makes the system understandable to non-technical stakeholders. Do NOT use for annotating an EXISTING document — use accessibility-annotator for that. Do NOT use for plain markdown-to-Word formatting with no annotations — use /convert-markdown for that.4---56<!-- ═══════════════════════════════════════════════════════════════════7 EXPLAIN PROJECT SKILL8 ═══════════════════════════════════════════════════════════════════910 PURPOSE:11 Generates a comprehensive technical overview document (.docx) for any12 software project, written for a brilliant non-CS reader. The document13 includes all accessibility annotations baked in from the start:14 sidebars, glossary, inline definitions, and optional images.1516 TARGET READER:17 A top-quintile intelligence mechanical engineer who has never taken18 a CS class. Sharp, process-oriented, comfortable with measurements19 and thresholds. Understands quality gates and structured problem-solving.2021 INPUT MODES:22 1. Local project directory path (e.g., "/path/to/my-project")23 2. Public GitHub URL (e.g., "https://github.com/owner/repo")24 - Clones to temp, generates doc to ~/Downloads, cleans up2526 OUTPUT:27 A styled Word document (.docx) following the CFA brand guidelines,28 with the document structure adapted to the project's complexity.2930 COMPANION TOOLS:31 Paths below are defaults on the author's machine. Override via flags or environment variables.32 - CLI tool: ~/dev/tools/doc-builder33 (python -m doc_builder create --content content.json --output doc.docx)34 - Structure template: ~/dev/info/technical-document-structure-template.md35 - Style guide: ~/.claude/styles/CFA_Word_Style_Guide.md36 - Image style: ~/dev/brand-assets/clients/cfa/styles/clean-style-sanitized.json37 - Image learnings: ~/dev/info/gemini-image-generation-learnings.md3839 HISTORY:40 Built and tested 2026-03-27. Tested on 4 projects:41 - cfa/pipeline (complex ML pipeline, 25 pages)42 - cfa/kb-analysis (complex analysis pipeline, 21 pages)43 - stratfield/community-mgt (Next.js enterprise app)44 - personal/open-brain (multi-container AI knowledge system)45 ═══════════════════════════════════════════════════════════════════ -->4647# Explain Project4849Generate a comprehensive technical overview document for a project, written for a brilliant reader who lacks computer science training.5051**Target reader:** A top-quintile intelligence mechanical engineer. Sharp, process-oriented, comfortable with measurements and thresholds, experienced with quality systems and structured problem-solving. Has never taken a CS class.5253**Output:** A styled Word document (.docx) with all accessibility annotations baked in — sidebars, glossary, inline definitions, footnotes, developer section labels, and optionally generated images.5455## Inputs5657<!-- ─── INPUT PARSING ───58 Accept either a local filesystem path or a GitHub URL.59 GitHub URLs are shallow-cloned to /tmp, analyzed, then cleaned up.60 Output for GitHub repos goes to ~/Downloads by default.61─── -->6263One required argument (either a local path OR a GitHub URL):641. **Project directory path** -- a local directory containing the codebase to document652. **OR GitHub URL** -- a public repo URL (e.g., `https://github.com/owner/repo`). The skill will clone it to a temp directory, analyze it, and output the document to the user's Downloads folder.6667Optional flags:68- `--style PATH` -- Path to a markdown style guide for Word formatting (default: `$DOC_STYLE_GUIDE` env var if set; author's default: `~/.claude/styles/CFA_Word_Style_Guide.md`)69- `--style-json PATH` -- Path to image style JSON for Nano Banana Pro (default: `$IMAGE_STYLE_JSON` env var if set; author's default: `~/dev/brand-assets/clients/cfa/styles/clean-style-sanitized.json`)70- `--generate-images` -- Generate diagrams via Google Gemini and insert them (default: OFF — costs money)71- `--update` -- Incremental update mode: reads the existing document, diffs the codebase against the last generation (via git log since the commit hash in the document's freshness metadata), generates only changed sections, and preserves the user's manual refinements to unchanged sections72- `--output PATH` -- Output file path (default: `{project-dir}/docs/{project-name}-overview.docx`, or `~/Downloads/{repo-name}-overview.docx` for GitHub URLs)7374Parse from the user's message. If neither a path nor URL is provided, ask.7576### Detecting Previous Documents7778Before starting a fresh generation, check for existing documents matching `docs/*-overview*.docx` in the project directory. If found:791. Read the existing document to understand what it covers802. Check git log for changes since the document was last generated (use the freshness metadata commit hash if available, otherwise file modification date)813. Offer the user a choice: **update** (incremental, preserves manual edits) vs **regenerate** (full fresh generation)8283In `--update` mode:84- Parse the existing document's section structure85- Diff the codebase to identify what changed (new files, modified stages, config changes)86- Generate only the sections affected by codebase changes87- Preserve the user's manual refinements to unchanged sections88- Update the Document Freshness metadata block with current values8990### Handling GitHub URLs9192<!-- ─── GITHUB FLOW ───93 Shallow clone keeps it fast. Only public repos — no auth complexity.94 isolation: worktree provides automatic cleanup — no manual rm needed.95 explain-project is read-only, so worktree cleanup is always safe.96─── -->9798When the input is a GitHub URL (contains `github.com`):991001. **Clone the repo** using worktree isolation:101 ```yaml102 isolation: worktree103 ```104 Use `git clone --depth 1 "{url}" .` inside the worktree. Worktree auto-cleanup replaces manual `/tmp` directory management — no explicit cleanup step needed.1051062. **Set output path** to Downloads:107 ```108 ~/Downloads/{repo-name}-overview.docx109 ```1101113. **Analyze and generate** using the same Phase 1-5 process as for local projects.112113Note: Only public repos are supported (no authentication). For private repos, clone manually first and provide the local path. Worktree cleanup is automatic because this skill is read-only and makes no commits.114115## Process116117<!-- ═══════════════════════════════════════════════════════════════════118 PHASE 1: DEEP PROJECT ANALYSIS119120 This is where we build the understanding that drives the document.121 Read broadly first, then deeply into the components that matter most.122 Use the Explore agent for broad sweeps, direct reads for specifics.123 ═══════════════════════════════════════════════════════════════════ -->124125### Phase 1: Deep Project Analysis126127<!-- ─── DISPATCH TO EXPLORE AGENT ───128 Phase 1 is pure read-only analysis — no writes, no side effects.129 Dispatch to an isolated Explore subagent for broad parallel reading.130 Dynamic context injection pre-loads git stats before the subagent sees the prompt.131─── -->132133**Dispatch this entire phase to an isolated Explore subagent:**134```yaml135context: fork136agent: Explore137```138139Inject project git context before analysis:140- Recent commits: `!`git log --oneline -20``141- Top contributors: `!`git shortlog -sn --no-merges | head -10``142143The Explore subagent builds comprehensive understanding:1441451. **Project identity:** Read README, CLAUDE.md, package.json/pyproject.toml, and top-level docs1462. **Architecture:** Map the directory structure, identify major components, entry points, and data flow1473. **Pipeline/stages:** Identify processing stages, their order, inputs/outputs, and dependencies1484. **Data models:** Read model definitions, schemas, configuration files1495. **Products/outputs:** What does the system produce? What consumes the output?1506. **Testing:** Test suite structure, coverage, evaluation approach1517. **Infrastructure:** What hardware/services does it depend on? How does it deploy?1528. **Technical vocabulary:** Catalog every CS/ML/domain term the project uses1539. **Runtime artifacts:** If the project produces output artifacts (reports, logs, dashboards, metrics files), read them. Look for:154 - Latest pipeline output in `output/` or similar directories (statistics, counts, timing)155 - Log files with timing data, cache hit rates, throughput numbers156 - Metrics or evaluation result files from recent runs157 - Configuration files with active thresholds, weights, and feature flags158159 Ground the document in production reality, not code-reading estimates. Every production number cited in the document should trace back to an actual output artifact, not a guess derived from reading the code.160161Return all findings to the parent skill for Phase 2 document planning.162163<!-- ═══════════════════════════════════════════════════════════════════164 PHASE 2: DOCUMENT PLANNING165166 IMPORTANT: Read the structure template BEFORE planning.167 Not every project needs every section. A 200-line CLI tool gets 5 pages.168 A 16-stage ML pipeline gets 25. Let the project dictate depth.169170 Present the plan to the user before writing — this is a checkpoint.171 ═══════════════════════════════════════════════════════════════════ -->172173### Phase 2: Document Planning174175**IMPORTANT:** Read the structure template at `$DOC_STRUCTURE_TEMPLATE` (author's default: `~/dev/info/technical-document-structure-template.md`) before planning. If this file is absent, proceed without the structure template and note that in the output. It contains a complexity table that maps project size to expected document depth. Not every section applies to every project.1761771. **Select Key Concept Sidebars (2-3):** Choose the foundational concepts THIS project relies on most. These will be the first things the reader sees.1781792. **Plan the "Why This Approach" section (if warranted):** Identify 2-4 reasonable objections a skeptic would raise. What simpler approaches would people suggest? Why do they fail? Skip for simple projects where the approach is obvious. Where available, include:180 - Actual benchmark data from evaluation runs (precision, recall, F1 from test sets)181 - Specific evaluation results that justify design decisions182 - A cost/benefit table for the overall system vs. simpler alternatives (time to build, accuracy gained, maintenance burden)1831843. **Design the worked example:** Choose a concrete, realistic input that will be traced through every stage. It should exercise the system's most important capabilities.1851864. **Map the stage/component walkthrough:** List every processing stage or major component with:187 - What it transforms (input → output)188 - Why it matters (consequence of skipping)189 - How the worked example changes at this stage1901915. **Plan images (3-5):** Identify where diagrams would most help.192193 **Always generate:**194 - Data flow diagram — stages with their inputs and outputs, showing the transformation pipeline end to end195 - System architecture — infrastructure topology showing hardware, services, and their connections196197 **Generate if applicable:**198 - Worked example transformation — showing how the running example changes at key stages199 - Dashboard/UI mockup — conceptual layout of any interactive output the system produces200 - Conceptual visualization of the novel/hardest technique201202 **Never generate:**203 - Screenshots of code (not useful for the target reader)204 - Class diagrams or UML (too developer-focused for the ME audience)2052066. **Build the glossary list:** Every CS/ML term that will appear in the document, with draft definitions at the right depth. Plan bookmark names for each entry (convention: `_glossary_` + lowercase_underscored_name). The glossary will be the hyperlink target for first-occurrence terms in the body text.207208Present this plan to the user before writing. Format as a brief outline showing:209- Proposed sidebar topics210- "Why not just..." questions (if any)211- Worked example selection212- Stage/component list with one-line descriptions213- Image locations214- Glossary term count215216<!-- ═══════════════════════════════════════════════════════════════════217 PHASE 3: DOCUMENT GENERATION218219 Write section by section, following the proven patterns below.220 The key structural patterns that work for the ME audience:221222 - "What happens / Why it matters / Our example becomes" for stages223 - 3-column comparison tables for "Why This Approach"224 - Concrete numbers and examples over abstract descriptions225 - Consequence-based reasoning ("if you skip this, X breaks")226227 All technical terms must be explained INLINE at first use, not just228 in the glossary. The glossary is the safety net, not the primary tool.229 ═══════════════════════════════════════════════════════════════════ -->230231### Phase 3: Document Generation232233Write each section following the proven patterns:234235**Executive Summary:**236- Key Concept Sidebars (2-3) at the top — these are pedagogical gateways for the most foundational concepts only; all other terms use the glossary hyperlink mechanism237- What goes in → what comes out (one sentence)238- Problem context (why the status quo fails)239- What the system does (high-level, naming major phases)240- Production numbers table (if available)241- Validation summary242243**Why This Approach (if warranted):**244- 2-4 subsections, each a skeptic's question245- 3-column comparison tables where applicable246- Concrete data and failure modes, not abstract arguments247- Include actual benchmark data when available (e.g., evaluation precision/recall)248- Include a cost/benefit summary table for the overall system vs. alternatives249250**Worked Example:**251- Show the actual input (raw data, article text, etc.)252- Explain why this example demonstrates the system's capabilities253- **Prefer real examples from production output** when available — they are automatically accurate and carry more weight with the reader254- If a fabricated example is necessary, state explicitly: "This is a representative example constructed to illustrate the process" — never present fabricated data as production output255256**Stage-by-Stage / Component Walkthrough:**257For each stage or component, follow this template:258```text259**What happens:** [concrete transformation]260**Why it matters:** [consequence of skipping]261**Our example becomes:** [running example after this stage]262**Technical details:** [developer-oriented, preceded by "Technical Reference" label]263```264265**Products/Applications** (if applicable):266- What uses the pipeline output267- How end users interact with it268269**Second Worked Example** (if the system has a distinct "use" phase):270- Trace a realistic query/request through the system271- Show intermediate results at each step272273**Quality and Validation:**274- Testing summary table275- Evaluation approach276- Quality metrics and regression gates277278**Technical Architecture:**279- Preceded by "Technical Reference" label280- Infrastructure, models, caching, concurrency281282**How to Evaluate This System** (if appropriate):283- Decision-maker-oriented questions with pointers to answers284285**Known Limitations and Coverage Gaps:**286This is a standard section for every document — the ME reader treats this as the specification sheet. Every product has specs AND limitations. Include:287- What the system does not cover (explicit scope boundaries)288- What data it excludes and why289- Edge cases it handles poorly or not at all290- Known accuracy limitations (false positive rates, failure modes)291- Scale or performance boundaries292293**Current Operational State / Config Snapshot** (if the project has a production deployment):294Auto-populate from actual config files and latest run output:295- Current deployment topology (what runs where)296- Latest run metrics (pair counts, timing, cache hit rates — sourced from output artifacts)297- Active configuration snapshot (key thresholds, weights, enabled features — pulled from config files)298- Known issues or operational constraints299300**What's Next / Roadmap** (if applicable):301- Planned improvements and known gaps302303**Technical Glossary:**304- Dependency-ordered, not alphabetical305- Every term annotated inline at first use in the body306- Every entry bookmarked as a hyperlink target307- First body-text occurrence of each term hyperlinked to its glossary entry308- Key Concept sidebar boxes (2-3) for the most foundational concepts remain as pedagogical gateways; the hyperlinked glossary handles all other terms309310<!-- ═══════════════════════════════════════════════════════════════════311 PHASE 3.5: VERIFICATION AGAINST RUNTIME DATA312313 Every claim in the document must be verifiable. This phase catches314 stale thresholds, outdated counts, and features described as active315 that are actually disabled. Run this BEFORE assembling the final316 document — it's cheaper to fix claims in draft than in formatted output.317 ═══════════════════════════════════════════════════════════════════ -->318319### Phase 3.5: Verification Against Runtime Data320321<!-- ─── DISPATCH TO EXPLORE AGENT ───322 Phase 3.5 is read-only verification — checking claims against actual files/config.323 Dispatch to an isolated Explore subagent: no writes, no side effects.324─── -->325326**Dispatch this entire phase to an isolated Explore subagent:**327```yaml328context: fork329agent: Explore330```331332Before assembling the final document, verify every factual claim against the actual project state:3333341. **Config verification:** Read config files (YAML, JSON, .env) and confirm that every threshold, weight, or setting mentioned in the document matches the current config values. Flag any discrepancies.3353362. **Production numbers verification:** Cross-reference every number cited in the document (article counts, pair counts, timing, accuracy metrics) against actual pipeline output, logs, or metrics files. Every production number must be sourced from actual output, not estimated from code.3373383. **Feature state verification:** For every feature described in the document, check the production config to determine whether it is enabled or disabled. Features that are disabled in config must not be described as part of the standard processing flow (see Writing Guidelines: "Available vs Active Features").3393404. **Staleness check:** Run `git log --since` against the date the document was last generated (or the date of the output artifacts used for production numbers). Flag any changes that would invalidate document claims.3413425. **Flag for review:** Present any stale, incorrect, or unverifiable claims to the user before proceeding to assembly. Do not silently correct — the user needs to see what changed.343344<!-- ═══════════════════════════════════════════════════════════════════345 PHASE 4: DOCUMENT ASSEMBLY346347 The doc-builder CLI tool at dev/tools/doc-builder handles the348 mechanical Word document creation. Write content as structured JSON,349 then invoke the CLI.350351 JSON SCHEMA — the content JSON must follow this structure:352 {353 "title": "System Name — Overview",354 "sidebars": [{"title": "...", "body": "..."}],355 "sections": [{"heading": "...", "level": 2, "content": [...]}],356 "glossary": [{"term": "...", "definition": "..."}],357 "footnotes": [{"id": 1, "text": "..."}],358 "images": [{"name": "...", "prompt": "..."}]359 }360361 Content element types: paragraph, heading, table, list, blockquote,362 sidebar, tech_ref_label, image_placeholder, glossary_entry, rich_paragraph363 ═══════════════════════════════════════════════════════════════════ -->364365### Phase 4: Document Assembly366367Write the complete content as a JSON file following the doc-builder schema, then invoke the CLI tool:368369```bash370python -m doc_builder create \371 --content "{content_json}" \372 --output "{output_path}" \373 [--generate-images] \374 [--style-json "{style_json}"]375```376377The CLI tool is at `$DOC_BUILDER_PATH` (or `python -m doc_builder` if on PYTHONPATH; author's default: `~/dev/tools/doc-builder`) and handles:378- Word document creation with proper CFA styling379- Sidebar callout box formatting (red left border, light grey background)380- Glossary appendix formatting (dependency-ordered, bold red terms)381- Tables with navy headers and alternating row stripes382- Image placeholders (teal left border) or generated images (square text wrap)383- Developer section labeling (italic "Technical Reference" labels)384- Footnote creation385386**Document Freshness Metadata:** Include a metadata block at the end of the document (or as a document property) with:387- **Generated:** date of document generation (ISO 8601)388- **Git commit:** the HEAD commit hash at generation time389- **Pipeline run:** version or run ID used for production numbers (if applicable)390391This metadata supports the `--update` mode (enables diff detection) and tells readers how current the document is. Do not add a field asserting that claims were re-checked against runtime data at some point after generation — no mechanism ever performs that check, so the field would be a claim nobody backs.392393### Phase 5: Review394395After generating the document:3961. Report the document structure (section count, page estimate, glossary entries, images)3972. **Glossary hyperlink coverage check:** Verify that every glossary term has at least one body-text hyperlink pointing to it. Report any gaps (terms defined in the glossary but never hyperlinked from the body text). These gaps mean the reader has no navigation path to that definition.3983. Ask if the user wants to review before finalizing3994. If `--generate-images` was used, note which images were generated400401<!-- ═══════════════════════════════════════════════════════════════════402 WRITING GUIDELINES403404 These are the rules that make the document work for the target reader.405 Every decision here was validated by having a review agent read the406 output from the ME persona's perspective.407 ═══════════════════════════════════════════════════════════════════ -->408409## Writing Guidelines410411### Voice and Tone412- Match the project's existing documentation tone if it has any413- Default to direct, conversational, confident — not academic or hedging414- Use "the system" not "our system" or "we"415416### Depth Calibration417<!-- The "paint sample" test: could the ME follow the argument after reading your explanation? -->418- **Right depth:** The ME can follow WHY each technical choice was made and WHAT it accomplishes419- **Too shallow:** Useless ("vector search is a type of search")420- **Too deep:** CS-explaining-CS ("high-dimensional dense representations via transformer neural networks")421- The test: could the ME explain this system to a colleague after reading?422423### Accessibility Rules (baked in from the start)424<!-- These are non-negotiable. Every one was learned from review feedback. -->4251. **Every technical term gets an inline definition at first use AND a hyperlink to the glossary** — the inline definition is the primary explanation, the glossary hyperlink is the navigation path for readers who need to revisit the definition later4262. **Replace developer jargon** — code class names become plain language4273. **Remove mathematical formulas** — replace with plain descriptions of what they accomplish4284. **Physical-world analogies** — paint samples for embeddings, ingredient lists for TF-IDF, book indexes for inverted indexes, quality inspection for cross-encoders4295. **Consequence-based reasoning** — "if you skip this, here's what breaks" earns trust with engineers4306. **Each document is self-contained** — never assume the reader has read another document431432### Available vs Active Features433<!-- Features described as active must match production config. Misleading feature descriptions erode trust. -->434- **Check the actual production config** (YAML, JSON, .env) to determine which features are enabled vs disabled435- **Describe the active production configuration as the primary path** — this is what the system actually does today436- **Document disabled-but-available features in a clearly labeled "Available Extensions" section**, separate from the standard processing flow. Do not weave disabled features into stage descriptions as though they are part of normal operation.437- The test: if someone reads the stage walkthrough and cross-checks against the running config, do they match?438439### What NOT to include440- Code snippets (unless they're configuration examples essential for operators)441- API documentation (that belongs in separate docs)442- Installation/setup instructions (that's README territory)443- Changelog/version history444445<!-- ═══════════════════════════════════════════════════════════════════446 LESSONS LEARNED447448 These patterns emerged from testing on 4 real projects and a thorough449 review by an agent reading from the ME persona. Each lesson represents450 a mistake we made and corrected. They prevent repeat errors.451 ═══════════════════════════════════════════════════════════════════ -->452453## Lessons Learned4544551. **The "Why Not Just..." section is the single strongest trust-builder.** Invest time here. Use data, not assertions.4564572. **Worked examples make or break the document.** Choose examples that exercise the system's most interesting capabilities. Trace them ALL the way through — don't stop halfway.4584593. **Tables are the visual language of the target reader.** Use 3-column comparison tables, scoring tables with concrete numbers, and threshold tables with rationale columns.4604614. **Sidebars determine first impressions.** If the reader can't follow the executive summary because they don't know what an LLM or embedding is, they'll disengage. Gate with sidebars.4624635. **Developer sections need explicit labels.** Port numbers, concurrency tuning, caching internals — label these "Technical Reference" so the target reader knows to skip.4644656. **Dashboard/UI descriptions need mockup images.** Text descriptions of interactive tools are insufficient. Even a conceptual mockup helps more than no visual.4664677. **The glossary is the safety net, not the primary mechanism.** Inline annotations at first use are the primary mechanism. The glossary catches terms the reader needs to revisit.4684698. **Production numbers earn credibility.** "137,000 atoms" and "sub-second retrieval" are more convincing than "a lot of knowledge" and "fast responses."4704719. **Scope the document to the project's complexity.** A 200-line bookmark validator doesn't need 25 pages. A 16-stage ML pipeline does. Let the project dictate depth.47247310. **Glossary terms must be navigable via hyperlinks.** The glossary is only useful if readers can get to it from the body text. Every glossary term's first body-text occurrence should be an internal hyperlink to the glossary entry. This replaces the "see glossary" parenthetical pattern — hyperlinks are cleaner and less verbose. The doc-builder tool should generate bookmarks on glossary entries and hyperlinks on first occurrences automatically.47447511. **TOC is mandatory for documents over 5 pages.** Every document with more than ~5 pages of content needs a Table of Contents. Include H2 and H3 scope (add H4 if the document uses it for meaningful content). The doc-builder should generate a TOC field automatically.47647712. **Never embed images inside heading paragraphs.** When docx-js or the doc-builder places an anchored image, it must be in its own paragraph — not sharing a `<w:p>` with a heading. Images in heading paragraphs break outline view, corrupt TOC entries, and cause the heading text to render as part of the image float. Always create a separate body paragraph for the image, placed before or after the heading.47847913. **Each numbered list needs an independent numbering ID.** In OOXML, paragraphs sharing the same numId are treated as a single continuous list. If the document has 3 separate numbered lists (e.g., classification steps, workflow steps, scoring criteria), each needs its own numId with a startOverride. Without this, the second list continues from the first (numbering as 5, 6, 7 instead of 1, 2, 3). The doc-builder should assign unique numbering references per list group.48048114. **Features described as active must be verified against config.** Documents that describe disabled features as part of the standard processing flow mislead readers and erode trust when cross-checked against the running system. Always read the production config to determine what is actually enabled before writing stage descriptions.48248315. **Production numbers fabricated from code analysis are the #1 source of document inaccuracy.** Code tells you what the system *can* do; output artifacts tell you what it *did* do. Always source counts, timing, accuracy metrics, and threshold values from actual pipeline output, logs, or config files — never estimate them by reading the code.484485## Error Handling486487- **No local path or GitHub URL provided:** ask the user (see Inputs) rather than assuming a target.488- **GitHub URL clone fails** (private repo, network error, invalid URL): report the failure and ask the user to clone manually and provide a local path instead (see "Handling GitHub URLs" — only public repos are supported).489- **`$DOC_STRUCTURE_TEMPLATE` file is absent:** proceed without it and note the omission in the output (see Phase 2) rather than blocking generation.490- **Phase 3.5 verification finds stale, incorrect, or unverifiable claims** against runtime data: flag them for user review before assembly — never silently correct or silently proceed (see Phase 3.5 step 5).491- **`doc_builder` CLI is missing or the assembly command fails:** report the error with the exact command attempted; do not fall back to a plain-markdown substitute, since the accessibility formatting (sidebars, glossary hyperlinks) would be lost.492- **`--generate-images` is ON but Gemini generation fails for an image:** fall back to a placeholder for that image (consistent with the default OFF behavior) and note it in the Phase 5 report.