pi-spine 2.25.0 → 2.27.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 (66) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-review-step.mjs +8 -1
  3. package/bin/spine-worker-runner.mjs +14 -1
  4. package/package.json +3 -3
  5. package/skills/spine-release-operator/SKILL.md +3 -0
  6. package/src/batch/abort.mjs +74 -38
  7. package/src/batch/attached-engine-handoff.mjs +2 -2
  8. package/src/batch/attached-runner-promote.mjs +1 -1
  9. package/src/batch/attached-runner-reconcile.mjs +1 -1
  10. package/src/batch/batch-meta-reconstruct.mjs +9 -1
  11. package/src/batch/batch-state-lock.mjs +173 -31
  12. package/src/batch/contract-exec.mjs +48 -47
  13. package/src/batch/contract-parse.mjs +2 -2
  14. package/src/batch/contract-prelanded.mjs +2 -2
  15. package/src/batch/contract-spawn.mjs +225 -0
  16. package/src/batch/contract-verify.mjs +2 -1
  17. package/src/batch/detached-wait.mjs +1 -1
  18. package/src/batch/diagnosis-handoff-packet.mjs +74 -0
  19. package/src/batch/diagnosis-pending-lane.mjs +34 -1
  20. package/src/batch/engine-lanes/matrix-run.mjs +6 -6
  21. package/src/batch/engine-lanes/merge.mjs +135 -34
  22. package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
  23. package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
  24. package/src/batch/engine-lanes/review-code.mjs +1 -0
  25. package/src/batch/engine-lanes/review-final.mjs +83 -46
  26. package/src/batch/engine-lanes/review-plan.mjs +22 -2
  27. package/src/batch/engine-lanes/review-poll.mjs +47 -1
  28. package/src/batch/engine-lanes.mjs +17 -16
  29. package/src/batch/engine.mjs +10 -10
  30. package/src/batch/journal.mjs +15 -0
  31. package/src/batch/lifecycle-archive.mjs +76 -1
  32. package/src/batch/lifecycle-cleanup.mjs +110 -0
  33. package/src/batch/lifecycle.mjs +100 -72
  34. package/src/batch/metrics.mjs +13 -1
  35. package/src/batch/parent-session-monitor.mjs +77 -70
  36. package/src/batch/pause.mjs +92 -25
  37. package/src/batch/post-merge-limbo.mjs +35 -5
  38. package/src/batch/provider-quota.mjs +220 -0
  39. package/src/batch/quota-fallback.mjs +319 -0
  40. package/src/batch/reconcile-diagnosis-context.mjs +22 -0
  41. package/src/batch/resume-gate-reopen.mjs +24 -8
  42. package/src/batch/resume-multi-queue.mjs +25 -10
  43. package/src/batch/resume-multi.mjs +1 -1
  44. package/src/batch/resume.mjs +1 -1
  45. package/src/batch/review-artifacts.mjs +93 -15
  46. package/src/batch/review-spawn-retry.mjs +106 -0
  47. package/src/batch/review-spawn.mjs +48 -2
  48. package/src/batch/review-step-run.mjs +96 -6
  49. package/src/batch/reviewer-output.mjs +162 -0
  50. package/src/batch/sequence-run.mjs +26 -8
  51. package/src/batch/sequence-wait.mjs +87 -8
  52. package/src/batch/state-guards.mjs +39 -7
  53. package/src/batch/state-io.mjs +131 -17
  54. package/src/batch/state.mjs +1 -0
  55. package/src/batch/worker-host.mjs +81 -7
  56. package/src/config/cursor-rules/discover.mjs +2 -2
  57. package/src/config/cursor-rules/match-globs.mjs +6 -4
  58. package/src/config/defaults.mjs +15 -1
  59. package/src/config/env-overrides.mjs +41 -4
  60. package/src/config/preflight/git-batch.mjs +47 -0
  61. package/src/config/settings-fields.mjs +6 -0
  62. package/src/config/spine-config-schema.mjs +91 -1
  63. package/src/doctor/quota-risk.mjs +45 -0
  64. package/src/fs/atomic-write.mjs +37 -1
  65. package/src/planner/file-scope.mjs +6 -6
  66. package/src/tasks/packet/validate-contract.mjs +3 -3
package/README.md CHANGED
@@ -49,7 +49,7 @@ Primary monitor surfaces: **`spine status --diagnose`**, **`spine dashboard`** /
49
49
  | [pi](https://pi.dev) coding agent | ≥ 0.80.0 (`pi.minPiVersion`) | Yes |
50
50
  | Git (worktree support) | — | Yes |
51
51
 
52
- These are the Wave A floors ([#285](https://github.com/beettlle/pi-spine/issues/285)). `spine doctor` **warns** when the installed pi is below `pi.minPiVersion` ("pi version supported"). The optional peer `@earendil-works/pi-coding-agent` is developed and tested against `^0.87.1` (pinned in `devDependencies`; the `peerDependencies` range stays `*`).
52
+ These are the Wave A floors ([#285](https://github.com/beettlle/pi-spine/issues/285)). `spine doctor` **warns** when the installed pi is below `pi.minPiVersion` ("pi version supported"). The optional peer `@earendil-works/pi-coding-agent` is developed and tested against `^1.0.1` (pinned in `devDependencies`; the `peerDependencies` range stays `*`).
53
53
 
54
54
  ## Install
55
55
 
@@ -61,7 +61,14 @@ export async function runSpineReviewStep(options) {
61
61
  if (loaded.config) config = loaded.config;
62
62
  }
63
63
 
64
- const journal = options.journal ?? resolveBatchJournalContext();
64
+ // Only plan/code reviews may inherit the env-derived journal: those are the
65
+ // only types the worker tool requests (extensions/spine/worker-tools.ts), so
66
+ // the legit worker journal path is preserved. Final reviews are engine-owned
67
+ // and always run in-process with an explicit journal, so a CLI `--type final`
68
+ // that inherited worker env (e.g. a test run inside a worker) must not write
69
+ // to the live journal (#328).
70
+ const envJournal = reviewType === "final" ? undefined : resolveBatchJournalContext();
71
+ const journal = options.journal ?? envJournal;
65
72
 
66
73
  const result = await runStepReview({
67
74
  taskFolder,
@@ -317,13 +317,26 @@ async function runWorkerRunner() {
317
317
  const failTasks = String(process.env.SPINE_WORKER_STUB_FAIL_TASKS ?? "")
318
318
  .split(/[,\s]+/)
319
319
  .filter(Boolean);
320
- if (failTasks.includes(parsedTaskId)) {
320
+ // SP-809 (#329): after a quota fallback hop the worker host pins
321
+ // SPINE_AGENT_PROFILE_OVERRIDE to the fallback profile; when the test
322
+ // marks that profile as passing, the retry takes the normal stub path.
323
+ const passProfile = process.env.SPINE_WORKER_STUB_PASS_PROFILE;
324
+ const passOnFallback =
325
+ typeof passProfile === "string" &&
326
+ passProfile !== "" &&
327
+ passProfile === process.env.SPINE_AGENT_PROFILE_OVERRIDE;
328
+ if (failTasks.includes(parsedTaskId) && !passOnFallback) {
321
329
  const dirtyRel = process.env.SPINE_WORKER_STUB_DIRTY_FILE;
322
330
  if (dirtyRel && worktreePath) {
323
331
  const dirtyPath = path.join(worktreePath, dirtyRel);
324
332
  fs.mkdirSync(path.dirname(dirtyPath), { recursive: true });
325
333
  fs.writeFileSync(dirtyPath, `stub dirty ${new Date().toISOString()}\n`, "utf-8");
326
334
  }
335
+ // SP-806 (#329): optional provider payload forwarded on stderr so stub
336
+ // runs can drive quota classification in the worker host. Printed before
337
+ // the forced-failure line so the payload stays the terminal status-JSON.
338
+ const failOutput = process.env.SPINE_WORKER_STUB_FAIL_OUTPUT;
339
+ if (failOutput) console.error(failOutput);
327
340
  console.error(`stub worker forced failure for ${parsedTaskId}`);
328
341
  process.exit(1);
329
342
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.25.0",
3
+ "version": "2.27.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -72,7 +72,7 @@
72
72
  }
73
73
  },
74
74
  "devDependencies": {
75
- "@earendil-works/pi-coding-agent": "^0.87.1",
75
+ "@earendil-works/pi-coding-agent": "^1.0.1",
76
76
  "@types/node": "^22.20.4",
77
77
  "eslint": "^10.11.0",
78
78
  "globals": "^17.12.0",
@@ -81,6 +81,6 @@
81
81
  },
82
82
  "license": "MIT",
83
83
  "dependencies": {
84
- "micromatch": "^4.0.8"
84
+ "picomatch": "^4.0.7"
85
85
  }
86
86
  }
@@ -61,6 +61,7 @@ Invoke explicitly: `/skill:spine-release-operator` or "run a spine release cycle
61
61
  - **Do not** execute tasks outside the approved manifest scope
62
62
  - **Never** start Phase 4 (execute) without **recorded scope approval** — the release manifest must show `Operator approved scope: yes` from the Phase 2 gate. Refuse the first wave when approval is missing or `no` (F1, [#249](https://github.com/beettlle/pi-spine/issues/249))
63
63
  - **Never** mid-release-edit `.spine/spine-config.json` agent pins (`agents.worker.model` / `agents.reviewer.model`) while a batch is running or integrated work is still unpublished. Pin **one worker** per release; escalate models **only** on content/contract failure — never on quota/403 or launch storms, which make releases worse (F7, [#248](https://github.com/beettlle/pi-spine/issues/248)). To override mid-release, first record the reason and date in the release manifest
64
+ - **Distinguish quota fallback from escalation** ([#329](https://github.com/beettlle/pi-spine/issues/329), v2.27.0): `agents.quotaFallbackProfile` is **provider failover, not escalation** — it switches the batch to a fallback profile on a **different provider pool**, not to a stronger model. It is single-hop per batch, sticky once applied, journaled (`batch.quota_fallback_applied`), and never edits `.spine/spine-config.json`. Because it changes pool, not model strength, it is **allowed mid-release** and does not violate the #248 rule above — that rule still bans escalating models on quota/403 or launch storms. After a fallback fires, paste the `Agent pin override: yes (<date>, auto quota fallback <pool> -> <profile>, batch <id>)` line shown by `spine status --diagnose` into the release manifest (the override record the #248 rule requires)
64
65
  - **Heed** the doctor/preflight **quota-risk advisory** ([#251](https://github.com/beettlle/pi-spine/issues/251)): `spine doctor` surfaces `ok: true, warning: true` when escalate/hard worker pins target quota-constrained pools without headroom evidence, or recent run-metrics show launch-storm / quota-abort patterns. It is advisory only — never fails preflight — and does not change the mid-release pin-thrash ban above
65
66
  - **Always** push/sync `main` to `origin` after each land loop once the post-integrate regression gate is green — do not let `main` drift far ahead of `origin` during a release (F8, [#249](https://github.com/beettlle/pi-spine/issues/249))
66
67
  - **Always** close GitHub issues linked as `Closes #NNN` / `Closes: #NNN` **as soon as that task's work is on `main`** (after integrate + post-integrate `release:check` green) — do **not** defer closing until Phase 6 publish. Leave `Partial #NNN` / `Partial: #NNN` open. Phase 6 is only a final sweep for any still-open `Closes` links (v2.15.0 left #257–#261, #263 open after ship — avoid that)
@@ -275,6 +276,8 @@ Before the first wave, confirm the release manifest records **`Operator approved
275
276
 
276
277
  **Model pin:** one worker pin for the release — do not mid-release-edit `.spine/spine-config.json` agent pins. Escalate models only on content/contract failure, never quota/403 or launch storms (F7, [#248](https://github.com/beettlle/pi-spine/issues/248)). A doctor/preflight quota-risk escalate signal is intentionally **out of scope** for this release — deferred to a later release ([#248](https://github.com/beettlle/pi-spine/issues/248) optional AC).
277
278
 
279
+ **Quota fallback is provider failover, not escalation** ([#329](https://github.com/beettlle/pi-spine/issues/329), v2.27.0): when `agents.quotaFallbackProfile` names a profile on a different provider pool, the engine moves the batch to that pool automatically — once per batch, sticky, journaled, without editing `.spine/spine-config.json` — and retries each quota-exhausted task once in its lane worktree. This is the sanctioned mid-release response to quota exhaustion; it does not count as a pin override under the rule above. When it fires, record it in the release manifest by pasting the `Agent pin override: yes (<date>, auto quota fallback <pool> -> <profile>, batch <id>)` line from `spine status --diagnose`.
280
+
278
281
  **Detached-first:** See [agent-shell-batch-policy.md](../spine-autonomous-operator/references/agent-shell-batch-policy.md). Omit `--attached` for release waves unless the operator shell is a persistent interactive terminal that blocks until batch completion.
279
282
 
280
283
  **Scope:** manifest tasks only — build a comma-separated release scope ID list.
@@ -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", {
@@ -456,7 +456,7 @@ export function finalizeResumePostMergeLimbo({
456
456
  batchId,
457
457
  fromPhase,
458
458
  });
459
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
459
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
460
460
 
461
461
  return finalizeResumedBatchForIntegrate({
462
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,
@@ -321,6 +321,9 @@ export function reconstructBatchStateFromRuntime(projectRoot, options = {}) {
321
321
  ...(priorResilience.forceMergedWaves
322
322
  ? { forceMergedWaves: priorResilience.forceMergedWaves }
323
323
  : {}),
324
+ // SP-808 (#329): the sticky quota-fallback hop must survive force-resume
325
+ // reconstruct so every later worker spawn keeps the override.
326
+ ...(priorResilience.quotaFallback ? { quotaFallback: priorResilience.quotaFallback } : {}),
324
327
  };
325
328
  rebuilt.currentWaveIndex = findResumableWave(rebuilt, computePendingTasks(rebuilt));
326
329
  rebuilt.updatedAt = Date.now();
@@ -382,7 +385,12 @@ export function ensureForceResumeBatchState(projectRoot, options = {}) {
382
385
  };
383
386
  }
384
387
 
385
- const saved = saveSpineBatchState(projectRoot, reconstructed.state, { bypassWriteGuard: true });
388
+ // Operator-initiated force-resume intentionally rebuilds a batch whose live
389
+ // state is gone (#126): this is the one sanctioned archived resurrection.
390
+ const saved = saveSpineBatchState(projectRoot, reconstructed.state, {
391
+ bypassOwnerCheck: true,
392
+ allowArchivedResurrection: true,
393
+ });
386
394
  appendJournalEvent(projectRoot, reconstructed.batchId, "batch.state_reconstructed", {
387
395
  reason,
388
396
  source: reconstructed.reconstructedFrom ?? "batch-meta",
@@ -24,6 +24,7 @@
24
24
  import crypto from "node:crypto";
25
25
  import fs from "node:fs";
26
26
  import path from "node:path";
27
+ import { setTimeout as sleepAsync } from "node:timers/promises";
27
28
  import {
28
29
  ENGINE_STARTTIME_TOLERANCE_MS,
29
30
  isProcessAlive,
@@ -172,6 +173,93 @@ function tryCreateLockFile(lockPath, token) {
172
173
  }
173
174
  }
174
175
 
176
+ /**
177
+ * Steal the lock by renaming it out of the acquisition path, but only when
178
+ * the renamed file is still the exact lock that was judged stale (SP-794 /
179
+ * GitHub #302 defect 1).
180
+ *
181
+ * A bare `unlinkSync` could remove a lock a different waiter had freshly
182
+ * acquired after the staleness judgment: two concurrent breakers of the same
183
+ * dead holder would both "win", each running the critical section while the
184
+ * other holds it. `renameSync` is atomic, so at most one breaker ever moves a
185
+ * given lock file; the token/content re-check guarantees the moved file is
186
+ * the same one the breaker judged stale. Exported for direct unit testing of
187
+ * the put-back branch, which cannot be scheduled deterministically through
188
+ * `withBatchStateLock`.
189
+ *
190
+ * @param {string} lockPath
191
+ * @param {string} staleToken ownership token observed when the lock was
192
+ * judged stale; empty for corrupt/invalid payloads that carry no token.
193
+ * @param {string} reason diagnostic label for the steal log
194
+ * @param {string | null} [staleContent] raw payload text observed when the
195
+ * lock was judged stale; compared in full when `staleToken` is empty.
196
+ */
197
+ export function stealIfTokenMatches(lockPath, staleToken, reason, staleContent = null) {
198
+ const stolenPath = `${lockPath}.break.${process.pid}.${newOwnershipToken()}`;
199
+ try {
200
+ fs.renameSync(lockPath, stolenPath);
201
+ } catch {
202
+ // ENOENT: another breaker or the holder's release already removed the
203
+ // lock — nothing to steal. Any other FS error also leaves lockPath
204
+ // untouched; treat it as a lost race so the acquire loop keeps its
205
+ // wait-then-timeout behavior (the unlink-based break this replaces
206
+ // swallowed its failures the same way).
207
+ return;
208
+ }
209
+ // Below this point nothing throws: every op is wrapped so a live holder's
210
+ // lock file is never stranded away from lockPath.
211
+
212
+ /** @type {string | null} */
213
+ let currentContent = null;
214
+ try {
215
+ currentContent = fs.readFileSync(stolenPath, "utf-8");
216
+ } catch {
217
+ currentContent = null;
218
+ }
219
+ let sameStaleLock = false;
220
+ if (typeof staleToken === "string" && staleToken.length > 0) {
221
+ try {
222
+ const current = JSON.parse(currentContent ?? "");
223
+ sameStaleLock =
224
+ current != null &&
225
+ typeof current === "object" &&
226
+ String(/** @type {{ token?: unknown }} */ (current).token ?? "") === staleToken;
227
+ } catch {
228
+ sameStaleLock = false;
229
+ }
230
+ } else {
231
+ // Corrupt/invalid payloads carry no trustworthy token — compare the
232
+ // full file content instead.
233
+ sameStaleLock = currentContent != null && currentContent === staleContent;
234
+ }
235
+
236
+ if (sameStaleLock) {
237
+ logLockBreak(lockPath, reason);
238
+ try {
239
+ fs.unlinkSync(stolenPath);
240
+ } catch {
241
+ /* already removed */
242
+ }
243
+ return;
244
+ }
245
+
246
+ // The lock at lockPath was replaced between the staleness judgment and the
247
+ // rename — a new holder now owns it. Put the file back; EEXIST means a
248
+ // third process already acquired lockPath in the microscopic gap, which is
249
+ // also fine. Either way the renamed copy is discarded.
250
+ try {
251
+ fs.linkSync(stolenPath, lockPath);
252
+ } catch {
253
+ /* EEXIST — someone else owns lockPath now; discard the copy below */
254
+ } finally {
255
+ try {
256
+ fs.unlinkSync(stolenPath);
257
+ } catch {
258
+ /* already removed */
259
+ }
260
+ }
261
+ }
262
+
175
263
  /**
176
264
  * Break the lock when the recorded holder cannot still own it: dead PID,
177
265
  * abandoned corrupt payload, same-process leak (no active holder), or a live
@@ -186,9 +274,12 @@ function tryCreateLockFile(lockPath, token) {
186
274
  function breakStaleLock(lockPath) {
187
275
  /** @type {{ pid?: number, startedAt?: number, token?: string } | null} */
188
276
  let holder = null;
277
+ /** @type {string | null} raw payload text, for content-compare steals. */
278
+ let rawContent = null;
189
279
  let corrupt = false;
190
280
  try {
191
- holder = JSON.parse(fs.readFileSync(lockPath, "utf-8"));
281
+ rawContent = fs.readFileSync(lockPath, "utf-8");
282
+ holder = JSON.parse(rawContent);
192
283
  if (!holder || typeof holder !== "object") corrupt = true;
193
284
  } catch {
194
285
  corrupt = true;
@@ -211,23 +302,13 @@ function breakStaleLock(lockPath) {
211
302
  } catch {
212
303
  return;
213
304
  }
214
- try {
215
- logLockBreak(lockPath, "corrupt-stale");
216
- fs.unlinkSync(lockPath);
217
- } catch {
218
- /* raced unlink */
219
- }
305
+ stealIfTokenMatches(lockPath, "", "corrupt-stale", rawContent);
220
306
  return;
221
307
  }
222
308
 
223
309
  const holderPid = Number(holder?.pid);
224
310
  if (!Number.isFinite(holderPid) || holderPid <= 0) {
225
- try {
226
- logLockBreak(lockPath, "invalid-pid");
227
- fs.unlinkSync(lockPath);
228
- } catch {
229
- /* raced unlink */
230
- }
311
+ stealIfTokenMatches(lockPath, "", "invalid-pid", rawContent);
231
312
  return;
232
313
  }
233
314
 
@@ -242,12 +323,12 @@ function breakStaleLock(lockPath) {
242
323
  if (stillHeldByToken || stillHeldByPath) {
243
324
  return;
244
325
  }
245
- try {
246
- logLockBreak(lockPath, `leakedSelf token=${token} mapSize=${heldByThisProcess.size}`);
247
- fs.unlinkSync(lockPath);
248
- } catch {
249
- /* raced unlink */
250
- }
326
+ stealIfTokenMatches(
327
+ lockPath,
328
+ token,
329
+ `leakedSelf token=${token} mapSize=${heldByThisProcess.size}`,
330
+ rawContent,
331
+ );
251
332
  return;
252
333
  }
253
334
 
@@ -255,12 +336,12 @@ function breakStaleLock(lockPath) {
255
336
  // under suite load the PID is often recycled by an unrelated live process,
256
337
  // and refusing to break left waiters stuck until timeout (stale-lock flake).
257
338
  if (holderPid !== process.pid && !isProcessAlive(holderPid)) {
258
- try {
259
- logLockBreak(lockPath, `deadPid holder=${holderPid}`);
260
- fs.unlinkSync(lockPath);
261
- } catch {
262
- /* raced unlink */
263
- }
339
+ stealIfTokenMatches(
340
+ lockPath,
341
+ String(holder?.token ?? ""),
342
+ `deadPid holder=${holderPid}`,
343
+ rawContent,
344
+ );
264
345
  return;
265
346
  }
266
347
 
@@ -281,12 +362,12 @@ function breakStaleLock(lockPath) {
281
362
  }
282
363
  if (liveStart == null || !Number.isFinite(liveStart) || liveStart <= 0) return;
283
364
  if (liveStart - expectedStart > STARTTIME_TOLERANCE_MS) {
284
- try {
285
- logLockBreak(lockPath, `pidRecycled holder=${holderPid}`);
286
- fs.unlinkSync(lockPath);
287
- } catch {
288
- /* raced unlink */
289
- }
365
+ stealIfTokenMatches(
366
+ lockPath,
367
+ String(holder?.token ?? ""),
368
+ `pidRecycled holder=${holderPid}`,
369
+ rawContent,
370
+ );
290
371
  }
291
372
  }
292
373
  }
@@ -355,3 +436,64 @@ export function withBatchStateLock(projectRoot, fn, options = {}) {
355
436
  }
356
437
  }
357
438
  }
439
+
440
+ /**
441
+ * Async twin of `withBatchStateLock` for event-loop callers (SP-797 / #302):
442
+ * same acquire loop, stale breaking, token release, and re-entrancy, but the
443
+ * contention wait yields via `node:timers/promises` instead of blocking the
444
+ * thread — a CLI-held lock can no longer freeze engine heartbeats, pipe
445
+ * draining, and stall timers. `fn` MUST stay synchronous: no `await` between
446
+ * acquire and release, or the re-entrancy map breaks. Uncontended calls reach
447
+ * `fn` before the first `await`. Waits >1 s log one `[spine]` stderr line.
448
+ *
449
+ * @param {string} projectRoot
450
+ * @param {() => unknown} fn synchronous critical section
451
+ * @param {{ timeoutMs?: number }} [options]
452
+ * @returns {Promise<unknown>} `fn`'s return value
453
+ */
454
+ export async function withBatchStateLockAsync(projectRoot, fn, options = {}) {
455
+ const lockPath = batchStateLockPath(projectRoot);
456
+
457
+ // Re-entrant pass-through: nested sync/async calls from this process run directly.
458
+ if (heldByThisProcess.has(lockPath)) {
459
+ return fn();
460
+ }
461
+
462
+ const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : DEFAULT_TIMEOUT_MS;
463
+ const deadline = Date.now() + timeoutMs;
464
+ const token = newOwnershipToken();
465
+ const waitStartedAt = Date.now();
466
+
467
+ for (;;) {
468
+ if (tryCreateLockFile(lockPath, token)) break;
469
+ breakStaleLock(lockPath);
470
+ if (Date.now() >= deadline) {
471
+ throw new Error(
472
+ `Timed out acquiring batch-state lock (${path.relative(projectRoot, lockPath)}) ` +
473
+ `after ${timeoutMs}ms — another spine process may be holding it`,
474
+ );
475
+ }
476
+ await sleepAsync(POLL_INTERVAL_MS);
477
+ }
478
+
479
+ const waitedMs = Date.now() - waitStartedAt;
480
+ heldByThisProcess.set(lockPath, token);
481
+ try {
482
+ return fn();
483
+ } finally {
484
+ // Token-gated unlink before map clear (see `withBatchStateLock`).
485
+ try {
486
+ releaseLockFile(lockPath, token);
487
+ } finally {
488
+ heldByThisProcess.delete(lockPath);
489
+ if (waitedMs > 1_000) {
490
+ const rel = path.relative(projectRoot, lockPath);
491
+ try {
492
+ process.stderr.write(`[spine] batch-state lock wait took ${waitedMs}ms (${rel}) — another spine process held it\n`);
493
+ } catch {
494
+ /* diagnostic only — never fail a state save on stderr */
495
+ }
496
+ }
497
+ }
498
+ }
499
+ }