cap-pro 1.0.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 (275) hide show
  1. package/.claude-plugin/README.md +26 -0
  2. package/.claude-plugin/marketplace.json +24 -0
  3. package/.claude-plugin/plugin.json +24 -0
  4. package/LICENSE +21 -0
  5. package/README.ja-JP.md +834 -0
  6. package/README.ko-KR.md +823 -0
  7. package/README.md +806 -0
  8. package/README.pt-BR.md +452 -0
  9. package/README.zh-CN.md +800 -0
  10. package/agents/cap-architect.md +269 -0
  11. package/agents/cap-brainstormer.md +207 -0
  12. package/agents/cap-curator.md +276 -0
  13. package/agents/cap-debugger.md +365 -0
  14. package/agents/cap-designer.md +246 -0
  15. package/agents/cap-historian.md +464 -0
  16. package/agents/cap-migrator.md +291 -0
  17. package/agents/cap-prototyper.md +197 -0
  18. package/agents/cap-validator.md +308 -0
  19. package/bin/install.js +5433 -0
  20. package/cap/bin/cap-tools.cjs +853 -0
  21. package/cap/bin/lib/arc-scanner.cjs +344 -0
  22. package/cap/bin/lib/cap-affinity-engine.cjs +862 -0
  23. package/cap/bin/lib/cap-anchor.cjs +228 -0
  24. package/cap/bin/lib/cap-annotation-writer.cjs +340 -0
  25. package/cap/bin/lib/cap-checkpoint.cjs +434 -0
  26. package/cap/bin/lib/cap-cluster-detect.cjs +945 -0
  27. package/cap/bin/lib/cap-cluster-display.cjs +52 -0
  28. package/cap/bin/lib/cap-cluster-format.cjs +245 -0
  29. package/cap/bin/lib/cap-cluster-helpers.cjs +295 -0
  30. package/cap/bin/lib/cap-cluster-io.cjs +212 -0
  31. package/cap/bin/lib/cap-completeness.cjs +540 -0
  32. package/cap/bin/lib/cap-deps.cjs +583 -0
  33. package/cap/bin/lib/cap-design-families.cjs +332 -0
  34. package/cap/bin/lib/cap-design.cjs +966 -0
  35. package/cap/bin/lib/cap-divergence-detector.cjs +400 -0
  36. package/cap/bin/lib/cap-doctor.cjs +752 -0
  37. package/cap/bin/lib/cap-feature-map-internals.cjs +19 -0
  38. package/cap/bin/lib/cap-feature-map-migrate.cjs +335 -0
  39. package/cap/bin/lib/cap-feature-map-monorepo.cjs +885 -0
  40. package/cap/bin/lib/cap-feature-map-shard.cjs +315 -0
  41. package/cap/bin/lib/cap-feature-map.cjs +1943 -0
  42. package/cap/bin/lib/cap-fitness-score.cjs +1075 -0
  43. package/cap/bin/lib/cap-impact-analysis.cjs +652 -0
  44. package/cap/bin/lib/cap-learn-review.cjs +1072 -0
  45. package/cap/bin/lib/cap-learning-signals.cjs +627 -0
  46. package/cap/bin/lib/cap-loader.cjs +227 -0
  47. package/cap/bin/lib/cap-logger.cjs +57 -0
  48. package/cap/bin/lib/cap-memory-bridge.cjs +764 -0
  49. package/cap/bin/lib/cap-memory-confidence.cjs +452 -0
  50. package/cap/bin/lib/cap-memory-dir.cjs +987 -0
  51. package/cap/bin/lib/cap-memory-engine.cjs +698 -0
  52. package/cap/bin/lib/cap-memory-extends.cjs +398 -0
  53. package/cap/bin/lib/cap-memory-graph.cjs +790 -0
  54. package/cap/bin/lib/cap-memory-migrate.cjs +2015 -0
  55. package/cap/bin/lib/cap-memory-pin.cjs +183 -0
  56. package/cap/bin/lib/cap-memory-platform.cjs +490 -0
  57. package/cap/bin/lib/cap-memory-prune.cjs +707 -0
  58. package/cap/bin/lib/cap-memory-schema.cjs +812 -0
  59. package/cap/bin/lib/cap-migrate-tags.cjs +309 -0
  60. package/cap/bin/lib/cap-migrate.cjs +540 -0
  61. package/cap/bin/lib/cap-pattern-apply.cjs +1203 -0
  62. package/cap/bin/lib/cap-pattern-pipeline.cjs +1034 -0
  63. package/cap/bin/lib/cap-plugin-manifest.cjs +80 -0
  64. package/cap/bin/lib/cap-realtime-affinity.cjs +399 -0
  65. package/cap/bin/lib/cap-reconcile.cjs +570 -0
  66. package/cap/bin/lib/cap-research-gate.cjs +218 -0
  67. package/cap/bin/lib/cap-scope-filter.cjs +402 -0
  68. package/cap/bin/lib/cap-semantic-pipeline.cjs +1038 -0
  69. package/cap/bin/lib/cap-session-extract.cjs +987 -0
  70. package/cap/bin/lib/cap-session.cjs +445 -0
  71. package/cap/bin/lib/cap-snapshot-linkage.cjs +963 -0
  72. package/cap/bin/lib/cap-stack-docs.cjs +646 -0
  73. package/cap/bin/lib/cap-tag-observer.cjs +371 -0
  74. package/cap/bin/lib/cap-tag-scanner.cjs +1766 -0
  75. package/cap/bin/lib/cap-telemetry.cjs +466 -0
  76. package/cap/bin/lib/cap-test-audit.cjs +1438 -0
  77. package/cap/bin/lib/cap-thread-migrator.cjs +307 -0
  78. package/cap/bin/lib/cap-thread-synthesis.cjs +545 -0
  79. package/cap/bin/lib/cap-thread-tracker.cjs +519 -0
  80. package/cap/bin/lib/cap-trace.cjs +399 -0
  81. package/cap/bin/lib/cap-trust-mode.cjs +336 -0
  82. package/cap/bin/lib/cap-ui-design-editor.cjs +642 -0
  83. package/cap/bin/lib/cap-ui-mind-map.cjs +712 -0
  84. package/cap/bin/lib/cap-ui-thread-nav.cjs +693 -0
  85. package/cap/bin/lib/cap-ui.cjs +1245 -0
  86. package/cap/bin/lib/cap-upgrade.cjs +1028 -0
  87. package/cap/bin/lib/cli/arg-helpers.cjs +49 -0
  88. package/cap/bin/lib/cli/frontmatter-router.cjs +31 -0
  89. package/cap/bin/lib/cli/init-router.cjs +68 -0
  90. package/cap/bin/lib/cli/phase-router.cjs +102 -0
  91. package/cap/bin/lib/cli/state-router.cjs +61 -0
  92. package/cap/bin/lib/cli/template-router.cjs +37 -0
  93. package/cap/bin/lib/cli/uat-router.cjs +29 -0
  94. package/cap/bin/lib/cli/validation-router.cjs +26 -0
  95. package/cap/bin/lib/cli/verification-router.cjs +31 -0
  96. package/cap/bin/lib/cli/workstream-router.cjs +39 -0
  97. package/cap/bin/lib/commands.cjs +961 -0
  98. package/cap/bin/lib/config.cjs +467 -0
  99. package/cap/bin/lib/convention-reader.cjs +258 -0
  100. package/cap/bin/lib/core.cjs +1241 -0
  101. package/cap/bin/lib/feature-aggregator.cjs +423 -0
  102. package/cap/bin/lib/frontmatter.cjs +337 -0
  103. package/cap/bin/lib/init.cjs +1443 -0
  104. package/cap/bin/lib/manifest-generator.cjs +383 -0
  105. package/cap/bin/lib/milestone.cjs +253 -0
  106. package/cap/bin/lib/model-profiles.cjs +69 -0
  107. package/cap/bin/lib/monorepo-context.cjs +226 -0
  108. package/cap/bin/lib/monorepo-migrator.cjs +509 -0
  109. package/cap/bin/lib/phase.cjs +889 -0
  110. package/cap/bin/lib/profile-output.cjs +989 -0
  111. package/cap/bin/lib/profile-pipeline.cjs +540 -0
  112. package/cap/bin/lib/roadmap.cjs +330 -0
  113. package/cap/bin/lib/security.cjs +394 -0
  114. package/cap/bin/lib/session-manager.cjs +292 -0
  115. package/cap/bin/lib/skeleton-generator.cjs +179 -0
  116. package/cap/bin/lib/state.cjs +1032 -0
  117. package/cap/bin/lib/template.cjs +231 -0
  118. package/cap/bin/lib/test-detector.cjs +62 -0
  119. package/cap/bin/lib/uat.cjs +283 -0
  120. package/cap/bin/lib/verify.cjs +889 -0
  121. package/cap/bin/lib/workspace-detector.cjs +371 -0
  122. package/cap/bin/lib/workstream.cjs +492 -0
  123. package/cap/commands/gsd/workstreams.md +63 -0
  124. package/cap/references/arc-standard.md +315 -0
  125. package/cap/references/cap-agent-architecture.md +101 -0
  126. package/cap/references/cap-gitignore-template +9 -0
  127. package/cap/references/cap-zero-deps.md +158 -0
  128. package/cap/references/checkpoints.md +778 -0
  129. package/cap/references/continuation-format.md +249 -0
  130. package/cap/references/contract-test-templates.md +312 -0
  131. package/cap/references/feature-map-template.md +25 -0
  132. package/cap/references/git-integration.md +295 -0
  133. package/cap/references/git-planning-commit.md +38 -0
  134. package/cap/references/model-profiles.md +174 -0
  135. package/cap/references/phase-numbering.md +126 -0
  136. package/cap/references/planning-config.md +202 -0
  137. package/cap/references/property-test-templates.md +316 -0
  138. package/cap/references/security-test-templates.md +347 -0
  139. package/cap/references/session-template.json +8 -0
  140. package/cap/references/tdd.md +263 -0
  141. package/cap/references/user-profiling.md +681 -0
  142. package/cap/references/verification-patterns.md +612 -0
  143. package/cap/templates/UAT.md +265 -0
  144. package/cap/templates/claude-md.md +175 -0
  145. package/cap/templates/codebase/architecture.md +255 -0
  146. package/cap/templates/codebase/concerns.md +310 -0
  147. package/cap/templates/codebase/conventions.md +307 -0
  148. package/cap/templates/codebase/integrations.md +280 -0
  149. package/cap/templates/codebase/stack.md +186 -0
  150. package/cap/templates/codebase/structure.md +285 -0
  151. package/cap/templates/codebase/testing.md +480 -0
  152. package/cap/templates/config.json +44 -0
  153. package/cap/templates/context.md +352 -0
  154. package/cap/templates/continue-here.md +78 -0
  155. package/cap/templates/copilot-instructions.md +7 -0
  156. package/cap/templates/debug-subagent-prompt.md +91 -0
  157. package/cap/templates/discussion-log.md +63 -0
  158. package/cap/templates/milestone-archive.md +123 -0
  159. package/cap/templates/milestone.md +115 -0
  160. package/cap/templates/phase-prompt.md +610 -0
  161. package/cap/templates/planner-subagent-prompt.md +117 -0
  162. package/cap/templates/project.md +186 -0
  163. package/cap/templates/requirements.md +231 -0
  164. package/cap/templates/research-project/ARCHITECTURE.md +204 -0
  165. package/cap/templates/research-project/FEATURES.md +147 -0
  166. package/cap/templates/research-project/PITFALLS.md +200 -0
  167. package/cap/templates/research-project/STACK.md +120 -0
  168. package/cap/templates/research-project/SUMMARY.md +170 -0
  169. package/cap/templates/research.md +552 -0
  170. package/cap/templates/roadmap.md +202 -0
  171. package/cap/templates/state.md +176 -0
  172. package/cap/templates/summary.md +364 -0
  173. package/cap/templates/user-preferences.md +498 -0
  174. package/cap/templates/verification-report.md +322 -0
  175. package/cap/workflows/add-phase.md +112 -0
  176. package/cap/workflows/add-tests.md +351 -0
  177. package/cap/workflows/add-todo.md +158 -0
  178. package/cap/workflows/audit-milestone.md +340 -0
  179. package/cap/workflows/audit-uat.md +109 -0
  180. package/cap/workflows/autonomous.md +891 -0
  181. package/cap/workflows/check-todos.md +177 -0
  182. package/cap/workflows/cleanup.md +152 -0
  183. package/cap/workflows/complete-milestone.md +767 -0
  184. package/cap/workflows/diagnose-issues.md +231 -0
  185. package/cap/workflows/discovery-phase.md +289 -0
  186. package/cap/workflows/discuss-phase-assumptions.md +653 -0
  187. package/cap/workflows/discuss-phase.md +1049 -0
  188. package/cap/workflows/do.md +104 -0
  189. package/cap/workflows/execute-phase.md +846 -0
  190. package/cap/workflows/execute-plan.md +514 -0
  191. package/cap/workflows/fast.md +105 -0
  192. package/cap/workflows/forensics.md +265 -0
  193. package/cap/workflows/health.md +181 -0
  194. package/cap/workflows/help.md +660 -0
  195. package/cap/workflows/insert-phase.md +130 -0
  196. package/cap/workflows/list-phase-assumptions.md +178 -0
  197. package/cap/workflows/list-workspaces.md +56 -0
  198. package/cap/workflows/manager.md +362 -0
  199. package/cap/workflows/map-codebase.md +377 -0
  200. package/cap/workflows/milestone-summary.md +223 -0
  201. package/cap/workflows/new-milestone.md +486 -0
  202. package/cap/workflows/new-project.md +1250 -0
  203. package/cap/workflows/new-workspace.md +237 -0
  204. package/cap/workflows/next.md +97 -0
  205. package/cap/workflows/node-repair.md +92 -0
  206. package/cap/workflows/note.md +156 -0
  207. package/cap/workflows/pause-work.md +176 -0
  208. package/cap/workflows/plan-milestone-gaps.md +273 -0
  209. package/cap/workflows/plan-phase.md +857 -0
  210. package/cap/workflows/plant-seed.md +169 -0
  211. package/cap/workflows/pr-branch.md +129 -0
  212. package/cap/workflows/profile-user.md +449 -0
  213. package/cap/workflows/progress.md +507 -0
  214. package/cap/workflows/quick.md +757 -0
  215. package/cap/workflows/remove-phase.md +155 -0
  216. package/cap/workflows/remove-workspace.md +90 -0
  217. package/cap/workflows/research-phase.md +82 -0
  218. package/cap/workflows/resume-project.md +326 -0
  219. package/cap/workflows/review.md +228 -0
  220. package/cap/workflows/session-report.md +146 -0
  221. package/cap/workflows/settings.md +283 -0
  222. package/cap/workflows/ship.md +228 -0
  223. package/cap/workflows/stats.md +60 -0
  224. package/cap/workflows/transition.md +671 -0
  225. package/cap/workflows/ui-phase.md +298 -0
  226. package/cap/workflows/ui-review.md +161 -0
  227. package/cap/workflows/update.md +323 -0
  228. package/cap/workflows/validate-phase.md +170 -0
  229. package/cap/workflows/verify-phase.md +254 -0
  230. package/cap/workflows/verify-work.md +637 -0
  231. package/commands/cap/annotate.md +165 -0
  232. package/commands/cap/brainstorm.md +393 -0
  233. package/commands/cap/checkpoint.md +106 -0
  234. package/commands/cap/completeness.md +94 -0
  235. package/commands/cap/continue.md +72 -0
  236. package/commands/cap/debug.md +588 -0
  237. package/commands/cap/deps.md +169 -0
  238. package/commands/cap/design.md +479 -0
  239. package/commands/cap/init.md +354 -0
  240. package/commands/cap/iterate.md +249 -0
  241. package/commands/cap/learn.md +459 -0
  242. package/commands/cap/memory.md +275 -0
  243. package/commands/cap/migrate-feature-map.md +91 -0
  244. package/commands/cap/migrate-memory.md +108 -0
  245. package/commands/cap/migrate-tags.md +91 -0
  246. package/commands/cap/migrate.md +131 -0
  247. package/commands/cap/prototype.md +510 -0
  248. package/commands/cap/reconcile.md +121 -0
  249. package/commands/cap/review.md +360 -0
  250. package/commands/cap/save.md +72 -0
  251. package/commands/cap/scan.md +404 -0
  252. package/commands/cap/start.md +356 -0
  253. package/commands/cap/status.md +118 -0
  254. package/commands/cap/test-audit.md +262 -0
  255. package/commands/cap/test.md +394 -0
  256. package/commands/cap/trace.md +133 -0
  257. package/commands/cap/ui.md +167 -0
  258. package/hooks/dist/cap-check-update.js +115 -0
  259. package/hooks/dist/cap-context-monitor.js +185 -0
  260. package/hooks/dist/cap-learn-review-hook.js +114 -0
  261. package/hooks/dist/cap-learning-hook.js +192 -0
  262. package/hooks/dist/cap-memory.js +299 -0
  263. package/hooks/dist/cap-prompt-guard.js +97 -0
  264. package/hooks/dist/cap-statusline.js +157 -0
  265. package/hooks/dist/cap-tag-observer.js +115 -0
  266. package/hooks/dist/cap-version-check.js +112 -0
  267. package/hooks/dist/cap-workflow-guard.js +175 -0
  268. package/hooks/hooks.json +55 -0
  269. package/package.json +58 -0
  270. package/scripts/base64-scan.sh +262 -0
  271. package/scripts/build-hooks.js +93 -0
  272. package/scripts/cap-removal-checklist.md +202 -0
  273. package/scripts/prompt-injection-scan.sh +199 -0
  274. package/scripts/run-tests.cjs +181 -0
  275. package/scripts/secret-scan.sh +227 -0
@@ -0,0 +1,354 @@
1
+ ---
2
+ name: cap:init
3
+ description: "Initialize CAP project -- creates .cap/, FEATURE-MAP.md, detects dependencies via Context7, performs brownfield analysis on existing codebases."
4
+ allowed-tools:
5
+ - Read
6
+ - Write
7
+ - Bash
8
+ - Glob
9
+ - Grep
10
+ ---
11
+
12
+ <!-- @cap-context CAP v2.0 init command (final pass) -- adds mandatory Context7 integration and brownfield detection on top of the base init flow. -->
13
+ <!-- @cap-decision Context7 fetch is mandatory at init time per AC-81. If unreachable, warning is emitted but init continues with explicit marker in SESSION.json. -->
14
+ <!-- @cap-decision Brownfield analysis is ephemeral -- results are used as context for /cap:annotate suggestion, NOT persisted as a separate document (AC-87). -->
15
+ <!-- @cap-decision No /cap:map command exists. Codebase analysis is part of /cap:init only (AC-90). -->
16
+ <!-- @cap-constraint No prompts, wizards, or configuration forms. Init completes in a single invocation (AC-4, AC-5). -->
17
+
18
+ <!-- @cap-todo(ref:AC-81) Detect all dependencies from package.json / requirements.txt / Cargo.toml / go.mod and fetch docs via Context7 -->
19
+ <!-- @cap-todo(ref:AC-82) Store fetched stack docs in .cap/stack-docs/{library-name}.md compressed to API surface, config, breaking changes -->
20
+ <!-- @cap-todo(ref:AC-83) Agents receive .cap/stack-docs/ as context input on every invocation -->
21
+ <!-- @cap-todo(ref:AC-84) Stack-docs carry freshness marker (fetch date). Docs older than 7 days auto-refreshed. Manual refresh: see docs/setup-and-upgrade.md (`npx ctx7@latest docs ...`) -->
22
+ <!-- @cap-todo(ref:AC-85) Context7 fetching is MANDATORY at init. If unreachable, warning emitted and init continues with explicit marker -->
23
+ <!-- @cap-todo(ref:AC-86) Brownfield init performs one-time codebase analysis: architecture detection, convention detection, test setup detection -->
24
+ <!-- @cap-todo(ref:AC-87) Brownfield analysis result NOT persisted as separate document -- used as init context for /cap:annotate suggestion -->
25
+ <!-- @cap-todo(ref:AC-88) After brownfield init, suggest /cap:annotate to retroactively annotate existing code -->
26
+ <!-- @cap-todo(ref:AC-90) No /cap:map command. Codebase analysis is part of /cap:init -->
27
+ <!-- @cap-todo(ref:AC-91) To refresh codebase information: /cap:annotate; for library docs see docs/setup-and-upgrade.md -->
28
+ <!-- @cap-todo(ref:AC-92) The 7 documents from .planning/codebase/ shall NOT be generated in v2.0 -->
29
+
30
+ <objective>
31
+ Initialize the CAP project structure with mandatory Context7 stack documentation fetch and brownfield codebase analysis. This command:
32
+
33
+ 1. Creates `.cap/` directory with subdirectories (stack-docs, debug)
34
+ 2. Creates `.cap/.gitignore` (ignores SESSION.json and debug/)
35
+ 3. Creates `.cap/SESSION.json` with default session state
36
+ 4. Creates `FEATURE-MAP.md` at project root (ONLY if it does not already exist)
37
+ 5. **Detects project dependencies** from manifest files (package.json, requirements.txt, Cargo.toml, go.mod)
38
+ 6. **Fetches stack documentation via Context7** for all detected dependencies
39
+ 7. **Performs brownfield analysis** if existing source code is detected
40
+ 8. Suggests `/cap:annotate` if brownfield code is found
41
+
42
+ **Idempotent:** Safe to run multiple times. Never overwrites existing FEATURE-MAP.md.
43
+ **Non-interactive:** No prompts, no wizards, no configuration forms.
44
+ **Context7 is MANDATORY:** If unreachable, warning emitted and init continues with explicit marker.
45
+ </objective>
46
+
47
+ <context>
48
+ $ARGUMENTS
49
+
50
+ @FEATURE-MAP.md
51
+ </context>
52
+
53
+ <process>
54
+
55
+ ## Step 1: Detect project root and check initialization state
56
+
57
+ Use Bash to check current state:
58
+
59
+ ```bash
60
+ ls -la .cap/ 2>/dev/null && echo "ALREADY_INITIALIZED" || echo "FRESH_PROJECT"
61
+ test -f FEATURE-MAP.md && echo "FEATURE_MAP_EXISTS" || echo "NO_FEATURE_MAP"
62
+ ```
63
+
64
+ ## Step 2: Create .cap/ directory structure
65
+
66
+ ```bash
67
+ mkdir -p .cap/stack-docs .cap/debug
68
+ ```
69
+
70
+ ## Step 3: Write .cap/.gitignore
71
+
72
+ Use the Write tool to create `.cap/.gitignore`:
73
+
74
+ ```
75
+ # CAP ephemeral state -- do not commit
76
+ SESSION.json
77
+ debug/
78
+ ```
79
+
80
+ ## Step 4: Write .cap/SESSION.json (only if not exists)
81
+
82
+ Check if SESSION.json exists first. If not, write default session:
83
+
84
+ ```json
85
+ {
86
+ "version": "2.0.0",
87
+ "lastCommand": "/cap:init",
88
+ "lastCommandTimestamp": "<ISO_NOW>",
89
+ "activeFeature": null,
90
+ "step": "init",
91
+ "startedAt": "<ISO_NOW>",
92
+ "activeDebugSession": null,
93
+ "context7Available": null,
94
+ "metadata": {}
95
+ }
96
+ ```
97
+
98
+ Note the `context7Available` field -- this gets set in Step 6 to indicate whether Context7 was reachable.
99
+
100
+ ## Step 5: Write FEATURE-MAP.md (only if not exists)
101
+
102
+ **CRITICAL: Skip this step if FEATURE-MAP.md already exists.**
103
+
104
+ If FEATURE-MAP.md does NOT exist, write the empty template.
105
+
106
+ ## Step 5b: Detect monorepo and create per-app FEATURE-MAP.md files
107
+
108
+ ```bash
109
+ node -e "
110
+ const session = require('./cap/bin/lib/cap-session.cjs');
111
+ const fm = require('./cap/bin/lib/cap-feature-map.cjs');
112
+ const fs = require('node:fs');
113
+ const path = require('node:path');
114
+ const projectRoot = process.cwd();
115
+ const mono = session.listApps(projectRoot);
116
+
117
+ if (!mono.isMonorepo) {
118
+ console.log(JSON.stringify({ isMonorepo: false, created: 0, apps: [] }));
119
+ } else {
120
+ let created = 0;
121
+ const createdApps = [];
122
+ for (const app of mono.apps) {
123
+ // Only create FEATURE-MAP.md for apps that have source files
124
+ const appDir = path.join(projectRoot, app);
125
+ if (!fs.existsSync(appDir)) continue;
126
+ const entries = fs.readdirSync(appDir, { withFileTypes: true });
127
+ const hasSrc = entries.some(e =>
128
+ (e.isDirectory() && (e.name === 'src' || e.name === 'lib' || e.name === 'app')) ||
129
+ (e.isFile() && /\.(js|ts|py|go|rs|java|rb)$/.test(e.name))
130
+ );
131
+ if (hasSrc) {
132
+ const wasCreated = fm.initAppFeatureMap(projectRoot, app);
133
+ if (wasCreated) {
134
+ created++;
135
+ createdApps.push(app);
136
+ }
137
+ }
138
+ }
139
+ console.log(JSON.stringify({ isMonorepo: true, created, apps: createdApps, totalApps: mono.apps.length }));
140
+ }
141
+ "
142
+ ```
143
+
144
+ Store as `monorepo_init`.
145
+
146
+ **If monorepo detected:**
147
+ Log: "Monorepo detected with {totalApps} workspace packages."
148
+ If `created > 0`: Log: "Created FEATURE-MAP.md for {created} apps: {apps list}"
149
+ If `created === 0`: Log: "All apps already have FEATURE-MAP.md (or no source files detected)."
150
+
151
+ ## Step 6: Mandatory Context7 dependency fetch
152
+
153
+ <!-- @cap-decision Multi-language dependency detection runs in priority order: package.json first, then requirements.txt, then Cargo.toml, then go.mod. First match sets project type. -->
154
+
155
+ ### 6a: Detect dependencies
156
+
157
+ Run dependency detection for all supported manifest files:
158
+
159
+ ```bash
160
+ node -e "
161
+ const stackDocs = require('./cap/bin/lib/cap-stack-docs.cjs');
162
+ const result = stackDocs.detectDependencies(process.cwd());
163
+ console.log(JSON.stringify(result, null, 2));
164
+ "
165
+ ```
166
+
167
+ Store the result as `dep_info`. Log: "Detected {dep_info.type} project with {dep_info.dependencies.length} dependencies."
168
+
169
+ ### 6b: Fetch stack docs via Context7
170
+
171
+ For each dependency in `dep_info.dependencies` (limit to top 10 most important -- skip internal/scoped packages that start with `@company/`):
172
+
173
+ ```bash
174
+ node -e "
175
+ const stackDocs = require('./cap/bin/lib/cap-stack-docs.cjs');
176
+ const depName = process.argv[1];
177
+ const lib = stackDocs.resolveLibrary(depName, 'API surface and configuration');
178
+ if (lib) {
179
+ const result = stackDocs.fetchDocs(process.cwd(), lib.id, 'API surface, configuration, breaking changes');
180
+ console.log(JSON.stringify({ library: depName, ...result }));
181
+ } else {
182
+ console.log(JSON.stringify({ library: depName, success: false, error: 'Library not found in Context7' }));
183
+ }
184
+ " "<DEP_NAME>"
185
+ ```
186
+
187
+ Track results:
188
+ - `fetched_count` -- number of successfully fetched docs
189
+ - `failed_count` -- number of failed fetches
190
+ - `context7_available` -- true if at least one fetch succeeded
191
+
192
+ ### 6c: Handle Context7 unreachable
193
+
194
+ If ALL fetches fail (context7_available = false):
195
+
196
+ 1. Update SESSION.json to set `context7Available: false`
197
+ 2. Emit warning:
198
+ ```
199
+ WARNING: Context7 is unreachable. Stack documentation could not be fetched.
200
+ Init continues without stack docs. Re-fetch via `npx ctx7@latest` when network is available (see docs/setup-and-upgrade.md).
201
+ ```
202
+
203
+ If some fetches succeeded:
204
+ 1. Update SESSION.json to set `context7Available: true`
205
+ 2. Log summary: "Fetched docs for {fetched_count} of {total} dependencies."
206
+
207
+ ## Step 7: Brownfield codebase analysis
208
+
209
+ <!-- @cap-decision Brownfield analysis detects 3 things: (1) architecture pattern, (2) coding conventions, (3) test setup. Results are ephemeral -- used only for the /cap:annotate suggestion. -->
210
+
211
+ ### 7a: Check for existing source code
212
+
213
+ ```bash
214
+ # Count source files by language
215
+ find . -maxdepth 4 -not -path './node_modules/*' -not -path './.git/*' -not -path './.cap/*' \( -name "*.js" -o -name "*.ts" -o -name "*.py" -o -name "*.go" -o -name "*.rs" -o -name "*.java" -o -name "*.rb" \) | head -50
216
+ ```
217
+
218
+ If NO source files are found, this is a greenfield project. Skip to Step 8.
219
+
220
+ ### 7b: Architecture detection (ephemeral)
221
+
222
+ If source files exist, analyze the codebase structure:
223
+
224
+ ```bash
225
+ # Detect directory structure pattern
226
+ ls -d */ 2>/dev/null | head -20
227
+ # Check for common framework indicators
228
+ test -f tsconfig.json && echo "TYPESCRIPT"
229
+ test -f next.config.js -o -f next.config.mjs && echo "NEXTJS"
230
+ test -f vite.config.ts -o -f vite.config.js && echo "VITE"
231
+ test -f Dockerfile && echo "DOCKER"
232
+ test -d src && echo "SRC_DIR"
233
+ test -d lib && echo "LIB_DIR"
234
+ test -d packages && echo "MONOREPO"
235
+ ```
236
+
237
+ ### 7c: Convention detection (ephemeral)
238
+
239
+ ```bash
240
+ # Check for linting/formatting config
241
+ test -f .eslintrc.json -o -f .eslintrc.js -o -f eslint.config.js && echo "ESLINT"
242
+ test -f .prettierrc -o -f .prettierrc.json && echo "PRETTIER"
243
+ test -f .editorconfig && echo "EDITORCONFIG"
244
+ ```
245
+
246
+ ### 7d: Test setup detection (ephemeral)
247
+
248
+ ```bash
249
+ # Check for test frameworks
250
+ test -f jest.config.js -o -f jest.config.ts && echo "JEST"
251
+ test -f vitest.config.ts -o -f vitest.config.js && echo "VITEST"
252
+ test -d __tests__ -o -d tests -o -d test && echo "TEST_DIR_EXISTS"
253
+ ```
254
+
255
+ ### 7e: Suggest /cap:annotate
256
+
257
+ If brownfield code was detected, output:
258
+
259
+ ```
260
+ Existing codebase detected:
261
+ Source files: ~{count} files ({languages})
262
+ Architecture: {detected patterns}
263
+ Test setup: {detected test frameworks}
264
+
265
+ Recommended: Run /cap:annotate to add @cap-feature tags to your existing code.
266
+ This helps CAP track your features across the codebase.
267
+ ```
268
+
269
+ **Do NOT persist the brownfield analysis as a separate document** (AC-87).
270
+
271
+ ## Step 7f: Build memory graph
272
+
273
+ **MANDATORY** — always run this step. The script auto-detects whether data exists.
274
+
275
+ ```bash
276
+ node -e "const fs=require('fs'),p=require('path'),c=process.cwd(),md=p.join(c,'.cap','memory');if(fs.existsSync(p.join(c,'FEATURE-MAP.md'))||fs.existsSync(p.join(md,'decisions.md'))){const g=require('./cap/bin/lib/cap-memory-graph.cjs'),gr=g.buildFromMemory(c);g.saveGraph(c,gr);console.log(JSON.stringify({built:true,nodes:Object.keys(gr.nodes).length,edges:gr.edges.length}))}else{console.log(JSON.stringify({built:false}))}"
277
+ ```
278
+
279
+ Log the result. If `built: true`: "Memory graph built: {nodes} nodes, {edges} edges"
280
+
281
+ ## Step 7g: Migrate brainstorm sessions to conversation threads
282
+
283
+ **MANDATORY** — always run this step. The script auto-detects whether migration is needed and handles re-migration of metadata-only threads.
284
+
285
+ ```bash
286
+ node -e "const m=require('./cap/bin/lib/cap-thread-migrator.cjs');console.log(JSON.stringify(m.migrateBrainstormSessions(process.cwd())))"
287
+ ```
288
+
289
+ Log the result. If `migrated > 0`: "Migrated {migrated} brainstorm session(s) to conversation threads."
290
+
291
+ ## Step 8: Report results
292
+
293
+ ```
294
+ CAP initialized.
295
+
296
+ Created:
297
+ .cap/ -- runtime directory
298
+ .cap/.gitignore -- excludes SESSION.json from git
299
+ .cap/SESSION.json -- ephemeral workflow state
300
+ .cap/stack-docs/ -- cached documentation ({fetched_count} docs fetched)
301
+ .cap/debug/ -- debug session logs
302
+ FEATURE-MAP.md -- feature source of truth (or: already existed, preserved)
303
+
304
+ Stack docs: {fetched_count} fetched, {failed_count} failed{context7_warning}
305
+ {If graph_result.built:}Memory graph: {graph_result.nodes} nodes, {graph_result.edges} edges{End if}
306
+ {If thread_migration.migrated > 0:}Threads: {thread_migration.migrated} brainstorm session(s) migrated{End if}
307
+
308
+ Next steps:
309
+ /cap:brainstorm -- generate features from conversation
310
+ /cap:annotate -- add @cap-feature tags to existing code
311
+ /cap:prototype -- build features from Feature Map
312
+ /cap:status -- view project dashboard
313
+
314
+ To refresh stack documentation later, run `npx ctx7@latest` directly (see docs/setup-and-upgrade.md).
315
+ ```
316
+
317
+ ## Step 8b: Lightweight doctor check
318
+
319
+ Run a quick check for optional tool availability (especially ctx7 since init depends on it):
320
+
321
+ ```bash
322
+ node -e "
323
+ const doctor = require('./cap/bin/lib/cap-doctor.cjs');
324
+ const report = doctor.runDoctor();
325
+ const missing = report.tools.filter(t => !t.ok && !t.required);
326
+ if (missing.length > 0) {
327
+ console.log('Optional tools not found:');
328
+ for (const t of missing) {
329
+ console.log(' - ' + t.name + ': ' + t.purpose);
330
+ console.log(' Install: ' + t.installHint);
331
+ }
332
+ console.log('\nFor a full environment check, see docs/setup-and-upgrade.md.');
333
+ } else {
334
+ console.log('All optional tools available.');
335
+ }
336
+ "
337
+ ```
338
+
339
+ If missing tools are reported, display the output as an informational note (not a blocking error).
340
+
341
+ ## Step 9: Update session
342
+
343
+ ```bash
344
+ node -e "
345
+ const session = require('./cap/bin/lib/cap-session.cjs');
346
+ session.updateSession(process.cwd(), {
347
+ lastCommand: '/cap:init',
348
+ lastCommandTimestamp: new Date().toISOString(),
349
+ step: 'initialized'
350
+ });
351
+ "
352
+ ```
353
+
354
+ </process>
@@ -0,0 +1,249 @@
1
+ ---
2
+ name: cap:iterate
3
+ description: Refine an already-prototyped feature to close remaining `@cap-todo` tags or address feedback. TRIGGER when after a feature has been prototyped there are still pending @cap-todo tags in code, when the user says "iterate on X / this isn't quite right / refine F-XXX / let's keep going", or after a `/cap:scan` reveals open gaps for the active feature. Auto-loops scan→build→rescan until ACs satisfied (--max N for safety, --auto to skip per-iteration approval). DO NOT trigger when the feature has no prototype yet (use cap:prototype), when only minor edits are needed (just edit directly), or when the user is in a **Frontend Sprint** loop on UI files (visual tweaks on .tsx/.jsx/.css — handle directly, run cap:annotate + cap:test only at sprint end).
4
+ argument-hint: "[--features NAME] [--max N] [--auto]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Edit
9
+ - Bash
10
+ - Task
11
+ - Glob
12
+ - Grep
13
+ - AskUserQuestion
14
+ ---
15
+
16
+ <!-- @cap-context CAP v2.0 iterate command -- the flagship code-first loop. Scan -> identify gaps -> generate code -> re-scan -> repeat. Human approval gate between each iteration unless --auto is specified. -->
17
+ <!-- @cap-decision Iteration loop is scan-driven: /cap:scan output determines what to build next. No upfront planning step. -->
18
+ <!-- @cap-decision Human approval gate between iterations by default. --auto flag enables autonomous loop with --max N safety limit. -->
19
+ <!-- @cap-constraint --auto mode requires --max N to prevent runaway loops. Default max is 5 if --auto specified without --max. -->
20
+
21
+ <objective>
22
+ <!-- @cap-todo(ref:AC-49) /cap:iterate shall invoke cap-prototyper in iterate mode. -->
23
+
24
+ The core code-first iteration loop:
25
+ 1. Run /cap:scan to assess current Feature Map status
26
+ 2. Identify incomplete ACs and unimplemented features
27
+ 3. Spawn cap-prototyper in ITERATE mode to address gaps
28
+ 4. Re-scan to verify progress
29
+ 5. Present results to user, ask to continue or stop
30
+
31
+ **Arguments:**
32
+ - `--features NAME` -- scope iteration to specific Feature Map entries
33
+ - `--max N` -- maximum number of iterations (default 5 with --auto)
34
+ - `--auto` -- autonomous mode, no approval gate between iterations
35
+ </objective>
36
+
37
+ <context>
38
+ $ARGUMENTS
39
+
40
+ @FEATURE-MAP.md
41
+ @.cap/SESSION.json
42
+ </context>
43
+
44
+ <process>
45
+
46
+ ## Step 0: Parse flags
47
+
48
+ <!-- @cap-todo(ref:AC-50) /cap:iterate shall support a --auto flag for multi-iteration autonomous loops. -->
49
+
50
+ Check `$ARGUMENTS` for:
51
+ - `--features NAME` -- if present, store as `feature_filter`
52
+ - `--max N` -- if present, store as `max_iterations` (default: 5)
53
+ - `--auto` -- if present, set `auto_mode = true`
54
+
55
+ If `auto_mode` is true and `max_iterations` is not set: `max_iterations = 5`
56
+
57
+ Log: "cap:iterate | mode: {auto or manual} | max: {max_iterations} | features: {feature_filter or 'all'}"
58
+
59
+ ## Step 1: Load active feature from session
60
+
61
+ <!-- @cap-todo(ref:AC-51) /cap:iterate shall read the current feature from SESSION.json and refine the associated prototype. -->
62
+
63
+ ```bash
64
+ node -e "
65
+ const session = require('./cap/bin/lib/cap-session.cjs');
66
+ const fm = require('./cap/bin/lib/cap-feature-map.cjs');
67
+ const s = session.loadSession(process.cwd());
68
+ // @cap-todo(ac:F-081/AC-4 iter:2) Migrated to {safe: true} opt-in to preserve CLI on duplicate-ID FEATURE-MAP.
69
+ // @cap-decision(F-081/iter2) Warn on parseError; continue with partial map for read-only display.
70
+ const featureMap = fm.readFeatureMap(process.cwd(), undefined, { safe: true });
71
+ if (featureMap && featureMap.parseError) {
72
+ console.warn('cap: iterate — duplicate feature ID detected, target list uses partial map: ' + String(featureMap.parseError.message).trim());
73
+ }
74
+ console.log(JSON.stringify({
75
+ activeFeature: s.activeFeature,
76
+ features: featureMap.features.map(f => ({
77
+ id: f.id, title: f.title, state: f.state,
78
+ acs: f.acs, files: f.files, dependencies: f.dependencies
79
+ }))
80
+ }));
81
+ "
82
+ ```
83
+
84
+ **Scope features:**
85
+ - If `feature_filter` is set: filter to matching IDs
86
+ - Else if active feature is set: use only that feature
87
+ - Else: use all features not in `shipped` state
88
+
89
+ Store as `target_features`.
90
+
91
+ Initialize: `ITERATION = 0`
92
+
93
+ ## Step 2: Run scan and identify gaps (loop start)
94
+
95
+ ```bash
96
+ node -e "
97
+ const scanner = require('./cap/bin/lib/cap-tag-scanner.cjs');
98
+ const fm = require('./cap/bin/lib/cap-feature-map.cjs');
99
+ const tags = scanner.scanDirectory(process.cwd());
100
+ // @cap-todo(ac:F-081/AC-4 iter:2) Migrated to {safe: true} opt-in to preserve CLI on duplicate-ID FEATURE-MAP.
101
+ // @cap-decision(F-081/iter2) Warn on parseError; continue with partial map for read-only display.
102
+ const featureMap = fm.readFeatureMap(process.cwd(), undefined, { safe: true });
103
+ if (featureMap && featureMap.parseError) {
104
+ console.warn('cap: iterate scan — duplicate feature ID detected, gap report uses partial map: ' + String(featureMap.parseError.message).trim());
105
+ }
106
+
107
+ // Identify ACs that are still pending
108
+ const gaps = [];
109
+ const targetIds = new Set({JSON.stringify(target_feature_ids)});
110
+ for (const f of featureMap.features) {
111
+ if (!targetIds.has(f.id)) continue;
112
+ for (const ac of f.acs) {
113
+ if (ac.status === 'pending') {
114
+ gaps.push({ featureId: f.id, featureTitle: f.title, acId: ac.id, acDesc: ac.description });
115
+ }
116
+ }
117
+ }
118
+
119
+ // Count @cap-todo tags
120
+ const todoTags = tags.filter(t => t.type === 'todo');
121
+
122
+ console.log(JSON.stringify({
123
+ totalTags: tags.length,
124
+ todoCount: todoTags.length,
125
+ gapCount: gaps.length,
126
+ gaps: gaps
127
+ }));
128
+ "
129
+ ```
130
+
131
+ Store as `scan_result`.
132
+
133
+ **If `scan_result.gapCount == 0`:**
134
+ Log: "All acceptance criteria resolved after {ITERATION} iteration(s)."
135
+ Proceed to Step 6.
136
+
137
+ **If `ITERATION == max_iterations`:**
138
+ Log: "Iteration cap ({max_iterations}) reached. {scan_result.gapCount} ACs remain unresolved."
139
+ Proceed to Step 6.
140
+
141
+ ## Step 3: Spawn cap-prototyper in ITERATE mode
142
+
143
+ Increment `ITERATION`.
144
+
145
+ Log: "--- Iteration {ITERATION}/{max_iterations} --- ({scan_result.gapCount} ACs remaining)"
146
+
147
+ Spawn `cap-prototyper` via Task tool:
148
+
149
+ ```
150
+ $ARGUMENTS
151
+
152
+ **MODE: ITERATE**
153
+
154
+ **Iteration {ITERATION} of {max_iterations}**
155
+
156
+ **Gaps to address (unresolved ACs):**
157
+ {For each gap:}
158
+ {gap.featureId}/{gap.acId}: {gap.acDesc}
159
+ {End for}
160
+
161
+ **Target features:**
162
+ {For each target_feature:}
163
+ Feature: {feature.id} - {feature.title} [{feature.state}]
164
+ Files: {feature.files.join(', ') or 'none yet'}
165
+ {For each AC:}
166
+ {ac.id}: {ac.description} [{ac.status}]
167
+ {End for}
168
+ {End for}
169
+
170
+ **Instructions:**
171
+ 1. Read the existing code files listed under each feature
172
+ 2. Address the unresolved ACs by implementing or refining code
173
+ 3. Add @cap-feature(feature:{ID}) tags to new code
174
+ 4. Add @cap-todo(ac:{FEATURE-ID}/AC-N) tags where ACs are implemented
175
+ 5. Update existing @cap-todo tags that are now resolved
176
+ 6. Do NOT break existing passing tests
177
+
178
+ **ALWAYS use the Write tool to create files** -- never use heredoc commands.
179
+ ```
180
+
181
+ Wait for cap-prototyper to complete.
182
+
183
+ ## Step 4: Re-scan after iteration
184
+
185
+ ```bash
186
+ node -e "
187
+ const scanner = require('./cap/bin/lib/cap-tag-scanner.cjs');
188
+ const fm = require('./cap/bin/lib/cap-feature-map.cjs');
189
+ const tags = scanner.scanDirectory(process.cwd());
190
+ fm.enrichFromTags(process.cwd(), tags);
191
+ // @cap-todo(ac:F-081/AC-4 iter:2) Migrated to {safe: true} opt-in to preserve CLI on duplicate-ID FEATURE-MAP.
192
+ // @cap-decision(F-081/iter2) Warn on parseError; continue with partial map for read-only display.
193
+ const featureMap = fm.readFeatureMap(process.cwd(), undefined, { safe: true });
194
+ if (featureMap && featureMap.parseError) {
195
+ console.warn('cap: iterate re-scan — duplicate feature ID detected, remaining count uses partial map: ' + String(featureMap.parseError.message).trim());
196
+ }
197
+ const targetIds = new Set({JSON.stringify(target_feature_ids)});
198
+ let remaining = 0;
199
+ for (const f of featureMap.features) {
200
+ if (!targetIds.has(f.id)) continue;
201
+ remaining += f.acs.filter(a => a.status === 'pending').length;
202
+ }
203
+ console.log(JSON.stringify({ totalTags: tags.length, acsRemaining: remaining }));
204
+ "
205
+ ```
206
+
207
+ Log: "Iteration {ITERATION} complete. ACs remaining: {acsRemaining}"
208
+
209
+ ## Step 5: Approval gate or auto-continue
210
+
211
+ **If `auto_mode`:** Loop back to Step 2.
212
+
213
+ **If NOT `auto_mode`:**
214
+
215
+ Use AskUserQuestion:
216
+ > "Iteration {ITERATION} complete. {acsRemaining} ACs remaining. Continue to next iteration? [yes / stop / redirect: instructions]"
217
+
218
+ - If `yes`: Loop back to Step 2
219
+ - If `stop`: Proceed to Step 6
220
+ - If `redirect: <instructions>`: Store instructions as additional context for next iteration, loop back to Step 2
221
+
222
+ ## Step 6: Final report
223
+
224
+ ```bash
225
+ node -e "
226
+ const session = require('./cap/bin/lib/cap-session.cjs');
227
+ session.updateSession(process.cwd(), {
228
+ lastCommand: '/cap:iterate',
229
+ lastCommandTimestamp: new Date().toISOString(),
230
+ step: 'iterate-complete'
231
+ });
232
+ "
233
+ ```
234
+
235
+ ```
236
+ cap:iterate complete.
237
+
238
+ Mode: {auto or manual}
239
+ Iterations used: {ITERATION} of {max_iterations}
240
+ ACs remaining: {acsRemaining}
241
+
242
+ {If acsRemaining > 0:}
243
+ Run /cap:iterate to continue, or /cap:iterate --auto for autonomous mode.
244
+ {Else:}
245
+ All ACs resolved. Run /cap:test to write tests, or /cap:review to verify.
246
+ {End if}
247
+ ```
248
+
249
+ </process>