pi-spine 1.0.2 → 1.2.0

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 (129) hide show
  1. package/README.md +61 -489
  2. package/bin/get-version.mjs +1 -13
  3. package/bin/spine-batch.mjs +162 -51
  4. package/bin/spine-cli/batch.mjs +3 -3
  5. package/bin/spine-cli/lane-logs.mjs +24 -0
  6. package/bin/spine-cli/scenarios.mjs +298 -0
  7. package/bin/spine-cli/wait.mjs +30 -0
  8. package/bin/spine-cli/watch.mjs +27 -0
  9. package/bin/spine-config.mjs +1 -212
  10. package/bin/spine-doctor.mjs +2 -418
  11. package/bin/spine-init.mjs +1 -398
  12. package/bin/spine-issue.mjs +196 -0
  13. package/bin/spine-journal.mjs +1 -0
  14. package/bin/spine-preflight.mjs +1 -700
  15. package/bin/spine-review-step.mjs +6 -4
  16. package/bin/spine-run.mjs +30 -0
  17. package/bin/spine-status.mjs +19 -1
  18. package/bin/spine-tasks.mjs +112 -13
  19. package/bin/spine-worker-runner.mjs +24 -14
  20. package/bin/spine.mjs +52 -2
  21. package/extensions/spine/worker-tools.ts +14 -12
  22. package/package.json +5 -2
  23. package/skills/create-spine-tasks/SKILL.md +135 -6
  24. package/skills/create-spine-tasks/references/clarify-template.md +73 -0
  25. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  26. package/skills/create-spine-tasks/references/prompt-template.md +2 -0
  27. package/skills/create-spine-tasks/references/requirements-checklist-template.md +94 -0
  28. package/src/batch/abort.mjs +3 -12
  29. package/src/batch/agent-session-worker.mjs +45 -5
  30. package/src/batch/attached-engine-handoff.mjs +188 -0
  31. package/src/batch/attached-runner.mjs +312 -0
  32. package/src/batch/contract-prelanded.mjs +180 -0
  33. package/src/batch/contract-verify.mjs +140 -2
  34. package/src/batch/detached-start.mjs +105 -7
  35. package/src/batch/diagnosis-alternatives.mjs +46 -0
  36. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  37. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  38. package/src/batch/diagnosis-stub.mjs +109 -0
  39. package/src/batch/diagnosis-task-done.mjs +110 -0
  40. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  41. package/src/batch/diagnosis.mjs +174 -62
  42. package/src/batch/engine-lanes/merge.mjs +168 -77
  43. package/src/batch/engine-lanes/queue.mjs +4 -1
  44. package/src/batch/engine-lanes/review.mjs +32 -74
  45. package/src/batch/engine-lanes/watch.mjs +29 -0
  46. package/src/batch/engine-lanes.mjs +1 -0
  47. package/src/batch/engine-scope.mjs +42 -5
  48. package/src/batch/engine.mjs +115 -68
  49. package/src/batch/evidence.mjs +81 -17
  50. package/src/batch/gate.mjs +46 -17
  51. package/src/batch/git-helpers.mjs +96 -0
  52. package/src/batch/heartbeat.mjs +73 -7
  53. package/src/batch/integrate.mjs +3 -5
  54. package/src/batch/journal.mjs +25 -0
  55. package/src/batch/lane-commit.mjs +90 -5
  56. package/src/batch/lifecycle.mjs +131 -4
  57. package/src/batch/macro-phase.mjs +226 -0
  58. package/src/batch/merge/adoption-doc-merge.mjs +243 -0
  59. package/src/batch/merge/wave-merge-state.mjs +108 -0
  60. package/src/batch/metrics.mjs +74 -5
  61. package/src/batch/orphan-detect.mjs +74 -0
  62. package/src/batch/pause.mjs +223 -0
  63. package/src/batch/post-merge-limbo.mjs +345 -17
  64. package/src/batch/reconcile.mjs +473 -50
  65. package/src/batch/resume-common.mjs +6 -2
  66. package/src/batch/resume-engine.mjs +58 -1
  67. package/src/batch/resume-lane-reviews.mjs +16 -0
  68. package/src/batch/resume-multi-lanes.mjs +56 -1
  69. package/src/batch/resume-multi-validate.mjs +148 -8
  70. package/src/batch/resume-multi.mjs +45 -44
  71. package/src/batch/resume.mjs +64 -47
  72. package/src/batch/retry.mjs +56 -5
  73. package/src/batch/review-shared.mjs +196 -0
  74. package/src/batch/review-spawn.mjs +326 -0
  75. package/src/batch/review.mjs +178 -212
  76. package/src/batch/rules-manifest-drift.mjs +157 -0
  77. package/src/batch/salvage.mjs +2 -1
  78. package/src/batch/sequence.mjs +454 -0
  79. package/src/batch/state.mjs +18 -3
  80. package/src/batch/status-json.mjs +67 -0
  81. package/src/batch/task-stall-budget.mjs +94 -10
  82. package/src/batch/worker-host.mjs +185 -37
  83. package/src/batch/worker-output.mjs +196 -3
  84. package/src/batch/worktree.mjs +10 -0
  85. package/src/cli/handoff.mjs +1 -1
  86. package/src/cli/issue-draft.mjs +180 -0
  87. package/src/cli/journal-follow.mjs +239 -0
  88. package/src/cli/lane-logs.mjs +291 -0
  89. package/src/cli/rules.mjs +1 -1
  90. package/src/cli/sequence.mjs +108 -0
  91. package/src/cli/settings-set.mjs +3 -22
  92. package/src/cli/settings-slash.mjs +27 -5
  93. package/src/cli/wait.mjs +187 -0
  94. package/src/cli/watch.mjs +160 -0
  95. package/src/config/agent-model-resolve.mjs +48 -0
  96. package/src/config/cursor-rules/discover.mjs +3 -21
  97. package/src/config/defaults.mjs +7 -1
  98. package/src/config/settings-fields.mjs +48 -0
  99. package/src/config/spine-config-load.mjs +221 -0
  100. package/src/config/spine-init-constants.mjs +424 -0
  101. package/src/config/spine-preflight-lib.mjs +1180 -0
  102. package/src/dashboard/lane-throughput.mjs +351 -0
  103. package/src/dashboard/public/dashboard.css +25 -1
  104. package/src/dashboard/public/dashboard.js +224 -40
  105. package/src/dashboard/public/index.html +15 -9
  106. package/src/dashboard/server.mjs +4 -0
  107. package/src/dashboard/snapshot.mjs +387 -6
  108. package/src/dashboard/view.mjs +170 -15
  109. package/src/doctor/agent-model-inherit.mjs +61 -6
  110. package/src/doctor/run-doctor-checks.mjs +483 -0
  111. package/src/doctor/sequence-safety.mjs +57 -0
  112. package/src/doctor/stale-path.mjs +22 -0
  113. package/src/doctor/stale-worktrees.mjs +102 -0
  114. package/src/fixtures/scenario-registry.mjs +194 -0
  115. package/src/fs/atomic-write.mjs +49 -0
  116. package/src/migrate/taskplane-config.mjs +1 -1
  117. package/src/planner/file-scope.mjs +246 -0
  118. package/src/planner/format-plan.mjs +9 -7
  119. package/src/planner/index.mjs +6 -2
  120. package/src/planner/pending.mjs +92 -1
  121. package/src/planner/wave-scope.mjs +136 -0
  122. package/src/planner/waves.mjs +133 -0
  123. package/src/tasks/analyze/index.mjs +453 -0
  124. package/src/tasks/packet/index.mjs +1 -0
  125. package/src/tasks/packet/parse-prompt.mjs +42 -1
  126. package/src/tasks/packet/validate-prompt.mjs +124 -0
  127. package/src/util/command-exists.mjs +19 -0
  128. package/templates/docs/constitution.md +61 -0
  129. package/templates/spine-config.json +9 -2
@@ -0,0 +1,454 @@
1
+ /**
2
+ * Planner wave sequence runner (GitHub #54 Tier 2 SP-C).
3
+ * Chains separate batch starts through gate → integrate → complete per planner wave.
4
+ */
5
+
6
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
7
+ import { runBatchPreflight, resolveTasksRoot } from "../config/spine-preflight-lib.mjs";
8
+ import { buildPlan } from "../planner/index.mjs";
9
+ import { resolveWaveTaskIds } from "../planner/wave-scope.mjs";
10
+
11
+ export { resolveWaveTaskIds };
12
+ import { startBatch } from "./engine.mjs";
13
+ import { startBatchDetached } from "./detached-start.mjs";
14
+ import { approveIntegrateGate, loadGateRecord } from "./gate.mjs";
15
+ import { integrateOrchToBase } from "./integrate.mjs";
16
+ import { completeBatch } from "./lifecycle.mjs";
17
+ import { reconcileBatch } from "./reconcile.mjs";
18
+ import { loadSpineBatchState } from "./state.mjs";
19
+ import { validateSequenceAutoApproveGate } from "../doctor/sequence-safety.mjs";
20
+
21
+ const WAVE_BATCH_SETTLED_DIAGNOSES = new Set([
22
+ "completed",
23
+ "completed_manual",
24
+ "needs_integrate",
25
+ "limbo_stale",
26
+ ]);
27
+ const WAVE_BATCH_FAILURE_DIAGNOSES = new Set(["failed", "aborted"]);
28
+ const WAVE_BATCH_WAITING_DIAGNOSES = new Set([
29
+ "running",
30
+ "paused",
31
+ "needs_retry",
32
+ "worker_orphaned",
33
+ "engine_orphaned",
34
+ "state_drift",
35
+ "needs_merge",
36
+ "needs_replan",
37
+ ]);
38
+
39
+ function sleep(ms) {
40
+ return new Promise((resolve) => setTimeout(resolve, ms));
41
+ }
42
+
43
+ export function isSequenceBatchSettled(diagnosis) {
44
+ return Boolean(diagnosis && WAVE_BATCH_SETTLED_DIAGNOSES.has(diagnosis));
45
+ }
46
+
47
+ export function isSequenceBatchFailure(diagnosis) {
48
+ return Boolean(diagnosis && WAVE_BATCH_FAILURE_DIAGNOSES.has(diagnosis));
49
+ }
50
+
51
+ export function isSequenceBatchWaiting(diagnosis) {
52
+ return Boolean(diagnosis && WAVE_BATCH_WAITING_DIAGNOSES.has(diagnosis));
53
+ }
54
+
55
+ export async function waitForSequenceBatchTerminal({
56
+ projectRoot,
57
+ pollIntervalMs = 250,
58
+ timeoutMs = 120_000,
59
+ }) {
60
+ const deadline = Date.now() + timeoutMs;
61
+ while (Date.now() < deadline) {
62
+ const reconciliation = reconcileBatch({ projectRoot });
63
+ const diagnosis = reconciliation.diagnosis;
64
+ if (isSequenceBatchFailure(diagnosis)) {
65
+ return {
66
+ ok: false,
67
+ halted: true,
68
+ diagnosis,
69
+ reconciliation,
70
+ batchId: reconciliation.batchId ?? null,
71
+ };
72
+ }
73
+ if (isSequenceBatchSettled(diagnosis)) {
74
+ return {
75
+ ok: true,
76
+ diagnosis,
77
+ reconciliation,
78
+ batchId: reconciliation.batchId ?? null,
79
+ };
80
+ }
81
+ await sleep(pollIntervalMs);
82
+ }
83
+ const reconciliation = reconcileBatch({ projectRoot });
84
+ return {
85
+ ok: false,
86
+ error: "timeout_waiting_for_batch",
87
+ diagnosis: reconciliation.diagnosis ?? null,
88
+ reconciliation,
89
+ batchId: reconciliation.batchId ?? null,
90
+ };
91
+ }
92
+
93
+ /**
94
+ * @param {object} plan
95
+ * @param {object} [options]
96
+ * @param {number} [options.fromWave]
97
+ * @param {number|null} [options.throughWave]
98
+ */
99
+ export function resolveSequenceWaves(plan, { fromWave = 0, throughWave = null } = {}) {
100
+ const waves = plan?.waves ?? [];
101
+ if (waves.length === 0) {
102
+ return { ok: false, error: "plan_has_no_waves", output: "Planner scope has no waves." };
103
+ }
104
+
105
+ const lastWave = throughWave ?? waves.length - 1;
106
+ if (!Number.isInteger(fromWave) || fromWave < 0 || fromWave >= waves.length) {
107
+ return {
108
+ ok: false,
109
+ error: "from_wave_out_of_range",
110
+ fromWave,
111
+ waveCount: waves.length,
112
+ output: `--from-wave ${fromWave} is out of range (plan has ${waves.length} wave(s)).`,
113
+ };
114
+ }
115
+ if (!Number.isInteger(lastWave) || lastWave < fromWave || lastWave >= waves.length) {
116
+ return {
117
+ ok: false,
118
+ error: "through_wave_out_of_range",
119
+ throughWave: lastWave,
120
+ fromWave,
121
+ waveCount: waves.length,
122
+ output: `--through-wave ${lastWave} is invalid for plan with ${waves.length} wave(s) (from-wave=${fromWave}).`,
123
+ };
124
+ }
125
+
126
+ /** @type {Array<{ waveIndex: number, taskIds: string[] }>} */
127
+ const entries = [];
128
+ for (let waveIndex = fromWave; waveIndex <= lastWave; waveIndex++) {
129
+ const resolved = resolveWaveTaskIds(plan, waveIndex);
130
+ if (!resolved.ok) return resolved;
131
+ entries.push({ waveIndex, taskIds: resolved.taskIds });
132
+ }
133
+
134
+ return { ok: true, waves: entries, waveCount: waves.length, fromWave, throughWave: lastWave };
135
+ }
136
+
137
+ /**
138
+ * @param {object} params
139
+ * @param {number} params.waveIndex
140
+ * @param {string[]} params.taskIds
141
+ * @param {boolean} [params.autoApproveGate]
142
+ */
143
+ export function buildSequenceWaveCommands({ waveIndex, taskIds, autoApproveGate = false }) {
144
+ const taskScope = taskIds.join(" ");
145
+ return [
146
+ `# Wave ${waveIndex}`,
147
+ `spine batch start ${taskScope}`,
148
+ "spine status --diagnose # wait for terminal batch phase",
149
+ autoApproveGate ? "spine gate approve" : "spine gate approve # when integrate gate is open",
150
+ "spine integrate",
151
+ "spine batch complete",
152
+ ];
153
+ }
154
+
155
+ /**
156
+ * @param {object} params
157
+ * @param {object} params.plan
158
+ * @param {number} [params.fromWave]
159
+ * @param {number|null} [params.throughWave]
160
+ * @param {boolean} [params.autoApproveGate]
161
+ */
162
+ export function buildSequenceDryRunPlan({
163
+ plan,
164
+ fromWave = 0,
165
+ throughWave = null,
166
+ autoApproveGate = false,
167
+ }) {
168
+ const wavePlan = resolveSequenceWaves(plan, { fromWave, throughWave });
169
+ if (!wavePlan.ok) return wavePlan;
170
+
171
+ const commands = wavePlan.waves.flatMap((wave) =>
172
+ buildSequenceWaveCommands({
173
+ waveIndex: wave.waveIndex,
174
+ taskIds: wave.taskIds,
175
+ autoApproveGate,
176
+ }),
177
+ );
178
+
179
+ return {
180
+ ok: true,
181
+ waves: wavePlan.waves,
182
+ waveCount: wavePlan.waveCount,
183
+ fromWave: wavePlan.fromWave,
184
+ throughWave: wavePlan.throughWave,
185
+ commands,
186
+ output: `${commands.join("\n")}\n`,
187
+ };
188
+ }
189
+
190
+ /**
191
+ * @param {string} projectRoot
192
+ * @param {string} scope
193
+ */
194
+ export function buildSequencePlan(projectRoot, scope) {
195
+ const configResult = loadSpineConfig(projectRoot);
196
+ const config = configResult.config ?? {};
197
+ const tasksRoot = resolveTasksRoot(projectRoot, configResult);
198
+ if (!tasksRoot) {
199
+ return { ok: false, error: "tasks_root_missing", output: "Tasks root is not configured.\n" };
200
+ }
201
+
202
+ return { ok: true, plan: buildPlan({ scope, config, tasksRoot }), config, tasksRoot };
203
+ }
204
+
205
+ /**
206
+ * @param {object} params
207
+ * @param {string} params.projectRoot
208
+ * @param {string|null} params.batchId
209
+ * @param {boolean} [params.autoApproveGate]
210
+ */
211
+ export function runSequenceWaveLandLoop({ projectRoot, batchId, autoApproveGate = false }) {
212
+ const reconciliation = reconcileBatch({ projectRoot });
213
+ const diagnosis = reconciliation.diagnosis;
214
+ const activeBatchId =
215
+ batchId ?? reconciliation.batchId ?? loadSpineBatchState(projectRoot).raw?.batchId ?? null;
216
+
217
+ if (!isSequenceBatchSettled(diagnosis)) {
218
+ return {
219
+ ok: false,
220
+ step: "land_loop",
221
+ error: "batch_not_settled",
222
+ diagnosis,
223
+ batchId: activeBatchId,
224
+ headline: `Cannot land wave — batch diagnosis is ${diagnosis ?? "unknown"}`,
225
+ };
226
+ }
227
+
228
+ const config = loadSpineConfig(projectRoot).config ?? {};
229
+ const gateRequired = config.gates?.requireBeforeIntegrate !== false;
230
+ const gate = activeBatchId ? loadGateRecord(projectRoot, activeBatchId) : null;
231
+
232
+ if (gateRequired && gate?.status === "pending") {
233
+ if (!autoApproveGate) {
234
+ return {
235
+ ok: false,
236
+ step: "gate_approve",
237
+ error: "gate_approval_required",
238
+ diagnosis,
239
+ batchId: activeBatchId,
240
+ headline: "Integrate gate requires approval — pass autoApproveGate or approve manually",
241
+ suggestedCommand: "spine gate approve",
242
+ };
243
+ }
244
+ const approve = approveIntegrateGate({ projectRoot, batchId: activeBatchId });
245
+ if (!approve.ok) {
246
+ return { ok: false, step: "gate_approve", diagnosis, batchId: activeBatchId, ...approve };
247
+ }
248
+ }
249
+
250
+ const integrate = integrateOrchToBase({ projectRoot, batchId: activeBatchId });
251
+ if (!integrate.ok) {
252
+ return { ok: false, step: "integrate", diagnosis, batchId: activeBatchId, ...integrate };
253
+ }
254
+
255
+ const complete = completeBatch({ projectRoot, batchId: activeBatchId });
256
+ if (!complete.ok) {
257
+ return { ok: false, step: "complete", diagnosis, batchId: activeBatchId, ...complete };
258
+ }
259
+
260
+ return {
261
+ ok: true,
262
+ diagnosis,
263
+ batchId: activeBatchId,
264
+ headline: `Wave batch ${activeBatchId} landed on main`,
265
+ };
266
+ }
267
+
268
+ /**
269
+ * @param {object} params
270
+ * @param {number} params.waveIndex
271
+ * @param {string} [params.error]
272
+ * @param {string|null} [params.diagnosis]
273
+ * @param {string|null} [params.batchId]
274
+ * @param {Array<{ waveIndex: number, batchId: string|null, diagnosis: string|null }>} params.completedWaves
275
+ */
276
+ function sequenceHalt({ waveIndex, error, diagnosis = null, batchId = null, completedWaves }) {
277
+ return {
278
+ ok: false,
279
+ exitCode: 1,
280
+ halted: true,
281
+ waveIndex,
282
+ error,
283
+ diagnosis,
284
+ batchId,
285
+ completedWaves,
286
+ };
287
+ }
288
+
289
+ /**
290
+ * @param {object} ctx
291
+ */
292
+ export async function runSequence(ctx) {
293
+ const {
294
+ projectRoot,
295
+ plan,
296
+ fromWave = 0,
297
+ throughWave = null,
298
+ attached = false,
299
+ autoApproveGate = false,
300
+ force = false,
301
+ stopOnFailure = true,
302
+ dryRun = false,
303
+ skipPreflight = false,
304
+ pollIntervalMs = 250,
305
+ timeoutMs = 120_000,
306
+ spineBin = null,
307
+ startBatchFn = startBatch,
308
+ } = ctx;
309
+
310
+ const wavePlan = resolveSequenceWaves(plan, { fromWave, throughWave });
311
+ if (!wavePlan.ok) {
312
+ return { ok: false, exitCode: 1, error: wavePlan.error, output: wavePlan.output };
313
+ }
314
+
315
+ const autoApproveCheck = validateSequenceAutoApproveGate({ autoApproveGate, force });
316
+ if (!autoApproveCheck.ok) {
317
+ return {
318
+ ok: false,
319
+ exitCode: 1,
320
+ error: autoApproveCheck.error,
321
+ output: autoApproveCheck.output,
322
+ suggestedCommand: autoApproveCheck.suggestedCommand,
323
+ };
324
+ }
325
+
326
+ if (dryRun) {
327
+ const dryPlan = buildSequenceDryRunPlan({ plan, fromWave, throughWave, autoApproveGate });
328
+ return {
329
+ ok: true,
330
+ exitCode: 0,
331
+ dryRun: true,
332
+ waves: dryPlan.waves,
333
+ commands: dryPlan.commands,
334
+ output: dryPlan.output,
335
+ };
336
+ }
337
+
338
+ if (!skipPreflight) {
339
+ const preflight = runBatchPreflight({ projectRoot, skipDoctor: false });
340
+ if (!preflight.ok) {
341
+ return {
342
+ ok: false,
343
+ exitCode: preflight.exitCode ?? 1,
344
+ error: "preflight_failed",
345
+ output: preflight.output,
346
+ };
347
+ }
348
+ }
349
+
350
+ /** @type {Array<{ waveIndex: number, batchId: string|null, diagnosis: string|null }>} */
351
+ const completedWaves = [];
352
+
353
+ for (const wave of wavePlan.waves) {
354
+ const taskScope = wave.taskIds.join(" ");
355
+ let batchId = null;
356
+
357
+ if (attached) {
358
+ const startResult = await startBatchFn({
359
+ projectRoot,
360
+ scope: taskScope,
361
+ skipPreflight: true,
362
+ });
363
+ if (!startResult.ok) {
364
+ if (!stopOnFailure) continue;
365
+ return {
366
+ ...sequenceHalt({
367
+ waveIndex: wave.waveIndex,
368
+ error: startResult.error ?? "batch_start_failed",
369
+ completedWaves,
370
+ }),
371
+ output: startResult.output,
372
+ };
373
+ }
374
+ batchId = startResult.batchId ?? loadSpineBatchState(projectRoot).raw?.batchId ?? null;
375
+ } else {
376
+ if (!spineBin) {
377
+ return {
378
+ ok: false,
379
+ exitCode: 1,
380
+ error: "spine_bin_required",
381
+ output: "Detached sequence runs require spineBin.\n",
382
+ };
383
+ }
384
+ const detached = await startBatchDetached({
385
+ projectRoot,
386
+ spineBin,
387
+ scope: taskScope,
388
+ skipPreflight: true,
389
+ waitTerminal: true,
390
+ });
391
+ if (!detached.ok) {
392
+ if (!stopOnFailure) continue;
393
+ return {
394
+ ...sequenceHalt({
395
+ waveIndex: wave.waveIndex,
396
+ error: detached.result?.error ?? "batch_start_failed",
397
+ completedWaves,
398
+ }),
399
+ output: detached.output,
400
+ };
401
+ }
402
+ batchId = detached.result?.batchId ?? null;
403
+ }
404
+
405
+ const wait = attached
406
+ ? {
407
+ ok: true,
408
+ batchId,
409
+ diagnosis: reconcileBatch({ projectRoot }).diagnosis ?? null,
410
+ }
411
+ : await waitForSequenceBatchTerminal({ projectRoot, pollIntervalMs, timeoutMs });
412
+
413
+ if (!wait.ok || isSequenceBatchFailure(wait.diagnosis)) {
414
+ if (!stopOnFailure) continue;
415
+ return sequenceHalt({
416
+ waveIndex: wave.waveIndex,
417
+ error: wait.error ?? "batch_failed",
418
+ diagnosis: wait.diagnosis ?? null,
419
+ batchId: wait.batchId ?? batchId,
420
+ completedWaves,
421
+ });
422
+ }
423
+
424
+ const land = runSequenceWaveLandLoop({ projectRoot, batchId: wait.batchId ?? batchId, autoApproveGate });
425
+ if (!land.ok) {
426
+ if (!stopOnFailure) continue;
427
+ return {
428
+ ...sequenceHalt({
429
+ waveIndex: wave.waveIndex,
430
+ error: land.error ?? "land_loop_failed",
431
+ diagnosis: land.diagnosis ?? wait.diagnosis ?? null,
432
+ batchId: land.batchId ?? wait.batchId ?? batchId,
433
+ completedWaves,
434
+ }),
435
+ step: land.step,
436
+ headline: land.headline,
437
+ };
438
+ }
439
+
440
+ completedWaves.push({
441
+ waveIndex: wave.waveIndex,
442
+ batchId: land.batchId ?? wait.batchId ?? batchId,
443
+ diagnosis: wait.diagnosis ?? null,
444
+ });
445
+ }
446
+
447
+ return {
448
+ ok: true,
449
+ exitCode: 0,
450
+ completedWaves,
451
+ waveCount: wavePlan.waves.length,
452
+ output: `Sequence completed ${completedWaves.length} wave(s).\n`,
453
+ };
454
+ }
@@ -4,6 +4,7 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
+ import { writeJsonAtomic } from "../fs/atomic-write.mjs";
7
8
  import { appendJournalEvent } from "./journal.mjs";
8
9
  import { loadBatchStateFile } from "./batch-state-io.mjs";
9
10
  import { isProcessAlive } from "../process/liveness.mjs";
@@ -14,7 +15,12 @@ export const SPINE_BATCH_STATE_REL = path.join(".spine", "batch-state.json");
14
15
  export const ACTIVE_PHASES = new Set(["planning", "running", "paused"]);
15
16
 
16
17
  /** @type {ReadonlySet<string>} */
17
- export const TERMINAL_BATCH_PHASES = new Set(["completed", "failed", "aborted"]);
18
+ export const TERMINAL_BATCH_PHASES = new Set([
19
+ "completed",
20
+ "failed",
21
+ "aborted",
22
+ "merge_blocked",
23
+ ]);
18
24
 
19
25
  /**
20
26
  * @returns {string} batchId `{YYYYMMDD}T{HHmmss}` UTC
@@ -115,7 +121,7 @@ export function saveSpineBatchState(projectRoot, state, options = {}) {
115
121
  clearBatchEnginePid(state);
116
122
  }
117
123
  const next = { ...state, updatedAt: Date.now() };
118
- fs.writeFileSync(filePath, `${JSON.stringify(next, null, 2)}\n`, "utf-8");
124
+ writeJsonAtomic(filePath, next);
119
125
  return next;
120
126
  }
121
127
 
@@ -291,7 +297,16 @@ export function validateBatchState(state) {
291
297
  if (!batchId) errors.push("batchId is required");
292
298
 
293
299
  const phase = String(raw.phase ?? "").trim();
294
- const validPhases = new Set(["planning", "running", "paused", "completed", "failed", "aborted"]);
300
+ const validPhases = new Set([
301
+ "planning",
302
+ "running",
303
+ "paused",
304
+ "merging",
305
+ "completed",
306
+ "failed",
307
+ "aborted",
308
+ "merge_blocked",
309
+ ]);
295
310
  if (!validPhases.has(phase)) {
296
311
  errors.push(`phase must be one of ${[...validPhases].join(", ")} (found ${phase || "missing"})`);
297
312
  }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Structured JSON output for `spine status --json` (issue #30, SP-339).
3
+ */
4
+
5
+ import { TASK_DONE_FLAG_FIELD_NAMES } from "./diagnosis.mjs";
6
+
7
+ /** @typedef {import("./reconcile.mjs").ReconciliationResult & Record<string, unknown>} StatusJsonInput */
8
+
9
+ export { TASK_DONE_FLAG_FIELD_NAMES };
10
+
11
+ export const STATUS_JSON_PROGRESS_FIELD_NAMES = [
12
+ "succeededTasks",
13
+ "pendingTasks",
14
+ "totalTasks",
15
+ "currentWaveIndex",
16
+ "waveCount",
17
+ ];
18
+
19
+ /**
20
+ * Derive monitor-friendly task/wave progress from batch state.
21
+ *
22
+ * @param {object} ctx
23
+ * @param {Record<string, unknown>|null|undefined} ctx.batchRaw
24
+ * @param {number|null|undefined} [ctx.succeededTasks]
25
+ * @param {number|null|undefined} [ctx.totalTasks]
26
+ * @param {number} ctx.pendingTasks
27
+ * @returns {Record<string, number>|null}
28
+ */
29
+ export function computeStatusProgress(ctx) {
30
+ const { batchRaw, succeededTasks, totalTasks, pendingTasks } = ctx;
31
+ if (batchRaw == null || typeof batchRaw !== "object") {
32
+ return null;
33
+ }
34
+
35
+ const wavePlan = Array.isArray(batchRaw.wavePlan) ? batchRaw.wavePlan : [];
36
+ const currentWaveIndex = Number(batchRaw.currentWaveIndex ?? 0);
37
+ const waveCount = Number(batchRaw.totalWaves ?? wavePlan.length);
38
+
39
+ return {
40
+ succeededTasks: Number(succeededTasks ?? batchRaw.succeededTasks ?? 0),
41
+ pendingTasks: Number(pendingTasks),
42
+ totalTasks: Number(totalTasks ?? batchRaw.totalTasks ?? 0),
43
+ currentWaveIndex: Number.isFinite(currentWaveIndex) ? currentWaveIndex : 0,
44
+ waveCount: Number.isFinite(waveCount) ? waveCount : 0,
45
+ };
46
+ }
47
+
48
+ /**
49
+ * Build the JSON-serializable payload for `spine status --json`.
50
+ *
51
+ * Task entries under `signals.tasks` (when `--diagnose`) expose:
52
+ * - `doneFileFound` — journal/batch-state worker completion
53
+ * - `doneOnMain` — `.DONE` on integration checkout tasks root
54
+ * - `doneInLane` — `.DONE` in lane worktree (pre-merge)
55
+ *
56
+ * @param {StatusJsonInput} reconcileResult
57
+ */
58
+ export function buildStatusJson(reconcileResult) {
59
+ return reconcileResult;
60
+ }
61
+
62
+ /**
63
+ * @param {StatusJsonInput} reconcileResult
64
+ */
65
+ export function formatStatusJson(reconcileResult) {
66
+ return `${JSON.stringify(buildStatusJson(reconcileResult), null, 2)}\n`;
67
+ }
@@ -37,30 +37,41 @@ export function parseTaskSizeFromFolder(taskFolder) {
37
37
  /**
38
38
  * @param {"S"|"M"|"L"|"XL"|null} size
39
39
  * @param {object} [config]
40
+ * @param {{ stallTimeoutMinutes?: number | null }} [contract]
40
41
  */
41
- export function resolveTaskStallMinutes(size, config = {}) {
42
+ export function resolveTaskStallMinutes(size, config = {}, contract = {}) {
42
43
  const configured = Number(config.lanes?.stallTimeoutMinutes);
43
44
  const configMinutes = Number.isFinite(configured) && configured > 0 ? configured : 60;
44
45
  const sizeMinutes =
45
46
  size && size in STALL_MINUTES_BY_SIZE
46
47
  ? STALL_MINUTES_BY_SIZE[/** @type {keyof typeof STALL_MINUTES_BY_SIZE} */ (size)]
47
48
  : null;
48
- return sizeMinutes ? Math.max(configMinutes, sizeMinutes) : configMinutes;
49
+ const baseMinutes = sizeMinutes ? Math.max(configMinutes, sizeMinutes) : configMinutes;
50
+ const contractMinutes = Number(contract.stallTimeoutMinutes);
51
+ if (Number.isFinite(contractMinutes) && contractMinutes > 0) {
52
+ return Math.max(baseMinutes, contractMinutes);
53
+ }
54
+ return baseMinutes;
49
55
  }
50
56
 
51
57
  /**
52
58
  * @param {object} params
53
59
  * @param {object} [params.config]
54
60
  * @param {string|null} [params.taskSize]
61
+ * @param {{ stallTimeoutMinutes?: number | null, extendGraceOnFileScope?: boolean | null }} [params.contract]
55
62
  */
56
- export function resolveStallConfigForTask({ config = {}, taskSize = null }) {
57
- const stallTimeoutMinutes = resolveTaskStallMinutes(taskSize, config);
63
+ export function resolveStallConfigForTask({ config = {}, taskSize = null, contract = {} }) {
64
+ const stallTimeoutMinutes = resolveTaskStallMinutes(taskSize, config, contract);
65
+ const lanes = {
66
+ ...(config.lanes ?? {}),
67
+ stallTimeoutMinutes,
68
+ };
69
+ if (contract.extendGraceOnFileScope === true) {
70
+ lanes.extendGraceOnFileScope = true;
71
+ }
58
72
  return resolveStallConfig({
59
73
  ...config,
60
- lanes: {
61
- ...(config.lanes ?? {}),
62
- stallTimeoutMinutes,
63
- },
74
+ lanes,
64
75
  });
65
76
  }
66
77
 
@@ -74,8 +85,9 @@ export const DEFAULT_PI_WORKER_TIMEOUT_MS = 60 * 60 * 1000;
74
85
  * @param {object} params
75
86
  * @param {object} [params.config]
76
87
  * @param {"S"|"M"|"L"|"XL"|null} [params.taskSize]
88
+ * @param {{ stallTimeoutMinutes?: number | null }} [params.contract]
77
89
  */
78
- export function resolveWorkerPiTimeoutMs({ config = {}, taskSize = null }) {
90
+ export function resolveWorkerPiTimeoutMs({ config = {}, taskSize = null, contract = {} }) {
79
91
  const envRaw = process.env.SPINE_WORKER_PI_TIMEOUT_MS;
80
92
  if (envRaw) {
81
93
  const parsed = Number(envRaw);
@@ -83,6 +95,78 @@ export function resolveWorkerPiTimeoutMs({ config = {}, taskSize = null }) {
83
95
  return parsed;
84
96
  }
85
97
  }
86
- const stallMinutes = resolveTaskStallMinutes(taskSize, config);
98
+ const stallMinutes = resolveTaskStallMinutes(taskSize, config, contract);
87
99
  return stallMinutes * 60 * 1000;
88
100
  }
101
+
102
+ /**
103
+ * Reviewer `pi` spawn timeout aligned with per-task stall budget (SP-279).
104
+ * Honors `SPINE_REVIEW_TIMEOUT_MS` when set in the parent environment.
105
+ *
106
+ * @param {object} params
107
+ * @param {object} [params.config]
108
+ * @param {"S"|"M"|"L"|"XL"|null} [params.taskSize]
109
+ */
110
+ export function resolveReviewSpawnTimeoutMs({ config = {}, taskSize = null }) {
111
+ const envRaw = process.env.SPINE_REVIEW_TIMEOUT_MS;
112
+ if (envRaw) {
113
+ const parsed = Number(envRaw);
114
+ if (Number.isFinite(parsed) && parsed > 0) {
115
+ return parsed;
116
+ }
117
+ }
118
+ return resolveWorkerPiTimeoutMs({ config, taskSize });
119
+ }
120
+
121
+ /** Default poll interval while awaiting reviewer artifact (SP-294). */
122
+ export const DEFAULT_REVIEW_ARTIFACT_POLL_INTERVAL_MS = 5_000;
123
+
124
+ /** Upper bound for reviewer artifact poll interval. */
125
+ export const MAX_REVIEW_ARTIFACT_POLL_INTERVAL_MS = 30_000;
126
+
127
+ /** Default mtime quiescence before honoring an on-disk review artifact. */
128
+ export const DEFAULT_REVIEW_ARTIFACT_QUIESCENCE_MS = 2_000;
129
+
130
+ /**
131
+ * Poll interval for early reviewer artifact honor (SP-294).
132
+ * Honors `SPINE_REVIEW_ARTIFACT_POLL_MS` when set; capped at 30s.
133
+ *
134
+ * @param {object} [params]
135
+ * @param {object} [params.config]
136
+ */
137
+ export function resolveReviewArtifactPollIntervalMs({ config = {} } = {}) {
138
+ const envRaw = process.env.SPINE_REVIEW_ARTIFACT_POLL_MS;
139
+ if (envRaw) {
140
+ const parsed = Number(envRaw);
141
+ if (Number.isFinite(parsed) && parsed > 0) {
142
+ return Math.min(parsed, MAX_REVIEW_ARTIFACT_POLL_INTERVAL_MS);
143
+ }
144
+ }
145
+ const configured = Number(config.review?.artifactPollIntervalMs);
146
+ if (Number.isFinite(configured) && configured > 0) {
147
+ return Math.min(configured, MAX_REVIEW_ARTIFACT_POLL_INTERVAL_MS);
148
+ }
149
+ return DEFAULT_REVIEW_ARTIFACT_POLL_INTERVAL_MS;
150
+ }
151
+
152
+ /**
153
+ * Mtime quiescence window before honoring reviewer artifact (SP-294).
154
+ * Honors `SPINE_REVIEW_ARTIFACT_QUIESCENCE_MS` when set.
155
+ *
156
+ * @param {object} [params]
157
+ * @param {object} [params.config]
158
+ */
159
+ export function resolveReviewArtifactQuiescenceMs({ config = {} } = {}) {
160
+ const envRaw = process.env.SPINE_REVIEW_ARTIFACT_QUIESCENCE_MS;
161
+ if (envRaw) {
162
+ const parsed = Number(envRaw);
163
+ if (Number.isFinite(parsed) && parsed > 0) {
164
+ return parsed;
165
+ }
166
+ }
167
+ const configured = Number(config.review?.artifactQuiescenceMs);
168
+ if (Number.isFinite(configured) && configured > 0) {
169
+ return configured;
170
+ }
171
+ return DEFAULT_REVIEW_ARTIFACT_QUIESCENCE_MS;
172
+ }