pi-spine 2.25.0 → 2.26.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 (35) hide show
  1. package/package.json +1 -1
  2. package/src/batch/abort.mjs +74 -38
  3. package/src/batch/attached-engine-handoff.mjs +2 -2
  4. package/src/batch/attached-runner-promote.mjs +1 -1
  5. package/src/batch/attached-runner-reconcile.mjs +1 -1
  6. package/src/batch/batch-meta-reconstruct.mjs +6 -1
  7. package/src/batch/batch-state-lock.mjs +173 -31
  8. package/src/batch/contract-exec.mjs +46 -45
  9. package/src/batch/contract-spawn.mjs +225 -0
  10. package/src/batch/contract-verify.mjs +2 -1
  11. package/src/batch/detached-wait.mjs +1 -1
  12. package/src/batch/engine-lanes/matrix-run.mjs +6 -6
  13. package/src/batch/engine-lanes/merge.mjs +135 -34
  14. package/src/batch/engine-lanes/review-final.mjs +1 -1
  15. package/src/batch/engine-lanes.mjs +11 -9
  16. package/src/batch/engine.mjs +10 -10
  17. package/src/batch/lifecycle-archive.mjs +76 -1
  18. package/src/batch/lifecycle-cleanup.mjs +110 -0
  19. package/src/batch/lifecycle.mjs +100 -72
  20. package/src/batch/parent-session-monitor.mjs +77 -70
  21. package/src/batch/pause.mjs +92 -25
  22. package/src/batch/post-merge-limbo.mjs +35 -5
  23. package/src/batch/resume-gate-reopen.mjs +24 -8
  24. package/src/batch/resume-multi.mjs +1 -1
  25. package/src/batch/resume.mjs +1 -1
  26. package/src/batch/sequence-run.mjs +26 -8
  27. package/src/batch/sequence-wait.mjs +87 -8
  28. package/src/batch/state-guards.mjs +39 -7
  29. package/src/batch/state-io.mjs +131 -17
  30. package/src/batch/state.mjs +1 -0
  31. package/src/batch/worker-host.mjs +32 -4
  32. package/src/config/defaults.mjs +15 -1
  33. package/src/config/preflight/git-batch.mjs +47 -0
  34. package/src/config/spine-config-schema.mjs +67 -1
  35. package/src/fs/atomic-write.mjs +37 -1
@@ -23,6 +23,7 @@ import {
23
23
  recordBatchEnginePid,
24
24
  saveSpineBatchState,
25
25
  } from "./state.mjs";
26
+ import { isBatchArchived } from "./state-guards.mjs";
26
27
 
27
28
  export { isPostMergeLimbo } from "./limbo-detect.mjs";
28
29
  export { hydrateMergeResultsFromJournal, isLastWaveIndex } from "./post-merge-finalize.mjs";
@@ -168,7 +169,7 @@ export function ensureLandLoopFinalizedAfterGateOrIntegrate({
168
169
  }
169
170
 
170
171
  if (changed) {
171
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
172
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
172
173
  }
173
174
 
174
175
  return {
@@ -241,7 +242,7 @@ export function finalizeAttachedLandLoopBeforeExit({
241
242
  });
242
243
  if (finalizeResult?.ok) {
243
244
  clearBatchEnginePid(state);
244
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
245
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
245
246
  appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
246
247
  signal,
247
248
  action: "finalized_in_process",
@@ -266,7 +267,7 @@ export function finalizeAttachedLandLoopBeforeExit({
266
267
  const fresh = loadSpineBatchState(projectRoot);
267
268
  if (fresh.raw && enginePid) {
268
269
  recordBatchEnginePid(fresh.raw, enginePid);
269
- saveSpineBatchState(projectRoot, fresh.raw, { bypassWriteGuard: true });
270
+ saveSpineBatchState(projectRoot, fresh.raw, { bypassOwnerCheck: true });
270
271
  }
271
272
 
272
273
  appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
@@ -375,7 +376,7 @@ export function finalizeBatchForIntegrate({
375
376
 
376
377
  // Persist PID clear before evidence collection can hang (#198 / SP-636).
377
378
  clearBatchEnginePid(state);
378
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
379
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
379
380
 
380
381
  const gateResult = openIntegrateGateAfterBatchComplete({
381
382
  projectRoot,
@@ -383,6 +384,35 @@ export function finalizeBatchForIntegrate({
383
384
  batchState: { ...state, phase: "completed" },
384
385
  });
385
386
 
387
+ // Late-finalize no-op after archive (#293 / SP-790): the operator can run
388
+ // gate approve → integrate → batch complete while extended evidence collection
389
+ // above is still running. `batch complete` archives and removes the active state
390
+ // file; persisting from this late path would resurrect a phantom completed batch
391
+ // that blocks the next `spine batch start`. Skip the land-loop finalize and the
392
+ // final save — the write guard would reject the write anyway — and journal the
393
+ // skip so the no-op is visible instead of silent.
394
+ const activeStateAfterGate = loadSpineBatchState(projectRoot);
395
+ if (!activeStateAfterGate.raw && isBatchArchived(projectRoot, batchId)) {
396
+ appendJournalEvent(projectRoot, batchId, "batch.late_finalize_skipped", {
397
+ batchId,
398
+ reason: "archived",
399
+ });
400
+ return {
401
+ ok: true,
402
+ exitCode: 0,
403
+ batchId,
404
+ taskIds,
405
+ taskId: taskIds.length === 1 ? taskIds[0] : undefined,
406
+ orchBranch,
407
+ mergeCommit: state.mergeResults?.at(-1)?.mergeCommit,
408
+ gateResult,
409
+ lateFinalizeSkipped: "archived",
410
+ output:
411
+ `Batch ${batchId} archived while finalizing: ${summaryTask} succeeded; merged to ${orchBranch}.\n` +
412
+ " → late land-loop finalize skipped — batch already completed and archived\n",
413
+ };
414
+ }
415
+
386
416
  // Always mark completed in memory before ensure so a prior land-loop journal
387
417
  // (e.g. start then pause/resume) still persists phase: completed on disk.
388
418
  if (!alreadyCompleted) {
@@ -398,7 +428,7 @@ export function finalizeBatchForIntegrate({
398
428
  source: landLoopSource,
399
429
  });
400
430
  // Ensure may no-op when journal events already exist; always persist phase/PID.
401
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
431
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
402
432
 
403
433
  const completionLabel = resumed ? "resumed and completed" : "completed";
404
434
  const nextSteps = resumed
@@ -5,13 +5,19 @@
5
5
  */
6
6
 
7
7
  import { reopenIntegrateGateForCompletedBatch } from "./gate.mjs";
8
- import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
8
+ import { updateSpineBatchState } from "./state.mjs";
9
9
 
10
10
  /**
11
11
  * When `resumeCheck.gateReopen` is set, re-open the integrate gate and return
12
12
  * a resumeBatch-shaped result. Caller must release the resume lock via the
13
13
  * returned path (this helper releases it).
14
14
  *
15
+ * The reopen decision and the state persist run in one `updateSpineBatchState`
16
+ * critical section (SP-793 / #301): the phase is re-read under the lock from the
17
+ * latest committed state instead of a stale pre-load, and the persist goes
18
+ * through the write guard with no owner bypass — a completed batch has no live
19
+ * engine owner, so a guard rejection here is a real signal, not an obstacle.
20
+ *
15
21
  * @param {{
16
22
  * projectRoot: string,
17
23
  * resumeCheck: { batchId: string, gateReopen?: boolean },
@@ -24,14 +30,24 @@ export function tryResumeCompletedGateReopen({ projectRoot, resumeCheck, release
24
30
  return null;
25
31
  }
26
32
 
27
- const reopenState = loadSpineBatchState(projectRoot).raw;
28
- const reopenResult = reopenIntegrateGateForCompletedBatch({
29
- projectRoot,
30
- batchId: resumeCheck.batchId,
31
- batchState: reopenState,
33
+ let reopenResult = null;
34
+ updateSpineBatchState(projectRoot, (draft) => {
35
+ reopenResult = reopenIntegrateGateForCompletedBatch({
36
+ projectRoot,
37
+ batchId: resumeCheck.batchId,
38
+ batchState: draft,
39
+ });
40
+ // The gate record is written by the reopen itself; persisting the draft
41
+ // keeps parity with the prior unconditional save (refreshes updatedAt).
42
+ return true;
32
43
  });
33
- if (reopenState) {
34
- saveSpineBatchState(projectRoot, reopenState, { bypassWriteGuard: true });
44
+ if (!reopenResult) {
45
+ // Missing or corrupt batch-state on disk: evaluate reopen without state
46
+ // so the CLI reports the same batch_not_completed result as before.
47
+ reopenResult = reopenIntegrateGateForCompletedBatch({
48
+ projectRoot,
49
+ batchId: resumeCheck.batchId,
50
+ });
35
51
  }
36
52
  releaseResumeLock?.();
37
53
  const output = reopenResult.reopened
@@ -74,7 +74,7 @@ export async function resumeMultiTaskBatch({ projectRoot, force = false, resumeC
74
74
  batchId,
75
75
  fromPhase: phase,
76
76
  });
77
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
77
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
78
78
  return finalizeResumedBatchForIntegrate({
79
79
  projectRoot,
80
80
  state,
@@ -452,7 +452,7 @@ export async function resumeBatch({ projectRoot, force = false }) {
452
452
  taskBranch,
453
453
  orchBranch,
454
454
  });
455
- const merge = mergeLaneToOrch({ projectRoot, baseBranch, orchBranch, taskBranch, batchId });
455
+ const merge = mergeLaneToOrch({ projectRoot, baseBranch, orchBranch, taskBranch, batchId, laneFileScopePaths: fileScopePaths });
456
456
  if (!merge.ok) {
457
457
  state.endedAt = Date.now();
458
458
  state.lastError = merge.error ?? "merge failed";
@@ -3,7 +3,11 @@
3
3
  */
4
4
 
5
5
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
6
- import { resolveSequencePollMs } from "../config/spine-config-schema.mjs";
6
+ import {
7
+ resolveSequenceMaxWaitMs,
8
+ resolveSequencePollMs,
9
+ resolveSequenceStallMs,
10
+ } from "../config/spine-config-schema.mjs";
7
11
  import {
8
12
  formatPreflightHuman,
9
13
  runBatchPreflight,
@@ -67,6 +71,8 @@ export async function runSequence(ctx) {
67
71
  profile: profileOverride = null,
68
72
  pollIntervalMs: pollIntervalMsOverride,
69
73
  timeoutMs = 120_000,
74
+ maxWaitMs: maxWaitMsOverride,
75
+ stallMs: stallMsOverride,
70
76
  spineBin = null,
71
77
  startBatchFn = startBatch,
72
78
  } = ctx;
@@ -77,6 +83,12 @@ export async function runSequence(ctx) {
77
83
  const pollIntervalMs =
78
84
  pollIntervalMsOverride ??
79
85
  resolveSequencePollMs({ config: configResult.config ?? {} });
86
+ const maxWaitMs =
87
+ maxWaitMsOverride ??
88
+ resolveSequenceMaxWaitMs({ config: configResult.config ?? {} });
89
+ const stallMs =
90
+ stallMsOverride ??
91
+ resolveSequenceStallMs({ config: configResult.config ?? {} });
80
92
 
81
93
  let sequenceState = null;
82
94
  let effectiveFromWave = fromWave;
@@ -334,7 +346,7 @@ export async function runSequence(ctx) {
334
346
  batchId,
335
347
  diagnosis: reconcileBatch({ projectRoot }).diagnosis ?? null,
336
348
  }
337
- : await waitForSequenceBatchTerminal({ projectRoot, pollIntervalMs, timeoutMs, enginePid: detachedEnginePid ?? null });
349
+ : await waitForSequenceBatchTerminal({ projectRoot, pollIntervalMs, timeoutMs, maxWaitMs, stallMs, enginePid: detachedEnginePid ?? null });
338
350
 
339
351
  if (!wait.ok || isSequenceBatchFailure(wait.diagnosis)) {
340
352
  const reconciliation = wait.reconciliation ?? reconcileBatch({ projectRoot });
@@ -347,13 +359,19 @@ export async function runSequence(ctx) {
347
359
  continue;
348
360
  }
349
361
  if (!stopOnFailure) continue;
350
- return haltSequenceAndPersist(projectRoot, sequenceState, completedWaves, {
351
- waveIndex: wave.waveIndex,
352
- error: wait.error ?? "batch_failed",
353
- diagnosis: wait.diagnosis ?? null,
354
- batchId: wait.batchId ?? batchId,
362
+ return haltSequenceAndPersist(
363
+ projectRoot,
364
+ sequenceState,
355
365
  completedWaves,
356
- });
366
+ {
367
+ waveIndex: wave.waveIndex,
368
+ error: wait.error ?? "batch_failed",
369
+ diagnosis: wait.diagnosis ?? null,
370
+ batchId: wait.batchId ?? batchId,
371
+ completedWaves,
372
+ },
373
+ wait.suggestedCommand ? { suggestedCommand: wait.suggestedCommand } : {},
374
+ );
357
375
  }
358
376
 
359
377
  const land = runSequenceWaveLandLoop({ projectRoot, batchId: wait.batchId ?? batchId, autoApproveGate });
@@ -3,12 +3,17 @@
3
3
  */
4
4
 
5
5
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
6
- import { DEFAULT_SEQUENCE_POLL_MS } from "../config/spine-config-schema.mjs";
7
- import { isProcessAlive } from "../process/liveness.mjs";
6
+ import {
7
+ DEFAULT_SEQUENCE_MAX_WAIT_MS,
8
+ DEFAULT_SEQUENCE_POLL_MS,
9
+ DEFAULT_SEQUENCE_STALL_MS,
10
+ } from "../config/spine-config-schema.mjs";
11
+ import { isEngineProcessAlive, isProcessAlive } from "../process/liveness.mjs";
8
12
  import { approveIntegrateGate, loadGateRecord, maybeAutoApproveIntegrateGate } from "./gate.mjs";
9
13
  import { integrateOrchToBase } from "./integrate.mjs";
10
14
  import { completeBatch } from "./lifecycle.mjs";
11
15
  import { reconcileBatch } from "./reconcile.mjs";
16
+ import { readBatchEnginePid, readBatchEngineStartedAt } from "./state-guards.mjs";
12
17
  import { loadSpineBatchState } from "./state.mjs";
13
18
 
14
19
  const WAVE_BATCH_SETTLED_DIAGNOSES = new Set([
@@ -49,12 +54,28 @@ export async function waitForSequenceBatchTerminal({
49
54
  projectRoot,
50
55
  pollIntervalMs = DEFAULT_SEQUENCE_POLL_MS,
51
56
  timeoutMs = 120_000,
57
+ maxWaitMs = DEFAULT_SEQUENCE_MAX_WAIT_MS,
58
+ stallMs = DEFAULT_SEQUENCE_STALL_MS,
52
59
  enginePid = null,
53
60
  reconcileFn = reconcileBatch,
54
61
  }) {
55
- const deadline = Date.now() + timeoutMs;
62
+ const startedAt = Date.now();
63
+ const deadline = startedAt + timeoutMs;
64
+ const hardCap = startedAt + maxWaitMs;
65
+ let lastProgressAt = startedAt;
56
66
  let useLightReconcile = false;
57
67
  while (Date.now() < deadline || isEngineStillRunning(enginePid, projectRoot)) {
68
+ if (Date.now() >= hardCap) {
69
+ const reconciliation = reconcileFn({ projectRoot });
70
+ return {
71
+ ok: false,
72
+ error: "sequence_wait_timeout",
73
+ diagnosis: reconciliation.diagnosis ?? null,
74
+ reconciliation,
75
+ batchId: reconciliation.batchId ?? null,
76
+ suggestedCommand: "spine status --diagnose",
77
+ };
78
+ }
58
79
  const reconciliation = reconcileFn({ projectRoot, light: useLightReconcile });
59
80
  useLightReconcile = true;
60
81
  const diagnosis = reconciliation.diagnosis;
@@ -75,6 +96,20 @@ export async function waitForSequenceBatchTerminal({
75
96
  batchId: reconciliation.batchId ?? null,
76
97
  };
77
98
  }
99
+ const progressAt = newestProgressSignalMs(reconciliation);
100
+ if (progressAt != null && progressAt > lastProgressAt) {
101
+ lastProgressAt = progressAt;
102
+ }
103
+ if (Date.now() - lastProgressAt >= stallMs) {
104
+ return {
105
+ ok: false,
106
+ error: "engine_stalled",
107
+ diagnosis,
108
+ reconciliation,
109
+ batchId: reconciliation.batchId ?? null,
110
+ suggestedCommand: "spine status --diagnose",
111
+ };
112
+ }
78
113
  await sleep(pollIntervalMs);
79
114
  }
80
115
  const reconciliation = reconcileFn({ projectRoot });
@@ -88,14 +123,58 @@ export async function waitForSequenceBatchTerminal({
88
123
  }
89
124
 
90
125
  /**
91
- * Returns true when a detached engine PID is alive or the batch phase is active,
92
- * preventing sequence timeout while work is still in progress.
126
+ * Newest progress signal exposed by a reconciliation, in epoch ms: batch-state
127
+ * `updatedAt` or the latest journal event timestamp (lane heartbeats are
128
+ * journal `lane.heartbeat` events, so they are covered by the journal tail).
129
+ * Returns null when no signal is available (SP-802 / #307).
130
+ *
131
+ * @param {object} reconciliation
132
+ * @returns {number|null}
133
+ */
134
+ function newestProgressSignalMs(reconciliation) {
135
+ const signals = reconciliation?.signals ?? {};
136
+ /** @type {number|null} */
137
+ let newest = null;
138
+ const updatedAt = Number(signals.raw?.updatedAt);
139
+ if (Number.isFinite(updatedAt) && updatedAt > 0) {
140
+ newest = updatedAt;
141
+ }
142
+ const events = Array.isArray(signals.journalEvents) ? signals.journalEvents : [];
143
+ for (let index = events.length - 1; index >= 0; index -= 1) {
144
+ const ts = Date.parse(String(events[index]?.timestamp ?? ""));
145
+ if (Number.isFinite(ts) && ts > 0) {
146
+ if (newest == null || ts > newest) newest = ts;
147
+ break;
148
+ }
149
+ }
150
+ return newest;
151
+ }
152
+
153
+ /**
154
+ * Returns true when the batch engine is verifiably still running, so the wait
155
+ * extends past `timeoutMs` while work is in progress. PID-reuse-safe (SP-802 /
156
+ * #307, #259): the explicit `enginePid` is paired with the state's recorded
157
+ * `engineStartedAt` when the PIDs match; the state fallback uses the recorded
158
+ * PID + start time from `resilience`; otherwise it degrades to PID-only
159
+ * liveness.
160
+ *
161
+ * @param {number|null} enginePid
162
+ * @param {string} projectRoot
93
163
  */
94
164
  function isEngineStillRunning(enginePid, projectRoot) {
95
- if (enginePid && isProcessAlive(enginePid)) return true;
96
165
  const { raw } = loadSpineBatchState(projectRoot);
97
- const pid = raw?.enginePid ?? null;
98
- if (pid && isProcessAlive(pid)) return true;
166
+ const statePid = readBatchEnginePid(raw);
167
+ const stateStartedAt = readBatchEngineStartedAt(raw);
168
+ const pid = Number(enginePid);
169
+ if (Number.isFinite(pid) && pid > 0) {
170
+ if (statePid != null && statePid === pid) {
171
+ return isEngineProcessAlive(pid, stateStartedAt);
172
+ }
173
+ if (isProcessAlive(pid)) return true;
174
+ }
175
+ if (statePid != null) {
176
+ return isEngineProcessAlive(statePid, stateStartedAt);
177
+ }
99
178
  return false;
100
179
  }
101
180
 
@@ -34,17 +34,42 @@ function archivedBatchStatePath(projectRoot, batchId) {
34
34
  return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
35
35
  }
36
36
 
37
+ /**
38
+ * Whether `<root>/.spine/runtime/<batchId>/archive/batch-state.json` exists — i.e. the
39
+ * batch was archived by `spine batch complete` / `dismiss` / `abort` (SP-790 / #293).
40
+ * Callers use this to check archive status without duplicating the path.
41
+ *
42
+ * @param {string} projectRoot
43
+ * @param {string} batchId
44
+ * @returns {boolean}
45
+ */
46
+ export function isBatchArchived(projectRoot, batchId) {
47
+ const id = String(batchId ?? "");
48
+ if (!id) return false;
49
+ return fs.existsSync(archivedBatchStatePath(projectRoot, id));
50
+ }
51
+
37
52
  /**
38
53
  * Reject cache writes from non-owner engines or post-archive resurrection (SP-254).
39
54
  *
55
+ * The resurrection check applies to **every** incoming phase, including terminal
56
+ * ones (`completed`/`failed`): a late land-loop finalize after `spine batch complete`
57
+ * archived the batch must not recreate `.spine/batch-state.json` (SP-790 / #293).
58
+ * Operator recovery that intentionally rebuilds an archived batch passes
59
+ * `allowArchivedResurrection: true` (force-resume from batch-meta, #126).
60
+ *
61
+ * `skipOwnerCheck` skips only the live-foreign-owner-PID rejection so trusted
62
+ * engine writers cannot be blocked by their own recorded PID; resurrection
63
+ * protection always runs.
64
+ *
40
65
  * @param {string} projectRoot
41
66
  * @param {Record<string, any>} state
67
+ * @param {{ skipOwnerCheck?: boolean, allowArchivedResurrection?: boolean }} [options]
42
68
  * @returns {{ allowed: boolean, reason?: string }}
43
69
  */
44
- export function evaluateBatchStateWriteGuard(projectRoot, state) {
70
+ export function evaluateBatchStateWriteGuard(projectRoot, state, options = {}) {
45
71
  const filePath = spineBatchStatePath(projectRoot);
46
72
  const batchId = String(state.batchId ?? "");
47
- const incomingPhase = String(state.phase ?? "");
48
73
 
49
74
  if (fs.existsSync(filePath)) {
50
75
  try {
@@ -63,16 +88,23 @@ export function evaluateBatchStateWriteGuard(projectRoot, state) {
63
88
  ) {
64
89
  return { allowed: true };
65
90
  }
66
- if (ownerPid && ownerPid !== process.pid && isEngineProcessAlive(ownerPid, ownerStartedAt)) {
91
+ if (
92
+ !options.skipOwnerCheck &&
93
+ ownerPid &&
94
+ ownerPid !== process.pid &&
95
+ isEngineProcessAlive(ownerPid, ownerStartedAt)
96
+ ) {
67
97
  return { allowed: false, reason: "stale_engine_pid" };
68
98
  }
69
99
  } catch {
70
100
  /* corrupt on-disk state — allow overwrite */
71
101
  }
72
- } else if (batchId && ACTIVE_PHASES.has(incomingPhase)) {
73
- if (fs.existsSync(archivedBatchStatePath(projectRoot, batchId))) {
74
- return { allowed: false, reason: "archived_batch_resurrection" };
75
- }
102
+ } else if (
103
+ batchId &&
104
+ !options.allowArchivedResurrection &&
105
+ isBatchArchived(projectRoot, batchId)
106
+ ) {
107
+ return { allowed: false, reason: "archived_batch_resurrection" };
76
108
  }
77
109
 
78
110
  return { allowed: true };
@@ -5,6 +5,7 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { writeJsonAtomic } from "../fs/atomic-write.mjs";
8
+ import { appendJournalEvent } from "./journal.mjs";
8
9
  import { withBatchStateLock } from "./batch-state-lock.mjs";
9
10
  import {
10
11
  clearBatchEnginePid,
@@ -52,6 +53,69 @@ function archivedBatchStatePath(projectRoot, batchId) {
52
53
  return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
53
54
  }
54
55
 
56
+ /**
57
+ * Make a rejected batch-state write visible instead of silent (#293 / SP-790):
58
+ * journal `batch.state_write_rejected` (when the incoming state carries a batchId)
59
+ * and print one `[spine]` line to stderr so a swallowed late write is diagnosable.
60
+ *
61
+ * @param {string} projectRoot
62
+ * @param {Record<string, any>} state
63
+ * @param {string} reason
64
+ */
65
+ function reportRejectedBatchStateWrite(projectRoot, state, reason) {
66
+ const batchId = String(state?.batchId ?? "");
67
+ if (batchId) {
68
+ try {
69
+ appendJournalEvent(projectRoot, batchId, "batch.state_write_rejected", {
70
+ reason,
71
+ incomingPhase: String(state.phase ?? ""),
72
+ });
73
+ } catch {
74
+ /* journal failure must not turn a guarded no-op into a crash */
75
+ }
76
+ }
77
+ console.error(
78
+ `[spine] refused batch-state write (${reason}) for batch ${batchId || "unknown"} — keeping on-disk state`,
79
+ );
80
+ }
81
+
82
+ /**
83
+ * Guard + write path shared by `saveSpineBatchState` and `updateSpineBatchState`
84
+ * (SP-791 / #301). The caller must already hold the batch-state lock; the
85
+ * guard evaluation and the write run in one critical section so the
86
+ * check-then-act pair cannot race a concurrent writer from another process.
87
+ *
88
+ * Returns a structured result so callers can distinguish a rejected write
89
+ * (`{ ok: false, reason }`, disk state returned as `state`) from a persisted
90
+ * one (`{ ok: true, state: next }`).
91
+ *
92
+ * @param {string} projectRoot
93
+ * @param {Record<string, any>} state
94
+ * @param {{ bypassOwnerCheck?: boolean, allowArchivedResurrection?: boolean }} options
95
+ * @returns {{ ok: true, state: Record<string, any> } | { ok: false, reason: string, state: Record<string, any> }}
96
+ */
97
+ function persistSpineBatchStateGuarded(projectRoot, state, options) {
98
+ const guard = evaluateBatchStateWriteGuard(projectRoot, state, {
99
+ skipOwnerCheck: options.bypassOwnerCheck === true,
100
+ allowArchivedResurrection: options.allowArchivedResurrection === true,
101
+ });
102
+ if (!guard.allowed) {
103
+ const reason = String(guard.reason ?? "unknown");
104
+ reportRejectedBatchStateWrite(projectRoot, state, reason);
105
+ const loaded = loadSpineBatchState(projectRoot);
106
+ return { ok: false, reason, state: loaded.raw ?? state };
107
+ }
108
+
109
+ const filePath = spineBatchStatePath(projectRoot);
110
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
111
+ if (TERMINAL_BATCH_PHASES.has(String(state.phase ?? ""))) {
112
+ clearBatchEnginePid(state);
113
+ }
114
+ const next = { ...state, updatedAt: Date.now() };
115
+ writeJsonAtomic(filePath, next);
116
+ return { ok: true, state: next };
117
+ }
118
+
55
119
  /**
56
120
  * Persist batch state under the global batch-state lock (SP-722 / #264).
57
121
  *
@@ -59,29 +123,79 @@ function archivedBatchStatePath(projectRoot, batchId) {
59
123
  * check-then-act pair cannot race a concurrent writer from another process
60
124
  * (engine vs. CLI complete/resume/abort).
61
125
  *
126
+ * `bypassOwnerCheck: true` skips only the live-foreign-owner-PID check; the
127
+ * post-archive resurrection check always runs (SP-790 / #293).
128
+ * `allowArchivedResurrection: true` is reserved for operator recovery that
129
+ * intentionally rebuilds an archived batch (force-resume from batch-meta, #126).
130
+ *
131
+ * When the guard rejects, the on-disk state (or the incoming state when no
132
+ * disk state exists) is returned unchanged so existing callers keep their
133
+ * pre-SP-790 contract.
134
+ *
62
135
  * @param {string} projectRoot
63
136
  * @param {Record<string, any>} state
64
- * @param {{ bypassWriteGuard?: boolean }} [options]
137
+ * @param {{ bypassOwnerCheck?: boolean, allowArchivedResurrection?: boolean }} [options]
65
138
  */
66
139
  export function saveSpineBatchState(projectRoot, state, options = {}) {
67
- return withBatchStateLock(projectRoot, () => {
68
- const guard = options.bypassWriteGuard
69
- ? { allowed: true }
70
- : evaluateBatchStateWriteGuard(projectRoot, state);
71
- if (!guard.allowed) {
72
- const loaded = loadSpineBatchState(projectRoot);
73
- return loaded.raw ?? state;
74
- }
140
+ return withBatchStateLock(projectRoot, () =>
141
+ persistSpineBatchStateGuarded(projectRoot, state, options).state,
142
+ );
143
+ }
75
144
 
76
- const filePath = spineBatchStatePath(projectRoot);
77
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
78
- if (TERMINAL_BATCH_PHASES.has(String(state.phase ?? ""))) {
79
- clearBatchEnginePid(state);
145
+ /**
146
+ * Atomic read-modify-write on `.spine/batch-state.json` (SP-791 / #301).
147
+ *
148
+ * Load, clone, mutate, and guarded save all run inside ONE `withBatchStateLock`
149
+ * hold, so racing processes (engine progress save vs. operator pause/resume)
150
+ * each mutate the latest committed state instead of clobbering each other with
151
+ * stale whole-file snapshots. The lock is re-entrant per process, so callers
152
+ * may already hold it (e.g. under `withBatchStateLock`) and the nested
153
+ * acquisition composes instead of self-deadlocking.
154
+ *
155
+ * `mutate(draft, { diskState })` receives a `structuredClone` of the raw disk
156
+ * state plus the disk state itself for read-only reference; mutating `draft`
157
+ * never affects the returned `diskState`. Returning exactly `false` from
158
+ * `mutate` is a no-op: nothing is written and `{ changed: false }` is returned.
159
+ *
160
+ * Results:
161
+ * - `{ ok: false, reason: "missing" }` — no batch-state.json on disk
162
+ * - `{ ok: false, reason: "corrupt" }` — batch-state.json is unparseable
163
+ * - `{ ok: false, reason, state }` — the write guard rejected (e.g.
164
+ * `stale_engine_pid`, `archived_batch_resurrection`); `state` is the on-disk
165
+ * state that was kept
166
+ * - `{ ok: true, changed: false, state }` — `mutate` returned `false`;
167
+ * `state` is the untouched disk state
168
+ * - `{ ok: true, changed: true, state }` — mutated state persisted
169
+ *
170
+ * `options` passes through to the same guard/write path as
171
+ * `saveSpineBatchState` (`bypassOwnerCheck` / `allowArchivedResurrection`).
172
+ *
173
+ * @param {string} projectRoot
174
+ * @param {(draft: Record<string, any>, ctx: { diskState: Record<string, any> }) => boolean | unknown} mutate
175
+ * @param {{ bypassOwnerCheck?: boolean, allowArchivedResurrection?: boolean }} [options]
176
+ * @returns {{ ok: boolean, reason?: string, changed?: boolean, state?: Record<string, any> }}
177
+ */
178
+ export function updateSpineBatchState(projectRoot, mutate, options = {}) {
179
+ const result = /** @type {{ ok: boolean, reason?: string, changed?: boolean, state?: Record<string, any> }} */ (
180
+ withBatchStateLock(projectRoot, () => {
181
+ const loaded = loadSpineBatchState(projectRoot);
182
+ if (!loaded.raw) {
183
+ return { ok: false, reason: loaded.parseError ? "corrupt" : "missing" };
80
184
  }
81
- const next = { ...state, updatedAt: Date.now() };
82
- writeJsonAtomic(filePath, next);
83
- return next;
84
- });
185
+ const diskState = loaded.raw;
186
+ const draft = structuredClone(diskState);
187
+ const mutated = mutate(draft, { diskState });
188
+ if (mutated === false) {
189
+ return { ok: true, changed: false, state: diskState };
190
+ }
191
+ const persisted = persistSpineBatchStateGuarded(projectRoot, draft, options);
192
+ if (!persisted.ok) {
193
+ return { ok: false, reason: persisted.reason, state: persisted.state };
194
+ }
195
+ return { ok: true, changed: true, state: persisted.state };
196
+ })
197
+ );
198
+ return result;
85
199
  }
86
200
 
87
201
  /**
@@ -21,6 +21,7 @@ export {
21
21
  spineBatchStatePath,
22
22
  loadSpineBatchState,
23
23
  saveSpineBatchState,
24
+ updateSpineBatchState,
24
25
  batchHistoryPath,
25
26
  resolveBatchStateFileForValidation,
26
27
  appendBatchHistoryEntry,
@@ -183,10 +183,12 @@ export async function runWorker({
183
183
  return { ok: true, exitCode: 0, mode: "already-done" };
184
184
  }
185
185
 
186
- const useStub =
187
- process.env.SPINE_WORKER_STUB === "1" ||
188
- process.env.SPINE_WORKER_STUB === "true" ||
189
- (!commandExists("pi") && resolveWorkerBackend(config) !== "agentSession");
186
+ const stubExplicit =
187
+ process.env.SPINE_WORKER_STUB === "1" || process.env.SPINE_WORKER_STUB === "true";
188
+ // #299 (SP-801): the stub is opt-in only. The old implicit fallback
189
+ // (missing `pi` → stub) could mark review-level-0 tasks done with no work
190
+ // when PATH lacked `pi`; the fail-closed guard below replaces it.
191
+ const useStub = stubExplicit;
190
192
 
191
193
  const workerBackend = useStub ? "subprocess" : resolveWorkerBackend(config);
192
194
  const workerMode = useStub ? "stub" : workerBackend === "agentSession" ? "agentSession" : "pi";
@@ -229,6 +231,32 @@ export async function runWorker({
229
231
  const isExecute = parsedPrompt?.type === "execute";
230
232
  const runCommand = contract.runCommand || contract.testCommand;
231
233
 
234
+ // #299 (SP-801): fail closed when the pi CLI is missing rather than silently
235
+ // falling back to the stub. Placed after the review gate so review-tool
236
+ // unavailability keeps its `review_failed` precedence, and scoped to
237
+ // non-execute tasks (execute-only runs the contract command, never `pi`);
238
+ // agentSession workers spawn in-process and never consult PATH for `pi`.
239
+ if (!stubExplicit && !isExecute && workerBackend !== "agentSession" && !commandExists("pi")) {
240
+ if (projectRoot && batchId) {
241
+ appendJournalEvent(projectRoot, batchId, "worker.spawn_failed", {
242
+ taskId,
243
+ laneNumber,
244
+ correlationId: laneCorrelationId,
245
+ reason: "pi_missing",
246
+ phase: "preflight",
247
+ });
248
+ }
249
+ return {
250
+ ok: false,
251
+ exitCode: 1,
252
+ mode: workerMode,
253
+ output:
254
+ "worker requires pi on PATH (fail closed); set SPINE_WORKER_STUB=1 only for stub runs",
255
+ classification: "launch_failed",
256
+ doneFound: false,
257
+ };
258
+ }
259
+
232
260
  const child = isExecute
233
261
  ? spawnExecutionOnlyHandle({
234
262
  worktreePath,