mindforge-cc 2.0.0 → 2.1.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 (323) hide show
  1. package/.agent/bin/lib/commands.cjs +959 -0
  2. package/.agent/bin/lib/config.cjs +421 -0
  3. package/.agent/bin/lib/core.cjs +1166 -0
  4. package/.agent/bin/lib/frontmatter.cjs +307 -0
  5. package/.agent/bin/lib/init.cjs +1336 -0
  6. package/.agent/bin/lib/milestone.cjs +252 -0
  7. package/.agent/bin/lib/model-profiles.cjs +68 -0
  8. package/.agent/bin/lib/phase.cjs +888 -0
  9. package/.agent/bin/lib/profile-output.cjs +952 -0
  10. package/.agent/bin/lib/profile-pipeline.cjs +539 -0
  11. package/.agent/bin/lib/roadmap.cjs +329 -0
  12. package/.agent/bin/lib/security.cjs +356 -0
  13. package/.agent/bin/lib/state.cjs +969 -0
  14. package/.agent/bin/lib/template.cjs +222 -0
  15. package/.agent/bin/lib/uat.cjs +189 -0
  16. package/.agent/bin/lib/verify.cjs +851 -0
  17. package/.agent/bin/lib/workstream.cjs +491 -0
  18. package/.agent/bin/mindforge-tools.cjs +897 -0
  19. package/.agent/file-manifest.json +219 -0
  20. package/.agent/hooks/mindforge-check-update.js +114 -0
  21. package/.agent/hooks/mindforge-context-monitor.js +156 -0
  22. package/.agent/hooks/mindforge-prompt-guard.js +96 -0
  23. package/.agent/hooks/mindforge-statusline.js +119 -0
  24. package/.agent/hooks/mindforge-workflow-guard.js +94 -0
  25. package/.agent/mindforge/add-backlog.md +32 -0
  26. package/.agent/mindforge/agent.md +31 -0
  27. package/.agent/mindforge/discuss-phase.md +1 -1
  28. package/.agent/mindforge/do.md +31 -0
  29. package/.agent/mindforge/help.md +1 -1
  30. package/.agent/mindforge/learn.md +3 -2
  31. package/.agent/mindforge/note.md +35 -0
  32. package/.agent/mindforge/plant-seed.md +31 -0
  33. package/.agent/mindforge/research.md +3 -2
  34. package/.agent/mindforge/review-backlog.md +34 -0
  35. package/.agent/mindforge/session-report.md +39 -0
  36. package/.agent/mindforge/steer.md +1 -1
  37. package/.agent/mindforge/ui-phase.md +34 -0
  38. package/.agent/mindforge/ui-review.md +36 -0
  39. package/.agent/mindforge/validate-phase.md +31 -0
  40. package/.agent/mindforge/workstreams.md +35 -0
  41. package/.agent/settings.json +38 -0
  42. package/.agent/skills/mindforge-add-backlog/SKILL.md +72 -0
  43. package/.agent/skills/mindforge-add-phase/SKILL.md +39 -0
  44. package/.agent/skills/mindforge-add-tests/SKILL.md +28 -0
  45. package/.agent/skills/mindforge-add-todo/SKILL.md +42 -0
  46. package/.agent/skills/mindforge-audit-milestone/SKILL.md +29 -0
  47. package/.agent/skills/mindforge-audit-uat/SKILL.md +20 -0
  48. package/.agent/skills/mindforge-autonomous/SKILL.md +33 -0
  49. package/.agent/skills/mindforge-check-todos/SKILL.md +40 -0
  50. package/.agent/skills/mindforge-cleanup/SKILL.md +19 -0
  51. package/.agent/skills/mindforge-complete-milestone/SKILL.md +131 -0
  52. package/.agent/skills/mindforge-debug/SKILL.md +163 -0
  53. package/.agent/skills/mindforge-discuss-phase/SKILL.md +54 -0
  54. package/.agent/skills/mindforge-do/SKILL.md +26 -0
  55. package/.agent/skills/mindforge-execute-phase/SKILL.md +49 -0
  56. package/.agent/skills/mindforge-fast/SKILL.md +23 -0
  57. package/.agent/skills/mindforge-forensics/SKILL.md +49 -0
  58. package/.agent/skills/mindforge-health/SKILL.md +17 -0
  59. package/.agent/skills/mindforge-help/SKILL.md +23 -0
  60. package/.agent/skills/mindforge-insert-phase/SKILL.md +28 -0
  61. package/.agent/skills/mindforge-join-discord/SKILL.md +19 -0
  62. package/.agent/skills/mindforge-list-phase-assumptions/SKILL.md +41 -0
  63. package/.agent/skills/mindforge-list-workspaces/SKILL.md +17 -0
  64. package/.agent/skills/mindforge-manager/SKILL.md +32 -0
  65. package/.agent/skills/mindforge-map-codebase/SKILL.md +64 -0
  66. package/.agent/skills/mindforge-milestone-summary/SKILL.md +44 -0
  67. package/.agent/skills/mindforge-new-milestone/SKILL.md +38 -0
  68. package/.agent/skills/mindforge-new-project/SKILL.md +36 -0
  69. package/.agent/skills/mindforge-new-workspace/SKILL.md +39 -0
  70. package/.agent/skills/mindforge-next/SKILL.md +19 -0
  71. package/.agent/skills/mindforge-note/SKILL.md +29 -0
  72. package/.agent/skills/mindforge-pause-work/SKILL.md +35 -0
  73. package/.agent/skills/mindforge-plan-milestone-gaps/SKILL.md +28 -0
  74. package/.agent/skills/mindforge-plan-phase/SKILL.md +37 -0
  75. package/.agent/skills/mindforge-plant-seed/SKILL.md +22 -0
  76. package/.agent/skills/mindforge-pr-branch/SKILL.md +21 -0
  77. package/.agent/skills/mindforge-profile-user/SKILL.md +38 -0
  78. package/.agent/skills/mindforge-progress/SKILL.md +19 -0
  79. package/.agent/skills/mindforge-quick/SKILL.md +38 -0
  80. package/.agent/skills/mindforge-reapply-patches/SKILL.md +124 -0
  81. package/.agent/skills/mindforge-remove-phase/SKILL.md +26 -0
  82. package/.agent/skills/mindforge-remove-workspace/SKILL.md +22 -0
  83. package/.agent/skills/mindforge-research-phase/SKILL.md +186 -0
  84. package/.agent/skills/mindforge-resume-work/SKILL.md +35 -0
  85. package/.agent/skills/mindforge-review/SKILL.md +31 -0
  86. package/.agent/skills/mindforge-review-backlog/SKILL.md +58 -0
  87. package/.agent/skills/mindforge-session-report/SKILL.md +16 -0
  88. package/.agent/skills/mindforge-set-profile/SKILL.md +9 -0
  89. package/.agent/skills/mindforge-settings/SKILL.md +32 -0
  90. package/.agent/skills/mindforge-ship/SKILL.md +16 -0
  91. package/.agent/skills/mindforge-stats/SKILL.md +16 -0
  92. package/.agent/skills/mindforge-thread/SKILL.md +123 -0
  93. package/.agent/skills/mindforge-ui-phase/SKILL.md +24 -0
  94. package/.agent/skills/mindforge-ui-review/SKILL.md +24 -0
  95. package/.agent/skills/mindforge-update/SKILL.md +35 -0
  96. package/.agent/skills/mindforge-validate-phase/SKILL.md +26 -0
  97. package/.agent/skills/mindforge-verify-work/SKILL.md +30 -0
  98. package/.agent/skills/mindforge-workstreams/SKILL.md +65 -0
  99. package/.agent/workflows/mindforge-add-phase.md +112 -0
  100. package/.agent/workflows/mindforge-add-tests.md +351 -0
  101. package/.agent/workflows/mindforge-add-todo.md +158 -0
  102. package/.agent/workflows/mindforge-audit-milestone.md +332 -0
  103. package/.agent/workflows/mindforge-audit-uat.md +109 -0
  104. package/.agent/workflows/mindforge-autonomous.md +815 -0
  105. package/.agent/workflows/mindforge-check-todos.md +177 -0
  106. package/.agent/workflows/mindforge-cleanup.md +152 -0
  107. package/.agent/workflows/mindforge-complete-milestone.md +766 -0
  108. package/.agent/workflows/mindforge-diagnose-issues.md +220 -0
  109. package/.agent/workflows/mindforge-discovery-phase.md +289 -0
  110. package/.agent/workflows/mindforge-discuss-phase-assumptions.md +645 -0
  111. package/.agent/workflows/mindforge-discuss-phase.md +1047 -0
  112. package/.agent/workflows/mindforge-do.md +104 -0
  113. package/.agent/workflows/mindforge-execute-phase.md +838 -0
  114. package/.agent/workflows/mindforge-execute-plan.md +509 -0
  115. package/.agent/workflows/mindforge-fast.md +105 -0
  116. package/.agent/workflows/mindforge-forensics.md +265 -0
  117. package/.agent/workflows/mindforge-health.md +181 -0
  118. package/.agent/workflows/mindforge-help.md +606 -0
  119. package/.agent/workflows/mindforge-insert-phase.md +130 -0
  120. package/.agent/workflows/mindforge-list-phase-assumptions.md +178 -0
  121. package/.agent/workflows/mindforge-list-workspaces.md +56 -0
  122. package/.agent/workflows/mindforge-manager.md +360 -0
  123. package/.agent/workflows/mindforge-map-codebase.md +370 -0
  124. package/.agent/workflows/mindforge-milestone-summary.md +223 -0
  125. package/.agent/workflows/mindforge-new-milestone.md +469 -0
  126. package/.agent/workflows/mindforge-new-project.md +1226 -0
  127. package/.agent/workflows/mindforge-new-workspace.md +237 -0
  128. package/.agent/workflows/mindforge-next.md +97 -0
  129. package/.agent/workflows/mindforge-node-repair.md +92 -0
  130. package/.agent/workflows/mindforge-note.md +156 -0
  131. package/.agent/workflows/mindforge-pause-work.md +176 -0
  132. package/.agent/workflows/mindforge-plan-milestone-gaps.md +273 -0
  133. package/.agent/workflows/mindforge-plan-phase.md +848 -0
  134. package/.agent/workflows/mindforge-plant-seed.md +169 -0
  135. package/.agent/workflows/mindforge-pr-branch.md +129 -0
  136. package/.agent/workflows/mindforge-profile-user.md +450 -0
  137. package/.agent/workflows/mindforge-progress.md +507 -0
  138. package/.agent/workflows/mindforge-quick.md +732 -0
  139. package/.agent/workflows/mindforge-remove-phase.md +155 -0
  140. package/.agent/workflows/mindforge-remove-workspace.md +90 -0
  141. package/.agent/workflows/mindforge-research-phase.md +74 -0
  142. package/.agent/workflows/mindforge-resume-project.md +325 -0
  143. package/.agent/workflows/mindforge-review.md +228 -0
  144. package/.agent/workflows/mindforge-session-report.md +146 -0
  145. package/.agent/workflows/mindforge-settings.md +283 -0
  146. package/.agent/workflows/mindforge-ship.md +228 -0
  147. package/.agent/workflows/mindforge-stats.md +60 -0
  148. package/.agent/workflows/mindforge-transition.md +671 -0
  149. package/.agent/workflows/mindforge-ui-phase.md +290 -0
  150. package/.agent/workflows/mindforge-ui-review.md +157 -0
  151. package/.agent/workflows/mindforge-update.md +323 -0
  152. package/.agent/workflows/mindforge-validate-phase.md +167 -0
  153. package/.agent/workflows/mindforge-verify-phase.md +254 -0
  154. package/.agent/workflows/mindforge-verify-work.md +623 -0
  155. package/.claude/commands/mindforge/add-backlog.md +32 -0
  156. package/.claude/commands/mindforge/agent.md +31 -0
  157. package/.claude/commands/mindforge/approve.md +27 -15
  158. package/.claude/commands/mindforge/audit.md +30 -26
  159. package/.claude/commands/mindforge/auto.md +29 -18
  160. package/.claude/commands/mindforge/benchmark.md +26 -29
  161. package/.claude/commands/mindforge/browse.md +24 -22
  162. package/.claude/commands/mindforge/complete-milestone.md +28 -14
  163. package/.claude/commands/mindforge/costs.md +26 -9
  164. package/.claude/commands/mindforge/cross-review.md +27 -13
  165. package/.claude/commands/mindforge/dashboard.md +35 -98
  166. package/.claude/commands/mindforge/debug.md +34 -126
  167. package/.claude/commands/mindforge/discuss-phase.md +36 -138
  168. package/.claude/commands/mindforge/do.md +31 -0
  169. package/.claude/commands/mindforge/execute-phase.md +37 -190
  170. package/.claude/commands/mindforge/health.md +27 -17
  171. package/.claude/commands/mindforge/help.md +25 -19
  172. package/.claude/commands/mindforge/init-org.md +37 -131
  173. package/.claude/commands/mindforge/init-project.md +40 -155
  174. package/.claude/commands/mindforge/install-skill.md +32 -15
  175. package/.claude/commands/mindforge/learn.md +36 -142
  176. package/.claude/commands/mindforge/map-codebase.md +36 -298
  177. package/.claude/commands/mindforge/marketplace.md +33 -120
  178. package/.claude/commands/mindforge/metrics.md +29 -18
  179. package/.claude/commands/mindforge/migrate.md +33 -40
  180. package/.claude/commands/mindforge/milestone.md +35 -12
  181. package/.claude/commands/mindforge/new-runtime.md +25 -15
  182. package/.claude/commands/mindforge/next.md +34 -105
  183. package/.claude/commands/mindforge/note.md +35 -0
  184. package/.claude/commands/mindforge/plan-phase.md +34 -125
  185. package/.claude/commands/mindforge/plant-seed.md +31 -0
  186. package/.claude/commands/mindforge/plugins.md +30 -36
  187. package/.claude/commands/mindforge/pr-review.md +32 -41
  188. package/.claude/commands/mindforge/profile-team.md +26 -19
  189. package/.claude/commands/mindforge/publish-skill.md +28 -17
  190. package/.claude/commands/mindforge/qa.md +27 -12
  191. package/.claude/commands/mindforge/quick.md +35 -135
  192. package/.claude/commands/mindforge/release.md +27 -8
  193. package/.claude/commands/mindforge/remember.md +25 -10
  194. package/.claude/commands/mindforge/research.md +27 -9
  195. package/.claude/commands/mindforge/retrospective.md +28 -22
  196. package/.claude/commands/mindforge/review-backlog.md +34 -0
  197. package/.claude/commands/mindforge/review.md +37 -157
  198. package/.claude/commands/mindforge/security-scan.md +34 -233
  199. package/.claude/commands/mindforge/session-report.md +39 -0
  200. package/.claude/commands/mindforge/ship.md +34 -100
  201. package/.claude/commands/mindforge/skills.md +36 -141
  202. package/.claude/commands/mindforge/status.md +30 -104
  203. package/.claude/commands/mindforge/steer.md +25 -10
  204. package/.claude/commands/mindforge/sync-confluence.md +28 -9
  205. package/.claude/commands/mindforge/sync-jira.md +32 -12
  206. package/.claude/commands/mindforge/tokens.md +25 -6
  207. package/.claude/commands/mindforge/ui-phase.md +34 -0
  208. package/.claude/commands/mindforge/ui-review.md +36 -0
  209. package/.claude/commands/mindforge/update.md +33 -42
  210. package/.claude/commands/mindforge/validate-phase.md +31 -0
  211. package/.claude/commands/mindforge/verify-phase.md +30 -62
  212. package/.claude/commands/mindforge/workspace.md +28 -25
  213. package/.claude/commands/mindforge/workstreams.md +35 -0
  214. package/.mindforge/memory/decision-library.jsonl +0 -0
  215. package/.mindforge/memory/knowledge-base.jsonl +7 -0
  216. package/.mindforge/memory/pattern-library.jsonl +1 -0
  217. package/.mindforge/memory/team-preferences.jsonl +4 -0
  218. package/.mindforge/personas/advisor-researcher.md +89 -0
  219. package/.mindforge/personas/analyst.md +112 -52
  220. package/.mindforge/personas/architect.md +100 -67
  221. package/.mindforge/personas/assumptions-analyzer-extend.md +87 -0
  222. package/.mindforge/personas/assumptions-analyzer.md +109 -0
  223. package/.mindforge/personas/codebase-mapper-extend.md +93 -0
  224. package/.mindforge/personas/codebase-mapper.md +770 -0
  225. package/.mindforge/personas/coverage-specialist.md +104 -0
  226. package/.mindforge/personas/debug-specialist.md +118 -52
  227. package/.mindforge/personas/debugger.md +97 -0
  228. package/.mindforge/personas/decision-architect.md +102 -0
  229. package/.mindforge/personas/developer.md +97 -85
  230. package/.mindforge/personas/executor.md +88 -0
  231. package/.mindforge/personas/integration-checker.md +92 -0
  232. package/.mindforge/personas/nyquist-auditor.md +84 -0
  233. package/.mindforge/personas/phase-researcher.md +107 -0
  234. package/.mindforge/personas/plan-checker.md +92 -0
  235. package/.mindforge/personas/planner.md +105 -0
  236. package/.mindforge/personas/project-researcher.md +99 -0
  237. package/.mindforge/personas/qa-engineer.md +113 -61
  238. package/.mindforge/personas/release-manager.md +102 -64
  239. package/.mindforge/personas/research-agent.md +109 -24
  240. package/.mindforge/personas/research-synthesizer.md +101 -0
  241. package/.mindforge/personas/roadmapper-extend.md +100 -0
  242. package/.mindforge/personas/roadmapper.md +103 -0
  243. package/.mindforge/personas/security-reviewer.md +114 -91
  244. package/.mindforge/personas/tech-writer.md +118 -51
  245. package/.mindforge/personas/ui-auditor.md +94 -0
  246. package/.mindforge/personas/ui-checker.md +89 -0
  247. package/.mindforge/personas/ui-researcher.md +99 -0
  248. package/.mindforge/personas/user-profiler.md +93 -0
  249. package/.mindforge/personas/verifier.md +101 -0
  250. package/.planning/ROADMAP.md +10 -0
  251. package/.planning/browser-daemon.log +32 -0
  252. package/.planning/phases/01-migrate-gsd-to-mindforge/.gitkeep +0 -0
  253. package/CHANGELOG.md +41 -0
  254. package/MINDFORGE.md +2 -0
  255. package/README.md +40 -3
  256. package/bin/installer-core.js +3 -4
  257. package/docs/PERSONAS.md +611 -0
  258. package/docs/commands-reference.md +1 -0
  259. package/docs/{Context → context}/Master-Context.md +6 -13
  260. package/docs/references/checkpoints.md +778 -0
  261. package/docs/{reference → references}/commands.md +53 -43
  262. package/docs/references/continuation-format.md +249 -0
  263. package/docs/references/decimal-phase-calculation.md +64 -0
  264. package/docs/references/git-integration.md +295 -0
  265. package/docs/references/git-planning-commit.md +38 -0
  266. package/docs/references/model-profile-resolution.md +36 -0
  267. package/docs/references/model-profiles.md +139 -0
  268. package/docs/references/phase-argument-parsing.md +61 -0
  269. package/docs/references/planning-config.md +202 -0
  270. package/docs/references/questioning.md +162 -0
  271. package/docs/references/tdd.md +263 -0
  272. package/docs/references/ui-brand.md +160 -0
  273. package/docs/references/user-profiling.md +681 -0
  274. package/docs/references/verification-patterns.md +612 -0
  275. package/docs/references/workstream-flag.md +58 -0
  276. package/docs/skills-authoring-guide.md +1 -1
  277. package/docs/templates/Agents/CLAUDE-MD.md +122 -0
  278. package/docs/templates/Agents/COPILOT-INSTRUCTIONS.md +7 -0
  279. package/docs/templates/Agents/DEBUGGER-PROMPT.md +91 -0
  280. package/docs/templates/Agents/PLANNER-PROMPT.md +117 -0
  281. package/docs/templates/Execution/CONTINUE-HERE.md +78 -0
  282. package/docs/templates/Execution/DISCUSSION-LOG.md +63 -0
  283. package/docs/templates/Execution/PHASE-PROMPT.md +610 -0
  284. package/docs/templates/Execution/STATE.md +176 -0
  285. package/docs/templates/Execution/SUMMARY-COMPLEX.md +59 -0
  286. package/docs/templates/Execution/SUMMARY-MINIMAL.md +41 -0
  287. package/docs/templates/Execution/SUMMARY-STANDARD.md +48 -0
  288. package/docs/templates/Execution/SUMMARY.md +248 -0
  289. package/docs/templates/Profile/DEV-PREFERENCES.md +21 -0
  290. package/docs/templates/Profile/USER-PROFILE.md +146 -0
  291. package/docs/templates/Profile/USER-SETUP.md +311 -0
  292. package/docs/templates/Project/DISCOVERY.md +146 -0
  293. package/docs/templates/Project/MILESTONE-ARCHIVE.md +123 -0
  294. package/docs/templates/Project/MILESTONE.md +115 -0
  295. package/docs/templates/Project/PROJECT.md +206 -0
  296. package/docs/templates/Project/REQUIREMENTS.md +231 -0
  297. package/docs/templates/Project/RETROSPECTIVE.md +54 -0
  298. package/docs/templates/Project/ROADMAP.md +202 -0
  299. package/docs/templates/Quality/DEBUG.md +164 -0
  300. package/docs/templates/Quality/UAT.md +280 -0
  301. package/docs/templates/Quality/UI-SPEC.md +100 -0
  302. package/docs/templates/Quality/VALIDATION.md +76 -0
  303. package/docs/templates/Quality/VERIFICATION-REPORT.md +322 -0
  304. package/docs/templates/System/CONFIG.json +43 -0
  305. package/docs/templates/System/CONTEXT.md +352 -0
  306. package/docs/templates/codebase/architecture.md +255 -0
  307. package/docs/templates/codebase/concerns.md +310 -0
  308. package/docs/templates/codebase/conventions.md +307 -0
  309. package/docs/templates/codebase/integrations.md +280 -0
  310. package/docs/templates/codebase/stack.md +186 -0
  311. package/docs/templates/codebase/structure.md +285 -0
  312. package/docs/templates/codebase/testing.md +480 -0
  313. package/docs/templates/research/ARCHITECTURE.md +204 -0
  314. package/docs/templates/research/FEATURES.md +147 -0
  315. package/docs/templates/research/PITFALLS.md +200 -0
  316. package/docs/templates/research/STACK.md +120 -0
  317. package/docs/templates/research/SUMMARY.md +170 -0
  318. package/docs/user-guide.md +1 -1
  319. package/package.json +7 -2
  320. /package/docs/{reference → references}/audit-events.md +0 -0
  321. /package/docs/{reference → references}/config-reference.md +0 -0
  322. /package/docs/{reference → references}/sdk-api.md +0 -0
  323. /package/docs/{reference → references}/skills-api.md +0 -0
@@ -0,0 +1,969 @@
1
+ /**
2
+ * State — STATE.md operations and progression engine
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { escapeRegex, loadConfig, getMilestoneInfo, getMilestonePhaseFilter, normalizeMd, planningDir, planningPaths, output, error } = require('./core.cjs');
8
+ const { extractFrontmatter, reconstructFrontmatter } = require('./frontmatter.cjs');
9
+
10
+ /** Shorthand — every state command needs this path */
11
+ function getStatePath(cwd) {
12
+ return planningPaths(cwd).state;
13
+ }
14
+
15
+ // Shared helper: extract a field value from STATE.md content.
16
+ // Supports both **Field:** bold and plain Field: format.
17
+ function stateExtractField(content, fieldName) {
18
+ const escaped = escapeRegex(fieldName);
19
+ const boldPattern = new RegExp(`\\*\\*${escaped}:\\*\\*\\s*(.+)`, 'i');
20
+ const boldMatch = content.match(boldPattern);
21
+ if (boldMatch) return boldMatch[1].trim();
22
+ const plainPattern = new RegExp(`^${escaped}:\\s*(.+)`, 'im');
23
+ const plainMatch = content.match(plainPattern);
24
+ return plainMatch ? plainMatch[1].trim() : null;
25
+ }
26
+
27
+ function cmdStateLoad(cwd, raw) {
28
+ const config = loadConfig(cwd);
29
+ const planDir = planningPaths(cwd).planning;
30
+
31
+ let stateRaw = '';
32
+ try {
33
+ stateRaw = fs.readFileSync(path.join(planDir, 'STATE.md'), 'utf-8');
34
+ } catch { /* intentionally empty */ }
35
+
36
+ const configExists = fs.existsSync(path.join(planDir, 'config.json'));
37
+ const roadmapExists = fs.existsSync(path.join(planDir, 'ROADMAP.md'));
38
+ const stateExists = stateRaw.length > 0;
39
+
40
+ const result = {
41
+ config,
42
+ state_raw: stateRaw,
43
+ state_exists: stateExists,
44
+ roadmap_exists: roadmapExists,
45
+ config_exists: configExists,
46
+ };
47
+
48
+ // For --raw, output a condensed key=value format
49
+ if (raw) {
50
+ const c = config;
51
+ const lines = [
52
+ `model_profile=${c.model_profile}`,
53
+ `commit_docs=${c.commit_docs}`,
54
+ `branching_strategy=${c.branching_strategy}`,
55
+ `phase_branch_template=${c.phase_branch_template}`,
56
+ `milestone_branch_template=${c.milestone_branch_template}`,
57
+ `parallelization=${c.parallelization}`,
58
+ `research=${c.research}`,
59
+ `plan_checker=${c.plan_checker}`,
60
+ `verifier=${c.verifier}`,
61
+ `config_exists=${configExists}`,
62
+ `roadmap_exists=${roadmapExists}`,
63
+ `state_exists=${stateExists}`,
64
+ ];
65
+ process.stdout.write(lines.join('\n'));
66
+ process.exit(0);
67
+ }
68
+
69
+ output(result);
70
+ }
71
+
72
+ function cmdStateGet(cwd, section, raw) {
73
+ const statePath = planningPaths(cwd).state;
74
+ try {
75
+ const content = fs.readFileSync(statePath, 'utf-8');
76
+
77
+ if (!section) {
78
+ output({ content }, raw, content);
79
+ return;
80
+ }
81
+
82
+ // Try to find markdown section or field
83
+ const fieldEscaped = escapeRegex(section);
84
+
85
+ // Check for **field:** value (bold format)
86
+ const boldPattern = new RegExp(`\\*\\*${fieldEscaped}:\\*\\*\\s*(.*)`, 'i');
87
+ const boldMatch = content.match(boldPattern);
88
+ if (boldMatch) {
89
+ output({ [section]: boldMatch[1].trim() }, raw, boldMatch[1].trim());
90
+ return;
91
+ }
92
+
93
+ // Check for field: value (plain format)
94
+ const plainPattern = new RegExp(`^${fieldEscaped}:\\s*(.*)`, 'im');
95
+ const plainMatch = content.match(plainPattern);
96
+ if (plainMatch) {
97
+ output({ [section]: plainMatch[1].trim() }, raw, plainMatch[1].trim());
98
+ return;
99
+ }
100
+
101
+ // Check for ## Section
102
+ const sectionPattern = new RegExp(`##\\s*${fieldEscaped}\\s*\n([\\s\\S]*?)(?=\\n##|$)`, 'i');
103
+ const sectionMatch = content.match(sectionPattern);
104
+ if (sectionMatch) {
105
+ output({ [section]: sectionMatch[1].trim() }, raw, sectionMatch[1].trim());
106
+ return;
107
+ }
108
+
109
+ output({ error: `Section or field "${section}" not found` }, raw, '');
110
+ } catch {
111
+ error('STATE.md not found');
112
+ }
113
+ }
114
+
115
+ function readTextArgOrFile(cwd, value, filePath, label) {
116
+ if (!filePath) return value;
117
+
118
+ // Path traversal guard: ensure file resolves within project directory
119
+ const { validatePath } = require('./security.cjs');
120
+ const pathCheck = validatePath(filePath, cwd, { allowAbsolute: true });
121
+ if (!pathCheck.safe) {
122
+ throw new Error(`${label} path rejected: ${pathCheck.error}`);
123
+ }
124
+
125
+ try {
126
+ return fs.readFileSync(pathCheck.resolved, 'utf-8').trimEnd();
127
+ } catch {
128
+ throw new Error(`${label} file not found: ${filePath}`);
129
+ }
130
+ }
131
+
132
+ function cmdStatePatch(cwd, patches, raw) {
133
+ // Validate all field names before processing
134
+ const { validateFieldName } = require('./security.cjs');
135
+ for (const field of Object.keys(patches)) {
136
+ const fieldCheck = validateFieldName(field);
137
+ if (!fieldCheck.valid) {
138
+ error(`state patch: ${fieldCheck.error}`);
139
+ }
140
+ }
141
+
142
+ const statePath = planningPaths(cwd).state;
143
+ try {
144
+ let content = fs.readFileSync(statePath, 'utf-8');
145
+ const results = { updated: [], failed: [] };
146
+
147
+ for (const [field, value] of Object.entries(patches)) {
148
+ const fieldEscaped = escapeRegex(field);
149
+ // Try **Field:** bold format first, then plain Field: format
150
+ const boldPattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
151
+ const plainPattern = new RegExp(`(^${fieldEscaped}:\\s*)(.*)`, 'im');
152
+
153
+ if (boldPattern.test(content)) {
154
+ content = content.replace(boldPattern, (_match, prefix) => `${prefix}${value}`);
155
+ results.updated.push(field);
156
+ } else if (plainPattern.test(content)) {
157
+ content = content.replace(plainPattern, (_match, prefix) => `${prefix}${value}`);
158
+ results.updated.push(field);
159
+ } else {
160
+ results.failed.push(field);
161
+ }
162
+ }
163
+
164
+ if (results.updated.length > 0) {
165
+ writeStateMd(statePath, content, cwd);
166
+ }
167
+
168
+ output(results, raw, results.updated.length > 0 ? 'true' : 'false');
169
+ } catch {
170
+ error('STATE.md not found');
171
+ }
172
+ }
173
+
174
+ function cmdStateUpdate(cwd, field, value) {
175
+ if (!field || value === undefined) {
176
+ error('field and value required for state update');
177
+ }
178
+
179
+ // Validate field name to prevent regex injection via crafted field names
180
+ const { validateFieldName } = require('./security.cjs');
181
+ const fieldCheck = validateFieldName(field);
182
+ if (!fieldCheck.valid) {
183
+ error(`state update: ${fieldCheck.error}`);
184
+ }
185
+
186
+ const statePath = planningPaths(cwd).state;
187
+ try {
188
+ let content = fs.readFileSync(statePath, 'utf-8');
189
+ const fieldEscaped = escapeRegex(field);
190
+ // Try **Field:** bold format first, then plain Field: format
191
+ const boldPattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
192
+ const plainPattern = new RegExp(`(^${fieldEscaped}:\\s*)(.*)`, 'im');
193
+ if (boldPattern.test(content)) {
194
+ content = content.replace(boldPattern, (_match, prefix) => `${prefix}${value}`);
195
+ writeStateMd(statePath, content, cwd);
196
+ output({ updated: true });
197
+ } else if (plainPattern.test(content)) {
198
+ content = content.replace(plainPattern, (_match, prefix) => `${prefix}${value}`);
199
+ writeStateMd(statePath, content, cwd);
200
+ output({ updated: true });
201
+ } else {
202
+ output({ updated: false, reason: `Field "${field}" not found in STATE.md` });
203
+ }
204
+ } catch {
205
+ output({ updated: false, reason: 'STATE.md not found' });
206
+ }
207
+ }
208
+
209
+ // ─── State Progression Engine ────────────────────────────────────────────────
210
+ // stateExtractField is defined above (shared helper) — do not duplicate.
211
+
212
+ function stateReplaceField(content, fieldName, newValue) {
213
+ const escaped = escapeRegex(fieldName);
214
+ // Try **Field:** bold format first, then plain Field: format
215
+ const boldPattern = new RegExp(`(\\*\\*${escaped}:\\*\\*\\s*)(.*)`, 'i');
216
+ if (boldPattern.test(content)) {
217
+ return content.replace(boldPattern, (_match, prefix) => `${prefix}${newValue}`);
218
+ }
219
+ const plainPattern = new RegExp(`(^${escaped}:\\s*)(.*)`, 'im');
220
+ if (plainPattern.test(content)) {
221
+ return content.replace(plainPattern, (_match, prefix) => `${prefix}${newValue}`);
222
+ }
223
+ return null;
224
+ }
225
+
226
+ /**
227
+ * Replace a STATE.md field with fallback field name support.
228
+ * Tries `primary` first, then `fallback` (if provided), returns content unchanged
229
+ * if neither matches. This consolidates the replaceWithFallback pattern that was
230
+ * previously duplicated inline across phase.cjs, milestone.cjs, and state.cjs.
231
+ */
232
+ function stateReplaceFieldWithFallback(content, primary, fallback, value) {
233
+ let result = stateReplaceField(content, primary, value);
234
+ if (result) return result;
235
+ if (fallback) {
236
+ result = stateReplaceField(content, fallback, value);
237
+ if (result) return result;
238
+ }
239
+ return content;
240
+ }
241
+
242
+ function cmdStateAdvancePlan(cwd, raw) {
243
+ const statePath = planningPaths(cwd).state;
244
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
245
+
246
+ let content = fs.readFileSync(statePath, 'utf-8');
247
+ const today = new Date().toISOString().split('T')[0];
248
+
249
+ // Try legacy separate fields first, then compound "Plan: X of Y" format
250
+ const legacyPlan = stateExtractField(content, 'Current Plan');
251
+ const legacyTotal = stateExtractField(content, 'Total Plans in Phase');
252
+ const planField = stateExtractField(content, 'Plan');
253
+
254
+ let currentPlan, totalPlans;
255
+ let useCompoundFormat = false;
256
+
257
+ if (legacyPlan && legacyTotal) {
258
+ currentPlan = parseInt(legacyPlan, 10);
259
+ totalPlans = parseInt(legacyTotal, 10);
260
+ } else if (planField) {
261
+ // Compound format: "2 of 6 in current phase" or "2 of 6"
262
+ currentPlan = parseInt(planField, 10);
263
+ const ofMatch = planField.match(/of\s+(\d+)/);
264
+ totalPlans = ofMatch ? parseInt(ofMatch[1], 10) : NaN;
265
+ useCompoundFormat = true;
266
+ }
267
+
268
+ if (isNaN(currentPlan) || isNaN(totalPlans)) {
269
+ output({ error: 'Cannot parse Current Plan or Total Plans in Phase from STATE.md' }, raw);
270
+ return;
271
+ }
272
+
273
+ if (currentPlan >= totalPlans) {
274
+ content = stateReplaceFieldWithFallback(content, 'Status', null, 'Phase complete — ready for verification');
275
+ content = stateReplaceFieldWithFallback(content, 'Last Activity', 'Last activity', today);
276
+ writeStateMd(statePath, content, cwd);
277
+ output({ advanced: false, reason: 'last_plan', current_plan: currentPlan, total_plans: totalPlans, status: 'ready_for_verification' }, raw, 'false');
278
+ } else {
279
+ const newPlan = currentPlan + 1;
280
+ if (useCompoundFormat) {
281
+ // Preserve compound format: "X of Y in current phase" → replace X only
282
+ const newPlanValue = planField.replace(/^\d+/, String(newPlan));
283
+ content = stateReplaceField(content, 'Plan', newPlanValue) || content;
284
+ } else {
285
+ content = stateReplaceField(content, 'Current Plan', String(newPlan)) || content;
286
+ }
287
+ content = stateReplaceFieldWithFallback(content, 'Status', null, 'Ready to execute');
288
+ content = stateReplaceFieldWithFallback(content, 'Last Activity', 'Last activity', today);
289
+ writeStateMd(statePath, content, cwd);
290
+ output({ advanced: true, previous_plan: currentPlan, current_plan: newPlan, total_plans: totalPlans }, raw, 'true');
291
+ }
292
+ }
293
+
294
+ function cmdStateRecordMetric(cwd, options, raw) {
295
+ const statePath = planningPaths(cwd).state;
296
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
297
+
298
+ let content = fs.readFileSync(statePath, 'utf-8');
299
+ const { phase, plan, duration, tasks, files } = options;
300
+
301
+ if (!phase || !plan || !duration) {
302
+ output({ error: 'phase, plan, and duration required' }, raw);
303
+ return;
304
+ }
305
+
306
+ // Find Performance Metrics section and its table
307
+ const metricsPattern = /(##\s*Performance Metrics[\s\S]*?\n\|[^\n]+\n\|[-|\s]+\n)([\s\S]*?)(?=\n##|\n$|$)/i;
308
+ const metricsMatch = content.match(metricsPattern);
309
+
310
+ if (metricsMatch) {
311
+ let tableBody = metricsMatch[2].trimEnd();
312
+ const newRow = `| Phase ${phase} P${plan} | ${duration} | ${tasks || '-'} tasks | ${files || '-'} files |`;
313
+
314
+ if (tableBody.trim() === '' || tableBody.includes('None yet')) {
315
+ tableBody = newRow;
316
+ } else {
317
+ tableBody = tableBody + '\n' + newRow;
318
+ }
319
+
320
+ content = content.replace(metricsPattern, (_match, header) => `${header}${tableBody}\n`);
321
+ writeStateMd(statePath, content, cwd);
322
+ output({ recorded: true, phase, plan, duration }, raw, 'true');
323
+ } else {
324
+ output({ recorded: false, reason: 'Performance Metrics section not found in STATE.md' }, raw, 'false');
325
+ }
326
+ }
327
+
328
+ function cmdStateUpdateProgress(cwd, raw) {
329
+ const statePath = planningPaths(cwd).state;
330
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
331
+
332
+ let content = fs.readFileSync(statePath, 'utf-8');
333
+
334
+ // Count summaries across current milestone phases only
335
+ const phasesDir = planningPaths(cwd).phases;
336
+ let totalPlans = 0;
337
+ let totalSummaries = 0;
338
+
339
+ if (fs.existsSync(phasesDir)) {
340
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
341
+ const phaseDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
342
+ .filter(e => e.isDirectory()).map(e => e.name)
343
+ .filter(isDirInMilestone);
344
+ for (const dir of phaseDirs) {
345
+ const files = fs.readdirSync(path.join(phasesDir, dir));
346
+ totalPlans += files.filter(f => f.match(/-PLAN\.md$/i)).length;
347
+ totalSummaries += files.filter(f => f.match(/-SUMMARY\.md$/i)).length;
348
+ }
349
+ }
350
+
351
+ const percent = totalPlans > 0 ? Math.min(100, Math.round(totalSummaries / totalPlans * 100)) : 0;
352
+ const barWidth = 10;
353
+ const filled = Math.round(percent / 100 * barWidth);
354
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
355
+ const progressStr = `[${bar}] ${percent}%`;
356
+
357
+ // Try **Progress:** bold format first, then plain Progress: format
358
+ const boldProgressPattern = /(\*\*Progress:\*\*\s*).*/i;
359
+ const plainProgressPattern = /^(Progress:\s*).*/im;
360
+ if (boldProgressPattern.test(content)) {
361
+ content = content.replace(boldProgressPattern, (_match, prefix) => `${prefix}${progressStr}`);
362
+ writeStateMd(statePath, content, cwd);
363
+ output({ updated: true, percent, completed: totalSummaries, total: totalPlans, bar: progressStr }, raw, progressStr);
364
+ } else if (plainProgressPattern.test(content)) {
365
+ content = content.replace(plainProgressPattern, (_match, prefix) => `${prefix}${progressStr}`);
366
+ writeStateMd(statePath, content, cwd);
367
+ output({ updated: true, percent, completed: totalSummaries, total: totalPlans, bar: progressStr }, raw, progressStr);
368
+ } else {
369
+ output({ updated: false, reason: 'Progress field not found in STATE.md' }, raw, 'false');
370
+ }
371
+ }
372
+
373
+ function cmdStateAddDecision(cwd, options, raw) {
374
+ const statePath = planningPaths(cwd).state;
375
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
376
+
377
+ const { phase, summary, summary_file, rationale, rationale_file } = options;
378
+ let summaryText = null;
379
+ let rationaleText = '';
380
+
381
+ try {
382
+ summaryText = readTextArgOrFile(cwd, summary, summary_file, 'summary');
383
+ rationaleText = readTextArgOrFile(cwd, rationale || '', rationale_file, 'rationale');
384
+ } catch (err) {
385
+ output({ added: false, reason: err.message }, raw, 'false');
386
+ return;
387
+ }
388
+
389
+ if (!summaryText) { output({ error: 'summary required' }, raw); return; }
390
+
391
+ let content = fs.readFileSync(statePath, 'utf-8');
392
+ const entry = `- [Phase ${phase || '?'}]: ${summaryText}${rationaleText ? ` — ${rationaleText}` : ''}`;
393
+
394
+ // Find Decisions section (various heading patterns)
395
+ const sectionPattern = /(###?\s*(?:Decisions|Decisions Made|Accumulated.*Decisions)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
396
+ const match = content.match(sectionPattern);
397
+
398
+ if (match) {
399
+ let sectionBody = match[2];
400
+ // Remove placeholders
401
+ sectionBody = sectionBody.replace(/None yet\.?\s*\n?/gi, '').replace(/No decisions yet\.?\s*\n?/gi, '');
402
+ sectionBody = sectionBody.trimEnd() + '\n' + entry + '\n';
403
+ content = content.replace(sectionPattern, (_match, header) => `${header}${sectionBody}`);
404
+ writeStateMd(statePath, content, cwd);
405
+ output({ added: true, decision: entry }, raw, 'true');
406
+ } else {
407
+ output({ added: false, reason: 'Decisions section not found in STATE.md' }, raw, 'false');
408
+ }
409
+ }
410
+
411
+ function cmdStateAddBlocker(cwd, text, raw) {
412
+ const statePath = planningPaths(cwd).state;
413
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
414
+ const blockerOptions = typeof text === 'object' && text !== null ? text : { text };
415
+ let blockerText = null;
416
+
417
+ try {
418
+ blockerText = readTextArgOrFile(cwd, blockerOptions.text, blockerOptions.text_file, 'blocker');
419
+ } catch (err) {
420
+ output({ added: false, reason: err.message }, raw, 'false');
421
+ return;
422
+ }
423
+
424
+ if (!blockerText) { output({ error: 'text required' }, raw); return; }
425
+
426
+ let content = fs.readFileSync(statePath, 'utf-8');
427
+ const entry = `- ${blockerText}`;
428
+
429
+ const sectionPattern = /(###?\s*(?:Blockers|Blockers\/Concerns|Concerns)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
430
+ const match = content.match(sectionPattern);
431
+
432
+ if (match) {
433
+ let sectionBody = match[2];
434
+ sectionBody = sectionBody.replace(/None\.?\s*\n?/gi, '').replace(/None yet\.?\s*\n?/gi, '');
435
+ sectionBody = sectionBody.trimEnd() + '\n' + entry + '\n';
436
+ content = content.replace(sectionPattern, (_match, header) => `${header}${sectionBody}`);
437
+ writeStateMd(statePath, content, cwd);
438
+ output({ added: true, blocker: blockerText }, raw, 'true');
439
+ } else {
440
+ output({ added: false, reason: 'Blockers section not found in STATE.md' }, raw, 'false');
441
+ }
442
+ }
443
+
444
+ function cmdStateResolveBlocker(cwd, text, raw) {
445
+ const statePath = planningPaths(cwd).state;
446
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
447
+ if (!text) { output({ error: 'text required' }, raw); return; }
448
+
449
+ let content = fs.readFileSync(statePath, 'utf-8');
450
+
451
+ const sectionPattern = /(###?\s*(?:Blockers|Blockers\/Concerns|Concerns)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
452
+ const match = content.match(sectionPattern);
453
+
454
+ if (match) {
455
+ const sectionBody = match[2];
456
+ const lines = sectionBody.split('\n');
457
+ const filtered = lines.filter(line => {
458
+ if (!line.startsWith('- ')) return true;
459
+ return !line.toLowerCase().includes(text.toLowerCase());
460
+ });
461
+
462
+ let newBody = filtered.join('\n');
463
+ // If section is now empty, add placeholder
464
+ if (!newBody.trim() || !newBody.includes('- ')) {
465
+ newBody = 'None\n';
466
+ }
467
+
468
+ content = content.replace(sectionPattern, (_match, header) => `${header}${newBody}`);
469
+ writeStateMd(statePath, content, cwd);
470
+ output({ resolved: true, blocker: text }, raw, 'true');
471
+ } else {
472
+ output({ resolved: false, reason: 'Blockers section not found in STATE.md' }, raw, 'false');
473
+ }
474
+ }
475
+
476
+ function cmdStateRecordSession(cwd, options, raw) {
477
+ const statePath = planningPaths(cwd).state;
478
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
479
+
480
+ let content = fs.readFileSync(statePath, 'utf-8');
481
+ const now = new Date().toISOString();
482
+ const updated = [];
483
+
484
+ // Update Last session / Last Date
485
+ let result = stateReplaceField(content, 'Last session', now);
486
+ if (result) { content = result; updated.push('Last session'); }
487
+ result = stateReplaceField(content, 'Last Date', now);
488
+ if (result) { content = result; updated.push('Last Date'); }
489
+
490
+ // Update Stopped at
491
+ if (options.stopped_at) {
492
+ result = stateReplaceField(content, 'Stopped At', options.stopped_at);
493
+ if (!result) result = stateReplaceField(content, 'Stopped at', options.stopped_at);
494
+ if (result) { content = result; updated.push('Stopped At'); }
495
+ }
496
+
497
+ // Update Resume file
498
+ const resumeFile = options.resume_file || 'None';
499
+ result = stateReplaceField(content, 'Resume File', resumeFile);
500
+ if (!result) result = stateReplaceField(content, 'Resume file', resumeFile);
501
+ if (result) { content = result; updated.push('Resume File'); }
502
+
503
+ if (updated.length > 0) {
504
+ writeStateMd(statePath, content, cwd);
505
+ output({ recorded: true, updated }, raw, 'true');
506
+ } else {
507
+ output({ recorded: false, reason: 'No session fields found in STATE.md' }, raw, 'false');
508
+ }
509
+ }
510
+
511
+ function cmdStateSnapshot(cwd, raw) {
512
+ const statePath = planningPaths(cwd).state;
513
+
514
+ if (!fs.existsSync(statePath)) {
515
+ output({ error: 'STATE.md not found' }, raw);
516
+ return;
517
+ }
518
+
519
+ const content = fs.readFileSync(statePath, 'utf-8');
520
+
521
+ // Extract basic fields
522
+ const currentPhase = stateExtractField(content, 'Current Phase');
523
+ const currentPhaseName = stateExtractField(content, 'Current Phase Name');
524
+ const totalPhasesRaw = stateExtractField(content, 'Total Phases');
525
+ const currentPlan = stateExtractField(content, 'Current Plan');
526
+ const totalPlansRaw = stateExtractField(content, 'Total Plans in Phase');
527
+ const status = stateExtractField(content, 'Status');
528
+ const progressRaw = stateExtractField(content, 'Progress');
529
+ const lastActivity = stateExtractField(content, 'Last Activity');
530
+ const lastActivityDesc = stateExtractField(content, 'Last Activity Description');
531
+ const pausedAt = stateExtractField(content, 'Paused At');
532
+
533
+ // Parse numeric fields
534
+ const totalPhases = totalPhasesRaw ? parseInt(totalPhasesRaw, 10) : null;
535
+ const totalPlansInPhase = totalPlansRaw ? parseInt(totalPlansRaw, 10) : null;
536
+ const progressPercent = progressRaw ? parseInt(progressRaw.replace('%', ''), 10) : null;
537
+
538
+ // Extract decisions table
539
+ const decisions = [];
540
+ const decisionsMatch = content.match(/##\s*Decisions Made[\s\S]*?\n\|[^\n]+\n\|[-|\s]+\n([\s\S]*?)(?=\n##|\n$|$)/i);
541
+ if (decisionsMatch) {
542
+ const tableBody = decisionsMatch[1];
543
+ const rows = tableBody.trim().split('\n').filter(r => r.includes('|'));
544
+ for (const row of rows) {
545
+ const cells = row.split('|').map(c => c.trim()).filter(Boolean);
546
+ if (cells.length >= 3) {
547
+ decisions.push({
548
+ phase: cells[0],
549
+ summary: cells[1],
550
+ rationale: cells[2],
551
+ });
552
+ }
553
+ }
554
+ }
555
+
556
+ // Extract blockers list
557
+ const blockers = [];
558
+ const blockersMatch = content.match(/##\s*Blockers\s*\n([\s\S]*?)(?=\n##|$)/i);
559
+ if (blockersMatch) {
560
+ const blockersSection = blockersMatch[1];
561
+ const items = blockersSection.match(/^-\s+(.+)$/gm) || [];
562
+ for (const item of items) {
563
+ blockers.push(item.replace(/^-\s+/, '').trim());
564
+ }
565
+ }
566
+
567
+ // Extract session info
568
+ const session = {
569
+ last_date: null,
570
+ stopped_at: null,
571
+ resume_file: null,
572
+ };
573
+
574
+ const sessionMatch = content.match(/##\s*Session\s*\n([\s\S]*?)(?=\n##|$)/i);
575
+ if (sessionMatch) {
576
+ const sessionSection = sessionMatch[1];
577
+ const lastDateMatch = sessionSection.match(/\*\*Last Date:\*\*\s*(.+)/i)
578
+ || sessionSection.match(/^Last Date:\s*(.+)/im);
579
+ const stoppedAtMatch = sessionSection.match(/\*\*Stopped At:\*\*\s*(.+)/i)
580
+ || sessionSection.match(/^Stopped At:\s*(.+)/im);
581
+ const resumeFileMatch = sessionSection.match(/\*\*Resume File:\*\*\s*(.+)/i)
582
+ || sessionSection.match(/^Resume File:\s*(.+)/im);
583
+
584
+ if (lastDateMatch) session.last_date = lastDateMatch[1].trim();
585
+ if (stoppedAtMatch) session.stopped_at = stoppedAtMatch[1].trim();
586
+ if (resumeFileMatch) session.resume_file = resumeFileMatch[1].trim();
587
+ }
588
+
589
+ const result = {
590
+ current_phase: currentPhase,
591
+ current_phase_name: currentPhaseName,
592
+ total_phases: totalPhases,
593
+ current_plan: currentPlan,
594
+ total_plans_in_phase: totalPlansInPhase,
595
+ status,
596
+ progress_percent: progressPercent,
597
+ last_activity: lastActivity,
598
+ last_activity_desc: lastActivityDesc,
599
+ decisions,
600
+ blockers,
601
+ paused_at: pausedAt,
602
+ session,
603
+ };
604
+
605
+ output(result, raw);
606
+ }
607
+
608
+ // ─── State Frontmatter Sync ──────────────────────────────────────────────────
609
+
610
+ /**
611
+ * Extract machine-readable fields from STATE.md markdown body and build
612
+ * a YAML frontmatter object. Allows hooks and scripts to read state
613
+ * reliably via `state json` instead of fragile regex parsing.
614
+ */
615
+ function buildStateFrontmatter(bodyContent, cwd) {
616
+ const currentPhase = stateExtractField(bodyContent, 'Current Phase');
617
+ const currentPhaseName = stateExtractField(bodyContent, 'Current Phase Name');
618
+ const currentPlan = stateExtractField(bodyContent, 'Current Plan');
619
+ const totalPhasesRaw = stateExtractField(bodyContent, 'Total Phases');
620
+ const totalPlansRaw = stateExtractField(bodyContent, 'Total Plans in Phase');
621
+ const status = stateExtractField(bodyContent, 'Status');
622
+ const progressRaw = stateExtractField(bodyContent, 'Progress');
623
+ const lastActivity = stateExtractField(bodyContent, 'Last Activity');
624
+ const stoppedAt = stateExtractField(bodyContent, 'Stopped At') || stateExtractField(bodyContent, 'Stopped at');
625
+ const pausedAt = stateExtractField(bodyContent, 'Paused At');
626
+
627
+ let milestone = null;
628
+ let milestoneName = null;
629
+ if (cwd) {
630
+ try {
631
+ const info = getMilestoneInfo(cwd);
632
+ milestone = info.version;
633
+ milestoneName = info.name;
634
+ } catch { /* intentionally empty */ }
635
+ }
636
+
637
+ let totalPhases = totalPhasesRaw ? parseInt(totalPhasesRaw, 10) : null;
638
+ let completedPhases = null;
639
+ let totalPlans = totalPlansRaw ? parseInt(totalPlansRaw, 10) : null;
640
+ let completedPlans = null;
641
+
642
+ if (cwd) {
643
+ try {
644
+ const phasesDir = planningPaths(cwd).phases;
645
+ if (fs.existsSync(phasesDir)) {
646
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
647
+ const phaseDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
648
+ .filter(e => e.isDirectory()).map(e => e.name)
649
+ .filter(isDirInMilestone);
650
+ let diskTotalPlans = 0;
651
+ let diskTotalSummaries = 0;
652
+ let diskCompletedPhases = 0;
653
+
654
+ for (const dir of phaseDirs) {
655
+ const files = fs.readdirSync(path.join(phasesDir, dir));
656
+ const plans = files.filter(f => f.match(/-PLAN\.md$/i)).length;
657
+ const summaries = files.filter(f => f.match(/-SUMMARY\.md$/i)).length;
658
+ diskTotalPlans += plans;
659
+ diskTotalSummaries += summaries;
660
+ if (plans > 0 && summaries >= plans) diskCompletedPhases++;
661
+ }
662
+ totalPhases = isDirInMilestone.phaseCount > 0
663
+ ? Math.max(phaseDirs.length, isDirInMilestone.phaseCount)
664
+ : phaseDirs.length;
665
+ completedPhases = diskCompletedPhases;
666
+ totalPlans = diskTotalPlans;
667
+ completedPlans = diskTotalSummaries;
668
+ }
669
+ } catch { /* intentionally empty */ }
670
+ }
671
+
672
+ let progressPercent = null;
673
+ if (progressRaw) {
674
+ const pctMatch = progressRaw.match(/(\d+)%/);
675
+ if (pctMatch) progressPercent = parseInt(pctMatch[1], 10);
676
+ }
677
+
678
+ // Normalize status to one of: planning, discussing, executing, verifying, paused, completed, unknown
679
+ let normalizedStatus = status || 'unknown';
680
+ const statusLower = (status || '').toLowerCase();
681
+ if (statusLower.includes('paused') || statusLower.includes('stopped') || pausedAt) {
682
+ normalizedStatus = 'paused';
683
+ } else if (statusLower.includes('executing') || statusLower.includes('in progress')) {
684
+ normalizedStatus = 'executing';
685
+ } else if (statusLower.includes('planning') || statusLower.includes('ready to plan')) {
686
+ normalizedStatus = 'planning';
687
+ } else if (statusLower.includes('discussing')) {
688
+ normalizedStatus = 'discussing';
689
+ } else if (statusLower.includes('verif')) {
690
+ normalizedStatus = 'verifying';
691
+ } else if (statusLower.includes('complete') || statusLower.includes('done')) {
692
+ normalizedStatus = 'completed';
693
+ } else if (statusLower.includes('ready to execute')) {
694
+ normalizedStatus = 'executing';
695
+ }
696
+
697
+ const fm = { mindforge_state_version: '1.0' };
698
+
699
+ if (milestone) fm.milestone = milestone;
700
+ if (milestoneName) fm.milestone_name = milestoneName;
701
+ if (currentPhase) fm.current_phase = currentPhase;
702
+ if (currentPhaseName) fm.current_phase_name = currentPhaseName;
703
+ if (currentPlan) fm.current_plan = currentPlan;
704
+ fm.status = normalizedStatus;
705
+ if (stoppedAt) fm.stopped_at = stoppedAt;
706
+ if (pausedAt) fm.paused_at = pausedAt;
707
+ fm.last_updated = new Date().toISOString();
708
+ if (lastActivity) fm.last_activity = lastActivity;
709
+
710
+ const progress = {};
711
+ if (totalPhases !== null) progress.total_phases = totalPhases;
712
+ if (completedPhases !== null) progress.completed_phases = completedPhases;
713
+ if (totalPlans !== null) progress.total_plans = totalPlans;
714
+ if (completedPlans !== null) progress.completed_plans = completedPlans;
715
+ if (progressPercent !== null) progress.percent = progressPercent;
716
+ if (Object.keys(progress).length > 0) fm.progress = progress;
717
+
718
+ return fm;
719
+ }
720
+
721
+ function stripFrontmatter(content) {
722
+ // Strip ALL frontmatter blocks at the start of the file.
723
+ // Handles CRLF line endings and multiple stacked blocks (corruption recovery).
724
+ // Greedy: keeps stripping ---...--- blocks separated by optional whitespace.
725
+ let result = content;
726
+ // eslint-disable-next-line no-constant-condition
727
+ while (true) {
728
+ const stripped = result.replace(/^\s*---\r?\n[\s\S]*?\r?\n---\s*/, '');
729
+ if (stripped === result) break;
730
+ result = stripped;
731
+ }
732
+ return result;
733
+ }
734
+
735
+ function syncStateFrontmatter(content, cwd) {
736
+ // Read existing frontmatter BEFORE stripping — it may contain values
737
+ // that the body no longer has (e.g., Status field removed by an agent).
738
+ const existingFm = extractFrontmatter(content);
739
+ const body = stripFrontmatter(content);
740
+ const derivedFm = buildStateFrontmatter(body, cwd);
741
+
742
+ // Preserve existing frontmatter status when body-derived status is 'unknown'.
743
+ // This prevents a missing Status: field in the body from overwriting a
744
+ // previously valid status (e.g., 'executing' → 'unknown').
745
+ if (derivedFm.status === 'unknown' && existingFm.status && existingFm.status !== 'unknown') {
746
+ derivedFm.status = existingFm.status;
747
+ }
748
+
749
+ const yamlStr = reconstructFrontmatter(derivedFm);
750
+ return `---\n${yamlStr}\n---\n\n${body}`;
751
+ }
752
+
753
+ /**
754
+ * Write STATE.md with synchronized YAML frontmatter.
755
+ * All STATE.md writes should use this instead of raw writeFileSync.
756
+ * Uses a simple lockfile to prevent parallel agents from overwriting
757
+ * each other's changes (race condition with read-modify-write cycle).
758
+ */
759
+ function writeStateMd(statePath, content, cwd) {
760
+ const synced = syncStateFrontmatter(content, cwd);
761
+ const lockPath = statePath + '.lock';
762
+ const maxRetries = 10;
763
+ const retryDelay = 200; // ms
764
+
765
+ // Acquire lock (spin with backoff)
766
+ for (let i = 0; i < maxRetries; i++) {
767
+ try {
768
+ // O_EXCL fails if file already exists — atomic lock
769
+ const fd = fs.openSync(lockPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY);
770
+ fs.writeSync(fd, String(process.pid));
771
+ fs.closeSync(fd);
772
+ break;
773
+ } catch (err) {
774
+ if (err.code === 'EEXIST') {
775
+ // Check for stale lock (> 10s old)
776
+ try {
777
+ const stat = fs.statSync(lockPath);
778
+ if (Date.now() - stat.mtimeMs > 10000) {
779
+ fs.unlinkSync(lockPath);
780
+ continue; // retry immediately after clearing stale lock
781
+ }
782
+ } catch { /* lock was released between check — retry */ }
783
+
784
+ if (i === maxRetries - 1) {
785
+ // Last resort: write anyway rather than losing data
786
+ try { fs.unlinkSync(lockPath); } catch {}
787
+ break;
788
+ }
789
+ // Spin-wait with small jitter
790
+ const jitter = Math.floor(Math.random() * 50);
791
+ const start = Date.now();
792
+ while (Date.now() - start < retryDelay + jitter) { /* busy wait */ }
793
+ continue;
794
+ }
795
+ break; // non-EEXIST error — proceed without lock
796
+ }
797
+ }
798
+
799
+ try {
800
+ fs.writeFileSync(statePath, normalizeMd(synced), 'utf-8');
801
+ } finally {
802
+ try { fs.unlinkSync(lockPath); } catch { /* lock already gone */ }
803
+ }
804
+ }
805
+
806
+ function cmdStateJson(cwd, raw) {
807
+ const statePath = planningPaths(cwd).state;
808
+ if (!fs.existsSync(statePath)) {
809
+ output({ error: 'STATE.md not found' }, raw, 'STATE.md not found');
810
+ return;
811
+ }
812
+
813
+ const content = fs.readFileSync(statePath, 'utf-8');
814
+ const fm = extractFrontmatter(content);
815
+
816
+ if (!fm || Object.keys(fm).length === 0) {
817
+ const body = stripFrontmatter(content);
818
+ const built = buildStateFrontmatter(body, cwd);
819
+ output(built, raw, JSON.stringify(built, null, 2));
820
+ return;
821
+ }
822
+
823
+ output(fm, raw, JSON.stringify(fm, null, 2));
824
+ }
825
+
826
+ /**
827
+ * Update STATE.md when a new phase begins execution.
828
+ * Updates body text fields (Current focus, Status, Last Activity, Current Position)
829
+ * and synchronizes frontmatter via writeStateMd.
830
+ * Fixes: #1102 (plan counts), #1103 (status/last_activity), #1104 (body text).
831
+ */
832
+ function cmdStateBeginPhase(cwd, phaseNumber, phaseName, planCount, raw) {
833
+ const statePath = planningPaths(cwd).state;
834
+ if (!fs.existsSync(statePath)) {
835
+ output({ error: 'STATE.md not found' }, raw);
836
+ return;
837
+ }
838
+
839
+ let content = fs.readFileSync(statePath, 'utf-8');
840
+ const today = new Date().toISOString().split('T')[0];
841
+ const updated = [];
842
+
843
+ // Update Status field
844
+ const statusValue = `Executing Phase ${phaseNumber}`;
845
+ let result = stateReplaceField(content, 'Status', statusValue);
846
+ if (result) { content = result; updated.push('Status'); }
847
+
848
+ // Update Last Activity
849
+ result = stateReplaceField(content, 'Last Activity', today);
850
+ if (result) { content = result; updated.push('Last Activity'); }
851
+
852
+ // Update Last Activity Description if it exists
853
+ const activityDesc = `Phase ${phaseNumber} execution started`;
854
+ result = stateReplaceField(content, 'Last Activity Description', activityDesc);
855
+ if (result) { content = result; updated.push('Last Activity Description'); }
856
+
857
+ // Update Current Phase
858
+ result = stateReplaceField(content, 'Current Phase', String(phaseNumber));
859
+ if (result) { content = result; updated.push('Current Phase'); }
860
+
861
+ // Update Current Phase Name
862
+ if (phaseName) {
863
+ result = stateReplaceField(content, 'Current Phase Name', phaseName);
864
+ if (result) { content = result; updated.push('Current Phase Name'); }
865
+ }
866
+
867
+ // Update Current Plan to 1 (starting from the first plan)
868
+ result = stateReplaceField(content, 'Current Plan', '1');
869
+ if (result) { content = result; updated.push('Current Plan'); }
870
+
871
+ // Update Total Plans in Phase
872
+ if (planCount) {
873
+ result = stateReplaceField(content, 'Total Plans in Phase', String(planCount));
874
+ if (result) { content = result; updated.push('Total Plans in Phase'); }
875
+ }
876
+
877
+ // Update **Current focus:** body text line (#1104)
878
+ const focusLabel = phaseName ? `Phase ${phaseNumber} — ${phaseName}` : `Phase ${phaseNumber}`;
879
+ const focusPattern = /(\*\*Current focus:\*\*\s*).*/i;
880
+ if (focusPattern.test(content)) {
881
+ content = content.replace(focusPattern, (_match, prefix) => `${prefix}${focusLabel}`);
882
+ updated.push('Current focus');
883
+ }
884
+
885
+ // Update ## Current Position section (#1104)
886
+ const positionPattern = /(##\s*Current Position\s*\n)([\s\S]*?)(?=\n##|$)/i;
887
+ const positionMatch = content.match(positionPattern);
888
+ if (positionMatch) {
889
+ const newPosition = `Phase: ${phaseNumber}${phaseName ? ` (${phaseName})` : ''} — EXECUTING\nPlan: 1 of ${planCount || '?'}\n`;
890
+ content = content.replace(positionPattern, (_match, header) => `${header}${newPosition}`);
891
+ updated.push('Current Position');
892
+ }
893
+
894
+ if (updated.length > 0) {
895
+ writeStateMd(statePath, content, cwd);
896
+ }
897
+
898
+ output({ updated, phase: phaseNumber, phase_name: phaseName || null, plan_count: planCount || null }, raw, updated.length > 0 ? 'true' : 'false');
899
+ }
900
+
901
+ /**
902
+ * Write a WAITING.json signal file when MindForge hits a decision point.
903
+ * External watchers (fswatch, polling, orchestrators) can detect this.
904
+ * File is written to .planning/WAITING.json (or .mindforge/WAITING.json if .mindforge exists).
905
+ * Fixes #1034.
906
+ */
907
+ function cmdSignalWaiting(cwd, type, question, options, phase, raw) {
908
+ const mindforgeDir = fs.existsSync(path.join(cwd, '.mindforge')) ? path.join(cwd, '.mindforge') : planningDir(cwd);
909
+ const waitingPath = path.join(mindforgeDir, 'WAITING.json');
910
+
911
+ const signal = {
912
+ status: 'waiting',
913
+ type: type || 'decision_point',
914
+ question: question || null,
915
+ options: options ? options.split('|').map(o => o.trim()) : [],
916
+ since: new Date().toISOString(),
917
+ phase: phase || null,
918
+ };
919
+
920
+ try {
921
+ fs.mkdirSync(mindforgeDir, { recursive: true });
922
+ fs.writeFileSync(waitingPath, JSON.stringify(signal, null, 2), 'utf-8');
923
+ output({ signaled: true, path: waitingPath }, raw, 'true');
924
+ } catch (e) {
925
+ output({ signaled: false, error: e.message }, raw, 'false');
926
+ }
927
+ }
928
+
929
+ /**
930
+ * Remove the WAITING.json signal file when user answers and agent resumes.
931
+ */
932
+ function cmdSignalResume(cwd, raw) {
933
+ const paths = [
934
+ path.join(cwd, '.mindforge', 'WAITING.json'),
935
+ path.join(planningDir(cwd), 'WAITING.json'),
936
+ ];
937
+
938
+ let removed = false;
939
+ for (const p of paths) {
940
+ if (fs.existsSync(p)) {
941
+ try { fs.unlinkSync(p); removed = true; } catch {}
942
+ }
943
+ }
944
+
945
+ output({ resumed: true, removed }, raw, removed ? 'true' : 'false');
946
+ }
947
+
948
+ module.exports = {
949
+ stateExtractField,
950
+ stateReplaceField,
951
+ stateReplaceFieldWithFallback,
952
+ writeStateMd,
953
+ cmdStateLoad,
954
+ cmdStateGet,
955
+ cmdStatePatch,
956
+ cmdStateUpdate,
957
+ cmdStateAdvancePlan,
958
+ cmdStateRecordMetric,
959
+ cmdStateUpdateProgress,
960
+ cmdStateAddDecision,
961
+ cmdStateAddBlocker,
962
+ cmdStateResolveBlocker,
963
+ cmdStateRecordSession,
964
+ cmdStateSnapshot,
965
+ cmdStateJson,
966
+ cmdStateBeginPhase,
967
+ cmdSignalWaiting,
968
+ cmdSignalResume,
969
+ };