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
@@ -11,15 +11,14 @@ import {
11
11
  } from "./diagnosis-pending-lane.mjs";
12
12
  import {
13
13
  archiveBatchState,
14
- cleanupBatchLaneWorktrees,
15
14
  clearCompletedBatchState,
15
+ reloadStateForTerminalWrite,
16
16
  } from "./lifecycle-archive.mjs";
17
17
  export { archiveBatchStatePath } from "./lifecycle-archive.mjs";
18
+ import { runLifecycleCleanupAfterRelease } from "./lifecycle-cleanup.mjs";
18
19
  import { assertOrchIntegratable } from "./integrate.mjs";
19
- import { loadSpineConfig } from "../config/spine-config-load.mjs";
20
20
  import { appendJournalEvent } from "./journal.mjs";
21
- import { recordBatchTerminalMetric } from "./metrics.mjs";
22
- import { writeBatchPostMortem } from "./postmortem.mjs";
21
+ import { postMortemRelPath } from "./postmortem.mjs";
23
22
  import { appendBatchHistoryEntry, clearBatchEnginePid, saveSpineBatchState } from "./state.mjs";
24
23
  import { withBatchStateLock } from "./batch-state-lock.mjs";
25
24
  import { loadBatchStateFile, parseBatchState, reconcileBatch } from "./reconcile.mjs";
@@ -208,16 +207,29 @@ export function dismissBatch(ctx) {
208
207
  });
209
208
  }
210
209
  // Terminal dismiss write section under the global batch-state lock
211
- // (SP-722 / #264): archive, history entry, and clearing the active state
212
- // must not interleave with a concurrent engine save or resume writer.
213
- return withBatchStateLock(projectRoot, () => {
214
- const archivePath = archiveBatchState(projectRoot, batchId, loaded.raw);
215
- const postMortemPath = writeBatchPostMortem({
210
+ // (SP-722 / #264; SP-796 / #302): archive, history entry, journal event,
211
+ // and clearing the active state must not interleave with a concurrent
212
+ // engine save or resume writer. Post-mortem, metrics, and worktree
213
+ // cleanup run after the lock is released.
214
+ const inLock = withBatchStateLock(projectRoot, () => {
215
+ // SP-792 / #301: archive from the state re-read inside the lock; fail
216
+ // closed when the batch changed or became active again mid-dismiss.
217
+ const { state: fresh, refusal } = reloadStateForTerminalWrite({
216
218
  projectRoot,
217
- batchState: loaded.raw,
218
- reconciliation,
219
+ batchStatePath: loaded.path,
220
+ batchId,
221
+ action: "dismiss",
222
+ requireTerminalPhase: true,
223
+ force,
224
+ diagnosis,
219
225
  });
226
+ if (refusal) return { refusal, archivePath: null, fresh: null, endedAt: 0 };
227
+
228
+ const archivePath = archiveBatchState(projectRoot, batchId, fresh.raw);
220
229
  const endedAt = Date.now();
230
+ // Deterministic post-mortem location: the file itself is written after
231
+ // release (SP-796), but the history entry carries the exact path
232
+ // `writeBatchPostMortem` reports, so lookups keep working.
221
233
  appendBatchHistoryEntry(projectRoot, {
222
234
  batchId,
223
235
  action: "dismissed",
@@ -225,42 +237,46 @@ export function dismissBatch(ctx) {
225
237
  diagnosis,
226
238
  reason: reason ?? null,
227
239
  archivePath: path.relative(projectRoot, archivePath),
228
- postMortemPath,
240
+ postMortemPath: postMortemRelPath(batchId),
229
241
  });
230
242
  appendJournalEvent(projectRoot, batchId, "batch.dismissed", {
231
243
  diagnosis,
232
244
  reason: reason ?? null,
233
245
  archivePath: path.relative(projectRoot, archivePath),
234
246
  });
235
- const configResult = loadSpineConfig(projectRoot);
236
- const config = configResult.config ?? {};
237
- recordBatchTerminalMetric({
238
- projectRoot,
239
- batchId,
240
- batchState: { ...loaded.raw, endedAt },
241
- diagnosis: diagnosis ?? "dismissed",
242
- config,
243
- });
244
- cleanupBatchLaneWorktrees({
245
- projectRoot,
246
- batchId,
247
- batchState: loaded.raw,
248
- config,
249
- });
250
- clearCompletedBatchState(projectRoot, loaded.path, batchId);
247
+ clearCompletedBatchState(projectRoot, fresh.path, batchId);
251
248
  bumpDashboardInvalidateSignal(projectRoot, "batch_dismiss", batchId);
252
249
 
253
- return {
254
- ok: true,
255
- exitCode: 0,
256
- batchId,
257
- diagnosis,
258
- headline: `Batch ${batchId} dismissed and archived`,
259
- suggestedCommand: "spine preflight",
260
- alternatives: ["spine plan all"],
261
- archivePath,
262
- };
250
+ return { refusal: null, archivePath, fresh, endedAt };
263
251
  });
252
+
253
+ // Cleanup runs only when the in-lock section succeeded (archived and
254
+ // journaled `batch.dismissed`); a refusal archived nothing for this batch.
255
+ if (inLock.refusal) return inLock.refusal;
256
+
257
+ // SP-796 / #302: post-mortem, metrics, and worktree cleanup run after the
258
+ // lock is released; failures are reported as cleanupWarnings +
259
+ // `batch.cleanup_failed`, never thrown after the state was archived.
260
+ const cleanupWarnings = runLifecycleCleanupAfterRelease({
261
+ projectRoot,
262
+ batchId,
263
+ batchState: inLock.fresh.raw,
264
+ reconciliation,
265
+ diagnosis: diagnosis ?? "dismissed",
266
+ endedAt: inLock.endedAt,
267
+ });
268
+
269
+ return {
270
+ ok: true,
271
+ exitCode: 0,
272
+ batchId,
273
+ diagnosis,
274
+ headline: `Batch ${batchId} dismissed and archived`,
275
+ suggestedCommand: "spine preflight",
276
+ alternatives: ["spine plan all"],
277
+ archivePath: inLock.archivePath,
278
+ cleanupWarnings,
279
+ };
264
280
  }
265
281
 
266
282
  /**
@@ -414,16 +430,25 @@ export function completeBatch(ctx) {
414
430
  terminateSupervisorIfRunning(projectRoot, batchId, "batch_complete");
415
431
 
416
432
  // Terminal complete write section under the global batch-state lock
417
- // (SP-722 / #264): archive, history entry, and clearing the active state
418
- // must not interleave with a concurrent engine save or resume writer.
419
- return withBatchStateLock(projectRoot, () => {
420
- const archivePath = archiveBatchState(projectRoot, batchId, loaded.raw);
421
- const postMortemPath = writeBatchPostMortem({
433
+ // (SP-722 / #264; SP-796 / #302) — same split as dismiss: state I/O only,
434
+ // post-mortem/metrics/worktrees after release.
435
+ const inLock = withBatchStateLock(projectRoot, () => {
436
+ // SP-792 / #301: archive from the state re-read inside the lock; fail
437
+ // closed when the batch changed or became active again mid-complete.
438
+ const { state: fresh, refusal } = reloadStateForTerminalWrite({
422
439
  projectRoot,
423
- batchState: loaded.raw,
424
- reconciliation,
440
+ batchStatePath: loaded.path,
441
+ batchId,
442
+ action: "complete",
443
+ requireTerminalPhase: true,
425
444
  });
445
+ if (refusal) return { refusal, archivePath: null, fresh: null, endedAt: 0 };
446
+
447
+ const archivePath = archiveBatchState(projectRoot, batchId, fresh.raw);
426
448
  const endedAt = Date.now();
449
+ // Deterministic post-mortem location: the file itself is written after
450
+ // release (SP-796), but the history entry carries the exact path
451
+ // `writeBatchPostMortem` reports, so lookups keep working.
427
452
  appendBatchHistoryEntry(projectRoot, {
428
453
  batchId,
429
454
  action: "completed",
@@ -431,39 +456,42 @@ export function completeBatch(ctx) {
431
456
  diagnosis: "completed",
432
457
  detectManualMerge,
433
458
  archivePath: path.relative(projectRoot, archivePath),
434
- postMortemPath,
459
+ postMortemPath: postMortemRelPath(batchId),
435
460
  });
436
461
  appendJournalEvent(projectRoot, batchId, "batch.completed", {
437
462
  detectManualMerge,
438
463
  archivePath: path.relative(projectRoot, archivePath),
439
464
  lifecycle: "complete",
440
465
  });
441
- const configResult = loadSpineConfig(projectRoot);
442
- const config = configResult.config ?? {};
443
- recordBatchTerminalMetric({
444
- projectRoot,
445
- batchId,
446
- batchState: { ...loaded.raw, endedAt },
447
- diagnosis: "completed",
448
- config,
449
- });
450
- cleanupBatchLaneWorktrees({
451
- projectRoot,
452
- batchId,
453
- batchState: loaded.raw,
454
- config,
455
- });
456
- clearCompletedBatchState(projectRoot, loaded.path, batchId);
466
+ clearCompletedBatchState(projectRoot, fresh.path, batchId);
457
467
 
458
- return {
459
- ok: true,
460
- exitCode: 0,
461
- batchId,
462
- diagnosis: "completed",
463
- headline: `Batch ${batchId} completed and archived`,
464
- suggestedCommand: "spine preflight",
465
- alternatives: ["spine plan all"],
466
- archivePath,
467
- };
468
+ return { refusal: null, archivePath, fresh, endedAt };
469
+ });
470
+
471
+ // Cleanup runs only when the in-lock section succeeded (archived and
472
+ // journaled `batch.completed`); a refusal archived nothing for this batch.
473
+ if (inLock.refusal) return inLock.refusal;
474
+
475
+ // SP-796 / #302: same post-release split as dismiss — failures become
476
+ // cleanupWarnings + `batch.cleanup_failed`, never thrown post-archive.
477
+ const cleanupWarnings = runLifecycleCleanupAfterRelease({
478
+ projectRoot,
479
+ batchId,
480
+ batchState: inLock.fresh.raw,
481
+ reconciliation,
482
+ diagnosis: "completed",
483
+ endedAt: inLock.endedAt,
468
484
  });
485
+
486
+ return {
487
+ ok: true,
488
+ exitCode: 0,
489
+ batchId,
490
+ diagnosis: "completed",
491
+ headline: `Batch ${batchId} completed and archived`,
492
+ suggestedCommand: "spine preflight",
493
+ alternatives: ["spine plan all"],
494
+ archivePath: inLock.archivePath,
495
+ cleanupWarnings,
496
+ };
469
497
  }
@@ -12,11 +12,10 @@ import { resolveAttachedMilestonePollMs } from "../config/spine-config-schema.mj
12
12
  import { appendJournalEvent } from "./journal.mjs";
13
13
  import {
14
14
  clearBatchEnginePid,
15
- loadSpineBatchState,
16
15
  readBatchEnginePid,
17
16
  recomputeTaskCounters,
18
- saveSpineBatchState,
19
17
  updateSegmentForTask,
18
+ updateSpineBatchState,
20
19
  } from "./state.mjs";
21
20
 
22
21
  /**
@@ -56,6 +55,14 @@ export function isParentSessionLost({
56
55
  /**
57
56
  * Fail-closed reconcile when the attached engine parent session is gone.
58
57
  *
58
+ * The whole reconcile is one `updateSpineBatchState` read-modify-write
59
+ * (SP-793 / #301): the phase is re-checked under the lock on the latest
60
+ * committed state, and the persist goes through the write guard with no owner
61
+ * bypass — the recorded owner is the dead parent engine, so the guard allows
62
+ * the write; if ownership was handed to a live detached child meanwhile, the
63
+ * loud guard rejection is the correct outcome instead of clobbering the new
64
+ * owner's state.
65
+ *
59
66
  * @param {object} params
60
67
  * @param {string} params.projectRoot
61
68
  * @param {number} params.parentPid
@@ -63,85 +70,85 @@ export function isParentSessionLost({
63
70
  * @returns {{ handled: boolean, batchId?: string, taskIds?: string[] }}
64
71
  */
65
72
  export function reconcileParentSessionLost({ projectRoot, parentPid, enginePid = process.pid }) {
66
- const loaded = loadSpineBatchState(projectRoot);
67
- const state = loaded.raw;
68
- if (!state || typeof state !== "object") {
69
- return { handled: false };
70
- }
73
+ /** @type {{ handled: boolean, batchId?: string, taskIds?: string[] }} */
74
+ let outcome = { handled: false };
75
+ updateSpineBatchState(projectRoot, (draft) => {
76
+ const batchId = String(draft.batchId ?? "");
77
+ if (!batchId) {
78
+ return false;
79
+ }
71
80
 
72
- const batchId = String(state.batchId ?? "");
73
- if (!batchId) {
74
- return { handled: false };
75
- }
81
+ const phase = String(draft.phase ?? "");
82
+ if (phase === "completed" || phase === "aborted" || phase === "failed") {
83
+ outcome = { handled: false, batchId };
84
+ return false;
85
+ }
76
86
 
77
- const phase = String(state.phase ?? "");
78
- if (phase === "completed" || phase === "aborted" || phase === "failed") {
79
- return { handled: false, batchId };
80
- }
87
+ appendJournalEvent(projectRoot, batchId, "engine.parent_died", {
88
+ parentPid,
89
+ enginePid,
90
+ signal: "parent_exit",
91
+ });
81
92
 
82
- appendJournalEvent(projectRoot, batchId, "engine.parent_died", {
83
- parentPid,
84
- enginePid,
85
- signal: "parent_exit",
86
- });
93
+ const now = Date.now();
94
+ /** @type {string[]} */
95
+ const failedTaskIds = [];
96
+ let changed = false;
87
97
 
88
- const now = Date.now();
89
- /** @type {string[]} */
90
- const failedTaskIds = [];
91
- let changed = false;
92
-
93
- for (const task of state.tasks ?? []) {
94
- if (!task || typeof task !== "object") continue;
95
- if (String(task.status ?? "").toLowerCase() !== "running") continue;
96
-
97
- const taskId = String(task.taskId ?? "");
98
- if (!taskId) continue;
99
-
100
- task.status = "failed";
101
- task.endedAt = now;
102
- task.exitReason = "parent_exit";
103
- updateSegmentForTask(state, taskId, "failed");
104
- failedTaskIds.push(taskId);
105
- changed = true;
106
-
107
- const laneNumber = Number(task.laneNumber ?? 1);
108
- const lane = (state.lanes ?? []).find((entry) => Number(entry?.laneNumber) === laneNumber);
109
- appendJournalEvent(projectRoot, batchId, "task.failed", {
110
- taskId,
111
- laneNumber,
112
- laneId: lane?.laneId ?? `lane-${laneNumber}`,
113
- reason: "parent_exit",
114
- reconciled: true,
115
- });
116
- }
98
+ for (const task of draft.tasks ?? []) {
99
+ if (!task || typeof task !== "object") continue;
100
+ if (String(task.status ?? "").toLowerCase() !== "running") continue;
117
101
 
118
- for (const lane of state.lanes ?? []) {
119
- if (!lane || typeof lane !== "object") continue;
120
- const workerPid = Number(/** @type {{ workerPid?: number }} */ (lane).workerPid);
121
- if (Number.isFinite(workerPid) && workerPid > 0 && !isProcessAlive(workerPid)) {
122
- delete lane.workerPid;
102
+ const taskId = String(task.taskId ?? "");
103
+ if (!taskId) continue;
104
+
105
+ task.status = "failed";
106
+ task.endedAt = now;
107
+ task.exitReason = "parent_exit";
108
+ updateSegmentForTask(draft, taskId, "failed");
109
+ failedTaskIds.push(taskId);
123
110
  changed = true;
111
+
112
+ const laneNumber = Number(task.laneNumber ?? 1);
113
+ const lane = (draft.lanes ?? []).find((entry) => Number(entry?.laneNumber) === laneNumber);
114
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
115
+ taskId,
116
+ laneNumber,
117
+ laneId: lane?.laneId ?? `lane-${laneNumber}`,
118
+ reason: "parent_exit",
119
+ reconciled: true,
120
+ });
124
121
  }
125
- }
126
122
 
127
- const recordedEnginePid = readBatchEnginePid(state);
128
- if (recordedEnginePid != null) {
129
- clearBatchEnginePid(state);
130
- changed = true;
131
- }
123
+ for (const lane of draft.lanes ?? []) {
124
+ if (!lane || typeof lane !== "object") continue;
125
+ const workerPid = Number(/** @type {{ workerPid?: number }} */ (lane).workerPid);
126
+ if (Number.isFinite(workerPid) && workerPid > 0 && !isProcessAlive(workerPid)) {
127
+ delete lane.workerPid;
128
+ changed = true;
129
+ }
130
+ }
132
131
 
133
- if (phase !== "paused") {
134
- state.phase = "paused";
135
- changed = true;
136
- }
132
+ const recordedEnginePid = readBatchEnginePid(draft);
133
+ if (recordedEnginePid != null) {
134
+ clearBatchEnginePid(draft);
135
+ changed = true;
136
+ }
137
137
 
138
- if (!changed) {
139
- return { handled: true, batchId, taskIds: failedTaskIds };
140
- }
138
+ if (phase !== "paused") {
139
+ draft.phase = "paused";
140
+ changed = true;
141
+ }
142
+
143
+ outcome = { handled: true, batchId, taskIds: failedTaskIds };
144
+ if (!changed) {
145
+ return false;
146
+ }
141
147
 
142
- recomputeTaskCounters(state);
143
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
144
- return { handled: true, batchId, taskIds: failedTaskIds };
148
+ recomputeTaskCounters(draft);
149
+ return true;
150
+ });
151
+ return outcome;
145
152
  }
146
153
 
147
154
  /**
@@ -5,12 +5,14 @@
5
5
  */
6
6
 
7
7
  import { isProcessAlive } from "../process/liveness.mjs";
8
+ import { withBatchStateLockAsync } from "./batch-state-lock.mjs";
8
9
  import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
9
10
  import { recordResumePhaseTransition } from "./resume-common.mjs";
10
11
  import {
11
12
  loadSpineBatchState,
12
13
  readBatchEnginePid,
13
14
  saveSpineBatchState,
15
+ updateSpineBatchState,
14
16
  } from "./state.mjs";
15
17
 
16
18
  /** Grace period for attached engine to persist phase: paused (SP-376). */
@@ -62,31 +64,61 @@ export function mergeEngineStateWithDiskPause(projectRoot, state) {
62
64
  /**
63
65
  * Persist engine state while honoring an operator pause already on disk or in the journal.
64
66
  *
67
+ * The pause merge (a disk read) and the save run inside one async
68
+ * `withBatchStateLockAsync` hold (SP-791 / #301, SP-797 / #302): previously the
69
+ * merge ran before the lock, so an operator pause landing between the merge and
70
+ * the write was clobbered by the engine's whole-file snapshot; and the wait for
71
+ * a contended lock must not block the engine's event loop. The lock is
72
+ * re-entrant per process, so the nested `saveSpineBatchState` acquisition
73
+ * composes instead of self-deadlocking. All callers are engine-side and async
74
+ * (Step 0 of SP-797 found no synchronous non-engine callers), so no sync
75
+ * fallback path is kept — CLI callers keep the synchronous
76
+ * `withBatchStateLock` via `state-io.mjs` / `updateSpineBatchState`.
77
+ *
65
78
  * @param {string} projectRoot
66
79
  * @param {object} state
67
- * @param {{ bypassWriteGuard?: boolean }} [options]
80
+ * @param {{ bypassOwnerCheck?: boolean }} [options]
81
+ * @returns {Promise<unknown>}
68
82
  */
69
- export function saveEngineBatchState(projectRoot, state, options = {}) {
70
- mergeEngineStateWithDiskPause(projectRoot, state);
71
- return saveSpineBatchState(projectRoot, state, options);
83
+ export async function saveEngineBatchState(projectRoot, state, options = {}) {
84
+ return withBatchStateLockAsync(projectRoot, () => {
85
+ mergeEngineStateWithDiskPause(projectRoot, state);
86
+ return saveSpineBatchState(projectRoot, state, options);
87
+ });
72
88
  }
73
89
 
74
90
  /**
75
91
  * Re-assert phase: paused on disk when the operator paused but a running engine overwrote it.
76
92
  *
93
+ * The read-modify-write runs through `updateSpineBatchState` so the phase check
94
+ * and the write are one atomic section (SP-791 / #301). Returns true when the
95
+ * disk ends up paused — already paused (nothing to re-assert) or re-asserted by
96
+ * this call — and false when there is no usable state, no batchId, no active
97
+ * pause, or the write was refused.
98
+ *
77
99
  * @param {string} projectRoot
78
100
  * @returns {boolean}
79
101
  */
80
102
  export function enforceOperatorPauseOnDisk(projectRoot) {
81
- const loaded = loadSpineBatchState(projectRoot);
82
- if (!loaded.raw) return false;
83
- const batchId = String(loaded.raw.batchId ?? "");
84
- if (!batchId) return false;
85
- if (loaded.raw.phase === "paused") return true;
86
- if (!isOperatorPauseActive(projectRoot, batchId)) return false;
87
- loaded.raw.phase = "paused";
88
- saveSpineBatchState(projectRoot, loaded.raw, { bypassWriteGuard: true });
89
- return true;
103
+ let enforced = false;
104
+ const result = updateSpineBatchState(
105
+ projectRoot,
106
+ (draft, { diskState }) => {
107
+ const batchId = String(diskState.batchId ?? "");
108
+ if (!batchId) return false;
109
+ if (diskState.phase === "paused") {
110
+ // Operator pause is already on disk — nothing to re-assert.
111
+ enforced = true;
112
+ return false;
113
+ }
114
+ if (!isOperatorPauseActive(projectRoot, batchId)) return false;
115
+ draft.phase = "paused";
116
+ enforced = true;
117
+ return true;
118
+ },
119
+ { bypassOwnerCheck: true },
120
+ );
121
+ return result.ok === true && enforced;
90
122
  }
91
123
 
92
124
  /**
@@ -96,10 +128,10 @@ export function enforceOperatorPauseOnDisk(projectRoot) {
96
128
  * @param {string} params.batchId
97
129
  * @returns {{ stop: boolean }}
98
130
  */
99
- export function adoptPauseIfRequested({ projectRoot, state, batchId }) {
131
+ export async function adoptPauseIfRequested({ projectRoot, state, batchId }) {
100
132
  const paused = mergeEngineStateWithDiskPause(projectRoot, state);
101
133
  if (!paused) return { stop: false };
102
- saveEngineBatchState(projectRoot, state);
134
+ await saveEngineBatchState(projectRoot, state);
103
135
  appendJournalEvent(projectRoot, batchId, "engine.pause_observed", {
104
136
  enginePid: process.pid,
105
137
  });
@@ -182,8 +214,33 @@ export async function pauseBatch({
182
214
  const attachedEngineAlive =
183
215
  enginePid != null && enginePid !== process.pid && isProcessAlive(enginePid);
184
216
 
185
- state.phase = "paused";
186
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
217
+ // Initial pause write as an atomic read-modify-write (SP-791 / #301): the
218
+ // phase is re-checked under the lock so a state change that landed after the
219
+ // pre-load (operator re-pause, engine completing the batch) is respected
220
+ // instead of being overwritten by this potentially stale snapshot.
221
+ const pauseWrite = updateSpineBatchState(
222
+ projectRoot,
223
+ (draft, { diskState }) => {
224
+ const diskPhase = String(diskState.phase ?? "");
225
+ if (diskPhase !== "running" && diskPhase !== "planning") return false;
226
+ draft.phase = "paused";
227
+ return true;
228
+ },
229
+ { bypassOwnerCheck: true },
230
+ );
231
+ const diskPhase = String(pauseWrite.state?.phase ?? phase ?? "unknown");
232
+ if (!pauseWrite.ok || (!pauseWrite.changed && diskPhase !== "paused")) {
233
+ // State changed (or vanished/corrupted) between the pre-load and the
234
+ // locked write — report the observed phase rather than the stale one.
235
+ return {
236
+ ok: false,
237
+ exitCode: 1,
238
+ error: "cannot_pause",
239
+ output: `Cannot pause batch in phase ${diskPhase}. Only running or planning batches can be paused.\n`,
240
+ batchId,
241
+ phase: diskPhase,
242
+ };
243
+ }
187
244
 
188
245
  if (attachedEngineAlive) {
189
246
  const confirmed = await waitForPauseConfirmation({
@@ -194,20 +251,30 @@ export async function pauseBatch({
194
251
  });
195
252
 
196
253
  if (!confirmed) {
197
- const current = loadSpineBatchState(projectRoot).raw;
198
- const currentPhase = String(current?.phase ?? "unknown");
199
- if (current) {
200
- current.phase = fromPhase;
201
- saveSpineBatchState(projectRoot, current, { bypassWriteGuard: true });
202
- }
254
+ // Roll back only while the disk phase is still our unconfirmed "paused";
255
+ // a terminal phase (completed/failed/aborted/merge_blocked) or an engine
256
+ // rewrite that landed during the grace window must never be reverted to
257
+ // fromPhase (SP-791 / #301 — the rollback could otherwise resurrect a
258
+ // completed batch as running).
259
+ let observedPhase = "unknown";
260
+ updateSpineBatchState(
261
+ projectRoot,
262
+ (draft, { diskState }) => {
263
+ observedPhase = String(diskState.phase ?? "unknown");
264
+ if (diskState.phase !== "paused") return false;
265
+ draft.phase = fromPhase;
266
+ return true;
267
+ },
268
+ { bypassOwnerCheck: true },
269
+ );
203
270
  appendJournalEvent(projectRoot, batchId, "batch.pause_failed", {
204
271
  fromPhase,
205
272
  enginePid,
206
- observedPhase: currentPhase,
273
+ observedPhase,
207
274
  graceMs: confirmGraceMs,
208
275
  });
209
276
  const output =
210
- `Pause not confirmed: batch-state phase is still "${currentPhase}" after ${confirmGraceMs}ms.\n` +
277
+ `Pause not confirmed: batch-state phase is still "${observedPhase}" after ${confirmGraceMs}ms.\n` +
211
278
  `Attached engine (PID ${enginePid}) did not persist phase: paused — batch.paused was not recorded.\n` +
212
279
  "Stop the attached engine or wait for the current step to finish, then run spine batch pause again.\n" +
213
280
  "spine batch retry is blocked while phase is running — retry only after phase is paused.\n";