specsmd 0.0.0-dev.8 → 0.0.0-dev.80

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 (77) hide show
  1. package/README.md +175 -231
  2. package/flows/aidlc/commands/construction-agent.md +5 -1
  3. package/flows/aidlc/commands/inception-agent.md +4 -0
  4. package/flows/aidlc/commands/master-agent.md +4 -0
  5. package/flows/aidlc/commands/operations-agent.md +4 -0
  6. package/flows/aidlc/memory-bank.yaml +2 -1
  7. package/{scripts/artifact-validator.js → flows/aidlc/scripts/artifact-validator.cjs} +3 -3
  8. package/{scripts/bolt-complete.js → flows/aidlc/scripts/bolt-complete.cjs} +36 -5
  9. package/{scripts/status-integrity.js → flows/aidlc/scripts/status-integrity.cjs} +5 -5
  10. package/flows/aidlc/skills/construction/bolt-list.md +1 -1
  11. package/flows/aidlc/skills/construction/bolt-start.md +3 -3
  12. package/flows/aidlc/skills/construction/bolt-status.md +1 -1
  13. package/flows/aidlc/skills/construction/prototype-apply.md +311 -0
  14. package/flows/aidlc/skills/inception/bolt-plan.md +2 -0
  15. package/flows/aidlc/skills/inception/vibe-to-spec.md +410 -0
  16. package/flows/aidlc/skills/master/analyze-context.md +1 -1
  17. package/flows/aidlc/templates/construction/bolt-template.md +2 -2
  18. package/flows/aidlc/templates/construction/bolt-types/ddd-construction-bolt.md +73 -11
  19. package/flows/aidlc/templates/standards/decision-index-template.md +32 -0
  20. package/flows/fire/README.md +19 -0
  21. package/flows/fire/agents/builder/agent.md +260 -0
  22. package/flows/fire/agents/builder/skills/code-review/SKILL.md +257 -0
  23. package/flows/fire/agents/builder/skills/code-review/references/auto-fix-rules.md +218 -0
  24. package/flows/fire/agents/builder/skills/code-review/references/review-categories.md +154 -0
  25. package/flows/fire/agents/builder/skills/code-review/templates/review-report.md.hbs +120 -0
  26. package/flows/fire/agents/builder/skills/run-execute/SKILL.md +705 -0
  27. package/flows/fire/agents/builder/skills/run-execute/scripts/complete-run.cjs +781 -0
  28. package/flows/fire/agents/builder/skills/run-execute/scripts/init-run.cjs +457 -0
  29. package/flows/fire/agents/builder/skills/run-execute/scripts/update-phase.cjs +239 -0
  30. package/flows/fire/agents/builder/skills/run-execute/templates/plan.md.hbs +61 -0
  31. package/flows/fire/agents/builder/skills/run-execute/templates/test-report.md.hbs +81 -0
  32. package/flows/fire/agents/builder/skills/run-plan/SKILL.md +378 -0
  33. package/flows/fire/agents/builder/skills/run-status/SKILL.md +96 -0
  34. package/flows/fire/agents/builder/skills/walkthrough-generate/SKILL.md +264 -0
  35. package/flows/fire/agents/builder/skills/walkthrough-generate/templates/walkthrough.md.hbs +176 -0
  36. package/flows/fire/agents/orchestrator/agent.md +144 -0
  37. package/flows/fire/agents/orchestrator/skills/project-init/SKILL.md +226 -0
  38. package/flows/fire/agents/orchestrator/skills/project-init/templates/coding-standards.md.hbs +149 -0
  39. package/flows/fire/agents/orchestrator/skills/project-init/templates/constitution.md.hbs +43 -0
  40. package/flows/fire/agents/orchestrator/skills/project-init/templates/system-architecture.md.hbs +101 -0
  41. package/flows/fire/agents/orchestrator/skills/project-init/templates/tech-stack.md.hbs +136 -0
  42. package/flows/fire/agents/orchestrator/skills/project-init/templates/testing-standards.md.hbs +94 -0
  43. package/flows/fire/agents/orchestrator/skills/route/SKILL.md +146 -0
  44. package/flows/fire/agents/orchestrator/skills/status/SKILL.md +696 -0
  45. package/flows/fire/agents/planner/agent.md +143 -0
  46. package/flows/fire/agents/planner/skills/design-doc-generate/SKILL.md +156 -0
  47. package/flows/fire/agents/planner/skills/design-doc-generate/templates/design.md.hbs +124 -0
  48. package/flows/fire/agents/planner/skills/intent-capture/SKILL.md +125 -0
  49. package/flows/fire/agents/planner/skills/intent-capture/templates/brief.md.hbs +40 -0
  50. package/flows/fire/agents/planner/skills/work-item-decompose/SKILL.md +166 -0
  51. package/flows/fire/agents/planner/skills/work-item-decompose/templates/work-item.md.hbs +40 -0
  52. package/flows/fire/commands/fire-builder.md +56 -0
  53. package/flows/fire/commands/fire-planner.md +48 -0
  54. package/flows/fire/commands/fire.md +46 -0
  55. package/flows/fire/memory-bank.yaml +240 -0
  56. package/flows/fire/quick-start.md +146 -0
  57. package/flows/simple/README.md +190 -0
  58. package/flows/simple/agents/agent.md +404 -0
  59. package/flows/simple/commands/agent.md +60 -0
  60. package/flows/simple/context-config.yaml +34 -0
  61. package/flows/simple/memory-bank.yaml +66 -0
  62. package/flows/simple/quick-start.md +231 -0
  63. package/flows/simple/skills/design.md +96 -0
  64. package/flows/simple/skills/execute.md +190 -0
  65. package/flows/simple/skills/requirements.md +94 -0
  66. package/flows/simple/skills/tasks.md +136 -0
  67. package/flows/simple/templates/design-template.md +138 -0
  68. package/flows/simple/templates/requirements-template.md +85 -0
  69. package/flows/simple/templates/tasks-template.md +104 -0
  70. package/lib/analytics/tracker.js +6 -2
  71. package/lib/constants.js +20 -8
  72. package/lib/installer.js +19 -15
  73. package/lib/installers/KiroInstaller.js +55 -0
  74. package/lib/installers/OpenCodeInstaller.js +9 -1
  75. package/lib/installers/ToolInstaller.js +4 -1
  76. package/lib/installers/WindsurfInstaller.js +0 -54
  77. package/package.json +3 -52
@@ -0,0 +1,781 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * FIRE Run Completion Script
5
+ *
6
+ * Supports both single and batch/wide runs.
7
+ *
8
+ * For single runs: Completes the run and removes from runs.active[].
9
+ * For batch/wide runs:
10
+ * - --complete-item: Marks current work item done, moves to next
11
+ * - --complete-run: Marks all items done and finalizes entire run
12
+ *
13
+ * Usage:
14
+ * Complete current item: node complete-run.cjs <rootPath> <runId> --complete-item [options]
15
+ * Complete entire run: node complete-run.cjs <rootPath> <runId> --complete-run [options]
16
+ * Complete (single/auto): node complete-run.cjs <rootPath> <runId> [options]
17
+ *
18
+ * Options:
19
+ * --files-created=JSON - JSON array of {path, purpose}
20
+ * --files-modified=JSON - JSON array of {path, changes}
21
+ * --decisions=JSON - JSON array of {decision, choice, rationale}
22
+ * --tests=N - Number of tests added
23
+ * --coverage=N - Coverage percentage
24
+ * --force - Override phase guard (skip review phase check)
25
+ */
26
+
27
+ const fs = require('fs');
28
+ const path = require('path');
29
+ const yaml = require('yaml');
30
+
31
+ // =============================================================================
32
+ // Error Helper
33
+ // =============================================================================
34
+
35
+ function fireError(message, code, suggestion) {
36
+ const err = new Error(`FIRE Error [${code}]: ${message} ${suggestion}`);
37
+ err.code = code;
38
+ err.suggestion = suggestion;
39
+ return err;
40
+ }
41
+
42
+ // =============================================================================
43
+ // Validation
44
+ // =============================================================================
45
+
46
+ function validateInputs(rootPath, runId) {
47
+ if (!rootPath || typeof rootPath !== 'string' || rootPath.trim() === '') {
48
+ throw fireError('rootPath is required.', 'COMPLETE_001', 'Provide a valid project root path.');
49
+ }
50
+
51
+ if (!runId || typeof runId !== 'string' || runId.trim() === '') {
52
+ throw fireError('runId is required.', 'COMPLETE_002', 'Provide the run ID to complete.');
53
+ }
54
+
55
+ if (!fs.existsSync(rootPath)) {
56
+ throw fireError(
57
+ `Project root not found: "${rootPath}".`,
58
+ 'COMPLETE_003',
59
+ 'Ensure the path exists and is accessible.'
60
+ );
61
+ }
62
+ }
63
+
64
+ function validateFireProject(rootPath, runId) {
65
+ const fireDir = path.join(rootPath, '.specs-fire');
66
+ const statePath = path.join(fireDir, 'state.yaml');
67
+ const runsPath = path.join(fireDir, 'runs');
68
+ const runPath = path.join(runsPath, runId);
69
+ const runLogPath = path.join(runPath, 'run.md');
70
+
71
+ if (!fs.existsSync(fireDir)) {
72
+ throw fireError(
73
+ `FIRE project not initialized at: "${rootPath}".`,
74
+ 'COMPLETE_010',
75
+ 'Run fire-init first to initialize the project.'
76
+ );
77
+ }
78
+
79
+ if (!fs.existsSync(statePath)) {
80
+ throw fireError(
81
+ `State file not found at: "${statePath}".`,
82
+ 'COMPLETE_011',
83
+ 'The project may be corrupted. Try re-initializing.'
84
+ );
85
+ }
86
+
87
+ if (!fs.existsSync(runPath)) {
88
+ throw fireError(
89
+ `Run folder not found: "${runPath}".`,
90
+ 'COMPLETE_012',
91
+ `Ensure run "${runId}" was properly initialized.`
92
+ );
93
+ }
94
+
95
+ if (!fs.existsSync(runLogPath)) {
96
+ throw fireError(
97
+ `Run log not found: "${runLogPath}".`,
98
+ 'COMPLETE_013',
99
+ `The run may have been partially initialized.`
100
+ );
101
+ }
102
+
103
+ return { statePath, runPath, runLogPath };
104
+ }
105
+
106
+ // =============================================================================
107
+ // Frontmatter Helpers
108
+ // =============================================================================
109
+
110
+ /**
111
+ * Parse YAML frontmatter from markdown content.
112
+ * Returns { frontmatter: object, body: string } or null if no frontmatter.
113
+ */
114
+ function parseFrontmatter(content) {
115
+ const match = content.match(/^---\n([\s\S]*?)\n---/);
116
+ if (!match) return null;
117
+
118
+ try {
119
+ const frontmatter = yaml.parse(match[1]);
120
+ const body = content.slice(match[0].length);
121
+ return { frontmatter, body };
122
+ } catch (err) {
123
+ return null;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Reconstruct markdown content from frontmatter and body.
129
+ */
130
+ function buildMarkdownWithFrontmatter(frontmatter, body) {
131
+ return `---\n${yaml.stringify(frontmatter)}---${body}`;
132
+ }
133
+
134
+ // =============================================================================
135
+ // Markdown Frontmatter Sync
136
+ // =============================================================================
137
+
138
+ /**
139
+ * Update work item markdown file frontmatter with new status.
140
+ */
141
+ function updateWorkItemMarkdown(rootPath, intentId, workItemId, status, runId, completedAt) {
142
+ const filePath = path.join(rootPath, '.specs-fire', 'intents', intentId, 'work-items', `${workItemId}.md`);
143
+
144
+ if (!fs.existsSync(filePath)) {
145
+ // File doesn't exist - not an error, just skip
146
+ return false;
147
+ }
148
+
149
+ try {
150
+ const content = fs.readFileSync(filePath, 'utf8');
151
+ const parsed = parseFrontmatter(content);
152
+
153
+ if (!parsed) {
154
+ // No valid frontmatter - skip
155
+ return false;
156
+ }
157
+
158
+ // Update frontmatter fields
159
+ parsed.frontmatter.status = status;
160
+ if (runId) parsed.frontmatter.run_id = runId;
161
+ if (completedAt && status === 'completed') {
162
+ parsed.frontmatter.completed_at = completedAt;
163
+ }
164
+
165
+ const newContent = buildMarkdownWithFrontmatter(parsed.frontmatter, parsed.body);
166
+ fs.writeFileSync(filePath, newContent);
167
+ return true;
168
+ } catch (err) {
169
+ // Log but don't fail - markdown sync is best-effort
170
+ console.error(`Warning: Could not update work item markdown ${filePath}: ${err.message}`);
171
+ return false;
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Update intent brief.md frontmatter based on work item statuses.
177
+ */
178
+ function updateIntentMarkdown(rootPath, intentId, state) {
179
+ const filePath = path.join(rootPath, '.specs-fire', 'intents', intentId, 'brief.md');
180
+
181
+ if (!fs.existsSync(filePath)) {
182
+ return false;
183
+ }
184
+
185
+ try {
186
+ // Determine intent status from its work items
187
+ const intent = state.intents?.find(i => i.id === intentId);
188
+ if (!intent || !Array.isArray(intent.work_items)) {
189
+ return false;
190
+ }
191
+
192
+ const allCompleted = intent.work_items.every(wi => wi.status === 'completed');
193
+ const anyInProgress = intent.work_items.some(wi => wi.status === 'in_progress');
194
+
195
+ let newStatus = 'pending';
196
+ if (allCompleted) {
197
+ newStatus = 'completed';
198
+ } else if (anyInProgress || intent.work_items.some(wi => wi.status === 'completed')) {
199
+ newStatus = 'in_progress';
200
+ }
201
+
202
+ const content = fs.readFileSync(filePath, 'utf8');
203
+ const parsed = parseFrontmatter(content);
204
+
205
+ if (!parsed) {
206
+ return false;
207
+ }
208
+
209
+ // Only update if status actually changed
210
+ if (parsed.frontmatter.status === newStatus) {
211
+ return false;
212
+ }
213
+
214
+ parsed.frontmatter.status = newStatus;
215
+ if (allCompleted) {
216
+ parsed.frontmatter.completed_at = new Date().toISOString();
217
+ }
218
+
219
+ const newContent = buildMarkdownWithFrontmatter(parsed.frontmatter, parsed.body);
220
+ fs.writeFileSync(filePath, newContent);
221
+ return true;
222
+ } catch (err) {
223
+ console.error(`Warning: Could not update intent markdown ${filePath}: ${err.message}`);
224
+ return false;
225
+ }
226
+ }
227
+
228
+ // =============================================================================
229
+ // State Operations
230
+ // =============================================================================
231
+
232
+ function readState(statePath) {
233
+ try {
234
+ const content = fs.readFileSync(statePath, 'utf8');
235
+ const state = yaml.parse(content);
236
+ if (!state || typeof state !== 'object') {
237
+ throw fireError('State file is empty or invalid.', 'COMPLETE_020', 'Check state.yaml format.');
238
+ }
239
+ return state;
240
+ } catch (err) {
241
+ if (err.code && err.code.startsWith('COMPLETE_')) throw err;
242
+ throw fireError(
243
+ `Failed to read state file: ${err.message}`,
244
+ 'COMPLETE_021',
245
+ 'Check file permissions and YAML syntax.'
246
+ );
247
+ }
248
+ }
249
+
250
+ function writeState(statePath, state) {
251
+ try {
252
+ fs.writeFileSync(statePath, yaml.stringify(state));
253
+ } catch (err) {
254
+ throw fireError(
255
+ `Failed to write state file: ${err.message}`,
256
+ 'COMPLETE_022',
257
+ 'Check file permissions and disk space.'
258
+ );
259
+ }
260
+ }
261
+
262
+ // =============================================================================
263
+ // Run Log Operations
264
+ // =============================================================================
265
+
266
+ /**
267
+ * Update run.md using proper YAML parsing instead of fragile regex.
268
+ * This ensures frontmatter updates work regardless of field order or formatting.
269
+ */
270
+ function updateRunLog(runLogPath, activeRun, params, completedTime, isFullCompletion) {
271
+ let content;
272
+ try {
273
+ content = fs.readFileSync(runLogPath, 'utf8');
274
+ } catch (err) {
275
+ throw fireError(
276
+ `Failed to read run log: ${err.message}`,
277
+ 'COMPLETE_030',
278
+ 'Check file permissions.'
279
+ );
280
+ }
281
+
282
+ // Parse frontmatter using YAML (robust approach)
283
+ const parsed = parseFrontmatter(content);
284
+ if (!parsed) {
285
+ throw fireError(
286
+ 'Invalid run.md format - no valid YAML frontmatter found.',
287
+ 'COMPLETE_032',
288
+ 'Ensure run.md has valid ---\\n...\\n--- frontmatter.'
289
+ );
290
+ }
291
+
292
+ let { frontmatter, body } = parsed;
293
+
294
+ // Update frontmatter fields
295
+ if (isFullCompletion) {
296
+ frontmatter.status = 'completed';
297
+ frontmatter.completed = completedTime;
298
+ }
299
+
300
+ frontmatter.current_item = activeRun.current_item || null;
301
+
302
+ // Update work_items array in frontmatter
303
+ if (activeRun.work_items && Array.isArray(activeRun.work_items)) {
304
+ frontmatter.work_items = activeRun.work_items.map(item => ({
305
+ id: item.id,
306
+ intent: item.intent,
307
+ mode: item.mode,
308
+ status: item.status,
309
+ }));
310
+ }
311
+
312
+ // Update markdown body sections
313
+ // Update Work Items section
314
+ if (activeRun.work_items && Array.isArray(activeRun.work_items)) {
315
+ const workItemsLines = activeRun.work_items.map((item, i) =>
316
+ `${i + 1}. **${item.id}** (${item.mode}) — ${item.status}`
317
+ ).join('\n');
318
+
319
+ body = body.replace(
320
+ /## Work Items\n[\s\S]*?(?=\n## )/,
321
+ `## Work Items\n${workItemsLines}\n\n`
322
+ );
323
+
324
+ // Update Current Item section
325
+ if (activeRun.current_item) {
326
+ const currentItem = activeRun.work_items.find(i => i.id === activeRun.current_item);
327
+ if (currentItem) {
328
+ body = body.replace(
329
+ /## Current Item\n[^\n]+/,
330
+ `## Current Item\n${currentItem.id} (${currentItem.mode})`
331
+ );
332
+ }
333
+ } else {
334
+ body = body.replace(
335
+ /## Current Item\n[^\n]+/,
336
+ `## Current Item\n(all completed)`
337
+ );
338
+ }
339
+ }
340
+
341
+ // Format file lists (only on full completion)
342
+ if (isFullCompletion) {
343
+ const filesCreatedText = params.filesCreated.length > 0
344
+ ? params.filesCreated.map(f => `- \`${f.path}\`: ${f.purpose || '(no purpose)'}`).join('\n')
345
+ : '(none)';
346
+
347
+ const filesModifiedText = params.filesModified.length > 0
348
+ ? params.filesModified.map(f => `- \`${f.path}\`: ${f.changes || '(no changes)'}`).join('\n')
349
+ : '(none)';
350
+
351
+ const decisionsText = params.decisions.length > 0
352
+ ? params.decisions.map(d => `- **${d.decision}**: ${d.choice} (${d.rationale || 'no rationale'})`).join('\n')
353
+ : '(none)';
354
+
355
+ // Replace placeholder sections
356
+ body = body.replace('## Files Created\n(none yet)', `## Files Created\n${filesCreatedText}`);
357
+ body = body.replace('## Files Modified\n(none yet)', `## Files Modified\n${filesModifiedText}`);
358
+ body = body.replace('## Decisions\n(none yet)', `## Decisions\n${decisionsText}`);
359
+
360
+ // Add summary if not present
361
+ if (!body.includes('## Summary')) {
362
+ const itemCount = activeRun.work_items ? activeRun.work_items.length : 1;
363
+ body += `
364
+
365
+ ## Summary
366
+
367
+ - Work items completed: ${itemCount}
368
+ - Files created: ${params.filesCreated.length}
369
+ - Files modified: ${params.filesModified.length}
370
+ - Tests added: ${params.testsAdded}
371
+ - Coverage: ${params.coverage}%
372
+ - Completed: ${completedTime}
373
+ `;
374
+ }
375
+ }
376
+
377
+ // Reconstruct content with updated frontmatter and body
378
+ const newContent = buildMarkdownWithFrontmatter(frontmatter, body);
379
+
380
+ try {
381
+ fs.writeFileSync(runLogPath, newContent);
382
+ } catch (err) {
383
+ throw fireError(
384
+ `Failed to write run log: ${err.message}`,
385
+ 'COMPLETE_031',
386
+ 'Check file permissions.'
387
+ );
388
+ }
389
+ }
390
+
391
+ // =============================================================================
392
+ // Complete Current Item (for batch runs)
393
+ // =============================================================================
394
+
395
+ function completeCurrentItem(rootPath, runId, params = {}, options = {}) {
396
+ const completionParams = {
397
+ filesCreated: params.filesCreated || [],
398
+ filesModified: params.filesModified || [],
399
+ decisions: params.decisions || [],
400
+ testsAdded: params.testsAdded || 0,
401
+ coverage: params.coverage || 0,
402
+ };
403
+ const force = options.force || false;
404
+
405
+ validateInputs(rootPath, runId);
406
+ const { statePath, runLogPath } = validateFireProject(rootPath, runId);
407
+ const state = readState(statePath);
408
+
409
+ // Find run in active runs list
410
+ const activeRuns = state.runs?.active || [];
411
+ const runIndex = activeRuns.findIndex(r => r.id === runId);
412
+
413
+ if (runIndex === -1) {
414
+ throw fireError(
415
+ `Run "${runId}" not found in active runs.`,
416
+ 'COMPLETE_040',
417
+ 'The run may have already been completed or was never started.'
418
+ );
419
+ }
420
+
421
+ const activeRun = activeRuns[runIndex];
422
+ const completedTime = new Date().toISOString();
423
+ const workItems = activeRun.work_items || [];
424
+ const currentItemId = activeRun.current_item;
425
+
426
+ // Find and mark current item as completed
427
+ let currentItemIndex = -1;
428
+ for (let i = 0; i < workItems.length; i++) {
429
+ if (workItems[i].id === currentItemId) {
430
+ workItems[i].status = 'completed';
431
+ workItems[i].completed_at = completedTime;
432
+ currentItemIndex = i;
433
+ break;
434
+ }
435
+ }
436
+
437
+ if (currentItemIndex === -1) {
438
+ throw fireError(
439
+ `Current item "${currentItemId}" not found in work items.`,
440
+ 'COMPLETE_050',
441
+ 'The run state may be corrupted.'
442
+ );
443
+ }
444
+
445
+ // Phase guard: item must be at 'review' phase before completion
446
+ const currentPhase = workItems[currentItemIndex].current_phase;
447
+ if (!force && currentPhase !== 'review') {
448
+ throw fireError(
449
+ `Cannot complete item "${currentItemId}" — current phase is "${currentPhase || 'unknown'}", not "review".`,
450
+ 'COMPLETE_051',
451
+ 'The item must reach the review phase before completion. Use --force to override.'
452
+ );
453
+ }
454
+
455
+ // Find next pending item
456
+ let nextItem = null;
457
+ for (let i = currentItemIndex + 1; i < workItems.length; i++) {
458
+ if (workItems[i].status === 'pending') {
459
+ workItems[i].status = 'in_progress';
460
+ workItems[i].current_phase = 'plan';
461
+ nextItem = workItems[i];
462
+ break;
463
+ }
464
+ }
465
+
466
+ // Update active run in list
467
+ activeRun.work_items = workItems;
468
+ activeRun.current_item = nextItem ? nextItem.id : null;
469
+ state.runs.active[runIndex] = activeRun;
470
+
471
+ // Update run log
472
+ updateRunLog(runLogPath, activeRun, completionParams, completedTime, false);
473
+
474
+ // Sync markdown frontmatter for completed work item
475
+ const completedWorkItem = workItems.find(wi => wi.id === currentItemId);
476
+ if (completedWorkItem) {
477
+ updateWorkItemMarkdown(
478
+ rootPath,
479
+ completedWorkItem.intent,
480
+ currentItemId,
481
+ 'completed',
482
+ runId,
483
+ completedTime
484
+ );
485
+ // Update intent status based on its work items
486
+ updateIntentMarkdown(rootPath, completedWorkItem.intent, state);
487
+ }
488
+
489
+ // Also update next item's markdown to in_progress
490
+ if (nextItem) {
491
+ updateWorkItemMarkdown(rootPath, nextItem.intent, nextItem.id, 'in_progress', null, null);
492
+ }
493
+
494
+ // Save state
495
+ writeState(statePath, state);
496
+
497
+ return {
498
+ success: true,
499
+ runId: runId,
500
+ completedItem: currentItemId,
501
+ nextItem: nextItem ? nextItem.id : null,
502
+ remainingItems: workItems.filter(i => i.status === 'pending').length,
503
+ allItemsCompleted: nextItem === null,
504
+ completedAt: completedTime,
505
+ };
506
+ }
507
+
508
+ // =============================================================================
509
+ // Complete Entire Run
510
+ // =============================================================================
511
+
512
+ function completeRun(rootPath, runId, params = {}, options = {}) {
513
+ const completionParams = {
514
+ filesCreated: params.filesCreated || [],
515
+ filesModified: params.filesModified || [],
516
+ decisions: params.decisions || [],
517
+ testsAdded: params.testsAdded || 0,
518
+ coverage: params.coverage || 0,
519
+ };
520
+ const force = options.force || false;
521
+
522
+ validateInputs(rootPath, runId);
523
+ const { statePath, runLogPath } = validateFireProject(rootPath, runId);
524
+ const state = readState(statePath);
525
+
526
+ // Initialize runs structure if needed
527
+ if (!state.runs) {
528
+ state.runs = { active: [], completed: [] };
529
+ }
530
+ if (!Array.isArray(state.runs.active)) {
531
+ state.runs.active = [];
532
+ }
533
+ if (!Array.isArray(state.runs.completed)) {
534
+ state.runs.completed = [];
535
+ }
536
+
537
+ // Find run in active runs list
538
+ const runIndex = state.runs.active.findIndex(r => r.id === runId);
539
+
540
+ if (runIndex === -1) {
541
+ throw fireError(
542
+ `Run "${runId}" not found in active runs.`,
543
+ 'COMPLETE_040',
544
+ 'The run may have already been completed or was never started.'
545
+ );
546
+ }
547
+
548
+ const activeRun = state.runs.active[runIndex];
549
+ const completedTime = new Date().toISOString();
550
+ const workItems = activeRun.work_items || [];
551
+ const scope = activeRun.scope || 'single';
552
+
553
+ // Phase guard: all non-completed items must be at 'review' phase
554
+ if (!force) {
555
+ const notReady = workItems.filter(
556
+ item => item.status !== 'completed' && item.current_phase !== 'review'
557
+ );
558
+ if (notReady.length > 0) {
559
+ const list = notReady.map(i => `${i.id} (phase: ${i.current_phase || 'unknown'})`).join(', ');
560
+ throw fireError(
561
+ `Cannot complete run — ${notReady.length} item(s) have not reached review phase: ${list}.`,
562
+ 'COMPLETE_060',
563
+ 'All items must reach the review phase before run completion. Use --force to override.'
564
+ );
565
+ }
566
+ }
567
+
568
+ // Mark all items as completed
569
+ for (const item of workItems) {
570
+ if (item.status !== 'completed') {
571
+ item.status = 'completed';
572
+ item.completed_at = completedTime;
573
+ }
574
+ }
575
+
576
+ activeRun.work_items = workItems;
577
+ activeRun.current_item = null;
578
+
579
+ // Update run log
580
+ updateRunLog(runLogPath, activeRun, completionParams, completedTime, true);
581
+
582
+ // Build completed run record
583
+ const completedRun = {
584
+ id: runId,
585
+ scope: scope,
586
+ work_items: workItems.map(i => ({
587
+ id: i.id,
588
+ intent: i.intent,
589
+ mode: i.mode,
590
+ })),
591
+ started: activeRun.started,
592
+ completed: completedTime,
593
+ };
594
+
595
+ // Check for duplicate (idempotency)
596
+ const alreadyRecorded = state.runs.completed.some(r => r.id === runId);
597
+
598
+ // Update work item status in intents (state.yaml)
599
+ const affectedIntents = new Set();
600
+ if (Array.isArray(state.intents)) {
601
+ for (const workItem of workItems) {
602
+ for (const intent of state.intents) {
603
+ if (intent.id === workItem.intent && Array.isArray(intent.work_items)) {
604
+ for (const wi of intent.work_items) {
605
+ if (wi.id === workItem.id) {
606
+ wi.status = 'completed';
607
+ wi.run_id = runId;
608
+ wi.completed_at = completedTime;
609
+ affectedIntents.add(intent.id);
610
+ break;
611
+ }
612
+ }
613
+ }
614
+ }
615
+ }
616
+ }
617
+
618
+ // Remove from active runs and add to completed
619
+ state.runs.active.splice(runIndex, 1);
620
+ if (!alreadyRecorded) {
621
+ state.runs.completed.push(completedRun);
622
+ }
623
+
624
+ // Save state first (so markdown sync has correct state)
625
+ writeState(statePath, state);
626
+
627
+ // Sync markdown frontmatter for all completed work items
628
+ for (const workItem of workItems) {
629
+ updateWorkItemMarkdown(
630
+ rootPath,
631
+ workItem.intent,
632
+ workItem.id,
633
+ 'completed',
634
+ runId,
635
+ workItem.completed_at || completedTime
636
+ );
637
+ }
638
+
639
+ // Update intent markdown for all affected intents
640
+ for (const intentId of affectedIntents) {
641
+ updateIntentMarkdown(rootPath, intentId, state);
642
+ }
643
+
644
+ return {
645
+ success: true,
646
+ runId: runId,
647
+ scope: scope,
648
+ workItemsCompleted: workItems.length,
649
+ completedAt: completedTime,
650
+ filesCreated: completionParams.filesCreated.length,
651
+ filesModified: completionParams.filesModified.length,
652
+ testsAdded: completionParams.testsAdded,
653
+ coverage: completionParams.coverage,
654
+ };
655
+ }
656
+
657
+ // =============================================================================
658
+ // CLI Argument Parsing
659
+ // =============================================================================
660
+
661
+ function parseArgs(args) {
662
+ const result = {
663
+ rootPath: args[0],
664
+ runId: args[1],
665
+ completeItem: false,
666
+ completeRunFlag: false,
667
+ force: false,
668
+ filesCreated: [],
669
+ filesModified: [],
670
+ decisions: [],
671
+ testsAdded: 0,
672
+ coverage: 0,
673
+ };
674
+
675
+ for (let i = 2; i < args.length; i++) {
676
+ const arg = args[i];
677
+ if (arg === '--complete-item') {
678
+ result.completeItem = true;
679
+ } else if (arg === '--complete-run') {
680
+ result.completeRunFlag = true;
681
+ } else if (arg === '--force') {
682
+ result.force = true;
683
+ } else if (arg.startsWith('--files-created=')) {
684
+ try {
685
+ result.filesCreated = JSON.parse(arg.substring('--files-created='.length));
686
+ } catch (e) {
687
+ console.error('Warning: Could not parse --files-created JSON');
688
+ }
689
+ } else if (arg.startsWith('--files-modified=')) {
690
+ try {
691
+ result.filesModified = JSON.parse(arg.substring('--files-modified='.length));
692
+ } catch (e) {
693
+ console.error('Warning: Could not parse --files-modified JSON');
694
+ }
695
+ } else if (arg.startsWith('--decisions=')) {
696
+ try {
697
+ result.decisions = JSON.parse(arg.substring('--decisions='.length));
698
+ } catch (e) {
699
+ console.error('Warning: Could not parse --decisions JSON');
700
+ }
701
+ } else if (arg.startsWith('--tests=')) {
702
+ result.testsAdded = parseInt(arg.substring('--tests='.length), 10) || 0;
703
+ } else if (arg.startsWith('--coverage=')) {
704
+ result.coverage = parseFloat(arg.substring('--coverage='.length)) || 0;
705
+ }
706
+ }
707
+
708
+ return result;
709
+ }
710
+
711
+ function printUsage() {
712
+ console.error('Usage:');
713
+ console.error(' Complete current item: node complete-run.cjs <rootPath> <runId> --complete-item [options]');
714
+ console.error(' Complete entire run: node complete-run.cjs <rootPath> <runId> --complete-run [options]');
715
+ console.error(' Auto (single runs): node complete-run.cjs <rootPath> <runId> [options]');
716
+ console.error('');
717
+ console.error('Arguments:');
718
+ console.error(' rootPath - Project root directory');
719
+ console.error(' runId - Run ID to complete (e.g., run-003)');
720
+ console.error('');
721
+ console.error('Flags:');
722
+ console.error(' --complete-item - Complete only the current work item (batch/wide runs)');
723
+ console.error(' --complete-run - Complete the entire run');
724
+ console.error(' --force - Override phase guard (skip review phase check)');
725
+ console.error('');
726
+ console.error('Options:');
727
+ console.error(' --files-created=JSON - JSON array of {path, purpose}');
728
+ console.error(' --files-modified=JSON - JSON array of {path, changes}');
729
+ console.error(' --decisions=JSON - JSON array of {decision, choice, rationale}');
730
+ console.error(' --tests=N - Number of tests added');
731
+ console.error(' --coverage=N - Coverage percentage');
732
+ console.error('');
733
+ console.error('Examples:');
734
+ console.error(' node complete-run.cjs /project run-003 --complete-item');
735
+ console.error(' node complete-run.cjs /project run-003 --complete-run --tests=5 --coverage=85');
736
+ }
737
+
738
+ // =============================================================================
739
+ // CLI Interface
740
+ // =============================================================================
741
+
742
+ if (require.main === module) {
743
+ const args = process.argv.slice(2);
744
+
745
+ if (args.length < 2) {
746
+ printUsage();
747
+ process.exit(1);
748
+ }
749
+
750
+ const params = parseArgs(args);
751
+
752
+ try {
753
+ const cliOptions = { force: params.force };
754
+ let result;
755
+ if (params.completeItem) {
756
+ result = completeCurrentItem(params.rootPath, params.runId, {
757
+ filesCreated: params.filesCreated,
758
+ filesModified: params.filesModified,
759
+ decisions: params.decisions,
760
+ testsAdded: params.testsAdded,
761
+ coverage: params.coverage,
762
+ }, cliOptions);
763
+ } else {
764
+ // Default: complete entire run
765
+ result = completeRun(params.rootPath, params.runId, {
766
+ filesCreated: params.filesCreated,
767
+ filesModified: params.filesModified,
768
+ decisions: params.decisions,
769
+ testsAdded: params.testsAdded,
770
+ coverage: params.coverage,
771
+ }, cliOptions);
772
+ }
773
+ console.log(JSON.stringify(result, null, 2));
774
+ process.exit(0);
775
+ } catch (err) {
776
+ console.error(err.message);
777
+ process.exit(1);
778
+ }
779
+ }
780
+
781
+ module.exports = { completeRun, completeCurrentItem };