pi-spine 2.24.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 (53) hide show
  1. package/bin/spine-worker-runner.mjs +2 -1
  2. package/package.json +1 -1
  3. package/src/batch/abort.mjs +74 -38
  4. package/src/batch/attached-engine-handoff.mjs +2 -2
  5. package/src/batch/attached-runner-promote.mjs +15 -1
  6. package/src/batch/attached-runner-reconcile.mjs +1 -1
  7. package/src/batch/batch-meta-reconstruct.mjs +6 -1
  8. package/src/batch/batch-state-io.mjs +120 -45
  9. package/src/batch/batch-state-lock.mjs +173 -31
  10. package/src/batch/contract-exec.mjs +46 -45
  11. package/src/batch/contract-spawn.mjs +225 -0
  12. package/src/batch/contract-verify.mjs +2 -1
  13. package/src/batch/detached-wait.mjs +1 -1
  14. package/src/batch/engine-crash-guard.mjs +143 -0
  15. package/src/batch/engine-lanes/matrix-run.mjs +34 -8
  16. package/src/batch/engine-lanes/matrix.mjs +143 -8
  17. package/src/batch/engine-lanes/merge.mjs +135 -34
  18. package/src/batch/engine-lanes/review-final.mjs +1 -1
  19. package/src/batch/engine-lanes.mjs +11 -9
  20. package/src/batch/engine.mjs +10 -10
  21. package/src/batch/integrate-dirty-overlap.mjs +35 -0
  22. package/src/batch/integrate-worktree.mjs +106 -13
  23. package/src/batch/integrate.mjs +34 -93
  24. package/src/batch/journal-checksum.mjs +26 -0
  25. package/src/batch/journal.mjs +32 -13
  26. package/src/batch/lifecycle-archive.mjs +84 -3
  27. package/src/batch/lifecycle-cleanup.mjs +110 -0
  28. package/src/batch/lifecycle.mjs +100 -72
  29. package/src/batch/parent-session-monitor.mjs +77 -70
  30. package/src/batch/pause.mjs +92 -25
  31. package/src/batch/post-merge-limbo.mjs +35 -5
  32. package/src/batch/reconcile-batch.mjs +13 -1
  33. package/src/batch/resume-gate-reopen.mjs +24 -8
  34. package/src/batch/resume-multi.mjs +1 -1
  35. package/src/batch/resume.mjs +1 -1
  36. package/src/batch/salvage-batch-integrate.mjs +13 -17
  37. package/src/batch/sequence-run.mjs +26 -8
  38. package/src/batch/sequence-wait.mjs +87 -8
  39. package/src/batch/state-guards.mjs +39 -7
  40. package/src/batch/state-io.mjs +131 -17
  41. package/src/batch/state.mjs +23 -1
  42. package/src/batch/worker-heartbeat.mjs +29 -8
  43. package/src/batch/worker-host.mjs +61 -8
  44. package/src/batch/worker-output.mjs +9 -6
  45. package/src/batch/worker-prompt.mjs +4 -2
  46. package/src/batch/worker-spawn.mjs +99 -12
  47. package/src/config/defaults.mjs +15 -1
  48. package/src/config/preflight/discovery.mjs +20 -12
  49. package/src/config/preflight/git-batch.mjs +47 -0
  50. package/src/config/spine-config-schema.mjs +67 -1
  51. package/src/fs/atomic-write.mjs +37 -1
  52. package/src/planner/scope.mjs +3 -1
  53. package/src/tasks/packet/discover.mjs +59 -3
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Post-release cleanup for terminal batch lifecycle writes (SP-796 / #302).
3
+ *
4
+ * abort/complete/dismiss hold the global batch-state lock only for state
5
+ * I/O (in-lock reload, archive write, history append, terminal journal
6
+ * event, active-state clear). Post-mortem, metrics, worker termination and
7
+ * worktree cleanup run after the lock is released so concurrent engine
8
+ * saves are never blocked behind them.
9
+ *
10
+ * A failure in this phase must never throw: the batch state was already
11
+ * archived and journaled terminal, so an exception could only turn a
12
+ * finished batch into a reported failure. Each failed step is reported in
13
+ * the caller's `cleanupWarnings` and journaled as `batch.cleanup_failed`
14
+ * `{ step, error }` instead.
15
+ */
16
+
17
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
18
+ import { appendJournalEvent } from "./journal.mjs";
19
+ import { cleanupBatchLaneWorktrees } from "./lifecycle-archive.mjs";
20
+ import { recordBatchTerminalMetric } from "./metrics.mjs";
21
+ import { writeBatchPostMortem } from "./postmortem.mjs";
22
+
23
+ /**
24
+ * Run named cleanup steps after the batch-state lock was released. Steps run
25
+ * in order; a failing step records a warning and journals `batch.cleanup_failed`
26
+ * but never stops the remaining steps or throws to the caller.
27
+ *
28
+ * @param {object} params
29
+ * @param {string} params.projectRoot
30
+ * @param {string} params.batchId
31
+ * @param {Array<{ step: string, run: () => void }>} params.steps
32
+ * @returns {string[]} `cleanupWarnings` — one `"<step>: <error>"` per failed step
33
+ */
34
+ export function runPostReleaseCleanup({ projectRoot, batchId, steps }) {
35
+ const warnings = [];
36
+ for (const { step, run } of steps) {
37
+ try {
38
+ run();
39
+ } catch (err) {
40
+ const message = err instanceof Error ? err.message : String(err);
41
+ warnings.push(`${step}: ${message}`);
42
+ try {
43
+ appendJournalEvent(projectRoot, batchId, "batch.cleanup_failed", {
44
+ step,
45
+ error: message,
46
+ });
47
+ } catch {
48
+ // Journal I/O failing while reporting a cleanup failure must not
49
+ // mask the terminal result — the warning string still carries it.
50
+ }
51
+ }
52
+ }
53
+ return warnings;
54
+ }
55
+
56
+ /**
57
+ * Post-release cleanup shared by dismiss and complete (SP-796 / #302):
58
+ * post-mortem write, terminal metrics, and lane-worktree cleanup — all after
59
+ * the in-lock section archived the state and journaled the terminal event.
60
+ *
61
+ * @param {object} params
62
+ * @param {string} params.projectRoot
63
+ * @param {string} params.batchId
64
+ * @param {object} params.batchState the in-lock snapshot that was archived
65
+ * @param {import("./reconcile.mjs").ReconciliationResult} [params.reconciliation]
66
+ * @param {string} params.diagnosis
67
+ * @param {number} params.endedAt
68
+ * @returns {string[]} `cleanupWarnings`
69
+ */
70
+ export function runLifecycleCleanupAfterRelease({
71
+ projectRoot,
72
+ batchId,
73
+ batchState,
74
+ reconciliation,
75
+ diagnosis,
76
+ endedAt,
77
+ }) {
78
+ return runPostReleaseCleanup({
79
+ projectRoot,
80
+ batchId,
81
+ steps: [
82
+ {
83
+ step: "post_mortem",
84
+ run: () => {
85
+ writeBatchPostMortem({ projectRoot, batchState, reconciliation });
86
+ },
87
+ },
88
+ {
89
+ step: "metrics",
90
+ run: () => {
91
+ const config = loadSpineConfig(projectRoot).config ?? {};
92
+ recordBatchTerminalMetric({
93
+ projectRoot,
94
+ batchId,
95
+ batchState: { ...batchState, endedAt },
96
+ diagnosis,
97
+ config,
98
+ });
99
+ },
100
+ },
101
+ {
102
+ step: "worktrees",
103
+ run: () => {
104
+ const config = loadSpineConfig(projectRoot).config ?? {};
105
+ cleanupBatchLaneWorktrees({ projectRoot, batchId, batchState, config });
106
+ },
107
+ },
108
+ ],
109
+ });
110
+ }
@@ -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(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(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
  /**