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,1241 @@
1
+ /**
2
+ * Core — Shared utilities, constants, and internal helpers
3
+ */
4
+ // @cap-feature(feature:F-011) Legacy GSD Modules — core shared utilities, path helpers, config loading, git operations
5
+
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { execSync, execFileSync, spawnSync } = require('child_process');
9
+ const { MODEL_PROFILES } = require('./model-profiles.cjs');
10
+
11
+ // ─── Path helpers ────────────────────────────────────────────────────────────
12
+
13
+ /** Normalize a relative path to always use forward slashes (cross-platform). */
14
+ function toPosixPath(p) {
15
+ return p.split(path.sep).join('/');
16
+ }
17
+
18
+ /**
19
+ * Scan immediate child directories for separate git repos.
20
+ * Returns a sorted array of directory names that have their own `.git`.
21
+ * Excludes hidden directories and node_modules.
22
+ */
23
+ function detectSubRepos(cwd) {
24
+ const results = [];
25
+ try {
26
+ const entries = fs.readdirSync(cwd, { withFileTypes: true });
27
+ for (const entry of entries) {
28
+ if (!entry.isDirectory()) continue;
29
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
30
+ const gitPath = path.join(cwd, entry.name, '.git');
31
+ try {
32
+ if (fs.existsSync(gitPath)) {
33
+ results.push(entry.name);
34
+ }
35
+ } catch {}
36
+ }
37
+ } catch {}
38
+ return results.sort();
39
+ }
40
+
41
+ /**
42
+ * Walk up from `startDir` to find the project root that owns `.planning/`.
43
+ *
44
+ * In multi-repo workspaces, Claude may open inside a sub-repo (e.g. `backend/`)
45
+ * instead of the project root. This function prevents `.planning/` from being
46
+ * created inside the sub-repo by locating the nearest ancestor that already has
47
+ * a `.planning/` directory.
48
+ *
49
+ * Detection strategy (checked in order for each ancestor):
50
+ * 1. Parent has `.planning/config.json` with `sub_repos` listing this directory
51
+ * 2. Parent has `.planning/config.json` with `multiRepo: true` (legacy format)
52
+ * 3. Parent has `.planning/` and current dir has its own `.git` (heuristic)
53
+ *
54
+ * Returns `startDir` unchanged when no ancestor `.planning/` is found (first-run
55
+ * or single-repo projects).
56
+ */
57
+ function findProjectRoot(startDir) {
58
+ const resolved = path.resolve(startDir);
59
+ const root = path.parse(resolved).root;
60
+ const homedir = require('os').homedir();
61
+
62
+ // If startDir already contains .planning/, it IS the project root.
63
+ // Do not walk up to a parent workspace that also has .planning/ (#1362).
64
+ const ownPlanning = path.join(resolved, '.planning');
65
+ if (fs.existsSync(ownPlanning) && fs.statSync(ownPlanning).isDirectory()) {
66
+ return startDir;
67
+ }
68
+
69
+ // Check if startDir or any of its ancestors (up to AND including the
70
+ // candidate project root) contains a .git directory. This handles both
71
+ // `backend/` (direct sub-repo) and `backend/src/modules/` (nested inside),
72
+ // as well as the common case where .git lives at the same level as .planning/.
73
+ function isInsideGitRepo(candidateParent) {
74
+ let d = resolved;
75
+ while (d !== root) {
76
+ if (fs.existsSync(path.join(d, '.git'))) return true;
77
+ if (d === candidateParent) break;
78
+ d = path.dirname(d);
79
+ }
80
+ return false;
81
+ }
82
+
83
+ let dir = resolved;
84
+ while (dir !== root) {
85
+ const parent = path.dirname(dir);
86
+ if (parent === dir) break; // filesystem root
87
+ if (parent === homedir) break; // never go above home
88
+
89
+ const parentPlanning = path.join(parent, '.planning');
90
+ if (fs.existsSync(parentPlanning) && fs.statSync(parentPlanning).isDirectory()) {
91
+ const configPath = path.join(parentPlanning, 'config.json');
92
+ try {
93
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
94
+ const subRepos = config.sub_repos || config.planning?.sub_repos || [];
95
+
96
+ // Check explicit sub_repos list
97
+ if (Array.isArray(subRepos) && subRepos.length > 0) {
98
+ const relPath = path.relative(parent, resolved);
99
+ const topSegment = relPath.split(path.sep)[0];
100
+ if (subRepos.includes(topSegment)) {
101
+ return parent;
102
+ }
103
+ }
104
+
105
+ // Check legacy multiRepo flag
106
+ if (config.multiRepo === true && isInsideGitRepo(parent)) {
107
+ return parent;
108
+ }
109
+ } catch {
110
+ // config.json missing or malformed — fall back to .git heuristic
111
+ }
112
+
113
+ // Heuristic: parent has .planning/ and we're inside a git repo
114
+ if (isInsideGitRepo(parent)) {
115
+ return parent;
116
+ }
117
+ }
118
+ dir = parent;
119
+ }
120
+ return startDir;
121
+ }
122
+
123
+ // ─── Output helpers ───────────────────────────────────────────────────────────
124
+
125
+ /**
126
+ * Remove stale gsd-* temp files/dirs older than maxAgeMs (default: 5 minutes).
127
+ * Runs opportunistically before each new temp file write to prevent unbounded accumulation.
128
+ * @param {string} prefix - filename prefix to match (e.g., 'gsd-')
129
+ * @param {object} opts
130
+ * @param {number} opts.maxAgeMs - max age in ms before removal (default: 5 min)
131
+ * @param {boolean} opts.dirsOnly - if true, only remove directories (default: false)
132
+ */
133
+ function reapStaleTempFiles(prefix = 'gsd-', { maxAgeMs = 5 * 60 * 1000, dirsOnly = false } = {}) {
134
+ try {
135
+ const tmpDir = require('os').tmpdir();
136
+ const now = Date.now();
137
+ const entries = fs.readdirSync(tmpDir);
138
+ for (const entry of entries) {
139
+ if (!entry.startsWith(prefix)) continue;
140
+ const fullPath = path.join(tmpDir, entry);
141
+ try {
142
+ const stat = fs.statSync(fullPath);
143
+ if (now - stat.mtimeMs > maxAgeMs) {
144
+ if (stat.isDirectory()) {
145
+ fs.rmSync(fullPath, { recursive: true, force: true });
146
+ } else if (!dirsOnly) {
147
+ fs.unlinkSync(fullPath);
148
+ }
149
+ }
150
+ } catch {
151
+ // File may have been removed between readdir and stat — ignore
152
+ }
153
+ }
154
+ } catch {
155
+ // Non-critical — don't let cleanup failures break output
156
+ }
157
+ }
158
+
159
+ function output(result, raw, rawValue) {
160
+ let data;
161
+ if (raw && rawValue !== undefined) {
162
+ data = String(rawValue);
163
+ } else {
164
+ const json = JSON.stringify(result, null, 2);
165
+ // Large payloads exceed Claude Code's Bash tool buffer (~50KB).
166
+ // Write to tmpfile and output the path prefixed with @file: so callers can detect it.
167
+ if (json.length > 50000) {
168
+ reapStaleTempFiles();
169
+ const tmpPath = path.join(require('os').tmpdir(), `gsd-${Date.now()}.json`);
170
+ fs.writeFileSync(tmpPath, json, 'utf-8');
171
+ data = '@file:' + tmpPath;
172
+ } else {
173
+ data = json;
174
+ }
175
+ }
176
+ // process.stdout.write() is async when stdout is a pipe — process.exit()
177
+ // can tear down the process before the reader consumes the buffer.
178
+ // fs.writeSync(1, ...) blocks until the kernel accepts the bytes, and
179
+ // skipping process.exit() lets the event loop drain naturally.
180
+ fs.writeSync(1, data);
181
+ }
182
+
183
+ function error(message) {
184
+ fs.writeSync(2, 'Error: ' + message + '\n');
185
+ process.exit(1);
186
+ }
187
+
188
+ // ─── File & Config utilities ──────────────────────────────────────────────────
189
+
190
+ function safeReadFile(filePath) {
191
+ try {
192
+ return fs.readFileSync(filePath, 'utf-8');
193
+ } catch {
194
+ return null;
195
+ }
196
+ }
197
+
198
+ function loadConfig(cwd) {
199
+ const configPath = path.join(cwd, '.planning', 'config.json');
200
+ const defaults = {
201
+ model_profile: 'balanced',
202
+ commit_docs: true,
203
+ search_gitignored: false,
204
+ branching_strategy: 'none',
205
+ phase_branch_template: 'gsd/phase-{phase}-{slug}',
206
+ milestone_branch_template: 'gsd/{milestone}-{slug}',
207
+ quick_branch_template: null,
208
+ research: true,
209
+ plan_checker: true,
210
+ verifier: true,
211
+ nyquist_validation: true,
212
+ parallelization: true,
213
+ brave_search: false,
214
+ firecrawl: false,
215
+ exa_search: false,
216
+ text_mode: false, // when true, use plain-text numbered lists instead of AskUserQuestion menus
217
+ sub_repos: [],
218
+ resolve_model_ids: false, // false: return alias as-is | true: map to full Claude model ID | "omit": return '' (runtime uses its default)
219
+ context_window: 200000, // default 200k; set to 1000000 for Opus/Sonnet 4.6 1M models
220
+ phase_naming: 'sequential', // 'sequential' (default, auto-increment) or 'custom' (arbitrary string IDs)
221
+ };
222
+
223
+ try {
224
+ const raw = fs.readFileSync(configPath, 'utf-8');
225
+ const parsed = JSON.parse(raw);
226
+
227
+ // Migrate deprecated "depth" key to "granularity" with value mapping
228
+ if ('depth' in parsed && !('granularity' in parsed)) {
229
+ const depthToGranularity = { quick: 'coarse', standard: 'standard', comprehensive: 'fine' };
230
+ parsed.granularity = depthToGranularity[parsed.depth] || parsed.depth;
231
+ delete parsed.depth;
232
+ try { fs.writeFileSync(configPath, JSON.stringify(parsed, null, 2), 'utf-8'); } catch { /* intentionally empty */ }
233
+ }
234
+
235
+ // Auto-detect and sync sub_repos: scan for child directories with .git
236
+ let configDirty = false;
237
+
238
+ // Migrate legacy "multiRepo: true" boolean → sub_repos array
239
+ if (parsed.multiRepo === true && !parsed.sub_repos && !parsed.planning?.sub_repos) {
240
+ const detected = detectSubRepos(cwd);
241
+ if (detected.length > 0) {
242
+ parsed.sub_repos = detected;
243
+ if (!parsed.planning) parsed.planning = {};
244
+ parsed.planning.commit_docs = false;
245
+ delete parsed.multiRepo;
246
+ configDirty = true;
247
+ }
248
+ }
249
+
250
+ // Keep sub_repos in sync with actual filesystem
251
+ const currentSubRepos = parsed.sub_repos || parsed.planning?.sub_repos || [];
252
+ if (Array.isArray(currentSubRepos) && currentSubRepos.length > 0) {
253
+ const detected = detectSubRepos(cwd);
254
+ if (detected.length > 0) {
255
+ const sorted = [...currentSubRepos].sort();
256
+ if (JSON.stringify(sorted) !== JSON.stringify(detected)) {
257
+ parsed.sub_repos = detected;
258
+ configDirty = true;
259
+ }
260
+ }
261
+ }
262
+
263
+ // Persist sub_repos changes (migration or sync)
264
+ if (configDirty) {
265
+ try { fs.writeFileSync(configPath, JSON.stringify(parsed, null, 2), 'utf-8'); } catch {}
266
+ }
267
+
268
+ const get = (key, nested) => {
269
+ if (parsed[key] !== undefined) return parsed[key];
270
+ if (nested && parsed[nested.section] && parsed[nested.section][nested.field] !== undefined) {
271
+ return parsed[nested.section][nested.field];
272
+ }
273
+ return undefined;
274
+ };
275
+
276
+ const parallelization = (() => {
277
+ const val = get('parallelization');
278
+ if (typeof val === 'boolean') return val;
279
+ if (typeof val === 'object' && val !== null && 'enabled' in val) return val.enabled;
280
+ return defaults.parallelization;
281
+ })();
282
+
283
+ return {
284
+ model_profile: get('model_profile') ?? defaults.model_profile,
285
+ commit_docs: (() => {
286
+ const explicit = get('commit_docs', { section: 'planning', field: 'commit_docs' });
287
+ // If explicitly set in config, respect the user's choice
288
+ if (explicit !== undefined) return explicit;
289
+ // Auto-detection: when no explicit value and .planning/ is gitignored,
290
+ // default to false instead of true
291
+ if (isGitIgnored(cwd, '.planning/')) return false;
292
+ return defaults.commit_docs;
293
+ })(),
294
+ search_gitignored: get('search_gitignored', { section: 'planning', field: 'search_gitignored' }) ?? defaults.search_gitignored,
295
+ branching_strategy: get('branching_strategy', { section: 'git', field: 'branching_strategy' }) ?? defaults.branching_strategy,
296
+ phase_branch_template: get('phase_branch_template', { section: 'git', field: 'phase_branch_template' }) ?? defaults.phase_branch_template,
297
+ milestone_branch_template: get('milestone_branch_template', { section: 'git', field: 'milestone_branch_template' }) ?? defaults.milestone_branch_template,
298
+ quick_branch_template: get('quick_branch_template', { section: 'git', field: 'quick_branch_template' }) ?? defaults.quick_branch_template,
299
+ research: get('research', { section: 'workflow', field: 'research' }) ?? defaults.research,
300
+ plan_checker: get('plan_checker', { section: 'workflow', field: 'plan_check' }) ?? defaults.plan_checker,
301
+ verifier: get('verifier', { section: 'workflow', field: 'verifier' }) ?? defaults.verifier,
302
+ nyquist_validation: get('nyquist_validation', { section: 'workflow', field: 'nyquist_validation' }) ?? defaults.nyquist_validation,
303
+ parallelization,
304
+ brave_search: get('brave_search') ?? defaults.brave_search,
305
+ firecrawl: get('firecrawl') ?? defaults.firecrawl,
306
+ exa_search: get('exa_search') ?? defaults.exa_search,
307
+ text_mode: get('text_mode', { section: 'workflow', field: 'text_mode' }) ?? defaults.text_mode,
308
+ sub_repos: get('sub_repos', { section: 'planning', field: 'sub_repos' }) ?? defaults.sub_repos,
309
+ resolve_model_ids: get('resolve_model_ids') ?? defaults.resolve_model_ids,
310
+ context_window: get('context_window') ?? defaults.context_window,
311
+ phase_naming: get('phase_naming') ?? defaults.phase_naming,
312
+ model_overrides: parsed.model_overrides || null,
313
+ agent_skills: parsed.agent_skills || {},
314
+ };
315
+ } catch {
316
+ return defaults;
317
+ }
318
+ }
319
+
320
+ // ─── Git utilities ────────────────────────────────────────────────────────────
321
+
322
+ function isGitIgnored(cwd, targetPath) {
323
+ try {
324
+ // --no-index checks .gitignore rules regardless of whether the file is tracked.
325
+ // Without it, git check-ignore returns "not ignored" for tracked files even when
326
+ // .gitignore explicitly lists them — a common source of confusion when .planning/
327
+ // was committed before being added to .gitignore.
328
+ // Use execFileSync (array args) to prevent shell interpretation of special characters
329
+ // in file paths — avoids command injection via crafted path names.
330
+ execFileSync('git', ['check-ignore', '-q', '--no-index', '--', targetPath], {
331
+ cwd,
332
+ stdio: 'pipe',
333
+ });
334
+ return true;
335
+ } catch {
336
+ return false;
337
+ }
338
+ }
339
+
340
+ // ─── Markdown normalization ─────────────────────────────────────────────────
341
+
342
+ /**
343
+ * Normalize markdown to fix common markdownlint violations.
344
+ * Applied at write points so GSD-generated .planning/ files are IDE-friendly.
345
+ *
346
+ * Rules enforced:
347
+ * MD022 — Blank lines around headings
348
+ * MD031 — Blank lines around fenced code blocks
349
+ * MD032 — Blank lines around lists
350
+ * MD012 — No multiple consecutive blank lines (collapsed to 2 max)
351
+ * MD047 — Files end with a single newline
352
+ */
353
+ function normalizeMd(content) {
354
+ if (!content || typeof content !== 'string') return content;
355
+
356
+ // Normalize line endings to LF for consistent processing
357
+ let text = content.replace(/\r\n/g, '\n');
358
+
359
+ const lines = text.split('\n');
360
+ const result = [];
361
+
362
+ for (let i = 0; i < lines.length; i++) {
363
+ const line = lines[i];
364
+ const prev = i > 0 ? lines[i - 1] : '';
365
+ const prevTrimmed = prev.trimEnd();
366
+ const trimmed = line.trimEnd();
367
+
368
+ // MD022: Blank line before headings (skip first line and frontmatter delimiters)
369
+ if (/^#{1,6}\s/.test(trimmed) && i > 0 && prevTrimmed !== '' && prevTrimmed !== '---') {
370
+ result.push('');
371
+ }
372
+
373
+ // MD031: Blank line before fenced code blocks
374
+ if (/^```/.test(trimmed) && i > 0 && prevTrimmed !== '' && !isInsideFencedBlock(lines, i)) {
375
+ result.push('');
376
+ }
377
+
378
+ // MD032: Blank line before lists (- item, * item, N. item, - [ ] item)
379
+ if (/^(\s*[-*+]\s|\s*\d+\.\s)/.test(line) && i > 0 &&
380
+ prevTrimmed !== '' && !/^(\s*[-*+]\s|\s*\d+\.\s)/.test(prev) &&
381
+ prevTrimmed !== '---') {
382
+ result.push('');
383
+ }
384
+
385
+ result.push(line);
386
+
387
+ // MD022: Blank line after headings
388
+ if (/^#{1,6}\s/.test(trimmed) && i < lines.length - 1) {
389
+ const next = lines[i + 1];
390
+ if (next !== undefined && next.trimEnd() !== '') {
391
+ result.push('');
392
+ }
393
+ }
394
+
395
+ // MD031: Blank line after closing fenced code blocks
396
+ if (/^```\s*$/.test(trimmed) && isClosingFence(lines, i) && i < lines.length - 1) {
397
+ const next = lines[i + 1];
398
+ if (next !== undefined && next.trimEnd() !== '') {
399
+ result.push('');
400
+ }
401
+ }
402
+
403
+ // MD032: Blank line after last list item in a block
404
+ if (/^(\s*[-*+]\s|\s*\d+\.\s)/.test(line) && i < lines.length - 1) {
405
+ const next = lines[i + 1];
406
+ if (next !== undefined && next.trimEnd() !== '' &&
407
+ !/^(\s*[-*+]\s|\s*\d+\.\s)/.test(next) &&
408
+ !/^\s/.test(next)) {
409
+ // Only add blank line if next line is not a continuation/indented line
410
+ result.push('');
411
+ }
412
+ }
413
+ }
414
+
415
+ text = result.join('\n');
416
+
417
+ // MD012: Collapse 3+ consecutive blank lines to 2
418
+ text = text.replace(/\n{3,}/g, '\n\n');
419
+
420
+ // MD047: Ensure file ends with exactly one newline
421
+ text = text.replace(/\n*$/, '\n');
422
+
423
+ return text;
424
+ }
425
+
426
+ /** Check if line index i is inside an already-open fenced code block */
427
+ function isInsideFencedBlock(lines, i) {
428
+ let fenceCount = 0;
429
+ for (let j = 0; j < i; j++) {
430
+ if (/^```/.test(lines[j].trimEnd())) fenceCount++;
431
+ }
432
+ return fenceCount % 2 === 1;
433
+ }
434
+
435
+ /** Check if a ``` line is a closing fence (odd number of fences up to and including this one) */
436
+ function isClosingFence(lines, i) {
437
+ let fenceCount = 0;
438
+ for (let j = 0; j <= i; j++) {
439
+ if (/^```/.test(lines[j].trimEnd())) fenceCount++;
440
+ }
441
+ return fenceCount % 2 === 0;
442
+ }
443
+
444
+ function execGit(cwd, args) {
445
+ const result = spawnSync('git', args, {
446
+ cwd,
447
+ stdio: 'pipe',
448
+ encoding: 'utf-8',
449
+ });
450
+ return {
451
+ exitCode: result.status ?? 1,
452
+ stdout: (result.stdout ?? '').toString().trim(),
453
+ stderr: (result.stderr ?? '').toString().trim(),
454
+ };
455
+ }
456
+
457
+ // ─── Common path helpers ──────────────────────────────────────────────────────
458
+
459
+ /**
460
+ * Resolve the main worktree root when running inside a git worktree.
461
+ * In a linked worktree, .planning/ lives in the main worktree, not in the linked one.
462
+ * Returns the main worktree path, or cwd if not in a worktree.
463
+ */
464
+ function resolveWorktreeRoot(cwd) {
465
+ // If the current directory already has its own .planning/, respect it.
466
+ // This handles linked worktrees with independent planning state (e.g., Conductor workspaces).
467
+ if (fs.existsSync(path.join(cwd, '.planning'))) {
468
+ return cwd;
469
+ }
470
+
471
+ // Check if we're in a linked worktree
472
+ const gitDir = execGit(cwd, ['rev-parse', '--git-dir']);
473
+ const commonDir = execGit(cwd, ['rev-parse', '--git-common-dir']);
474
+
475
+ if (gitDir.exitCode !== 0 || commonDir.exitCode !== 0) return cwd;
476
+
477
+ // In a linked worktree, .git is a file pointing to .git/worktrees/<name>
478
+ // and git-common-dir points to the main repo's .git directory
479
+ const gitDirResolved = path.resolve(cwd, gitDir.stdout);
480
+ const commonDirResolved = path.resolve(cwd, commonDir.stdout);
481
+
482
+ if (gitDirResolved !== commonDirResolved) {
483
+ // We're in a linked worktree — resolve main worktree root
484
+ // The common dir is the main repo's .git, so its parent is the main worktree root
485
+ return path.dirname(commonDirResolved);
486
+ }
487
+
488
+ return cwd;
489
+ }
490
+
491
+ /**
492
+ * Acquire a file-based lock for .planning/ writes.
493
+ * Prevents concurrent worktrees from corrupting shared planning files.
494
+ * Lock is auto-released after the callback completes.
495
+ */
496
+ function withPlanningLock(cwd, fn) {
497
+ const lockPath = path.join(planningDir(cwd), '.lock');
498
+ const lockTimeout = 10000; // 10 seconds
499
+ const retryDelay = 100;
500
+ const start = Date.now();
501
+
502
+ // Ensure .planning/ exists
503
+ try { fs.mkdirSync(planningDir(cwd), { recursive: true }); } catch { /* ok */ }
504
+
505
+ while (Date.now() - start < lockTimeout) {
506
+ try {
507
+ // Atomic create — fails if file exists
508
+ fs.writeFileSync(lockPath, JSON.stringify({
509
+ pid: process.pid,
510
+ cwd,
511
+ acquired: new Date().toISOString(),
512
+ }), { flag: 'wx' });
513
+
514
+ // Lock acquired — run the function
515
+ try {
516
+ return fn();
517
+ } finally {
518
+ try { fs.unlinkSync(lockPath); } catch { /* already released */ }
519
+ }
520
+ } catch (err) {
521
+ if (err.code === 'EEXIST') {
522
+ // Lock exists — check if stale (>30s old)
523
+ try {
524
+ const stat = fs.statSync(lockPath);
525
+ if (Date.now() - stat.mtimeMs > 30000) {
526
+ fs.unlinkSync(lockPath);
527
+ continue; // retry
528
+ }
529
+ } catch { continue; }
530
+
531
+ // Wait and retry
532
+ spawnSync('sleep', ['0.1'], { stdio: 'ignore' });
533
+ continue;
534
+ }
535
+ throw err;
536
+ }
537
+ }
538
+ // Timeout — force acquire (stale lock recovery)
539
+ try { fs.unlinkSync(lockPath); } catch { /* ok */ }
540
+ return fn();
541
+ }
542
+
543
+ /**
544
+ * Get the .planning directory path, workstream-aware.
545
+ * When a workstream is active (via explicit ws arg or GSD_WORKSTREAM env var),
546
+ * returns `.planning/workstreams/{ws}/`. Otherwise returns `.planning/`.
547
+ *
548
+ * @param {string} cwd - project root
549
+ * @param {string} [ws] - explicit workstream name; if omitted, checks GSD_WORKSTREAM env var
550
+ */
551
+ function planningDir(cwd, ws) {
552
+ if (ws === undefined) ws = process.env.GSD_WORKSTREAM || null;
553
+ if (!ws) return path.join(cwd, '.planning');
554
+ return path.join(cwd, '.planning', 'workstreams', ws);
555
+ }
556
+
557
+ /** Always returns the root .planning/ path, ignoring workstreams. For shared resources. */
558
+ function planningRoot(cwd) {
559
+ return path.join(cwd, '.planning');
560
+ }
561
+
562
+ /**
563
+ * Get common .planning file paths, workstream-aware.
564
+ * Scoped paths (state, roadmap, phases, requirements) resolve to the active workstream.
565
+ * Shared paths (project, config) always resolve to the root .planning/.
566
+ */
567
+ function planningPaths(cwd, ws) {
568
+ const base = planningDir(cwd, ws);
569
+ const root = path.join(cwd, '.planning');
570
+ return {
571
+ planning: base,
572
+ state: path.join(base, 'STATE.md'),
573
+ roadmap: path.join(base, 'ROADMAP.md'),
574
+ project: path.join(root, 'PROJECT.md'),
575
+ config: path.join(root, 'config.json'),
576
+ phases: path.join(base, 'phases'),
577
+ requirements: path.join(base, 'REQUIREMENTS.md'),
578
+ };
579
+ }
580
+
581
+ // ─── Active Workstream Detection ─────────────────────────────────────────────
582
+
583
+ /**
584
+ * Get the active workstream name from .planning/active-workstream file.
585
+ * Returns null if no active workstream or file doesn't exist.
586
+ */
587
+ function getActiveWorkstream(cwd) {
588
+ const filePath = path.join(planningRoot(cwd), 'active-workstream');
589
+ try {
590
+ const name = fs.readFileSync(filePath, 'utf-8').trim();
591
+ if (!name || !/^[a-zA-Z0-9_-]+$/.test(name)) return null;
592
+ const wsDir = path.join(planningRoot(cwd), 'workstreams', name);
593
+ if (!fs.existsSync(wsDir)) return null;
594
+ return name;
595
+ } catch {
596
+ return null;
597
+ }
598
+ }
599
+
600
+ /**
601
+ * Set the active workstream. Pass null to clear.
602
+ */
603
+ function setActiveWorkstream(cwd, name) {
604
+ const filePath = path.join(planningRoot(cwd), 'active-workstream');
605
+ if (!name) {
606
+ try { fs.unlinkSync(filePath); } catch {}
607
+ return;
608
+ }
609
+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
610
+ throw new Error('Invalid workstream name: must be alphanumeric, hyphens, and underscores only');
611
+ }
612
+ fs.writeFileSync(filePath, name + '\n', 'utf-8');
613
+ }
614
+
615
+ // ─── Phase utilities ──────────────────────────────────────────────────────────
616
+
617
+ function escapeRegex(value) {
618
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
619
+ }
620
+
621
+ function normalizePhaseName(phase) {
622
+ const str = String(phase);
623
+ // Standard numeric phases: 1, 01, 12A, 12.1
624
+ const match = str.match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
625
+ if (match) {
626
+ const padded = match[1].padStart(2, '0');
627
+ const letter = match[2] ? match[2].toUpperCase() : '';
628
+ const decimal = match[3] || '';
629
+ return padded + letter + decimal;
630
+ }
631
+ // Custom phase IDs (e.g. PROJ-42, AUTH-101): return as-is
632
+ return str;
633
+ }
634
+
635
+ function comparePhaseNum(a, b) {
636
+ const pa = String(a).match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
637
+ const pb = String(b).match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
638
+ // If either is non-numeric (custom ID), fall back to string comparison
639
+ if (!pa || !pb) return String(a).localeCompare(String(b));
640
+ const intDiff = parseInt(pa[1], 10) - parseInt(pb[1], 10);
641
+ if (intDiff !== 0) return intDiff;
642
+ // No letter sorts before letter: 12 < 12A < 12B
643
+ const la = (pa[2] || '').toUpperCase();
644
+ const lb = (pb[2] || '').toUpperCase();
645
+ if (la !== lb) {
646
+ if (!la) return -1;
647
+ if (!lb) return 1;
648
+ return la < lb ? -1 : 1;
649
+ }
650
+ // Segment-by-segment decimal comparison: 12A < 12A.1 < 12A.1.2 < 12A.2
651
+ const aDecParts = pa[3] ? pa[3].slice(1).split('.').map(p => parseInt(p, 10)) : [];
652
+ const bDecParts = pb[3] ? pb[3].slice(1).split('.').map(p => parseInt(p, 10)) : [];
653
+ const maxLen = Math.max(aDecParts.length, bDecParts.length);
654
+ if (aDecParts.length === 0 && bDecParts.length > 0) return -1;
655
+ if (bDecParts.length === 0 && aDecParts.length > 0) return 1;
656
+ for (let i = 0; i < maxLen; i++) {
657
+ const av = Number.isFinite(aDecParts[i]) ? aDecParts[i] : 0;
658
+ const bv = Number.isFinite(bDecParts[i]) ? bDecParts[i] : 0;
659
+ if (av !== bv) return av - bv;
660
+ }
661
+ return 0;
662
+ }
663
+
664
+ function searchPhaseInDir(baseDir, relBase, normalized) {
665
+ try {
666
+ const dirs = readSubdirectories(baseDir, true);
667
+ // Match: starts with normalized (numeric) OR contains normalized as prefix segment (custom ID)
668
+ const match = dirs.find(d => {
669
+ if (d.startsWith(normalized)) return true;
670
+ // For custom IDs like PROJ-42, match case-insensitively
671
+ if (d.toUpperCase().startsWith(normalized.toUpperCase())) return true;
672
+ return false;
673
+ });
674
+ if (!match) return null;
675
+
676
+ // Extract phase number and name — supports both numeric (01-name) and custom (PROJ-42-name)
677
+ const dirMatch = match.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i)
678
+ || match.match(/^([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)*)-(.+)/i)
679
+ || [null, match, null];
680
+ const phaseNumber = dirMatch ? dirMatch[1] : normalized;
681
+ const phaseName = dirMatch && dirMatch[2] ? dirMatch[2] : null;
682
+ const phaseDir = path.join(baseDir, match);
683
+ const { plans: unsortedPlans, summaries: unsortedSummaries, hasResearch, hasContext, hasVerification, hasReviews } = getPhaseFileStats(phaseDir);
684
+ const plans = unsortedPlans.sort();
685
+ const summaries = unsortedSummaries.sort();
686
+
687
+ const completedPlanIds = new Set(
688
+ summaries.map(s => s.replace('-SUMMARY.md', '').replace('SUMMARY.md', ''))
689
+ );
690
+ const incompletePlans = plans.filter(p => {
691
+ const planId = p.replace('-PLAN.md', '').replace('PLAN.md', '');
692
+ return !completedPlanIds.has(planId);
693
+ });
694
+
695
+ return {
696
+ found: true,
697
+ directory: toPosixPath(path.join(relBase, match)),
698
+ phase_number: phaseNumber,
699
+ phase_name: phaseName,
700
+ phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
701
+ plans,
702
+ summaries,
703
+ incomplete_plans: incompletePlans,
704
+ has_research: hasResearch,
705
+ has_context: hasContext,
706
+ has_verification: hasVerification,
707
+ has_reviews: hasReviews,
708
+ };
709
+ } catch {
710
+ return null;
711
+ }
712
+ }
713
+
714
+ function findPhaseInternal(cwd, phase) {
715
+ if (!phase) return null;
716
+
717
+ const phasesDir = path.join(planningDir(cwd), 'phases');
718
+ const normalized = normalizePhaseName(phase);
719
+
720
+ // Search current phases first
721
+ const relPhasesDir = toPosixPath(path.relative(cwd, phasesDir));
722
+ const current = searchPhaseInDir(phasesDir, relPhasesDir, normalized);
723
+ if (current) return current;
724
+
725
+ // Search archived milestone phases (newest first)
726
+ const milestonesDir = path.join(cwd, '.planning', 'milestones');
727
+ if (!fs.existsSync(milestonesDir)) return null;
728
+
729
+ try {
730
+ const milestoneEntries = fs.readdirSync(milestonesDir, { withFileTypes: true });
731
+ const archiveDirs = milestoneEntries
732
+ .filter(e => e.isDirectory() && /^v[\d.]+-phases$/.test(e.name))
733
+ .map(e => e.name)
734
+ .sort()
735
+ .reverse();
736
+
737
+ for (const archiveName of archiveDirs) {
738
+ const version = archiveName.match(/^(v[\d.]+)-phases$/)[1];
739
+ const archivePath = path.join(milestonesDir, archiveName);
740
+ const relBase = '.planning/milestones/' + archiveName;
741
+ const result = searchPhaseInDir(archivePath, relBase, normalized);
742
+ if (result) {
743
+ result.archived = version;
744
+ return result;
745
+ }
746
+ }
747
+ } catch { /* intentionally empty */ }
748
+
749
+ return null;
750
+ }
751
+
752
+ function getArchivedPhaseDirs(cwd) {
753
+ const milestonesDir = path.join(cwd, '.planning', 'milestones');
754
+ const results = [];
755
+
756
+ if (!fs.existsSync(milestonesDir)) return results;
757
+
758
+ try {
759
+ const milestoneEntries = fs.readdirSync(milestonesDir, { withFileTypes: true });
760
+ // Find v*-phases directories, sort newest first
761
+ const phaseDirs = milestoneEntries
762
+ .filter(e => e.isDirectory() && /^v[\d.]+-phases$/.test(e.name))
763
+ .map(e => e.name)
764
+ .sort()
765
+ .reverse();
766
+
767
+ for (const archiveName of phaseDirs) {
768
+ const version = archiveName.match(/^(v[\d.]+)-phases$/)[1];
769
+ const archivePath = path.join(milestonesDir, archiveName);
770
+ const dirs = readSubdirectories(archivePath, true);
771
+
772
+ for (const dir of dirs) {
773
+ results.push({
774
+ name: dir,
775
+ milestone: version,
776
+ basePath: path.join('.planning', 'milestones', archiveName),
777
+ fullPath: path.join(archivePath, dir),
778
+ });
779
+ }
780
+ }
781
+ } catch { /* intentionally empty */ }
782
+
783
+ return results;
784
+ }
785
+
786
+ // ─── Roadmap milestone scoping ───────────────────────────────────────────────
787
+
788
+ /**
789
+ * Strip shipped milestone content wrapped in <details> blocks.
790
+ * Used to isolate current milestone phases when searching ROADMAP.md
791
+ * for phase headings or checkboxes — prevents matching archived milestone
792
+ * phases that share the same numbers as current milestone phases.
793
+ */
794
+ function stripShippedMilestones(content) {
795
+ return content.replace(/<details>[\s\S]*?<\/details>/gi, '');
796
+ }
797
+
798
+ /**
799
+ * Extract the current milestone section from ROADMAP.md by positive lookup.
800
+ *
801
+ * Instead of stripping <details> blocks (negative heuristic that breaks if
802
+ * agents wrap the current milestone in <details>), this finds the section
803
+ * matching the current milestone version and returns only that content.
804
+ *
805
+ * Falls back to stripShippedMilestones() if:
806
+ * - cwd is not provided
807
+ * - STATE.md doesn't exist or has no milestone field
808
+ * - Version can't be found in ROADMAP.md
809
+ *
810
+ * @param {string} content - Full ROADMAP.md content
811
+ * @param {string} [cwd] - Working directory for reading STATE.md
812
+ * @returns {string} Content scoped to current milestone
813
+ */
814
+ function extractCurrentMilestone(content, cwd) {
815
+ if (!cwd) return stripShippedMilestones(content);
816
+
817
+ // 1. Get current milestone version from STATE.md frontmatter
818
+ let version = null;
819
+ try {
820
+ const statePath = path.join(planningDir(cwd), 'STATE.md');
821
+ if (fs.existsSync(statePath)) {
822
+ const stateRaw = fs.readFileSync(statePath, 'utf-8');
823
+ const milestoneMatch = stateRaw.match(/^milestone:\s*(.+)/m);
824
+ if (milestoneMatch) {
825
+ version = milestoneMatch[1].trim();
826
+ }
827
+ }
828
+ } catch {}
829
+
830
+ // 2. Fallback: derive version from getMilestoneInfo pattern in ROADMAP.md itself
831
+ if (!version) {
832
+ // Check for 🚧 in-progress marker
833
+ const inProgressMatch = content.match(/🚧\s*\*\*v(\d+\.\d+)\s/);
834
+ if (inProgressMatch) {
835
+ version = 'v' + inProgressMatch[1];
836
+ }
837
+ }
838
+
839
+ if (!version) return stripShippedMilestones(content);
840
+
841
+ // 3. Find the section matching this version
842
+ // Match headings like: ## Roadmap v3.0: Name, ## v3.0 Name, etc.
843
+ const escapedVersion = escapeRegex(version);
844
+ const sectionPattern = new RegExp(
845
+ `(^#{1,3}\\s+.*${escapedVersion}[^\\n]*)`,
846
+ 'mi'
847
+ );
848
+ const sectionMatch = content.match(sectionPattern);
849
+
850
+ if (!sectionMatch) return stripShippedMilestones(content);
851
+
852
+ const sectionStart = sectionMatch.index;
853
+
854
+ // Find the end: next milestone heading at same or higher level, or EOF
855
+ // Milestone headings look like: ## v2.0, ## Roadmap v2.0, ## ✅ v1.0, etc.
856
+ const headingLevel = sectionMatch[1].match(/^(#{1,3})\s/)[1].length;
857
+ const restContent = content.slice(sectionStart + sectionMatch[0].length);
858
+ const nextMilestonePattern = new RegExp(
859
+ `^#{1,${headingLevel}}\\s+(?:.*v\\d+\\.\\d+|✅|📋|🚧)`,
860
+ 'mi'
861
+ );
862
+ const nextMatch = restContent.match(nextMilestonePattern);
863
+
864
+ let sectionEnd;
865
+ if (nextMatch) {
866
+ sectionEnd = sectionStart + sectionMatch[0].length + nextMatch.index;
867
+ } else {
868
+ sectionEnd = content.length;
869
+ }
870
+
871
+ // Return everything before the current milestone section (non-milestone content
872
+ // like title, overview) plus the current milestone section
873
+ const beforeMilestones = content.slice(0, sectionStart);
874
+ const currentSection = content.slice(sectionStart, sectionEnd);
875
+
876
+ // Also include any content before the first milestone heading (title, overview, etc.)
877
+ // but strip any <details> blocks in it (these are definitely shipped)
878
+ const preamble = beforeMilestones.replace(/<details>[\s\S]*?<\/details>/gi, '');
879
+
880
+ return preamble + currentSection;
881
+ }
882
+
883
+ /**
884
+ * Replace a pattern only in the current milestone section of ROADMAP.md
885
+ * (everything after the last </details> close tag). Used for write operations
886
+ * that must not accidentally modify archived milestone checkboxes/tables.
887
+ */
888
+ function replaceInCurrentMilestone(content, pattern, replacement) {
889
+ const lastDetailsClose = content.lastIndexOf('</details>');
890
+ if (lastDetailsClose === -1) {
891
+ return content.replace(pattern, replacement);
892
+ }
893
+ const offset = lastDetailsClose + '</details>'.length;
894
+ const before = content.slice(0, offset);
895
+ const after = content.slice(offset);
896
+ return before + after.replace(pattern, replacement);
897
+ }
898
+
899
+ // ─── Roadmap & model utilities ────────────────────────────────────────────────
900
+
901
+ function getRoadmapPhaseInternal(cwd, phaseNum) {
902
+ if (!phaseNum) return null;
903
+ const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
904
+ if (!fs.existsSync(roadmapPath)) return null;
905
+
906
+ try {
907
+ const content = extractCurrentMilestone(fs.readFileSync(roadmapPath, 'utf-8'), cwd);
908
+ const escapedPhase = escapeRegex(phaseNum.toString());
909
+ // Match both numeric (Phase 1:) and custom (Phase PROJ-42:) headers
910
+ const phasePattern = new RegExp(`#{2,4}\\s*Phase\\s+${escapedPhase}:\\s*([^\\n]+)`, 'i');
911
+ const headerMatch = content.match(phasePattern);
912
+ if (!headerMatch) return null;
913
+
914
+ const phaseName = headerMatch[1].trim();
915
+ const headerIndex = headerMatch.index;
916
+ const restOfContent = content.slice(headerIndex);
917
+ const nextHeaderMatch = restOfContent.match(/\n#{2,4}\s+Phase\s+[\w]/i);
918
+ const sectionEnd = nextHeaderMatch ? headerIndex + nextHeaderMatch.index : content.length;
919
+ const section = content.slice(headerIndex, sectionEnd).trim();
920
+
921
+ const goalMatch = section.match(/\*\*Goal(?:\*\*:|\*?\*?:\*\*)\s*([^\n]+)/i);
922
+ const goal = goalMatch ? goalMatch[1].trim() : null;
923
+
924
+ return {
925
+ found: true,
926
+ phase_number: phaseNum.toString(),
927
+ phase_name: phaseName,
928
+ goal,
929
+ section,
930
+ };
931
+ } catch {
932
+ return null;
933
+ }
934
+ }
935
+
936
+ // ─── Agent installation validation (#1371) ───────────────────────────────────
937
+
938
+ /**
939
+ * Resolve the agents directory from the GSD install location.
940
+ * cap-tools.cjs lives at <configDir>/cap/bin/cap-tools.cjs,
941
+ * so agents/ is at <configDir>/agents/.
942
+ *
943
+ * @returns {string} Absolute path to the agents directory
944
+ */
945
+ function getAgentsDir() {
946
+ // __dirname is cap/bin/lib/ → go up 3 levels to configDir
947
+ return path.join(__dirname, '..', '..', '..', 'agents');
948
+ }
949
+
950
+ /**
951
+ * Check which CAP agents are installed on disk.
952
+ * Returns an object with installation status and details.
953
+ * Detects agents by scanning for cap-*.md files in the agents directory.
954
+ *
955
+ * @returns {{ agents_installed: boolean, missing_agents: string[], installed_agents: string[], agents_dir: string, expected: string[] }}
956
+ */
957
+ function checkAgentsInstalled() {
958
+ const agentsDir = getAgentsDir();
959
+ // Expected CAP agents (post cap-pro-4: cap-tester + cap-reviewer were
960
+ // consolidated into cap-validator). Only the per-feature micro-workflow
961
+ // agents are checked here; the macro-workflow agents (cap-historian,
962
+ // cap-curator, cap-architect, cap-migrator, cap-designer) are optional
963
+ // for an install to be considered "agents installed".
964
+ const expectedAgents = [
965
+ 'cap-brainstormer', 'cap-prototyper', 'cap-validator', 'cap-debugger',
966
+ ];
967
+ const installed = [];
968
+ const missing = [];
969
+
970
+ if (!fs.existsSync(agentsDir)) {
971
+ return {
972
+ agents_installed: false,
973
+ missing_agents: expectedAgents,
974
+ installed_agents: [],
975
+ agents_dir: agentsDir,
976
+ expected: expectedAgents,
977
+ };
978
+ }
979
+
980
+ for (const agent of expectedAgents) {
981
+ const agentFile = path.join(agentsDir, `${agent}.md`);
982
+ if (fs.existsSync(agentFile)) {
983
+ installed.push(agent);
984
+ } else {
985
+ missing.push(agent);
986
+ }
987
+ }
988
+
989
+ return {
990
+ agents_installed: installed.length > 0 && missing.length === 0,
991
+ missing_agents: missing,
992
+ installed_agents: installed,
993
+ agents_dir: agentsDir,
994
+ expected: expectedAgents,
995
+ };
996
+ }
997
+
998
+ // ─── Model alias resolution ───────────────────────────────────────────────────
999
+
1000
+ /**
1001
+ * Map short model aliases to full model IDs.
1002
+ * Updated each release to match current model versions.
1003
+ * Users can override with model_overrides in config.json for custom/latest models.
1004
+ */
1005
+ const MODEL_ALIAS_MAP = {
1006
+ 'opus': 'claude-opus-4-0',
1007
+ 'sonnet': 'claude-sonnet-4-5',
1008
+ 'haiku': 'claude-haiku-3-5',
1009
+ };
1010
+
1011
+ function resolveModelInternal(cwd, agentType) {
1012
+ const config = loadConfig(cwd);
1013
+
1014
+ // Check per-agent override first — always respected regardless of resolve_model_ids.
1015
+ // Users who set fully-qualified model IDs (e.g., "openai/gpt-5.4") get exactly that.
1016
+ const override = config.model_overrides?.[agentType];
1017
+ if (override) {
1018
+ return override;
1019
+ }
1020
+
1021
+ // resolve_model_ids: "omit" — return empty string so the runtime uses its configured
1022
+ // default model. For non-Claude runtimes (OpenCode, Codex, etc.) that don't recognize
1023
+ // Claude aliases (opus/sonnet/haiku/inherit). Set automatically during install. See #1156.
1024
+ if (config.resolve_model_ids === 'omit') {
1025
+ return '';
1026
+ }
1027
+
1028
+ // Fall back to profile lookup
1029
+ const profile = String(config.model_profile || 'balanced').toLowerCase();
1030
+ const agentModels = MODEL_PROFILES[agentType];
1031
+ if (!agentModels) return 'sonnet';
1032
+ if (profile === 'inherit') return 'inherit';
1033
+ const alias = agentModels[profile] || agentModels['balanced'] || 'sonnet';
1034
+
1035
+ // resolve_model_ids: true — map alias to full Claude model ID
1036
+ // Prevents 404s when the Task tool passes aliases directly to the API
1037
+ if (config.resolve_model_ids) {
1038
+ return MODEL_ALIAS_MAP[alias] || alias;
1039
+ }
1040
+
1041
+ return alias;
1042
+ }
1043
+
1044
+ // ─── Summary body helpers ─────────────────────────────────────────────────
1045
+
1046
+ /**
1047
+ * Extract a one-liner from the summary body when it's not in frontmatter.
1048
+ * The summary template defines one-liner as a bold markdown line after the heading:
1049
+ * # Phase X: Name Summary
1050
+ * **[substantive one-liner text]**
1051
+ */
1052
+ function extractOneLinerFromBody(content) {
1053
+ if (!content) return null;
1054
+ // Strip frontmatter first
1055
+ const body = content.replace(/^---\n[\s\S]*?\n---\n*/, '');
1056
+ // Find the first **...** line after a # heading
1057
+ const match = body.match(/^#[^\n]*\n+\*\*([^*]+)\*\*/m);
1058
+ return match ? match[1].trim() : null;
1059
+ }
1060
+
1061
+ // ─── Misc utilities ───────────────────────────────────────────────────────────
1062
+
1063
+ function pathExistsInternal(cwd, targetPath) {
1064
+ const fullPath = path.isAbsolute(targetPath) ? targetPath : path.join(cwd, targetPath);
1065
+ try {
1066
+ fs.statSync(fullPath);
1067
+ return true;
1068
+ } catch {
1069
+ return false;
1070
+ }
1071
+ }
1072
+
1073
+ function generateSlugInternal(text) {
1074
+ if (!text) return null;
1075
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
1076
+ }
1077
+
1078
+ function getMilestoneInfo(cwd) {
1079
+ try {
1080
+ const roadmap = fs.readFileSync(path.join(planningDir(cwd), 'ROADMAP.md'), 'utf-8');
1081
+
1082
+ // First: check for list-format roadmaps using 🚧 (in-progress) marker
1083
+ // e.g. "- 🚧 **v2.1 Belgium** — Phases 24-28 (in progress)"
1084
+ // e.g. "- 🚧 **v1.2.1 Tech Debt** — Phases 1-8 (in progress)"
1085
+ const inProgressMatch = roadmap.match(/🚧\s*\*\*v(\d+(?:\.\d+)+)\s+([^*]+)\*\*/);
1086
+ if (inProgressMatch) {
1087
+ return {
1088
+ version: 'v' + inProgressMatch[1],
1089
+ name: inProgressMatch[2].trim(),
1090
+ };
1091
+ }
1092
+
1093
+ // Second: heading-format roadmaps — strip shipped milestones in <details> blocks
1094
+ const cleaned = stripShippedMilestones(roadmap);
1095
+ // Extract version and name from the same ## heading for consistency
1096
+ // Supports 2+ segment versions: v1.2, v1.2.1, v2.0.1, etc.
1097
+ const headingMatch = cleaned.match(/## .*v(\d+(?:\.\d+)+)[:\s]+([^\n(]+)/);
1098
+ if (headingMatch) {
1099
+ return {
1100
+ version: 'v' + headingMatch[1],
1101
+ name: headingMatch[2].trim(),
1102
+ };
1103
+ }
1104
+ // Fallback: try bare version match (greedy — capture longest version string)
1105
+ const versionMatch = cleaned.match(/v(\d+(?:\.\d+)+)/);
1106
+ return {
1107
+ version: versionMatch ? versionMatch[0] : 'v1.0',
1108
+ name: 'milestone',
1109
+ };
1110
+ } catch {
1111
+ return { version: 'v1.0', name: 'milestone' };
1112
+ }
1113
+ }
1114
+
1115
+ /**
1116
+ * Returns a filter function that checks whether a phase directory belongs
1117
+ * to the current milestone based on ROADMAP.md phase headings.
1118
+ * If no ROADMAP exists or no phases are listed, returns a pass-all filter.
1119
+ */
1120
+ function getMilestonePhaseFilter(cwd) {
1121
+ const milestonePhaseNums = new Set();
1122
+ try {
1123
+ const roadmap = extractCurrentMilestone(fs.readFileSync(path.join(planningDir(cwd), 'ROADMAP.md'), 'utf-8'), cwd);
1124
+ // Match both numeric phases (Phase 1:) and custom IDs (Phase PROJ-42:)
1125
+ const phasePattern = /#{2,4}\s*Phase\s+([\w][\w.-]*)\s*:/gi;
1126
+ let m;
1127
+ while ((m = phasePattern.exec(roadmap)) !== null) {
1128
+ milestonePhaseNums.add(m[1]);
1129
+ }
1130
+ } catch { /* intentionally empty */ }
1131
+
1132
+ if (milestonePhaseNums.size === 0) {
1133
+ const passAll = () => true;
1134
+ passAll.phaseCount = 0;
1135
+ return passAll;
1136
+ }
1137
+
1138
+ const normalized = new Set(
1139
+ [...milestonePhaseNums].map(n => (n.replace(/^0+/, '') || '0').toLowerCase())
1140
+ );
1141
+
1142
+ function isDirInMilestone(dirName) {
1143
+ // Try numeric match first
1144
+ const m = dirName.match(/^0*(\d+[A-Za-z]?(?:\.\d+)*)/);
1145
+ if (m && normalized.has(m[1].toLowerCase())) return true;
1146
+ // Try custom ID match (e.g. PROJ-42-description → PROJ-42)
1147
+ const customMatch = dirName.match(/^([A-Za-z][A-Za-z0-9]*(?:-[A-Za-z0-9]+)*)/);
1148
+ if (customMatch && normalized.has(customMatch[1].toLowerCase())) return true;
1149
+ return false;
1150
+ }
1151
+ isDirInMilestone.phaseCount = milestonePhaseNums.size;
1152
+ return isDirInMilestone;
1153
+ }
1154
+
1155
+ // ─── Phase file helpers ──────────────────────────────────────────────────────
1156
+
1157
+ /** Filter a file list to just PLAN.md / *-PLAN.md entries. */
1158
+ function filterPlanFiles(files) {
1159
+ return files.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
1160
+ }
1161
+
1162
+ /** Filter a file list to just SUMMARY.md / *-SUMMARY.md entries. */
1163
+ function filterSummaryFiles(files) {
1164
+ return files.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
1165
+ }
1166
+
1167
+ /**
1168
+ * Read a phase directory and return counts/flags for common file types.
1169
+ * Returns an object with plans[], summaries[], and boolean flags for
1170
+ * research/context/verification files.
1171
+ */
1172
+ function getPhaseFileStats(phaseDir) {
1173
+ const files = fs.readdirSync(phaseDir);
1174
+ return {
1175
+ plans: filterPlanFiles(files),
1176
+ summaries: filterSummaryFiles(files),
1177
+ hasResearch: files.some(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md'),
1178
+ hasContext: files.some(f => f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md'),
1179
+ hasVerification: files.some(f => f.endsWith('-VERIFICATION.md') || f === 'VERIFICATION.md'),
1180
+ hasReviews: files.some(f => f.endsWith('-REVIEWS.md') || f === 'REVIEWS.md'),
1181
+ };
1182
+ }
1183
+
1184
+ /**
1185
+ * Read immediate child directories from a path.
1186
+ * Returns [] if the path doesn't exist or can't be read.
1187
+ * Pass sort=true to apply comparePhaseNum ordering.
1188
+ */
1189
+ function readSubdirectories(dirPath, sort = false) {
1190
+ try {
1191
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
1192
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
1193
+ return sort ? dirs.sort((a, b) => comparePhaseNum(a, b)) : dirs;
1194
+ } catch {
1195
+ return [];
1196
+ }
1197
+ }
1198
+
1199
+ module.exports = {
1200
+ output,
1201
+ error,
1202
+ safeReadFile,
1203
+ loadConfig,
1204
+ isGitIgnored,
1205
+ execGit,
1206
+ normalizeMd,
1207
+ escapeRegex,
1208
+ normalizePhaseName,
1209
+ comparePhaseNum,
1210
+ searchPhaseInDir,
1211
+ findPhaseInternal,
1212
+ getArchivedPhaseDirs,
1213
+ getRoadmapPhaseInternal,
1214
+ resolveModelInternal,
1215
+ pathExistsInternal,
1216
+ generateSlugInternal,
1217
+ getMilestoneInfo,
1218
+ getMilestonePhaseFilter,
1219
+ stripShippedMilestones,
1220
+ extractCurrentMilestone,
1221
+ replaceInCurrentMilestone,
1222
+ toPosixPath,
1223
+ extractOneLinerFromBody,
1224
+ resolveWorktreeRoot,
1225
+ withPlanningLock,
1226
+ findProjectRoot,
1227
+ detectSubRepos,
1228
+ reapStaleTempFiles,
1229
+ MODEL_ALIAS_MAP,
1230
+ planningDir,
1231
+ planningRoot,
1232
+ planningPaths,
1233
+ getActiveWorkstream,
1234
+ setActiveWorkstream,
1235
+ filterPlanFiles,
1236
+ filterSummaryFiles,
1237
+ getPhaseFileStats,
1238
+ readSubdirectories,
1239
+ getAgentsDir,
1240
+ checkAgentsInstalled,
1241
+ };