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
@@ -36,6 +36,7 @@ import {
36
36
  writeWorkerDoneMarker,
37
37
  } from "../src/batch/worker-output.mjs";
38
38
  import { buildWorkerTailPrompt, taskIdFromFolder } from "../src/batch/worker-prompt.mjs";
39
+ import { taskIdFromFolderName } from "../src/tasks/packet/discover.mjs";
39
40
  import { DEFAULT_TASKS_ROOT } from "../src/config/spine-init-constants.mjs";
40
41
  import {
41
42
  isPiExtensionConflictOutput,
@@ -312,7 +313,7 @@ async function runWorkerRunner() {
312
313
  const mode = process.argv.includes("--stub") ? "stub" : "pi";
313
314
 
314
315
  if (mode === "stub") {
315
- const parsedTaskId = path.basename(taskFolder).match(/^([A-Z]+-\d+)/)?.[1] ?? "";
316
+ const parsedTaskId = taskIdFromFolderName(path.basename(taskFolder)) ?? "";
316
317
  const failTasks = String(process.env.SPINE_WORKER_STUB_FAIL_TASKS ?? "")
317
318
  .split(/[,\s]+/)
318
319
  .filter(Boolean);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.24.0",
3
+ "version": "2.26.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -8,6 +8,8 @@ import path from "node:path";
8
8
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
9
  import { writeJsonAtomic } from "../fs/atomic-write.mjs";
10
10
  import { archiveBatchStatePath } from "./lifecycle.mjs";
11
+ import { reloadStateForTerminalWrite } from "./lifecycle-archive.mjs";
12
+ import { runPostReleaseCleanup } from "./lifecycle-cleanup.mjs";
11
13
  import { appendJournalEvent, journalPath, readJournalEvents, readJournalTail } from "./journal.mjs";
12
14
  import { loadBatchStateFile } from "./reconcile.mjs";
13
15
  import { appendBatchHistoryEntry } from "./state.mjs";
@@ -220,21 +222,29 @@ export function abortBatch(ctx) {
220
222
  }
221
223
 
222
224
  // Terminal abort write section runs under the global batch-state lock
223
- // (SP-722 / #264): abort signal, archive, history entry, and clearing the
224
- // active state must not interleave with a concurrent engine save or a
225
- // concurrent complete/resume writer.
226
- return withBatchStateLock(projectRoot, () => {
227
- const snapshot = buildAbortedSnapshot(loaded.raw, reason);
225
+ // (SP-722 / #264; SP-796 / #302): abort signal, archive, journal event,
226
+ // history entry, and clearing the active state must not interleave with a
227
+ // concurrent engine save or a concurrent complete/resume writer. Worker
228
+ // termination and worktree removal run after the lock is released.
229
+ const inLock = withBatchStateLock(projectRoot, () => {
230
+ // SP-792 / #301: archive the state as re-read inside the lock. Engine
231
+ // progress saved between the pre-lock read and here must survive into
232
+ // the archive; a changed or vanished state file fails closed instead.
233
+ const { state: fresh, refusal } = reloadStateForTerminalWrite({
234
+ projectRoot,
235
+ batchStatePath: loaded.path,
236
+ batchId,
237
+ action: "abort",
238
+ });
239
+ if (refusal) return { refusal, snapshot: null, archivePath: null };
240
+
241
+ const snapshot = buildAbortedSnapshot(fresh.raw, reason);
228
242
  writeAbortSignal(projectRoot, batchId, {
229
243
  hard,
230
244
  reason: reason ?? null,
231
245
  requestedAt: new Date().toISOString(),
232
246
  });
233
247
 
234
- if (hard) {
235
- killLaneWorkers(snapshot.lanes, true);
236
- }
237
-
238
248
  const archivePath = writeBatchArchive(projectRoot, batchId, snapshot);
239
249
 
240
250
  const eventsBefore = readJournalEvents(projectRoot, batchId);
@@ -250,12 +260,16 @@ export function abortBatch(ctx) {
250
260
  const journalFile = journalPath(projectRoot, batchId);
251
261
  if (!fs.existsSync(journalFile)) {
252
262
  return {
253
- ok: false,
254
- exitCode: 1,
255
- error: "journal_missing_after_abort",
256
- headline: "Abort archived state but journal file is missing",
257
- suggestedCommand: "spine status --diagnose",
258
- batchId,
263
+ refusal: {
264
+ ok: false,
265
+ exitCode: 1,
266
+ error: "journal_missing_after_abort",
267
+ headline: "Abort archived state but journal file is missing",
268
+ suggestedCommand: "spine status --diagnose",
269
+ batchId,
270
+ },
271
+ snapshot: null,
272
+ archivePath: null,
259
273
  };
260
274
  }
261
275
 
@@ -268,34 +282,56 @@ export function abortBatch(ctx) {
268
282
  archivePath: path.relative(projectRoot, archivePath),
269
283
  });
270
284
 
271
- if (hard) {
272
- const configResult = loadSpineConfig(projectRoot);
273
- const config = configResult.config ?? {};
274
- if (shouldCleanupWorktreesOnHardAbort(config)) {
275
- const laneCount = maxLaneNumberFromBatchState(snapshot);
285
+ clearActiveBatchState(fresh.path);
286
+
287
+ return { refusal: null, snapshot, archivePath };
288
+ });
289
+
290
+ // Cleanup runs only when the in-lock section succeeded (journaled
291
+ // `batch.aborted`); a refusal means nothing was archived for this batch.
292
+ if (inLock.refusal) return inLock.refusal;
293
+
294
+ // SP-796 / #302: worker kill and worktree removal run after the lock is
295
+ // released, so they no longer block concurrent engine saves. Failures
296
+ // here are reported as cleanupWarnings + `batch.cleanup_failed` instead
297
+ // of thrown, because the state was already archived and journaled aborted.
298
+ const cleanupSteps = [];
299
+ if (hard) {
300
+ cleanupSteps.push({
301
+ step: "kill_lane_workers",
302
+ run: () => {
303
+ killLaneWorkers(inLock.snapshot.lanes, true);
304
+ },
305
+ });
306
+ cleanupSteps.push({
307
+ step: "remove_worktrees",
308
+ run: () => {
309
+ const config = loadSpineConfig(projectRoot).config ?? {};
310
+ if (!shouldCleanupWorktreesOnHardAbort(config)) return;
311
+ const laneCount = maxLaneNumberFromBatchState(inLock.snapshot);
276
312
  removeLaneWorktrees(projectRoot, batchId, laneCount);
277
313
  appendJournalEvent(projectRoot, batchId, "batch.worktrees_cleaned", {
278
314
  batchId,
279
315
  laneCount,
280
316
  reason: "hard_abort",
281
317
  });
282
- }
283
- }
284
-
285
- clearActiveBatchState(loaded.path);
318
+ },
319
+ });
320
+ }
321
+ const cleanupWarnings = runPostReleaseCleanup({ projectRoot, batchId, steps: cleanupSteps });
286
322
 
287
- return {
288
- ok: true,
289
- exitCode: 0,
290
- batchId,
291
- diagnosis: "aborted",
292
- hard,
293
- headline: hard
294
- ? `Batch ${batchId} hard-aborted and archived`
295
- : `Batch ${batchId} aborted and archived`,
296
- suggestedCommand: "spine preflight",
297
- alternatives: ["spine batch dismiss", "spine status --diagnose"],
298
- archivePath,
299
- };
300
- });
323
+ return {
324
+ ok: true,
325
+ exitCode: 0,
326
+ batchId,
327
+ diagnosis: "aborted",
328
+ hard,
329
+ headline: hard
330
+ ? `Batch ${batchId} hard-aborted and archived`
331
+ : `Batch ${batchId} aborted and archived`,
332
+ suggestedCommand: "spine preflight",
333
+ alternatives: ["spine batch dismiss", "spine status --diagnose"],
334
+ archivePath: inLock.archivePath,
335
+ cleanupWarnings,
336
+ };
301
337
  }
@@ -120,7 +120,7 @@ export function attemptPostMergeLandLoopHandoff({
120
120
  });
121
121
  if (finalizeResult?.ok) {
122
122
  clearBatchEnginePid(state);
123
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
123
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
124
124
  appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
125
125
  signal,
126
126
  action: "finalized_in_process",
@@ -145,7 +145,7 @@ export function attemptPostMergeLandLoopHandoff({
145
145
  const fresh = loadSpineBatchState(projectRoot);
146
146
  if (fresh.raw && enginePid) {
147
147
  recordBatchEnginePid(fresh.raw, enginePid);
148
- saveSpineBatchState(projectRoot, fresh.raw, { bypassWriteGuard: true });
148
+ saveSpineBatchState(projectRoot, fresh.raw, { bypassOwnerCheck: true });
149
149
  }
150
150
 
151
151
  appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
@@ -19,6 +19,7 @@ import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
19
19
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
20
20
  import { resolveAttachedMilestonePollMs } from "../config/spine-config-schema.mjs";
21
21
  import { startParentSessionMonitor } from "./parent-session-monitor.mjs";
22
+ import { installEngineCrashHandlers } from "./engine-crash-guard.mjs";
22
23
  import {
23
24
  enforceAttachedEngineSingleOwner,
24
25
  reconcilePausedResumeDoneInLane,
@@ -240,6 +241,15 @@ export async function startAttachedMilestoneReporter({
240
241
  stop: async () => {
241
242
  stopped = true;
242
243
  await loopPromise;
244
+ // A fast engine can finish inside one poll interval, so the loop above
245
+ // may never have discovered the batchId (#308 follow-up: the worker
246
+ // poll loop no longer idles 5s per poll, shortening attached runs).
247
+ // Discover it here so the final flush still prints milestones — a
248
+ // completed batch must always surface [spine] batch.completed.
249
+ if (!batchId) {
250
+ const loaded = loadSpineBatchState(projectRoot);
251
+ batchId = loaded.raw?.batchId ? String(loaded.raw.batchId) : null;
252
+ }
243
253
  if (batchId) {
244
254
  const events = readJournalEventsCached(projectRoot, batchId);
245
255
  for (const event of events) {
@@ -282,6 +292,9 @@ export async function runAttachedBatchEngine({
282
292
  }
283
293
 
284
294
  installAttachedExitFinalizeHandlers({ projectRoot, spineBin });
295
+ // Scoped to this engine run: journal `engine.crashed` + fail the batch on a
296
+ // process-level crash, then uninstall so handlers never leak into importers (SP-788).
297
+ const uninstallEngineCrashGuard = installEngineCrashHandlers({ projectRoot });
285
298
  const reporter = await startAttachedMilestoneReporter({ projectRoot, write });
286
299
  /** @type {{ stop: () => Promise<void> }} */
287
300
  let parentMonitor = { stop: async () => {} };
@@ -301,6 +314,7 @@ export async function runAttachedBatchEngine({
301
314
  }
302
315
  return result;
303
316
  } finally {
317
+ uninstallEngineCrashGuard();
304
318
  await parentMonitor.stop();
305
319
  await reporter.stop();
306
320
  }
@@ -442,7 +456,7 @@ export function finalizeResumePostMergeLimbo({
442
456
  batchId,
443
457
  fromPhase,
444
458
  });
445
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
459
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
446
460
 
447
461
  return finalizeResumedBatchForIntegrate({
448
462
  projectRoot,
@@ -229,7 +229,7 @@ export function enforceAttachedEngineSingleOwner({ projectRoot, force = false, o
229
229
  fromPhase,
230
230
  allowRunningOrphanTerminate: true,
231
231
  });
232
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
232
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
233
233
  return {
234
234
  ok: true,
235
235
  handoff: true,
@@ -382,7 +382,12 @@ export function ensureForceResumeBatchState(projectRoot, options = {}) {
382
382
  };
383
383
  }
384
384
 
385
- const saved = saveSpineBatchState(projectRoot, reconstructed.state, { bypassWriteGuard: true });
385
+ // Operator-initiated force-resume intentionally rebuilds a batch whose live
386
+ // state is gone (#126): this is the one sanctioned archived resurrection.
387
+ const saved = saveSpineBatchState(projectRoot, reconstructed.state, {
388
+ bypassOwnerCheck: true,
389
+ allowArchivedResurrection: true,
390
+ });
386
391
  appendJournalEvent(projectRoot, reconstructed.batchId, "batch.state_reconstructed", {
387
392
  reason,
388
393
  source: reconstructed.reconstructedFrom ?? "batch-meta",
@@ -7,6 +7,7 @@ import path from "node:path";
7
7
  import { isProcessAlive } from "../process/liveness.mjs";
8
8
  import { parseSpineBatchState } from "./readers/spine-state.mjs";
9
9
  import { parseTaskplaneBatchState } from "./readers/taskplane-state.mjs";
10
+ import { withBatchStateLock } from "./batch-state-lock.mjs";
10
11
 
11
12
  /** Terminal phases safe to clear before a new batch start (SP-441 / #94). */
12
13
  const TERMINAL_PHASES_FOR_HANDOFF = new Set(["completed", "failed", "aborted", "merge_blocked"]);
@@ -126,77 +127,151 @@ export function readAliveBatchEnginePid(raw) {
126
127
  return enginePid;
127
128
  }
128
129
 
130
+ /**
131
+ * Detect a Taskplane-owned batch-state path (`.pi/`) that spine must never
132
+ * modify (SP-786 / #303). Spine start/clear paths act on `.spine/` state only.
133
+ *
134
+ * @param {string} batchStatePath
135
+ */
136
+ function isForeignBatchStatePath(batchStatePath) {
137
+ return batchStatePath.includes(`${path.sep}.pi${path.sep}`);
138
+ }
139
+
140
+ /**
141
+ * Rename a corrupt batch-state file to a collision-safe quarantine name in the
142
+ * same directory (SP-786 / #303). Never unlink: the file is evidence for
143
+ * post-mortem inspection. Uses a UTC timestamp plus a numeric suffix when the
144
+ * name is already taken (two corruptions within the same millisecond).
145
+ *
146
+ * @param {string} batchStatePath
147
+ * @returns {string} the quarantined file path
148
+ */
149
+ function quarantineCorruptBatchState(batchStatePath) {
150
+ const dir = path.dirname(batchStatePath);
151
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
152
+ let quarantinedPath = path.join(dir, `batch-state.corrupt-${stamp}.json`);
153
+ let attempt = 1;
154
+ while (fs.existsSync(quarantinedPath)) {
155
+ quarantinedPath = path.join(dir, `batch-state.corrupt-${stamp}-${attempt}.json`);
156
+ attempt += 1;
157
+ }
158
+ fs.renameSync(batchStatePath, quarantinedPath);
159
+ return quarantinedPath;
160
+ }
161
+
129
162
  /**
130
163
  * Remove active batch-state only when on-disk batch matches expected (SP-441 / #94).
131
164
  * Prevents complete/dismiss from clearing a newer batch after a concurrent start handoff.
132
165
  *
166
+ * Spine-owned path only: a Taskplane-owned `.pi/batch-state.json` is never
167
+ * renamed or unlinked here (SP-786 / #303). A corrupt spine-owned state file
168
+ * is quarantined (renamed), never deleted. The read-check-mutate sequence runs
169
+ * under the global batch-state lock; `projectRoot` may be omitted and is then
170
+ * derived from the `.spine` parent directory of `batchStatePath`.
171
+ *
133
172
  * @param {string|null} batchStatePath
134
173
  * @param {string} expectedBatchId
135
- * @returns {{ cleared: boolean, reason?: string, activeBatchId?: string }}
174
+ * @param {string|null} [projectRoot] derived from the `.spine` parent when omitted
175
+ * @returns {{ cleared: boolean, reason?: string, activeBatchId?: string, quarantinedPath?: string }}
136
176
  */
137
- export function clearActiveBatchStateIfMatches(batchStatePath, expectedBatchId) {
177
+ export function clearActiveBatchStateIfMatches(batchStatePath, expectedBatchId, projectRoot = null) {
138
178
  if (!batchStatePath || !fs.existsSync(batchStatePath)) {
139
179
  return { cleared: false, reason: "missing" };
140
180
  }
141
-
142
- try {
143
- const onDisk = JSON.parse(fs.readFileSync(batchStatePath, "utf-8"));
144
- const onDiskBatchId = readBatchStateId(onDisk);
145
- if (onDiskBatchId && onDiskBatchId !== expectedBatchId) {
146
- return {
147
- cleared: false,
148
- reason: "batch_id_mismatch",
149
- activeBatchId: onDiskBatchId,
150
- };
151
- }
152
- } catch {
153
- // Corrupt active state — remove so a new batch can start cleanly.
181
+ if (isForeignBatchStatePath(batchStatePath)) {
182
+ return { cleared: false, reason: "foreign_state" };
154
183
  }
155
184
 
156
- fs.unlinkSync(batchStatePath);
157
- return { cleared: true };
185
+ // Derive the lock root from `<root>/.spine/batch-state.json` when no caller supplies one.
186
+ const lockRoot = projectRoot ?? path.dirname(path.dirname(batchStatePath));
187
+ const result = /** @type {{ cleared: boolean, reason?: string, activeBatchId?: string, quarantinedPath?: string }} */ (
188
+ withBatchStateLock(lockRoot, () => {
189
+ try {
190
+ const onDisk = JSON.parse(fs.readFileSync(batchStatePath, "utf-8"));
191
+ const onDiskBatchId = readBatchStateId(onDisk);
192
+ if (onDiskBatchId && onDiskBatchId !== expectedBatchId) {
193
+ return {
194
+ cleared: false,
195
+ reason: "batch_id_mismatch",
196
+ activeBatchId: onDiskBatchId,
197
+ };
198
+ }
199
+ } catch (err) {
200
+ if (/** @type {NodeJS.ErrnoException} */ (err)?.code === "ENOENT") {
201
+ return { cleared: false, reason: "missing" };
202
+ }
203
+ // Corrupt active state — quarantine for inspection, never delete (SP-786 / #303).
204
+ const quarantinedPath = quarantineCorruptBatchState(batchStatePath);
205
+ return { cleared: false, reason: "corrupt", quarantinedPath };
206
+ }
207
+
208
+ fs.unlinkSync(batchStatePath);
209
+ return { cleared: true };
210
+ })
211
+ );
212
+ return result;
158
213
  }
159
214
 
160
215
  /**
161
216
  * Clear a terminal completed batch-state pointer before spine batch start (SP-441 / #94).
162
217
  *
218
+ * Spine-owned path only (SP-786 / #303): when `.spine/batch-state.json` is
219
+ * absent, a Taskplane-owned `.pi/batch-state.json` is reported as
220
+ * `foreign_state` and never renamed or unlinked. A corrupt spine-owned state
221
+ * file is quarantined (renamed), never deleted. The read-check-mutate sequence
222
+ * runs under the global batch-state lock.
223
+ *
163
224
  * @param {string} projectRoot
164
- * @returns {{ cleared: boolean, reason?: string, batchId?: string }}
225
+ * @returns {{ cleared: boolean, reason?: string, batchId?: string, quarantinedPath?: string }}
165
226
  */
166
227
  export function clearStaleTerminalBatchStateForStart(projectRoot) {
167
- const resolved = resolveBatchStatePath(projectRoot);
168
- if (!resolved || !fs.existsSync(resolved)) {
228
+ const spinePath = path.join(projectRoot, ".spine", "batch-state.json");
229
+ const piPath = path.join(projectRoot, ".pi", "batch-state.json");
230
+
231
+ if (!fs.existsSync(spinePath)) {
232
+ if (fs.existsSync(piPath)) {
233
+ return { cleared: false, reason: "foreign_state" };
234
+ }
169
235
  return { cleared: false, reason: "missing" };
170
236
  }
171
237
 
172
- /** @type {unknown} */
173
- let raw;
174
- try {
175
- raw = JSON.parse(fs.readFileSync(resolved, "utf-8"));
176
- } catch {
177
- fs.unlinkSync(resolved);
178
- return { cleared: true, reason: "corrupt" };
179
- }
238
+ const result = /** @type {{ cleared: boolean, reason?: string, batchId?: string, quarantinedPath?: string }} */ (
239
+ withBatchStateLock(projectRoot, () => {
240
+ /** @type {unknown} */
241
+ let raw;
242
+ try {
243
+ raw = JSON.parse(fs.readFileSync(spinePath, "utf-8"));
244
+ } catch (err) {
245
+ if (/** @type {NodeJS.ErrnoException} */ (err)?.code === "ENOENT") {
246
+ return { cleared: false, reason: "missing" };
247
+ }
248
+ // Corrupt state — quarantine for inspection, never delete (SP-786 / #303).
249
+ const quarantinedPath = quarantineCorruptBatchState(spinePath);
250
+ return { cleared: false, reason: "corrupt", quarantinedPath };
251
+ }
180
252
 
181
- const batchId = readBatchStateId(raw);
182
- const phase = String(/** @type {{ phase?: string }} */ (raw)?.phase ?? "");
183
- const ownerPid = readBatchStateEnginePid(raw);
253
+ const batchId = readBatchStateId(raw);
254
+ const phase = String(/** @type {{ phase?: string }} */ (raw)?.phase ?? "");
255
+ const ownerPid = readBatchStateEnginePid(raw);
184
256
 
185
- if (ACTIVE_PHASES_FOR_HANDOFF.has(phase) && !/** @type {{ endedAt?: unknown }} */ (raw)?.endedAt) {
186
- return { cleared: false, reason: "active", batchId };
187
- }
257
+ if (ACTIVE_PHASES_FOR_HANDOFF.has(phase) && !/** @type {{ endedAt?: unknown }} */ (raw)?.endedAt) {
258
+ return { cleared: false, reason: "active", batchId };
259
+ }
188
260
 
189
- if (ownerPid && isProcessAlive(ownerPid)) {
190
- throw new Error(
191
- `Active batch ${batchId || "(unknown)"} engine still running (pid=${ownerPid}). ` +
192
- "Wait for it to exit or run spine batch dismiss before spine batch start.",
193
- );
194
- }
261
+ if (ownerPid && isProcessAlive(ownerPid)) {
262
+ throw new Error(
263
+ `Active batch ${batchId || "(unknown)"} engine still running (pid=${ownerPid}). ` +
264
+ "Wait for it to exit or run spine batch dismiss before spine batch start.",
265
+ );
266
+ }
195
267
 
196
- if (TERMINAL_PHASES_FOR_HANDOFF.has(phase) || /** @type {{ endedAt?: unknown }} */ (raw)?.endedAt) {
197
- fs.unlinkSync(resolved);
198
- return { cleared: true, reason: "stale_terminal", batchId };
199
- }
268
+ if (TERMINAL_PHASES_FOR_HANDOFF.has(phase) || /** @type {{ endedAt?: unknown }} */ (raw)?.endedAt) {
269
+ fs.unlinkSync(spinePath);
270
+ return { cleared: true, reason: "stale_terminal", batchId };
271
+ }
200
272
 
201
- return { cleared: false, reason: "idle", batchId };
273
+ return { cleared: false, reason: "idle", batchId };
274
+ })
275
+ );
276
+ return result;
202
277
  }