specdacular 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +3 -3
  2. package/bin/install.js +3 -1
  3. package/bin/specd.js +135 -0
  4. package/commands/specd.best-practices.md +75 -0
  5. package/commands/specd.docs.md +81 -0
  6. package/commands/specd.docs.review.md +80 -0
  7. package/commands/specd.generate-skills.learn.md +65 -0
  8. package/commands/specd.new-runner-task.md +52 -0
  9. package/commands/specd.new.md +6 -6
  10. package/commands/specd.runner-status.md +27 -0
  11. package/package.json +6 -2
  12. package/runner/main/agent/parser.js +39 -0
  13. package/runner/main/agent/runner.js +137 -0
  14. package/runner/main/agent/template.js +16 -0
  15. package/runner/main/bootstrap.js +69 -0
  16. package/runner/main/db.js +45 -0
  17. package/runner/main/index.js +103 -0
  18. package/runner/main/ipc.js +72 -0
  19. package/runner/main/notifications/telegram.js +45 -0
  20. package/runner/main/orchestrator.js +193 -0
  21. package/runner/main/paths.js +36 -0
  22. package/runner/main/pipeline/resolver.js +20 -0
  23. package/runner/main/pipeline/sequencer.js +42 -0
  24. package/runner/main/server/api.js +125 -0
  25. package/runner/main/server/index.js +33 -0
  26. package/runner/main/server/websocket.js +24 -0
  27. package/runner/main/state/manager.js +83 -0
  28. package/runner/main/template-manager.js +41 -0
  29. package/runner/main/test/agent-parser.test.js +44 -0
  30. package/runner/main/test/bootstrap.test.js +58 -0
  31. package/runner/main/test/db.test.js +72 -0
  32. package/runner/main/test/paths.test.js +29 -0
  33. package/runner/main/test/state-manager.test.js +72 -0
  34. package/runner/main/test/template-manager.test.js +66 -0
  35. package/runner/main/worktree/manager.js +95 -0
  36. package/runner/package.json +22 -0
  37. package/runner/preload.js +19 -0
  38. package/specdacular/HELP.md +14 -11
  39. package/specdacular/agents/best-practices-researcher.md +271 -0
  40. package/specdacular/references/load-context.md +4 -7
  41. package/specdacular/templates/orchestrator/CONCERNS.md +1 -1
  42. package/specdacular/templates/orchestrator/PROJECTS.md +3 -4
  43. package/specdacular/templates/tasks/PLAN.md +2 -2
  44. package/specdacular/workflows/best-practices.md +472 -0
  45. package/specdacular/workflows/context-add.md +16 -30
  46. package/specdacular/workflows/context-manual-review.md +7 -7
  47. package/specdacular/workflows/docs-review.md +273 -0
  48. package/specdacular/workflows/docs.md +420 -0
  49. package/specdacular/workflows/generate-learn-skill.md +214 -0
  50. package/specdacular/workflows/new.md +5 -4
  51. package/specdacular/workflows/orchestrator/new.md +4 -4
  52. package/specdacular/workflows/orchestrator/plan.md +6 -6
  53. package/commands/specd.codebase.map.md +0 -72
  54. package/commands/specd.codebase.review.md +0 -39
  55. package/specdacular/workflows/map-codebase.md +0 -715
@@ -0,0 +1,273 @@
1
+ <purpose>
2
+ Audit existing topic docs for accuracy, staleness, and coverage gaps. Optionally research best practices for the detected stack. Update frontmatter review dates after user approval.
3
+
4
+ **Output:** Review findings, updated docs and review dates, CLAUDE.md routing table changes if docs added/removed.
5
+ </purpose>
6
+
7
+ <philosophy>
8
+
9
+ ## Trust But Verify
10
+
11
+ Docs were generated from real code, but code changes. The review checks whether docs still reflect reality.
12
+
13
+ ## Freshness Is Not Accuracy
14
+
15
+ A doc can be stale (old review date) but still accurate, or fresh but drifted (code changed right after review). Check both dimensions.
16
+
17
+ ## Research Is Additive
18
+
19
+ Research agents suggest improvements based on current best practices. They don't override what the codebase actually does — they propose what it could do better.
20
+
21
+ ## User Decides
22
+
23
+ Present findings. Let the user choose what to update. Don't auto-fix.
24
+
25
+ </philosophy>
26
+
27
+ <process>
28
+
29
+ <step name="discover_docs">
30
+ Find all specd-generated docs and parse their frontmatter.
31
+
32
+ **Read CLAUDE.md routing table:**
33
+ ```bash
34
+ [ -f "CLAUDE.md" ] && cat CLAUDE.md || echo "no_claude_md"
35
+ ```
36
+
37
+ Extract `$DOCS_DIR` from routing table paths. Default to `docs/` if not found.
38
+
39
+ **Find specd-generated docs:**
40
+ ```bash
41
+ grep -rl "generated_by: specd" $DOCS_DIR/ 2>/dev/null
42
+ ```
43
+
44
+ **For each doc found, parse frontmatter:**
45
+ Read the file, extract:
46
+ - `last_reviewed` date
47
+ - `generated_by` field
48
+ - Doc topic/name from filename
49
+
50
+ If no specd-generated docs found:
51
+ ```
52
+ No specd-generated docs found. Run /specd.docs first to generate topic docs.
53
+ ```
54
+ End workflow.
55
+
56
+ Build `$DOC_LIST` — array of docs with their metadata.
57
+
58
+ Continue to assess_freshness.
59
+ </step>
60
+
61
+ <step name="assess_freshness">
62
+ Check how fresh each doc is based on review dates and git history.
63
+
64
+ **For each doc in `$DOC_LIST`:**
65
+
66
+ 1. Calculate days since `last_reviewed`:
67
+ ```bash
68
+ # Days between last_reviewed and today
69
+ echo $(( ($(date +%s) - $(date -d "{last_reviewed}" +%s)) / 86400 ))
70
+ ```
71
+
72
+ 2. Check if significant code changed since last review:
73
+ ```bash
74
+ git log --since="{last_reviewed}" --name-only --pretty=format: -- "src/" "lib/" "app/" | sort -u | head -20
75
+ ```
76
+
77
+ 3. Classify freshness:
78
+ - **Fresh** — reviewed within 30 days, no significant code changes
79
+ - **Aging** — reviewed 30-90 days ago
80
+ - **Stale** — reviewed 90+ days ago
81
+ - **Code changed** — significant changes to source files since last review (regardless of age)
82
+
83
+ Continue to check_accuracy.
84
+ </step>
85
+
86
+ <step name="check_accuracy">
87
+ Spot-check doc content against current code.
88
+
89
+ **For each doc in `$DOC_LIST`:**
90
+
91
+ 1. **File path check:** Extract all file paths mentioned in the doc. Verify each exists:
92
+ ```bash
93
+ # For each path referenced in the doc
94
+ [ -f "{path}" ] && echo "exists" || echo "missing: {path}"
95
+ ```
96
+
97
+ 2. **Pattern check:** For docs that describe code patterns (with code examples), spot-check a few:
98
+ - Read the referenced source file
99
+ - Check if the pattern described still matches the actual code
100
+ - Note any significant differences
101
+
102
+ 3. **Rules check (for rules.md):** Verify each rule still applies:
103
+ - Import conventions — check a few imports in source files
104
+ - Naming conventions — check recent files follow the pattern
105
+ - File placement — check if new files follow the described structure
106
+
107
+ 4. **Classify accuracy:**
108
+ - **Accurate** — spot-checks pass, content matches code
109
+ - **Minor drift** — small inaccuracies (renamed function, moved file)
110
+ - **Major drift** — significant patterns changed, doc is misleading
111
+ - **Obsolete** — technology/pattern no longer exists in codebase
112
+
113
+ Continue to detect_gaps.
114
+ </step>
115
+
116
+ <step name="detect_gaps">
117
+ Find technologies and patterns in the code not covered by existing docs.
118
+
119
+ **Scan codebase for technology markers:**
120
+ ```bash
121
+ # Check package.json / go.mod / Cargo.toml for dependencies
122
+ cat package.json 2>/dev/null | grep -E '"dependencies"|"devDependencies"' -A 50
123
+ cat go.mod 2>/dev/null
124
+ cat Cargo.toml 2>/dev/null
125
+
126
+ # Check for common patterns in source files
127
+ grep -rl "import.*from" src/ 2>/dev/null | head -10
128
+ ```
129
+
130
+ **Compare against existing doc topics:**
131
+ - List technologies/frameworks used in the code
132
+ - List topics covered by existing docs
133
+ - Identify gaps: technologies in code but not documented
134
+ - Identify obsolete: topics in docs but technology no longer in code
135
+
136
+ **Propose new docs** for significant gaps (technology used in 3+ files).
137
+ **Propose removal** for obsolete topics.
138
+
139
+ Continue to research_improvements.
140
+ </step>
141
+
142
+ <step name="research_improvements">
143
+ Optionally research best practices for the detected stack.
144
+
145
+ Use AskUserQuestion:
146
+ - header: "Research?"
147
+ - question: "Want me to research current best practices for your stack to suggest improvements?"
148
+ - options:
149
+ - "Yes — research improvements" — Spawn research agents for detected technologies
150
+ - "No — just review accuracy" — Skip research, go to findings
151
+
152
+ **If user says yes:**
153
+
154
+ For each major technology detected in the codebase, spawn a research agent:
155
+
156
+ Use Agent tool:
157
+ - description: "Research {technology} best practices"
158
+ - prompt: "Research current best practices for {technology} in {year}. Focus on:
159
+ - Common patterns and anti-patterns
160
+ - Performance recommendations
161
+ - Security considerations
162
+ - Migration guidance for newer versions
163
+ Return a concise list of actionable suggestions."
164
+
165
+ Collect research results. For each suggestion, note:
166
+ - What the codebase currently does
167
+ - What best practice recommends
168
+ - Impact level (low/medium/high)
169
+
170
+ Continue to present_findings.
171
+ </step>
172
+
173
+ <step name="present_findings">
174
+ Show review results to user.
175
+
176
+ ```
177
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
178
+ DOCS REVIEW
179
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
180
+
181
+ {count} docs reviewed
182
+
183
+ {For each doc:}
184
+ {✅|⚠️|❌|🔍} {doc name} — {Accurate|Minor drift|Major drift|Stale|Obsolete}
185
+ Last reviewed: {date} ({N} days ago)
186
+ {If drifted: "Drift: {specific inaccuracy}"}
187
+ {If code changed: "Code changed: {N} files modified since review"}
188
+ ```
189
+
190
+ **If gaps found:**
191
+ ```
192
+ Coverage gaps:
193
+ - {technology/pattern} — Used in {N} files, not documented
194
+ Proposed: docs/{topic}.md
195
+ ```
196
+
197
+ **If obsolete docs found:**
198
+ ```
199
+ Possibly obsolete:
200
+ - {doc name} — {technology} no longer found in codebase
201
+ ```
202
+
203
+ **If research done:**
204
+ ```
205
+ Improvement suggestions:
206
+ {For each suggestion:}
207
+ - [{impact}] {suggestion}
208
+ Current: {what code does}
209
+ Recommended: {what best practice says}
210
+ ```
211
+
212
+ Continue to apply_updates.
213
+ </step>
214
+
215
+ <step name="apply_updates">
216
+ Let user choose what actions to take.
217
+
218
+ Use AskUserQuestion:
219
+ - header: "Actions"
220
+ - question: "What would you like to do with these findings?"
221
+ - multiSelect: true
222
+ - options:
223
+ - "Update drifted docs" — Fix inaccuracies in docs that have drifted
224
+ - "Generate new docs for gaps" — Create docs for uncovered topics
225
+ - "Remove obsolete docs" — Delete docs for removed technologies
226
+ - "Mark accurate docs as reviewed" — Update last_reviewed to today
227
+
228
+ **For "Update drifted docs":**
229
+ For each drifted doc, read the current code and update the doc content to match reality. Update frontmatter `last_reviewed` to today.
230
+
231
+ **For "Generate new docs for gaps":**
232
+ For significant gaps, generate new topic docs. This may require re-running mapper agents for fresh codebase data, or the review workflow can generate targeted docs from its own analysis. Add new docs to CLAUDE.md routing table (between section markers).
233
+
234
+ **For "Remove obsolete docs":**
235
+ Delete obsolete doc files. Remove their entries from CLAUDE.md routing table.
236
+
237
+ **For "Mark accurate docs as reviewed":**
238
+ For each doc classified as accurate, update `last_reviewed` in frontmatter to today's date.
239
+
240
+ **Update CLAUDE.md routing table** if docs were added or removed:
241
+ - Add new entries for generated docs
242
+ - Remove entries for deleted docs
243
+ - Keep within `<!-- specd:docs-routing:start -->` / `<!-- specd:docs-routing:end -->` markers
244
+
245
+ **Do not auto-commit.** User manages commits.
246
+
247
+ **Present completion:**
248
+ ```
249
+ Review complete.
250
+
251
+ Updated: {count} docs
252
+ Generated: {count} new docs
253
+ Removed: {count} obsolete docs
254
+ Reviewed: {count} docs marked as fresh
255
+ ```
256
+
257
+ End workflow.
258
+ </step>
259
+
260
+ </process>
261
+
262
+ <success_criteria>
263
+ - All specd-generated docs found via frontmatter scan
264
+ - Freshness assessed using last_reviewed dates + git history
265
+ - Accuracy spot-checked against current code (file paths, patterns, rules)
266
+ - Coverage gaps detected by comparing codebase vs. doc topics
267
+ - Research is optional — user chooses
268
+ - Findings presented with clear per-doc status
269
+ - User selects which actions to take (multiSelect)
270
+ - Frontmatter last_reviewed updated on approved docs
271
+ - CLAUDE.md routing table updated if docs added/removed
272
+ - No auto-commit — user manages commits
273
+ </success_criteria>
@@ -0,0 +1,420 @@
1
+ <purpose>
2
+ Orchestrate codebase analysis and generate topic-based documentation in docs/ with a CLAUDE.md routing table.
3
+
4
+ Reuses the 4 parallel mapper agents for raw analysis, then merges their outputs into dynamically-detected topic docs. CLAUDE.md is a pure router — all rules go in docs/rules.md.
5
+
6
+ **Output:** docs/ folder with topic docs + CLAUDE.md routing table
7
+ </purpose>
8
+
9
+ <philosophy>
10
+
11
+ ## Context Engineering
12
+
13
+ Every token fights for its place. CLAUDE.md is a thin router, docs are loaded on-demand per task context. No bloat.
14
+
15
+ ## Dynamic Topics
16
+
17
+ Topics emerge from what the codebase actually uses. A React project gets react-query.md; a Go API gets middleware.md. No fixed list.
18
+
19
+ ## Merge, Don't Replace
20
+
21
+ Agent outputs are raw material. The merge step reorganizes by topic ("how to use it") not by agent ("what the agent found"). Content from all 4 agents can land in the same doc.
22
+
23
+ ## Rules Are Special
24
+
25
+ docs/rules.md is always generated. It contains one-liner rules that apply to every code change — the "always read first" file.
26
+
27
+ </philosophy>
28
+
29
+ <process>
30
+
31
+ <step name="discover_docs_location">
32
+ Determine where docs should be written.
33
+
34
+ **Check existing CLAUDE.md for doc path references:**
35
+ ```bash
36
+ [ -f "CLAUDE.md" ] && cat CLAUDE.md || echo "no_claude_md"
37
+ ```
38
+
39
+ If CLAUDE.md exists, scan for references to a docs directory:
40
+ - Look for patterns like `docs/`, `documentation/`, or path references in tables/links
41
+ - If a consistent docs path is referenced, use it as `$DOCS_DIR`
42
+
43
+ **If no CLAUDE.md or no docs path found:**
44
+ Set `$DOCS_DIR = "docs"`
45
+
46
+ ```bash
47
+ mkdir -p $DOCS_DIR
48
+ ```
49
+
50
+ Continue to check_existing.
51
+ </step>
52
+
53
+ <step name="check_existing">
54
+ Check if specd-generated docs already exist.
55
+
56
+ ```bash
57
+ # Check for specd-generated docs (have generated_by: specd in frontmatter)
58
+ grep -rl "generated_by: specd" $DOCS_DIR/ 2>/dev/null
59
+ ```
60
+
61
+ **If specd-generated docs found:**
62
+
63
+ Use AskUserQuestion:
64
+ - header: "Existing Docs"
65
+ - question: "Found existing specd-generated docs. What would you like to do?"
66
+ - options:
67
+ - "Refresh — regenerate all docs" — Delete specd-generated docs and regenerate
68
+ - "Skip — use existing" — Keep current docs, exit workflow
69
+
70
+ If "Refresh": Delete only files with `generated_by: specd` frontmatter. Continue.
71
+ If "Skip": Exit workflow.
72
+
73
+ **Also check for existing CLAUDE.md content to preserve later:**
74
+ ```bash
75
+ [ -f "CLAUDE.md" ] && cat CLAUDE.md
76
+ ```
77
+ Store existing CLAUDE.md content as `$EXISTING_CLAUDE_MD` for merge step.
78
+
79
+ Continue to check_existing_docs.
80
+ </step>
81
+
82
+ <step name="check_existing_docs">
83
+ Scan for existing project documentation to feed to mapper agents.
84
+
85
+ ```bash
86
+ # Find common documentation files
87
+ ls README* CONTRIBUTING* ARCHITECTURE* docs/ doc/ wiki/ 2>/dev/null
88
+ find . -maxdepth 2 -name "*.md" -not -path "./node_modules/*" -not -path "./.git/*" -not -path "./.specd/*" 2>/dev/null | head -20
89
+ ```
90
+
91
+ **Always read and incorporate any docs found.** Existing documentation contains tribal knowledge we want to capture.
92
+
93
+ **Ask user for additional context:**
94
+
95
+ Use AskUserQuestion:
96
+ - header: "More docs?"
97
+ - question: "Do you have any other documentation I should incorporate? (wiki, Notion, external docs, etc.)"
98
+ - options:
99
+ - "No — that's everything" — Proceed with what was found
100
+ - "Yes — I have more" — Wait for user to share additional context
101
+
102
+ If user selects "Yes — I have more": wait for user to provide context, incorporate it.
103
+
104
+ Build `$EXISTING_DOCS_CONTEXT` — a summary of all found documentation to include in agent prompts.
105
+
106
+ Continue to spawn_agents.
107
+ </step>
108
+
109
+ <step name="spawn_agents">
110
+ Spawn 4 parallel mapper agents to a temp directory.
111
+
112
+ **Create temp directory for raw outputs:**
113
+ ```bash
114
+ mkdir -p .specd/tmp/docs-raw
115
+ ```
116
+
117
+ **CRITICAL:** Use the dedicated `specd-codebase-mapper` agent, NOT `Explore`.
118
+
119
+ Spawn all 4 agents with `subagent_type="specd-codebase-mapper"`, `model="sonnet"`, and `run_in_background=true`.
120
+
121
+ **If existing documentation was found:**
122
+ Include `$EXISTING_DOCS_CONTEXT` in each agent's prompt:
123
+ ```
124
+ Existing documentation context:
125
+ {summary of README, ARCHITECTURE, CONTRIBUTING, etc.}
126
+
127
+ Use this context to inform your analysis. Incorporate relevant architectural decisions, gotchas, and conventions mentioned in the docs.
128
+ ```
129
+
130
+ **Agent 1: Map Focus**
131
+
132
+ ```
133
+ Focus: map
134
+
135
+ Create a navigation map of this codebase for Claude.
136
+
137
+ Write MAP.md to .specd/tmp/docs-raw/ containing:
138
+ - Entry points (where execution starts)
139
+ - Core modules with function signatures
140
+ - External integrations (services, env vars)
141
+ - Key type definitions
142
+
143
+ {$EXISTING_DOCS_CONTEXT if available}
144
+
145
+ Extract ACTUAL function signatures from the code. Include file paths everywhere.
146
+ Return confirmation only when done.
147
+ ```
148
+
149
+ **Agent 2: Patterns Focus**
150
+
151
+ ```
152
+ Focus: patterns
153
+
154
+ Extract code patterns from this codebase for Claude to follow.
155
+
156
+ Write PATTERNS.md to .specd/tmp/docs-raw/ containing:
157
+ - Service/handler patterns (with real code examples)
158
+ - Error handling patterns (with real code examples)
159
+ - Testing patterns (with real code examples)
160
+ - Mocking patterns (with real code examples)
161
+ - Import conventions
162
+
163
+ {$EXISTING_DOCS_CONTEXT if available}
164
+
165
+ Use ACTUAL code from the codebase, not generic examples. Include file paths and line numbers.
166
+ Return confirmation only when done.
167
+ ```
168
+
169
+ **Agent 3: Structure Focus**
170
+
171
+ ```
172
+ Focus: structure
173
+
174
+ Document where to put new code in this codebase.
175
+
176
+ Write STRUCTURE.md to .specd/tmp/docs-raw/ containing:
177
+ - Quick reference table: "I want to add X → put it in Y"
178
+ - Directory purposes (what goes where)
179
+ - Naming conventions
180
+ - Where NOT to put code
181
+ - Active migrations (if any)
182
+
183
+ {$EXISTING_DOCS_CONTEXT if available}
184
+
185
+ Be prescriptive: "Put new services in X" not "Services are in X".
186
+ Return confirmation only when done.
187
+ ```
188
+
189
+ **Agent 4: Concerns Focus**
190
+
191
+ ```
192
+ Focus: concerns
193
+
194
+ Find gotchas and problems in this codebase that Claude needs to know.
195
+
196
+ Write CONCERNS.md to .specd/tmp/docs-raw/ containing:
197
+ - Gotchas (surprising but intentional behaviors)
198
+ - Anti-patterns (what NOT to do, with examples)
199
+ - Tech debt (with guidance on working around it)
200
+ - Fragile areas (with safe modification guidance)
201
+ - Dependency notes (pinned versions, upgrade blockers)
202
+ - Performance notes
203
+
204
+ {$EXISTING_DOCS_CONTEXT if available}
205
+
206
+ Gotchas section is MOST IMPORTANT. Include file paths for everything.
207
+ Return confirmation only when done.
208
+ ```
209
+
210
+ Continue to collect_and_merge.
211
+ </step>
212
+
213
+ <step name="collect_and_merge">
214
+ Wait for all 4 agents to complete. Read their raw outputs and detect topics.
215
+
216
+ **Collect outputs:**
217
+ ```bash
218
+ ls -la .specd/tmp/docs-raw/
219
+ wc -l .specd/tmp/docs-raw/*.md
220
+ ```
221
+
222
+ Read all 4 files from `.specd/tmp/docs-raw/`.
223
+
224
+ If any agent failed, note the failure and continue with successful outputs.
225
+
226
+ **Topic detection algorithm:**
227
+
228
+ 1. **Extract mentions:** Scan all 4 raw outputs for technology names, framework references, pattern categories, and architectural concepts. Examples: "React Query", "CSS Modules", "Express middleware", "authentication", "database", "testing", "error handling", "API routes".
229
+
230
+ 2. **Cluster related mentions:** Group mentions that naturally belong together:
231
+ - Same technology (e.g., "React Query hooks" + "useQuery" + "data fetching" → one cluster)
232
+ - Same concern area (e.g., "auth middleware" + "session tokens" + "JWT" → one cluster)
233
+ - Same architectural layer (e.g., "API routes" + "endpoint handlers" + "request validation" → one cluster)
234
+
235
+ 3. **Name each cluster:** Use the dominant theme as the doc filename:
236
+ - `react-query-and-apis.md` (not `data-fetching.md` if React Query is the specific tech)
237
+ - `authentication.md` (not `security.md` if auth is the specific topic)
238
+ - `testing-patterns.md` (if testing has enough content for its own doc)
239
+ - `project-structure.md` (where to put files, directory purposes)
240
+
241
+ 4. **Always include `rules.md`:** Extract always-true rules from across all outputs:
242
+ - Import conventions ("always use src/ alias")
243
+ - Naming patterns ("components are PascalCase")
244
+ - File placement rules ("tests go next to source files")
245
+ - Forbidden patterns ("never use X, always use Y")
246
+
247
+ 5. **Evaluate cluster size:** If a cluster has too little content (< 3 meaningful points), merge it into the most related larger cluster. If too large (> 30 meaningful points), consider splitting.
248
+
249
+ **Propose topics to user:**
250
+
251
+ Use AskUserQuestion:
252
+ - header: "Doc Topics"
253
+ - question: "Here are the proposed documentation topics based on your codebase analysis. Select the ones to generate:"
254
+ - multiSelect: true
255
+ - options: List each proposed topic with a brief description of what it covers
256
+
257
+ **Note:** `rules.md` is always generated regardless of selection — inform user of this.
258
+
259
+ Store approved topic list as `$APPROVED_TOPICS`.
260
+
261
+ Continue to generate_docs.
262
+ </step>
263
+
264
+ <step name="generate_docs">
265
+ Generate each approved topic doc and rules.md.
266
+
267
+ **For each topic in `$APPROVED_TOPICS`:**
268
+
269
+ 1. Pull relevant content from all 4 raw agent outputs that matches this topic
270
+ 2. Reorganize by "how to use it":
271
+ - What is this? (brief intro)
272
+ - Key patterns (with code examples from the actual codebase)
273
+ - Where to find things (file paths)
274
+ - Rules and conventions
275
+ - Gotchas and warnings
276
+ 3. Not every section is required — only include sections with real content
277
+ 4. Add YAML frontmatter:
278
+ ```yaml
279
+ ---
280
+ last_reviewed: {YYYY-MM-DD}
281
+ generated_by: specd
282
+ ---
283
+ ```
284
+ 5. Write to `$DOCS_DIR/{topic}.md`
285
+
286
+ **For `rules.md` specifically:**
287
+
288
+ 1. Extract one-liner rules from all 4 agent outputs that apply universally:
289
+ - Import conventions
290
+ - Naming conventions
291
+ - File placement rules
292
+ - Component/pattern usage rules
293
+ - Forbidden patterns
294
+ 2. Format as a scannable list — no long explanations:
295
+ ```markdown
296
+ ## Import Rules
297
+ - Always use `@/` alias for src imports
298
+ - Never import from `internal/` outside its module
299
+
300
+ ## Naming
301
+ - Components: PascalCase
302
+ - Hooks: camelCase with `use` prefix
303
+ ```
304
+ 3. Add same frontmatter
305
+ 4. Write to `$DOCS_DIR/rules.md`
306
+
307
+ Continue to write_claude_md.
308
+ </step>
309
+
310
+ <step name="write_claude_md">
311
+ Write or update CLAUDE.md as a pure routing table.
312
+
313
+ **Build routing table:**
314
+
315
+ ```markdown
316
+ <!-- specd:docs-routing:start -->
317
+ # Context Docs
318
+
319
+ > Always read `docs/rules.md` first — it contains project-wide rules.
320
+
321
+ | Working on... | Read |
322
+ |---------------|------|
323
+ | {topic context description} | `docs/{topic}.md` |
324
+ | {topic context description} | `docs/{topic}.md` |
325
+ <!-- specd:docs-routing:end -->
326
+ ```
327
+
328
+ Each row maps a working context to the relevant doc file. Examples:
329
+ - "React Query hooks, data fetching, API calls" → `docs/react-query-and-apis.md`
330
+ - "Styling, CSS, component appearance" → `docs/css-and-styles.md`
331
+ - "Writing or running tests" → `docs/testing-patterns.md`
332
+
333
+ **If CLAUDE.md doesn't exist (`$EXISTING_CLAUDE_MD` is empty):**
334
+ Write new CLAUDE.md with just the routing table.
335
+
336
+ **If CLAUDE.md exists (`$EXISTING_CLAUDE_MD` has content):**
337
+
338
+ 1. Check if it already has specd section markers (`<!-- specd:docs-routing:start -->` and `<!-- specd:docs-routing:end -->`)
339
+ 2. If markers found: replace content between markers with new routing table
340
+ 3. If no markers: append routing table at the end of existing content
341
+
342
+ **Bloat detection (optional proposal):**
343
+ If existing CLAUDE.md has content that looks like rules, patterns, or documentation (not just project setup info), propose migration:
344
+
345
+ ```
346
+ Your CLAUDE.md has content that might work better as topic docs:
347
+
348
+ - Lines {N}-{M}: Looks like coding rules → could move to docs/rules.md
349
+ - Lines {N}-{M}: Looks like API patterns → could move to docs/{topic}.md
350
+
351
+ Want me to migrate these? (This would slim down CLAUDE.md to just a router)
352
+ ```
353
+
354
+ Use AskUserQuestion:
355
+ - header: "Migrate?"
356
+ - question: "Move existing CLAUDE.md content to topic docs?"
357
+ - options:
358
+ - "Yes — migrate and slim down" — Move content to appropriate docs
359
+ - "No — keep CLAUDE.md as-is" — Just append routing table
360
+
361
+ Only propose if there's significant bloat (>20 lines of rules/patterns). Skip this for small CLAUDE.md files.
362
+
363
+ Continue to cleanup.
364
+ </step>
365
+
366
+ <step name="cleanup">
367
+ Clean up temp files and commit results.
368
+
369
+ **Delete temp directory:**
370
+ ```bash
371
+ rm -rf .specd/tmp/docs-raw
372
+ rmdir .specd/tmp 2>/dev/null # Remove tmp dir if empty
373
+ ```
374
+
375
+ **Do not commit.** The user manages commits with their own workflow.
376
+
377
+ Continue to completion.
378
+ </step>
379
+
380
+ <step name="completion">
381
+ Present summary.
382
+
383
+ **Get line counts:**
384
+ ```bash
385
+ wc -l $DOCS_DIR/*.md
386
+ ```
387
+
388
+ **Output:**
389
+
390
+ ```
391
+ Codebase docs generated.
392
+
393
+ Created {DOCS_DIR}/:
394
+ {For each doc:}
395
+ - {topic}.md ({N} lines) — {brief description}
396
+ - rules.md ({N} lines) — Project-wide rules (always read first)
397
+
398
+ CLAUDE.md routing table {created | updated}.
399
+
400
+ To review docs: /specd.docs.review
401
+ To refresh: /specd.docs
402
+ ```
403
+
404
+ End workflow.
405
+ </step>
406
+
407
+ </process>
408
+
409
+ <success_criteria>
410
+ - 4 parallel specd-codebase-mapper agents spawned with run_in_background=true
411
+ - Agents write to temp directory, not final docs location
412
+ - Topic detection produces dynamic topic list from agent outputs
413
+ - User approves topic list before generation
414
+ - docs/rules.md always generated with project-wide rules
415
+ - All docs have YAML frontmatter (last_reviewed, generated_by)
416
+ - CLAUDE.md is purely a routing table — zero inline rules
417
+ - Existing CLAUDE.md content preserved during merge (section markers)
418
+ - Temp files cleaned up
419
+ - No auto-commit — user manages commits
420
+ </success_criteria>