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,1443 @@
1
+ /**
2
+ * Init — Compound init commands for workflow bootstrapping
3
+ */
4
+ // @cap-feature(feature:F-011) Legacy GSD Modules — workflow initialization and bootstrapping
5
+
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { execSync } = require('child_process');
9
+ const { loadConfig, resolveModelInternal, findPhaseInternal, getRoadmapPhaseInternal, pathExistsInternal, generateSlugInternal, getMilestoneInfo, getMilestonePhaseFilter, stripShippedMilestones, extractCurrentMilestone, normalizePhaseName, planningPaths, planningDir, planningRoot, toPosixPath, output, error, checkAgentsInstalled } = require('./core.cjs');
10
+
11
+ function getLatestCompletedMilestone(cwd) {
12
+ const milestonesPath = path.join(planningRoot(cwd), 'MILESTONES.md');
13
+ if (!fs.existsSync(milestonesPath)) return null;
14
+
15
+ try {
16
+ const content = fs.readFileSync(milestonesPath, 'utf-8');
17
+ const match = content.match(/^##\s+(v[\d.]+)\s+(.+?)\s+\(Shipped:/m);
18
+ if (!match) return null;
19
+ return {
20
+ version: match[1],
21
+ name: match[2].trim(),
22
+ };
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Inject `project_root` into an init result object.
30
+ * Workflows use this to prefix `.planning/` paths correctly when Claude's CWD
31
+ * differs from the project root (e.g., inside a sub-repo).
32
+ */
33
+ function withProjectRoot(cwd, result) {
34
+ result.project_root = cwd;
35
+ // Inject agent installation status into all init outputs (#1371).
36
+ // Workflows that spawn named subagents use this to detect when agents
37
+ // are missing and would silently fall back to general-purpose.
38
+ const agentStatus = checkAgentsInstalled();
39
+ result.agents_installed = agentStatus.agents_installed;
40
+ result.missing_agents = agentStatus.missing_agents;
41
+ return result;
42
+ }
43
+
44
+ function cmdInitExecutePhase(cwd, phase, raw) {
45
+ if (!phase) {
46
+ error('phase required for init execute-phase');
47
+ }
48
+
49
+ const config = loadConfig(cwd);
50
+ let phaseInfo = findPhaseInternal(cwd, phase);
51
+ const milestone = getMilestoneInfo(cwd);
52
+
53
+ const roadmapPhase = getRoadmapPhaseInternal(cwd, phase);
54
+
55
+ // Fallback to ROADMAP.md if no phase directory exists yet
56
+ if (!phaseInfo && roadmapPhase?.found) {
57
+ const phaseName = roadmapPhase.phase_name;
58
+ phaseInfo = {
59
+ found: true,
60
+ directory: null,
61
+ phase_number: roadmapPhase.phase_number,
62
+ phase_name: phaseName,
63
+ phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
64
+ plans: [],
65
+ summaries: [],
66
+ incomplete_plans: [],
67
+ has_research: false,
68
+ has_context: false,
69
+ has_verification: false,
70
+ has_reviews: false,
71
+ };
72
+ }
73
+ const reqMatch = roadmapPhase?.section?.match(/^\*\*Requirements\*\*:[^\S\n]*([^\n]*)$/m);
74
+ const reqExtracted = reqMatch
75
+ ? reqMatch[1].replace(/[\[\]]/g, '').split(',').map(s => s.trim()).filter(Boolean).join(', ')
76
+ : null;
77
+ const phase_req_ids = (reqExtracted && reqExtracted !== 'TBD') ? reqExtracted : null;
78
+
79
+ const result = {
80
+ // Models
81
+ executor_model: resolveModelInternal(cwd, 'gsd-executor'),
82
+ verifier_model: resolveModelInternal(cwd, 'gsd-verifier'),
83
+
84
+ // Config flags
85
+ commit_docs: config.commit_docs,
86
+ sub_repos: config.sub_repos,
87
+ parallelization: config.parallelization,
88
+ context_window: config.context_window,
89
+ branching_strategy: config.branching_strategy,
90
+ phase_branch_template: config.phase_branch_template,
91
+ milestone_branch_template: config.milestone_branch_template,
92
+ verifier_enabled: config.verifier,
93
+
94
+ // Phase info
95
+ phase_found: !!phaseInfo,
96
+ phase_dir: phaseInfo?.directory || null,
97
+ phase_number: phaseInfo?.phase_number || null,
98
+ phase_name: phaseInfo?.phase_name || null,
99
+ phase_slug: phaseInfo?.phase_slug || null,
100
+ phase_req_ids,
101
+
102
+ // Plan inventory
103
+ plans: phaseInfo?.plans || [],
104
+ summaries: phaseInfo?.summaries || [],
105
+ incomplete_plans: phaseInfo?.incomplete_plans || [],
106
+ plan_count: phaseInfo?.plans?.length || 0,
107
+ incomplete_count: phaseInfo?.incomplete_plans?.length || 0,
108
+
109
+ // Branch name (pre-computed)
110
+ branch_name: config.branching_strategy === 'phase' && phaseInfo
111
+ ? config.phase_branch_template
112
+ .replace('{phase}', phaseInfo.phase_number)
113
+ .replace('{slug}', phaseInfo.phase_slug || 'phase')
114
+ : config.branching_strategy === 'milestone'
115
+ ? config.milestone_branch_template
116
+ .replace('{milestone}', milestone.version)
117
+ .replace('{slug}', generateSlugInternal(milestone.name) || 'milestone')
118
+ : null,
119
+
120
+ // Milestone info
121
+ milestone_version: milestone.version,
122
+ milestone_name: milestone.name,
123
+ milestone_slug: generateSlugInternal(milestone.name),
124
+
125
+ // File existence
126
+ state_exists: fs.existsSync(path.join(planningDir(cwd), 'STATE.md')),
127
+ roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
128
+ config_exists: fs.existsSync(path.join(planningDir(cwd), 'config.json')),
129
+ // File paths
130
+ state_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'STATE.md'))),
131
+ roadmap_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'ROADMAP.md'))),
132
+ config_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'config.json'))),
133
+ };
134
+
135
+ output(withProjectRoot(cwd, result), raw);
136
+ }
137
+
138
+ function cmdInitPlanPhase(cwd, phase, raw) {
139
+ if (!phase) {
140
+ error('phase required for init plan-phase');
141
+ }
142
+
143
+ const config = loadConfig(cwd);
144
+ let phaseInfo = findPhaseInternal(cwd, phase);
145
+
146
+ const roadmapPhase = getRoadmapPhaseInternal(cwd, phase);
147
+
148
+ // Fallback to ROADMAP.md if no phase directory exists yet
149
+ if (!phaseInfo && roadmapPhase?.found) {
150
+ const phaseName = roadmapPhase.phase_name;
151
+ phaseInfo = {
152
+ found: true,
153
+ directory: null,
154
+ phase_number: roadmapPhase.phase_number,
155
+ phase_name: phaseName,
156
+ phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
157
+ plans: [],
158
+ summaries: [],
159
+ incomplete_plans: [],
160
+ has_research: false,
161
+ has_context: false,
162
+ has_verification: false,
163
+ has_reviews: false,
164
+ };
165
+ }
166
+ const reqMatch = roadmapPhase?.section?.match(/^\*\*Requirements\*\*:[^\S\n]*([^\n]*)$/m);
167
+ const reqExtracted = reqMatch
168
+ ? reqMatch[1].replace(/[\[\]]/g, '').split(',').map(s => s.trim()).filter(Boolean).join(', ')
169
+ : null;
170
+ const phase_req_ids = (reqExtracted && reqExtracted !== 'TBD') ? reqExtracted : null;
171
+
172
+ const result = {
173
+ // Models
174
+ researcher_model: resolveModelInternal(cwd, 'gsd-phase-researcher'),
175
+ planner_model: resolveModelInternal(cwd, 'gsd-planner'),
176
+ checker_model: resolveModelInternal(cwd, 'gsd-plan-checker'),
177
+
178
+ // Workflow flags
179
+ research_enabled: config.research,
180
+ plan_checker_enabled: config.plan_checker,
181
+ nyquist_validation_enabled: config.nyquist_validation,
182
+ commit_docs: config.commit_docs,
183
+ text_mode: config.text_mode,
184
+
185
+ // Phase info
186
+ phase_found: !!phaseInfo,
187
+ phase_dir: phaseInfo?.directory || null,
188
+ phase_number: phaseInfo?.phase_number || null,
189
+ phase_name: phaseInfo?.phase_name || null,
190
+ phase_slug: phaseInfo?.phase_slug || null,
191
+ padded_phase: phaseInfo?.phase_number ? normalizePhaseName(phaseInfo.phase_number) : null,
192
+ phase_req_ids,
193
+
194
+ // Existing artifacts
195
+ has_research: phaseInfo?.has_research || false,
196
+ has_context: phaseInfo?.has_context || false,
197
+ has_reviews: phaseInfo?.has_reviews || false,
198
+ has_plans: (phaseInfo?.plans?.length || 0) > 0,
199
+ plan_count: phaseInfo?.plans?.length || 0,
200
+
201
+ // Environment
202
+ planning_exists: fs.existsSync(planningDir(cwd)),
203
+ roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
204
+
205
+ // File paths
206
+ state_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'STATE.md'))),
207
+ roadmap_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'ROADMAP.md'))),
208
+ requirements_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'REQUIREMENTS.md'))),
209
+ };
210
+
211
+ if (phaseInfo?.directory) {
212
+ // Find *-CONTEXT.md in phase directory
213
+ const phaseDirFull = path.join(cwd, phaseInfo.directory);
214
+ try {
215
+ const files = fs.readdirSync(phaseDirFull);
216
+ const contextFile = files.find(f => f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md');
217
+ if (contextFile) {
218
+ result.context_path = toPosixPath(path.join(phaseInfo.directory, contextFile));
219
+ }
220
+ const researchFile = files.find(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md');
221
+ if (researchFile) {
222
+ result.research_path = toPosixPath(path.join(phaseInfo.directory, researchFile));
223
+ }
224
+ const verificationFile = files.find(f => f.endsWith('-VERIFICATION.md') || f === 'VERIFICATION.md');
225
+ if (verificationFile) {
226
+ result.verification_path = toPosixPath(path.join(phaseInfo.directory, verificationFile));
227
+ }
228
+ const uatFile = files.find(f => f.endsWith('-UAT.md') || f === 'UAT.md');
229
+ if (uatFile) {
230
+ result.uat_path = toPosixPath(path.join(phaseInfo.directory, uatFile));
231
+ }
232
+ const reviewsFile = files.find(f => f.endsWith('-REVIEWS.md') || f === 'REVIEWS.md');
233
+ if (reviewsFile) {
234
+ result.reviews_path = toPosixPath(path.join(phaseInfo.directory, reviewsFile));
235
+ }
236
+ } catch { /* intentionally empty */ }
237
+ }
238
+
239
+ output(withProjectRoot(cwd, result), raw);
240
+ }
241
+
242
+ function cmdInitNewProject(cwd, raw) {
243
+ const config = loadConfig(cwd);
244
+
245
+ // Detect Brave Search API key availability
246
+ const homedir = require('os').homedir();
247
+ const braveKeyFile = path.join(homedir, '.gsd', 'brave_api_key');
248
+ const hasBraveSearch = !!(process.env.BRAVE_API_KEY || fs.existsSync(braveKeyFile));
249
+
250
+ // Detect Firecrawl API key availability
251
+ const firecrawlKeyFile = path.join(homedir, '.gsd', 'firecrawl_api_key');
252
+ const hasFirecrawl = !!(process.env.FIRECRAWL_API_KEY || fs.existsSync(firecrawlKeyFile));
253
+
254
+ // Detect Exa API key availability
255
+ const exaKeyFile = path.join(homedir, '.gsd', 'exa_api_key');
256
+ const hasExaSearch = !!(process.env.EXA_API_KEY || fs.existsSync(exaKeyFile));
257
+
258
+ // Detect existing code (cross-platform — no Unix `find` dependency)
259
+ let hasCode = false;
260
+ let hasPackageFile = false;
261
+ try {
262
+ const codeExtensions = new Set([
263
+ '.ts', '.js', '.py', '.go', '.rs', '.swift', '.java',
264
+ '.kt', '.kts', // Kotlin (Android, server-side)
265
+ '.c', '.cpp', '.h', // C/C++
266
+ '.cs', // C#
267
+ '.rb', // Ruby
268
+ '.php', // PHP
269
+ '.dart', // Dart (Flutter)
270
+ '.m', '.mm', // Objective-C / Objective-C++
271
+ '.scala', // Scala
272
+ '.groovy', // Groovy (Gradle build scripts)
273
+ '.lua', // Lua
274
+ '.r', '.R', // R
275
+ '.zig', // Zig
276
+ '.ex', '.exs', // Elixir
277
+ '.clj', // Clojure
278
+ ]);
279
+ const skipDirs = new Set(['node_modules', '.git', '.planning', '.claude', '__pycache__', 'target', 'dist', 'build']);
280
+ function findCodeFiles(dir, depth) {
281
+ if (depth > 3) return false;
282
+ let entries;
283
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return false; }
284
+ for (const entry of entries) {
285
+ if (entry.isFile() && codeExtensions.has(path.extname(entry.name))) return true;
286
+ if (entry.isDirectory() && !skipDirs.has(entry.name)) {
287
+ if (findCodeFiles(path.join(dir, entry.name), depth + 1)) return true;
288
+ }
289
+ }
290
+ return false;
291
+ }
292
+ hasCode = findCodeFiles(cwd, 0);
293
+ } catch { /* intentionally empty — best-effort detection */ }
294
+
295
+ hasPackageFile = pathExistsInternal(cwd, 'package.json') ||
296
+ pathExistsInternal(cwd, 'requirements.txt') ||
297
+ pathExistsInternal(cwd, 'Cargo.toml') ||
298
+ pathExistsInternal(cwd, 'go.mod') ||
299
+ pathExistsInternal(cwd, 'Package.swift') ||
300
+ pathExistsInternal(cwd, 'build.gradle') ||
301
+ pathExistsInternal(cwd, 'build.gradle.kts') ||
302
+ pathExistsInternal(cwd, 'pom.xml') ||
303
+ pathExistsInternal(cwd, 'Gemfile') ||
304
+ pathExistsInternal(cwd, 'composer.json') ||
305
+ pathExistsInternal(cwd, 'pubspec.yaml') ||
306
+ pathExistsInternal(cwd, 'CMakeLists.txt') ||
307
+ pathExistsInternal(cwd, 'Makefile') ||
308
+ pathExistsInternal(cwd, 'build.zig') ||
309
+ pathExistsInternal(cwd, 'mix.exs') ||
310
+ pathExistsInternal(cwd, 'project.clj');
311
+
312
+ const result = {
313
+ // Models
314
+ researcher_model: resolveModelInternal(cwd, 'gsd-project-researcher'),
315
+ synthesizer_model: resolveModelInternal(cwd, 'gsd-research-synthesizer'),
316
+ roadmapper_model: resolveModelInternal(cwd, 'gsd-roadmapper'),
317
+
318
+ // Config
319
+ commit_docs: config.commit_docs,
320
+
321
+ // Existing state
322
+ project_exists: pathExistsInternal(cwd, '.planning/PROJECT.md'),
323
+ has_codebase_map: pathExistsInternal(cwd, '.planning/codebase'),
324
+ planning_exists: pathExistsInternal(cwd, '.planning'),
325
+
326
+ // Brownfield detection
327
+ has_existing_code: hasCode,
328
+ has_package_file: hasPackageFile,
329
+ is_brownfield: hasCode || hasPackageFile,
330
+ needs_codebase_map: (hasCode || hasPackageFile) && !pathExistsInternal(cwd, '.planning/codebase'),
331
+
332
+ // Git state
333
+ has_git: pathExistsInternal(cwd, '.git'),
334
+
335
+ // Enhanced search
336
+ brave_search_available: hasBraveSearch,
337
+ firecrawl_available: hasFirecrawl,
338
+ exa_search_available: hasExaSearch,
339
+
340
+ // File paths
341
+ project_path: '.planning/PROJECT.md',
342
+ };
343
+
344
+ output(withProjectRoot(cwd, result), raw);
345
+ }
346
+
347
+ function cmdInitNewMilestone(cwd, raw) {
348
+ const config = loadConfig(cwd);
349
+ const milestone = getMilestoneInfo(cwd);
350
+ const latestCompleted = getLatestCompletedMilestone(cwd);
351
+ const phasesDir = path.join(planningDir(cwd), 'phases');
352
+ let phaseDirCount = 0;
353
+
354
+ try {
355
+ if (fs.existsSync(phasesDir)) {
356
+ phaseDirCount = fs.readdirSync(phasesDir, { withFileTypes: true })
357
+ .filter(entry => entry.isDirectory())
358
+ .length;
359
+ }
360
+ } catch {}
361
+
362
+ const result = {
363
+ // Models
364
+ researcher_model: resolveModelInternal(cwd, 'gsd-project-researcher'),
365
+ synthesizer_model: resolveModelInternal(cwd, 'gsd-research-synthesizer'),
366
+ roadmapper_model: resolveModelInternal(cwd, 'gsd-roadmapper'),
367
+
368
+ // Config
369
+ commit_docs: config.commit_docs,
370
+ research_enabled: config.research,
371
+
372
+ // Current milestone
373
+ current_milestone: milestone.version,
374
+ current_milestone_name: milestone.name,
375
+ latest_completed_milestone: latestCompleted?.version || null,
376
+ latest_completed_milestone_name: latestCompleted?.name || null,
377
+ phase_dir_count: phaseDirCount,
378
+ phase_archive_path: latestCompleted ? toPosixPath(path.relative(cwd, path.join(planningRoot(cwd), 'milestones', `${latestCompleted.version}-phases`))) : null,
379
+
380
+ // File existence
381
+ project_exists: pathExistsInternal(cwd, '.planning/PROJECT.md'),
382
+ roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
383
+ state_exists: fs.existsSync(path.join(planningDir(cwd), 'STATE.md')),
384
+
385
+ // File paths
386
+ project_path: '.planning/PROJECT.md',
387
+ roadmap_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'ROADMAP.md'))),
388
+ state_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'STATE.md'))),
389
+ };
390
+
391
+ output(withProjectRoot(cwd, result), raw);
392
+ }
393
+
394
+ function cmdInitQuick(cwd, description, raw) {
395
+ const config = loadConfig(cwd);
396
+ const now = new Date();
397
+ const slug = description ? generateSlugInternal(description)?.substring(0, 40) : null;
398
+
399
+ // Generate collision-resistant quick task ID: YYMMDD-xxx
400
+ // xxx = 2-second precision blocks since midnight, encoded as 3-char Base36 (lowercase)
401
+ // Range: 000 (00:00:00) to xbz (23:59:58), guaranteed 3 chars for any time of day.
402
+ // Provides ~2s uniqueness window per user — practically collision-free across a team.
403
+ const yy = String(now.getFullYear()).slice(-2);
404
+ const mm = String(now.getMonth() + 1).padStart(2, '0');
405
+ const dd = String(now.getDate()).padStart(2, '0');
406
+ const dateStr = yy + mm + dd;
407
+ const secondsSinceMidnight = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds();
408
+ const timeBlocks = Math.floor(secondsSinceMidnight / 2);
409
+ const timeEncoded = timeBlocks.toString(36).padStart(3, '0');
410
+ const quickId = dateStr + '-' + timeEncoded;
411
+ const branchSlug = slug || 'quick';
412
+ const quickBranchName = config.quick_branch_template
413
+ ? config.quick_branch_template
414
+ .replace('{num}', quickId)
415
+ .replace('{quick}', quickId)
416
+ .replace('{slug}', branchSlug)
417
+ : null;
418
+
419
+ const result = {
420
+ // Models
421
+ planner_model: resolveModelInternal(cwd, 'gsd-planner'),
422
+ executor_model: resolveModelInternal(cwd, 'gsd-executor'),
423
+ checker_model: resolveModelInternal(cwd, 'gsd-plan-checker'),
424
+ verifier_model: resolveModelInternal(cwd, 'gsd-verifier'),
425
+
426
+ // Config
427
+ commit_docs: config.commit_docs,
428
+ branch_name: quickBranchName,
429
+
430
+ // Quick task info
431
+ quick_id: quickId,
432
+ slug: slug,
433
+ description: description || null,
434
+
435
+ // Timestamps
436
+ date: now.toISOString().split('T')[0],
437
+ timestamp: now.toISOString(),
438
+
439
+ // Paths
440
+ quick_dir: '.planning/quick',
441
+ task_dir: slug ? `.planning/quick/${quickId}-${slug}` : null,
442
+
443
+ // File existence
444
+ roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
445
+ planning_exists: fs.existsSync(planningRoot(cwd)),
446
+
447
+ };
448
+
449
+ output(withProjectRoot(cwd, result), raw);
450
+ }
451
+
452
+ function cmdInitResume(cwd, raw) {
453
+ const config = loadConfig(cwd);
454
+
455
+ // Check for interrupted agent
456
+ let interruptedAgentId = null;
457
+ try {
458
+ interruptedAgentId = fs.readFileSync(path.join(planningRoot(cwd), 'current-agent-id.txt'), 'utf-8').trim();
459
+ } catch { /* intentionally empty */ }
460
+
461
+ const result = {
462
+ // File existence
463
+ state_exists: fs.existsSync(path.join(planningDir(cwd), 'STATE.md')),
464
+ roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
465
+ project_exists: pathExistsInternal(cwd, '.planning/PROJECT.md'),
466
+ planning_exists: fs.existsSync(planningRoot(cwd)),
467
+
468
+ // File paths
469
+ state_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'STATE.md'))),
470
+ roadmap_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'ROADMAP.md'))),
471
+ project_path: '.planning/PROJECT.md',
472
+
473
+ // Agent state
474
+ has_interrupted_agent: !!interruptedAgentId,
475
+ interrupted_agent_id: interruptedAgentId,
476
+
477
+ // Config
478
+ commit_docs: config.commit_docs,
479
+ };
480
+
481
+ output(withProjectRoot(cwd, result), raw);
482
+ }
483
+
484
+ function cmdInitVerifyWork(cwd, phase, raw) {
485
+ if (!phase) {
486
+ error('phase required for init verify-work');
487
+ }
488
+
489
+ const config = loadConfig(cwd);
490
+ let phaseInfo = findPhaseInternal(cwd, phase);
491
+
492
+ // Fallback to ROADMAP.md if no phase directory exists yet
493
+ if (!phaseInfo) {
494
+ const roadmapPhase = getRoadmapPhaseInternal(cwd, phase);
495
+ if (roadmapPhase?.found) {
496
+ const phaseName = roadmapPhase.phase_name;
497
+ phaseInfo = {
498
+ found: true,
499
+ directory: null,
500
+ phase_number: roadmapPhase.phase_number,
501
+ phase_name: phaseName,
502
+ phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
503
+ plans: [],
504
+ summaries: [],
505
+ incomplete_plans: [],
506
+ has_research: false,
507
+ has_context: false,
508
+ has_verification: false,
509
+ };
510
+ }
511
+ }
512
+
513
+ const result = {
514
+ // Models
515
+ planner_model: resolveModelInternal(cwd, 'gsd-planner'),
516
+ checker_model: resolveModelInternal(cwd, 'gsd-plan-checker'),
517
+
518
+ // Config
519
+ commit_docs: config.commit_docs,
520
+
521
+ // Phase info
522
+ phase_found: !!phaseInfo,
523
+ phase_dir: phaseInfo?.directory || null,
524
+ phase_number: phaseInfo?.phase_number || null,
525
+ phase_name: phaseInfo?.phase_name || null,
526
+
527
+ // Existing artifacts
528
+ has_verification: phaseInfo?.has_verification || false,
529
+ };
530
+
531
+ output(withProjectRoot(cwd, result), raw);
532
+ }
533
+
534
+ function cmdInitPhaseOp(cwd, phase, raw) {
535
+ const config = loadConfig(cwd);
536
+ let phaseInfo = findPhaseInternal(cwd, phase);
537
+
538
+ // If the only disk match comes from an archived milestone, prefer the
539
+ // current milestone's ROADMAP entry so discuss-phase and similar flows
540
+ // don't attach to shipped work that reused the same phase number.
541
+ if (phaseInfo?.archived) {
542
+ const roadmapPhase = getRoadmapPhaseInternal(cwd, phase);
543
+ if (roadmapPhase?.found) {
544
+ const phaseName = roadmapPhase.phase_name;
545
+ phaseInfo = {
546
+ found: true,
547
+ directory: null,
548
+ phase_number: roadmapPhase.phase_number,
549
+ phase_name: phaseName,
550
+ phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
551
+ plans: [],
552
+ summaries: [],
553
+ incomplete_plans: [],
554
+ has_research: false,
555
+ has_context: false,
556
+ has_verification: false,
557
+ };
558
+ }
559
+ }
560
+
561
+ // Fallback to ROADMAP.md if no directory exists (e.g., Plans: TBD)
562
+ if (!phaseInfo) {
563
+ const roadmapPhase = getRoadmapPhaseInternal(cwd, phase);
564
+ if (roadmapPhase?.found) {
565
+ const phaseName = roadmapPhase.phase_name;
566
+ phaseInfo = {
567
+ found: true,
568
+ directory: null,
569
+ phase_number: roadmapPhase.phase_number,
570
+ phase_name: phaseName,
571
+ phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
572
+ plans: [],
573
+ summaries: [],
574
+ incomplete_plans: [],
575
+ has_research: false,
576
+ has_context: false,
577
+ has_verification: false,
578
+ };
579
+ }
580
+ }
581
+
582
+ const result = {
583
+ // Config
584
+ commit_docs: config.commit_docs,
585
+ brave_search: config.brave_search,
586
+ firecrawl: config.firecrawl,
587
+ exa_search: config.exa_search,
588
+
589
+ // Phase info
590
+ phase_found: !!phaseInfo,
591
+ phase_dir: phaseInfo?.directory || null,
592
+ phase_number: phaseInfo?.phase_number || null,
593
+ phase_name: phaseInfo?.phase_name || null,
594
+ phase_slug: phaseInfo?.phase_slug || null,
595
+ padded_phase: phaseInfo?.phase_number ? normalizePhaseName(phaseInfo.phase_number) : null,
596
+
597
+ // Existing artifacts
598
+ has_research: phaseInfo?.has_research || false,
599
+ has_context: phaseInfo?.has_context || false,
600
+ has_plans: (phaseInfo?.plans?.length || 0) > 0,
601
+ has_verification: phaseInfo?.has_verification || false,
602
+ has_reviews: phaseInfo?.has_reviews || false,
603
+ plan_count: phaseInfo?.plans?.length || 0,
604
+
605
+ // File existence
606
+ roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
607
+ planning_exists: fs.existsSync(planningDir(cwd)),
608
+
609
+ // File paths
610
+ state_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'STATE.md'))),
611
+ roadmap_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'ROADMAP.md'))),
612
+ requirements_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'REQUIREMENTS.md'))),
613
+ };
614
+
615
+ if (phaseInfo?.directory) {
616
+ const phaseDirFull = path.join(cwd, phaseInfo.directory);
617
+ try {
618
+ const files = fs.readdirSync(phaseDirFull);
619
+ const contextFile = files.find(f => f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md');
620
+ if (contextFile) {
621
+ result.context_path = toPosixPath(path.join(phaseInfo.directory, contextFile));
622
+ }
623
+ const researchFile = files.find(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md');
624
+ if (researchFile) {
625
+ result.research_path = toPosixPath(path.join(phaseInfo.directory, researchFile));
626
+ }
627
+ const verificationFile = files.find(f => f.endsWith('-VERIFICATION.md') || f === 'VERIFICATION.md');
628
+ if (verificationFile) {
629
+ result.verification_path = toPosixPath(path.join(phaseInfo.directory, verificationFile));
630
+ }
631
+ const uatFile = files.find(f => f.endsWith('-UAT.md') || f === 'UAT.md');
632
+ if (uatFile) {
633
+ result.uat_path = toPosixPath(path.join(phaseInfo.directory, uatFile));
634
+ }
635
+ const reviewsFile = files.find(f => f.endsWith('-REVIEWS.md') || f === 'REVIEWS.md');
636
+ if (reviewsFile) {
637
+ result.reviews_path = toPosixPath(path.join(phaseInfo.directory, reviewsFile));
638
+ }
639
+ } catch { /* intentionally empty */ }
640
+ }
641
+
642
+ output(withProjectRoot(cwd, result), raw);
643
+ }
644
+
645
+ function cmdInitTodos(cwd, area, raw) {
646
+ const config = loadConfig(cwd);
647
+ const now = new Date();
648
+
649
+ // List todos (reuse existing logic)
650
+ const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
651
+ let count = 0;
652
+ const todos = [];
653
+
654
+ try {
655
+ const files = fs.readdirSync(pendingDir).filter(f => f.endsWith('.md'));
656
+ for (const file of files) {
657
+ try {
658
+ const content = fs.readFileSync(path.join(pendingDir, file), 'utf-8');
659
+ const createdMatch = content.match(/^created:\s*(.+)$/m);
660
+ const titleMatch = content.match(/^title:\s*(.+)$/m);
661
+ const areaMatch = content.match(/^area:\s*(.+)$/m);
662
+ const todoArea = areaMatch ? areaMatch[1].trim() : 'general';
663
+
664
+ if (area && todoArea !== area) continue;
665
+
666
+ count++;
667
+ todos.push({
668
+ file,
669
+ created: createdMatch ? createdMatch[1].trim() : 'unknown',
670
+ title: titleMatch ? titleMatch[1].trim() : 'Untitled',
671
+ area: todoArea,
672
+ path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'todos', 'pending', file))),
673
+ });
674
+ } catch { /* intentionally empty */ }
675
+ }
676
+ } catch { /* intentionally empty */ }
677
+
678
+ const result = {
679
+ // Config
680
+ commit_docs: config.commit_docs,
681
+
682
+ // Timestamps
683
+ date: now.toISOString().split('T')[0],
684
+ timestamp: now.toISOString(),
685
+
686
+ // Todo inventory
687
+ todo_count: count,
688
+ todos,
689
+ area_filter: area || null,
690
+
691
+ // Paths
692
+ pending_dir: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'todos', 'pending'))),
693
+ completed_dir: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'todos', 'completed'))),
694
+
695
+ // File existence
696
+ planning_exists: fs.existsSync(planningDir(cwd)),
697
+ todos_dir_exists: fs.existsSync(path.join(planningDir(cwd), 'todos')),
698
+ pending_dir_exists: fs.existsSync(path.join(planningDir(cwd), 'todos', 'pending')),
699
+ };
700
+
701
+ output(withProjectRoot(cwd, result), raw);
702
+ }
703
+
704
+ function cmdInitMilestoneOp(cwd, raw) {
705
+ const config = loadConfig(cwd);
706
+ const milestone = getMilestoneInfo(cwd);
707
+
708
+ // Count phases
709
+ let phaseCount = 0;
710
+ let completedPhases = 0;
711
+ const phasesDir = path.join(planningDir(cwd), 'phases');
712
+ try {
713
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
714
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
715
+ phaseCount = dirs.length;
716
+
717
+ // Count phases with summaries (completed)
718
+ for (const dir of dirs) {
719
+ try {
720
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
721
+ const hasSummary = phaseFiles.some(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
722
+ if (hasSummary) completedPhases++;
723
+ } catch { /* intentionally empty */ }
724
+ }
725
+ } catch { /* intentionally empty */ }
726
+
727
+ // Check archive
728
+ const archiveDir = path.join(planningRoot(cwd), 'archive');
729
+ let archivedMilestones = [];
730
+ try {
731
+ archivedMilestones = fs.readdirSync(archiveDir, { withFileTypes: true })
732
+ .filter(e => e.isDirectory())
733
+ .map(e => e.name);
734
+ } catch { /* intentionally empty */ }
735
+
736
+ const result = {
737
+ // Config
738
+ commit_docs: config.commit_docs,
739
+
740
+ // Current milestone
741
+ milestone_version: milestone.version,
742
+ milestone_name: milestone.name,
743
+ milestone_slug: generateSlugInternal(milestone.name),
744
+
745
+ // Phase counts
746
+ phase_count: phaseCount,
747
+ completed_phases: completedPhases,
748
+ all_phases_complete: phaseCount > 0 && phaseCount === completedPhases,
749
+
750
+ // Archive
751
+ archived_milestones: archivedMilestones,
752
+ archive_count: archivedMilestones.length,
753
+
754
+ // File existence
755
+ project_exists: pathExistsInternal(cwd, '.planning/PROJECT.md'),
756
+ roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
757
+ state_exists: fs.existsSync(path.join(planningDir(cwd), 'STATE.md')),
758
+ archive_exists: fs.existsSync(path.join(planningRoot(cwd), 'archive')),
759
+ phases_dir_exists: fs.existsSync(path.join(planningDir(cwd), 'phases')),
760
+ };
761
+
762
+ output(withProjectRoot(cwd, result), raw);
763
+ }
764
+
765
+ function cmdInitMapCodebase(cwd, raw) {
766
+ const config = loadConfig(cwd);
767
+
768
+ // Check for existing codebase maps
769
+ const codebaseDir = path.join(planningRoot(cwd), 'codebase');
770
+ let existingMaps = [];
771
+ try {
772
+ existingMaps = fs.readdirSync(codebaseDir).filter(f => f.endsWith('.md'));
773
+ } catch { /* intentionally empty */ }
774
+
775
+ const result = {
776
+ // Models
777
+ mapper_model: resolveModelInternal(cwd, 'gsd-codebase-mapper'),
778
+
779
+ // Config
780
+ commit_docs: config.commit_docs,
781
+ search_gitignored: config.search_gitignored,
782
+ parallelization: config.parallelization,
783
+
784
+ // Paths
785
+ codebase_dir: '.planning/codebase',
786
+
787
+ // Existing maps
788
+ existing_maps: existingMaps,
789
+ has_maps: existingMaps.length > 0,
790
+
791
+ // File existence
792
+ planning_exists: pathExistsInternal(cwd, '.planning'),
793
+ codebase_dir_exists: pathExistsInternal(cwd, '.planning/codebase'),
794
+ };
795
+
796
+ output(withProjectRoot(cwd, result), raw);
797
+ }
798
+
799
+ function cmdInitManager(cwd, raw) {
800
+ const config = loadConfig(cwd);
801
+ const milestone = getMilestoneInfo(cwd);
802
+
803
+ // Use planningPaths for forward-compatibility with workstream scoping (#1268)
804
+ const paths = planningPaths(cwd);
805
+
806
+ // Validate prerequisites
807
+ if (!fs.existsSync(paths.roadmap)) {
808
+ error('No ROADMAP.md found. Run /gsd:new-milestone first.');
809
+ }
810
+ if (!fs.existsSync(paths.state)) {
811
+ error('No STATE.md found. Run /gsd:new-milestone first.');
812
+ }
813
+ const rawContent = fs.readFileSync(paths.roadmap, 'utf-8');
814
+ const content = extractCurrentMilestone(rawContent, cwd);
815
+ const phasesDir = paths.phases;
816
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
817
+
818
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
819
+ const phases = [];
820
+ let match;
821
+
822
+ while ((match = phasePattern.exec(content)) !== null) {
823
+ const phaseNum = match[1];
824
+ const phaseName = match[2].replace(/\(INSERTED\)/i, '').trim();
825
+
826
+ const sectionStart = match.index;
827
+ const restOfContent = content.slice(sectionStart);
828
+ const nextHeader = restOfContent.match(/\n#{2,4}\s+Phase\s+\d/i);
829
+ const sectionEnd = nextHeader ? sectionStart + nextHeader.index : content.length;
830
+ const section = content.slice(sectionStart, sectionEnd);
831
+
832
+ const goalMatch = section.match(/\*\*Goal(?::\*\*|\*\*:)\s*([^\n]+)/i);
833
+ const goal = goalMatch ? goalMatch[1].trim() : null;
834
+
835
+ const dependsMatch = section.match(/\*\*Depends on(?::\*\*|\*\*:)\s*([^\n]+)/i);
836
+ const depends_on = dependsMatch ? dependsMatch[1].trim() : null;
837
+
838
+ const normalized = normalizePhaseName(phaseNum);
839
+ let diskStatus = 'no_directory';
840
+ let planCount = 0;
841
+ let summaryCount = 0;
842
+ let hasContext = false;
843
+ let hasResearch = false;
844
+ let lastActivity = null;
845
+ let isActive = false;
846
+
847
+ try {
848
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
849
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).filter(isDirInMilestone);
850
+ const dirMatch = dirs.find(d => d.startsWith(normalized + '-') || d === normalized);
851
+
852
+ if (dirMatch) {
853
+ const fullDir = path.join(phasesDir, dirMatch);
854
+ const phaseFiles = fs.readdirSync(fullDir);
855
+ planCount = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
856
+ summaryCount = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
857
+ hasContext = phaseFiles.some(f => f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md');
858
+ hasResearch = phaseFiles.some(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md');
859
+
860
+ if (summaryCount >= planCount && planCount > 0) diskStatus = 'complete';
861
+ else if (summaryCount > 0) diskStatus = 'partial';
862
+ else if (planCount > 0) diskStatus = 'planned';
863
+ else if (hasResearch) diskStatus = 'researched';
864
+ else if (hasContext) diskStatus = 'discussed';
865
+ else diskStatus = 'empty';
866
+
867
+ // Activity detection: check most recent file mtime
868
+ const now = Date.now();
869
+ let newestMtime = 0;
870
+ for (const f of phaseFiles) {
871
+ try {
872
+ const stat = fs.statSync(path.join(fullDir, f));
873
+ if (stat.mtimeMs > newestMtime) newestMtime = stat.mtimeMs;
874
+ } catch { /* intentionally empty */ }
875
+ }
876
+ if (newestMtime > 0) {
877
+ lastActivity = new Date(newestMtime).toISOString();
878
+ isActive = (now - newestMtime) < 300000; // 5 minutes
879
+ }
880
+ }
881
+ } catch { /* intentionally empty */ }
882
+
883
+ // Check ROADMAP checkbox status
884
+ const checkboxPattern = new RegExp(`-\\s*\\[(x| )\\]\\s*.*Phase\\s+${phaseNum.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[:\\s]`, 'i');
885
+ const checkboxMatch = content.match(checkboxPattern);
886
+ const roadmapComplete = checkboxMatch ? checkboxMatch[1] === 'x' : false;
887
+ if (roadmapComplete && diskStatus !== 'complete') {
888
+ diskStatus = 'complete';
889
+ }
890
+
891
+ phases.push({
892
+ number: phaseNum,
893
+ name: phaseName,
894
+ goal,
895
+ depends_on,
896
+ disk_status: diskStatus,
897
+ has_context: hasContext,
898
+ has_research: hasResearch,
899
+ plan_count: planCount,
900
+ summary_count: summaryCount,
901
+ roadmap_complete: roadmapComplete,
902
+ last_activity: lastActivity,
903
+ is_active: isActive,
904
+ });
905
+ }
906
+
907
+ // Compute display names: truncate to keep table aligned
908
+ const MAX_NAME_WIDTH = 20;
909
+ for (const phase of phases) {
910
+ if (phase.name.length > MAX_NAME_WIDTH) {
911
+ phase.display_name = phase.name.slice(0, MAX_NAME_WIDTH - 1) + '…';
912
+ } else {
913
+ phase.display_name = phase.name;
914
+ }
915
+ }
916
+
917
+ // Dependency satisfaction: check if all depends_on phases are complete
918
+ const completedNums = new Set(phases.filter(p => p.disk_status === 'complete').map(p => p.number));
919
+ for (const phase of phases) {
920
+ if (!phase.depends_on || /^none$/i.test(phase.depends_on.trim())) {
921
+ phase.deps_satisfied = true;
922
+ } else {
923
+ // Parse "Phase 1, Phase 3" or "1, 3" formats
924
+ const depNums = phase.depends_on.match(/\d+(?:\.\d+)*/g) || [];
925
+ phase.deps_satisfied = depNums.every(n => completedNums.has(n));
926
+ phase.dep_phases = depNums;
927
+ }
928
+ }
929
+
930
+ // Compact dependency display for dashboard
931
+ for (const phase of phases) {
932
+ phase.deps_display = (phase.dep_phases && phase.dep_phases.length > 0)
933
+ ? phase.dep_phases.join(',')
934
+ : '—';
935
+ }
936
+
937
+ // Sliding window: discuss is sequential — only the first undiscussed phase is available
938
+ let foundNextToDiscuss = false;
939
+ for (const phase of phases) {
940
+ if (!foundNextToDiscuss && (phase.disk_status === 'empty' || phase.disk_status === 'no_directory')) {
941
+ phase.is_next_to_discuss = true;
942
+ foundNextToDiscuss = true;
943
+ } else {
944
+ phase.is_next_to_discuss = false;
945
+ }
946
+ }
947
+
948
+ // Check for WAITING.json signal
949
+ let waitingSignal = null;
950
+ try {
951
+ const waitingPath = path.join(cwd, '.planning', 'WAITING.json');
952
+ if (fs.existsSync(waitingPath)) {
953
+ waitingSignal = JSON.parse(fs.readFileSync(waitingPath, 'utf-8'));
954
+ }
955
+ } catch { /* intentionally empty */ }
956
+
957
+ // Compute recommended actions (execute > plan > discuss)
958
+ const recommendedActions = [];
959
+ for (const phase of phases) {
960
+ if (phase.disk_status === 'complete') continue;
961
+
962
+ if (phase.disk_status === 'planned' && phase.deps_satisfied) {
963
+ recommendedActions.push({
964
+ phase: phase.number,
965
+ phase_name: phase.name,
966
+ action: 'execute',
967
+ reason: `${phase.plan_count} plans ready, dependencies met`,
968
+ command: `/gsd:execute-phase ${phase.number}`,
969
+ });
970
+ } else if (phase.disk_status === 'discussed' || phase.disk_status === 'researched') {
971
+ recommendedActions.push({
972
+ phase: phase.number,
973
+ phase_name: phase.name,
974
+ action: 'plan',
975
+ reason: 'Context gathered, ready for planning',
976
+ command: `/gsd:plan-phase ${phase.number}`,
977
+ });
978
+ } else if ((phase.disk_status === 'empty' || phase.disk_status === 'no_directory') && phase.is_next_to_discuss) {
979
+ recommendedActions.push({
980
+ phase: phase.number,
981
+ phase_name: phase.name,
982
+ action: 'discuss',
983
+ reason: 'Unblocked, ready to gather context',
984
+ command: `/gsd:discuss-phase ${phase.number}`,
985
+ });
986
+ }
987
+ }
988
+
989
+ // Filter recommendations: no parallel execute/plan unless phases are independent
990
+ // Two phases are "independent" if neither depends on the other (directly or transitively)
991
+ const phaseMap = new Map(phases.map(p => [p.number, p]));
992
+
993
+ function reaches(from, to, visited = new Set()) {
994
+ if (visited.has(from)) return false;
995
+ visited.add(from);
996
+ const p = phaseMap.get(from);
997
+ if (!p || !p.dep_phases || p.dep_phases.length === 0) return false;
998
+ if (p.dep_phases.includes(to)) return true;
999
+ return p.dep_phases.some(dep => reaches(dep, to, visited));
1000
+ }
1001
+
1002
+ function hasDepRelationship(numA, numB) {
1003
+ return reaches(numA, numB) || reaches(numB, numA);
1004
+ }
1005
+
1006
+ // Detect phases with active work (file modified in last 5 min)
1007
+ const activeExecuting = phases.filter(p =>
1008
+ p.disk_status === 'partial' ||
1009
+ (p.disk_status === 'planned' && p.is_active)
1010
+ );
1011
+ const activePlanning = phases.filter(p =>
1012
+ p.is_active && (p.disk_status === 'discussed' || p.disk_status === 'researched')
1013
+ );
1014
+
1015
+ const filteredActions = recommendedActions.filter(action => {
1016
+ if (action.action === 'execute' && activeExecuting.length > 0) {
1017
+ // Only allow if independent of ALL actively-executing phases
1018
+ return activeExecuting.every(active => !hasDepRelationship(action.phase, active.number));
1019
+ }
1020
+ if (action.action === 'plan' && activePlanning.length > 0) {
1021
+ // Only allow if independent of ALL actively-planning phases
1022
+ return activePlanning.every(active => !hasDepRelationship(action.phase, active.number));
1023
+ }
1024
+ return true;
1025
+ });
1026
+
1027
+ const completedCount = phases.filter(p => p.disk_status === 'complete').length;
1028
+ const result = {
1029
+ milestone_version: milestone.version,
1030
+ milestone_name: milestone.name,
1031
+ phases,
1032
+ phase_count: phases.length,
1033
+ completed_count: completedCount,
1034
+ in_progress_count: phases.filter(p => ['partial', 'planned', 'discussed', 'researched'].includes(p.disk_status)).length,
1035
+ recommended_actions: filteredActions,
1036
+ waiting_signal: waitingSignal,
1037
+ all_complete: completedCount === phases.length && phases.length > 0,
1038
+ project_exists: pathExistsInternal(cwd, '.planning/PROJECT.md'),
1039
+ roadmap_exists: true,
1040
+ state_exists: true,
1041
+ };
1042
+
1043
+ output(withProjectRoot(cwd, result), raw);
1044
+ }
1045
+
1046
+ function cmdInitProgress(cwd, raw) {
1047
+ const config = loadConfig(cwd);
1048
+ const milestone = getMilestoneInfo(cwd);
1049
+
1050
+ // Analyze phases — filter to current milestone and include ROADMAP-only phases
1051
+ const phasesDir = path.join(planningDir(cwd), 'phases');
1052
+ const phases = [];
1053
+ let currentPhase = null;
1054
+ let nextPhase = null;
1055
+
1056
+ // Build set of phases defined in ROADMAP for the current milestone
1057
+ const roadmapPhaseNums = new Set();
1058
+ const roadmapPhaseNames = new Map();
1059
+ try {
1060
+ const roadmapContent = extractCurrentMilestone(
1061
+ fs.readFileSync(path.join(planningDir(cwd), 'ROADMAP.md'), 'utf-8'), cwd
1062
+ );
1063
+ const headingPattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
1064
+ let hm;
1065
+ while ((hm = headingPattern.exec(roadmapContent)) !== null) {
1066
+ roadmapPhaseNums.add(hm[1]);
1067
+ roadmapPhaseNames.set(hm[1], hm[2].replace(/\(INSERTED\)/i, '').trim());
1068
+ }
1069
+ } catch { /* intentionally empty */ }
1070
+
1071
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
1072
+ const seenPhaseNums = new Set();
1073
+
1074
+ try {
1075
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
1076
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name)
1077
+ .filter(isDirInMilestone)
1078
+ .sort((a, b) => {
1079
+ const pa = a.match(/^(\d+[A-Z]?(?:\.\d+)*)/i);
1080
+ const pb = b.match(/^(\d+[A-Z]?(?:\.\d+)*)/i);
1081
+ if (!pa || !pb) return a.localeCompare(b);
1082
+ return parseInt(pa[1], 10) - parseInt(pb[1], 10);
1083
+ });
1084
+
1085
+ for (const dir of dirs) {
1086
+ const match = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
1087
+ const phaseNumber = match ? match[1] : dir;
1088
+ const phaseName = match && match[2] ? match[2] : null;
1089
+ seenPhaseNums.add(phaseNumber.replace(/^0+/, '') || '0');
1090
+
1091
+ const phasePath = path.join(phasesDir, dir);
1092
+ const phaseFiles = fs.readdirSync(phasePath);
1093
+
1094
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
1095
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
1096
+ const hasResearch = phaseFiles.some(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md');
1097
+
1098
+ const status = summaries.length >= plans.length && plans.length > 0 ? 'complete' :
1099
+ plans.length > 0 ? 'in_progress' :
1100
+ hasResearch ? 'researched' : 'pending';
1101
+
1102
+ const phaseInfo = {
1103
+ number: phaseNumber,
1104
+ name: phaseName,
1105
+ directory: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'phases', dir))),
1106
+ status,
1107
+ plan_count: plans.length,
1108
+ summary_count: summaries.length,
1109
+ has_research: hasResearch,
1110
+ };
1111
+
1112
+ phases.push(phaseInfo);
1113
+
1114
+ // Find current (first incomplete with plans) and next (first pending)
1115
+ if (!currentPhase && (status === 'in_progress' || status === 'researched')) {
1116
+ currentPhase = phaseInfo;
1117
+ }
1118
+ if (!nextPhase && status === 'pending') {
1119
+ nextPhase = phaseInfo;
1120
+ }
1121
+ }
1122
+ } catch { /* intentionally empty */ }
1123
+
1124
+ // Add phases defined in ROADMAP but not yet scaffolded to disk
1125
+ for (const [num, name] of roadmapPhaseNames) {
1126
+ const stripped = num.replace(/^0+/, '') || '0';
1127
+ if (!seenPhaseNums.has(stripped)) {
1128
+ const phaseInfo = {
1129
+ number: num,
1130
+ name: name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, ''),
1131
+ directory: null,
1132
+ status: 'not_started',
1133
+ plan_count: 0,
1134
+ summary_count: 0,
1135
+ has_research: false,
1136
+ };
1137
+ phases.push(phaseInfo);
1138
+ if (!nextPhase && !currentPhase) {
1139
+ nextPhase = phaseInfo;
1140
+ }
1141
+ }
1142
+ }
1143
+
1144
+ // Re-sort phases by number after adding ROADMAP-only phases
1145
+ phases.sort((a, b) => parseInt(a.number, 10) - parseInt(b.number, 10));
1146
+
1147
+ // Check for paused work
1148
+ let pausedAt = null;
1149
+ try {
1150
+ const state = fs.readFileSync(path.join(planningDir(cwd), 'STATE.md'), 'utf-8');
1151
+ const pauseMatch = state.match(/\*\*Paused At:\*\*\s*(.+)/);
1152
+ if (pauseMatch) pausedAt = pauseMatch[1].trim();
1153
+ } catch { /* intentionally empty */ }
1154
+
1155
+ const result = {
1156
+ // Models
1157
+ executor_model: resolveModelInternal(cwd, 'gsd-executor'),
1158
+ planner_model: resolveModelInternal(cwd, 'gsd-planner'),
1159
+
1160
+ // Config
1161
+ commit_docs: config.commit_docs,
1162
+
1163
+ // Milestone
1164
+ milestone_version: milestone.version,
1165
+ milestone_name: milestone.name,
1166
+
1167
+ // Phase overview
1168
+ phases,
1169
+ phase_count: phases.length,
1170
+ completed_count: phases.filter(p => p.status === 'complete').length,
1171
+ in_progress_count: phases.filter(p => p.status === 'in_progress').length,
1172
+
1173
+ // Current state
1174
+ current_phase: currentPhase,
1175
+ next_phase: nextPhase,
1176
+ paused_at: pausedAt,
1177
+ has_work_in_progress: !!currentPhase,
1178
+
1179
+ // File existence
1180
+ project_exists: pathExistsInternal(cwd, '.planning/PROJECT.md'),
1181
+ roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
1182
+ state_exists: fs.existsSync(path.join(planningDir(cwd), 'STATE.md')),
1183
+ // File paths
1184
+ state_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'STATE.md'))),
1185
+ roadmap_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'ROADMAP.md'))),
1186
+ project_path: '.planning/PROJECT.md',
1187
+ config_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'config.json'))),
1188
+ };
1189
+
1190
+ output(withProjectRoot(cwd, result), raw);
1191
+ }
1192
+
1193
+ /**
1194
+ * Detect child git repos in a directory (one level deep).
1195
+ * Returns array of { name, path, has_uncommitted } objects.
1196
+ */
1197
+ function detectChildRepos(dir) {
1198
+ const repos = [];
1199
+ let entries;
1200
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return repos; }
1201
+ for (const entry of entries) {
1202
+ if (!entry.isDirectory()) continue;
1203
+ if (entry.name.startsWith('.')) continue;
1204
+ const fullPath = path.join(dir, entry.name);
1205
+ const gitDir = path.join(fullPath, '.git');
1206
+ if (fs.existsSync(gitDir)) {
1207
+ let hasUncommitted = false;
1208
+ try {
1209
+ const status = execSync('git status --porcelain', { cwd: fullPath, encoding: 'utf8', timeout: 5000 });
1210
+ hasUncommitted = status.trim().length > 0;
1211
+ } catch { /* best-effort */ }
1212
+ repos.push({ name: entry.name, path: fullPath, has_uncommitted: hasUncommitted });
1213
+ }
1214
+ }
1215
+ return repos;
1216
+ }
1217
+
1218
+ function cmdInitNewWorkspace(cwd, raw) {
1219
+ const homedir = process.env.HOME || require('os').homedir();
1220
+ const defaultBase = path.join(homedir, 'gsd-workspaces');
1221
+
1222
+ // Detect child git repos for interactive selection
1223
+ const childRepos = detectChildRepos(cwd);
1224
+
1225
+ // Check if git worktree is available
1226
+ let worktreeAvailable = false;
1227
+ try {
1228
+ execSync('git --version', { encoding: 'utf8', timeout: 5000, stdio: 'pipe' });
1229
+ worktreeAvailable = true;
1230
+ } catch { /* no git at all */ }
1231
+
1232
+ const result = {
1233
+ default_workspace_base: defaultBase,
1234
+ child_repos: childRepos,
1235
+ child_repo_count: childRepos.length,
1236
+ worktree_available: worktreeAvailable,
1237
+ is_git_repo: pathExistsInternal(cwd, '.git'),
1238
+ cwd_repo_name: path.basename(cwd),
1239
+ };
1240
+
1241
+ output(withProjectRoot(cwd, result), raw);
1242
+ }
1243
+
1244
+ function cmdInitListWorkspaces(cwd, raw) {
1245
+ const homedir = process.env.HOME || require('os').homedir();
1246
+ const defaultBase = path.join(homedir, 'gsd-workspaces');
1247
+
1248
+ const workspaces = [];
1249
+ if (fs.existsSync(defaultBase)) {
1250
+ let entries;
1251
+ try { entries = fs.readdirSync(defaultBase, { withFileTypes: true }); } catch { entries = []; }
1252
+ for (const entry of entries) {
1253
+ if (!entry.isDirectory()) continue;
1254
+ const wsPath = path.join(defaultBase, entry.name);
1255
+ const manifestPath = path.join(wsPath, 'WORKSPACE.md');
1256
+ if (!fs.existsSync(manifestPath)) continue;
1257
+
1258
+ let repoCount = 0;
1259
+ let hasProject = false;
1260
+ let strategy = 'unknown';
1261
+ try {
1262
+ const manifest = fs.readFileSync(manifestPath, 'utf8');
1263
+ const strategyMatch = manifest.match(/^Strategy:\s*(.+)$/m);
1264
+ if (strategyMatch) strategy = strategyMatch[1].trim();
1265
+ // Count table rows (lines starting with |, excluding header and separator)
1266
+ const tableRows = manifest.split('\n').filter(l => l.match(/^\|\s*\w/) && !l.includes('Repo') && !l.includes('---'));
1267
+ repoCount = tableRows.length;
1268
+ } catch { /* best-effort */ }
1269
+ hasProject = fs.existsSync(path.join(wsPath, '.planning', 'PROJECT.md'));
1270
+
1271
+ workspaces.push({
1272
+ name: entry.name,
1273
+ path: wsPath,
1274
+ repo_count: repoCount,
1275
+ strategy,
1276
+ has_project: hasProject,
1277
+ });
1278
+ }
1279
+ }
1280
+
1281
+ const result = {
1282
+ workspace_base: defaultBase,
1283
+ workspaces,
1284
+ workspace_count: workspaces.length,
1285
+ };
1286
+
1287
+ output(result, raw);
1288
+ }
1289
+
1290
+ function cmdInitRemoveWorkspace(cwd, name, raw) {
1291
+ const homedir = process.env.HOME || require('os').homedir();
1292
+ const defaultBase = path.join(homedir, 'gsd-workspaces');
1293
+
1294
+ if (!name) {
1295
+ error('workspace name required for init remove-workspace');
1296
+ }
1297
+
1298
+ const wsPath = path.join(defaultBase, name);
1299
+ const manifestPath = path.join(wsPath, 'WORKSPACE.md');
1300
+
1301
+ if (!fs.existsSync(wsPath)) {
1302
+ error(`Workspace not found: ${wsPath}`);
1303
+ }
1304
+
1305
+ // Parse manifest for repo info
1306
+ const repos = [];
1307
+ let strategy = 'unknown';
1308
+ if (fs.existsSync(manifestPath)) {
1309
+ try {
1310
+ const manifest = fs.readFileSync(manifestPath, 'utf8');
1311
+ const strategyMatch = manifest.match(/^Strategy:\s*(.+)$/m);
1312
+ if (strategyMatch) strategy = strategyMatch[1].trim();
1313
+
1314
+ // Parse table rows for repo names and source paths
1315
+ const lines = manifest.split('\n');
1316
+ for (const line of lines) {
1317
+ const match = line.match(/^\|\s*(\S+)\s*\|\s*(\S+)\s*\|\s*(\S+)\s*\|\s*(\S+)\s*\|$/);
1318
+ if (match && match[1] !== 'Repo' && !match[1].includes('---')) {
1319
+ repos.push({ name: match[1], source: match[2], branch: match[3], strategy: match[4] });
1320
+ }
1321
+ }
1322
+ } catch { /* best-effort */ }
1323
+ }
1324
+
1325
+ // Check for uncommitted changes in workspace repos
1326
+ const dirtyRepos = [];
1327
+ for (const repo of repos) {
1328
+ const repoPath = path.join(wsPath, repo.name);
1329
+ if (!fs.existsSync(repoPath)) continue;
1330
+ try {
1331
+ const status = execSync('git status --porcelain', { cwd: repoPath, encoding: 'utf8', timeout: 5000, stdio: 'pipe' });
1332
+ if (status.trim().length > 0) {
1333
+ dirtyRepos.push(repo.name);
1334
+ }
1335
+ } catch { /* best-effort */ }
1336
+ }
1337
+
1338
+ const result = {
1339
+ workspace_name: name,
1340
+ workspace_path: wsPath,
1341
+ has_manifest: fs.existsSync(manifestPath),
1342
+ strategy,
1343
+ repos,
1344
+ repo_count: repos.length,
1345
+ dirty_repos: dirtyRepos,
1346
+ has_dirty_repos: dirtyRepos.length > 0,
1347
+ };
1348
+
1349
+ output(result, raw);
1350
+ }
1351
+
1352
+ /**
1353
+ * Build a formatted agent skills block for injection into Task() prompts.
1354
+ *
1355
+ * Reads `config.agent_skills[agentType]` and validates each skill path exists
1356
+ * within the project root. Returns a formatted `<agent_skills>` block or empty
1357
+ * string if no skills are configured.
1358
+ *
1359
+ * @param {object} config - Loaded project config
1360
+ * @param {string} agentType - The agent type (e.g., 'gsd-executor', 'gsd-planner')
1361
+ * @param {string} projectRoot - Absolute path to project root (for path validation)
1362
+ * @returns {string} Formatted skills block or empty string
1363
+ */
1364
+ function buildAgentSkillsBlock(config, agentType, projectRoot) {
1365
+ const { validatePath } = require('./security.cjs');
1366
+
1367
+ if (!config || !config.agent_skills || !agentType) return '';
1368
+
1369
+ let skillPaths = config.agent_skills[agentType];
1370
+ if (!skillPaths) return '';
1371
+
1372
+ // Normalize single string to array
1373
+ if (typeof skillPaths === 'string') skillPaths = [skillPaths];
1374
+ if (!Array.isArray(skillPaths) || skillPaths.length === 0) return '';
1375
+
1376
+ const validPaths = [];
1377
+ for (const skillPath of skillPaths) {
1378
+ if (typeof skillPath !== 'string') continue;
1379
+
1380
+ // Validate path safety — must resolve within project root
1381
+ const pathCheck = validatePath(skillPath, projectRoot);
1382
+ if (!pathCheck.safe) {
1383
+ process.stderr.write(`[agent-skills] WARNING: Skipping unsafe path "${skillPath}": ${pathCheck.error}\n`);
1384
+ continue;
1385
+ }
1386
+
1387
+ // Check that the skill directory and SKILL.md exist
1388
+ const skillMdPath = path.join(projectRoot, skillPath, 'SKILL.md');
1389
+ if (!fs.existsSync(skillMdPath)) {
1390
+ process.stderr.write(`[agent-skills] WARNING: Skill not found at "${skillPath}/SKILL.md" — skipping\n`);
1391
+ continue;
1392
+ }
1393
+
1394
+ validPaths.push(skillPath);
1395
+ }
1396
+
1397
+ if (validPaths.length === 0) return '';
1398
+
1399
+ const lines = validPaths.map(p => `- @${p}/SKILL.md`).join('\n');
1400
+ return `<agent_skills>\nRead these user-configured skills:\n${lines}\n</agent_skills>`;
1401
+ }
1402
+
1403
+ /**
1404
+ * Command: output the agent skills block for a given agent type.
1405
+ * Used by workflows: SKILLS=$(node "$TOOLS" agent-skills gsd-executor 2>/dev/null)
1406
+ */
1407
+ function cmdAgentSkills(cwd, agentType, raw) {
1408
+ if (!agentType) {
1409
+ // No agent type — output empty string silently
1410
+ output('', raw, '');
1411
+ return;
1412
+ }
1413
+
1414
+ const config = loadConfig(cwd);
1415
+ const block = buildAgentSkillsBlock(config, agentType, cwd);
1416
+ // Output raw text (not JSON) so workflows can embed it directly
1417
+ if (block) {
1418
+ process.stdout.write(block);
1419
+ }
1420
+ process.exit(0);
1421
+ }
1422
+
1423
+ module.exports = {
1424
+ cmdInitExecutePhase,
1425
+ cmdInitPlanPhase,
1426
+ cmdInitNewProject,
1427
+ cmdInitNewMilestone,
1428
+ cmdInitQuick,
1429
+ cmdInitResume,
1430
+ cmdInitVerifyWork,
1431
+ cmdInitPhaseOp,
1432
+ cmdInitTodos,
1433
+ cmdInitMilestoneOp,
1434
+ cmdInitMapCodebase,
1435
+ cmdInitProgress,
1436
+ cmdInitManager,
1437
+ cmdInitNewWorkspace,
1438
+ cmdInitListWorkspaces,
1439
+ cmdInitRemoveWorkspace,
1440
+ detectChildRepos,
1441
+ buildAgentSkillsBlock,
1442
+ cmdAgentSkills,
1443
+ };