@howlil/ez-agents 3.4.1 → 3.4.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 (102) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +7 -18
  3. package/bin/install.js +52 -10
  4. package/commands/ez/join-discord.md +18 -18
  5. package/ez-agents/bin/lib/assistant-adapter.cjs +264 -264
  6. package/ez-agents/bin/lib/audit-exec.cjs +7 -2
  7. package/ez-agents/bin/lib/circuit-breaker.cjs +118 -118
  8. package/ez-agents/bin/lib/config.cjs +190 -190
  9. package/ez-agents/bin/lib/file-lock.cjs +236 -236
  10. package/ez-agents/bin/lib/frontmatter.cjs +299 -299
  11. package/ez-agents/bin/lib/fs-utils.cjs +153 -153
  12. package/ez-agents/bin/lib/git-utils.cjs +203 -203
  13. package/ez-agents/bin/lib/index.cjs +113 -113
  14. package/ez-agents/bin/lib/init.cjs +757 -757
  15. package/ez-agents/bin/lib/logger.cjs +47 -17
  16. package/ez-agents/bin/lib/milestone.cjs +241 -241
  17. package/ez-agents/bin/lib/model-provider.cjs +241 -241
  18. package/ez-agents/bin/lib/phase.cjs +925 -925
  19. package/ez-agents/bin/lib/planning-write.cjs +107 -107
  20. package/ez-agents/bin/lib/retry.cjs +119 -119
  21. package/ez-agents/bin/lib/roadmap.cjs +306 -306
  22. package/ez-agents/bin/lib/safe-exec.cjs +90 -4
  23. package/ez-agents/bin/lib/safe-path.cjs +130 -130
  24. package/ez-agents/bin/lib/state.cjs +736 -736
  25. package/ez-agents/bin/lib/temp-file.cjs +239 -239
  26. package/ez-agents/bin/lib/template.cjs +223 -223
  27. package/ez-agents/bin/lib/test-file-lock.cjs +112 -112
  28. package/ez-agents/bin/lib/test-graceful.cjs +93 -93
  29. package/ez-agents/bin/lib/test-logger.cjs +60 -60
  30. package/ez-agents/bin/lib/test-safe-exec.cjs +38 -38
  31. package/ez-agents/bin/lib/test-safe-path.cjs +33 -33
  32. package/ez-agents/bin/lib/test-temp-file.cjs +125 -125
  33. package/ez-agents/bin/lib/timeout-exec.cjs +63 -63
  34. package/ez-agents/bin/lib/verify.cjs +15 -1
  35. package/ez-agents/references/checkpoints.md +776 -776
  36. package/ez-agents/references/continuation-format.md +249 -249
  37. package/ez-agents/references/questioning.md +162 -162
  38. package/ez-agents/references/tdd.md +263 -263
  39. package/ez-agents/templates/codebase/concerns.md +310 -310
  40. package/ez-agents/templates/codebase/conventions.md +307 -307
  41. package/ez-agents/templates/codebase/integrations.md +280 -280
  42. package/ez-agents/templates/codebase/stack.md +186 -186
  43. package/ez-agents/templates/codebase/testing.md +480 -480
  44. package/ez-agents/templates/config.json +37 -37
  45. package/ez-agents/templates/continue-here.md +78 -78
  46. package/ez-agents/templates/milestone-archive.md +123 -123
  47. package/ez-agents/templates/milestone.md +115 -115
  48. package/ez-agents/templates/requirements.md +231 -231
  49. package/ez-agents/templates/research-project/ARCHITECTURE.md +204 -204
  50. package/ez-agents/templates/research-project/FEATURES.md +147 -147
  51. package/ez-agents/templates/research-project/PITFALLS.md +200 -200
  52. package/ez-agents/templates/research-project/STACK.md +120 -120
  53. package/ez-agents/templates/research-project/SUMMARY.md +170 -170
  54. package/ez-agents/templates/retrospective.md +54 -54
  55. package/ez-agents/templates/roadmap.md +202 -202
  56. package/ez-agents/templates/summary-minimal.md +41 -41
  57. package/ez-agents/templates/summary-standard.md +48 -48
  58. package/ez-agents/templates/summary.md +248 -248
  59. package/ez-agents/templates/user-setup.md +311 -311
  60. package/ez-agents/templates/verification-report.md +322 -322
  61. package/ez-agents/workflows/add-phase.md +112 -112
  62. package/ez-agents/workflows/add-tests.md +351 -351
  63. package/ez-agents/workflows/add-todo.md +158 -158
  64. package/ez-agents/workflows/audit-milestone.md +332 -332
  65. package/ez-agents/workflows/autonomous.md +743 -743
  66. package/ez-agents/workflows/check-todos.md +177 -177
  67. package/ez-agents/workflows/cleanup.md +152 -152
  68. package/ez-agents/workflows/complete-milestone.md +766 -766
  69. package/ez-agents/workflows/diagnose-issues.md +219 -219
  70. package/ez-agents/workflows/discovery-phase.md +289 -289
  71. package/ez-agents/workflows/discuss-phase.md +762 -762
  72. package/ez-agents/workflows/execute-phase.md +468 -468
  73. package/ez-agents/workflows/execute-plan.md +483 -483
  74. package/ez-agents/workflows/health.md +159 -159
  75. package/ez-agents/workflows/help.md +492 -492
  76. package/ez-agents/workflows/insert-phase.md +130 -130
  77. package/ez-agents/workflows/list-phase-assumptions.md +178 -178
  78. package/ez-agents/workflows/map-codebase.md +316 -316
  79. package/ez-agents/workflows/new-milestone.md +384 -384
  80. package/ez-agents/workflows/new-project.md +1113 -1113
  81. package/ez-agents/workflows/node-repair.md +92 -92
  82. package/ez-agents/workflows/pause-work.md +122 -122
  83. package/ez-agents/workflows/plan-milestone-gaps.md +274 -274
  84. package/ez-agents/workflows/plan-phase.md +651 -651
  85. package/ez-agents/workflows/progress.md +382 -382
  86. package/ez-agents/workflows/quick.md +610 -610
  87. package/ez-agents/workflows/remove-phase.md +155 -155
  88. package/ez-agents/workflows/research-phase.md +74 -74
  89. package/ez-agents/workflows/resume-project.md +307 -307
  90. package/ez-agents/workflows/set-profile.md +81 -81
  91. package/ez-agents/workflows/settings.md +242 -242
  92. package/ez-agents/workflows/stats.md +57 -57
  93. package/ez-agents/workflows/transition.md +544 -544
  94. package/ez-agents/workflows/ui-phase.md +290 -290
  95. package/ez-agents/workflows/ui-review.md +157 -157
  96. package/ez-agents/workflows/update.md +320 -320
  97. package/ez-agents/workflows/validate-phase.md +167 -167
  98. package/ez-agents/workflows/verify-phase.md +243 -243
  99. package/ez-agents/workflows/verify-work.md +584 -584
  100. package/package.json +2 -3
  101. package/scripts/build-hooks.js +43 -43
  102. package/scripts/run-tests.cjs +29 -29
@@ -1,736 +1,736 @@
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, output, error } = require('./core.cjs');
8
- const { extractFrontmatter, reconstructFrontmatter } = require('./frontmatter.cjs');
9
- const { safePlanningWriteSync } = require('./planning-write.cjs');
10
- const { defaultLogger: logger } = require('./logger.cjs');
11
-
12
- // Shared helper: extract a field value from STATE.md content.
13
- // Supports both **Field:** bold and plain Field: format.
14
- function stateExtractField(content, fieldName) {
15
- const escaped = escapeRegex(fieldName);
16
- const boldPattern = new RegExp(`\\*\\*${escaped}:\\*\\*\\s*(.+)`, 'i');
17
- const boldMatch = content.match(boldPattern);
18
- if (boldMatch) return boldMatch[1].trim();
19
- const plainPattern = new RegExp(`^${escaped}:\\s*(.+)`, 'im');
20
- const plainMatch = content.match(plainPattern);
21
- return plainMatch ? plainMatch[1].trim() : null;
22
- }
23
-
24
- function cmdStateLoad(cwd, raw) {
25
- const config = loadConfig(cwd);
26
- const planningDir = path.join(cwd, '.planning');
27
-
28
- let stateRaw = '';
29
- try {
30
- stateRaw = fs.readFileSync(path.join(planningDir, 'STATE.md'), 'utf-8');
31
- } catch (err) {
32
- logger.warn('Failed to read STATE.md in cmdStateLoad', { planningDir, error: err.message });
33
- }
34
-
35
- const configExists = fs.existsSync(path.join(planningDir, 'config.json'));
36
- const roadmapExists = fs.existsSync(path.join(planningDir, 'ROADMAP.md'));
37
- const stateExists = stateRaw.length > 0;
38
-
39
- const result = {
40
- config,
41
- state_raw: stateRaw,
42
- state_exists: stateExists,
43
- roadmap_exists: roadmapExists,
44
- config_exists: configExists,
45
- };
46
-
47
- // For --raw, output a condensed key=value format
48
- if (raw) {
49
- const c = config;
50
- const lines = [
51
- `model_profile=${c.model_profile}`,
52
- `commit_docs=${c.commit_docs}`,
53
- `branching_strategy=${c.branching_strategy}`,
54
- `phase_branch_template=${c.phase_branch_template}`,
55
- `milestone_branch_template=${c.milestone_branch_template}`,
56
- `parallelization=${c.parallelization}`,
57
- `research=${c.research}`,
58
- `plan_checker=${c.plan_checker}`,
59
- `verifier=${c.verifier}`,
60
- `config_exists=${configExists}`,
61
- `roadmap_exists=${roadmapExists}`,
62
- `state_exists=${stateExists}`,
63
- ];
64
- process.stdout.write(lines.join('\n'));
65
- process.exit(0);
66
- }
67
-
68
- output(result);
69
- }
70
-
71
- function cmdStateGet(cwd, section, raw) {
72
- const statePath = path.join(cwd, '.planning', 'STATE.md');
73
- try {
74
- const content = fs.readFileSync(statePath, 'utf-8');
75
-
76
- if (!section) {
77
- output({ content }, raw, content);
78
- return;
79
- }
80
-
81
- // Try to find markdown section or field
82
- const fieldEscaped = section.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
83
-
84
- // Check for **field:** value (bold format)
85
- const boldPattern = new RegExp(`\\*\\*${fieldEscaped}:\\*\\*\\s*(.*)`, 'i');
86
- const boldMatch = content.match(boldPattern);
87
- if (boldMatch) {
88
- output({ [section]: boldMatch[1].trim() }, raw, boldMatch[1].trim());
89
- return;
90
- }
91
-
92
- // Check for field: value (plain format)
93
- const plainPattern = new RegExp(`^${fieldEscaped}:\\s*(.*)`, 'im');
94
- const plainMatch = content.match(plainPattern);
95
- if (plainMatch) {
96
- output({ [section]: plainMatch[1].trim() }, raw, plainMatch[1].trim());
97
- return;
98
- }
99
-
100
- // Check for ## Section
101
- const sectionPattern = new RegExp(`##\\s*${fieldEscaped}\\s*\n([\\s\\S]*?)(?=\\n##|$)`, 'i');
102
- const sectionMatch = content.match(sectionPattern);
103
- if (sectionMatch) {
104
- output({ [section]: sectionMatch[1].trim() }, raw, sectionMatch[1].trim());
105
- return;
106
- }
107
-
108
- output({ error: `Section or field "${section}" not found` }, raw, '');
109
- } catch (err) {
110
- logger.error('STATE.md not found in cmdStateGet', { statePath, error: err.message });
111
- error('STATE.md not found');
112
- }
113
- }
114
-
115
- function readTextArgOrFile(cwd, value, filePath, label) {
116
- if (!filePath) return value;
117
-
118
- const resolvedPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
119
- try {
120
- return fs.readFileSync(resolvedPath, 'utf-8').trimEnd();
121
- } catch {
122
- throw new Error(`${label} file not found: ${filePath}`);
123
- }
124
- }
125
-
126
- function cmdStatePatch(cwd, patches, raw) {
127
- const statePath = path.join(cwd, '.planning', 'STATE.md');
128
- try {
129
- let content = fs.readFileSync(statePath, 'utf-8');
130
- const results = { updated: [], failed: [] };
131
-
132
- for (const [field, value] of Object.entries(patches)) {
133
- const fieldEscaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
134
- // Try **Field:** bold format first, then plain Field: format
135
- const boldPattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
136
- const plainPattern = new RegExp(`(^${fieldEscaped}:\\s*)(.*)`, 'im');
137
-
138
- if (boldPattern.test(content)) {
139
- content = content.replace(boldPattern, (_match, prefix) => `${prefix}${value}`);
140
- results.updated.push(field);
141
- } else if (plainPattern.test(content)) {
142
- content = content.replace(plainPattern, (_match, prefix) => `${prefix}${value}`);
143
- results.updated.push(field);
144
- } else {
145
- results.failed.push(field);
146
- }
147
- }
148
-
149
- if (results.updated.length > 0) {
150
- writeStateMd(statePath, content, cwd);
151
- }
152
-
153
- output(results, raw, results.updated.length > 0 ? 'true' : 'false');
154
- } catch (err) {
155
- logger.error('Failed to patch STATE.md', { statePath, error: err.message });
156
- error('STATE.md not found');
157
- }
158
- }
159
-
160
- function cmdStateUpdate(cwd, field, value) {
161
- if (!field || value === undefined) {
162
- error('field and value required for state update');
163
- }
164
-
165
- const statePath = path.join(cwd, '.planning', 'STATE.md');
166
- try {
167
- let content = fs.readFileSync(statePath, 'utf-8');
168
- const fieldEscaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
169
- // Try **Field:** bold format first, then plain Field: format
170
- const boldPattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
171
- const plainPattern = new RegExp(`(^${fieldEscaped}:\\s*)(.*)`, 'im');
172
- if (boldPattern.test(content)) {
173
- content = content.replace(boldPattern, (_match, prefix) => `${prefix}${value}`);
174
- writeStateMd(statePath, content, cwd);
175
- output({ updated: true });
176
- } else if (plainPattern.test(content)) {
177
- content = content.replace(plainPattern, (_match, prefix) => `${prefix}${value}`);
178
- writeStateMd(statePath, content, cwd);
179
- output({ updated: true });
180
- } else {
181
- output({ updated: false, reason: `Field "${field}" not found in STATE.md` });
182
- }
183
- } catch (err) {
184
- logger.error('Failed to update STATE.md', { statePath, field, error: err.message });
185
- output({ updated: false, reason: 'STATE.md not found' });
186
- }
187
- }
188
-
189
- // ─── State Progression Engine ────────────────────────────────────────────────
190
-
191
- function stateExtractField(content, fieldName) {
192
- const escaped = fieldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
193
- // Try **Field:** bold format first
194
- const boldPattern = new RegExp(`\\*\\*${escaped}:\\*\\*\\s*(.+)`, 'i');
195
- const boldMatch = content.match(boldPattern);
196
- if (boldMatch) return boldMatch[1].trim();
197
- // Fall back to plain Field: format
198
- const plainPattern = new RegExp(`^${escaped}:\\s*(.+)`, 'im');
199
- const plainMatch = content.match(plainPattern);
200
- return plainMatch ? plainMatch[1].trim() : null;
201
- }
202
-
203
- function stateReplaceField(content, fieldName, newValue) {
204
- const escaped = fieldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
205
- // Try **Field:** bold format first, then plain Field: format
206
- const boldPattern = new RegExp(`(\\*\\*${escaped}:\\*\\*\\s*)(.*)`, 'i');
207
- if (boldPattern.test(content)) {
208
- return content.replace(boldPattern, (_match, prefix) => `${prefix}${newValue}`);
209
- }
210
- const plainPattern = new RegExp(`(^${escaped}:\\s*)(.*)`, 'im');
211
- if (plainPattern.test(content)) {
212
- return content.replace(plainPattern, (_match, prefix) => `${prefix}${newValue}`);
213
- }
214
- return null;
215
- }
216
-
217
- function cmdStateAdvancePlan(cwd, raw) {
218
- const statePath = path.join(cwd, '.planning', 'STATE.md');
219
- if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
220
-
221
- let content = fs.readFileSync(statePath, 'utf-8');
222
- const currentPlan = parseInt(stateExtractField(content, 'Current Plan'), 10);
223
- const totalPlans = parseInt(stateExtractField(content, 'Total Plans in Phase'), 10);
224
- const today = new Date().toISOString().split('T')[0];
225
-
226
- if (isNaN(currentPlan) || isNaN(totalPlans)) {
227
- output({ error: 'Cannot parse Current Plan or Total Plans in Phase from STATE.md' }, raw);
228
- return;
229
- }
230
-
231
- if (currentPlan >= totalPlans) {
232
- content = stateReplaceField(content, 'Status', 'Phase complete — ready for verification') || content;
233
- content = stateReplaceField(content, 'Last Activity', today) || content;
234
- writeStateMd(statePath, content, cwd);
235
- output({ advanced: false, reason: 'last_plan', current_plan: currentPlan, total_plans: totalPlans, status: 'ready_for_verification' }, raw, 'false');
236
- } else {
237
- const newPlan = currentPlan + 1;
238
- content = stateReplaceField(content, 'Current Plan', String(newPlan)) || content;
239
- content = stateReplaceField(content, 'Status', 'Ready to execute') || content;
240
- content = stateReplaceField(content, 'Last Activity', today) || content;
241
- writeStateMd(statePath, content, cwd);
242
- output({ advanced: true, previous_plan: currentPlan, current_plan: newPlan, total_plans: totalPlans }, raw, 'true');
243
- }
244
- }
245
-
246
- function cmdStateRecordMetric(cwd, options, raw) {
247
- const statePath = path.join(cwd, '.planning', 'STATE.md');
248
- if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
249
-
250
- let content = fs.readFileSync(statePath, 'utf-8');
251
- const { phase, plan, duration, tasks, files } = options;
252
-
253
- if (!phase || !plan || !duration) {
254
- output({ error: 'phase, plan, and duration required' }, raw);
255
- return;
256
- }
257
-
258
- // Find Performance Metrics section and its table
259
- const metricsPattern = /(##\s*Performance Metrics[\s\S]*?\n\|[^\n]+\n\|[-|\s]+\n)([\s\S]*?)(?=\n##|\n$|$)/i;
260
- const metricsMatch = content.match(metricsPattern);
261
-
262
- if (metricsMatch) {
263
- let tableBody = metricsMatch[2].trimEnd();
264
- const newRow = `| Phase ${phase} P${plan} | ${duration} | ${tasks || '-'} tasks | ${files || '-'} files |`;
265
-
266
- if (tableBody.trim() === '' || tableBody.includes('None yet')) {
267
- tableBody = newRow;
268
- } else {
269
- tableBody = tableBody + '\n' + newRow;
270
- }
271
-
272
- content = content.replace(metricsPattern, (_match, header) => `${header}${tableBody}\n`);
273
- writeStateMd(statePath, content, cwd);
274
- output({ recorded: true, phase, plan, duration }, raw, 'true');
275
- } else {
276
- output({ recorded: false, reason: 'Performance Metrics section not found in STATE.md' }, raw, 'false');
277
- }
278
- }
279
-
280
- function cmdStateUpdateProgress(cwd, raw) {
281
- const statePath = path.join(cwd, '.planning', 'STATE.md');
282
- if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
283
-
284
- let content = fs.readFileSync(statePath, 'utf-8');
285
-
286
- // Count summaries across all phases
287
- const phasesDir = path.join(cwd, '.planning', 'phases');
288
- let totalPlans = 0;
289
- let totalSummaries = 0;
290
-
291
- if (fs.existsSync(phasesDir)) {
292
- const phaseDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
293
- .filter(e => e.isDirectory()).map(e => e.name);
294
- for (const dir of phaseDirs) {
295
- const files = fs.readdirSync(path.join(phasesDir, dir));
296
- totalPlans += files.filter(f => f.match(/-PLAN\.md$/i)).length;
297
- totalSummaries += files.filter(f => f.match(/-SUMMARY\.md$/i)).length;
298
- }
299
- }
300
-
301
- const percent = totalPlans > 0 ? Math.min(100, Math.round(totalSummaries / totalPlans * 100)) : 0;
302
- const barWidth = 10;
303
- const filled = Math.round(percent / 100 * barWidth);
304
- const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
305
- const progressStr = `[${bar}] ${percent}%`;
306
-
307
- // Try **Progress:** bold format first, then plain Progress: format
308
- const boldProgressPattern = /(\*\*Progress:\*\*\s*).*/i;
309
- const plainProgressPattern = /^(Progress:\s*).*/im;
310
- if (boldProgressPattern.test(content)) {
311
- content = content.replace(boldProgressPattern, (_match, prefix) => `${prefix}${progressStr}`);
312
- writeStateMd(statePath, content, cwd);
313
- output({ updated: true, percent, completed: totalSummaries, total: totalPlans, bar: progressStr }, raw, progressStr);
314
- } else if (plainProgressPattern.test(content)) {
315
- content = content.replace(plainProgressPattern, (_match, prefix) => `${prefix}${progressStr}`);
316
- writeStateMd(statePath, content, cwd);
317
- output({ updated: true, percent, completed: totalSummaries, total: totalPlans, bar: progressStr }, raw, progressStr);
318
- } else {
319
- output({ updated: false, reason: 'Progress field not found in STATE.md' }, raw, 'false');
320
- }
321
- }
322
-
323
- function cmdStateAddDecision(cwd, options, raw) {
324
- const statePath = path.join(cwd, '.planning', 'STATE.md');
325
- if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
326
-
327
- const { phase, summary, summary_file, rationale, rationale_file } = options;
328
- let summaryText = null;
329
- let rationaleText = '';
330
-
331
- try {
332
- summaryText = readTextArgOrFile(cwd, summary, summary_file, 'summary');
333
- rationaleText = readTextArgOrFile(cwd, rationale || '', rationale_file, 'rationale');
334
- } catch (err) {
335
- logger.error('Failed to read decision text', { error: err.message });
336
- output({ added: false, reason: err.message }, raw, 'false');
337
- return;
338
- }
339
-
340
- if (!summaryText) { output({ error: 'summary required' }, raw); return; }
341
-
342
- let content = fs.readFileSync(statePath, 'utf-8');
343
- const entry = `- [Phase ${phase || '?'}]: ${summaryText}${rationaleText ? ` — ${rationaleText}` : ''}`;
344
-
345
- // Find Decisions section (various heading patterns)
346
- const sectionPattern = /(###?\s*(?:Decisions|Decisions Made|Accumulated.*Decisions)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
347
- const match = content.match(sectionPattern);
348
-
349
- if (match) {
350
- let sectionBody = match[2];
351
- // Remove placeholders
352
- sectionBody = sectionBody.replace(/None yet\.?\s*\n?/gi, '').replace(/No decisions yet\.?\s*\n?/gi, '');
353
- sectionBody = sectionBody.trimEnd() + '\n' + entry + '\n';
354
- content = content.replace(sectionPattern, (_match, header) => `${header}${sectionBody}`);
355
- writeStateMd(statePath, content, cwd);
356
- output({ added: true, decision: entry }, raw, 'true');
357
- } else {
358
- output({ added: false, reason: 'Decisions section not found in STATE.md' }, raw, 'false');
359
- }
360
- }
361
-
362
- function cmdStateAddBlocker(cwd, text, raw) {
363
- const statePath = path.join(cwd, '.planning', 'STATE.md');
364
- if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
365
- const blockerOptions = typeof text === 'object' && text !== null ? text : { text };
366
- let blockerText = null;
367
-
368
- try {
369
- blockerText = readTextArgOrFile(cwd, blockerOptions.text, blockerOptions.text_file, 'blocker');
370
- } catch (err) {
371
- logger.error('Failed to read blocker text', { error: err.message });
372
- output({ added: false, reason: err.message }, raw, 'false');
373
- return;
374
- }
375
-
376
- if (!blockerText) { output({ error: 'text required' }, raw); return; }
377
-
378
- let content = fs.readFileSync(statePath, 'utf-8');
379
- const entry = `- ${blockerText}`;
380
-
381
- const sectionPattern = /(###?\s*(?:Blockers|Blockers\/Concerns|Concerns)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
382
- const match = content.match(sectionPattern);
383
-
384
- if (match) {
385
- let sectionBody = match[2];
386
- sectionBody = sectionBody.replace(/None\.?\s*\n?/gi, '').replace(/None yet\.?\s*\n?/gi, '');
387
- sectionBody = sectionBody.trimEnd() + '\n' + entry + '\n';
388
- content = content.replace(sectionPattern, (_match, header) => `${header}${sectionBody}`);
389
- writeStateMd(statePath, content, cwd);
390
- output({ added: true, blocker: blockerText }, raw, 'true');
391
- } else {
392
- output({ added: false, reason: 'Blockers section not found in STATE.md' }, raw, 'false');
393
- }
394
- }
395
-
396
- function cmdStateResolveBlocker(cwd, text, raw) {
397
- const statePath = path.join(cwd, '.planning', 'STATE.md');
398
- if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
399
- if (!text) { output({ error: 'text required' }, raw); return; }
400
-
401
- let content = fs.readFileSync(statePath, 'utf-8');
402
-
403
- const sectionPattern = /(###?\s*(?:Blockers|Blockers\/Concerns|Concerns)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
404
- const match = content.match(sectionPattern);
405
-
406
- if (match) {
407
- const sectionBody = match[2];
408
- const lines = sectionBody.split('\n');
409
- const filtered = lines.filter(line => {
410
- if (!line.startsWith('- ')) return true;
411
- return !line.toLowerCase().includes(text.toLowerCase());
412
- });
413
-
414
- let newBody = filtered.join('\n');
415
- // If section is now empty, add placeholder
416
- if (!newBody.trim() || !newBody.includes('- ')) {
417
- newBody = 'None\n';
418
- }
419
-
420
- content = content.replace(sectionPattern, (_match, header) => `${header}${newBody}`);
421
- writeStateMd(statePath, content, cwd);
422
- output({ resolved: true, blocker: text }, raw, 'true');
423
- } else {
424
- output({ resolved: false, reason: 'Blockers section not found in STATE.md' }, raw, 'false');
425
- }
426
- }
427
-
428
- function cmdStateRecordSession(cwd, options, raw) {
429
- const statePath = path.join(cwd, '.planning', 'STATE.md');
430
- if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
431
-
432
- let content = fs.readFileSync(statePath, 'utf-8');
433
- const now = new Date().toISOString();
434
- const updated = [];
435
-
436
- // Update Last session / Last Date
437
- let result = stateReplaceField(content, 'Last session', now);
438
- if (result) { content = result; updated.push('Last session'); }
439
- result = stateReplaceField(content, 'Last Date', now);
440
- if (result) { content = result; updated.push('Last Date'); }
441
-
442
- // Update Stopped at
443
- if (options.stopped_at) {
444
- result = stateReplaceField(content, 'Stopped At', options.stopped_at);
445
- if (!result) result = stateReplaceField(content, 'Stopped at', options.stopped_at);
446
- if (result) { content = result; updated.push('Stopped At'); }
447
- }
448
-
449
- // Update Resume file
450
- const resumeFile = options.resume_file || 'None';
451
- result = stateReplaceField(content, 'Resume File', resumeFile);
452
- if (!result) result = stateReplaceField(content, 'Resume file', resumeFile);
453
- if (result) { content = result; updated.push('Resume File'); }
454
-
455
- if (updated.length > 0) {
456
- writeStateMd(statePath, content, cwd);
457
- output({ recorded: true, updated }, raw, 'true');
458
- } else {
459
- output({ recorded: false, reason: 'No session fields found in STATE.md' }, raw, 'false');
460
- }
461
- }
462
-
463
- function cmdStateSnapshot(cwd, raw) {
464
- const statePath = path.join(cwd, '.planning', 'STATE.md');
465
-
466
- if (!fs.existsSync(statePath)) {
467
- output({ error: 'STATE.md not found' }, raw);
468
- return;
469
- }
470
-
471
- const content = fs.readFileSync(statePath, 'utf-8');
472
-
473
- // Extract basic fields
474
- const currentPhase = stateExtractField(content, 'Current Phase');
475
- const currentPhaseName = stateExtractField(content, 'Current Phase Name');
476
- const totalPhasesRaw = stateExtractField(content, 'Total Phases');
477
- const currentPlan = stateExtractField(content, 'Current Plan');
478
- const totalPlansRaw = stateExtractField(content, 'Total Plans in Phase');
479
- const status = stateExtractField(content, 'Status');
480
- const progressRaw = stateExtractField(content, 'Progress');
481
- const lastActivity = stateExtractField(content, 'Last Activity');
482
- const lastActivityDesc = stateExtractField(content, 'Last Activity Description');
483
- const pausedAt = stateExtractField(content, 'Paused At');
484
-
485
- // Parse numeric fields
486
- const totalPhases = totalPhasesRaw ? parseInt(totalPhasesRaw, 10) : null;
487
- const totalPlansInPhase = totalPlansRaw ? parseInt(totalPlansRaw, 10) : null;
488
- const progressPercent = progressRaw ? parseInt(progressRaw.replace('%', ''), 10) : null;
489
-
490
- // Extract decisions table
491
- const decisions = [];
492
- const decisionsMatch = content.match(/##\s*Decisions Made[\s\S]*?\n\|[^\n]+\n\|[-|\s]+\n([\s\S]*?)(?=\n##|\n$|$)/i);
493
- if (decisionsMatch) {
494
- const tableBody = decisionsMatch[1];
495
- const rows = tableBody.trim().split('\n').filter(r => r.includes('|'));
496
- for (const row of rows) {
497
- const cells = row.split('|').map(c => c.trim()).filter(Boolean);
498
- if (cells.length >= 3) {
499
- decisions.push({
500
- phase: cells[0],
501
- summary: cells[1],
502
- rationale: cells[2],
503
- });
504
- }
505
- }
506
- }
507
-
508
- // Extract blockers list
509
- const blockers = [];
510
- const blockersMatch = content.match(/##\s*Blockers\s*\n([\s\S]*?)(?=\n##|$)/i);
511
- if (blockersMatch) {
512
- const blockersSection = blockersMatch[1];
513
- const items = blockersSection.match(/^-\s+(.+)$/gm) || [];
514
- for (const item of items) {
515
- blockers.push(item.replace(/^-\s+/, '').trim());
516
- }
517
- }
518
-
519
- // Extract session info
520
- const session = {
521
- last_date: null,
522
- stopped_at: null,
523
- resume_file: null,
524
- };
525
-
526
- const sessionMatch = content.match(/##\s*Session\s*\n([\s\S]*?)(?=\n##|$)/i);
527
- if (sessionMatch) {
528
- const sessionSection = sessionMatch[1];
529
- const lastDateMatch = sessionSection.match(/\*\*Last Date:\*\*\s*(.+)/i)
530
- || sessionSection.match(/^Last Date:\s*(.+)/im);
531
- const stoppedAtMatch = sessionSection.match(/\*\*Stopped At:\*\*\s*(.+)/i)
532
- || sessionSection.match(/^Stopped At:\s*(.+)/im);
533
- const resumeFileMatch = sessionSection.match(/\*\*Resume File:\*\*\s*(.+)/i)
534
- || sessionSection.match(/^Resume File:\s*(.+)/im);
535
-
536
- if (lastDateMatch) session.last_date = lastDateMatch[1].trim();
537
- if (stoppedAtMatch) session.stopped_at = stoppedAtMatch[1].trim();
538
- if (resumeFileMatch) session.resume_file = resumeFileMatch[1].trim();
539
- }
540
-
541
- const result = {
542
- current_phase: currentPhase,
543
- current_phase_name: currentPhaseName,
544
- total_phases: totalPhases,
545
- current_plan: currentPlan,
546
- total_plans_in_phase: totalPlansInPhase,
547
- status,
548
- progress_percent: progressPercent,
549
- last_activity: lastActivity,
550
- last_activity_desc: lastActivityDesc,
551
- decisions,
552
- blockers,
553
- paused_at: pausedAt,
554
- session,
555
- };
556
-
557
- output(result, raw);
558
- }
559
-
560
- // ─── State Frontmatter Sync ──────────────────────────────────────────────────
561
-
562
- /**
563
- * Extract machine-readable fields from STATE.md markdown body and build
564
- * a YAML frontmatter object. Allows hooks and scripts to read state
565
- * reliably via `state json` instead of fragile regex parsing.
566
- */
567
- function buildStateFrontmatter(bodyContent, cwd) {
568
- const currentPhase = stateExtractField(bodyContent, 'Current Phase');
569
- const currentPhaseName = stateExtractField(bodyContent, 'Current Phase Name');
570
- const currentPlan = stateExtractField(bodyContent, 'Current Plan');
571
- const totalPhasesRaw = stateExtractField(bodyContent, 'Total Phases');
572
- const totalPlansRaw = stateExtractField(bodyContent, 'Total Plans in Phase');
573
- const status = stateExtractField(bodyContent, 'Status');
574
- const progressRaw = stateExtractField(bodyContent, 'Progress');
575
- const lastActivity = stateExtractField(bodyContent, 'Last Activity');
576
- const stoppedAt = stateExtractField(bodyContent, 'Stopped At') || stateExtractField(bodyContent, 'Stopped at');
577
- const pausedAt = stateExtractField(bodyContent, 'Paused At');
578
-
579
- let milestone = null;
580
- let milestoneName = null;
581
- if (cwd) {
582
- try {
583
- const info = getMilestoneInfo(cwd);
584
- milestone = info.version;
585
- milestoneName = info.name;
586
- } catch (err) {
587
- logger.warn('Failed to resolve milestone info while building state frontmatter', { error: err.message });
588
- }
589
- }
590
-
591
- let totalPhases = totalPhasesRaw ? parseInt(totalPhasesRaw, 10) : null;
592
- let completedPhases = null;
593
- let totalPlans = totalPlansRaw ? parseInt(totalPlansRaw, 10) : null;
594
- let completedPlans = null;
595
-
596
- if (cwd) {
597
- try {
598
- const phasesDir = path.join(cwd, '.planning', 'phases');
599
- if (fs.existsSync(phasesDir)) {
600
- const isDirInMilestone = getMilestonePhaseFilter(cwd);
601
- const phaseDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
602
- .filter(e => e.isDirectory()).map(e => e.name)
603
- .filter(isDirInMilestone);
604
- let diskTotalPlans = 0;
605
- let diskTotalSummaries = 0;
606
- let diskCompletedPhases = 0;
607
-
608
- for (const dir of phaseDirs) {
609
- const files = fs.readdirSync(path.join(phasesDir, dir));
610
- const plans = files.filter(f => f.match(/-PLAN\.md$/i)).length;
611
- const summaries = files.filter(f => f.match(/-SUMMARY\.md$/i)).length;
612
- diskTotalPlans += plans;
613
- diskTotalSummaries += summaries;
614
- if (plans > 0 && summaries >= plans) diskCompletedPhases++;
615
- }
616
- totalPhases = isDirInMilestone.phaseCount > 0
617
- ? Math.max(phaseDirs.length, isDirInMilestone.phaseCount)
618
- : phaseDirs.length;
619
- completedPhases = diskCompletedPhases;
620
- totalPlans = diskTotalPlans;
621
- completedPlans = diskTotalSummaries;
622
- }
623
- } catch (err) {
624
- logger.warn('Failed to compute phase progress from disk while building state frontmatter', { error: err.message });
625
- }
626
- }
627
-
628
- let progressPercent = null;
629
- if (progressRaw) {
630
- const pctMatch = progressRaw.match(/(\d+)%/);
631
- if (pctMatch) progressPercent = parseInt(pctMatch[1], 10);
632
- }
633
-
634
- // Normalize status to one of: planning, discussing, executing, verifying, paused, completed, unknown
635
- let normalizedStatus = status || 'unknown';
636
- const statusLower = (status || '').toLowerCase();
637
- if (statusLower.includes('paused') || statusLower.includes('stopped') || pausedAt) {
638
- normalizedStatus = 'paused';
639
- } else if (statusLower.includes('executing') || statusLower.includes('in progress')) {
640
- normalizedStatus = 'executing';
641
- } else if (statusLower.includes('planning') || statusLower.includes('ready to plan')) {
642
- normalizedStatus = 'planning';
643
- } else if (statusLower.includes('discussing')) {
644
- normalizedStatus = 'discussing';
645
- } else if (statusLower.includes('verif')) {
646
- normalizedStatus = 'verifying';
647
- } else if (statusLower.includes('complete') || statusLower.includes('done')) {
648
- normalizedStatus = 'completed';
649
- } else if (statusLower.includes('ready to execute')) {
650
- normalizedStatus = 'executing';
651
- }
652
-
653
- const fm = {
654
- ez_state_version: '1.0',
655
- };
656
-
657
- if (milestone) fm.milestone = milestone;
658
- if (milestoneName) fm.milestone_name = milestoneName;
659
- if (currentPhase) fm.current_phase = currentPhase;
660
- if (currentPhaseName) fm.current_phase_name = currentPhaseName;
661
- if (currentPlan) fm.current_plan = currentPlan;
662
- fm.status = normalizedStatus;
663
- if (stoppedAt) fm.stopped_at = stoppedAt;
664
- if (pausedAt) fm.paused_at = pausedAt;
665
- fm.last_updated = new Date().toISOString();
666
- if (lastActivity) fm.last_activity = lastActivity;
667
-
668
- const progress = {};
669
- if (totalPhases !== null) progress.total_phases = totalPhases;
670
- if (completedPhases !== null) progress.completed_phases = completedPhases;
671
- if (totalPlans !== null) progress.total_plans = totalPlans;
672
- if (completedPlans !== null) progress.completed_plans = completedPlans;
673
- if (progressPercent !== null) progress.percent = progressPercent;
674
- if (Object.keys(progress).length > 0) fm.progress = progress;
675
-
676
- return fm;
677
- }
678
-
679
- function stripFrontmatter(content) {
680
- return content.replace(/^---\n[\s\S]*?\n---\n*/, '');
681
- }
682
-
683
- function syncStateFrontmatter(content, cwd) {
684
- const body = stripFrontmatter(content);
685
- const fm = buildStateFrontmatter(body, cwd);
686
- const yamlStr = reconstructFrontmatter(fm);
687
- return `---\n${yamlStr}\n---\n\n${body}`;
688
- }
689
-
690
- /**
691
- * Write STATE.md with synchronized YAML frontmatter.
692
- * All STATE.md writes should use this instead of raw writeFileSync.
693
- */
694
- function writeStateMd(statePath, content, cwd, options = {}) {
695
- const synced = syncStateFrontmatter(content, cwd);
696
- safePlanningWriteSync(statePath, synced, options);
697
- }
698
-
699
- function cmdStateJson(cwd, raw) {
700
- const statePath = path.join(cwd, '.planning', 'STATE.md');
701
- if (!fs.existsSync(statePath)) {
702
- output({ error: 'STATE.md not found' }, raw, 'STATE.md not found');
703
- return;
704
- }
705
-
706
- const content = fs.readFileSync(statePath, 'utf-8');
707
- const fm = extractFrontmatter(content);
708
-
709
- if (!fm || Object.keys(fm).length === 0) {
710
- const body = stripFrontmatter(content);
711
- const built = buildStateFrontmatter(body, cwd);
712
- output(built, raw, JSON.stringify(built, null, 2));
713
- return;
714
- }
715
-
716
- output(fm, raw, JSON.stringify(fm, null, 2));
717
- }
718
-
719
- module.exports = {
720
- stateExtractField,
721
- stateReplaceField,
722
- writeStateMd,
723
- cmdStateLoad,
724
- cmdStateGet,
725
- cmdStatePatch,
726
- cmdStateUpdate,
727
- cmdStateAdvancePlan,
728
- cmdStateRecordMetric,
729
- cmdStateUpdateProgress,
730
- cmdStateAddDecision,
731
- cmdStateAddBlocker,
732
- cmdStateResolveBlocker,
733
- cmdStateRecordSession,
734
- cmdStateSnapshot,
735
- cmdStateJson,
736
- };
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, output, error } = require('./core.cjs');
8
+ const { extractFrontmatter, reconstructFrontmatter } = require('./frontmatter.cjs');
9
+ const { safePlanningWriteSync } = require('./planning-write.cjs');
10
+ const { defaultLogger: logger } = require('./logger.cjs');
11
+
12
+ // Shared helper: extract a field value from STATE.md content.
13
+ // Supports both **Field:** bold and plain Field: format.
14
+ function stateExtractField(content, fieldName) {
15
+ const escaped = escapeRegex(fieldName);
16
+ const boldPattern = new RegExp(`\\*\\*${escaped}:\\*\\*\\s*(.+)`, 'i');
17
+ const boldMatch = content.match(boldPattern);
18
+ if (boldMatch) return boldMatch[1].trim();
19
+ const plainPattern = new RegExp(`^${escaped}:\\s*(.+)`, 'im');
20
+ const plainMatch = content.match(plainPattern);
21
+ return plainMatch ? plainMatch[1].trim() : null;
22
+ }
23
+
24
+ function cmdStateLoad(cwd, raw) {
25
+ const config = loadConfig(cwd);
26
+ const planningDir = path.join(cwd, '.planning');
27
+
28
+ let stateRaw = '';
29
+ try {
30
+ stateRaw = fs.readFileSync(path.join(planningDir, 'STATE.md'), 'utf-8');
31
+ } catch (err) {
32
+ logger.warn('Failed to read STATE.md in cmdStateLoad', { planningDir, error: err.message });
33
+ }
34
+
35
+ const configExists = fs.existsSync(path.join(planningDir, 'config.json'));
36
+ const roadmapExists = fs.existsSync(path.join(planningDir, 'ROADMAP.md'));
37
+ const stateExists = stateRaw.length > 0;
38
+
39
+ const result = {
40
+ config,
41
+ state_raw: stateRaw,
42
+ state_exists: stateExists,
43
+ roadmap_exists: roadmapExists,
44
+ config_exists: configExists,
45
+ };
46
+
47
+ // For --raw, output a condensed key=value format
48
+ if (raw) {
49
+ const c = config;
50
+ const lines = [
51
+ `model_profile=${c.model_profile}`,
52
+ `commit_docs=${c.commit_docs}`,
53
+ `branching_strategy=${c.branching_strategy}`,
54
+ `phase_branch_template=${c.phase_branch_template}`,
55
+ `milestone_branch_template=${c.milestone_branch_template}`,
56
+ `parallelization=${c.parallelization}`,
57
+ `research=${c.research}`,
58
+ `plan_checker=${c.plan_checker}`,
59
+ `verifier=${c.verifier}`,
60
+ `config_exists=${configExists}`,
61
+ `roadmap_exists=${roadmapExists}`,
62
+ `state_exists=${stateExists}`,
63
+ ];
64
+ process.stdout.write(lines.join('\n'));
65
+ process.exit(0);
66
+ }
67
+
68
+ output(result);
69
+ }
70
+
71
+ function cmdStateGet(cwd, section, raw) {
72
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
73
+ try {
74
+ const content = fs.readFileSync(statePath, 'utf-8');
75
+
76
+ if (!section) {
77
+ output({ content }, raw, content);
78
+ return;
79
+ }
80
+
81
+ // Try to find markdown section or field
82
+ const fieldEscaped = section.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
83
+
84
+ // Check for **field:** value (bold format)
85
+ const boldPattern = new RegExp(`\\*\\*${fieldEscaped}:\\*\\*\\s*(.*)`, 'i');
86
+ const boldMatch = content.match(boldPattern);
87
+ if (boldMatch) {
88
+ output({ [section]: boldMatch[1].trim() }, raw, boldMatch[1].trim());
89
+ return;
90
+ }
91
+
92
+ // Check for field: value (plain format)
93
+ const plainPattern = new RegExp(`^${fieldEscaped}:\\s*(.*)`, 'im');
94
+ const plainMatch = content.match(plainPattern);
95
+ if (plainMatch) {
96
+ output({ [section]: plainMatch[1].trim() }, raw, plainMatch[1].trim());
97
+ return;
98
+ }
99
+
100
+ // Check for ## Section
101
+ const sectionPattern = new RegExp(`##\\s*${fieldEscaped}\\s*\n([\\s\\S]*?)(?=\\n##|$)`, 'i');
102
+ const sectionMatch = content.match(sectionPattern);
103
+ if (sectionMatch) {
104
+ output({ [section]: sectionMatch[1].trim() }, raw, sectionMatch[1].trim());
105
+ return;
106
+ }
107
+
108
+ output({ error: `Section or field "${section}" not found` }, raw, '');
109
+ } catch (err) {
110
+ logger.error('STATE.md not found in cmdStateGet', { statePath, error: err.message });
111
+ error('STATE.md not found');
112
+ }
113
+ }
114
+
115
+ function readTextArgOrFile(cwd, value, filePath, label) {
116
+ if (!filePath) return value;
117
+
118
+ const resolvedPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
119
+ try {
120
+ return fs.readFileSync(resolvedPath, 'utf-8').trimEnd();
121
+ } catch {
122
+ throw new Error(`${label} file not found: ${filePath}`);
123
+ }
124
+ }
125
+
126
+ function cmdStatePatch(cwd, patches, raw) {
127
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
128
+ try {
129
+ let content = fs.readFileSync(statePath, 'utf-8');
130
+ const results = { updated: [], failed: [] };
131
+
132
+ for (const [field, value] of Object.entries(patches)) {
133
+ const fieldEscaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
134
+ // Try **Field:** bold format first, then plain Field: format
135
+ const boldPattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
136
+ const plainPattern = new RegExp(`(^${fieldEscaped}:\\s*)(.*)`, 'im');
137
+
138
+ if (boldPattern.test(content)) {
139
+ content = content.replace(boldPattern, (_match, prefix) => `${prefix}${value}`);
140
+ results.updated.push(field);
141
+ } else if (plainPattern.test(content)) {
142
+ content = content.replace(plainPattern, (_match, prefix) => `${prefix}${value}`);
143
+ results.updated.push(field);
144
+ } else {
145
+ results.failed.push(field);
146
+ }
147
+ }
148
+
149
+ if (results.updated.length > 0) {
150
+ writeStateMd(statePath, content, cwd);
151
+ }
152
+
153
+ output(results, raw, results.updated.length > 0 ? 'true' : 'false');
154
+ } catch (err) {
155
+ logger.error('Failed to patch STATE.md', { statePath, error: err.message });
156
+ error('STATE.md not found');
157
+ }
158
+ }
159
+
160
+ function cmdStateUpdate(cwd, field, value) {
161
+ if (!field || value === undefined) {
162
+ error('field and value required for state update');
163
+ }
164
+
165
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
166
+ try {
167
+ let content = fs.readFileSync(statePath, 'utf-8');
168
+ const fieldEscaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
169
+ // Try **Field:** bold format first, then plain Field: format
170
+ const boldPattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
171
+ const plainPattern = new RegExp(`(^${fieldEscaped}:\\s*)(.*)`, 'im');
172
+ if (boldPattern.test(content)) {
173
+ content = content.replace(boldPattern, (_match, prefix) => `${prefix}${value}`);
174
+ writeStateMd(statePath, content, cwd);
175
+ output({ updated: true });
176
+ } else if (plainPattern.test(content)) {
177
+ content = content.replace(plainPattern, (_match, prefix) => `${prefix}${value}`);
178
+ writeStateMd(statePath, content, cwd);
179
+ output({ updated: true });
180
+ } else {
181
+ output({ updated: false, reason: `Field "${field}" not found in STATE.md` });
182
+ }
183
+ } catch (err) {
184
+ logger.error('Failed to update STATE.md', { statePath, field, error: err.message });
185
+ output({ updated: false, reason: 'STATE.md not found' });
186
+ }
187
+ }
188
+
189
+ // ─── State Progression Engine ────────────────────────────────────────────────
190
+
191
+ function stateExtractField(content, fieldName) {
192
+ const escaped = fieldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
193
+ // Try **Field:** bold format first
194
+ const boldPattern = new RegExp(`\\*\\*${escaped}:\\*\\*\\s*(.+)`, 'i');
195
+ const boldMatch = content.match(boldPattern);
196
+ if (boldMatch) return boldMatch[1].trim();
197
+ // Fall back to plain Field: format
198
+ const plainPattern = new RegExp(`^${escaped}:\\s*(.+)`, 'im');
199
+ const plainMatch = content.match(plainPattern);
200
+ return plainMatch ? plainMatch[1].trim() : null;
201
+ }
202
+
203
+ function stateReplaceField(content, fieldName, newValue) {
204
+ const escaped = fieldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
205
+ // Try **Field:** bold format first, then plain Field: format
206
+ const boldPattern = new RegExp(`(\\*\\*${escaped}:\\*\\*\\s*)(.*)`, 'i');
207
+ if (boldPattern.test(content)) {
208
+ return content.replace(boldPattern, (_match, prefix) => `${prefix}${newValue}`);
209
+ }
210
+ const plainPattern = new RegExp(`(^${escaped}:\\s*)(.*)`, 'im');
211
+ if (plainPattern.test(content)) {
212
+ return content.replace(plainPattern, (_match, prefix) => `${prefix}${newValue}`);
213
+ }
214
+ return null;
215
+ }
216
+
217
+ function cmdStateAdvancePlan(cwd, raw) {
218
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
219
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
220
+
221
+ let content = fs.readFileSync(statePath, 'utf-8');
222
+ const currentPlan = parseInt(stateExtractField(content, 'Current Plan'), 10);
223
+ const totalPlans = parseInt(stateExtractField(content, 'Total Plans in Phase'), 10);
224
+ const today = new Date().toISOString().split('T')[0];
225
+
226
+ if (isNaN(currentPlan) || isNaN(totalPlans)) {
227
+ output({ error: 'Cannot parse Current Plan or Total Plans in Phase from STATE.md' }, raw);
228
+ return;
229
+ }
230
+
231
+ if (currentPlan >= totalPlans) {
232
+ content = stateReplaceField(content, 'Status', 'Phase complete — ready for verification') || content;
233
+ content = stateReplaceField(content, 'Last Activity', today) || content;
234
+ writeStateMd(statePath, content, cwd);
235
+ output({ advanced: false, reason: 'last_plan', current_plan: currentPlan, total_plans: totalPlans, status: 'ready_for_verification' }, raw, 'false');
236
+ } else {
237
+ const newPlan = currentPlan + 1;
238
+ content = stateReplaceField(content, 'Current Plan', String(newPlan)) || content;
239
+ content = stateReplaceField(content, 'Status', 'Ready to execute') || content;
240
+ content = stateReplaceField(content, 'Last Activity', today) || content;
241
+ writeStateMd(statePath, content, cwd);
242
+ output({ advanced: true, previous_plan: currentPlan, current_plan: newPlan, total_plans: totalPlans }, raw, 'true');
243
+ }
244
+ }
245
+
246
+ function cmdStateRecordMetric(cwd, options, raw) {
247
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
248
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
249
+
250
+ let content = fs.readFileSync(statePath, 'utf-8');
251
+ const { phase, plan, duration, tasks, files } = options;
252
+
253
+ if (!phase || !plan || !duration) {
254
+ output({ error: 'phase, plan, and duration required' }, raw);
255
+ return;
256
+ }
257
+
258
+ // Find Performance Metrics section and its table
259
+ const metricsPattern = /(##\s*Performance Metrics[\s\S]*?\n\|[^\n]+\n\|[-|\s]+\n)([\s\S]*?)(?=\n##|\n$|$)/i;
260
+ const metricsMatch = content.match(metricsPattern);
261
+
262
+ if (metricsMatch) {
263
+ let tableBody = metricsMatch[2].trimEnd();
264
+ const newRow = `| Phase ${phase} P${plan} | ${duration} | ${tasks || '-'} tasks | ${files || '-'} files |`;
265
+
266
+ if (tableBody.trim() === '' || tableBody.includes('None yet')) {
267
+ tableBody = newRow;
268
+ } else {
269
+ tableBody = tableBody + '\n' + newRow;
270
+ }
271
+
272
+ content = content.replace(metricsPattern, (_match, header) => `${header}${tableBody}\n`);
273
+ writeStateMd(statePath, content, cwd);
274
+ output({ recorded: true, phase, plan, duration }, raw, 'true');
275
+ } else {
276
+ output({ recorded: false, reason: 'Performance Metrics section not found in STATE.md' }, raw, 'false');
277
+ }
278
+ }
279
+
280
+ function cmdStateUpdateProgress(cwd, raw) {
281
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
282
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
283
+
284
+ let content = fs.readFileSync(statePath, 'utf-8');
285
+
286
+ // Count summaries across all phases
287
+ const phasesDir = path.join(cwd, '.planning', 'phases');
288
+ let totalPlans = 0;
289
+ let totalSummaries = 0;
290
+
291
+ if (fs.existsSync(phasesDir)) {
292
+ const phaseDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
293
+ .filter(e => e.isDirectory()).map(e => e.name);
294
+ for (const dir of phaseDirs) {
295
+ const files = fs.readdirSync(path.join(phasesDir, dir));
296
+ totalPlans += files.filter(f => f.match(/-PLAN\.md$/i)).length;
297
+ totalSummaries += files.filter(f => f.match(/-SUMMARY\.md$/i)).length;
298
+ }
299
+ }
300
+
301
+ const percent = totalPlans > 0 ? Math.min(100, Math.round(totalSummaries / totalPlans * 100)) : 0;
302
+ const barWidth = 10;
303
+ const filled = Math.round(percent / 100 * barWidth);
304
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
305
+ const progressStr = `[${bar}] ${percent}%`;
306
+
307
+ // Try **Progress:** bold format first, then plain Progress: format
308
+ const boldProgressPattern = /(\*\*Progress:\*\*\s*).*/i;
309
+ const plainProgressPattern = /^(Progress:\s*).*/im;
310
+ if (boldProgressPattern.test(content)) {
311
+ content = content.replace(boldProgressPattern, (_match, prefix) => `${prefix}${progressStr}`);
312
+ writeStateMd(statePath, content, cwd);
313
+ output({ updated: true, percent, completed: totalSummaries, total: totalPlans, bar: progressStr }, raw, progressStr);
314
+ } else if (plainProgressPattern.test(content)) {
315
+ content = content.replace(plainProgressPattern, (_match, prefix) => `${prefix}${progressStr}`);
316
+ writeStateMd(statePath, content, cwd);
317
+ output({ updated: true, percent, completed: totalSummaries, total: totalPlans, bar: progressStr }, raw, progressStr);
318
+ } else {
319
+ output({ updated: false, reason: 'Progress field not found in STATE.md' }, raw, 'false');
320
+ }
321
+ }
322
+
323
+ function cmdStateAddDecision(cwd, options, raw) {
324
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
325
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
326
+
327
+ const { phase, summary, summary_file, rationale, rationale_file } = options;
328
+ let summaryText = null;
329
+ let rationaleText = '';
330
+
331
+ try {
332
+ summaryText = readTextArgOrFile(cwd, summary, summary_file, 'summary');
333
+ rationaleText = readTextArgOrFile(cwd, rationale || '', rationale_file, 'rationale');
334
+ } catch (err) {
335
+ logger.error('Failed to read decision text', { error: err.message });
336
+ output({ added: false, reason: err.message }, raw, 'false');
337
+ return;
338
+ }
339
+
340
+ if (!summaryText) { output({ error: 'summary required' }, raw); return; }
341
+
342
+ let content = fs.readFileSync(statePath, 'utf-8');
343
+ const entry = `- [Phase ${phase || '?'}]: ${summaryText}${rationaleText ? ` — ${rationaleText}` : ''}`;
344
+
345
+ // Find Decisions section (various heading patterns)
346
+ const sectionPattern = /(###?\s*(?:Decisions|Decisions Made|Accumulated.*Decisions)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
347
+ const match = content.match(sectionPattern);
348
+
349
+ if (match) {
350
+ let sectionBody = match[2];
351
+ // Remove placeholders
352
+ sectionBody = sectionBody.replace(/None yet\.?\s*\n?/gi, '').replace(/No decisions yet\.?\s*\n?/gi, '');
353
+ sectionBody = sectionBody.trimEnd() + '\n' + entry + '\n';
354
+ content = content.replace(sectionPattern, (_match, header) => `${header}${sectionBody}`);
355
+ writeStateMd(statePath, content, cwd);
356
+ output({ added: true, decision: entry }, raw, 'true');
357
+ } else {
358
+ output({ added: false, reason: 'Decisions section not found in STATE.md' }, raw, 'false');
359
+ }
360
+ }
361
+
362
+ function cmdStateAddBlocker(cwd, text, raw) {
363
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
364
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
365
+ const blockerOptions = typeof text === 'object' && text !== null ? text : { text };
366
+ let blockerText = null;
367
+
368
+ try {
369
+ blockerText = readTextArgOrFile(cwd, blockerOptions.text, blockerOptions.text_file, 'blocker');
370
+ } catch (err) {
371
+ logger.error('Failed to read blocker text', { error: err.message });
372
+ output({ added: false, reason: err.message }, raw, 'false');
373
+ return;
374
+ }
375
+
376
+ if (!blockerText) { output({ error: 'text required' }, raw); return; }
377
+
378
+ let content = fs.readFileSync(statePath, 'utf-8');
379
+ const entry = `- ${blockerText}`;
380
+
381
+ const sectionPattern = /(###?\s*(?:Blockers|Blockers\/Concerns|Concerns)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
382
+ const match = content.match(sectionPattern);
383
+
384
+ if (match) {
385
+ let sectionBody = match[2];
386
+ sectionBody = sectionBody.replace(/None\.?\s*\n?/gi, '').replace(/None yet\.?\s*\n?/gi, '');
387
+ sectionBody = sectionBody.trimEnd() + '\n' + entry + '\n';
388
+ content = content.replace(sectionPattern, (_match, header) => `${header}${sectionBody}`);
389
+ writeStateMd(statePath, content, cwd);
390
+ output({ added: true, blocker: blockerText }, raw, 'true');
391
+ } else {
392
+ output({ added: false, reason: 'Blockers section not found in STATE.md' }, raw, 'false');
393
+ }
394
+ }
395
+
396
+ function cmdStateResolveBlocker(cwd, text, raw) {
397
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
398
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
399
+ if (!text) { output({ error: 'text required' }, raw); return; }
400
+
401
+ let content = fs.readFileSync(statePath, 'utf-8');
402
+
403
+ const sectionPattern = /(###?\s*(?:Blockers|Blockers\/Concerns|Concerns)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
404
+ const match = content.match(sectionPattern);
405
+
406
+ if (match) {
407
+ const sectionBody = match[2];
408
+ const lines = sectionBody.split('\n');
409
+ const filtered = lines.filter(line => {
410
+ if (!line.startsWith('- ')) return true;
411
+ return !line.toLowerCase().includes(text.toLowerCase());
412
+ });
413
+
414
+ let newBody = filtered.join('\n');
415
+ // If section is now empty, add placeholder
416
+ if (!newBody.trim() || !newBody.includes('- ')) {
417
+ newBody = 'None\n';
418
+ }
419
+
420
+ content = content.replace(sectionPattern, (_match, header) => `${header}${newBody}`);
421
+ writeStateMd(statePath, content, cwd);
422
+ output({ resolved: true, blocker: text }, raw, 'true');
423
+ } else {
424
+ output({ resolved: false, reason: 'Blockers section not found in STATE.md' }, raw, 'false');
425
+ }
426
+ }
427
+
428
+ function cmdStateRecordSession(cwd, options, raw) {
429
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
430
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
431
+
432
+ let content = fs.readFileSync(statePath, 'utf-8');
433
+ const now = new Date().toISOString();
434
+ const updated = [];
435
+
436
+ // Update Last session / Last Date
437
+ let result = stateReplaceField(content, 'Last session', now);
438
+ if (result) { content = result; updated.push('Last session'); }
439
+ result = stateReplaceField(content, 'Last Date', now);
440
+ if (result) { content = result; updated.push('Last Date'); }
441
+
442
+ // Update Stopped at
443
+ if (options.stopped_at) {
444
+ result = stateReplaceField(content, 'Stopped At', options.stopped_at);
445
+ if (!result) result = stateReplaceField(content, 'Stopped at', options.stopped_at);
446
+ if (result) { content = result; updated.push('Stopped At'); }
447
+ }
448
+
449
+ // Update Resume file
450
+ const resumeFile = options.resume_file || 'None';
451
+ result = stateReplaceField(content, 'Resume File', resumeFile);
452
+ if (!result) result = stateReplaceField(content, 'Resume file', resumeFile);
453
+ if (result) { content = result; updated.push('Resume File'); }
454
+
455
+ if (updated.length > 0) {
456
+ writeStateMd(statePath, content, cwd);
457
+ output({ recorded: true, updated }, raw, 'true');
458
+ } else {
459
+ output({ recorded: false, reason: 'No session fields found in STATE.md' }, raw, 'false');
460
+ }
461
+ }
462
+
463
+ function cmdStateSnapshot(cwd, raw) {
464
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
465
+
466
+ if (!fs.existsSync(statePath)) {
467
+ output({ error: 'STATE.md not found' }, raw);
468
+ return;
469
+ }
470
+
471
+ const content = fs.readFileSync(statePath, 'utf-8');
472
+
473
+ // Extract basic fields
474
+ const currentPhase = stateExtractField(content, 'Current Phase');
475
+ const currentPhaseName = stateExtractField(content, 'Current Phase Name');
476
+ const totalPhasesRaw = stateExtractField(content, 'Total Phases');
477
+ const currentPlan = stateExtractField(content, 'Current Plan');
478
+ const totalPlansRaw = stateExtractField(content, 'Total Plans in Phase');
479
+ const status = stateExtractField(content, 'Status');
480
+ const progressRaw = stateExtractField(content, 'Progress');
481
+ const lastActivity = stateExtractField(content, 'Last Activity');
482
+ const lastActivityDesc = stateExtractField(content, 'Last Activity Description');
483
+ const pausedAt = stateExtractField(content, 'Paused At');
484
+
485
+ // Parse numeric fields
486
+ const totalPhases = totalPhasesRaw ? parseInt(totalPhasesRaw, 10) : null;
487
+ const totalPlansInPhase = totalPlansRaw ? parseInt(totalPlansRaw, 10) : null;
488
+ const progressPercent = progressRaw ? parseInt(progressRaw.replace('%', ''), 10) : null;
489
+
490
+ // Extract decisions table
491
+ const decisions = [];
492
+ const decisionsMatch = content.match(/##\s*Decisions Made[\s\S]*?\n\|[^\n]+\n\|[-|\s]+\n([\s\S]*?)(?=\n##|\n$|$)/i);
493
+ if (decisionsMatch) {
494
+ const tableBody = decisionsMatch[1];
495
+ const rows = tableBody.trim().split('\n').filter(r => r.includes('|'));
496
+ for (const row of rows) {
497
+ const cells = row.split('|').map(c => c.trim()).filter(Boolean);
498
+ if (cells.length >= 3) {
499
+ decisions.push({
500
+ phase: cells[0],
501
+ summary: cells[1],
502
+ rationale: cells[2],
503
+ });
504
+ }
505
+ }
506
+ }
507
+
508
+ // Extract blockers list
509
+ const blockers = [];
510
+ const blockersMatch = content.match(/##\s*Blockers\s*\n([\s\S]*?)(?=\n##|$)/i);
511
+ if (blockersMatch) {
512
+ const blockersSection = blockersMatch[1];
513
+ const items = blockersSection.match(/^-\s+(.+)$/gm) || [];
514
+ for (const item of items) {
515
+ blockers.push(item.replace(/^-\s+/, '').trim());
516
+ }
517
+ }
518
+
519
+ // Extract session info
520
+ const session = {
521
+ last_date: null,
522
+ stopped_at: null,
523
+ resume_file: null,
524
+ };
525
+
526
+ const sessionMatch = content.match(/##\s*Session\s*\n([\s\S]*?)(?=\n##|$)/i);
527
+ if (sessionMatch) {
528
+ const sessionSection = sessionMatch[1];
529
+ const lastDateMatch = sessionSection.match(/\*\*Last Date:\*\*\s*(.+)/i)
530
+ || sessionSection.match(/^Last Date:\s*(.+)/im);
531
+ const stoppedAtMatch = sessionSection.match(/\*\*Stopped At:\*\*\s*(.+)/i)
532
+ || sessionSection.match(/^Stopped At:\s*(.+)/im);
533
+ const resumeFileMatch = sessionSection.match(/\*\*Resume File:\*\*\s*(.+)/i)
534
+ || sessionSection.match(/^Resume File:\s*(.+)/im);
535
+
536
+ if (lastDateMatch) session.last_date = lastDateMatch[1].trim();
537
+ if (stoppedAtMatch) session.stopped_at = stoppedAtMatch[1].trim();
538
+ if (resumeFileMatch) session.resume_file = resumeFileMatch[1].trim();
539
+ }
540
+
541
+ const result = {
542
+ current_phase: currentPhase,
543
+ current_phase_name: currentPhaseName,
544
+ total_phases: totalPhases,
545
+ current_plan: currentPlan,
546
+ total_plans_in_phase: totalPlansInPhase,
547
+ status,
548
+ progress_percent: progressPercent,
549
+ last_activity: lastActivity,
550
+ last_activity_desc: lastActivityDesc,
551
+ decisions,
552
+ blockers,
553
+ paused_at: pausedAt,
554
+ session,
555
+ };
556
+
557
+ output(result, raw);
558
+ }
559
+
560
+ // ─── State Frontmatter Sync ──────────────────────────────────────────────────
561
+
562
+ /**
563
+ * Extract machine-readable fields from STATE.md markdown body and build
564
+ * a YAML frontmatter object. Allows hooks and scripts to read state
565
+ * reliably via `state json` instead of fragile regex parsing.
566
+ */
567
+ function buildStateFrontmatter(bodyContent, cwd) {
568
+ const currentPhase = stateExtractField(bodyContent, 'Current Phase');
569
+ const currentPhaseName = stateExtractField(bodyContent, 'Current Phase Name');
570
+ const currentPlan = stateExtractField(bodyContent, 'Current Plan');
571
+ const totalPhasesRaw = stateExtractField(bodyContent, 'Total Phases');
572
+ const totalPlansRaw = stateExtractField(bodyContent, 'Total Plans in Phase');
573
+ const status = stateExtractField(bodyContent, 'Status');
574
+ const progressRaw = stateExtractField(bodyContent, 'Progress');
575
+ const lastActivity = stateExtractField(bodyContent, 'Last Activity');
576
+ const stoppedAt = stateExtractField(bodyContent, 'Stopped At') || stateExtractField(bodyContent, 'Stopped at');
577
+ const pausedAt = stateExtractField(bodyContent, 'Paused At');
578
+
579
+ let milestone = null;
580
+ let milestoneName = null;
581
+ if (cwd) {
582
+ try {
583
+ const info = getMilestoneInfo(cwd);
584
+ milestone = info.version;
585
+ milestoneName = info.name;
586
+ } catch (err) {
587
+ logger.warn('Failed to resolve milestone info while building state frontmatter', { error: err.message });
588
+ }
589
+ }
590
+
591
+ let totalPhases = totalPhasesRaw ? parseInt(totalPhasesRaw, 10) : null;
592
+ let completedPhases = null;
593
+ let totalPlans = totalPlansRaw ? parseInt(totalPlansRaw, 10) : null;
594
+ let completedPlans = null;
595
+
596
+ if (cwd) {
597
+ try {
598
+ const phasesDir = path.join(cwd, '.planning', 'phases');
599
+ if (fs.existsSync(phasesDir)) {
600
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
601
+ const phaseDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
602
+ .filter(e => e.isDirectory()).map(e => e.name)
603
+ .filter(isDirInMilestone);
604
+ let diskTotalPlans = 0;
605
+ let diskTotalSummaries = 0;
606
+ let diskCompletedPhases = 0;
607
+
608
+ for (const dir of phaseDirs) {
609
+ const files = fs.readdirSync(path.join(phasesDir, dir));
610
+ const plans = files.filter(f => f.match(/-PLAN\.md$/i)).length;
611
+ const summaries = files.filter(f => f.match(/-SUMMARY\.md$/i)).length;
612
+ diskTotalPlans += plans;
613
+ diskTotalSummaries += summaries;
614
+ if (plans > 0 && summaries >= plans) diskCompletedPhases++;
615
+ }
616
+ totalPhases = isDirInMilestone.phaseCount > 0
617
+ ? Math.max(phaseDirs.length, isDirInMilestone.phaseCount)
618
+ : phaseDirs.length;
619
+ completedPhases = diskCompletedPhases;
620
+ totalPlans = diskTotalPlans;
621
+ completedPlans = diskTotalSummaries;
622
+ }
623
+ } catch (err) {
624
+ logger.warn('Failed to compute phase progress from disk while building state frontmatter', { error: err.message });
625
+ }
626
+ }
627
+
628
+ let progressPercent = null;
629
+ if (progressRaw) {
630
+ const pctMatch = progressRaw.match(/(\d+)%/);
631
+ if (pctMatch) progressPercent = parseInt(pctMatch[1], 10);
632
+ }
633
+
634
+ // Normalize status to one of: planning, discussing, executing, verifying, paused, completed, unknown
635
+ let normalizedStatus = status || 'unknown';
636
+ const statusLower = (status || '').toLowerCase();
637
+ if (statusLower.includes('paused') || statusLower.includes('stopped') || pausedAt) {
638
+ normalizedStatus = 'paused';
639
+ } else if (statusLower.includes('executing') || statusLower.includes('in progress')) {
640
+ normalizedStatus = 'executing';
641
+ } else if (statusLower.includes('planning') || statusLower.includes('ready to plan')) {
642
+ normalizedStatus = 'planning';
643
+ } else if (statusLower.includes('discussing')) {
644
+ normalizedStatus = 'discussing';
645
+ } else if (statusLower.includes('verif')) {
646
+ normalizedStatus = 'verifying';
647
+ } else if (statusLower.includes('complete') || statusLower.includes('done')) {
648
+ normalizedStatus = 'completed';
649
+ } else if (statusLower.includes('ready to execute')) {
650
+ normalizedStatus = 'executing';
651
+ }
652
+
653
+ const fm = {
654
+ ez_state_version: '1.0',
655
+ };
656
+
657
+ if (milestone) fm.milestone = milestone;
658
+ if (milestoneName) fm.milestone_name = milestoneName;
659
+ if (currentPhase) fm.current_phase = currentPhase;
660
+ if (currentPhaseName) fm.current_phase_name = currentPhaseName;
661
+ if (currentPlan) fm.current_plan = currentPlan;
662
+ fm.status = normalizedStatus;
663
+ if (stoppedAt) fm.stopped_at = stoppedAt;
664
+ if (pausedAt) fm.paused_at = pausedAt;
665
+ fm.last_updated = new Date().toISOString();
666
+ if (lastActivity) fm.last_activity = lastActivity;
667
+
668
+ const progress = {};
669
+ if (totalPhases !== null) progress.total_phases = totalPhases;
670
+ if (completedPhases !== null) progress.completed_phases = completedPhases;
671
+ if (totalPlans !== null) progress.total_plans = totalPlans;
672
+ if (completedPlans !== null) progress.completed_plans = completedPlans;
673
+ if (progressPercent !== null) progress.percent = progressPercent;
674
+ if (Object.keys(progress).length > 0) fm.progress = progress;
675
+
676
+ return fm;
677
+ }
678
+
679
+ function stripFrontmatter(content) {
680
+ return content.replace(/^---\n[\s\S]*?\n---\n*/, '');
681
+ }
682
+
683
+ function syncStateFrontmatter(content, cwd) {
684
+ const body = stripFrontmatter(content);
685
+ const fm = buildStateFrontmatter(body, cwd);
686
+ const yamlStr = reconstructFrontmatter(fm);
687
+ return `---\n${yamlStr}\n---\n\n${body}`;
688
+ }
689
+
690
+ /**
691
+ * Write STATE.md with synchronized YAML frontmatter.
692
+ * All STATE.md writes should use this instead of raw writeFileSync.
693
+ */
694
+ function writeStateMd(statePath, content, cwd, options = {}) {
695
+ const synced = syncStateFrontmatter(content, cwd);
696
+ safePlanningWriteSync(statePath, synced, options);
697
+ }
698
+
699
+ function cmdStateJson(cwd, raw) {
700
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
701
+ if (!fs.existsSync(statePath)) {
702
+ output({ error: 'STATE.md not found' }, raw, 'STATE.md not found');
703
+ return;
704
+ }
705
+
706
+ const content = fs.readFileSync(statePath, 'utf-8');
707
+ const fm = extractFrontmatter(content);
708
+
709
+ if (!fm || Object.keys(fm).length === 0) {
710
+ const body = stripFrontmatter(content);
711
+ const built = buildStateFrontmatter(body, cwd);
712
+ output(built, raw, JSON.stringify(built, null, 2));
713
+ return;
714
+ }
715
+
716
+ output(fm, raw, JSON.stringify(fm, null, 2));
717
+ }
718
+
719
+ module.exports = {
720
+ stateExtractField,
721
+ stateReplaceField,
722
+ writeStateMd,
723
+ cmdStateLoad,
724
+ cmdStateGet,
725
+ cmdStatePatch,
726
+ cmdStateUpdate,
727
+ cmdStateAdvancePlan,
728
+ cmdStateRecordMetric,
729
+ cmdStateUpdateProgress,
730
+ cmdStateAddDecision,
731
+ cmdStateAddBlocker,
732
+ cmdStateResolveBlocker,
733
+ cmdStateRecordSession,
734
+ cmdStateSnapshot,
735
+ cmdStateJson,
736
+ };