@ktpartners/dgs-platform 2.6.2

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 (256) hide show
  1. package/LICENSE +38 -0
  2. package/README.md +851 -0
  3. package/agents/dgs-codebase-cross-analyzer.md +183 -0
  4. package/agents/dgs-codebase-mapper.md +782 -0
  5. package/agents/dgs-codebase-synthesizer.md +156 -0
  6. package/agents/dgs-debugger.md +1256 -0
  7. package/agents/dgs-executor.md +550 -0
  8. package/agents/dgs-integration-checker.md +481 -0
  9. package/agents/dgs-nyquist-auditor.md +178 -0
  10. package/agents/dgs-phase-researcher.md +563 -0
  11. package/agents/dgs-phase-verifier.md +450 -0
  12. package/agents/dgs-plan-checker.md +708 -0
  13. package/agents/dgs-planner.md +1324 -0
  14. package/agents/dgs-project-researcher.md +631 -0
  15. package/agents/dgs-research-synthesizer.md +249 -0
  16. package/agents/dgs-roadmapper.md +652 -0
  17. package/agents/dgs-verifier.md +607 -0
  18. package/bin/install.js +2073 -0
  19. package/commands/dgs/add-doc.md +45 -0
  20. package/commands/dgs/add-idea.md +38 -0
  21. package/commands/dgs/add-phase.md +43 -0
  22. package/commands/dgs/add-repo.md +54 -0
  23. package/commands/dgs/add-tests.md +41 -0
  24. package/commands/dgs/add-todo.md +47 -0
  25. package/commands/dgs/approve-spec.md +38 -0
  26. package/commands/dgs/audit-milestone.md +36 -0
  27. package/commands/dgs/audit-phase.md +37 -0
  28. package/commands/dgs/cancel-job.md +23 -0
  29. package/commands/dgs/capture-principle.md +143 -0
  30. package/commands/dgs/check-todos.md +45 -0
  31. package/commands/dgs/cleanup.md +18 -0
  32. package/commands/dgs/complete-milestone.md +136 -0
  33. package/commands/dgs/complete-project.md +70 -0
  34. package/commands/dgs/consolidate-ideas.md +50 -0
  35. package/commands/dgs/create-milestone-job.md +37 -0
  36. package/commands/dgs/debug.md +164 -0
  37. package/commands/dgs/develop-idea.md +53 -0
  38. package/commands/dgs/discuss-idea.md +41 -0
  39. package/commands/dgs/discuss-phase.md +83 -0
  40. package/commands/dgs/execute-phase.md +41 -0
  41. package/commands/dgs/fast.md +38 -0
  42. package/commands/dgs/find-related-ideas.md +43 -0
  43. package/commands/dgs/health.md +28 -0
  44. package/commands/dgs/help.md +22 -0
  45. package/commands/dgs/import-spec.md +36 -0
  46. package/commands/dgs/init-product.md +28 -0
  47. package/commands/dgs/insert-phase.md +32 -0
  48. package/commands/dgs/join-discord.md +18 -0
  49. package/commands/dgs/list-docs.md +40 -0
  50. package/commands/dgs/list-ideas.md +42 -0
  51. package/commands/dgs/list-jobs.md +22 -0
  52. package/commands/dgs/list-phase-assumptions.md +46 -0
  53. package/commands/dgs/list-projects.md +57 -0
  54. package/commands/dgs/list-specs.md +40 -0
  55. package/commands/dgs/map-codebase.md +92 -0
  56. package/commands/dgs/new-milestone.md +44 -0
  57. package/commands/dgs/new-project.md +42 -0
  58. package/commands/dgs/node-repair.md +26 -0
  59. package/commands/dgs/overlap-check.md +20 -0
  60. package/commands/dgs/pause-work.md +38 -0
  61. package/commands/dgs/plan-milestone-gaps.md +34 -0
  62. package/commands/dgs/plan-phase.md +44 -0
  63. package/commands/dgs/progress.md +24 -0
  64. package/commands/dgs/quick.md +41 -0
  65. package/commands/dgs/reactivate-project.md +70 -0
  66. package/commands/dgs/reapply-patches.md +110 -0
  67. package/commands/dgs/refine-spec.md +38 -0
  68. package/commands/dgs/reject-idea.md +43 -0
  69. package/commands/dgs/remove-doc.md +44 -0
  70. package/commands/dgs/remove-phase.md +31 -0
  71. package/commands/dgs/remove-repo.md +69 -0
  72. package/commands/dgs/research-idea.md +43 -0
  73. package/commands/dgs/research-phase.md +189 -0
  74. package/commands/dgs/restore-idea.md +45 -0
  75. package/commands/dgs/resume-work.md +40 -0
  76. package/commands/dgs/rollback-job.md +24 -0
  77. package/commands/dgs/run-job.md +35 -0
  78. package/commands/dgs/search.md +40 -0
  79. package/commands/dgs/set-profile.md +34 -0
  80. package/commands/dgs/settings.md +38 -0
  81. package/commands/dgs/switch-project.md +58 -0
  82. package/commands/dgs/undo-consolidation.md +42 -0
  83. package/commands/dgs/update-idea.md +44 -0
  84. package/commands/dgs/update.md +37 -0
  85. package/commands/dgs/validate-phase.md +35 -0
  86. package/commands/dgs/verify-work.md +39 -0
  87. package/commands/dgs/write-spec.md +49 -0
  88. package/deliver-great-systems/.planning/phases/09-backend-wiring-and-error-handling/09-01-SUMMARY.md +84 -0
  89. package/deliver-great-systems/.planning/phases/09-backend-wiring-and-error-handling/09-02-SUMMARY.md +86 -0
  90. package/deliver-great-systems/.planning/phases/10-v1-to-v2-migration-flow/10-01-SUMMARY.md +85 -0
  91. package/deliver-great-systems/bin/dgs-tools.cjs +1444 -0
  92. package/deliver-great-systems/bin/lib/auto-test.cjs +1365 -0
  93. package/deliver-great-systems/bin/lib/commands.cjs +570 -0
  94. package/deliver-great-systems/bin/lib/config.cjs +417 -0
  95. package/deliver-great-systems/bin/lib/conflict-agent.cjs +1063 -0
  96. package/deliver-great-systems/bin/lib/conflict-agent.test.cjs +554 -0
  97. package/deliver-great-systems/bin/lib/context.cjs +929 -0
  98. package/deliver-great-systems/bin/lib/context.test.cjs +693 -0
  99. package/deliver-great-systems/bin/lib/core.cjs +744 -0
  100. package/deliver-great-systems/bin/lib/core.test.cjs +822 -0
  101. package/deliver-great-systems/bin/lib/docs.cjs +919 -0
  102. package/deliver-great-systems/bin/lib/docs.test.cjs +211 -0
  103. package/deliver-great-systems/bin/lib/execution.cjs +705 -0
  104. package/deliver-great-systems/bin/lib/execution.test.cjs +1472 -0
  105. package/deliver-great-systems/bin/lib/frontmatter.cjs +324 -0
  106. package/deliver-great-systems/bin/lib/ideas.cjs +1406 -0
  107. package/deliver-great-systems/bin/lib/ideas.test.cjs +1417 -0
  108. package/deliver-great-systems/bin/lib/identity.cjs +125 -0
  109. package/deliver-great-systems/bin/lib/init.cjs +1114 -0
  110. package/deliver-great-systems/bin/lib/init.test.cjs +1271 -0
  111. package/deliver-great-systems/bin/lib/jobs.cjs +2015 -0
  112. package/deliver-great-systems/bin/lib/jobs.test.cjs +2619 -0
  113. package/deliver-great-systems/bin/lib/merge-conflicts.cjs +654 -0
  114. package/deliver-great-systems/bin/lib/merge-conflicts.test.cjs +370 -0
  115. package/deliver-great-systems/bin/lib/migration.cjs +352 -0
  116. package/deliver-great-systems/bin/lib/migration.test.cjs +582 -0
  117. package/deliver-great-systems/bin/lib/milestone.cjs +243 -0
  118. package/deliver-great-systems/bin/lib/overlap.cjs +437 -0
  119. package/deliver-great-systems/bin/lib/overlap.test.cjs +747 -0
  120. package/deliver-great-systems/bin/lib/path-audit.test.cjs +384 -0
  121. package/deliver-great-systems/bin/lib/paths.cjs +144 -0
  122. package/deliver-great-systems/bin/lib/paths.test.cjs +486 -0
  123. package/deliver-great-systems/bin/lib/phase.cjs +910 -0
  124. package/deliver-great-systems/bin/lib/projects.cjs +691 -0
  125. package/deliver-great-systems/bin/lib/projects.test.cjs +871 -0
  126. package/deliver-great-systems/bin/lib/repos.cjs +1432 -0
  127. package/deliver-great-systems/bin/lib/repos.test.cjs +1882 -0
  128. package/deliver-great-systems/bin/lib/roadmap.cjs +305 -0
  129. package/deliver-great-systems/bin/lib/search.cjs +570 -0
  130. package/deliver-great-systems/bin/lib/specs.cjs +1303 -0
  131. package/deliver-great-systems/bin/lib/state.cjs +893 -0
  132. package/deliver-great-systems/bin/lib/template.cjs +228 -0
  133. package/deliver-great-systems/bin/lib/test-helpers.cjs +291 -0
  134. package/deliver-great-systems/bin/lib/verify.cjs +796 -0
  135. package/deliver-great-systems/references/checkpoints.md +776 -0
  136. package/deliver-great-systems/references/conflict-resolution.md +66 -0
  137. package/deliver-great-systems/references/context-tiers.md +166 -0
  138. package/deliver-great-systems/references/continuation-format.md +249 -0
  139. package/deliver-great-systems/references/decimal-phase-calculation.md +67 -0
  140. package/deliver-great-systems/references/git-integration.md +250 -0
  141. package/deliver-great-systems/references/git-planning-commit.md +40 -0
  142. package/deliver-great-systems/references/model-profile-resolution.md +36 -0
  143. package/deliver-great-systems/references/model-profiles.md +95 -0
  144. package/deliver-great-systems/references/phase-argument-parsing.md +61 -0
  145. package/deliver-great-systems/references/planning-config.md +224 -0
  146. package/deliver-great-systems/references/questioning.md +162 -0
  147. package/deliver-great-systems/references/spec-review-loop.md +177 -0
  148. package/deliver-great-systems/references/tdd.md +265 -0
  149. package/deliver-great-systems/references/ui-brand.md +160 -0
  150. package/deliver-great-systems/references/verification-patterns.md +612 -0
  151. package/deliver-great-systems/templates/DEBUG.md +166 -0
  152. package/deliver-great-systems/templates/UAT.md +251 -0
  153. package/deliver-great-systems/templates/VALIDATION.md +95 -0
  154. package/deliver-great-systems/templates/claude-md.md +74 -0
  155. package/deliver-great-systems/templates/codebase/architecture.md +257 -0
  156. package/deliver-great-systems/templates/codebase/concerns.md +312 -0
  157. package/deliver-great-systems/templates/codebase/conventions.md +309 -0
  158. package/deliver-great-systems/templates/codebase/integrations.md +282 -0
  159. package/deliver-great-systems/templates/codebase/stack.md +188 -0
  160. package/deliver-great-systems/templates/codebase/structure.md +287 -0
  161. package/deliver-great-systems/templates/codebase/testing.md +482 -0
  162. package/deliver-great-systems/templates/config.json +38 -0
  163. package/deliver-great-systems/templates/context.md +354 -0
  164. package/deliver-great-systems/templates/continue-here.md +80 -0
  165. package/deliver-great-systems/templates/debug-subagent-prompt.md +93 -0
  166. package/deliver-great-systems/templates/discovery.md +148 -0
  167. package/deliver-great-systems/templates/milestone-archive.md +125 -0
  168. package/deliver-great-systems/templates/milestone.md +117 -0
  169. package/deliver-great-systems/templates/phase-prompt.md +615 -0
  170. package/deliver-great-systems/templates/planner-subagent-prompt.md +119 -0
  171. package/deliver-great-systems/templates/project.md +186 -0
  172. package/deliver-great-systems/templates/requirements.md +233 -0
  173. package/deliver-great-systems/templates/research-project/ARCHITECTURE.md +206 -0
  174. package/deliver-great-systems/templates/research-project/FEATURES.md +149 -0
  175. package/deliver-great-systems/templates/research-project/PITFALLS.md +202 -0
  176. package/deliver-great-systems/templates/research-project/STACK.md +122 -0
  177. package/deliver-great-systems/templates/research-project/SUMMARY.md +172 -0
  178. package/deliver-great-systems/templates/research.md +554 -0
  179. package/deliver-great-systems/templates/retrospective.md +54 -0
  180. package/deliver-great-systems/templates/roadmap.md +204 -0
  181. package/deliver-great-systems/templates/state.md +178 -0
  182. package/deliver-great-systems/templates/summary-complex.md +59 -0
  183. package/deliver-great-systems/templates/summary-minimal.md +41 -0
  184. package/deliver-great-systems/templates/summary-standard.md +48 -0
  185. package/deliver-great-systems/templates/summary.md +253 -0
  186. package/deliver-great-systems/templates/user-setup.md +313 -0
  187. package/deliver-great-systems/templates/verification-report.md +324 -0
  188. package/deliver-great-systems/workflows/add-doc.md +151 -0
  189. package/deliver-great-systems/workflows/add-idea.md +96 -0
  190. package/deliver-great-systems/workflows/add-phase.md +120 -0
  191. package/deliver-great-systems/workflows/add-tests.md +359 -0
  192. package/deliver-great-systems/workflows/add-todo.md +162 -0
  193. package/deliver-great-systems/workflows/approve-spec.md +194 -0
  194. package/deliver-great-systems/workflows/audit-milestone.md +364 -0
  195. package/deliver-great-systems/workflows/audit-phase.md +462 -0
  196. package/deliver-great-systems/workflows/cancel-job.md +108 -0
  197. package/deliver-great-systems/workflows/check-todos.md +181 -0
  198. package/deliver-great-systems/workflows/cleanup.md +247 -0
  199. package/deliver-great-systems/workflows/codereview.md +526 -0
  200. package/deliver-great-systems/workflows/complete-milestone.md +1298 -0
  201. package/deliver-great-systems/workflows/consolidate-ideas.md +365 -0
  202. package/deliver-great-systems/workflows/create-milestone-job.md +177 -0
  203. package/deliver-great-systems/workflows/develop-idea.md +544 -0
  204. package/deliver-great-systems/workflows/diagnose-issues.md +231 -0
  205. package/deliver-great-systems/workflows/discovery-phase.md +301 -0
  206. package/deliver-great-systems/workflows/discuss-idea.md +263 -0
  207. package/deliver-great-systems/workflows/discuss-phase.md +733 -0
  208. package/deliver-great-systems/workflows/execute-phase.md +571 -0
  209. package/deliver-great-systems/workflows/execute-plan.md +592 -0
  210. package/deliver-great-systems/workflows/find-related-ideas.md +271 -0
  211. package/deliver-great-systems/workflows/health.md +173 -0
  212. package/deliver-great-systems/workflows/help.md +997 -0
  213. package/deliver-great-systems/workflows/import-spec.md +381 -0
  214. package/deliver-great-systems/workflows/init-product.md +767 -0
  215. package/deliver-great-systems/workflows/insert-phase.md +138 -0
  216. package/deliver-great-systems/workflows/list-docs.md +119 -0
  217. package/deliver-great-systems/workflows/list-ideas.md +154 -0
  218. package/deliver-great-systems/workflows/list-jobs.md +89 -0
  219. package/deliver-great-systems/workflows/list-phase-assumptions.md +192 -0
  220. package/deliver-great-systems/workflows/list-specs.md +101 -0
  221. package/deliver-great-systems/workflows/map-codebase.md +621 -0
  222. package/deliver-great-systems/workflows/new-milestone.md +591 -0
  223. package/deliver-great-systems/workflows/new-project.md +1113 -0
  224. package/deliver-great-systems/workflows/node-repair.md +94 -0
  225. package/deliver-great-systems/workflows/overlap-check.md +86 -0
  226. package/deliver-great-systems/workflows/pause-work.md +134 -0
  227. package/deliver-great-systems/workflows/plan-milestone-gaps.md +306 -0
  228. package/deliver-great-systems/workflows/plan-phase.md +698 -0
  229. package/deliver-great-systems/workflows/progress.md +386 -0
  230. package/deliver-great-systems/workflows/quick.md +845 -0
  231. package/deliver-great-systems/workflows/refine-spec.md +275 -0
  232. package/deliver-great-systems/workflows/reject-idea.md +109 -0
  233. package/deliver-great-systems/workflows/remove-doc.md +117 -0
  234. package/deliver-great-systems/workflows/remove-phase.md +163 -0
  235. package/deliver-great-systems/workflows/research-idea.md +325 -0
  236. package/deliver-great-systems/workflows/research-phase.md +81 -0
  237. package/deliver-great-systems/workflows/restore-idea.md +101 -0
  238. package/deliver-great-systems/workflows/resume-project.md +311 -0
  239. package/deliver-great-systems/workflows/rollback-job.md +130 -0
  240. package/deliver-great-systems/workflows/run-job.md +498 -0
  241. package/deliver-great-systems/workflows/search.md +130 -0
  242. package/deliver-great-systems/workflows/set-profile.md +83 -0
  243. package/deliver-great-systems/workflows/settings.md +470 -0
  244. package/deliver-great-systems/workflows/transition.md +563 -0
  245. package/deliver-great-systems/workflows/undo-consolidation.md +155 -0
  246. package/deliver-great-systems/workflows/update-idea.md +157 -0
  247. package/deliver-great-systems/workflows/update.md +242 -0
  248. package/deliver-great-systems/workflows/validate-phase.md +177 -0
  249. package/deliver-great-systems/workflows/verify-phase.md +253 -0
  250. package/deliver-great-systems/workflows/verify-work.md +671 -0
  251. package/deliver-great-systems/workflows/write-spec.md +450 -0
  252. package/hooks/dist/dgs-check-update.js +62 -0
  253. package/hooks/dist/dgs-context-monitor.js +141 -0
  254. package/hooks/dist/dgs-statusline.js +115 -0
  255. package/package.json +60 -0
  256. package/scripts/build-hooks.js +43 -0
@@ -0,0 +1,893 @@
1
+ /**
2
+ * State — STATE.md operations and progression engine
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { loadConfig, getMilestoneInfo, output, error, getProjectRoot } = require('./core.cjs');
8
+ const { extractFrontmatter, reconstructFrontmatter } = require('./frontmatter.cjs');
9
+ const { getPlanningRoot } = require('./paths.cjs');
10
+
11
+ // Escape special regex characters in a string
12
+ function escapeRegex(value) {
13
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
14
+ }
15
+
16
+ // Shared helper: extract a field value from STATE.md content.
17
+ // Supports both **Field:** bold AND plain Field: format.
18
+ function stateExtractField(content, fieldName) {
19
+ const escaped = escapeRegex(fieldName);
20
+ const boldPattern = new RegExp(`\\*\\*${escaped}:\\*\\*\\s*(.+)`, 'i');
21
+ const boldMatch = content.match(boldPattern);
22
+ if (boldMatch) return boldMatch[1].trim();
23
+ const plainPattern = new RegExp(`^${escaped}:\\s*(.+)`, 'im');
24
+ const plainMatch = content.match(plainPattern);
25
+ return plainMatch ? plainMatch[1].trim() : null;
26
+ }
27
+
28
+ function resolveStatePath(cwd) {
29
+ let projectRoot;
30
+ try {
31
+ projectRoot = getProjectRoot(cwd);
32
+ } catch {
33
+ projectRoot = path.relative(cwd, getPlanningRoot(cwd)) || '.';
34
+ }
35
+ return path.join(cwd, projectRoot, 'STATE.md');
36
+ }
37
+
38
+ function cmdStateLoad(cwd, raw) {
39
+ const config = loadConfig(cwd);
40
+ let projectRoot;
41
+ try {
42
+ projectRoot = getProjectRoot(cwd);
43
+ } catch {
44
+ projectRoot = path.relative(cwd, getPlanningRoot(cwd)) || '.';
45
+ }
46
+ const projectDir = path.join(cwd, projectRoot);
47
+ const productDir = getPlanningRoot(cwd);
48
+
49
+ let stateRaw = '';
50
+ try {
51
+ stateRaw = fs.readFileSync(path.join(projectDir, 'STATE.md'), 'utf-8');
52
+ } catch {}
53
+
54
+ const configExists = fs.existsSync(path.join(productDir, 'config.json'));
55
+ const roadmapExists = fs.existsSync(path.join(projectDir, 'ROADMAP.md'));
56
+ const stateExists = stateRaw.length > 0;
57
+
58
+ const result = {
59
+ config,
60
+ state_raw: stateRaw,
61
+ state_exists: stateExists,
62
+ roadmap_exists: roadmapExists,
63
+ config_exists: configExists,
64
+ };
65
+
66
+ // For --raw, output a condensed key=value format
67
+ if (raw) {
68
+ const c = config;
69
+ const lines = [
70
+ `model_profile=${c.model_profile}`,
71
+ `commit_docs=${c.commit_docs}`,
72
+ `branching_strategy=${c.branching_strategy}`,
73
+ `phase_branch_template=${c.phase_branch_template}`,
74
+ `milestone_branch_template=${c.milestone_branch_template}`,
75
+ `base_branch=${c.base_branch}`,
76
+ `parallelization=${c.parallelization}`,
77
+ `research=${c.research}`,
78
+ `plan_checker=${c.plan_checker}`,
79
+ `verifier=${c.verifier}`,
80
+ `config_exists=${configExists}`,
81
+ `roadmap_exists=${roadmapExists}`,
82
+ `state_exists=${stateExists}`,
83
+ ];
84
+ process.stdout.write(lines.join('\n'));
85
+ process.exit(0);
86
+ }
87
+
88
+ output(result);
89
+ }
90
+
91
+ function cmdStateGet(cwd, section, raw) {
92
+ const statePath = resolveStatePath(cwd);
93
+ try {
94
+ const content = fs.readFileSync(statePath, 'utf-8');
95
+
96
+ if (!section) {
97
+ output({ content }, raw, content);
98
+ return;
99
+ }
100
+
101
+ // Try to find markdown section or field
102
+ const fieldEscaped = section.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
103
+
104
+ // Check for **field:** value (bold format)
105
+ const boldPattern = new RegExp(`\\*\\*${fieldEscaped}:\\*\\*\\s*(.*)`, 'i');
106
+ const boldMatch = content.match(boldPattern);
107
+ if (boldMatch) {
108
+ output({ [section]: boldMatch[1].trim() }, raw, boldMatch[1].trim());
109
+ return;
110
+ }
111
+
112
+ // Check for field: value (plain format)
113
+ const plainPattern = new RegExp(`^${fieldEscaped}:\\s*(.*)`, 'im');
114
+ const plainMatch = content.match(plainPattern);
115
+ if (plainMatch) {
116
+ output({ [section]: plainMatch[1].trim() }, raw, plainMatch[1].trim());
117
+ return;
118
+ }
119
+
120
+ // Check for ## Section
121
+ const sectionPattern = new RegExp(`##\\s*${fieldEscaped}\\s*\n([\\s\\S]*?)(?=\\n##|$)`, 'i');
122
+ const sectionMatch = content.match(sectionPattern);
123
+ if (sectionMatch) {
124
+ output({ [section]: sectionMatch[1].trim() }, raw, sectionMatch[1].trim());
125
+ return;
126
+ }
127
+
128
+ output({ error: `Section or field "${section}" not found` }, raw, '');
129
+ } catch {
130
+ error('STATE.md not found');
131
+ }
132
+ }
133
+
134
+ function readTextArgOrFile(cwd, value, filePath, label) {
135
+ if (!filePath) return value;
136
+
137
+ const resolvedPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
138
+ try {
139
+ return fs.readFileSync(resolvedPath, 'utf-8').trimEnd();
140
+ } catch {
141
+ throw new Error(`${label} file not found: ${filePath}`);
142
+ }
143
+ }
144
+
145
+ function cmdStatePatch(cwd, patches, raw) {
146
+ const statePath = resolveStatePath(cwd);
147
+ try {
148
+ let content = fs.readFileSync(statePath, 'utf-8');
149
+ const results = { updated: [], failed: [] };
150
+
151
+ for (const [field, value] of Object.entries(patches)) {
152
+ const fieldEscaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
153
+ // Try **Field:** bold format first, then plain Field: format
154
+ const boldPattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
155
+ const plainPattern = new RegExp(`(^${fieldEscaped}:\\s*)(.*)`, 'im');
156
+
157
+ if (boldPattern.test(content)) {
158
+ content = content.replace(boldPattern, (_match, prefix) => `${prefix}${value}`);
159
+ results.updated.push(field);
160
+ } else if (plainPattern.test(content)) {
161
+ content = content.replace(plainPattern, (_match, prefix) => `${prefix}${value}`);
162
+ results.updated.push(field);
163
+ } else {
164
+ results.failed.push(field);
165
+ }
166
+ }
167
+
168
+ if (results.updated.length > 0) {
169
+ writeStateMd(statePath, content, cwd);
170
+ }
171
+
172
+ output(results, raw, results.updated.length > 0 ? 'true' : 'false');
173
+ } catch {
174
+ error('STATE.md not found');
175
+ }
176
+ }
177
+
178
+ function cmdStateUpdate(cwd, field, value) {
179
+ if (!field || value === undefined) {
180
+ error('field and value required for state update');
181
+ }
182
+
183
+ const statePath = resolveStatePath(cwd);
184
+ try {
185
+ let content = fs.readFileSync(statePath, 'utf-8');
186
+ const fieldEscaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
187
+ // Try **Field:** bold format first, then plain Field: format
188
+ const boldPattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
189
+ const plainPattern = new RegExp(`(^${fieldEscaped}:\\s*)(.*)`, 'im');
190
+ if (boldPattern.test(content)) {
191
+ content = content.replace(boldPattern, (_match, prefix) => `${prefix}${value}`);
192
+ writeStateMd(statePath, content, cwd);
193
+ output({ updated: true });
194
+ } else if (plainPattern.test(content)) {
195
+ content = content.replace(plainPattern, (_match, prefix) => `${prefix}${value}`);
196
+ writeStateMd(statePath, content, cwd);
197
+ output({ updated: true });
198
+ } else {
199
+ output({ updated: false, reason: `Field "${field}" not found in STATE.md` });
200
+ }
201
+ } catch {
202
+ output({ updated: false, reason: 'STATE.md not found' });
203
+ }
204
+ }
205
+
206
+ // ─── State Progression Engine ────────────────────────────────────────────────
207
+
208
+ function stateReplaceField(content, fieldName, newValue) {
209
+ const escaped = fieldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
210
+ // Try **Field:** bold format first, then plain Field: format
211
+ const boldPattern = new RegExp(`(\\*\\*${escaped}:\\*\\*\\s*)(.*)`, 'i');
212
+ if (boldPattern.test(content)) {
213
+ return content.replace(boldPattern, (_match, prefix) => `${prefix}${newValue}`);
214
+ }
215
+ const plainPattern = new RegExp(`(^${escaped}:\\s*)(.*)`, 'im');
216
+ if (plainPattern.test(content)) {
217
+ return content.replace(plainPattern, (_match, prefix) => `${prefix}${newValue}`);
218
+ }
219
+ return null;
220
+ }
221
+
222
+ function cmdStateAdvancePlan(cwd, raw) {
223
+ const statePath = resolveStatePath(cwd);
224
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
225
+
226
+ let content = fs.readFileSync(statePath, 'utf-8');
227
+ const currentPlan = parseInt(stateExtractField(content, 'Current Plan'), 10);
228
+ const totalPlans = parseInt(stateExtractField(content, 'Total Plans in Phase'), 10);
229
+ const today = new Date().toISOString().split('T')[0];
230
+
231
+ if (isNaN(currentPlan) || isNaN(totalPlans)) {
232
+ output({ error: 'Cannot parse Current Plan or Total Plans in Phase from STATE.md' }, raw);
233
+ return;
234
+ }
235
+
236
+ if (currentPlan >= totalPlans) {
237
+ content = stateReplaceField(content, 'Status', 'Phase complete — ready for verification') || content;
238
+ content = stateReplaceField(content, 'Last Activity', today) || content;
239
+ writeStateMd(statePath, content, cwd);
240
+ output({ advanced: false, reason: 'last_plan', current_plan: currentPlan, total_plans: totalPlans, status: 'ready_for_verification' }, raw, 'false');
241
+ } else {
242
+ const newPlan = currentPlan + 1;
243
+ content = stateReplaceField(content, 'Current Plan', String(newPlan)) || content;
244
+ content = stateReplaceField(content, 'Status', 'Ready to execute') || content;
245
+ content = stateReplaceField(content, 'Last Activity', today) || content;
246
+ writeStateMd(statePath, content, cwd);
247
+ output({ advanced: true, previous_plan: currentPlan, current_plan: newPlan, total_plans: totalPlans }, raw, 'true');
248
+ }
249
+ }
250
+
251
+ function cmdStateRecordMetric(cwd, options, raw) {
252
+ const statePath = resolveStatePath(cwd);
253
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
254
+
255
+ let content = fs.readFileSync(statePath, 'utf-8');
256
+ const { phase, plan, duration, tasks, files } = options;
257
+
258
+ if (!phase || !plan || !duration) {
259
+ output({ error: 'phase, plan, and duration required' }, raw);
260
+ return;
261
+ }
262
+
263
+ // Find Performance Metrics section and its table
264
+ const metricsPattern = /(##\s*Performance Metrics[\s\S]*?\n\|[^\n]+\n\|[-|\s]+\n)([\s\S]*?)(?=\n##|\n$|$)/i;
265
+ const metricsMatch = content.match(metricsPattern);
266
+
267
+ if (metricsMatch) {
268
+ let tableBody = metricsMatch[2].trimEnd();
269
+ const newRow = `| Phase ${phase} P${plan} | ${duration} | ${tasks || '-'} tasks | ${files || '-'} files |`;
270
+
271
+ if (tableBody.trim() === '' || tableBody.includes('None yet')) {
272
+ tableBody = newRow;
273
+ } else {
274
+ tableBody = tableBody + '\n' + newRow;
275
+ }
276
+
277
+ content = content.replace(metricsPattern, (_match, header) => `${header}${tableBody}\n`);
278
+ writeStateMd(statePath, content, cwd);
279
+ output({ recorded: true, phase, plan, duration }, raw, 'true');
280
+ } else {
281
+ output({ recorded: false, reason: 'Performance Metrics section not found in STATE.md' }, raw, 'false');
282
+ }
283
+ }
284
+
285
+ function cmdStateUpdateProgress(cwd, raw) {
286
+ let projectRoot;
287
+ try { projectRoot = getProjectRoot(cwd); } catch { projectRoot = path.relative(cwd, getPlanningRoot(cwd)) || '.'; }
288
+ const statePath = path.join(cwd, projectRoot, 'STATE.md');
289
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
290
+
291
+ let content = fs.readFileSync(statePath, 'utf-8');
292
+
293
+ // Count summaries across all phases
294
+ const phasesDir = path.join(cwd, projectRoot, 'phases');
295
+ let totalPlans = 0;
296
+ let totalSummaries = 0;
297
+
298
+ if (fs.existsSync(phasesDir)) {
299
+ const phaseDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
300
+ .filter(e => e.isDirectory()).map(e => e.name);
301
+ for (const dir of phaseDirs) {
302
+ const files = fs.readdirSync(path.join(phasesDir, dir));
303
+ totalPlans += files.filter(f => f.match(/-PLAN\.md$/i)).length;
304
+ totalSummaries += files.filter(f => f.match(/-SUMMARY\.md$/i)).length;
305
+ }
306
+ }
307
+
308
+ const percent = totalPlans > 0 ? Math.min(100, Math.round(totalSummaries / totalPlans * 100)) : 0;
309
+ const barWidth = 10;
310
+ const filled = Math.round(percent / 100 * barWidth);
311
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
312
+ const progressStr = `[${bar}] ${percent}%`;
313
+
314
+ // Try **Progress:** bold format first, then plain Progress: format
315
+ const boldProgressPattern = /(\*\*Progress:\*\*\s*).*/i;
316
+ const plainProgressPattern = /^(Progress:\s*).*/im;
317
+ if (boldProgressPattern.test(content)) {
318
+ content = content.replace(boldProgressPattern, (_match, prefix) => `${prefix}${progressStr}`);
319
+ writeStateMd(statePath, content, cwd);
320
+ output({ updated: true, percent, completed: totalSummaries, total: totalPlans, bar: progressStr }, raw, progressStr);
321
+ } else if (plainProgressPattern.test(content)) {
322
+ content = content.replace(plainProgressPattern, (_match, prefix) => `${prefix}${progressStr}`);
323
+ writeStateMd(statePath, content, cwd);
324
+ output({ updated: true, percent, completed: totalSummaries, total: totalPlans, bar: progressStr }, raw, progressStr);
325
+ } else {
326
+ output({ updated: false, reason: 'Progress field not found in STATE.md' }, raw, 'false');
327
+ }
328
+ }
329
+
330
+ function cmdStateAddDecision(cwd, options, raw) {
331
+ const statePath = resolveStatePath(cwd);
332
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
333
+
334
+ const { phase, summary, summary_file, rationale, rationale_file } = options;
335
+ let summaryText = null;
336
+ let rationaleText = '';
337
+
338
+ try {
339
+ summaryText = readTextArgOrFile(cwd, summary, summary_file, 'summary');
340
+ rationaleText = readTextArgOrFile(cwd, rationale || '', rationale_file, 'rationale');
341
+ } catch (err) {
342
+ output({ added: false, reason: err.message }, raw, 'false');
343
+ return;
344
+ }
345
+
346
+ if (!summaryText) { output({ error: 'summary required' }, raw); return; }
347
+
348
+ let content = fs.readFileSync(statePath, 'utf-8');
349
+ const entry = `- [Phase ${phase || '?'}]: ${summaryText}${rationaleText ? ` — ${rationaleText}` : ''}`;
350
+
351
+ // Find Decisions section (various heading patterns)
352
+ const sectionPattern = /(###?\s*(?:Decisions|Decisions Made|Accumulated.*Decisions)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
353
+ const match = content.match(sectionPattern);
354
+
355
+ if (match) {
356
+ let sectionBody = match[2];
357
+ // Remove placeholders
358
+ sectionBody = sectionBody.replace(/None yet\.?\s*\n?/gi, '').replace(/No decisions yet\.?\s*\n?/gi, '');
359
+ sectionBody = sectionBody.trimEnd() + '\n' + entry + '\n';
360
+ content = content.replace(sectionPattern, (_match, header) => `${header}${sectionBody}`);
361
+ writeStateMd(statePath, content, cwd);
362
+ output({ added: true, decision: entry }, raw, 'true');
363
+ } else {
364
+ output({ added: false, reason: 'Decisions section not found in STATE.md' }, raw, 'false');
365
+ }
366
+ }
367
+
368
+ function cmdStateAddBlocker(cwd, text, raw) {
369
+ const statePath = resolveStatePath(cwd);
370
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
371
+ const blockerOptions = typeof text === 'object' && text !== null ? text : { text };
372
+ let blockerText = null;
373
+
374
+ try {
375
+ blockerText = readTextArgOrFile(cwd, blockerOptions.text, blockerOptions.text_file, 'blocker');
376
+ } catch (err) {
377
+ output({ added: false, reason: err.message }, raw, 'false');
378
+ return;
379
+ }
380
+
381
+ if (!blockerText) { output({ error: 'text required' }, raw); return; }
382
+
383
+ let content = fs.readFileSync(statePath, 'utf-8');
384
+ const entry = `- ${blockerText}`;
385
+
386
+ const sectionPattern = /(###?\s*(?:Blockers|Blockers\/Concerns|Concerns)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
387
+ const match = content.match(sectionPattern);
388
+
389
+ if (match) {
390
+ let sectionBody = match[2];
391
+ sectionBody = sectionBody.replace(/None\.?\s*\n?/gi, '').replace(/None yet\.?\s*\n?/gi, '');
392
+ sectionBody = sectionBody.trimEnd() + '\n' + entry + '\n';
393
+ content = content.replace(sectionPattern, (_match, header) => `${header}${sectionBody}`);
394
+ writeStateMd(statePath, content, cwd);
395
+ output({ added: true, blocker: blockerText }, raw, 'true');
396
+ } else {
397
+ output({ added: false, reason: 'Blockers section not found in STATE.md' }, raw, 'false');
398
+ }
399
+ }
400
+
401
+ function cmdStateResolveBlocker(cwd, text, raw) {
402
+ const statePath = resolveStatePath(cwd);
403
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
404
+ if (!text) { output({ error: 'text required' }, raw); return; }
405
+
406
+ let content = fs.readFileSync(statePath, 'utf-8');
407
+
408
+ const sectionPattern = /(###?\s*(?:Blockers|Blockers\/Concerns|Concerns)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
409
+ const match = content.match(sectionPattern);
410
+
411
+ if (match) {
412
+ const sectionBody = match[2];
413
+ const lines = sectionBody.split('\n');
414
+ const filtered = lines.filter(line => {
415
+ if (!line.startsWith('- ')) return true;
416
+ return !line.toLowerCase().includes(text.toLowerCase());
417
+ });
418
+
419
+ let newBody = filtered.join('\n');
420
+ // If section is now empty, add placeholder
421
+ if (!newBody.trim() || !newBody.includes('- ')) {
422
+ newBody = 'None\n';
423
+ }
424
+
425
+ content = content.replace(sectionPattern, (_match, header) => `${header}${newBody}`);
426
+ writeStateMd(statePath, content, cwd);
427
+ output({ resolved: true, blocker: text }, raw, 'true');
428
+ } else {
429
+ output({ resolved: false, reason: 'Blockers section not found in STATE.md' }, raw, 'false');
430
+ }
431
+ }
432
+
433
+ function cmdStateRecordSession(cwd, options, raw) {
434
+ const statePath = resolveStatePath(cwd);
435
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
436
+
437
+ let content = fs.readFileSync(statePath, 'utf-8');
438
+ const now = new Date().toISOString();
439
+ const updated = [];
440
+
441
+ // Update Last session / Last Date
442
+ let result = stateReplaceField(content, 'Last session', now);
443
+ if (result) { content = result; updated.push('Last session'); }
444
+ result = stateReplaceField(content, 'Last Date', now);
445
+ if (result) { content = result; updated.push('Last Date'); }
446
+
447
+ // Update Stopped at
448
+ if (options.stopped_at) {
449
+ result = stateReplaceField(content, 'Stopped At', options.stopped_at);
450
+ if (!result) result = stateReplaceField(content, 'Stopped at', options.stopped_at);
451
+ if (result) { content = result; updated.push('Stopped At'); }
452
+ }
453
+
454
+ // Update Resume file
455
+ const resumeFile = options.resume_file || 'None';
456
+ result = stateReplaceField(content, 'Resume File', resumeFile);
457
+ if (!result) result = stateReplaceField(content, 'Resume file', resumeFile);
458
+ if (result) { content = result; updated.push('Resume File'); }
459
+
460
+ if (updated.length > 0) {
461
+ writeStateMd(statePath, content, cwd);
462
+ output({ recorded: true, updated }, raw, 'true');
463
+ } else {
464
+ output({ recorded: false, reason: 'No session fields found in STATE.md' }, raw, 'false');
465
+ }
466
+ }
467
+
468
+ function cmdStateSnapshot(cwd, raw) {
469
+ const statePath = resolveStatePath(cwd);
470
+
471
+ if (!fs.existsSync(statePath)) {
472
+ output({ error: 'STATE.md not found' }, raw);
473
+ return;
474
+ }
475
+
476
+ const content = fs.readFileSync(statePath, 'utf-8');
477
+
478
+ // Extract basic fields
479
+ const currentPhase = stateExtractField(content, 'Current Phase');
480
+ const currentPhaseName = stateExtractField(content, 'Current Phase Name');
481
+ const totalPhasesRaw = stateExtractField(content, 'Total Phases');
482
+ const currentPlan = stateExtractField(content, 'Current Plan');
483
+ const totalPlansRaw = stateExtractField(content, 'Total Plans in Phase');
484
+ const status = stateExtractField(content, 'Status');
485
+ const progressRaw = stateExtractField(content, 'Progress');
486
+ const lastActivity = stateExtractField(content, 'Last Activity');
487
+ const lastActivityDesc = stateExtractField(content, 'Last Activity Description');
488
+ const pausedAt = stateExtractField(content, 'Paused At');
489
+
490
+ // Parse numeric fields
491
+ const totalPhases = totalPhasesRaw ? parseInt(totalPhasesRaw, 10) : null;
492
+ const totalPlansInPhase = totalPlansRaw ? parseInt(totalPlansRaw, 10) : null;
493
+ const progressPercent = progressRaw ? parseInt(progressRaw.replace('%', ''), 10) : null;
494
+
495
+ // Extract decisions table
496
+ const decisions = [];
497
+ const decisionsMatch = content.match(/##\s*Decisions Made[\s\S]*?\n\|[^\n]+\n\|[-|\s]+\n([\s\S]*?)(?=\n##|\n$|$)/i);
498
+ if (decisionsMatch) {
499
+ const tableBody = decisionsMatch[1];
500
+ const rows = tableBody.trim().split('\n').filter(r => r.includes('|'));
501
+ for (const row of rows) {
502
+ const cells = row.split('|').map(c => c.trim()).filter(Boolean);
503
+ if (cells.length >= 3) {
504
+ decisions.push({
505
+ phase: cells[0],
506
+ summary: cells[1],
507
+ rationale: cells[2],
508
+ });
509
+ }
510
+ }
511
+ }
512
+
513
+ // Extract blockers list
514
+ const blockers = [];
515
+ const blockersMatch = content.match(/##\s*Blockers\s*\n([\s\S]*?)(?=\n##|$)/i);
516
+ if (blockersMatch) {
517
+ const blockersSection = blockersMatch[1];
518
+ const items = blockersSection.match(/^-\s+(.+)$/gm) || [];
519
+ for (const item of items) {
520
+ blockers.push(item.replace(/^-\s+/, '').trim());
521
+ }
522
+ }
523
+
524
+ // Extract session info
525
+ const session = {
526
+ last_date: null,
527
+ stopped_at: null,
528
+ resume_file: null,
529
+ };
530
+
531
+ const sessionMatch = content.match(/##\s*Session\s*\n([\s\S]*?)(?=\n##|$)/i);
532
+ if (sessionMatch) {
533
+ const sessionSection = sessionMatch[1];
534
+ const lastDateMatch = sessionSection.match(/\*\*Last Date:\*\*\s*(.+)/i)
535
+ || sessionSection.match(/^Last Date:\s*(.+)/im);
536
+ const stoppedAtMatch = sessionSection.match(/\*\*Stopped At:\*\*\s*(.+)/i)
537
+ || sessionSection.match(/^Stopped At:\s*(.+)/im);
538
+ const resumeFileMatch = sessionSection.match(/\*\*Resume File:\*\*\s*(.+)/i)
539
+ || sessionSection.match(/^Resume File:\s*(.+)/im);
540
+
541
+ if (lastDateMatch) session.last_date = lastDateMatch[1].trim();
542
+ if (stoppedAtMatch) session.stopped_at = stoppedAtMatch[1].trim();
543
+ if (resumeFileMatch) session.resume_file = resumeFileMatch[1].trim();
544
+ }
545
+
546
+ const result = {
547
+ current_phase: currentPhase,
548
+ current_phase_name: currentPhaseName,
549
+ total_phases: totalPhases,
550
+ current_plan: currentPlan,
551
+ total_plans_in_phase: totalPlansInPhase,
552
+ status,
553
+ progress_percent: progressPercent,
554
+ last_activity: lastActivity,
555
+ last_activity_desc: lastActivityDesc,
556
+ decisions,
557
+ blockers,
558
+ paused_at: pausedAt,
559
+ session,
560
+ };
561
+
562
+ output(result, raw);
563
+ }
564
+
565
+ // ─── State Frontmatter Sync ──────────────────────────────────────────────────
566
+
567
+ /**
568
+ * Build a milestone phase filter from ROADMAP.md.
569
+ * Returns a function that checks if a phase directory belongs to the current milestone.
570
+ */
571
+ function getMilestonePhaseFilter(cwd) {
572
+ const milestonePhaseNums = new Set();
573
+ try {
574
+ const roadmap = fs.readFileSync(path.join(cwd, '.planning', 'ROADMAP.md'), 'utf-8');
575
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:/gi;
576
+ let m;
577
+ while ((m = phasePattern.exec(roadmap)) !== null) {
578
+ milestonePhaseNums.add(m[1]);
579
+ }
580
+ } catch {}
581
+
582
+ if (milestonePhaseNums.size === 0) {
583
+ const passAll = () => true;
584
+ passAll.phaseCount = 0;
585
+ return passAll;
586
+ }
587
+
588
+ const normalized = new Set(
589
+ [...milestonePhaseNums].map(n => (n.replace(/^0+/, '') || '0').toLowerCase())
590
+ );
591
+
592
+ function isDirInMilestone(dirName) {
593
+ const m = dirName.match(/^0*(\d+[A-Za-z]?(?:\.\d+)*)/);
594
+ if (!m) return false;
595
+ return normalized.has(m[1].toLowerCase());
596
+ }
597
+ isDirInMilestone.phaseCount = milestonePhaseNums.size;
598
+ return isDirInMilestone;
599
+ }
600
+
601
+ /**
602
+ * Extract machine-readable fields from STATE.md markdown body and build
603
+ * a YAML frontmatter object. Allows hooks and scripts to read state
604
+ * reliably via `state json` instead of fragile regex parsing.
605
+ */
606
+ function buildStateFrontmatter(bodyContent, cwd) {
607
+ const currentPhase = stateExtractField(bodyContent, 'Current Phase');
608
+ const currentPhaseName = stateExtractField(bodyContent, 'Current Phase Name');
609
+ const currentPlan = stateExtractField(bodyContent, 'Current Plan');
610
+ const totalPhasesRaw = stateExtractField(bodyContent, 'Total Phases');
611
+ const totalPlansRaw = stateExtractField(bodyContent, 'Total Plans in Phase');
612
+ const status = stateExtractField(bodyContent, 'Status');
613
+ const progressRaw = stateExtractField(bodyContent, 'Progress');
614
+ const lastActivity = stateExtractField(bodyContent, 'Last Activity');
615
+ const stoppedAt = stateExtractField(bodyContent, 'Stopped At') || stateExtractField(bodyContent, 'Stopped at');
616
+ const pausedAt = stateExtractField(bodyContent, 'Paused At');
617
+
618
+ let milestone = null;
619
+ let milestoneName = null;
620
+ if (cwd) {
621
+ try {
622
+ const info = getMilestoneInfo(cwd);
623
+ milestone = info.version;
624
+ milestoneName = info.name;
625
+ } catch {}
626
+ }
627
+
628
+ let totalPhases = totalPhasesRaw ? parseInt(totalPhasesRaw, 10) : null;
629
+ let completedPhases = null;
630
+ let totalPlans = totalPlansRaw ? parseInt(totalPlansRaw, 10) : null;
631
+ let completedPlans = null;
632
+
633
+ if (cwd) {
634
+ try {
635
+ const phasesDir = path.join(cwd, '.planning', 'phases');
636
+ if (fs.existsSync(phasesDir)) {
637
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
638
+ const phaseDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
639
+ .filter(e => e.isDirectory()).map(e => e.name)
640
+ .filter(isDirInMilestone);
641
+ let diskTotalPlans = 0;
642
+ let diskTotalSummaries = 0;
643
+ let diskCompletedPhases = 0;
644
+
645
+ for (const dir of phaseDirs) {
646
+ const files = fs.readdirSync(path.join(phasesDir, dir));
647
+ const plans = files.filter(f => f.match(/-PLAN\.md$/i)).length;
648
+ const summaries = files.filter(f => f.match(/-SUMMARY\.md$/i)).length;
649
+ diskTotalPlans += plans;
650
+ diskTotalSummaries += summaries;
651
+ if (plans > 0 && summaries >= plans) diskCompletedPhases++;
652
+ }
653
+ totalPhases = isDirInMilestone.phaseCount > 0
654
+ ? Math.max(phaseDirs.length, isDirInMilestone.phaseCount)
655
+ : phaseDirs.length;
656
+ completedPhases = diskCompletedPhases;
657
+ totalPlans = diskTotalPlans;
658
+ completedPlans = diskTotalSummaries;
659
+ }
660
+ } catch {}
661
+ }
662
+
663
+ let progressPercent = null;
664
+ if (progressRaw) {
665
+ const pctMatch = progressRaw.match(/(\d+)%/);
666
+ if (pctMatch) progressPercent = parseInt(pctMatch[1], 10);
667
+ }
668
+
669
+ // Normalize status to one of: planning, discussing, executing, verifying, paused, completed, unknown
670
+ let normalizedStatus = status || 'unknown';
671
+ const statusLower = (status || '').toLowerCase();
672
+ if (statusLower.includes('paused') || statusLower.includes('stopped') || pausedAt) {
673
+ normalizedStatus = 'paused';
674
+ } else if (statusLower.includes('executing') || statusLower.includes('in progress')) {
675
+ normalizedStatus = 'executing';
676
+ } else if (statusLower.includes('planning') || statusLower.includes('ready to plan')) {
677
+ normalizedStatus = 'planning';
678
+ } else if (statusLower.includes('discussing')) {
679
+ normalizedStatus = 'discussing';
680
+ } else if (statusLower.includes('verif')) {
681
+ normalizedStatus = 'verifying';
682
+ } else if (statusLower.includes('complete') || statusLower.includes('done')) {
683
+ normalizedStatus = 'completed';
684
+ } else if (statusLower.includes('ready to execute')) {
685
+ normalizedStatus = 'executing';
686
+ }
687
+
688
+ const fm = { dgs_state_version: '1.0' };
689
+
690
+ if (milestone) fm.milestone = milestone;
691
+ if (milestoneName) fm.milestone_name = milestoneName;
692
+ if (currentPhase) fm.current_phase = currentPhase;
693
+ if (currentPhaseName) fm.current_phase_name = currentPhaseName;
694
+ if (currentPlan) fm.current_plan = currentPlan;
695
+ fm.status = normalizedStatus;
696
+ if (stoppedAt) fm.stopped_at = stoppedAt;
697
+ if (pausedAt) fm.paused_at = pausedAt;
698
+ fm.last_updated = new Date().toISOString();
699
+ if (lastActivity) fm.last_activity = lastActivity;
700
+
701
+ const progress = {};
702
+ if (totalPhases !== null) progress.total_phases = totalPhases;
703
+ if (completedPhases !== null) progress.completed_phases = completedPhases;
704
+ if (totalPlans !== null) progress.total_plans = totalPlans;
705
+ if (completedPlans !== null) progress.completed_plans = completedPlans;
706
+ if (progressPercent !== null) progress.percent = progressPercent;
707
+ if (Object.keys(progress).length > 0) fm.progress = progress;
708
+
709
+ return fm;
710
+ }
711
+
712
+ function stripFrontmatter(content) {
713
+ return content.replace(/^---\n[\s\S]*?\n---\n*/, '');
714
+ }
715
+
716
+ function syncStateFrontmatter(content, cwd) {
717
+ const body = stripFrontmatter(content);
718
+ const fm = buildStateFrontmatter(body, cwd);
719
+ const yamlStr = reconstructFrontmatter(fm);
720
+ return `---\n${yamlStr}\n---\n\n${body}`;
721
+ }
722
+
723
+ /**
724
+ * Write STATE.md with synchronized YAML frontmatter.
725
+ * All STATE.md writes should use this instead of raw writeFileSync.
726
+ */
727
+ function writeStateMd(statePath, content, cwd) {
728
+ const synced = syncStateFrontmatter(content, cwd);
729
+ fs.writeFileSync(statePath, synced, 'utf-8');
730
+ }
731
+
732
+ function cmdStateJson(cwd, raw) {
733
+ const statePath = resolveStatePath(cwd);
734
+ if (!fs.existsSync(statePath)) {
735
+ output({ error: 'STATE.md not found' }, raw, 'STATE.md not found');
736
+ return;
737
+ }
738
+
739
+ const content = fs.readFileSync(statePath, 'utf-8');
740
+ const fm = extractFrontmatter(content);
741
+
742
+ if (!fm || Object.keys(fm).length === 0) {
743
+ const body = stripFrontmatter(content);
744
+ const built = buildStateFrontmatter(body, cwd);
745
+ output(built, raw, JSON.stringify(built, null, 2));
746
+ return;
747
+ }
748
+
749
+ output(fm, raw, JSON.stringify(fm, null, 2));
750
+ }
751
+
752
+ // ─── Quick Task Archival ─────────────────────────────────────────────────────
753
+
754
+ function cmdStateArchiveQuickTasks(cwd, raw) {
755
+ const statePath = resolveStatePath(cwd);
756
+ if (!fs.existsSync(statePath)) {
757
+ output({ error: 'STATE.md not found' }, raw);
758
+ return;
759
+ }
760
+
761
+ let content = fs.readFileSync(statePath, 'utf-8');
762
+
763
+ // Find the Quick Tasks Completed section
764
+ const sectionPattern = /(###\s*Quick Tasks Completed\s*\n)([\s\S]*?)(?=\n###?\s|\n##[^#]|$)/i;
765
+ const sectionMatch = content.match(sectionPattern);
766
+
767
+ if (!sectionMatch) {
768
+ output({ archived: false, reason: 'no_section', row_count: 0 }, raw);
769
+ return;
770
+ }
771
+
772
+ const sectionBody = sectionMatch[2];
773
+ const lines = sectionBody.split('\n');
774
+
775
+ // Separate header/separator from data rows
776
+ let headerRow = null;
777
+ let separatorRow = null;
778
+ const dataRows = [];
779
+ const preTableLines = [];
780
+
781
+ for (const line of lines) {
782
+ if (!line.startsWith('|')) {
783
+ if (!headerRow) {
784
+ preTableLines.push(line);
785
+ }
786
+ continue;
787
+ }
788
+ // Check if this is the separator row (contains |---|)
789
+ if (/^\|[\s-|]+$/.test(line)) {
790
+ separatorRow = line;
791
+ continue;
792
+ }
793
+ // Check if this is the header row (contains column names like Description, Date)
794
+ if (!headerRow && (line.includes('Description') || line.includes('#'))) {
795
+ headerRow = line;
796
+ continue;
797
+ }
798
+ // Otherwise it's a data row
799
+ dataRows.push(line);
800
+ }
801
+
802
+ if (dataRows.length <= 20) {
803
+ output({ archived: false, reason: 'under_threshold', row_count: dataRows.length }, raw);
804
+ return;
805
+ }
806
+
807
+ // Archive down to 15 rows (buffer below the 20 threshold)
808
+ const archiveCount = dataRows.length - 15;
809
+ const rowsToArchive = dataRows.slice(0, archiveCount);
810
+ const rowsToKeep = dataRows.slice(archiveCount);
811
+
812
+ // Rebuild the section with remaining rows
813
+ const rebuiltSection = preTableLines.join('\n') +
814
+ (headerRow ? headerRow + '\n' : '') +
815
+ (separatorRow ? separatorRow + '\n' : '') +
816
+ rowsToKeep.join('\n') + '\n';
817
+
818
+ content = content.replace(sectionPattern, (_match, header) => `${header}${rebuiltSection}`);
819
+ writeStateMd(statePath, content, cwd);
820
+
821
+ // Build HISTORY.md path
822
+ const historyPath = path.join(path.dirname(statePath), 'quick', 'HISTORY.md');
823
+
824
+ // Ensure quick/ directory exists
825
+ fs.mkdirSync(path.dirname(historyPath), { recursive: true });
826
+
827
+ // Read or create HISTORY.md
828
+ let historyContent;
829
+ const historyTemplate = `# Quick Task History
830
+
831
+ Archived quick/fast task records from STATE.md.
832
+
833
+ | # | Description | Date | Commit | Status | Directory |
834
+ |---|-------------|------|--------|--------|-----------|
835
+ `;
836
+
837
+ if (fs.existsSync(historyPath)) {
838
+ historyContent = fs.readFileSync(historyPath, 'utf-8');
839
+ } else {
840
+ historyContent = historyTemplate;
841
+ }
842
+
843
+ // Count columns in HISTORY.md header
844
+ const historyHeaderMatch = historyContent.match(/^\|[^-\n]+\|/m);
845
+ let historyColCount = 0;
846
+ if (historyHeaderMatch) {
847
+ historyColCount = historyHeaderMatch[0].split('|').length - 2; // subtract leading and trailing empty splits
848
+ }
849
+
850
+ // Append archived rows, padding columns if needed
851
+ const paddedRows = rowsToArchive.map(row => {
852
+ if (historyColCount > 0) {
853
+ const cells = row.split('|').filter((_, i, arr) => i > 0 && i < arr.length - 1);
854
+ const currentColCount = cells.length;
855
+ if (currentColCount < historyColCount) {
856
+ // Pad with empty cells
857
+ const padding = Array(historyColCount - currentColCount).fill(' ').join('|');
858
+ return row.replace(/\|$/, `|${padding}|`);
859
+ }
860
+ }
861
+ return row;
862
+ });
863
+
864
+ // Ensure historyContent ends with newline before appending
865
+ if (!historyContent.endsWith('\n')) {
866
+ historyContent += '\n';
867
+ }
868
+ historyContent += paddedRows.join('\n') + '\n';
869
+
870
+ fs.writeFileSync(historyPath, historyContent, 'utf-8');
871
+
872
+ output({ archived: true, count: archiveCount, remaining: 15, history_path: historyPath }, raw);
873
+ }
874
+
875
+ module.exports = {
876
+ stateExtractField,
877
+ stateReplaceField,
878
+ writeStateMd,
879
+ cmdStateLoad,
880
+ cmdStateGet,
881
+ cmdStatePatch,
882
+ cmdStateUpdate,
883
+ cmdStateAdvancePlan,
884
+ cmdStateRecordMetric,
885
+ cmdStateUpdateProgress,
886
+ cmdStateAddDecision,
887
+ cmdStateAddBlocker,
888
+ cmdStateResolveBlocker,
889
+ cmdStateRecordSession,
890
+ cmdStateSnapshot,
891
+ cmdStateJson,
892
+ cmdStateArchiveQuickTasks,
893
+ };