@opengsd/gsd-core 1.2.0-rc.1

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 (503) hide show
  1. package/LICENSE +21 -0
  2. package/README.ja-JP.md +870 -0
  3. package/README.ko-KR.md +861 -0
  4. package/README.md +301 -0
  5. package/README.pt-BR.md +492 -0
  6. package/README.zh-CN.md +842 -0
  7. package/agents/gsd-advisor-researcher.md +127 -0
  8. package/agents/gsd-ai-researcher.md +133 -0
  9. package/agents/gsd-assumptions-analyzer.md +105 -0
  10. package/agents/gsd-code-fixer.md +668 -0
  11. package/agents/gsd-code-reviewer.md +387 -0
  12. package/agents/gsd-codebase-mapper.md +853 -0
  13. package/agents/gsd-debug-session-manager.md +314 -0
  14. package/agents/gsd-debugger.md +1452 -0
  15. package/agents/gsd-doc-classifier.md +168 -0
  16. package/agents/gsd-doc-synthesizer.md +204 -0
  17. package/agents/gsd-doc-verifier.md +217 -0
  18. package/agents/gsd-doc-writer.md +615 -0
  19. package/agents/gsd-domain-researcher.md +153 -0
  20. package/agents/gsd-eval-auditor.md +191 -0
  21. package/agents/gsd-eval-planner.md +154 -0
  22. package/agents/gsd-executor.md +772 -0
  23. package/agents/gsd-framework-selector.md +160 -0
  24. package/agents/gsd-integration-checker.md +470 -0
  25. package/agents/gsd-intel-updater.md +342 -0
  26. package/agents/gsd-nyquist-auditor.md +203 -0
  27. package/agents/gsd-pattern-mapper.md +335 -0
  28. package/agents/gsd-phase-researcher.md +928 -0
  29. package/agents/gsd-plan-checker.md +978 -0
  30. package/agents/gsd-planner.md +1218 -0
  31. package/agents/gsd-project-researcher.md +677 -0
  32. package/agents/gsd-research-synthesizer.md +255 -0
  33. package/agents/gsd-roadmapper.md +688 -0
  34. package/agents/gsd-security-auditor.md +155 -0
  35. package/agents/gsd-ui-auditor.md +495 -0
  36. package/agents/gsd-ui-checker.md +309 -0
  37. package/agents/gsd-ui-researcher.md +380 -0
  38. package/agents/gsd-user-profiler.md +171 -0
  39. package/agents/gsd-verifier.md +917 -0
  40. package/bin/install.js +10936 -0
  41. package/bin/lib/ui-safety-gate.cjs +107 -0
  42. package/commands/gsd/add-tests.md +42 -0
  43. package/commands/gsd/ai-integration-phase.md +37 -0
  44. package/commands/gsd/audit-fix.md +34 -0
  45. package/commands/gsd/audit-milestone.md +37 -0
  46. package/commands/gsd/audit-uat.md +24 -0
  47. package/commands/gsd/autonomous.md +46 -0
  48. package/commands/gsd/capture.md +62 -0
  49. package/commands/gsd/cleanup.md +24 -0
  50. package/commands/gsd/code-review.md +59 -0
  51. package/commands/gsd/complete-milestone.md +143 -0
  52. package/commands/gsd/config.md +56 -0
  53. package/commands/gsd/debug.md +52 -0
  54. package/commands/gsd/discuss-phase.md +76 -0
  55. package/commands/gsd/docs-update.md +49 -0
  56. package/commands/gsd/eval-review.md +33 -0
  57. package/commands/gsd/execute-phase.md +64 -0
  58. package/commands/gsd/explore.md +27 -0
  59. package/commands/gsd/extract-learnings.md +23 -0
  60. package/commands/gsd/fast.md +31 -0
  61. package/commands/gsd/forensics.md +57 -0
  62. package/commands/gsd/graphify.md +199 -0
  63. package/commands/gsd/health.md +31 -0
  64. package/commands/gsd/help.md +28 -0
  65. package/commands/gsd/import.md +41 -0
  66. package/commands/gsd/inbox.md +39 -0
  67. package/commands/gsd/ingest-docs.md +42 -0
  68. package/commands/gsd/manager.md +45 -0
  69. package/commands/gsd/map-codebase.md +83 -0
  70. package/commands/gsd/milestone-summary.md +51 -0
  71. package/commands/gsd/mvp-phase.md +45 -0
  72. package/commands/gsd/new-milestone.md +45 -0
  73. package/commands/gsd/new-project.md +47 -0
  74. package/commands/gsd/ns-context.md +23 -0
  75. package/commands/gsd/ns-ideate.md +24 -0
  76. package/commands/gsd/ns-manage.md +29 -0
  77. package/commands/gsd/ns-project.md +22 -0
  78. package/commands/gsd/ns-review.md +26 -0
  79. package/commands/gsd/ns-workflow.md +28 -0
  80. package/commands/gsd/pause-work.md +43 -0
  81. package/commands/gsd/phase.md +56 -0
  82. package/commands/gsd/plan-phase.md +62 -0
  83. package/commands/gsd/plan-review-convergence.md +59 -0
  84. package/commands/gsd/pr-branch.md +26 -0
  85. package/commands/gsd/profile-user.md +46 -0
  86. package/commands/gsd/progress.md +47 -0
  87. package/commands/gsd/quick.md +174 -0
  88. package/commands/gsd/resume-work.md +30 -0
  89. package/commands/gsd/review-backlog.md +63 -0
  90. package/commands/gsd/review.md +41 -0
  91. package/commands/gsd/secure-phase.md +36 -0
  92. package/commands/gsd/settings.md +29 -0
  93. package/commands/gsd/ship.md +24 -0
  94. package/commands/gsd/sketch.md +60 -0
  95. package/commands/gsd/spec-phase.md +63 -0
  96. package/commands/gsd/spike.md +57 -0
  97. package/commands/gsd/stats.md +19 -0
  98. package/commands/gsd/surface.md +155 -0
  99. package/commands/gsd/thread.md +24 -0
  100. package/commands/gsd/ui-phase.md +35 -0
  101. package/commands/gsd/ui-review.md +33 -0
  102. package/commands/gsd/ultraplan-phase.md +34 -0
  103. package/commands/gsd/undo.md +35 -0
  104. package/commands/gsd/update.md +48 -0
  105. package/commands/gsd/validate-phase.md +36 -0
  106. package/commands/gsd/verify-work.md +39 -0
  107. package/commands/gsd/workspace.md +52 -0
  108. package/commands/gsd/workstreams.md +70 -0
  109. package/get-shit-done/bin/check-latest-version.cjs +106 -0
  110. package/get-shit-done/bin/gsd-tools.cjs +1676 -0
  111. package/get-shit-done/bin/lib/active-workstream-store.cjs +302 -0
  112. package/get-shit-done/bin/lib/adr-parser.cjs +394 -0
  113. package/get-shit-done/bin/lib/agent-command-router.cjs +65 -0
  114. package/get-shit-done/bin/lib/artifacts.cjs +53 -0
  115. package/get-shit-done/bin/lib/audit.cjs +755 -0
  116. package/get-shit-done/bin/lib/check-command-router.cjs +333 -0
  117. package/get-shit-done/bin/lib/cjs-command-router-adapter.cjs +118 -0
  118. package/get-shit-done/bin/lib/clock.cjs +96 -0
  119. package/get-shit-done/bin/lib/clusters.cjs +135 -0
  120. package/get-shit-done/bin/lib/code-review-flags.cjs +74 -0
  121. package/get-shit-done/bin/lib/command-aliases.cjs +815 -0
  122. package/get-shit-done/bin/lib/command-arg-projection.cjs +62 -0
  123. package/get-shit-done/bin/lib/command-routing-hub.cjs +388 -0
  124. package/get-shit-done/bin/lib/commands.cjs +1188 -0
  125. package/get-shit-done/bin/lib/config-schema.cjs +31 -0
  126. package/get-shit-done/bin/lib/config.cjs +728 -0
  127. package/get-shit-done/bin/lib/configuration.cjs +248 -0
  128. package/get-shit-done/bin/lib/context-utilization.cjs +47 -0
  129. package/get-shit-done/bin/lib/core.cjs +2121 -0
  130. package/get-shit-done/bin/lib/decisions.cjs +116 -0
  131. package/get-shit-done/bin/lib/docs.cjs +270 -0
  132. package/get-shit-done/bin/lib/drift.cjs +388 -0
  133. package/get-shit-done/bin/lib/fallow-runner.cjs +109 -0
  134. package/get-shit-done/bin/lib/frontmatter.cjs +389 -0
  135. package/get-shit-done/bin/lib/gap-checker.cjs +205 -0
  136. package/get-shit-done/bin/lib/graphify.cjs +592 -0
  137. package/get-shit-done/bin/lib/gsd2-import.cjs +514 -0
  138. package/get-shit-done/bin/lib/init-command-router.cjs +58 -0
  139. package/get-shit-done/bin/lib/init.cjs +2112 -0
  140. package/get-shit-done/bin/lib/install-profiles.cjs +603 -0
  141. package/get-shit-done/bin/lib/installer-migration-authoring.cjs +117 -0
  142. package/get-shit-done/bin/lib/installer-migration-report.cjs +354 -0
  143. package/get-shit-done/bin/lib/installer-migrations/000-first-time-baseline.cjs +220 -0
  144. package/get-shit-done/bin/lib/installer-migrations/001-legacy-orphan-files.cjs +41 -0
  145. package/get-shit-done/bin/lib/installer-migrations/002-codex-legacy-hooks-json.cjs +80 -0
  146. package/get-shit-done/bin/lib/installer-migrations.cjs +778 -0
  147. package/get-shit-done/bin/lib/intel.cjs +708 -0
  148. package/get-shit-done/bin/lib/learnings.cjs +421 -0
  149. package/get-shit-done/bin/lib/milestone.cjs +314 -0
  150. package/get-shit-done/bin/lib/model-catalog.cjs +212 -0
  151. package/get-shit-done/bin/lib/model-profiles.cjs +31 -0
  152. package/get-shit-done/bin/lib/observability/event.cjs +82 -0
  153. package/get-shit-done/bin/lib/observability/logger.cjs +174 -0
  154. package/get-shit-done/bin/lib/observability/redaction.cjs +50 -0
  155. package/get-shit-done/bin/lib/package-identity.cjs +31 -0
  156. package/get-shit-done/bin/lib/phase-command-router.cjs +191 -0
  157. package/get-shit-done/bin/lib/phase-lifecycle.cjs +80 -0
  158. package/get-shit-done/bin/lib/phase.cjs +1607 -0
  159. package/get-shit-done/bin/lib/phases-command-router.cjs +39 -0
  160. package/get-shit-done/bin/lib/plan-scan.cjs +97 -0
  161. package/get-shit-done/bin/lib/planning-workspace.cjs +238 -0
  162. package/get-shit-done/bin/lib/profile-output.cjs +1141 -0
  163. package/get-shit-done/bin/lib/profile-pipeline.cjs +539 -0
  164. package/get-shit-done/bin/lib/project-root.cjs +112 -0
  165. package/get-shit-done/bin/lib/prompt-budget.cjs +399 -0
  166. package/get-shit-done/bin/lib/review-reviewer-selection.cjs +125 -0
  167. package/get-shit-done/bin/lib/roadmap-command-router.cjs +28 -0
  168. package/get-shit-done/bin/lib/roadmap.cjs +650 -0
  169. package/get-shit-done/bin/lib/runtime-artifact-layout.cjs +301 -0
  170. package/get-shit-done/bin/lib/runtime-homes.cjs +222 -0
  171. package/get-shit-done/bin/lib/runtime-name-policy.cjs +83 -0
  172. package/get-shit-done/bin/lib/runtime-slash.cjs +112 -0
  173. package/get-shit-done/bin/lib/schema-detect.cjs +165 -0
  174. package/get-shit-done/bin/lib/secrets.cjs +32 -0
  175. package/get-shit-done/bin/lib/security.cjs +600 -0
  176. package/get-shit-done/bin/lib/semver-compare.cjs +35 -0
  177. package/get-shit-done/bin/lib/shell-command-projection.cjs +500 -0
  178. package/get-shit-done/bin/lib/state-command-router.cjs +252 -0
  179. package/get-shit-done/bin/lib/state-document.cjs +263 -0
  180. package/get-shit-done/bin/lib/state.cjs +2038 -0
  181. package/get-shit-done/bin/lib/surface.cjs +470 -0
  182. package/get-shit-done/bin/lib/task-command-router.cjs +81 -0
  183. package/get-shit-done/bin/lib/template.cjs +228 -0
  184. package/get-shit-done/bin/lib/uat.cjs +289 -0
  185. package/get-shit-done/bin/lib/update-context.cjs +209 -0
  186. package/get-shit-done/bin/lib/validate-command-router.cjs +83 -0
  187. package/get-shit-done/bin/lib/validate.cjs +92 -0
  188. package/get-shit-done/bin/lib/verify-command-router.cjs +40 -0
  189. package/get-shit-done/bin/lib/verify.cjs +1511 -0
  190. package/get-shit-done/bin/lib/workstream-inventory-builder.cjs +74 -0
  191. package/get-shit-done/bin/lib/workstream-inventory.cjs +146 -0
  192. package/get-shit-done/bin/lib/workstream-name-policy.cjs +94 -0
  193. package/get-shit-done/bin/lib/workstream.cjs +389 -0
  194. package/get-shit-done/bin/lib/worktree-safety.cjs +985 -0
  195. package/get-shit-done/bin/shared/config-defaults.manifest.json +97 -0
  196. package/get-shit-done/bin/shared/config-schema.manifest.json +175 -0
  197. package/get-shit-done/bin/shared/model-catalog.json +122 -0
  198. package/get-shit-done/bin/shared/runtime-aliases.manifest.json +75 -0
  199. package/get-shit-done/bin/verify-reapply-patches.cjs +352 -0
  200. package/get-shit-done/contexts/dev.md +21 -0
  201. package/get-shit-done/contexts/research.md +22 -0
  202. package/get-shit-done/contexts/review.md +23 -0
  203. package/get-shit-done/references/agent-contracts.md +79 -0
  204. package/get-shit-done/references/ai-evals.md +156 -0
  205. package/get-shit-done/references/ai-frameworks.md +186 -0
  206. package/get-shit-done/references/artifact-types.md +131 -0
  207. package/get-shit-done/references/autonomous-smart-discuss.md +277 -0
  208. package/get-shit-done/references/checkpoints.md +814 -0
  209. package/get-shit-done/references/common-bug-patterns.md +114 -0
  210. package/get-shit-done/references/context-budget.md +85 -0
  211. package/get-shit-done/references/continuation-format.md +253 -0
  212. package/get-shit-done/references/debugger-philosophy.md +76 -0
  213. package/get-shit-done/references/decimal-phase-calculation.md +64 -0
  214. package/get-shit-done/references/doc-conflict-engine.md +91 -0
  215. package/get-shit-done/references/domain-probes.md +125 -0
  216. package/get-shit-done/references/execute-mvp-tdd.md +81 -0
  217. package/get-shit-done/references/executor-examples.md +110 -0
  218. package/get-shit-done/references/few-shot-examples/plan-checker.md +73 -0
  219. package/get-shit-done/references/few-shot-examples/verifier.md +109 -0
  220. package/get-shit-done/references/gate-prompts.md +100 -0
  221. package/get-shit-done/references/gates.md +70 -0
  222. package/get-shit-done/references/git-integration.md +298 -0
  223. package/get-shit-done/references/git-planning-commit.md +40 -0
  224. package/get-shit-done/references/ios-scaffold.md +123 -0
  225. package/get-shit-done/references/mandatory-initial-read.md +2 -0
  226. package/get-shit-done/references/model-profile-resolution.md +38 -0
  227. package/get-shit-done/references/model-profiles.md +245 -0
  228. package/get-shit-done/references/mvp-concepts.md +49 -0
  229. package/get-shit-done/references/phase-argument-parsing.md +61 -0
  230. package/get-shit-done/references/planner-antipatterns.md +89 -0
  231. package/get-shit-done/references/planner-chunked.md +49 -0
  232. package/get-shit-done/references/planner-gap-closure.md +62 -0
  233. package/get-shit-done/references/planner-graphify-auto-update.md +67 -0
  234. package/get-shit-done/references/planner-human-verify-mode.md +57 -0
  235. package/get-shit-done/references/planner-interface-context.md +62 -0
  236. package/get-shit-done/references/planner-mvp-mode.md +53 -0
  237. package/get-shit-done/references/planner-reviews.md +39 -0
  238. package/get-shit-done/references/planner-revision.md +87 -0
  239. package/get-shit-done/references/planner-source-audit.md +73 -0
  240. package/get-shit-done/references/planning-config.md +471 -0
  241. package/get-shit-done/references/project-skills-discovery.md +19 -0
  242. package/get-shit-done/references/questioning.md +162 -0
  243. package/get-shit-done/references/revision-loop.md +97 -0
  244. package/get-shit-done/references/scout-codebase.md +51 -0
  245. package/get-shit-done/references/skeleton-template.md +48 -0
  246. package/get-shit-done/references/sketch-interactivity.md +41 -0
  247. package/get-shit-done/references/sketch-theme-system.md +94 -0
  248. package/get-shit-done/references/sketch-tooling.md +45 -0
  249. package/get-shit-done/references/sketch-variant-patterns.md +81 -0
  250. package/get-shit-done/references/spidr-splitting.md +69 -0
  251. package/get-shit-done/references/tdd.md +330 -0
  252. package/get-shit-done/references/thinking-models-debug.md +44 -0
  253. package/get-shit-done/references/thinking-models-execution.md +50 -0
  254. package/get-shit-done/references/thinking-models-planning.md +62 -0
  255. package/get-shit-done/references/thinking-models-research.md +50 -0
  256. package/get-shit-done/references/thinking-models-verification.md +55 -0
  257. package/get-shit-done/references/thinking-partner.md +96 -0
  258. package/get-shit-done/references/ui-brand.md +160 -0
  259. package/get-shit-done/references/universal-anti-patterns.md +63 -0
  260. package/get-shit-done/references/user-profiling.md +681 -0
  261. package/get-shit-done/references/user-story-template.md +58 -0
  262. package/get-shit-done/references/verification-overrides.md +227 -0
  263. package/get-shit-done/references/verification-patterns.md +612 -0
  264. package/get-shit-done/references/verify-mvp-mode.md +85 -0
  265. package/get-shit-done/references/workstream-flag.md +111 -0
  266. package/get-shit-done/references/worktree-path-safety.md +89 -0
  267. package/get-shit-done/templates/AI-SPEC.md +246 -0
  268. package/get-shit-done/templates/DEBUG.md +169 -0
  269. package/get-shit-done/templates/README.md +77 -0
  270. package/get-shit-done/templates/SECURITY.md +61 -0
  271. package/get-shit-done/templates/UAT.md +265 -0
  272. package/get-shit-done/templates/UI-SPEC.md +100 -0
  273. package/get-shit-done/templates/VALIDATION.md +76 -0
  274. package/get-shit-done/templates/claude-md.md +145 -0
  275. package/get-shit-done/templates/codebase/architecture.md +255 -0
  276. package/get-shit-done/templates/codebase/concerns.md +310 -0
  277. package/get-shit-done/templates/codebase/conventions.md +307 -0
  278. package/get-shit-done/templates/codebase/integrations.md +280 -0
  279. package/get-shit-done/templates/codebase/stack.md +186 -0
  280. package/get-shit-done/templates/codebase/structure.md +285 -0
  281. package/get-shit-done/templates/codebase/testing.md +480 -0
  282. package/get-shit-done/templates/config.json +62 -0
  283. package/get-shit-done/templates/context.md +352 -0
  284. package/get-shit-done/templates/continue-here.md +78 -0
  285. package/get-shit-done/templates/copilot-instructions.md +7 -0
  286. package/get-shit-done/templates/debug-subagent-prompt.md +91 -0
  287. package/get-shit-done/templates/dev-preferences.md +21 -0
  288. package/get-shit-done/templates/discovery.md +146 -0
  289. package/get-shit-done/templates/discussion-log.md +63 -0
  290. package/get-shit-done/templates/milestone-archive.md +123 -0
  291. package/get-shit-done/templates/milestone.md +115 -0
  292. package/get-shit-done/templates/phase-prompt.md +610 -0
  293. package/get-shit-done/templates/planner-subagent-prompt.md +117 -0
  294. package/get-shit-done/templates/project.md +186 -0
  295. package/get-shit-done/templates/requirements.md +231 -0
  296. package/get-shit-done/templates/research-project/ARCHITECTURE.md +204 -0
  297. package/get-shit-done/templates/research-project/FEATURES.md +147 -0
  298. package/get-shit-done/templates/research-project/PITFALLS.md +200 -0
  299. package/get-shit-done/templates/research-project/STACK.md +120 -0
  300. package/get-shit-done/templates/research-project/SUMMARY.md +170 -0
  301. package/get-shit-done/templates/research.md +592 -0
  302. package/get-shit-done/templates/retrospective.md +54 -0
  303. package/get-shit-done/templates/roadmap.md +202 -0
  304. package/get-shit-done/templates/spec.md +307 -0
  305. package/get-shit-done/templates/state.md +195 -0
  306. package/get-shit-done/templates/summary-complex.md +59 -0
  307. package/get-shit-done/templates/summary-minimal.md +41 -0
  308. package/get-shit-done/templates/summary-standard.md +48 -0
  309. package/get-shit-done/templates/summary.md +248 -0
  310. package/get-shit-done/templates/user-profile.md +146 -0
  311. package/get-shit-done/templates/user-setup.md +311 -0
  312. package/get-shit-done/templates/verification-report.md +322 -0
  313. package/get-shit-done/workflows/_runtime-launcher.snippet.sh +1 -0
  314. package/get-shit-done/workflows/add-backlog.md +91 -0
  315. package/get-shit-done/workflows/add-phase.md +113 -0
  316. package/get-shit-done/workflows/add-tests.md +355 -0
  317. package/get-shit-done/workflows/add-todo.md +161 -0
  318. package/get-shit-done/workflows/ai-integration-phase.md +295 -0
  319. package/get-shit-done/workflows/analyze-dependencies.md +96 -0
  320. package/get-shit-done/workflows/audit-fix.md +178 -0
  321. package/get-shit-done/workflows/audit-milestone.md +358 -0
  322. package/get-shit-done/workflows/audit-uat.md +110 -0
  323. package/get-shit-done/workflows/autonomous.md +795 -0
  324. package/get-shit-done/workflows/check-todos.md +180 -0
  325. package/get-shit-done/workflows/cleanup.md +155 -0
  326. package/get-shit-done/workflows/code-review-fix.md +502 -0
  327. package/get-shit-done/workflows/code-review.md +656 -0
  328. package/get-shit-done/workflows/complete-milestone.md +855 -0
  329. package/get-shit-done/workflows/debug.md +232 -0
  330. package/get-shit-done/workflows/diagnose-issues.md +241 -0
  331. package/get-shit-done/workflows/discovery-phase.md +291 -0
  332. package/get-shit-done/workflows/discuss-phase/modes/advisor.md +176 -0
  333. package/get-shit-done/workflows/discuss-phase/modes/all.md +28 -0
  334. package/get-shit-done/workflows/discuss-phase/modes/analyze.md +44 -0
  335. package/get-shit-done/workflows/discuss-phase/modes/auto.md +57 -0
  336. package/get-shit-done/workflows/discuss-phase/modes/batch.md +52 -0
  337. package/get-shit-done/workflows/discuss-phase/modes/chain.md +98 -0
  338. package/get-shit-done/workflows/discuss-phase/modes/default.md +141 -0
  339. package/get-shit-done/workflows/discuss-phase/modes/power.md +44 -0
  340. package/get-shit-done/workflows/discuss-phase/modes/text.md +55 -0
  341. package/get-shit-done/workflows/discuss-phase/templates/checkpoint.json +18 -0
  342. package/get-shit-done/workflows/discuss-phase/templates/context.md +136 -0
  343. package/get-shit-done/workflows/discuss-phase/templates/discussion-log.md +50 -0
  344. package/get-shit-done/workflows/discuss-phase-assumptions.md +675 -0
  345. package/get-shit-done/workflows/discuss-phase-power.md +291 -0
  346. package/get-shit-done/workflows/discuss-phase.md +499 -0
  347. package/get-shit-done/workflows/do.md +111 -0
  348. package/get-shit-done/workflows/docs-update.md +1162 -0
  349. package/get-shit-done/workflows/edit-phase.md +295 -0
  350. package/get-shit-done/workflows/eval-review.md +156 -0
  351. package/get-shit-done/workflows/execute-phase/steps/codebase-drift-gate.md +82 -0
  352. package/get-shit-done/workflows/execute-phase/steps/per-plan-worktree-gate.md +94 -0
  353. package/get-shit-done/workflows/execute-phase/steps/post-merge-gate.md +117 -0
  354. package/get-shit-done/workflows/execute-phase.md +1709 -0
  355. package/get-shit-done/workflows/execute-plan.md +526 -0
  356. package/get-shit-done/workflows/explore.md +144 -0
  357. package/get-shit-done/workflows/extract-learnings.md +243 -0
  358. package/get-shit-done/workflows/fast.md +124 -0
  359. package/get-shit-done/workflows/forensics.md +279 -0
  360. package/get-shit-done/workflows/graduation.md +196 -0
  361. package/get-shit-done/workflows/health.md +224 -0
  362. package/get-shit-done/workflows/help/modes/brief.md +22 -0
  363. package/get-shit-done/workflows/help/modes/default.md +50 -0
  364. package/get-shit-done/workflows/help/modes/full.md +784 -0
  365. package/get-shit-done/workflows/help/modes/topic.md +74 -0
  366. package/get-shit-done/workflows/help.md +24 -0
  367. package/get-shit-done/workflows/import.md +254 -0
  368. package/get-shit-done/workflows/inbox.md +387 -0
  369. package/get-shit-done/workflows/ingest-docs.md +339 -0
  370. package/get-shit-done/workflows/insert-phase.md +152 -0
  371. package/get-shit-done/workflows/list-phase-assumptions.md +178 -0
  372. package/get-shit-done/workflows/list-workspaces.md +57 -0
  373. package/get-shit-done/workflows/manager.md +393 -0
  374. package/get-shit-done/workflows/map-codebase.md +444 -0
  375. package/get-shit-done/workflows/milestone-summary.md +224 -0
  376. package/get-shit-done/workflows/mvp-phase.md +222 -0
  377. package/get-shit-done/workflows/new-milestone.md +635 -0
  378. package/get-shit-done/workflows/new-project.md +1555 -0
  379. package/get-shit-done/workflows/new-workspace.md +240 -0
  380. package/get-shit-done/workflows/next.md +299 -0
  381. package/get-shit-done/workflows/node-repair.md +92 -0
  382. package/get-shit-done/workflows/note.md +158 -0
  383. package/get-shit-done/workflows/pause-work.md +244 -0
  384. package/get-shit-done/workflows/plan-milestone-gaps.md +281 -0
  385. package/get-shit-done/workflows/plan-phase.md +1809 -0
  386. package/get-shit-done/workflows/plan-review-convergence.md +346 -0
  387. package/get-shit-done/workflows/plant-seed.md +230 -0
  388. package/get-shit-done/workflows/pr-branch.md +157 -0
  389. package/get-shit-done/workflows/profile-user.md +453 -0
  390. package/get-shit-done/workflows/progress.md +699 -0
  391. package/get-shit-done/workflows/quick.md +1039 -0
  392. package/get-shit-done/workflows/reapply-patches.md +426 -0
  393. package/get-shit-done/workflows/remove-phase.md +156 -0
  394. package/get-shit-done/workflows/remove-workspace.md +108 -0
  395. package/get-shit-done/workflows/resume-project.md +332 -0
  396. package/get-shit-done/workflows/review.md +623 -0
  397. package/get-shit-done/workflows/scan.md +105 -0
  398. package/get-shit-done/workflows/secure-phase.md +180 -0
  399. package/get-shit-done/workflows/session-report.md +146 -0
  400. package/get-shit-done/workflows/settings-advanced.md +620 -0
  401. package/get-shit-done/workflows/settings-integrations.md +312 -0
  402. package/get-shit-done/workflows/settings.md +552 -0
  403. package/get-shit-done/workflows/ship.md +356 -0
  404. package/get-shit-done/workflows/sketch-wrap-up.md +286 -0
  405. package/get-shit-done/workflows/sketch.md +361 -0
  406. package/get-shit-done/workflows/spec-phase.md +262 -0
  407. package/get-shit-done/workflows/spike-wrap-up.md +307 -0
  408. package/get-shit-done/workflows/spike.md +453 -0
  409. package/get-shit-done/workflows/stats.md +80 -0
  410. package/get-shit-done/workflows/sync-skills.md +182 -0
  411. package/get-shit-done/workflows/thread.md +222 -0
  412. package/get-shit-done/workflows/transition.md +694 -0
  413. package/get-shit-done/workflows/ui-phase.md +328 -0
  414. package/get-shit-done/workflows/ui-review.md +193 -0
  415. package/get-shit-done/workflows/ultraplan-phase.md +199 -0
  416. package/get-shit-done/workflows/undo.md +314 -0
  417. package/get-shit-done/workflows/update.md +443 -0
  418. package/get-shit-done/workflows/validate-phase.md +179 -0
  419. package/get-shit-done/workflows/verify-phase.md +544 -0
  420. package/get-shit-done/workflows/verify-work.md +781 -0
  421. package/hooks/dist/gsd-check-update-worker.js +95 -0
  422. package/hooks/dist/gsd-check-update.js +64 -0
  423. package/hooks/dist/gsd-context-monitor.js +195 -0
  424. package/hooks/dist/gsd-graphify-update.sh +158 -0
  425. package/hooks/dist/gsd-phase-boundary.sh +47 -0
  426. package/hooks/dist/gsd-prompt-guard.js +97 -0
  427. package/hooks/dist/gsd-read-guard.js +101 -0
  428. package/hooks/dist/gsd-read-injection-scanner.js +203 -0
  429. package/hooks/dist/gsd-session-state.sh +59 -0
  430. package/hooks/dist/gsd-statusline.js +548 -0
  431. package/hooks/dist/gsd-update-banner.js +134 -0
  432. package/hooks/dist/gsd-validate-commit.sh +57 -0
  433. package/hooks/dist/gsd-workflow-guard.js +166 -0
  434. package/hooks/dist/lib/git-cmd.js +150 -0
  435. package/hooks/dist/lib/gsd-graphify-rebuild.sh +65 -0
  436. package/hooks/gsd-check-update-worker.js +95 -0
  437. package/hooks/gsd-check-update.js +64 -0
  438. package/hooks/gsd-context-monitor.js +195 -0
  439. package/hooks/gsd-graphify-update.sh +158 -0
  440. package/hooks/gsd-phase-boundary.sh +47 -0
  441. package/hooks/gsd-prompt-guard.js +97 -0
  442. package/hooks/gsd-read-guard.js +101 -0
  443. package/hooks/gsd-read-injection-scanner.js +203 -0
  444. package/hooks/gsd-session-state.sh +59 -0
  445. package/hooks/gsd-statusline.js +548 -0
  446. package/hooks/gsd-update-banner.js +134 -0
  447. package/hooks/gsd-validate-commit.sh +57 -0
  448. package/hooks/gsd-workflow-guard.js +166 -0
  449. package/hooks/lib/git-cmd.js +150 -0
  450. package/hooks/lib/gsd-graphify-rebuild.sh +65 -0
  451. package/hooks/managed-hooks-registry.cjs +34 -0
  452. package/package.json +102 -0
  453. package/scripts/affected-tests-lib.cjs +541 -0
  454. package/scripts/audit-workflow-script-paths.cjs +73 -0
  455. package/scripts/base64-scan.sh +339 -0
  456. package/scripts/build-hooks.js +236 -0
  457. package/scripts/changeset/README.md +129 -0
  458. package/scripts/changeset/cli.cjs +392 -0
  459. package/scripts/changeset/github-release-notes.cjs +199 -0
  460. package/scripts/changeset/lint.cjs +110 -0
  461. package/scripts/changeset/new.cjs +137 -0
  462. package/scripts/changeset/parse.cjs +114 -0
  463. package/scripts/changeset/render.cjs +34 -0
  464. package/scripts/changeset/serialize.cjs +130 -0
  465. package/scripts/check-alias-drift.cjs +108 -0
  466. package/scripts/check-env.cjs +302 -0
  467. package/scripts/check-npm-integrity.cjs +209 -0
  468. package/scripts/ci-guard-runner.cjs +16 -0
  469. package/scripts/ci-prepare-test-scope.cjs +46 -0
  470. package/scripts/ci-rebase-check.cjs +85 -0
  471. package/scripts/ci-test-scope.cjs +302 -0
  472. package/scripts/command-contract-helpers.cjs +64 -0
  473. package/scripts/diff-touches-shipped-paths.cjs +147 -0
  474. package/scripts/fix-slash-commands.cjs +147 -0
  475. package/scripts/gen-inventory-manifest.cjs +109 -0
  476. package/scripts/generate-package-identity.cjs +104 -0
  477. package/scripts/lint-command-contract.cjs +108 -0
  478. package/scripts/lint-descriptions.cjs +83 -0
  479. package/scripts/lint-docs-required.cjs +222 -0
  480. package/scripts/lint-no-source-grep-extras.cjs +81 -0
  481. package/scripts/lint-no-source-grep.cjs +174 -0
  482. package/scripts/lint-package-identity-drift.cjs +141 -0
  483. package/scripts/lint-pr-check-project-dir.cjs +98 -0
  484. package/scripts/lint-shared-module-handsync.cjs +388 -0
  485. package/scripts/lint-shell-command-projection-drift.cjs +57 -0
  486. package/scripts/lint-skill-deps.cjs +180 -0
  487. package/scripts/lint-test-file-count.allowlist.json +36 -0
  488. package/scripts/lint-test-file-count.cjs +190 -0
  489. package/scripts/pr-template-policy.cjs +268 -0
  490. package/scripts/prompt-injection-scan.sh +203 -0
  491. package/scripts/release-tarball-smoke.cjs +627 -0
  492. package/scripts/run-affected-tests.cjs +6 -0
  493. package/scripts/run-cross-platform-tests.cjs +63 -0
  494. package/scripts/run-tests.cjs +282 -0
  495. package/scripts/secret-scan-lint.sh +231 -0
  496. package/scripts/secret-scan.sh +358 -0
  497. package/scripts/setup-branch-protection.sh +236 -0
  498. package/scripts/shared-module-handsync-allowlist.json +183 -0
  499. package/scripts/strip-prose-atrefs.cjs +106 -0
  500. package/scripts/sync-rulesets.sh +34 -0
  501. package/scripts/sync-runtime-launcher.cjs +402 -0
  502. package/scripts/test-failure-reasons.cjs +34 -0
  503. package/scripts/workflow-policy.cjs +450 -0
@@ -0,0 +1,2121 @@
1
+ /**
2
+ * Core — Shared utilities, constants, and internal helpers
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+ const path = require('path');
8
+ const { execGit, platformWriteSync, platformReadSync, platformEnsureDir } = require('./shell-command-projection.cjs');
9
+ const { MODEL_PROFILES, AGENT_TO_PHASE_TYPE, VALID_PHASE_TYPES, AGENT_DEFAULT_TIERS, VALID_AGENT_TIERS, nextTier } = require('./model-profiles.cjs');
10
+ const { MODEL_ALIAS_MAP, RUNTIME_PROFILE_MAP, KNOWN_RUNTIMES, RUNTIMES_WITH_REASONING_EFFORT, renderEffortForRuntime, RUNTIMES_WITH_FAST_MODE } = require('./model-catalog.cjs');
11
+ const {
12
+ resolveWorktreeContext,
13
+ parseWorktreePorcelain: parseWorktreePorcelainPolicy,
14
+ planWorktreePrune,
15
+ executeWorktreePrunePlan,
16
+ inspectWorktreeHealth,
17
+ } = require('./worktree-safety.cjs');
18
+ // Compatibility shim: new imports should use planning-workspace.cjs directly.
19
+ const {
20
+ planningDir,
21
+ planningRoot,
22
+ planningPaths,
23
+ withPlanningLock,
24
+ getActiveWorkstream,
25
+ setActiveWorkstream,
26
+ findContextMdIn,
27
+ } = require('./planning-workspace.cjs');
28
+ const { findProjectRoot } = require('./project-root.cjs');
29
+
30
+ // ─── Configuration Module (generated CJS mirror) ────────────────────────────
31
+ // Cycle 4: import canonical defaults + normalization primitives from the
32
+ // generated module; core.cjs no longer carries its own inline literal or its
33
+ // own migration logic. The exported CONFIG_DEFAULTS remains a flat-key object
34
+ // (shape unchanged) so legacy consumers (config.cjs, verify.cjs, tests) require
35
+ // no changes. Values are sourced from the canonical nested manifest.
36
+ const {
37
+ CONFIG_DEFAULTS: CANONICAL_CONFIG_DEFAULTS,
38
+ normalizeLegacyKeys,
39
+ } = require('./configuration.cjs');
40
+
41
+ // ─── Path helpers ────────────────────────────────────────────────────────────
42
+
43
+ /** Normalize a relative path to always use forward slashes (cross-platform). */
44
+ function toPosixPath(p) {
45
+ return p.split(path.sep).join('/');
46
+ }
47
+
48
+ /**
49
+ * Scan immediate child directories for separate git repos.
50
+ * Returns a sorted array of directory names that have their own `.git`.
51
+ * Excludes hidden directories and node_modules.
52
+ */
53
+ function detectSubRepos(cwd) {
54
+ const results = [];
55
+ try {
56
+ const entries = fs.readdirSync(cwd, { withFileTypes: true });
57
+ for (const entry of entries) {
58
+ if (!entry.isDirectory()) continue;
59
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
60
+ const gitPath = path.join(cwd, entry.name, '.git');
61
+ try {
62
+ if (fs.existsSync(gitPath)) {
63
+ results.push(entry.name);
64
+ }
65
+ } catch {}
66
+ }
67
+ } catch {}
68
+ return results.sort();
69
+ }
70
+
71
+ // findProjectRoot is now re-exported from the generated CJS module above.
72
+
73
+ // ─── Output helpers ───────────────────────────────────────────────────────────
74
+
75
+ /**
76
+ * Remove stale gsd-* temp files/dirs older than maxAgeMs (default: 5 minutes).
77
+ * Runs opportunistically before each new temp file write to prevent unbounded accumulation.
78
+ * @param {string} prefix - filename prefix to match (e.g., 'gsd-')
79
+ * @param {object} opts
80
+ * @param {number} opts.maxAgeMs - max age in ms before removal (default: 5 min)
81
+ * @param {boolean} opts.dirsOnly - if true, only remove directories (default: false)
82
+ */
83
+ /**
84
+ * Dedicated GSD temp directory: path.join(os.tmpdir(), 'gsd').
85
+ * Created on first use. Keeps GSD temp files isolated from the system
86
+ * temp directory so reap scans only GSD files (#1975).
87
+ */
88
+ const GSD_TEMP_DIR = path.join(require('os').tmpdir(), 'gsd');
89
+
90
+ function ensureGsdTempDir() {
91
+ platformEnsureDir(GSD_TEMP_DIR);
92
+ }
93
+
94
+ function reapStaleTempFiles(prefix = 'gsd-', { maxAgeMs = 5 * 60 * 1000, dirsOnly = false } = {}) {
95
+ try {
96
+ ensureGsdTempDir();
97
+ const now = Date.now();
98
+ const entries = fs.readdirSync(GSD_TEMP_DIR);
99
+ for (const entry of entries) {
100
+ if (!entry.startsWith(prefix)) continue;
101
+ const fullPath = path.join(GSD_TEMP_DIR, entry);
102
+ try {
103
+ const stat = fs.statSync(fullPath);
104
+ if (now - stat.mtimeMs > maxAgeMs) {
105
+ if (stat.isDirectory()) {
106
+ fs.rmSync(fullPath, { recursive: true, force: true });
107
+ } else if (!dirsOnly) {
108
+ fs.unlinkSync(fullPath);
109
+ }
110
+ }
111
+ } catch {
112
+ // File may have been removed between readdir and stat — ignore
113
+ }
114
+ }
115
+ } catch {
116
+ // Non-critical — don't let cleanup failures break output
117
+ }
118
+ }
119
+
120
+ function output(result, raw, rawValue) {
121
+ let data;
122
+ if (raw && rawValue !== undefined) {
123
+ data = String(rawValue);
124
+ } else {
125
+ const json = JSON.stringify(result, null, 2);
126
+ // Large payloads exceed Claude Code's Bash tool buffer (~50KB).
127
+ // Write to tmpfile and output the path prefixed with @file: so callers can detect it.
128
+ if (json.length > 50000) {
129
+ reapStaleTempFiles();
130
+ ensureGsdTempDir();
131
+ const tmpPath = path.join(GSD_TEMP_DIR, `gsd-${Date.now()}.json`);
132
+ platformWriteSync(tmpPath, json);
133
+ data = '@file:' + tmpPath;
134
+ } else {
135
+ data = json;
136
+ }
137
+ }
138
+ // process.stdout.write() is async when stdout is a pipe — process.exit()
139
+ // can tear down the process before the reader consumes the buffer.
140
+ // fs.writeSync(1, ...) blocks until the kernel accepts the bytes, and
141
+ // skipping process.exit() lets the event loop drain naturally.
142
+ fs.writeSync(1, data);
143
+ }
144
+
145
+ /**
146
+ * Frozen enum of typed reason codes used by error() for structured errors.
147
+ * Each subcommand contributes its own codes; the enum exists so tests can
148
+ * assert against typed values instead of grepping stderr (#2974).
149
+ *
150
+ * Adding a new code:
151
+ * - Pick a snake_case lowercase value (the JSON wire form)
152
+ * - Group by subsystem prefix (CONFIG_*, SDK_*, etc)
153
+ * - Pass it to error(msg, ERROR_REASON.NEW_CODE) at the call site
154
+ */
155
+ const ERROR_REASON = Object.freeze({
156
+ // config-get / config-set
157
+ CONFIG_KEY_NOT_FOUND: 'config_key_not_found',
158
+ CONFIG_NO_FILE: 'config_no_file',
159
+ CONFIG_PARSE_FAILED: 'config_parse_failed',
160
+ CONFIG_INVALID_KEY: 'config_invalid_key',
161
+ // SDK / gsd-tools dispatch
162
+ SDK_FAIL_FAST: 'sdk_fail_fast',
163
+ SDK_UNKNOWN_COMMAND: 'sdk_unknown_command',
164
+ SDK_MISSING_ARG: 'sdk_missing_arg',
165
+ // workflow / phase
166
+ PHASE_NOT_FOUND: 'phase_not_found',
167
+ SUMMARY_NO_PLANNING: 'summary_no_planning',
168
+ // graphify
169
+ GRAPHIFY_NO_GRAPH: 'graphify_no_graph',
170
+ GRAPHIFY_INVALID_QUERY: 'graphify_invalid_query',
171
+ // hooks
172
+ HOOKS_OPT_OUT: 'hooks_opt_out',
173
+ // security-scan
174
+ SECURITY_SCAN_FAILED: 'security_scan_failed',
175
+ // generic
176
+ USAGE: 'usage',
177
+ UNKNOWN: 'unknown',
178
+ });
179
+
180
+ /**
181
+ * Process-level flag: when true, error() emits structured JSON to stderr
182
+ * instead of plain "Error: <message>" text. Set by gsd-tools.cjs when the
183
+ * CLI is invoked with `--json-errors`. Tests opt in to typed-IR error
184
+ * assertions by passing that flag and parsing the JSON.
185
+ *
186
+ * Default off so existing callers and human operators keep their plain-text
187
+ * diagnostics. The structured form is opt-in for tooling and tests (#2974).
188
+ */
189
+ let _jsonErrorMode = false;
190
+ function setJsonErrorMode(v) { _jsonErrorMode = !!v; }
191
+ function getJsonErrorMode() { return _jsonErrorMode; }
192
+
193
+ /**
194
+ * Emit an error and exit. When the second argument is provided it must be
195
+ * a value from ERROR_REASON; tests can assert on `result.reason`. When the
196
+ * process is in JSON-error mode, stderr receives `{ ok: false, reason,
197
+ * message }` so callers can parse it; otherwise stderr keeps the plain
198
+ * text form for human operators.
199
+ */
200
+ function error(message, reason = ERROR_REASON.UNKNOWN) {
201
+ if (_jsonErrorMode) {
202
+ const payload = JSON.stringify({ ok: false, reason, message }) + '\n';
203
+ fs.writeSync(2, payload);
204
+ } else {
205
+ fs.writeSync(2, 'Error: ' + message + '\n');
206
+ }
207
+ process.exit(1);
208
+ }
209
+
210
+ // ─── File & Config utilities ──────────────────────────────────────────────────
211
+
212
+ /**
213
+ * Canonical config defaults — flat-key projection for CJS consumers.
214
+ *
215
+ * Cycle 4: Values are sourced from CANONICAL_CONFIG_DEFAULTS (the nested
216
+ * manifest loaded by configuration.generated.cjs). The flat shape is
217
+ * preserved here so legacy consumers (config.cjs, verify.cjs, tests that
218
+ * regex-parse this source) continue to work without changes. The key names
219
+ * and the `const CONFIG_DEFAULTS = {` pattern are intentionally kept.
220
+ *
221
+ * Mapping notes:
222
+ * - workflow.plan_check → plan_checker (CJS flat name; verify.cjs uses this)
223
+ * - git.* → flat git keys (branching_strategy, templates)
224
+ * - workflow.* → flat names (research, verifier, …)
225
+ * - planning.sub_repos → sub_repos
226
+ * - planning.commit_docs / search_gitignored → top-level flat keys
227
+ */
228
+ const CONFIG_DEFAULTS = {
229
+ model_profile: CANONICAL_CONFIG_DEFAULTS.model_profile,
230
+ commit_docs: CANONICAL_CONFIG_DEFAULTS.commit_docs,
231
+ search_gitignored: CANONICAL_CONFIG_DEFAULTS.search_gitignored,
232
+ branching_strategy: CANONICAL_CONFIG_DEFAULTS.git.branching_strategy,
233
+ phase_branch_template: CANONICAL_CONFIG_DEFAULTS.git.phase_branch_template,
234
+ milestone_branch_template: CANONICAL_CONFIG_DEFAULTS.git.milestone_branch_template,
235
+ quick_branch_template: CANONICAL_CONFIG_DEFAULTS.git.quick_branch_template,
236
+ research: CANONICAL_CONFIG_DEFAULTS.workflow.research,
237
+ plan_checker: CANONICAL_CONFIG_DEFAULTS.workflow.plan_check, // flat CJS name maps to workflow.plan_check
238
+ verifier: CANONICAL_CONFIG_DEFAULTS.workflow.verifier,
239
+ nyquist_validation: CANONICAL_CONFIG_DEFAULTS.workflow.nyquist_validation,
240
+ ai_integration_phase: CANONICAL_CONFIG_DEFAULTS.workflow.ai_integration_phase,
241
+ parallelization: CANONICAL_CONFIG_DEFAULTS.parallelization,
242
+ brave_search: CANONICAL_CONFIG_DEFAULTS.brave_search,
243
+ firecrawl: CANONICAL_CONFIG_DEFAULTS.firecrawl,
244
+ exa_search: CANONICAL_CONFIG_DEFAULTS.exa_search,
245
+ text_mode: CANONICAL_CONFIG_DEFAULTS.workflow.text_mode,
246
+ sub_repos: CANONICAL_CONFIG_DEFAULTS.planning.sub_repos,
247
+ resolve_model_ids: CANONICAL_CONFIG_DEFAULTS.resolve_model_ids,
248
+ context_window: CANONICAL_CONFIG_DEFAULTS.context_window,
249
+ phase_naming: CANONICAL_CONFIG_DEFAULTS.phase_naming,
250
+ project_code: CANONICAL_CONFIG_DEFAULTS.project_code,
251
+ subagent_timeout: CANONICAL_CONFIG_DEFAULTS.workflow.subagent_timeout,
252
+ security_enforcement: CANONICAL_CONFIG_DEFAULTS.workflow.security_enforcement,
253
+ security_asvs_level: CANONICAL_CONFIG_DEFAULTS.workflow.security_asvs_level,
254
+ security_block_on: CANONICAL_CONFIG_DEFAULTS.workflow.security_block_on,
255
+ post_planning_gaps: CANONICAL_CONFIG_DEFAULTS.workflow.post_planning_gaps,
256
+ };
257
+
258
+ /**
259
+ * Deep-merge two plain config objects. `overlay` wins on key conflict.
260
+ * Explicit `null` in overlay overrides base (null means "unset this key").
261
+ * Arrays are replaced, not merged. Non-object primitives use overlay value.
262
+ *
263
+ * Note: `undefined` in overlay is treated as "no value provided" and falls
264
+ * back to base (preserves inheritance). Explicit `null` overrides base.
265
+ */
266
+ function _deepMergeConfig(base, overlay) {
267
+ if (overlay === null || overlay === undefined) return overlay;
268
+ if (typeof base !== 'object' || typeof overlay !== 'object') return overlay;
269
+ const result = { ...base };
270
+ for (const key of Object.keys(overlay)) {
271
+ if (overlay[key] !== null && typeof overlay[key] === 'object' && !Array.isArray(overlay[key])) {
272
+ result[key] = _deepMergeConfig(base[key] ?? {}, overlay[key]);
273
+ } else {
274
+ result[key] = overlay[key];
275
+ }
276
+ }
277
+ return result;
278
+ }
279
+
280
+ function loadConfig(cwd, options = {}) {
281
+ const activeWorkstream = Object.prototype.hasOwnProperty.call(options, 'workstream')
282
+ ? options.workstream
283
+ : (options.workstreamContext && Object.prototype.hasOwnProperty.call(options.workstreamContext, 'ws'))
284
+ ? options.workstreamContext.ws
285
+ : (process.env.GSD_WORKSTREAM || null);
286
+ // When GSD_WORKSTREAM is set, load root config first so workstream config
287
+ // can inherit from it. This prevents users from duplicating model_overrides,
288
+ // workflow.*, etc. across every workstream config (#2714).
289
+ const ws = activeWorkstream;
290
+ // #315 — per-call lazy memo: all three detection sites inside this loadConfig
291
+ // call operate on the same cwd and the subrepo set cannot change mid-call, so
292
+ // a single scan is sufficient. The memo is scoped to THIS call (not module-level)
293
+ // so separate loadConfig invocations each get a fresh scan.
294
+ let cachedSubRepos;
295
+ const getDetectedSubRepos = () => {
296
+ if (cachedSubRepos === undefined) cachedSubRepos = detectSubRepos(cwd);
297
+ // Return a copy: original detectSubRepos returned a fresh array per call,
298
+ // so each site must keep an independent array (avoid cross-site aliasing).
299
+ return cachedSubRepos.slice();
300
+ };
301
+ let rootParsed = null;
302
+ if (ws) {
303
+ const rootConfigPath = path.join(planningRoot(cwd), 'config.json');
304
+ try {
305
+ const raw = platformReadSync(rootConfigPath);
306
+ if (raw === null) throw new Error('missing');
307
+ rootParsed = JSON.parse(raw);
308
+ // Cycle 4: delegate all legacy-key normalization to the Configuration Module.
309
+ // normalizeLegacyKeys handles branching_strategy → git.branching_strategy,
310
+ // sub_repos → planning.sub_repos, multiRepo, and depth → granularity.
311
+ const { parsed: rootNormalized, normalizations: rootNorms } = normalizeLegacyKeys(rootParsed);
312
+ if (rootNorms.length > 0) {
313
+ // Resolve filesystem-dependent normalizations (multiRepo → planning.sub_repos)
314
+ for (const norm of rootNorms) {
315
+ if (norm.requiresFilesystem && !rootNormalized.planning?.sub_repos) {
316
+ const detected = getDetectedSubRepos();
317
+ if (detected.length > 0) {
318
+ if (!rootNormalized.planning) rootNormalized.planning = {};
319
+ rootNormalized.planning.sub_repos = detected;
320
+ rootNormalized.planning.commit_docs = false;
321
+ }
322
+ }
323
+ }
324
+ rootParsed = rootNormalized;
325
+ try { platformWriteSync(rootConfigPath, JSON.stringify(rootParsed, null, 2)); } catch {}
326
+ } else {
327
+ rootParsed = rootNormalized;
328
+ }
329
+ } catch {
330
+ // Root config missing or unparseable — workstream config stands alone
331
+ }
332
+ }
333
+
334
+ const configPath = path.join(planningDir(cwd, ws), 'config.json');
335
+ const defaults = CONFIG_DEFAULTS;
336
+
337
+ try {
338
+ const raw = platformReadSync(configPath);
339
+ if (raw === null) throw new Error('missing');
340
+ // `fileData` is the parsed content of the config.json file on disk — used
341
+ // for migrations and writes so we never persist merged values back to disk.
342
+ const fileData = JSON.parse(raw);
343
+
344
+ // Cycle 4: Single normalizeLegacyKeys call replaces all four inline migration
345
+ // blocks (depth→granularity, multiRepo→planning.sub_repos, sub_repos→planning.sub_repos,
346
+ // branching_strategy→git.branching_strategy). The Module is pure (no I/O); disk
347
+ // writeback is handled below with the existing platformWriteSync pattern.
348
+ // Note: migrateOnDisk from the Module is async; loadConfig is sync — so we
349
+ // call normalizeLegacyKeys inline and do the writeback at the call site.
350
+ // Per brief §4.3: "use normalizeLegacyKeys directly and do writeback inline."
351
+ let configDirty = false;
352
+ {
353
+ const { parsed: normalized, normalizations } = normalizeLegacyKeys(fileData);
354
+ if (normalizations.length > 0) {
355
+ // Merge normalized values back into fileData (mutation-in-place for legacy code below)
356
+ Object.keys(fileData).forEach(k => delete fileData[k]);
357
+ Object.assign(fileData, normalized);
358
+ configDirty = true;
359
+ // Resolve filesystem-dependent normalizations (multiRepo → planning.sub_repos).
360
+ // Guard: only populate sub_repos from filesystem if not already set by normalization
361
+ // AND the original file didn't have sub_repos already (preserve existing intent).
362
+ for (const norm of normalizations) {
363
+ if (norm.requiresFilesystem && !fileData.planning?.sub_repos) {
364
+ const detected = getDetectedSubRepos();
365
+ if (detected.length > 0) {
366
+ if (!fileData.planning) fileData.planning = {};
367
+ fileData.planning.sub_repos = detected;
368
+ fileData.planning.commit_docs = false;
369
+ }
370
+ }
371
+ }
372
+ }
373
+ }
374
+
375
+ // Keep planning.sub_repos in sync with actual filesystem
376
+ const currentSubRepos = fileData.planning?.sub_repos || [];
377
+ if (Array.isArray(currentSubRepos) && currentSubRepos.length > 0) {
378
+ const detected = getDetectedSubRepos();
379
+ if (detected.length > 0) {
380
+ const sorted = [...currentSubRepos].sort();
381
+ if (JSON.stringify(sorted) !== JSON.stringify(detected)) {
382
+ if (!fileData.planning) fileData.planning = {};
383
+ fileData.planning.sub_repos = detected;
384
+ configDirty = true;
385
+ }
386
+ }
387
+ }
388
+
389
+ // Persist sub_repos changes (migration or sync) — write only the on-disk
390
+ // file contents, never the merged result, to avoid polluting workstream configs.
391
+ if (configDirty) {
392
+ try { platformWriteSync(configPath, JSON.stringify(fileData, null, 2)); } catch {}
393
+ }
394
+
395
+ // Now apply root→workstream inheritance. `parsed` is the effective config
396
+ // used for value extraction below; fileData is kept for disk writes only.
397
+ const parsed = rootParsed ? _deepMergeConfig(rootParsed, fileData) : fileData;
398
+
399
+ // Warn about unrecognized top-level keys so users don't silently lose config.
400
+ // Derived from config-set's VALID_CONFIG_KEYS (canonical source) plus internal-only
401
+ // keys that loadConfig handles but config-set doesn't expose. This avoids maintaining
402
+ // a hardcoded duplicate that drifts when new config keys are added.
403
+ // DYNAMIC_KEY_PATTERNS supplies topLevel for each pattern so adding a new
404
+ // dynamic-pattern namespace to config-schema.cjs automatically updates this set
405
+ // — no more drift between the read side and the write side (#2687).
406
+ const { VALID_CONFIG_KEYS, DYNAMIC_KEY_PATTERNS } = require('./config-schema.cjs');
407
+ const KNOWN_TOP_LEVEL = new Set([
408
+ // Extract top-level key names from dot-notation paths (e.g., 'workflow.research' → 'workflow')
409
+ ...[...VALID_CONFIG_KEYS].map(k => k.split('.')[0]),
410
+ // Dynamic-pattern top-level containers (e.g. review, model_profile_overrides)
411
+ ...DYNAMIC_KEY_PATTERNS.map(p => p.topLevel),
412
+ // Internal keys loadConfig reads but config-set doesn't expose
413
+ 'model_overrides', 'context_window', 'resolve_model_ids', 'claude_md_path', 'effort', 'fast_mode',
414
+ // Deprecated keys (still accepted for migration, not in config-set)
415
+ // 'branching_strategy' is kept here as a safety net: it is migrated to
416
+ // git.branching_strategy above (#3523), but on the first read of a root
417
+ // config that feeds into a workstream merge, `parsed` may still surface it.
418
+ 'depth', 'multiRepo', 'branching_strategy',
419
+ ]);
420
+ const unknownKeys = Object.keys(parsed).filter(k => !KNOWN_TOP_LEVEL.has(k));
421
+ if (unknownKeys.length > 0) {
422
+ // Deduplicate: a single `init phase-op N` invocation calls loadConfig twice
423
+ // (once for the sub-command setup, once for git-config resolution). Guard with
424
+ // a module-level Set so the same message never fires more than once per process.
425
+ const warnKey = unknownKeys.join(',');
426
+ if (!_warnedUnknownConfigKeys.has(warnKey)) {
427
+ _warnedUnknownConfigKeys.add(warnKey);
428
+ process.stderr.write(
429
+ `gsd-tools: warning: unknown config key(s) in .planning/config.json: ${unknownKeys.join(', ')} — these will be ignored\n`
430
+ );
431
+ }
432
+ }
433
+
434
+ // #2517 — Validate runtime/tier values for keys that loadConfig handles but
435
+ // can be edited directly into config.json (bypassing config-set's enum check).
436
+ // This catches typos like `runtime: "codx"` and `model_profile_overrides.codex.banana`
437
+ // at read time without rejecting back-compat values from new runtimes
438
+ // (review findings #10, #13).
439
+ _warnUnknownProfileOverrides(parsed, '.planning/config.json');
440
+
441
+ const get = (key, nested) => {
442
+ if (parsed[key] !== undefined) return parsed[key];
443
+ if (nested && parsed[nested.section] && parsed[nested.section][nested.field] !== undefined) {
444
+ return parsed[nested.section][nested.field];
445
+ }
446
+ return undefined;
447
+ };
448
+
449
+ const parallelization = (() => {
450
+ const val = get('parallelization');
451
+ if (typeof val === 'boolean') return val;
452
+ if (typeof val === 'object' && val !== null && 'enabled' in val) return val.enabled;
453
+ return defaults.parallelization;
454
+ })();
455
+
456
+ return {
457
+ model_profile: get('model_profile') ?? defaults.model_profile,
458
+ commit_docs: (() => {
459
+ const explicit = get('commit_docs', { section: 'planning', field: 'commit_docs' });
460
+ // If explicitly set in config, respect the user's choice
461
+ if (explicit !== undefined) return explicit;
462
+ // Auto-detection: when no explicit value and .planning/ is gitignored,
463
+ // default to false instead of true
464
+ if (isGitIgnored(cwd, '.planning/')) return false;
465
+ return defaults.commit_docs;
466
+ })(),
467
+ search_gitignored: get('search_gitignored', { section: 'planning', field: 'search_gitignored' }) ?? defaults.search_gitignored,
468
+ branching_strategy: get('branching_strategy', { section: 'git', field: 'branching_strategy' }) ?? defaults.branching_strategy,
469
+ phase_branch_template: get('phase_branch_template', { section: 'git', field: 'phase_branch_template' }) ?? defaults.phase_branch_template,
470
+ milestone_branch_template: get('milestone_branch_template', { section: 'git', field: 'milestone_branch_template' }) ?? defaults.milestone_branch_template,
471
+ quick_branch_template: get('quick_branch_template', { section: 'git', field: 'quick_branch_template' }) ?? defaults.quick_branch_template,
472
+ research: get('research', { section: 'workflow', field: 'research' }) ?? defaults.research,
473
+ plan_checker: get('plan_checker', { section: 'workflow', field: 'plan_check' }) ?? defaults.plan_checker,
474
+ verifier: get('verifier', { section: 'workflow', field: 'verifier' }) ?? defaults.verifier,
475
+ nyquist_validation: get('nyquist_validation', { section: 'workflow', field: 'nyquist_validation' }) ?? defaults.nyquist_validation,
476
+ post_planning_gaps: get('post_planning_gaps', { section: 'workflow', field: 'post_planning_gaps' }) ?? defaults.post_planning_gaps,
477
+ parallelization,
478
+ brave_search: get('brave_search') ?? defaults.brave_search,
479
+ firecrawl: get('firecrawl') ?? defaults.firecrawl,
480
+ exa_search: get('exa_search') ?? defaults.exa_search,
481
+ tdd_mode: get('tdd_mode', { section: 'workflow', field: 'tdd_mode' }) ?? false,
482
+ mvp_mode: get('mvp_mode', { section: 'workflow', field: 'mvp_mode' }) ?? false,
483
+ text_mode: get('text_mode', { section: 'workflow', field: 'text_mode' }) ?? defaults.text_mode,
484
+ auto_advance: get('auto_advance', { section: 'workflow', field: 'auto_advance' }) ?? false,
485
+ _auto_chain_active: get('_auto_chain_active', { section: 'workflow', field: '_auto_chain_active' }) ?? false,
486
+ mode: get('mode') ?? 'interactive',
487
+ sub_repos: get('sub_repos', { section: 'planning', field: 'sub_repos' }) ?? defaults.sub_repos,
488
+ resolve_model_ids: get('resolve_model_ids') ?? defaults.resolve_model_ids,
489
+ context_window: get('context_window') ?? defaults.context_window,
490
+ phase_naming: get('phase_naming') ?? defaults.phase_naming,
491
+ project_code: get('project_code') ?? defaults.project_code,
492
+ subagent_timeout: get('subagent_timeout', { section: 'workflow', field: 'subagent_timeout' }) ?? defaults.subagent_timeout,
493
+ model_overrides: parsed.model_overrides || null,
494
+ // #3023 — per-phase-type model map. Six named slots
495
+ // (planning/discuss/research/execution/verification/completion).
496
+ // Resolves between per-agent override and profile-derived tier in
497
+ // resolveModelInternal. Defaults to null so configs without it
498
+ // behave exactly as today.
499
+ models: parsed.models || null,
500
+ // #3024 — dynamic routing block. When `enabled: true`, the
501
+ // resolveModelForTier() resolver picks tier_models[default_tier]
502
+ // for the agent and escalates one tier per attempt up to
503
+ // max_escalations. Disabled by default for backward compat.
504
+ dynamic_routing: parsed.dynamic_routing || null,
505
+ // #2517 — runtime-aware profiles. `runtime` defaults to null (back-compat).
506
+ // When null, resolveModelInternal preserves today's Claude-native behavior.
507
+ // NOTE: `runtime` and `model_profile_overrides` are intentionally read
508
+ // flat-only (not via `get()` with a workflow.X fallback) — they are
509
+ // top-level keys per docs/CONFIGURATION.md. The lighter-touch decision
510
+ // here was to document the constraint rather than introduce nested
511
+ // resolution edge cases for two new keys (review finding #9). The
512
+ // schema validation in `_warnUnknownProfileOverrides` runs against the
513
+ // raw `parsed` blob, so direct `.planning/config.json` edits surface
514
+ // unknown runtime/tier names at load time, not silently (review finding #10).
515
+ runtime: parsed.runtime || null,
516
+ model_profile_overrides: parsed.model_profile_overrides || null,
517
+ // #443 — effort/fast_mode: pass through from config.json; resolvers handle
518
+ // defaults + tier lookups internally.
519
+ effort: parsed.effort || null,
520
+ fast_mode: parsed.fast_mode || null,
521
+ agent_skills: parsed.agent_skills || {},
522
+ manager: parsed.manager || {},
523
+ response_language: get('response_language') || null,
524
+ claude_md_path: get('claude_md_path') || null,
525
+ claude_md_assembly: parsed.claude_md_assembly || null,
526
+ };
527
+ } catch {
528
+ // Fall back to ~/.gsd/defaults.json only for truly pre-project contexts (#1683)
529
+ // If .planning/ exists, the project is initialized — just missing config.json.
530
+ // When GSD_WORKSTREAM is set and root config was loaded, the workstream config
531
+ // doesn't exist — treat root config as the effective config for this workstream.
532
+ if (fs.existsSync(planningDir(cwd, ws))) {
533
+ if (rootParsed) {
534
+ // Workstream has no config.json: re-parse using root config as the sole source.
535
+ // Keep env immutable by explicitly reloading with workstream context cleared.
536
+ return loadConfig(cwd, { workstream: null });
537
+ }
538
+ return defaults;
539
+ }
540
+ try {
541
+ const home = process.env.GSD_HOME || os.homedir();
542
+ const globalDefaultsPath = path.join(home, '.gsd', 'defaults.json');
543
+ const raw = platformReadSync(globalDefaultsPath);
544
+ if (raw === null) throw new Error('missing');
545
+ const globalDefaults = JSON.parse(raw);
546
+ return {
547
+ ...defaults,
548
+ model_profile: globalDefaults.model_profile ?? defaults.model_profile,
549
+ commit_docs: globalDefaults.commit_docs ?? defaults.commit_docs,
550
+ research: globalDefaults.research ?? defaults.research,
551
+ plan_checker: globalDefaults.plan_checker ?? defaults.plan_checker,
552
+ verifier: globalDefaults.verifier ?? defaults.verifier,
553
+ nyquist_validation: globalDefaults.nyquist_validation ?? defaults.nyquist_validation,
554
+ post_planning_gaps: globalDefaults.post_planning_gaps
555
+ ?? globalDefaults.workflow?.post_planning_gaps
556
+ ?? defaults.post_planning_gaps,
557
+ parallelization: globalDefaults.parallelization ?? defaults.parallelization,
558
+ text_mode: globalDefaults.text_mode ?? defaults.text_mode,
559
+ resolve_model_ids: globalDefaults.resolve_model_ids ?? defaults.resolve_model_ids,
560
+ context_window: globalDefaults.context_window ?? defaults.context_window,
561
+ subagent_timeout: globalDefaults.subagent_timeout ?? defaults.subagent_timeout,
562
+ model_overrides: globalDefaults.model_overrides || null,
563
+ models: globalDefaults.models || null,
564
+ dynamic_routing: globalDefaults.dynamic_routing || null,
565
+ effort: globalDefaults.effort || null,
566
+ fast_mode: globalDefaults.fast_mode || null,
567
+ agent_skills: globalDefaults.agent_skills || {},
568
+ response_language: globalDefaults.response_language || null,
569
+ };
570
+ } catch {
571
+ return defaults;
572
+ }
573
+ }
574
+ }
575
+
576
+ // ─── Git utilities ────────────────────────────────────────────────────────────
577
+
578
+ // Module-level deduplication for unknown-key warnings (#3523).
579
+ // A single `init phase-op N` call invokes loadConfig more than once; this Set
580
+ // prevents the same warning from being echoed on each invocation.
581
+ const _warnedUnknownConfigKeys = new Set();
582
+
583
+ const _gitIgnoredCache = new Map();
584
+
585
+ function isGitIgnored(cwd, targetPath) {
586
+ const key = cwd + '::' + targetPath;
587
+ if (_gitIgnoredCache.has(key)) return _gitIgnoredCache.get(key);
588
+ // --no-index checks .gitignore rules regardless of whether the file is tracked.
589
+ // Without it, git check-ignore returns "not ignored" for tracked files even when
590
+ // .gitignore explicitly lists them — a common source of confusion when .planning/
591
+ // was committed before being added to .gitignore.
592
+ // Array args (via the seam) prevent shell interpretation of special characters in
593
+ // file paths — avoids command injection via crafted path names.
594
+ const result = execGit(['check-ignore', '-q', '--no-index', '--', targetPath], { cwd });
595
+ const ignored = result.exitCode === 0;
596
+ _gitIgnoredCache.set(key, ignored);
597
+ return ignored;
598
+ }
599
+
600
+ // ─── Common path helpers ──────────────────────────────────────────────────────
601
+
602
+ /**
603
+ * Resolve the main worktree root when running inside a git worktree.
604
+ * In a linked worktree, .planning/ lives in the main worktree, not in the linked one.
605
+ * Returns the main worktree path, or cwd if not in a worktree.
606
+ */
607
+ function resolveWorktreeRoot(cwd) {
608
+ // Omit execGit so worktree-safety uses its own execGitDefault — that wrapper
609
+ // delegates to the seam and derives the `timedOut` field that pruneResult
610
+ // branches on below.
611
+ const context = resolveWorktreeContext(cwd, {
612
+ existsSync: fs.existsSync,
613
+ });
614
+ return context.effectiveRoot;
615
+ }
616
+
617
+ /**
618
+ * Parse `git worktree list --porcelain` output into an array of
619
+ * { path, branch } objects. Entries with a detached HEAD (no branch line)
620
+ * are skipped because we cannot safely reason about their merge status.
621
+ *
622
+ * @param {string} porcelain - raw output from git worktree list --porcelain
623
+ * @returns {{ path: string, branch: string }[]}
624
+ */
625
+ function parseWorktreePorcelain(porcelain) {
626
+ return parseWorktreePorcelainPolicy(porcelain);
627
+ }
628
+
629
+ /**
630
+ * Clear stale worktree metadata references via `git worktree prune`.
631
+ *
632
+ * Destructive linked-worktree removal is disabled by default for safety.
633
+ *
634
+ * @param {string} repoRoot - absolute path to the main (or any) worktree of
635
+ * the repository; used as `cwd` for git commands.
636
+ * @returns {string[]} list of worktree paths that were removed (always empty)
637
+ */
638
+ function pruneOrphanedWorktrees(repoRoot) {
639
+ try {
640
+ const plan = planWorktreePrune(
641
+ repoRoot,
642
+ { allowDestructive: false },
643
+ { parseWorktreePorcelain }
644
+ );
645
+ const pruneResult = executeWorktreePrunePlan(plan);
646
+ if (pruneResult && pruneResult.timedOut) {
647
+ // AC2: surface structured warning instead of silently swallowing the timeout.
648
+ // Uses process.stderr.write to match the [gsd-tools] WARNING prefix style.
649
+ process.stderr.write(
650
+ '[gsd-tools] WARNING: worktree health check degraded' +
651
+ ' — git worktree prune timed out after 10s.' +
652
+ ' Orphaned worktree metadata may remain until the next successful run.\n'
653
+ );
654
+ }
655
+ } catch { /* never crash the caller */ }
656
+ return [];
657
+ }
658
+
659
+ // ─── Planning workspace (pathing + active workstream + lock) moved to planning-workspace.cjs ───
660
+
661
+ // ─── Phase utilities ──────────────────────────────────────────────────────────
662
+
663
+ function escapeRegex(value) {
664
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
665
+ }
666
+
667
+ function normalizePhaseName(phase) {
668
+ const str = String(phase);
669
+ // Strip optional project_code prefix (e.g., 'CK-01' → '01')
670
+ const stripped = str.replace(/^[A-Z]{1,6}-(?=\d)/, '');
671
+ // Standard numeric phases: 1, 01, 12A, 12.1
672
+ const match = stripped.match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
673
+ if (match) {
674
+ const padded = match[1].padStart(2, '0');
675
+ // Preserve original case of letter suffix (#1962).
676
+ // Uppercasing causes directory/roadmap mismatches on case-sensitive filesystems
677
+ // (e.g., "16c" in ROADMAP.md → directory "16C-name" → progress can't match).
678
+ const letter = match[2] || '';
679
+ const decimal = match[3] || '';
680
+ return padded + letter + decimal;
681
+ }
682
+ // Custom phase IDs (e.g. PROJ-42, AUTH-101): return as-is
683
+ return str;
684
+ }
685
+
686
+ /**
687
+ * Render a regex source fragment matching a phase number against ROADMAP/STATE
688
+ * prose regardless of zero-padding on either side. Skills pass the resolved
689
+ * padded form (`02.7`), but human-authored ROADMAP prose is conventionally
690
+ * un-padded (`### Phase 2.7:`); a naive `escapeRegex(phaseNum)` fragment never
691
+ * matches when the two diverge. Strips leading zeros from the integer part
692
+ * before re-emitting with a `0*` prefix, so the fragment matches both `2.7`
693
+ * and `02.7` (and `002.7`).
694
+ *
695
+ * Falls back to `escapeRegex(phaseNum)` for non-numeric IDs (custom project
696
+ * codes like `PROJ-42`) so callers can substitute it unconditionally.
697
+ *
698
+ * See #3537 — wired into every ROADMAP-prose regex builder.
699
+ */
700
+ function phaseMarkdownRegexSource(phaseNum) {
701
+ const stripped = String(phaseNum).replace(/^[A-Z]{1,6}-(?=\d)/i, '');
702
+ const match = stripped.match(/^0*(\d+)([A-Z])?((?:\.\d+)*)$/i);
703
+ if (!match) return escapeRegex(phaseNum);
704
+
705
+ const integer = match[1].replace(/^0+/, '') || '0';
706
+ const letter = match[2] ? escapeRegex(match[2]) : '';
707
+ const decimal = match[3] ? escapeRegex(match[3]) : '';
708
+ return `0*${escapeRegex(integer)}${letter}${decimal}`;
709
+ }
710
+
711
+ /**
712
+ * #3599: when the caller passed a project-code-prefixed ID like `PROJ-42`,
713
+ * return the exact-escaped form so the caller can search the ROADMAP for
714
+ * `### Phase PROJ-42:` BEFORE falling back to the padding-tolerant numeric
715
+ * form. Returns null when the input has no project-code prefix — in that
716
+ * case the numeric form (`phaseMarkdownRegexSource`) is the only thing the
717
+ * caller needs.
718
+ *
719
+ * Two-pass at the call site preserves the #3537 contract (`CK-01` directory
720
+ * names mapping to `Phase 1:` prose) while letting `PROJ-42` resolve to its
721
+ * own prefixed heading without cross-matching a bare `### Phase 42:` that
722
+ * happens to share the trailing integer.
723
+ */
724
+ function phaseMarkdownRegexSourceExact(phaseNum) {
725
+ const raw = String(phaseNum);
726
+ if (!/^[A-Z]{1,6}-(?=\d)/i.test(raw)) return null;
727
+ return escapeRegex(raw);
728
+ }
729
+
730
+ function comparePhaseNum(a, b) {
731
+ // Strip optional project_code prefix before comparing (e.g., 'CK-01-name' → '01-name')
732
+ const sa = String(a).replace(/^[A-Z]{1,6}-/, '');
733
+ const sb = String(b).replace(/^[A-Z]{1,6}-/, '');
734
+ const pa = sa.match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
735
+ const pb = sb.match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
736
+ // If either is non-numeric (custom ID), fall back to string comparison
737
+ if (!pa || !pb) return String(a).localeCompare(String(b));
738
+ const intDiff = parseInt(pa[1], 10) - parseInt(pb[1], 10);
739
+ if (intDiff !== 0) return intDiff;
740
+ // No letter sorts before letter: 12 < 12A < 12B
741
+ const la = (pa[2] || '').toUpperCase();
742
+ const lb = (pb[2] || '').toUpperCase();
743
+ if (la !== lb) {
744
+ if (!la) return -1;
745
+ if (!lb) return 1;
746
+ return la < lb ? -1 : 1;
747
+ }
748
+ // Segment-by-segment decimal comparison: 12A < 12A.1 < 12A.1.2 < 12A.2
749
+ const aDecParts = pa[3] ? pa[3].slice(1).split('.').map(p => parseInt(p, 10)) : [];
750
+ const bDecParts = pb[3] ? pb[3].slice(1).split('.').map(p => parseInt(p, 10)) : [];
751
+ const maxLen = Math.max(aDecParts.length, bDecParts.length);
752
+ if (aDecParts.length === 0 && bDecParts.length > 0) return -1;
753
+ if (bDecParts.length === 0 && aDecParts.length > 0) return 1;
754
+ for (let i = 0; i < maxLen; i++) {
755
+ const av = Number.isFinite(aDecParts[i]) ? aDecParts[i] : 0;
756
+ const bv = Number.isFinite(bDecParts[i]) ? bDecParts[i] : 0;
757
+ if (av !== bv) return av - bv;
758
+ }
759
+ return 0;
760
+ }
761
+
762
+ /**
763
+ * Extract the phase token from a directory name.
764
+ * Supports: '01-name', '1009A-name', '999.6-name', 'CK-01-name', 'PROJ-42-name'.
765
+ * Returns the token portion (e.g. '01', '1009A', '999.6', 'PROJ-42') or the full name if no separator.
766
+ */
767
+ function extractPhaseToken(dirName) {
768
+ // Try project-code-prefixed numeric: CK-01-name → CK-01, CK-01A.2-name → CK-01A.2
769
+ const codePrefixed = dirName.match(/^([A-Z]{1,6}-\d+[A-Z]?(?:\.\d+)*)(?:-|$)/i);
770
+ if (codePrefixed) return codePrefixed[1];
771
+ // Try plain numeric: 01-name, 1009A-name, 999.6-name
772
+ const numeric = dirName.match(/^(\d+[A-Z]?(?:\.\d+)*)(?:-|$)/i);
773
+ if (numeric) return numeric[1];
774
+ // Custom IDs: PROJ-42-name → everything before the last segment that looks like a name
775
+ const custom = dirName.match(/^([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)*)(?:-[a-z]|$)/i);
776
+ if (custom) return custom[1];
777
+ return dirName;
778
+ }
779
+
780
+ /**
781
+ * Check if a directory name's phase token matches the normalized phase exactly.
782
+ * Case-insensitive comparison for the token portion.
783
+ */
784
+ function phaseTokenMatches(dirName, normalized) {
785
+ const token = extractPhaseToken(dirName);
786
+ if (token.toUpperCase() === normalized.toUpperCase()) return true;
787
+ // Strip optional project_code prefix from dir and retry
788
+ const stripped = dirName.replace(/^[A-Z]{1,6}-(?=\d)/i, '');
789
+ if (stripped !== dirName) {
790
+ const strippedToken = extractPhaseToken(stripped);
791
+ if (strippedToken.toUpperCase() === normalized.toUpperCase()) return true;
792
+ }
793
+ return false;
794
+ }
795
+
796
+ function extractCanonicalPlanId(filename) {
797
+ const base = filename.replace(/-PLAN\.md$/i, '').replace(/-SUMMARY\.md$/i, '').replace(/\.md$/i, '');
798
+ const parts = base.split('-').filter(Boolean);
799
+ const tokenRe = /^\d+[A-Z]?(?:\.\d+)*$/i;
800
+ const phaseIdx = parts.findIndex(p => tokenRe.test(p));
801
+ if (phaseIdx >= 0 && phaseIdx + 1 < parts.length && tokenRe.test(parts[phaseIdx + 1])) {
802
+ return `${parts[phaseIdx]}-${parts[phaseIdx + 1]}`;
803
+ }
804
+ return base;
805
+ }
806
+
807
+ function searchPhaseInDir(baseDir, relBase, normalized) {
808
+ try {
809
+ const dirs = readSubdirectories(baseDir, true);
810
+ // Match: exact phase token comparison (not prefix matching)
811
+ const match = dirs.find(d => phaseTokenMatches(d, normalized));
812
+ if (!match) return null;
813
+
814
+ // Extract phase number and name — supports numeric (01-name), project-code-prefixed (CK-01-name), and custom (PROJ-42-name)
815
+ const dirMatch = match.match(/^(?:[A-Z]{1,6}-)(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i)
816
+ || match.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i)
817
+ || match.match(/^([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)*)-(.+)/i)
818
+ || [null, match, null];
819
+ const phaseNumber = dirMatch ? dirMatch[1] : normalized;
820
+ const phaseName = dirMatch && dirMatch[2] ? dirMatch[2] : null;
821
+ const phaseDir = path.join(baseDir, match);
822
+ const { plans: unsortedPlans, summaries: unsortedSummaries, hasResearch, hasContext, hasVerification, hasReviews } = getPhaseFileStats(phaseDir);
823
+ const plans = unsortedPlans.sort();
824
+ const summaries = unsortedSummaries.sort();
825
+
826
+ const completedPlanIds = new Set(
827
+ summaries.flatMap(s => {
828
+ const exact = s.replace('-SUMMARY.md', '').replace('SUMMARY.md', '');
829
+ const canonical = extractCanonicalPlanId(s);
830
+ return canonical === exact ? [exact] : [exact, canonical];
831
+ })
832
+ );
833
+ const incompletePlans = plans.filter(p => {
834
+ const planId = p.replace('-PLAN.md', '').replace('PLAN.md', '');
835
+ const canonical = extractCanonicalPlanId(p);
836
+ return !completedPlanIds.has(planId) && !completedPlanIds.has(canonical);
837
+ });
838
+
839
+ return {
840
+ found: true,
841
+ directory: toPosixPath(path.join(relBase, match)),
842
+ phase_number: phaseNumber,
843
+ phase_name: phaseName,
844
+ phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
845
+ plans,
846
+ summaries,
847
+ incomplete_plans: incompletePlans,
848
+ has_research: hasResearch,
849
+ has_context: hasContext,
850
+ has_verification: hasVerification,
851
+ has_reviews: hasReviews,
852
+ };
853
+ } catch {
854
+ return null;
855
+ }
856
+ }
857
+
858
+ function findPhaseInternal(cwd, phase) {
859
+ if (!phase) return null;
860
+
861
+ const phasesDir = path.join(planningDir(cwd), 'phases');
862
+ const normalized = normalizePhaseName(phase);
863
+
864
+ // Search current phases first
865
+ const relPhasesDir = toPosixPath(path.relative(cwd, phasesDir));
866
+ const current = searchPhaseInDir(phasesDir, relPhasesDir, normalized);
867
+ if (current) return current;
868
+
869
+ // Search archived milestone phases (newest first)
870
+ const milestonesDir = path.join(cwd, '.planning', 'milestones');
871
+ if (!fs.existsSync(milestonesDir)) return null;
872
+
873
+ try {
874
+ const milestoneEntries = fs.readdirSync(milestonesDir, { withFileTypes: true });
875
+ const archiveDirs = milestoneEntries
876
+ .filter(e => e.isDirectory() && /^v[\d.]+-phases$/.test(e.name))
877
+ .map(e => e.name)
878
+ .sort()
879
+ .reverse();
880
+
881
+ for (const archiveName of archiveDirs) {
882
+ const version = archiveName.match(/^(v[\d.]+)-phases$/)[1];
883
+ const archivePath = path.join(milestonesDir, archiveName);
884
+ const relBase = '.planning/milestones/' + archiveName;
885
+ const result = searchPhaseInDir(archivePath, relBase, normalized);
886
+ if (result) {
887
+ result.archived = version;
888
+ return result;
889
+ }
890
+ }
891
+ } catch { /* intentionally empty */ }
892
+
893
+ return null;
894
+ }
895
+
896
+ function getArchivedPhaseDirs(cwd) {
897
+ const milestonesDir = path.join(cwd, '.planning', 'milestones');
898
+ const results = [];
899
+
900
+ if (!fs.existsSync(milestonesDir)) return results;
901
+
902
+ try {
903
+ const milestoneEntries = fs.readdirSync(milestonesDir, { withFileTypes: true });
904
+ // Find v*-phases directories, sort newest first
905
+ const phaseDirs = milestoneEntries
906
+ .filter(e => e.isDirectory() && /^v[\d.]+-phases$/.test(e.name))
907
+ .map(e => e.name)
908
+ .sort()
909
+ .reverse();
910
+
911
+ for (const archiveName of phaseDirs) {
912
+ const version = archiveName.match(/^(v[\d.]+)-phases$/)[1];
913
+ const archivePath = path.join(milestonesDir, archiveName);
914
+ const dirs = readSubdirectories(archivePath, true);
915
+
916
+ for (const dir of dirs) {
917
+ results.push({
918
+ name: dir,
919
+ milestone: version,
920
+ basePath: path.join('.planning', 'milestones', archiveName),
921
+ fullPath: path.join(archivePath, dir),
922
+ });
923
+ }
924
+ }
925
+ } catch { /* intentionally empty */ }
926
+
927
+ return results;
928
+ }
929
+
930
+ // ─── Roadmap milestone scoping ───────────────────────────────────────────────
931
+
932
+ /**
933
+ * Strip shipped milestone content wrapped in <details> blocks.
934
+ * Used to isolate current milestone phases when searching ROADMAP.md
935
+ * for phase headings or checkboxes — prevents matching archived milestone
936
+ * phases that share the same numbers as current milestone phases.
937
+ */
938
+ function stripShippedMilestones(content) {
939
+ return content.replace(/<details>[\s\S]*?<\/details>/gi, '');
940
+ }
941
+
942
+ /**
943
+ * Extract the current milestone section from ROADMAP.md by positive lookup.
944
+ *
945
+ * Instead of stripping <details> blocks (negative heuristic that breaks if
946
+ * agents wrap the current milestone in <details>), this finds the section
947
+ * matching the current milestone version and returns only that content.
948
+ *
949
+ * Falls back to stripShippedMilestones() if:
950
+ * - cwd is not provided
951
+ * - STATE.md doesn't exist or has no milestone field
952
+ * - Version can't be found in ROADMAP.md
953
+ *
954
+ * @param {string} content - Full ROADMAP.md content
955
+ * @param {string} [cwd] - Working directory for reading STATE.md
956
+ * @returns {string} Content scoped to current milestone
957
+ */
958
+ function extractCurrentMilestone(content, cwd) {
959
+ if (!cwd) return stripShippedMilestones(content);
960
+
961
+ // 1. Get current milestone version from STATE.md frontmatter
962
+ let version = null;
963
+ try {
964
+ const statePath = path.join(planningDir(cwd), 'STATE.md');
965
+ const stateRaw = platformReadSync(statePath);
966
+ if (stateRaw !== null) {
967
+ const milestoneMatch = stateRaw.match(/^milestone:\s*(.+)/m);
968
+ if (milestoneMatch) {
969
+ version = milestoneMatch[1].trim();
970
+ }
971
+ }
972
+ } catch {}
973
+
974
+ // 2. Fallback: derive version from getMilestoneInfo pattern in ROADMAP.md itself
975
+ if (!version) {
976
+ // Check for 🚧 in-progress marker
977
+ const inProgressMatch = content.match(/🚧\s*\*\*v(\d+\.\d+)\s/);
978
+ if (inProgressMatch) {
979
+ version = 'v' + inProgressMatch[1];
980
+ }
981
+ }
982
+
983
+ if (!version) return stripShippedMilestones(content);
984
+
985
+ // 3. Find the section matching this version
986
+ // Match headings like: ## Roadmap v3.0: Name, ## v3.0 Name, etc.
987
+ const escapedVersion = escapeRegex(version);
988
+ const sectionPattern = new RegExp(
989
+ `(^#{1,3}\\s+.*${escapedVersion}\\b[^\\n]*)`,
990
+ 'gmi'
991
+ );
992
+ const allMatches = [...content.matchAll(sectionPattern)];
993
+
994
+ if (allMatches.length === 0) return stripShippedMilestones(content);
995
+
996
+ // Select the first non-closed heading; fall back to first match if all are closed.
997
+ // A heading is "closed" only if it carries a closed marker AND no active marker.
998
+ const closedMarkerPattern = /\b(?:CLOSED|ARCHIVED|ABANDONED|SHIPPED|FAILED)\b|✅|🗄/i;
999
+ const activeMarkerPattern = /\b(?:STARTED|ACTIVE|WIP)\b|in\s+progress|🚧/i;
1000
+ const isClosed = (h) => closedMarkerPattern.test(h) && !activeMarkerPattern.test(h);
1001
+ const firstMatch = allMatches[0];
1002
+ const selected = allMatches.find((m) => !isClosed(m[1])) || firstMatch;
1003
+
1004
+ const sectionStart = selected.index;
1005
+
1006
+ // Find the end: next milestone heading at same or higher level, or EOF.
1007
+ // Milestone headings look like: ## v2.0, ## Roadmap v2.0, ## ✅ v1.0, etc.
1008
+ // Scan line-by-line so that heading-like lines inside fenced code blocks
1009
+ // (``` or ~~~) are not mistaken for milestone boundaries. See #2787.
1010
+ const sectionMatch = selected;
1011
+ const headingLevel = sectionMatch[1].match(/^(#{1,3})\s/)[1].length;
1012
+ const restContent = content.slice(sectionStart + sectionMatch[0].length);
1013
+ // Exclude phase headings (e.g. "### Phase 12: v1.0 Tech-Debt Closure") from
1014
+ // being treated as milestone boundaries just because they mention vX.Y in
1015
+ // the title. Phase headings always start with the literal `Phase `. See #2619.
1016
+ const nextMilestonePattern = new RegExp(
1017
+ `^#{1,${headingLevel}}\\s+(?!Phase\\s+\\S)(?:.*v\\d+\\.\\d+|✅|📋|🚧)`,
1018
+ 'i'
1019
+ );
1020
+
1021
+ let sectionEnd = content.length;
1022
+ let fenceChar = null;
1023
+ let fenceLen = 0;
1024
+ let charOffset = 0;
1025
+ for (const line of restContent.split('\n')) {
1026
+ const fenceMatch = line.match(/^\s{0,3}((?:`{3,}|~{3,}))(.*)/);
1027
+ if (fenceMatch) {
1028
+ const char = fenceMatch[1][0];
1029
+ const len = fenceMatch[1].length;
1030
+ const trailing = fenceMatch[2] || '';
1031
+ if (!fenceChar) {
1032
+ fenceChar = char;
1033
+ fenceLen = len;
1034
+ } else if (char === fenceChar && len >= fenceLen && /^\s*$/.test(trailing)) {
1035
+ fenceChar = null;
1036
+ fenceLen = 0;
1037
+ }
1038
+ } else if (!fenceChar && nextMilestonePattern.test(line)) {
1039
+ sectionEnd = sectionStart + sectionMatch[0].length + charOffset;
1040
+ break;
1041
+ }
1042
+ charOffset += line.length + 1;
1043
+ }
1044
+
1045
+ // Return everything before the current milestone section (non-milestone content
1046
+ // like title, overview) plus the current milestone section.
1047
+ // Anchor the preamble at the first *any-version* milestone heading so that
1048
+ // unmatched sibling sections (e.g. v2.0-Beta when STATE=v2.0-B) do not leak
1049
+ // in as preamble content.
1050
+ const anyMilestonePattern = /^#{1,3}\s+(?!Phase\s+\S)(?:.*v\d+\.\d+|✅|📋|🚧)/im;
1051
+ const firstMilestoneMatch = content.match(anyMilestonePattern);
1052
+ const preambleCutoff = firstMilestoneMatch
1053
+ ? firstMilestoneMatch.index
1054
+ : firstMatch.index;
1055
+ const beforeMilestones = content.slice(0, preambleCutoff);
1056
+ const currentSection = content.slice(sectionStart, sectionEnd);
1057
+
1058
+ // Also include any content before the first milestone heading (title, overview, etc.)
1059
+ // but strip any <details> blocks in it (these are definitely shipped) and any
1060
+ // flat phase-detail blocks. A "## Phase Details"-style section before the first
1061
+ // milestone heading lists `### Phase N:` entries spanning ALL milestones; left
1062
+ // in the preamble they leak into the active-milestone scope and over-count
1063
+ // total_phases / total_plans (#501). The active milestone's own phase content
1064
+ // lives in currentSection, so stripping phase blocks from the preamble is safe.
1065
+ const preamble = beforeMilestones
1066
+ .replace(/<details>[\s\S]*?<\/details>/gi, '')
1067
+ // Drop each `### Phase N:` heading and its body up to the next heading.
1068
+ .replace(/^#{2,4}\s*Phase\s+[\w][\w.-]*\s*:[^\n]*(?:\n(?!#{1,6}\s)[^\n]*)*\n?/gim, '')
1069
+ // Drop a now-empty flat phase-details section heading, if present.
1070
+ .replace(/^#{1,4}\s*Phase Details\b[^\n]*\n?/gim, '');
1071
+
1072
+ return preamble + currentSection;
1073
+ }
1074
+
1075
+ /**
1076
+ * Replace a pattern only in the current milestone section of ROADMAP.md
1077
+ * (everything after the last </details> close tag). Used for write operations
1078
+ * that must not accidentally modify archived milestone checkboxes/tables.
1079
+ */
1080
+ function replaceInCurrentMilestone(content, pattern, replacement) {
1081
+ const lastDetailsClose = content.lastIndexOf('</details>');
1082
+ if (lastDetailsClose === -1) {
1083
+ return content.replace(pattern, replacement);
1084
+ }
1085
+ const offset = lastDetailsClose + '</details>'.length;
1086
+ const before = content.slice(0, offset);
1087
+ const after = content.slice(offset);
1088
+ return before + after.replace(pattern, replacement);
1089
+ }
1090
+
1091
+ // ─── Roadmap & model utilities ────────────────────────────────────────────────
1092
+
1093
+ function getRoadmapPhaseInternal(cwd, phaseNum) {
1094
+ if (!phaseNum) return null;
1095
+ const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
1096
+ if (!fs.existsSync(roadmapPath)) return null;
1097
+
1098
+ try {
1099
+ const roadmapRaw = platformReadSync(roadmapPath);
1100
+ if (roadmapRaw === null) throw new Error('missing');
1101
+ const content = extractCurrentMilestone(roadmapRaw, cwd);
1102
+ // #3537: route through canonical padding-tolerant fragment. The prior
1103
+ // hand-rolled `isNumeric` branch only stripped padding on integer-only
1104
+ // ids and missed decimal padding (`02.7` against `Phase 2.7:` headings).
1105
+ const phasePattern = new RegExp(
1106
+ `#{2,4}\\s*Phase\\s+${phaseMarkdownRegexSource(phaseNum)}:\\s*([^\\n]+)`,
1107
+ 'i'
1108
+ );
1109
+ const headerMatch = content.match(phasePattern);
1110
+ if (!headerMatch) return null;
1111
+
1112
+ const phaseName = headerMatch[1].trim();
1113
+ const headerIndex = headerMatch.index;
1114
+ const restOfContent = content.slice(headerIndex);
1115
+ const nextHeaderMatch = restOfContent.match(/\n#{2,4}\s+Phase\s+[\w]/i);
1116
+ const sectionEnd = nextHeaderMatch ? headerIndex + nextHeaderMatch.index : content.length;
1117
+ const section = content.slice(headerIndex, sectionEnd).trim();
1118
+
1119
+ const goalMatch = section.match(/\*\*Goal(?:\*\*:|\*?\*?:\*\*)\s*([^\n]+)/i);
1120
+ const goal = goalMatch ? goalMatch[1].trim() : null;
1121
+
1122
+ return {
1123
+ found: true,
1124
+ phase_number: phaseNum.toString(),
1125
+ phase_name: phaseName,
1126
+ goal,
1127
+ section,
1128
+ };
1129
+ } catch {
1130
+ return null;
1131
+ }
1132
+ }
1133
+
1134
+ // ─── Agent installation validation (#1371) ───────────────────────────────────
1135
+
1136
+ /**
1137
+ * Resolve the agents directory from the GSD install location.
1138
+ * gsd-tools.cjs lives at <configDir>/get-shit-done/bin/gsd-tools.cjs,
1139
+ * so agents/ is at <configDir>/agents/.
1140
+ *
1141
+ * GSD_AGENTS_DIR env var overrides the default path. Used in tests and for
1142
+ * installs where the agents directory is not co-located with gsd-tools.cjs.
1143
+ *
1144
+ * @returns {string} Absolute path to the agents directory
1145
+ */
1146
+ function getAgentsDir() {
1147
+ if (process.env.GSD_AGENTS_DIR) {
1148
+ return process.env.GSD_AGENTS_DIR;
1149
+ }
1150
+ // __dirname is get-shit-done/bin/lib/ → go up 3 levels to configDir
1151
+ return path.join(__dirname, '..', '..', '..', 'agents');
1152
+ }
1153
+
1154
+ /**
1155
+ * Check which GSD agents are installed on disk.
1156
+ * Returns an object with installation status and details.
1157
+ *
1158
+ * Recognises both standard format (gsd-planner.md) and Copilot format
1159
+ * (gsd-planner.agent.md). Copilot renames agent files during install (#1512).
1160
+ *
1161
+ * @returns {{ agents_installed: boolean, missing_agents: string[], installed_agents: string[], agents_dir: string }}
1162
+ */
1163
+ function checkAgentsInstalled() {
1164
+ const agentsDir = getAgentsDir();
1165
+ const expectedAgents = Object.keys(MODEL_PROFILES);
1166
+ const installed = [];
1167
+ const missing = [];
1168
+
1169
+ if (!fs.existsSync(agentsDir)) {
1170
+ return {
1171
+ agents_installed: false,
1172
+ missing_agents: expectedAgents,
1173
+ installed_agents: [],
1174
+ agents_dir: agentsDir,
1175
+ };
1176
+ }
1177
+
1178
+ for (const agent of expectedAgents) {
1179
+ // Check all runtime agent file formats:
1180
+ // - .md (Claude/OpenCode/Gemini/etc.)
1181
+ // - .agent.md (Copilot)
1182
+ // - .toml (Codex)
1183
+ const agentFile = path.join(agentsDir, `${agent}.md`);
1184
+ const agentFileCopilot = path.join(agentsDir, `${agent}.agent.md`);
1185
+ const agentFileCodex = path.join(agentsDir, `${agent}.toml`);
1186
+ if (fs.existsSync(agentFile) || fs.existsSync(agentFileCopilot) || fs.existsSync(agentFileCodex)) {
1187
+ installed.push(agent);
1188
+ } else {
1189
+ missing.push(agent);
1190
+ }
1191
+ }
1192
+
1193
+ return {
1194
+ agents_installed: installed.length > 0 && missing.length === 0,
1195
+ missing_agents: missing,
1196
+ installed_agents: installed,
1197
+ agents_dir: agentsDir,
1198
+ };
1199
+ }
1200
+
1201
+ // ─── Model alias resolution ───────────────────────────────────────────────────
1202
+
1203
+ const RUNTIME_OVERRIDE_TIERS = new Set(['opus', 'sonnet', 'haiku']);
1204
+ const _warnedConfigKeys = new Set();
1205
+
1206
+ function _warnUnknownProfileOverrides(parsed, configLabel) {
1207
+ if (!parsed || typeof parsed !== 'object') return;
1208
+
1209
+ const runtime = parsed.runtime;
1210
+ if (runtime && typeof runtime === 'string' && !KNOWN_RUNTIMES.has(runtime)) {
1211
+ const key = `${configLabel}::runtime::${runtime}`;
1212
+ if (!_warnedConfigKeys.has(key)) {
1213
+ _warnedConfigKeys.add(key);
1214
+ try {
1215
+ process.stderr.write(
1216
+ `gsd: warning — config key "runtime" has unknown value "${runtime}". ` +
1217
+ `Known runtimes: ${[...KNOWN_RUNTIMES].sort().join(', ')}. ` +
1218
+ `Resolution will fall back to safe defaults. (#2517)\n`
1219
+ );
1220
+ } catch { /* stderr might be closed in some test harnesses */ }
1221
+ }
1222
+ }
1223
+
1224
+ const overrides = parsed.model_profile_overrides;
1225
+ if (!overrides || typeof overrides !== 'object') return;
1226
+ for (const [overrideRuntime, tierMap] of Object.entries(overrides)) {
1227
+ if (!KNOWN_RUNTIMES.has(overrideRuntime)) {
1228
+ const key = `${configLabel}::override-runtime::${overrideRuntime}`;
1229
+ if (!_warnedConfigKeys.has(key)) {
1230
+ _warnedConfigKeys.add(key);
1231
+ try {
1232
+ process.stderr.write(
1233
+ `gsd: warning — model_profile_overrides.${overrideRuntime}.* uses ` +
1234
+ `unknown runtime "${overrideRuntime}". Known runtimes: ` +
1235
+ `${[...KNOWN_RUNTIMES].sort().join(', ')}. (#2517)\n`
1236
+ );
1237
+ } catch { /* ok */ }
1238
+ }
1239
+ }
1240
+ if (!tierMap || typeof tierMap !== 'object') continue;
1241
+ for (const tierName of Object.keys(tierMap)) {
1242
+ if (!RUNTIME_OVERRIDE_TIERS.has(tierName)) {
1243
+ const key = `${configLabel}::override-tier::${overrideRuntime}.${tierName}`;
1244
+ if (!_warnedConfigKeys.has(key)) {
1245
+ _warnedConfigKeys.add(key);
1246
+ try {
1247
+ process.stderr.write(
1248
+ `gsd: warning — model_profile_overrides.${overrideRuntime}.${tierName} ` +
1249
+ `uses unknown tier "${tierName}". Allowed tiers: opus, sonnet, haiku. (#2517)\n`
1250
+ );
1251
+ } catch { /* ok */ }
1252
+ }
1253
+ }
1254
+ }
1255
+ }
1256
+ }
1257
+
1258
+ // Internal helper exposed for tests so per-process warning state can be reset
1259
+ // between cases that intentionally exercise the warning path repeatedly.
1260
+ function _resetRuntimeWarningCacheForTests() {
1261
+ _warnedConfigKeys.clear();
1262
+ }
1263
+
1264
+ /**
1265
+ * #2517 — Resolve the runtime-aware tier entry for (runtime, tier).
1266
+ *
1267
+ * Single source of truth shared by core.cjs (resolveModelInternal)
1268
+ * and bin/install.js (Codex/OpenCode TOML emit paths). Always merges
1269
+ * built-in defaults with user overrides at the field
1270
+ * level so partial overrides keep the unspecified fields:
1271
+ *
1272
+ * `{ codex: { opus: "gpt-5-pro" } }` keeps reasoning_effort: 'xhigh'
1273
+ * `{ codex: { opus: { reasoning_effort: 'low' } } }` keeps model: 'gpt-5.4'
1274
+ *
1275
+ * Without this field-merge, the documented string-shorthand example silently
1276
+ * dropped reasoning_effort and a partial-object override silently dropped the
1277
+ * model — both reported as critical findings in the #2609 review.
1278
+ *
1279
+ * Inputs:
1280
+ * - runtime: string (e.g. 'codex', 'claude', 'opencode')
1281
+ * - tier: 'opus' | 'sonnet' | 'haiku'
1282
+ * - overrides: optional `model_profile_overrides` blob (may be null/undefined)
1283
+ *
1284
+ * Returns `{ model: string, reasoning_effort?: string } | null`.
1285
+ */
1286
+ function resolveTierEntry({ runtime, tier, overrides }) {
1287
+ if (!runtime || !tier) return null;
1288
+
1289
+ const builtin = RUNTIME_PROFILE_MAP[runtime]?.[tier] || null;
1290
+ const userRaw = overrides?.[runtime]?.[tier];
1291
+
1292
+ // String shorthand from CONFIGURATION.md examples — `{ codex: { opus: "gpt-5-pro" } }`.
1293
+ // Treat as `{ model: "gpt-5-pro" }` so the field-merge below still preserves
1294
+ // reasoning_effort from the built-in defaults.
1295
+ let userEntry = null;
1296
+ if (userRaw) {
1297
+ userEntry = typeof userRaw === 'string' ? { model: userRaw } : userRaw;
1298
+ }
1299
+
1300
+ if (!builtin && !userEntry) return null;
1301
+ // Field-merge: user fields win, built-in fills the gaps.
1302
+ return { ...(builtin || {}), ...(userEntry || {}) };
1303
+ }
1304
+
1305
+ /**
1306
+ * Convenience wrapper used by resolveModelInternal.
1307
+ * Pulls runtime + overrides out of a loaded config and delegates to resolveTierEntry.
1308
+ */
1309
+ function _resolveRuntimeTier(config, tier) {
1310
+ return resolveTierEntry({
1311
+ runtime: config.runtime,
1312
+ tier,
1313
+ overrides: config.model_profile_overrides,
1314
+ });
1315
+ }
1316
+
1317
+ function resolveModelInternal(cwd, agentType) {
1318
+ const config = loadConfig(cwd);
1319
+
1320
+ // 1. Per-agent override — always respected; highest precedence.
1321
+ // Users who set fully-qualified model IDs (e.g., "openai/gpt-5.4") get exactly that.
1322
+ const override = config.model_overrides?.[agentType];
1323
+ if (override) {
1324
+ return override;
1325
+ }
1326
+
1327
+ // 2. Compute the tier (opus/sonnet/haiku/inherit) for this agent.
1328
+ //
1329
+ // #3023: phase-type slot can override the profile-derived tier.
1330
+ // Precedence: per-agent override (above) > phase-type slot > profile.
1331
+ // Phase-type values are tier aliases (opus/sonnet/haiku/inherit) — same
1332
+ // shape as model_profile output — so the runtime-resolution chain
1333
+ // (step 3), resolve_model_ids handling (step 4), and profile lookup
1334
+ // (step 5) all stay correct without further branching.
1335
+ const profile = String(config.model_profile || 'balanced').toLowerCase();
1336
+ const agentModels = MODEL_PROFILES[agentType];
1337
+ const phaseType = AGENT_TO_PHASE_TYPE[agentType];
1338
+ const phaseTypeTier = (phaseType && config.models && typeof config.models === 'object')
1339
+ ? config.models[phaseType]
1340
+ : undefined;
1341
+ // Only honor phase-type tier if it's one of the recognized aliases.
1342
+ // Anything else falls through to profile lookup so a typo doesn't
1343
+ // silently break tier resolution.
1344
+ const VALID_TIERS = new Set(['opus', 'sonnet', 'haiku', 'inherit']);
1345
+ // Resolve tier: phase-type wins when valid; else profile-derived; else
1346
+ // (when profile === 'inherit') propagate inherit so the later short-
1347
+ // circuit fires. CR Major (#3030): a config like
1348
+ // { model_profile: 'inherit', models: { execution: 'opus' } }
1349
+ // must honor the phase-type opus, not return 'inherit'. Synthesizing
1350
+ // tier='inherit' only when there's no phase-type override keeps the
1351
+ // original inherit semantics intact while letting a valid phase-type
1352
+ // tier win.
1353
+ const tier = (phaseTypeTier && VALID_TIERS.has(phaseTypeTier))
1354
+ ? phaseTypeTier
1355
+ : (profile === 'inherit'
1356
+ ? 'inherit'
1357
+ : (agentModels ? (agentModels[profile] || agentModels['balanced']) : null));
1358
+
1359
+ // 3. Runtime-aware resolution (#2517) — only when `runtime` is explicitly set
1360
+ // to a non-Claude runtime. `runtime: "claude"` is the implicit default and is
1361
+ // treated as a no-op here so it does not silently override `resolve_model_ids:
1362
+ // "omit"` (review finding #4). Deliberate ordering for non-Claude runtimes:
1363
+ // explicit opt-in beats `resolve_model_ids: "omit"` so users on Codex installs
1364
+ // that auto-set "omit" can still flip on tiered behavior by setting runtime
1365
+ // alone. Gate on tier !== 'inherit' (not profile !== 'inherit') so a
1366
+ // valid phase-type tier flips runtime resolution on even when the
1367
+ // profile is inherit.
1368
+ if (config.runtime && config.runtime !== 'claude' && tier && tier !== 'inherit') {
1369
+ const entry = _resolveRuntimeTier(config, tier);
1370
+ if (entry?.model) return entry.model;
1371
+ // Unknown runtime with no user-supplied overrides — fall through to Claude-safe
1372
+ // default rather than emit an ID the runtime can't accept.
1373
+ }
1374
+
1375
+ // 4. resolve_model_ids: "omit" — return empty string so the runtime uses its
1376
+ // configured default model. For non-Claude runtimes (OpenCode, Codex, etc.) that
1377
+ // don't recognize Claude aliases. Set automatically during install. See #1156.
1378
+ if (config.resolve_model_ids === 'omit') {
1379
+ return '';
1380
+ }
1381
+
1382
+ // 5. Profile lookup (Claude-native default).
1383
+ if (!agentModels) {
1384
+ return profile === 'quality' ? 'opus'
1385
+ : profile === 'budget' ? 'haiku'
1386
+ : profile === 'inherit' ? 'inherit'
1387
+ : 'sonnet';
1388
+ }
1389
+ // Gate on tier (not profile) so a valid phase-type override beats
1390
+ // profile=inherit (#3030 CR Major).
1391
+ if (tier === 'inherit') return 'inherit';
1392
+ // `tier` is guaranteed truthy here: agentModels exists, and MODEL_PROFILES
1393
+ // entries always define `balanced`, so `agentModels[profile] || agentModels.balanced`
1394
+ // resolves to a string. Keep the local for readability — no defensive fallback.
1395
+ const alias = tier;
1396
+
1397
+ // resolve_model_ids: true — map alias to full Claude model ID.
1398
+ // Prevents 404s when the Task tool passes aliases directly to the API.
1399
+ if (config.resolve_model_ids) {
1400
+ return MODEL_ALIAS_MAP[alias] || alias;
1401
+ }
1402
+
1403
+ return alias;
1404
+ }
1405
+
1406
+ /**
1407
+ * #3024 — Resolve a model for a specific dynamic-routing attempt.
1408
+ *
1409
+ * The orchestrator (workflow agent) tracks the attempt counter. On
1410
+ * the first spawn, it calls with attempt=0. If the orchestrator detects
1411
+ * a soft failure (verification inconclusive, plan-check FLAG, etc.),
1412
+ * it re-spawns with attempt=1, which escalates the agent's tier one
1413
+ * step up. `max_escalations` caps how many escalations are allowed.
1414
+ *
1415
+ * Resolution precedence (highest → lowest):
1416
+ * 1. config.model_overrides[agent] (full IDs accepted)
1417
+ * 2. dynamic_routing.tier_models[escalated_tier] (when enabled)
1418
+ * 3. models[phase_type] / model_profile (existing chain via
1419
+ * resolveModelInternal)
1420
+ *
1421
+ * When dynamic_routing is null/disabled, this function is identical
1422
+ * to resolveModelInternal — orchestrators can call it unconditionally
1423
+ * without breaking back-compat.
1424
+ *
1425
+ * @param {string} cwd - Project directory.
1426
+ * @param {string} agentType - Agent name (e.g. 'gsd-verifier').
1427
+ * @param {number} [attempt=0] - 0 for first spawn; 1+ for escalation.
1428
+ * Capped internally at max_escalations.
1429
+ * @returns {string} Model alias (opus/sonnet/haiku) or full ID.
1430
+ */
1431
+ function resolveModelForTier(cwd, agentType, attempt) {
1432
+ const config = loadConfig(cwd);
1433
+ const attemptN = Number.isInteger(attempt) && attempt > 0 ? attempt : 0;
1434
+
1435
+ // Per-agent override always wins — same as resolveModelInternal step 1.
1436
+ // User-supplied full IDs bypass the entire tier mechanism.
1437
+ const override = config.model_overrides?.[agentType];
1438
+ if (override) return override;
1439
+
1440
+ const dr = config.dynamic_routing;
1441
+ // Disabled / missing / non-object → fall back to the existing resolver.
1442
+ if (!dr || typeof dr !== 'object' || dr.enabled !== true) {
1443
+ return resolveModelInternal(cwd, agentType);
1444
+ }
1445
+
1446
+ const tierModels = dr.tier_models;
1447
+ if (!tierModels || typeof tierModels !== 'object') {
1448
+ // tier_models missing — can't dynamic-route; fall back.
1449
+ return resolveModelInternal(cwd, agentType);
1450
+ }
1451
+
1452
+ const defaultTier = AGENT_DEFAULT_TIERS[agentType];
1453
+ if (!defaultTier || !VALID_AGENT_TIERS.has(defaultTier)) {
1454
+ // Unmapped agent — no default tier; fall back so we don't silently
1455
+ // pick the wrong model.
1456
+ return resolveModelInternal(cwd, agentType);
1457
+ }
1458
+
1459
+ // Cap effective escalation at max_escalations (default 1). Beyond
1460
+ // the cap, the resolver returns the model for the cap level so the
1461
+ // orchestrator can log "max escalations reached" without burning
1462
+ // further budget.
1463
+ //
1464
+ // CR Major (#3031): `escalate_on_failure: false` is the kill-switch
1465
+ // for escalation — when false, every attempt resolves to the default
1466
+ // tier regardless of the attempt counter. Without this guard, an
1467
+ // orchestrator that blindly bumps the counter on retry would silently
1468
+ // escalate even though the user opted out.
1469
+ const maxEscalations = Number.isInteger(dr.max_escalations) && dr.max_escalations >= 0
1470
+ ? dr.max_escalations
1471
+ : 1;
1472
+ const escalationEnabled = dr.escalate_on_failure !== false;
1473
+ const effectiveAttempt = escalationEnabled
1474
+ ? Math.min(attemptN, maxEscalations)
1475
+ : 0;
1476
+
1477
+ // Walk the escalation chain N times from the default tier.
1478
+ let tier = defaultTier;
1479
+ for (let i = 0; i < effectiveAttempt; i += 1) {
1480
+ const next = nextTier(tier);
1481
+ if (!next || next === tier) break; // already at top
1482
+ tier = next;
1483
+ }
1484
+
1485
+ const alias = tierModels[tier];
1486
+ if (typeof alias !== 'string' || alias.length === 0) {
1487
+ // Misconfigured tier_models — missing slot. Fall back rather
1488
+ // than emit an empty model id.
1489
+ return resolveModelInternal(cwd, agentType);
1490
+ }
1491
+ return alias;
1492
+ }
1493
+
1494
+ // ─── #443 — Unified effort + fast_mode resolvers ─────────────────────────────
1495
+ //
1496
+ // Universal effort ladder (ordered):
1497
+ const VALID_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
1498
+ const EFFORT_SET = new Set(VALID_EFFORTS);
1499
+
1500
+ /**
1501
+ * Walk one step up the effort ladder from `e`. Returns the next level, or
1502
+ * the same level if already at the top.
1503
+ */
1504
+ function nextEffort(e) {
1505
+ const i = VALID_EFFORTS.indexOf(e);
1506
+ if (i < 0) return null;
1507
+ return VALID_EFFORTS[Math.min(i + 1, VALID_EFFORTS.length - 1)];
1508
+ }
1509
+
1510
+ /**
1511
+ * #443 — Resolve a universal effort string for (cwd, agentType).
1512
+ *
1513
+ * Precedence (first valid wins; invalid/wrong-type values are IGNORED and fall
1514
+ * through — mirrors the VALID_TIERS gate pattern in resolveModelInternal):
1515
+ * 1. opts.override (if in EFFORT_SET)
1516
+ * 2. config.effort.agent_overrides[agentType] (if valid)
1517
+ * 3. config.effort.routing_tier_defaults[ AGENT_DEFAULT_TIERS[agentType] ] (agent known + valid)
1518
+ * 4. config.effort.default (if valid)
1519
+ * 5. 'high' (Anthropic Opus 4.8 universal default)
1520
+ *
1521
+ * Handles: config.effort missing; effort.* non-object/malformed; unknown
1522
+ * agentType skips step 3; numeric/boolean garbage ignored.
1523
+ *
1524
+ * @param {string} cwd - Project directory.
1525
+ * @param {string} agentType - Agent name.
1526
+ * @param {{ override?: string }} [opts]
1527
+ * @returns {string} A valid effort string.
1528
+ */
1529
+ function resolveEffortInternal(cwd, agentType, opts) {
1530
+ // Step 1: invocation override
1531
+ if (opts && typeof opts.override === 'string' && EFFORT_SET.has(opts.override)) {
1532
+ return opts.override;
1533
+ }
1534
+
1535
+ const config = loadConfig(cwd);
1536
+ const effortCfg = (config.effort && typeof config.effort === 'object' && !Array.isArray(config.effort))
1537
+ ? config.effort
1538
+ : null;
1539
+
1540
+ // Step 2: agent_overrides
1541
+ if (effortCfg) {
1542
+ const ao = effortCfg.agent_overrides;
1543
+ if (ao && typeof ao === 'object' && !Array.isArray(ao)) {
1544
+ const v = ao[agentType];
1545
+ if (typeof v === 'string' && EFFORT_SET.has(v)) return v;
1546
+ }
1547
+ }
1548
+
1549
+ // Step 3: routing_tier_defaults by agent's default tier.
1550
+ // Manifest tier defaults are only used when there is NO effort config block at all
1551
+ // (effortCfg === null). When the user explicitly sets an effort block, we respect
1552
+ // their explicit routing_tier_defaults (if set) and fall through to effort.default
1553
+ // if they didn't set them. This prevents the manifest tier defaults from silently
1554
+ // overriding a user's `effort: { default: "medium" }`.
1555
+ const agentTier = AGENT_DEFAULT_TIERS[agentType];
1556
+ if (agentTier) {
1557
+ if (effortCfg && effortCfg.routing_tier_defaults &&
1558
+ typeof effortCfg.routing_tier_defaults === 'object' &&
1559
+ !Array.isArray(effortCfg.routing_tier_defaults)) {
1560
+ // User provided routing_tier_defaults — honor them
1561
+ const v = effortCfg.routing_tier_defaults[agentTier];
1562
+ if (typeof v === 'string' && EFFORT_SET.has(v)) return v;
1563
+ } else if (!effortCfg) {
1564
+ // No effort config at all — use manifest tier defaults
1565
+ const manifestDefaults = CANONICAL_CONFIG_DEFAULTS.effort?.routing_tier_defaults;
1566
+ if (manifestDefaults && typeof manifestDefaults === 'object') {
1567
+ const v = manifestDefaults[agentTier];
1568
+ if (typeof v === 'string' && EFFORT_SET.has(v)) return v;
1569
+ }
1570
+ }
1571
+ // else: effortCfg exists but no routing_tier_defaults — fall through to effort.default
1572
+ }
1573
+
1574
+ // Step 4: effort.default
1575
+ if (effortCfg) {
1576
+ const d = effortCfg.default;
1577
+ if (typeof d === 'string' && EFFORT_SET.has(d)) return d;
1578
+ }
1579
+
1580
+ // Step 5: hardcoded default
1581
+ return 'high';
1582
+ }
1583
+
1584
+ /**
1585
+ * #443 — Resolve fast_mode boolean for (cwd, agentType).
1586
+ *
1587
+ * Accepts ONLY real booleans at each level. Strings like "true" are NOT accepted
1588
+ * and fall through.
1589
+ *
1590
+ * Precedence:
1591
+ * 1. opts.override (typeof boolean)
1592
+ * 2. config.fast_mode.agent_overrides[agentType] (boolean)
1593
+ * 3. config.fast_mode.routing_tier_defaults[ AGENT_DEFAULT_TIERS[agentType] ] (agent known + boolean)
1594
+ * 4. config.fast_mode.enabled (boolean)
1595
+ * 5. false
1596
+ *
1597
+ * @param {string} cwd
1598
+ * @param {string} agentType
1599
+ * @param {{ override?: boolean }} [opts]
1600
+ * @returns {boolean}
1601
+ */
1602
+ function resolveFastModeInternal(cwd, agentType, opts) {
1603
+ // Step 1: invocation override
1604
+ if (opts && typeof opts.override === 'boolean') {
1605
+ return opts.override;
1606
+ }
1607
+
1608
+ const config = loadConfig(cwd);
1609
+ const fmCfg = (config.fast_mode && typeof config.fast_mode === 'object' && !Array.isArray(config.fast_mode))
1610
+ ? config.fast_mode
1611
+ : null;
1612
+
1613
+ // Step 2: agent_overrides
1614
+ if (fmCfg) {
1615
+ const ao = fmCfg.agent_overrides;
1616
+ if (ao && typeof ao === 'object' && !Array.isArray(ao)) {
1617
+ const v = ao[agentType];
1618
+ if (typeof v === 'boolean') return v;
1619
+ }
1620
+ }
1621
+
1622
+ // Step 3: routing_tier_defaults by agent's default tier.
1623
+ // Manifest tier defaults are only used when there is no fast_mode config block at all
1624
+ // (fmCfg === null). When the user explicitly set a fast_mode block (even with just
1625
+ // `enabled`), manifest routing_tier_defaults do not fire — we fall through to enabled (step 4).
1626
+ // This ensures `fast_mode: { enabled: true }` works intuitively without the user having
1627
+ // to also spell out all three tier defaults.
1628
+ const agentTier = AGENT_DEFAULT_TIERS[agentType];
1629
+ if (agentTier) {
1630
+ if (fmCfg && fmCfg.routing_tier_defaults &&
1631
+ typeof fmCfg.routing_tier_defaults === 'object' &&
1632
+ !Array.isArray(fmCfg.routing_tier_defaults)) {
1633
+ // User provided routing_tier_defaults — honor them
1634
+ const v = fmCfg.routing_tier_defaults[agentTier];
1635
+ if (typeof v === 'boolean') return v;
1636
+ } else if (!fmCfg) {
1637
+ // No fast_mode config at all — use manifest defaults for tier
1638
+ const manifestDefaults = CANONICAL_CONFIG_DEFAULTS.fast_mode?.routing_tier_defaults;
1639
+ if (manifestDefaults && typeof manifestDefaults === 'object') {
1640
+ const v = manifestDefaults[agentTier];
1641
+ if (typeof v === 'boolean') return v;
1642
+ }
1643
+ }
1644
+ // else: fmCfg exists but no routing_tier_defaults — fall through to enabled
1645
+ }
1646
+
1647
+ // Step 4: fast_mode.enabled
1648
+ if (fmCfg && typeof fmCfg.enabled === 'boolean') {
1649
+ return fmCfg.enabled;
1650
+ }
1651
+
1652
+ // Step 5: hardcoded default
1653
+ return false;
1654
+ }
1655
+
1656
+ /**
1657
+ * #443 — Resolve effort for a dynamic-routing attempt (with escalation).
1658
+ *
1659
+ * MUST NOT modify resolveModelForTier behavior.
1660
+ * base = resolveEffortInternal(cwd, agentType).
1661
+ * If config.dynamic_routing missing/enabled!==true OR escalate_on_failure===false
1662
+ * -> return base (attempt ignored).
1663
+ * Else: effectiveAttempt = min(max(0, attempt), max_escalations).
1664
+ * Walk nextEffort effectiveAttempt times from base, clamp at 'max'.
1665
+ *
1666
+ * @param {string} cwd
1667
+ * @param {string} agentType
1668
+ * @param {number} [attempt=0]
1669
+ * @returns {string}
1670
+ */
1671
+ function resolveEffortForTier(cwd, agentType, attempt) {
1672
+ const base = resolveEffortInternal(cwd, agentType);
1673
+
1674
+ const config = loadConfig(cwd);
1675
+ const dr = config.dynamic_routing;
1676
+ if (!dr || typeof dr !== 'object' || dr.enabled !== true) {
1677
+ return base;
1678
+ }
1679
+ if (dr.escalate_on_failure === false) {
1680
+ return base;
1681
+ }
1682
+
1683
+ const maxEscalations = Number.isInteger(dr.max_escalations) && dr.max_escalations >= 0
1684
+ ? dr.max_escalations
1685
+ : 1;
1686
+
1687
+ const attemptN = Number.isInteger(attempt) && attempt > 0 ? attempt : 0;
1688
+ const effectiveAttempt = Math.min(attemptN, maxEscalations);
1689
+
1690
+ let current = base;
1691
+ for (let i = 0; i < effectiveAttempt; i++) {
1692
+ const next = nextEffort(current);
1693
+ if (!next || next === current) break; // already at max
1694
+ current = next;
1695
+ }
1696
+ return current;
1697
+ }
1698
+
1699
+ // ─── Summary body helpers ─────────────────────────────────────────────────
1700
+
1701
+ /**
1702
+ * Extract a one-liner from the summary body when it's not in frontmatter.
1703
+ * The summary template defines one-liner as a bold markdown line after the heading:
1704
+ * # Phase X: Name Summary
1705
+ * **[substantive one-liner text]**
1706
+ */
1707
+ function extractOneLinerFromBody(content) {
1708
+ if (!content) return null;
1709
+ // Normalize EOLs so matching works for LF and CRLF files.
1710
+ const normalized = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
1711
+ // Strip frontmatter first
1712
+ const body = normalized.replace(/^---\n[\s\S]*?\n---\n*/, '');
1713
+ // Find the first **...** span on a line after a # heading.
1714
+ // Two supported template forms:
1715
+ // 1) Labeled: **One-liner:** Real prose here. (bug #2660 — new template)
1716
+ // 2) Bare: **Real prose here.** (legacy template)
1717
+ // For (1), the first bold span ends in a colon and the prose that follows
1718
+ // on the same line is the one-liner. For (2), the bold span itself is the
1719
+ // one-liner.
1720
+ const match = body.match(/^#[^\n]*\n+\*\*([^*\n]+)\*\*([^\n]*)/m);
1721
+ if (!match) return null;
1722
+ const boldInner = match[1].trim();
1723
+ const afterBold = match[2];
1724
+ // Labeled form: bold span is a "Label:" prefix — capture prose after it.
1725
+ if (/:\s*$/.test(boldInner)) {
1726
+ const prose = afterBold.trim();
1727
+ return prose.length > 0 ? prose : null;
1728
+ }
1729
+ // Bare form: the bold content itself is the one-liner.
1730
+ return boldInner.length > 0 ? boldInner : null;
1731
+ }
1732
+
1733
+ // ─── Misc utilities ───────────────────────────────────────────────────────────
1734
+
1735
+ function pathExistsInternal(cwd, targetPath) {
1736
+ const fullPath = path.isAbsolute(targetPath) ? targetPath : path.join(cwd, targetPath);
1737
+ try {
1738
+ fs.statSync(fullPath);
1739
+ return true;
1740
+ } catch {
1741
+ return false;
1742
+ }
1743
+ }
1744
+
1745
+ /**
1746
+ * Detect whether `cwd` sits inside a git worktree, and if so, return the
1747
+ * absolute path of the worktree root.
1748
+ *
1749
+ * Bug #3491: the previous shallow `pathExistsInternal(cwd, '.git')` check
1750
+ * only saw a `.git` entry directly in cwd, so subdirectories of an existing
1751
+ * repo reported `has_git: false` and the new-project workflow then ran
1752
+ * `git init` — creating a nested `.git` inside the outer repo's worktree.
1753
+ *
1754
+ * Mirrors `git rev-parse --is-inside-work-tree` semantics. Uses the existing
1755
+ * `execGit` seam so behaviour is consistent with the rest of the toolchain
1756
+ * (non-interactive env, 10s timeout, mockable in tests).
1757
+ *
1758
+ * Returns: { inside: boolean, worktreeRoot: string | null }
1759
+ * - inside=true → cwd is somewhere inside a git worktree
1760
+ * - inside=false → cwd is not inside any git worktree (or git is unavailable)
1761
+ *
1762
+ * Failure modes (git not installed, command times out, non-zero exit) all
1763
+ * collapse to `{ inside: false, worktreeRoot: null }` — the conservative
1764
+ * default that preserves pre-fix behaviour for environments without git.
1765
+ */
1766
+ function gitWorktreeInfoInternal(cwd) {
1767
+ try {
1768
+ const insideResult = execGit(['rev-parse', '--is-inside-work-tree'], { cwd, timeout: 5000 });
1769
+ if (insideResult.exitCode !== 0) {
1770
+ return { inside: false, worktreeRoot: null };
1771
+ }
1772
+ const insideStdout = String(insideResult.stdout || '').trim();
1773
+ if (insideStdout !== 'true') {
1774
+ return { inside: false, worktreeRoot: null };
1775
+ }
1776
+ const rootResult = execGit(['rev-parse', '--show-toplevel'], { cwd, timeout: 5000 });
1777
+ if (rootResult.exitCode !== 0) {
1778
+ return { inside: true, worktreeRoot: null };
1779
+ }
1780
+ const root = String(rootResult.stdout || '').trim();
1781
+ return { inside: true, worktreeRoot: root || null };
1782
+ } catch {
1783
+ return { inside: false, worktreeRoot: null };
1784
+ }
1785
+ }
1786
+
1787
+ function generateSlugInternal(text) {
1788
+ if (!text) return null;
1789
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').substring(0, 60);
1790
+ }
1791
+
1792
+ function getMilestoneInfo(cwd) {
1793
+ try {
1794
+ const roadmap = platformReadSync(path.join(planningDir(cwd), 'ROADMAP.md'));
1795
+ if (roadmap === null) throw new Error('missing');
1796
+
1797
+ // 0. Prefer STATE.md milestone: frontmatter as the authoritative source.
1798
+ // This prevents falling through to a regex that may match an old heading
1799
+ // when the active milestone's 🚧 marker is inside a <summary> tag without
1800
+ // **bold** formatting (bug #2409).
1801
+ let stateVersion = null;
1802
+ if (cwd) {
1803
+ try {
1804
+ const statePath = path.join(planningDir(cwd), 'STATE.md');
1805
+ const stateRaw = platformReadSync(statePath);
1806
+ if (stateRaw !== null) {
1807
+ const m = stateRaw.match(/^milestone:\s*(.+)/m);
1808
+ if (m) stateVersion = m[1].trim();
1809
+ }
1810
+ } catch { /* intentionally empty */ }
1811
+ }
1812
+
1813
+ if (stateVersion) {
1814
+ // Look up the name for this version in ROADMAP.md
1815
+ const escapedVer = escapeRegex(stateVersion);
1816
+ // Match heading-format: ## Roadmap v2.9: Name or ## v2.9 Name
1817
+ const headingMatch = roadmap.match(
1818
+ new RegExp(`##[^\\n]*${escapedVer}[:\\s]+([^\\n(]+)`, 'i')
1819
+ );
1820
+ if (headingMatch) {
1821
+ // If the heading line contains ✅ the milestone is already shipped.
1822
+ // Fall through to normal detection so the NEW active milestone is returned
1823
+ // instead of the stale shipped one still recorded in STATE.md.
1824
+ if (!headingMatch[0].includes('✅')) {
1825
+ return { version: stateVersion, name: headingMatch[1].trim() };
1826
+ }
1827
+ // Shipped milestone — do not early-return; fall through to normal detection below.
1828
+ } else {
1829
+ // Match list-format: 🚧 **v2.9 Name** or 🚧 v2.9 Name
1830
+ const listMatch = roadmap.match(
1831
+ new RegExp(`🚧\\s*\\*?\\*?${escapedVer}\\s+([^*\\n]+)`, 'i')
1832
+ );
1833
+ if (listMatch) {
1834
+ return { version: stateVersion, name: listMatch[1].trim() };
1835
+ }
1836
+ // Version found in STATE.md but no name match in ROADMAP — return bare version
1837
+ return { version: stateVersion, name: 'milestone' };
1838
+ }
1839
+ }
1840
+
1841
+ // First: check for list-format roadmaps using 🚧 (in-progress) marker
1842
+ // e.g. "- 🚧 **v2.1 Belgium** — Phases 24-28 (in progress)"
1843
+ // e.g. "- 🚧 **v1.2.1 Tech Debt** — Phases 1-8 (in progress)"
1844
+ const inProgressMatch = roadmap.match(/🚧\s*\*\*v(\d+(?:\.\d+)+)\s+([^*]+)\*\*/);
1845
+ if (inProgressMatch) {
1846
+ return {
1847
+ version: 'v' + inProgressMatch[1],
1848
+ name: inProgressMatch[2].trim(),
1849
+ };
1850
+ }
1851
+
1852
+ // Second: heading-format roadmaps — strip shipped milestones.
1853
+ // <details> blocks are stripped by stripShippedMilestones; heading-format ✅ markers
1854
+ // are excluded by the negative lookahead below so a stale STATE.md version (or any
1855
+ // shipped ✅ heading) never wins over the first non-shipped milestone heading.
1856
+ const cleaned = stripShippedMilestones(roadmap);
1857
+ // Negative lookahead skips headings that contain ✅ (shipped milestone marker).
1858
+ // Supports 2+ segment versions: v1.2, v1.2.1, v2.0.1, etc.
1859
+ const headingMatch = cleaned.match(/## (?!.*✅).*v(\d+(?:\.\d+)+)[:\s]+([^\n(]+)/);
1860
+ if (headingMatch) {
1861
+ return {
1862
+ version: 'v' + headingMatch[1],
1863
+ name: headingMatch[2].trim(),
1864
+ };
1865
+ }
1866
+ // Fallback: try bare version match (greedy — capture longest version string)
1867
+ const versionMatch = cleaned.match(/v(\d+(?:\.\d+)+)/);
1868
+ return {
1869
+ version: versionMatch ? versionMatch[0] : 'v1.0',
1870
+ name: 'milestone',
1871
+ };
1872
+ } catch {
1873
+ return { version: 'v1.0', name: 'milestone' };
1874
+ }
1875
+ }
1876
+
1877
+ /**
1878
+ * Returns a filter function that checks whether a phase directory belongs
1879
+ * to the current milestone based on ROADMAP.md phase headings.
1880
+ * If no ROADMAP exists or no phases are listed, returns a pass-all filter.
1881
+ */
1882
+ function getMilestonePhaseFilter(cwd, versionOverride) {
1883
+ const milestonePhaseNums = new Set();
1884
+ let missingExplicitVersion = false;
1885
+ try {
1886
+ const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
1887
+ const roadmapContent = platformReadSync(roadmapPath);
1888
+ if (roadmapContent === null) throw new Error('missing');
1889
+ let roadmap = extractCurrentMilestone(roadmapContent, cwd);
1890
+
1891
+ if (versionOverride) {
1892
+ const escapedVersion = escapeRegex(versionOverride);
1893
+ const sectionPattern = new RegExp(`(^#{1,3}\\s+.*${escapedVersion}[^\\n]*)`, 'mi');
1894
+ const sectionMatch = roadmapContent.match(sectionPattern);
1895
+ if (!sectionMatch) {
1896
+ // Only treat this as an error case when the roadmap is milestone-versioned.
1897
+ // Older/flat roadmap formats without vX.Y milestone headings should keep
1898
+ // legacy pass-through behavior for milestone.complete.
1899
+ const hasVersionedMilestones = /^#{1,3}\s+.*v\d+\.\d+/mi.test(roadmapContent);
1900
+ if (hasVersionedMilestones) {
1901
+ roadmap = '';
1902
+ missingExplicitVersion = true;
1903
+ }
1904
+ } else {
1905
+ const sectionStart = sectionMatch.index;
1906
+ const headingLevel = sectionMatch[1].match(/^(#{1,3})\s/)[1].length;
1907
+ const restContent = roadmapContent.slice(sectionStart + sectionMatch[0].length);
1908
+ const nextMilestonePattern = new RegExp(`^#{1,${headingLevel}}\\s+(?!Phase\\s+\\S)(?:.*v\\d+\\.\\d+|✅|📋|🚧)`, 'i');
1909
+
1910
+ let sectionEnd = roadmapContent.length;
1911
+ let fenceChar = null;
1912
+ let fenceLen = 0;
1913
+ let charOffset = 0;
1914
+ for (const line of restContent.split('\n')) {
1915
+ const fenceMatch = line.match(/^\s{0,3}((?:`{3,}|~{3,}))(.*)/);
1916
+ if (fenceMatch) {
1917
+ const char = fenceMatch[1][0];
1918
+ const len = fenceMatch[1].length;
1919
+ const trailing = fenceMatch[2] || '';
1920
+ if (!fenceChar) {
1921
+ fenceChar = char;
1922
+ fenceLen = len;
1923
+ } else if (char === fenceChar && len >= fenceLen && /^\s*$/.test(trailing)) {
1924
+ fenceChar = null;
1925
+ fenceLen = 0;
1926
+ }
1927
+ } else if (!fenceChar && nextMilestonePattern.test(line)) {
1928
+ sectionEnd = sectionStart + sectionMatch[0].length + charOffset;
1929
+ break;
1930
+ }
1931
+ charOffset += line.length + 1;
1932
+ }
1933
+
1934
+ const currentSection = roadmapContent.slice(sectionStart, sectionEnd);
1935
+ roadmap = currentSection;
1936
+ }
1937
+ }
1938
+
1939
+ // Match both numeric phases (Phase 1:) and custom IDs (Phase PROJ-42:)
1940
+ const phasePattern = /#{2,4}\s*Phase\s+([\w][\w.-]*)\s*:/gi;
1941
+ let m;
1942
+ while ((m = phasePattern.exec(roadmap)) !== null) {
1943
+ milestonePhaseNums.add(m[1]);
1944
+ }
1945
+ } catch { /* intentionally empty */ }
1946
+
1947
+ if (milestonePhaseNums.size === 0) {
1948
+ const passAll = () => true;
1949
+ passAll.phaseCount = 0;
1950
+ passAll.missingExplicitVersion = missingExplicitVersion;
1951
+ return passAll;
1952
+ }
1953
+
1954
+ const normalized = new Set(
1955
+ [...milestonePhaseNums].map(n => (n.replace(/^0+(?=\d)/, '') || '0').toLowerCase())
1956
+ );
1957
+
1958
+ function isDirInMilestone(dirName) {
1959
+ // Try numeric match first
1960
+ const m = dirName.match(/^0*(\d+[A-Za-z]?(?:\.\d+)*)/);
1961
+ if (m && normalized.has(m[1].toLowerCase())) return true;
1962
+ // Try custom ID match (e.g. PROJ-42-description → PROJ-42)
1963
+ const customMatch = dirName.match(/^([A-Za-z][A-Za-z0-9]*(?:-[A-Za-z0-9]+)*)/);
1964
+ if (customMatch && normalized.has(customMatch[1].toLowerCase())) return true;
1965
+ // #3600: project-code-prefixed directory (`CK-01-name`) against a
1966
+ // numeric ROADMAP heading (`### Phase 1:`). Strip the same prefix
1967
+ // shape `normalizePhaseName` recognises (`^[A-Z]{1,6}-(?=\d)`) and
1968
+ // retry the numeric match. This runs AFTER the custom-ID match so
1969
+ // a roadmap that uses `Phase PROJ-42:` continues to win via the
1970
+ // existing custom-ID path; the strip-and-retry only fires when the
1971
+ // milestone is keyed on the bare numeric form.
1972
+ const stripped = dirName.replace(/^[A-Z]{1,6}-(?=\d)/i, '');
1973
+ if (stripped !== dirName) {
1974
+ const sm = stripped.match(/^0*(\d+[A-Za-z]?(?:\.\d+)*)/);
1975
+ if (sm && normalized.has(sm[1].toLowerCase())) return true;
1976
+ }
1977
+ return false;
1978
+ }
1979
+ isDirInMilestone.phaseCount = milestonePhaseNums.size;
1980
+ isDirInMilestone.missingExplicitVersion = missingExplicitVersion;
1981
+ return isDirInMilestone;
1982
+ }
1983
+
1984
+ // ─── Phase file helpers ──────────────────────────────────────────────────────
1985
+
1986
+ /** Filter a file list to just PLAN.md / *-PLAN.md entries. */
1987
+ function filterPlanFiles(files) {
1988
+ return files.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
1989
+ }
1990
+
1991
+ /** Filter a file list to just SUMMARY.md / *-SUMMARY.md entries. */
1992
+ function filterSummaryFiles(files) {
1993
+ return files.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
1994
+ }
1995
+
1996
+ /**
1997
+ * Read a phase directory and return counts/flags for common file types.
1998
+ * Returns an object with plans[], summaries[], and boolean flags for
1999
+ * research/context/verification files.
2000
+ */
2001
+ function getPhaseFileStats(phaseDir) {
2002
+ const files = fs.readdirSync(phaseDir);
2003
+ return {
2004
+ plans: filterPlanFiles(files),
2005
+ summaries: filterSummaryFiles(files),
2006
+ hasResearch: files.some(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md'),
2007
+ hasContext: findContextMdIn(files) !== null,
2008
+ hasVerification: files.some(f => f.endsWith('-VERIFICATION.md') || f === 'VERIFICATION.md'),
2009
+ hasReviews: files.some(f => f.endsWith('-REVIEWS.md') || f === 'REVIEWS.md'),
2010
+ };
2011
+ }
2012
+
2013
+ /**
2014
+ * Read immediate child directories from a path.
2015
+ * Returns [] if the path doesn't exist or can't be read.
2016
+ * Pass sort=true to apply comparePhaseNum ordering.
2017
+ */
2018
+ function readSubdirectories(dirPath, sort = false) {
2019
+ try {
2020
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
2021
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
2022
+ return sort ? dirs.sort((a, b) => comparePhaseNum(a, b)) : dirs;
2023
+ } catch {
2024
+ return [];
2025
+ }
2026
+ }
2027
+
2028
+ /**
2029
+ * Format a Date as a fuzzy relative time string (e.g. "5 minutes ago").
2030
+ * @param {Date} date
2031
+ * @returns {string}
2032
+ */
2033
+ function timeAgo(date) {
2034
+ const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
2035
+ if (seconds < 5) return 'just now';
2036
+ if (seconds < 60) return `${seconds} seconds ago`;
2037
+ const minutes = Math.floor(seconds / 60);
2038
+ if (minutes === 1) return '1 minute ago';
2039
+ if (minutes < 60) return `${minutes} minutes ago`;
2040
+ const hours = Math.floor(minutes / 60);
2041
+ if (hours === 1) return '1 hour ago';
2042
+ if (hours < 24) return `${hours} hours ago`;
2043
+ const days = Math.floor(hours / 24);
2044
+ if (days === 1) return '1 day ago';
2045
+ if (days < 30) return `${days} days ago`;
2046
+ const months = Math.floor(days / 30);
2047
+ if (months === 1) return '1 month ago';
2048
+ if (months < 12) return `${months} months ago`;
2049
+ const years = Math.floor(days / 365);
2050
+ if (years === 1) return '1 year ago';
2051
+ return `${years} years ago`;
2052
+ }
2053
+
2054
+ module.exports = {
2055
+ output,
2056
+ error,
2057
+ ERROR_REASON,
2058
+ setJsonErrorMode,
2059
+ getJsonErrorMode,
2060
+ loadConfig,
2061
+ isGitIgnored,
2062
+ escapeRegex,
2063
+ normalizePhaseName,
2064
+ phaseMarkdownRegexSource,
2065
+ phaseMarkdownRegexSourceExact,
2066
+ comparePhaseNum,
2067
+ searchPhaseInDir,
2068
+ extractPhaseToken,
2069
+ phaseTokenMatches,
2070
+ findPhaseInternal,
2071
+ getArchivedPhaseDirs,
2072
+ getRoadmapPhaseInternal,
2073
+ resolveModelInternal,
2074
+ resolveModelForTier,
2075
+ resolveEffortInternal,
2076
+ resolveFastModeInternal,
2077
+ resolveEffortForTier,
2078
+ VALID_EFFORTS,
2079
+ EFFORT_SET,
2080
+ nextEffort,
2081
+ RUNTIME_PROFILE_MAP,
2082
+ RUNTIMES_WITH_REASONING_EFFORT,
2083
+ RUNTIMES_WITH_FAST_MODE,
2084
+ KNOWN_RUNTIMES,
2085
+ RUNTIME_OVERRIDE_TIERS,
2086
+ resolveTierEntry,
2087
+ _resetRuntimeWarningCacheForTests,
2088
+ pathExistsInternal,
2089
+ gitWorktreeInfoInternal,
2090
+ generateSlugInternal,
2091
+ getMilestoneInfo,
2092
+ getMilestonePhaseFilter,
2093
+ stripShippedMilestones,
2094
+ extractCurrentMilestone,
2095
+ replaceInCurrentMilestone,
2096
+ toPosixPath,
2097
+ extractOneLinerFromBody,
2098
+ resolveWorktreeRoot,
2099
+ // Deprecated re-exports — prefer direct import from planning-workspace.cjs
2100
+ withPlanningLock,
2101
+ findProjectRoot,
2102
+ detectSubRepos,
2103
+ reapStaleTempFiles,
2104
+ GSD_TEMP_DIR,
2105
+ MODEL_ALIAS_MAP,
2106
+ CONFIG_DEFAULTS,
2107
+ planningDir,
2108
+ planningRoot,
2109
+ planningPaths,
2110
+ getActiveWorkstream,
2111
+ setActiveWorkstream,
2112
+ filterPlanFiles,
2113
+ filterSummaryFiles,
2114
+ getPhaseFileStats,
2115
+ readSubdirectories,
2116
+ getAgentsDir,
2117
+ checkAgentsInstalled,
2118
+ timeAgo,
2119
+ pruneOrphanedWorktrees,
2120
+ inspectWorktreeHealth,
2121
+ };