gsd-opencode 1.10.2 → 1.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/agents/gsd-codebase-mapper.md +29 -3
  2. package/agents/gsd-debugger.md +19 -21
  3. package/agents/gsd-executor.md +213 -528
  4. package/agents/gsd-integration-checker.md +20 -0
  5. package/agents/gsd-phase-researcher.md +189 -267
  6. package/agents/gsd-plan-checker.md +278 -279
  7. package/agents/gsd-planner.md +299 -490
  8. package/agents/gsd-project-researcher.md +103 -345
  9. package/agents/gsd-research-synthesizer.md +5 -22
  10. package/agents/gsd-roadmapper.md +43 -6
  11. package/agents/gsd-verifier.md +158 -377
  12. package/{lib → bin/dm/lib}/constants.js +10 -3
  13. package/{src → bin/dm/src}/commands/install.js +5 -4
  14. package/{src → bin/dm/src}/commands/uninstall.js +3 -1
  15. package/{src → bin/dm/src}/services/backup-manager.js +1 -1
  16. package/{src → bin/dm/src}/services/config.js +1 -1
  17. package/{src → bin/dm/src}/services/file-ops.js +20 -4
  18. package/{src → bin/dm/src}/services/health-checker.js +3 -1
  19. package/{src → bin/dm/src}/services/repair-service.js +3 -1
  20. package/{src → bin/dm/src}/services/settings.js +1 -1
  21. package/{src → bin/dm/src}/services/update-service.js +2 -2
  22. package/bin/gsd-install.js +0 -0
  23. package/bin/gsd.js +9 -9
  24. package/commands/gsd/gsd-add-phase.md +43 -0
  25. package/commands/gsd/gsd-add-todo.md +47 -0
  26. package/commands/gsd/gsd-audit-milestone.md +36 -0
  27. package/commands/gsd/gsd-check-todos.md +45 -0
  28. package/commands/gsd/gsd-cleanup.md +18 -0
  29. package/commands/gsd/{complete-milestone.md → gsd-complete-milestone.md} +1 -1
  30. package/commands/gsd/{debug.md → gsd-debug.md} +16 -21
  31. package/commands/gsd/{discuss-phase.md → gsd-discuss-phase.md} +6 -9
  32. package/commands/gsd/gsd-execute-phase.md +41 -0
  33. package/commands/gsd/gsd-health.md +22 -0
  34. package/commands/gsd/gsd-help.md +22 -0
  35. package/commands/gsd/gsd-insert-phase.md +32 -0
  36. package/commands/gsd/gsd-join-discord.md +18 -0
  37. package/commands/gsd/{list-phase-assumptions.md → gsd-list-phase-assumptions.md} +3 -7
  38. package/commands/gsd/{map-codebase.md → gsd-map-codebase.md} +3 -3
  39. package/commands/gsd/gsd-new-milestone.md +44 -0
  40. package/commands/gsd/gsd-new-project.md +42 -0
  41. package/commands/gsd/gsd-pause-work.md +38 -0
  42. package/commands/gsd/gsd-plan-milestone-gaps.md +34 -0
  43. package/commands/gsd/gsd-plan-phase.md +44 -0
  44. package/commands/gsd/gsd-progress.md +24 -0
  45. package/commands/gsd/gsd-quick.md +41 -0
  46. package/commands/gsd/gsd-reapply-patches.md +119 -0
  47. package/commands/gsd/gsd-remove-phase.md +31 -0
  48. package/commands/gsd/{research-phase.md → gsd-research-phase.md} +38 -49
  49. package/commands/gsd/{resume-work.md → gsd-resume-work.md} +2 -2
  50. package/commands/gsd/gsd-set-profile.md +34 -0
  51. package/commands/gsd/gsd-settings.md +36 -0
  52. package/commands/gsd/gsd-update.md +37 -0
  53. package/commands/gsd/gsd-verify-work.md +38 -0
  54. package/get-shit-done/bin/gsd-tools.cjs +553 -0
  55. package/get-shit-done/bin/gsd-tools.test.cjs +2346 -0
  56. package/get-shit-done/bin/lib/commands.cjs +556 -0
  57. package/get-shit-done/bin/lib/config.cjs +162 -0
  58. package/get-shit-done/bin/lib/core.cjs +377 -0
  59. package/get-shit-done/bin/lib/frontmatter.cjs +299 -0
  60. package/get-shit-done/bin/lib/init.cjs +694 -0
  61. package/get-shit-done/bin/lib/milestone.cjs +215 -0
  62. package/get-shit-done/bin/lib/phase.cjs +877 -0
  63. package/get-shit-done/bin/lib/roadmap.cjs +298 -0
  64. package/get-shit-done/bin/lib/state.cjs +490 -0
  65. package/get-shit-done/bin/lib/template.cjs +222 -0
  66. package/get-shit-done/bin/lib/verify.cjs +772 -0
  67. package/get-shit-done/references/checkpoints.md +62 -364
  68. package/get-shit-done/references/decimal-phase-calculation.md +65 -0
  69. package/get-shit-done/references/git-integration.md +10 -16
  70. package/get-shit-done/references/git-planning-commit.md +38 -0
  71. package/get-shit-done/references/model-profile-resolution.md +34 -0
  72. package/get-shit-done/references/model-profiles.md +54 -66
  73. package/get-shit-done/references/phase-argument-parsing.md +61 -0
  74. package/get-shit-done/references/planning-config.md +112 -10
  75. package/get-shit-done/references/questioning.md +4 -0
  76. package/get-shit-done/references/ui-brand.md +1 -1
  77. package/get-shit-done/templates/UAT.md +1 -1
  78. package/get-shit-done/templates/VALIDATION.md +104 -0
  79. package/get-shit-done/templates/codebase/structure.md +6 -6
  80. package/get-shit-done/templates/config.json +37 -0
  81. package/get-shit-done/templates/context.md +2 -10
  82. package/get-shit-done/templates/continue-here.md +6 -6
  83. package/get-shit-done/templates/debug-subagent-prompt.md +2 -2
  84. package/get-shit-done/templates/discovery.md +6 -6
  85. package/get-shit-done/templates/milestone-archive.md +3 -3
  86. package/get-shit-done/templates/phase-prompt.md +9 -7
  87. package/get-shit-done/templates/planner-subagent-prompt.md +6 -6
  88. package/get-shit-done/templates/research-project/ARCHITECTURE.md +1 -1
  89. package/get-shit-done/templates/research.md +29 -6
  90. package/get-shit-done/templates/roadmap.md +1 -1
  91. package/get-shit-done/templates/state.md +0 -30
  92. package/get-shit-done/templates/summary-complex.md +59 -0
  93. package/get-shit-done/templates/summary-minimal.md +41 -0
  94. package/get-shit-done/templates/summary-standard.md +48 -0
  95. package/get-shit-done/templates/summary.md +16 -37
  96. package/get-shit-done/templates/user-setup.md +1 -13
  97. package/get-shit-done/templates/verification-report.md +5 -5
  98. package/get-shit-done/workflows/add-phase.md +111 -0
  99. package/{commands/gsd → get-shit-done/workflows}/add-todo.md +24 -60
  100. package/{commands/gsd → get-shit-done/workflows}/audit-milestone.md +83 -63
  101. package/{commands/gsd → get-shit-done/workflows}/check-todos.md +21 -73
  102. package/get-shit-done/workflows/cleanup.md +152 -0
  103. package/get-shit-done/workflows/complete-milestone.md +251 -312
  104. package/get-shit-done/workflows/diagnose-issues.md +6 -31
  105. package/get-shit-done/workflows/discovery-phase.md +11 -11
  106. package/get-shit-done/workflows/discuss-phase.md +156 -49
  107. package/get-shit-done/workflows/execute-phase.md +238 -396
  108. package/get-shit-done/workflows/execute-plan.md +180 -1609
  109. package/get-shit-done/workflows/health.md +156 -0
  110. package/{commands/gsd → get-shit-done/workflows}/help.md +33 -35
  111. package/get-shit-done/workflows/insert-phase.md +129 -0
  112. package/get-shit-done/workflows/list-phase-assumptions.md +3 -3
  113. package/get-shit-done/workflows/map-codebase.md +73 -80
  114. package/get-shit-done/workflows/new-milestone.md +382 -0
  115. package/{commands/gsd → get-shit-done/workflows}/new-project.md +281 -234
  116. package/get-shit-done/workflows/oc-set-profile.md +320 -0
  117. package/{commands/gsd → get-shit-done/workflows}/pause-work.md +31 -43
  118. package/{commands/gsd → get-shit-done/workflows}/plan-milestone-gaps.md +29 -50
  119. package/get-shit-done/workflows/plan-phase.md +478 -0
  120. package/{commands/gsd → get-shit-done/workflows}/progress.md +64 -47
  121. package/get-shit-done/workflows/quick.md +453 -0
  122. package/get-shit-done/workflows/remove-phase.md +154 -0
  123. package/get-shit-done/workflows/research-phase.md +73 -0
  124. package/get-shit-done/workflows/resume-project.md +17 -26
  125. package/get-shit-done/workflows/set-profile.md +80 -0
  126. package/get-shit-done/workflows/settings.md +213 -0
  127. package/get-shit-done/workflows/transition.md +84 -104
  128. package/{commands/gsd → get-shit-done/workflows}/update.md +70 -28
  129. package/get-shit-done/workflows/verify-phase.md +106 -492
  130. package/get-shit-done/workflows/verify-work.md +26 -53
  131. package/package.json +7 -4
  132. package/rules/gsd-oc-work-hard.md +36 -0
  133. package/skills/gsd-oc-select-model/SKILL.md +348 -0
  134. package/skills/gsd-oc-select-model/scripts/select-models.cjs +268 -0
  135. package/agents/gsd-set-model.md +0 -287
  136. package/agents/gsd-set-profile.md +0 -239
  137. package/agents/gsd-settings.md +0 -749
  138. package/bin/install.js +0 -323
  139. package/commands/gsd/add-phase.md +0 -207
  140. package/commands/gsd/execute-phase.md +0 -339
  141. package/commands/gsd/insert-phase.md +0 -227
  142. package/commands/gsd/new-milestone.md +0 -721
  143. package/commands/gsd/plan-phase.md +0 -525
  144. package/commands/gsd/quick.md +0 -309
  145. package/commands/gsd/remove-phase.md +0 -349
  146. package/commands/gsd/set-model.md +0 -77
  147. package/commands/gsd/set-profile.md +0 -46
  148. package/commands/gsd/settings.md +0 -33
  149. package/commands/gsd/verify-work.md +0 -219
  150. package/commands/gsd/whats-new.md +0 -124
  151. /package/{src → bin/dm/src}/commands/check.js +0 -0
  152. /package/{src → bin/dm/src}/commands/config.js +0 -0
  153. /package/{src → bin/dm/src}/commands/list.js +0 -0
  154. /package/{src → bin/dm/src}/commands/repair.js +0 -0
  155. /package/{src → bin/dm/src}/commands/update.js +0 -0
  156. /package/{src → bin/dm/src}/services/manifest-manager.js +0 -0
  157. /package/{src → bin/dm/src}/services/migration-service.js +0 -0
  158. /package/{src → bin/dm/src}/services/scope-manager.js +0 -0
  159. /package/{src → bin/dm/src}/services/structure-detector.js +0 -0
  160. /package/{src → bin/dm/src}/utils/hash.js +0 -0
  161. /package/{src → bin/dm/src}/utils/interactive.js +0 -0
  162. /package/{src → bin/dm/src}/utils/logger.js +0 -0
  163. /package/{src → bin/dm/src}/utils/npm-registry.js +0 -0
  164. /package/{src → bin/dm/src}/utils/path-resolver.js +0 -0
@@ -0,0 +1,490 @@
1
+ /**
2
+ * State — STATE.md operations and progression engine
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { loadConfig, output, error } = require('./core.cjs');
8
+
9
+ function cmdStateLoad(cwd, raw) {
10
+ const config = loadConfig(cwd);
11
+ const planningDir = path.join(cwd, '.planning');
12
+
13
+ let stateRaw = '';
14
+ try {
15
+ stateRaw = fs.readFileSync(path.join(planningDir, 'STATE.md'), 'utf-8');
16
+ } catch {}
17
+
18
+ const configExists = fs.existsSync(path.join(planningDir, 'config.json'));
19
+ const roadmapExists = fs.existsSync(path.join(planningDir, 'ROADMAP.md'));
20
+ const stateExists = stateRaw.length > 0;
21
+
22
+ const result = {
23
+ config,
24
+ state_raw: stateRaw,
25
+ state_exists: stateExists,
26
+ roadmap_exists: roadmapExists,
27
+ config_exists: configExists,
28
+ };
29
+
30
+ // For --raw, output a condensed key=value format
31
+ if (raw) {
32
+ const c = config;
33
+ const lines = [
34
+ `model_profile=${c.model_profile}`,
35
+ `commit_docs=${c.commit_docs}`,
36
+ `branching_strategy=${c.branching_strategy}`,
37
+ `phase_branch_template=${c.phase_branch_template}`,
38
+ `milestone_branch_template=${c.milestone_branch_template}`,
39
+ `parallelization=${c.parallelization}`,
40
+ `research=${c.research}`,
41
+ `plan_checker=${c.plan_checker}`,
42
+ `verifier=${c.verifier}`,
43
+ `config_exists=${configExists}`,
44
+ `roadmap_exists=${roadmapExists}`,
45
+ `state_exists=${stateExists}`,
46
+ ];
47
+ process.stdout.write(lines.join('\n'));
48
+ process.exit(0);
49
+ }
50
+
51
+ output(result);
52
+ }
53
+
54
+ function cmdStateGet(cwd, section, raw) {
55
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
56
+ try {
57
+ const content = fs.readFileSync(statePath, 'utf-8');
58
+
59
+ if (!section) {
60
+ output({ content }, raw, content);
61
+ return;
62
+ }
63
+
64
+ // Try to find markdown section or field
65
+ const fieldEscaped = section.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
66
+
67
+ // Check for **field:** value
68
+ const fieldPattern = new RegExp(`\\*\\*${fieldEscaped}:\\*\\*\\s*(.*)`, 'i');
69
+ const fieldMatch = content.match(fieldPattern);
70
+ if (fieldMatch) {
71
+ output({ [section]: fieldMatch[1].trim() }, raw, fieldMatch[1].trim());
72
+ return;
73
+ }
74
+
75
+ // Check for ## Section
76
+ const sectionPattern = new RegExp(`##\\s*${fieldEscaped}\\s*\n([\\s\\S]*?)(?=\\n##|$)`, 'i');
77
+ const sectionMatch = content.match(sectionPattern);
78
+ if (sectionMatch) {
79
+ output({ [section]: sectionMatch[1].trim() }, raw, sectionMatch[1].trim());
80
+ return;
81
+ }
82
+
83
+ output({ error: `Section or field "${section}" not found` }, raw, '');
84
+ } catch {
85
+ error('STATE.md not found');
86
+ }
87
+ }
88
+
89
+ function cmdStatePatch(cwd, patches, raw) {
90
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
91
+ try {
92
+ let content = fs.readFileSync(statePath, 'utf-8');
93
+ const results = { updated: [], failed: [] };
94
+
95
+ for (const [field, value] of Object.entries(patches)) {
96
+ const fieldEscaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
97
+ const pattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
98
+
99
+ if (pattern.test(content)) {
100
+ content = content.replace(pattern, `$1${value}`);
101
+ results.updated.push(field);
102
+ } else {
103
+ results.failed.push(field);
104
+ }
105
+ }
106
+
107
+ if (results.updated.length > 0) {
108
+ fs.writeFileSync(statePath, content, 'utf-8');
109
+ }
110
+
111
+ output(results, raw, results.updated.length > 0 ? 'true' : 'false');
112
+ } catch {
113
+ error('STATE.md not found');
114
+ }
115
+ }
116
+
117
+ function cmdStateUpdate(cwd, field, value) {
118
+ if (!field || value === undefined) {
119
+ error('field and value required for state update');
120
+ }
121
+
122
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
123
+ try {
124
+ let content = fs.readFileSync(statePath, 'utf-8');
125
+ const fieldEscaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
126
+ const pattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
127
+ if (pattern.test(content)) {
128
+ content = content.replace(pattern, `$1${value}`);
129
+ fs.writeFileSync(statePath, content, 'utf-8');
130
+ output({ updated: true });
131
+ } else {
132
+ output({ updated: false, reason: `Field "${field}" not found in STATE.md` });
133
+ }
134
+ } catch {
135
+ output({ updated: false, reason: 'STATE.md not found' });
136
+ }
137
+ }
138
+
139
+ // ─── State Progression Engine ────────────────────────────────────────────────
140
+
141
+ function stateExtractField(content, fieldName) {
142
+ const pattern = new RegExp(`\\*\\*${fieldName}:\\*\\*\\s*(.+)`, 'i');
143
+ const match = content.match(pattern);
144
+ return match ? match[1].trim() : null;
145
+ }
146
+
147
+ function stateReplaceField(content, fieldName, newValue) {
148
+ const escaped = fieldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
149
+ const pattern = new RegExp(`(\\*\\*${escaped}:\\*\\*\\s*)(.*)`, 'i');
150
+ if (pattern.test(content)) {
151
+ return content.replace(pattern, `$1${newValue}`);
152
+ }
153
+ return null;
154
+ }
155
+
156
+ function cmdStateAdvancePlan(cwd, raw) {
157
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
158
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
159
+
160
+ let content = fs.readFileSync(statePath, 'utf-8');
161
+ const currentPlan = parseInt(stateExtractField(content, 'Current Plan'), 10);
162
+ const totalPlans = parseInt(stateExtractField(content, 'Total Plans in Phase'), 10);
163
+ const today = new Date().toISOString().split('T')[0];
164
+
165
+ if (isNaN(currentPlan) || isNaN(totalPlans)) {
166
+ output({ error: 'Cannot parse Current Plan or Total Plans in Phase from STATE.md' }, raw);
167
+ return;
168
+ }
169
+
170
+ if (currentPlan >= totalPlans) {
171
+ content = stateReplaceField(content, 'Status', 'Phase complete — ready for verification') || content;
172
+ content = stateReplaceField(content, 'Last Activity', today) || content;
173
+ fs.writeFileSync(statePath, content, 'utf-8');
174
+ output({ advanced: false, reason: 'last_plan', current_plan: currentPlan, total_plans: totalPlans, status: 'ready_for_verification' }, raw, 'false');
175
+ } else {
176
+ const newPlan = currentPlan + 1;
177
+ content = stateReplaceField(content, 'Current Plan', String(newPlan)) || content;
178
+ content = stateReplaceField(content, 'Status', 'Ready to execute') || content;
179
+ content = stateReplaceField(content, 'Last Activity', today) || content;
180
+ fs.writeFileSync(statePath, content, 'utf-8');
181
+ output({ advanced: true, previous_plan: currentPlan, current_plan: newPlan, total_plans: totalPlans }, raw, 'true');
182
+ }
183
+ }
184
+
185
+ function cmdStateRecordMetric(cwd, options, raw) {
186
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
187
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
188
+
189
+ let content = fs.readFileSync(statePath, 'utf-8');
190
+ const { phase, plan, duration, tasks, files } = options;
191
+
192
+ if (!phase || !plan || !duration) {
193
+ output({ error: 'phase, plan, and duration required' }, raw);
194
+ return;
195
+ }
196
+
197
+ // Find Performance Metrics section and its table
198
+ const metricsPattern = /(##\s*Performance Metrics[\s\S]*?\n\|[^\n]+\n\|[-|\s]+\n)([\s\S]*?)(?=\n##|\n$|$)/i;
199
+ const metricsMatch = content.match(metricsPattern);
200
+
201
+ if (metricsMatch) {
202
+ const tableHeader = metricsMatch[1];
203
+ let tableBody = metricsMatch[2].trimEnd();
204
+ const newRow = `| Phase ${phase} P${plan} | ${duration} | ${tasks || '-'} tasks | ${files || '-'} files |`;
205
+
206
+ if (tableBody.trim() === '' || tableBody.includes('None yet')) {
207
+ tableBody = newRow;
208
+ } else {
209
+ tableBody = tableBody + '\n' + newRow;
210
+ }
211
+
212
+ content = content.replace(metricsPattern, `${tableHeader}${tableBody}\n`);
213
+ fs.writeFileSync(statePath, content, 'utf-8');
214
+ output({ recorded: true, phase, plan, duration }, raw, 'true');
215
+ } else {
216
+ output({ recorded: false, reason: 'Performance Metrics section not found in STATE.md' }, raw, 'false');
217
+ }
218
+ }
219
+
220
+ function cmdStateUpdateProgress(cwd, raw) {
221
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
222
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
223
+
224
+ let content = fs.readFileSync(statePath, 'utf-8');
225
+
226
+ // Count summaries across all phases
227
+ const phasesDir = path.join(cwd, '.planning', 'phases');
228
+ let totalPlans = 0;
229
+ let totalSummaries = 0;
230
+
231
+ if (fs.existsSync(phasesDir)) {
232
+ const phaseDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
233
+ .filter(e => e.isDirectory()).map(e => e.name);
234
+ for (const dir of phaseDirs) {
235
+ const files = fs.readdirSync(path.join(phasesDir, dir));
236
+ totalPlans += files.filter(f => f.match(/-PLAN\.md$/i)).length;
237
+ totalSummaries += files.filter(f => f.match(/-SUMMARY\.md$/i)).length;
238
+ }
239
+ }
240
+
241
+ const percent = totalPlans > 0 ? Math.round(totalSummaries / totalPlans * 100) : 0;
242
+ const barWidth = 10;
243
+ const filled = Math.round(percent / 100 * barWidth);
244
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
245
+ const progressStr = `[${bar}] ${percent}%`;
246
+
247
+ const progressPattern = /(\*\*Progress:\*\*\s*).*/i;
248
+ if (progressPattern.test(content)) {
249
+ content = content.replace(progressPattern, `$1${progressStr}`);
250
+ fs.writeFileSync(statePath, content, 'utf-8');
251
+ output({ updated: true, percent, completed: totalSummaries, total: totalPlans, bar: progressStr }, raw, progressStr);
252
+ } else {
253
+ output({ updated: false, reason: 'Progress field not found in STATE.md' }, raw, 'false');
254
+ }
255
+ }
256
+
257
+ function cmdStateAddDecision(cwd, options, raw) {
258
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
259
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
260
+
261
+ const { phase, summary, rationale } = options;
262
+ if (!summary) { output({ error: 'summary required' }, raw); return; }
263
+
264
+ let content = fs.readFileSync(statePath, 'utf-8');
265
+ const entry = `- [Phase ${phase || '?'}]: ${summary}${rationale ? ` — ${rationale}` : ''}`;
266
+
267
+ // Find Decisions section (various heading patterns)
268
+ const sectionPattern = /(###?\s*(?:Decisions|Decisions Made|Accumulated.*Decisions)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
269
+ const match = content.match(sectionPattern);
270
+
271
+ if (match) {
272
+ let sectionBody = match[2];
273
+ // Remove placeholders
274
+ sectionBody = sectionBody.replace(/None yet\.?\s*\n?/gi, '').replace(/No decisions yet\.?\s*\n?/gi, '');
275
+ sectionBody = sectionBody.trimEnd() + '\n' + entry + '\n';
276
+ content = content.replace(sectionPattern, `${match[1]}${sectionBody}`);
277
+ fs.writeFileSync(statePath, content, 'utf-8');
278
+ output({ added: true, decision: entry }, raw, 'true');
279
+ } else {
280
+ output({ added: false, reason: 'Decisions section not found in STATE.md' }, raw, 'false');
281
+ }
282
+ }
283
+
284
+ function cmdStateAddBlocker(cwd, text, raw) {
285
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
286
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
287
+ if (!text) { output({ error: 'text required' }, raw); return; }
288
+
289
+ let content = fs.readFileSync(statePath, 'utf-8');
290
+ const entry = `- ${text}`;
291
+
292
+ const sectionPattern = /(###?\s*(?:Blockers|Blockers\/Concerns|Concerns)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
293
+ const match = content.match(sectionPattern);
294
+
295
+ if (match) {
296
+ let sectionBody = match[2];
297
+ sectionBody = sectionBody.replace(/None\.?\s*\n?/gi, '').replace(/None yet\.?\s*\n?/gi, '');
298
+ sectionBody = sectionBody.trimEnd() + '\n' + entry + '\n';
299
+ content = content.replace(sectionPattern, `${match[1]}${sectionBody}`);
300
+ fs.writeFileSync(statePath, content, 'utf-8');
301
+ output({ added: true, blocker: text }, raw, 'true');
302
+ } else {
303
+ output({ added: false, reason: 'Blockers section not found in STATE.md' }, raw, 'false');
304
+ }
305
+ }
306
+
307
+ function cmdStateResolveBlocker(cwd, text, raw) {
308
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
309
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
310
+ if (!text) { output({ error: 'text required' }, raw); return; }
311
+
312
+ let content = fs.readFileSync(statePath, 'utf-8');
313
+
314
+ const sectionPattern = /(###?\s*(?:Blockers|Blockers\/Concerns|Concerns)\s*\n)([\s\S]*?)(?=\n###?|\n##[^#]|$)/i;
315
+ const match = content.match(sectionPattern);
316
+
317
+ if (match) {
318
+ const sectionBody = match[2];
319
+ const lines = sectionBody.split('\n');
320
+ const filtered = lines.filter(line => {
321
+ if (!line.startsWith('- ')) return true;
322
+ return !line.toLowerCase().includes(text.toLowerCase());
323
+ });
324
+
325
+ let newBody = filtered.join('\n');
326
+ // If section is now empty, add placeholder
327
+ if (!newBody.trim() || !newBody.includes('- ')) {
328
+ newBody = 'None\n';
329
+ }
330
+
331
+ content = content.replace(sectionPattern, `${match[1]}${newBody}`);
332
+ fs.writeFileSync(statePath, content, 'utf-8');
333
+ output({ resolved: true, blocker: text }, raw, 'true');
334
+ } else {
335
+ output({ resolved: false, reason: 'Blockers section not found in STATE.md' }, raw, 'false');
336
+ }
337
+ }
338
+
339
+ function cmdStateRecordSession(cwd, options, raw) {
340
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
341
+ if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
342
+
343
+ let content = fs.readFileSync(statePath, 'utf-8');
344
+ const now = new Date().toISOString();
345
+ const updated = [];
346
+
347
+ // Update Last session / Last Date
348
+ let result = stateReplaceField(content, 'Last session', now);
349
+ if (result) { content = result; updated.push('Last session'); }
350
+ result = stateReplaceField(content, 'Last Date', now);
351
+ if (result) { content = result; updated.push('Last Date'); }
352
+
353
+ // Update Stopped at
354
+ if (options.stopped_at) {
355
+ result = stateReplaceField(content, 'Stopped At', options.stopped_at);
356
+ if (!result) result = stateReplaceField(content, 'Stopped at', options.stopped_at);
357
+ if (result) { content = result; updated.push('Stopped At'); }
358
+ }
359
+
360
+ // Update Resume file
361
+ const resumeFile = options.resume_file || 'None';
362
+ result = stateReplaceField(content, 'Resume File', resumeFile);
363
+ if (!result) result = stateReplaceField(content, 'Resume file', resumeFile);
364
+ if (result) { content = result; updated.push('Resume File'); }
365
+
366
+ if (updated.length > 0) {
367
+ fs.writeFileSync(statePath, content, 'utf-8');
368
+ output({ recorded: true, updated }, raw, 'true');
369
+ } else {
370
+ output({ recorded: false, reason: 'No session fields found in STATE.md' }, raw, 'false');
371
+ }
372
+ }
373
+
374
+ function cmdStateSnapshot(cwd, raw) {
375
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
376
+
377
+ if (!fs.existsSync(statePath)) {
378
+ output({ error: 'STATE.md not found' }, raw);
379
+ return;
380
+ }
381
+
382
+ const content = fs.readFileSync(statePath, 'utf-8');
383
+
384
+ // Helper to extract **Field:** value patterns
385
+ const extractField = (fieldName) => {
386
+ const pattern = new RegExp(`\\*\\*${fieldName}:\\*\\*\\s*(.+)`, 'i');
387
+ const match = content.match(pattern);
388
+ return match ? match[1].trim() : null;
389
+ };
390
+
391
+ // Extract basic fields
392
+ const currentPhase = extractField('Current Phase');
393
+ const currentPhaseName = extractField('Current Phase Name');
394
+ const totalPhasesRaw = extractField('Total Phases');
395
+ const currentPlan = extractField('Current Plan');
396
+ const totalPlansRaw = extractField('Total Plans in Phase');
397
+ const status = extractField('Status');
398
+ const progressRaw = extractField('Progress');
399
+ const lastActivity = extractField('Last Activity');
400
+ const lastActivityDesc = extractField('Last Activity Description');
401
+ const pausedAt = extractField('Paused At');
402
+
403
+ // Parse numeric fields
404
+ const totalPhases = totalPhasesRaw ? parseInt(totalPhasesRaw, 10) : null;
405
+ const totalPlansInPhase = totalPlansRaw ? parseInt(totalPlansRaw, 10) : null;
406
+ const progressPercent = progressRaw ? parseInt(progressRaw.replace('%', ''), 10) : null;
407
+
408
+ // Extract decisions table
409
+ const decisions = [];
410
+ const decisionsMatch = content.match(/##\s*Decisions Made[\s\S]*?\n\|[^\n]+\n\|[-|\s]+\n([\s\S]*?)(?=\n##|\n$|$)/i);
411
+ if (decisionsMatch) {
412
+ const tableBody = decisionsMatch[1];
413
+ const rows = tableBody.trim().split('\n').filter(r => r.includes('|'));
414
+ for (const row of rows) {
415
+ const cells = row.split('|').map(c => c.trim()).filter(Boolean);
416
+ if (cells.length >= 3) {
417
+ decisions.push({
418
+ phase: cells[0],
419
+ summary: cells[1],
420
+ rationale: cells[2],
421
+ });
422
+ }
423
+ }
424
+ }
425
+
426
+ // Extract blockers list
427
+ const blockers = [];
428
+ const blockersMatch = content.match(/##\s*Blockers\s*\n([\s\S]*?)(?=\n##|$)/i);
429
+ if (blockersMatch) {
430
+ const blockersSection = blockersMatch[1];
431
+ const items = blockersSection.match(/^-\s+(.+)$/gm) || [];
432
+ for (const item of items) {
433
+ blockers.push(item.replace(/^-\s+/, '').trim());
434
+ }
435
+ }
436
+
437
+ // Extract session info
438
+ const session = {
439
+ last_date: null,
440
+ stopped_at: null,
441
+ resume_file: null,
442
+ };
443
+
444
+ const sessionMatch = content.match(/##\s*Session\s*\n([\s\S]*?)(?=\n##|$)/i);
445
+ if (sessionMatch) {
446
+ const sessionSection = sessionMatch[1];
447
+ const lastDateMatch = sessionSection.match(/\*\*Last Date:\*\*\s*(.+)/i);
448
+ const stoppedAtMatch = sessionSection.match(/\*\*Stopped At:\*\*\s*(.+)/i);
449
+ const resumeFileMatch = sessionSection.match(/\*\*Resume File:\*\*\s*(.+)/i);
450
+
451
+ if (lastDateMatch) session.last_date = lastDateMatch[1].trim();
452
+ if (stoppedAtMatch) session.stopped_at = stoppedAtMatch[1].trim();
453
+ if (resumeFileMatch) session.resume_file = resumeFileMatch[1].trim();
454
+ }
455
+
456
+ const result = {
457
+ current_phase: currentPhase,
458
+ current_phase_name: currentPhaseName,
459
+ total_phases: totalPhases,
460
+ current_plan: currentPlan,
461
+ total_plans_in_phase: totalPlansInPhase,
462
+ status,
463
+ progress_percent: progressPercent,
464
+ last_activity: lastActivity,
465
+ last_activity_desc: lastActivityDesc,
466
+ decisions,
467
+ blockers,
468
+ paused_at: pausedAt,
469
+ session,
470
+ };
471
+
472
+ output(result, raw);
473
+ }
474
+
475
+ module.exports = {
476
+ stateExtractField,
477
+ stateReplaceField,
478
+ cmdStateLoad,
479
+ cmdStateGet,
480
+ cmdStatePatch,
481
+ cmdStateUpdate,
482
+ cmdStateAdvancePlan,
483
+ cmdStateRecordMetric,
484
+ cmdStateUpdateProgress,
485
+ cmdStateAddDecision,
486
+ cmdStateAddBlocker,
487
+ cmdStateResolveBlocker,
488
+ cmdStateRecordSession,
489
+ cmdStateSnapshot,
490
+ };