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
@@ -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";
@@ -23,6 +23,7 @@ import {
23
23
  recordBatchEnginePid,
24
24
  saveSpineBatchState,
25
25
  } from "./state.mjs";
26
+ import { isBatchArchived } from "./state-guards.mjs";
26
27
 
27
28
  export { isPostMergeLimbo } from "./limbo-detect.mjs";
28
29
  export { hydrateMergeResultsFromJournal, isLastWaveIndex } from "./post-merge-finalize.mjs";
@@ -168,7 +169,7 @@ export function ensureLandLoopFinalizedAfterGateOrIntegrate({
168
169
  }
169
170
 
170
171
  if (changed) {
171
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
172
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
172
173
  }
173
174
 
174
175
  return {
@@ -241,7 +242,7 @@ export function finalizeAttachedLandLoopBeforeExit({
241
242
  });
242
243
  if (finalizeResult?.ok) {
243
244
  clearBatchEnginePid(state);
244
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
245
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
245
246
  appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
246
247
  signal,
247
248
  action: "finalized_in_process",
@@ -266,7 +267,7 @@ export function finalizeAttachedLandLoopBeforeExit({
266
267
  const fresh = loadSpineBatchState(projectRoot);
267
268
  if (fresh.raw && enginePid) {
268
269
  recordBatchEnginePid(fresh.raw, enginePid);
269
- saveSpineBatchState(projectRoot, fresh.raw, { bypassWriteGuard: true });
270
+ saveSpineBatchState(projectRoot, fresh.raw, { bypassOwnerCheck: true });
270
271
  }
271
272
 
272
273
  appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
@@ -375,7 +376,7 @@ export function finalizeBatchForIntegrate({
375
376
 
376
377
  // Persist PID clear before evidence collection can hang (#198 / SP-636).
377
378
  clearBatchEnginePid(state);
378
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
379
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
379
380
 
380
381
  const gateResult = openIntegrateGateAfterBatchComplete({
381
382
  projectRoot,
@@ -383,6 +384,35 @@ export function finalizeBatchForIntegrate({
383
384
  batchState: { ...state, phase: "completed" },
384
385
  });
385
386
 
387
+ // Late-finalize no-op after archive (#293 / SP-790): the operator can run
388
+ // gate approve → integrate → batch complete while extended evidence collection
389
+ // above is still running. `batch complete` archives and removes the active state
390
+ // file; persisting from this late path would resurrect a phantom completed batch
391
+ // that blocks the next `spine batch start`. Skip the land-loop finalize and the
392
+ // final save — the write guard would reject the write anyway — and journal the
393
+ // skip so the no-op is visible instead of silent.
394
+ const activeStateAfterGate = loadSpineBatchState(projectRoot);
395
+ if (!activeStateAfterGate.raw && isBatchArchived(projectRoot, batchId)) {
396
+ appendJournalEvent(projectRoot, batchId, "batch.late_finalize_skipped", {
397
+ batchId,
398
+ reason: "archived",
399
+ });
400
+ return {
401
+ ok: true,
402
+ exitCode: 0,
403
+ batchId,
404
+ taskIds,
405
+ taskId: taskIds.length === 1 ? taskIds[0] : undefined,
406
+ orchBranch,
407
+ mergeCommit: state.mergeResults?.at(-1)?.mergeCommit,
408
+ gateResult,
409
+ lateFinalizeSkipped: "archived",
410
+ output:
411
+ `Batch ${batchId} archived while finalizing: ${summaryTask} succeeded; merged to ${orchBranch}.\n` +
412
+ " → late land-loop finalize skipped — batch already completed and archived\n",
413
+ };
414
+ }
415
+
386
416
  // Always mark completed in memory before ensure so a prior land-loop journal
387
417
  // (e.g. start then pause/resume) still persists phase: completed on disk.
388
418
  if (!alreadyCompleted) {
@@ -398,7 +428,7 @@ export function finalizeBatchForIntegrate({
398
428
  source: landLoopSource,
399
429
  });
400
430
  // Ensure may no-op when journal events already exist; always persist phase/PID.
401
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
431
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
402
432
 
403
433
  const completionLabel = resumed ? "resumed and completed" : "completed";
404
434
  const nextSteps = resumed
@@ -32,6 +32,7 @@ import {
32
32
  extractJournalDiagnosisHints,
33
33
  findPlanReviewNestedSpawnBlockedFailure,
34
34
  journalPath,
35
+ parseJournalLines,
35
36
  readJournalEvents,
36
37
  } from "./journal.mjs";
37
38
  import { findLatestSalvageInspection } from "./salvage.mjs";
@@ -181,7 +182,18 @@ export function reconcileBatch(ctx, _lightRetry = false) {
181
182
  /** @type {object[]} */
182
183
  let journalEvents = [];
183
184
  if (fs.existsSync(journalFile)) {
184
- journalEvents = readJournalEvents(projectRoot, batch.batchId);
185
+ const parsedJournal = parseJournalLines(fs.readFileSync(journalFile, "utf-8"));
186
+ journalEvents = parsedJournal.events;
187
+ if (parsedJournal.skippedLines.length > 0) {
188
+ // SP-780: surface torn/checksum-failed lines so --diagnose reports
189
+ // the corruption instead of silently dropping those events.
190
+ signals.journalCorruptLines = {
191
+ count: parsedJournal.skippedLines.length,
192
+ lines: parsedJournal.skippedLines
193
+ .slice(0, 20)
194
+ .map(({ lineNumber, byteOffset }) => ({ lineNumber, byteOffset })),
195
+ };
196
+ }
185
197
  signals.journalHints = extractJournalDiagnosisHints(journalEvents);
186
198
  signals.journalEvents = journalEvents;
187
199
  }
@@ -5,13 +5,19 @@
5
5
  */
6
6
 
7
7
  import { reopenIntegrateGateForCompletedBatch } from "./gate.mjs";
8
- import { loadSpineBatchState, saveSpineBatchState } from "./state.mjs";
8
+ import { updateSpineBatchState } from "./state.mjs";
9
9
 
10
10
  /**
11
11
  * When `resumeCheck.gateReopen` is set, re-open the integrate gate and return
12
12
  * a resumeBatch-shaped result. Caller must release the resume lock via the
13
13
  * returned path (this helper releases it).
14
14
  *
15
+ * The reopen decision and the state persist run in one `updateSpineBatchState`
16
+ * critical section (SP-793 / #301): the phase is re-read under the lock from the
17
+ * latest committed state instead of a stale pre-load, and the persist goes
18
+ * through the write guard with no owner bypass — a completed batch has no live
19
+ * engine owner, so a guard rejection here is a real signal, not an obstacle.
20
+ *
15
21
  * @param {{
16
22
  * projectRoot: string,
17
23
  * resumeCheck: { batchId: string, gateReopen?: boolean },
@@ -24,14 +30,24 @@ export function tryResumeCompletedGateReopen({ projectRoot, resumeCheck, release
24
30
  return null;
25
31
  }
26
32
 
27
- const reopenState = loadSpineBatchState(projectRoot).raw;
28
- const reopenResult = reopenIntegrateGateForCompletedBatch({
29
- projectRoot,
30
- batchId: resumeCheck.batchId,
31
- batchState: reopenState,
33
+ let reopenResult = null;
34
+ updateSpineBatchState(projectRoot, (draft) => {
35
+ reopenResult = reopenIntegrateGateForCompletedBatch({
36
+ projectRoot,
37
+ batchId: resumeCheck.batchId,
38
+ batchState: draft,
39
+ });
40
+ // The gate record is written by the reopen itself; persisting the draft
41
+ // keeps parity with the prior unconditional save (refreshes updatedAt).
42
+ return true;
32
43
  });
33
- if (reopenState) {
34
- saveSpineBatchState(projectRoot, reopenState, { bypassWriteGuard: true });
44
+ if (!reopenResult) {
45
+ // Missing or corrupt batch-state on disk: evaluate reopen without state
46
+ // so the CLI reports the same batch_not_completed result as before.
47
+ reopenResult = reopenIntegrateGateForCompletedBatch({
48
+ projectRoot,
49
+ batchId: resumeCheck.batchId,
50
+ });
35
51
  }
36
52
  releaseResumeLock?.();
37
53
  const output = reopenResult.reopened
@@ -74,7 +74,7 @@ export async function resumeMultiTaskBatch({ projectRoot, force = false, resumeC
74
74
  batchId,
75
75
  fromPhase: phase,
76
76
  });
77
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
77
+ saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
78
78
  return finalizeResumedBatchForIntegrate({
79
79
  projectRoot,
80
80
  state,
@@ -452,7 +452,7 @@ export async function resumeBatch({ projectRoot, force = false }) {
452
452
  taskBranch,
453
453
  orchBranch,
454
454
  });
455
- const merge = mergeLaneToOrch({ projectRoot, baseBranch, orchBranch, taskBranch, batchId });
455
+ const merge = mergeLaneToOrch({ projectRoot, baseBranch, orchBranch, taskBranch, batchId, laneFileScopePaths: fileScopePaths });
456
456
  if (!merge.ok) {
457
457
  state.endedAt = Date.now();
458
458
  state.lastError = merge.error ?? "merge failed";
@@ -8,10 +8,10 @@ import readline from "node:readline/promises";
8
8
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
9
  import { countCommitsAhead } from "./lane-commit.mjs";
10
10
  import { checkIntegrateGate } from "./gate.mjs";
11
- import { gitExec } from "./git-exec.mjs";
12
- import { mergeOrchIntoBaseIsolated, syncPlumbingMergePathsToWorktree } from "./integrate-worktree.mjs";
11
+ import { mergeOrchIntoBaseIsolated, syncMergeResultToCheckedOutBase } from "./integrate-worktree.mjs";
12
+ import { reportDirtyOverlap } from "./integrate-dirty-overlap.mjs";
13
13
  import { appendJournalEvent } from "./journal.mjs";
14
- import { resolveRulesManifestIntegrateDrift } from "./rules-manifest-drift.mjs";
14
+ import { listIntegrateDirtyPaths, resolveRulesManifestIntegrateDrift } from "./rules-manifest-drift.mjs";
15
15
  import {
16
16
  gateBlockedOnMissingGate,
17
17
  openGateFromSalvageEvidence,
@@ -20,14 +20,6 @@ import { healAfterSalvageLand } from "./salvage-batch-integrate-heal.mjs";
20
20
  import { laneTaskBranch } from "./worktree.mjs";
21
21
  import { listSalvageableLanes } from "./salvage-batch-list.mjs";
22
22
 
23
- /**
24
- * @param {string} projectRoot
25
- * @param {string[]} args
26
- */
27
- function git(projectRoot, args) {
28
- return gitExec(projectRoot, args, { projectRoot });
29
- }
30
-
31
23
  /**
32
24
  * Default interactive confirmation for salvage integrate.
33
25
  *
@@ -324,6 +316,7 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
324
316
  gateOpenedBySalvage,
325
317
  });
326
318
 
319
+ const preMergeDirtyPaths = listIntegrateDirtyPaths(projectRoot); // before merge moves base ref (SP-784)
327
320
  const mergeResult = mergeOrchIntoBaseIsolated({
328
321
  projectRoot,
329
322
  baseBranch,
@@ -358,12 +351,9 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
358
351
  }
359
352
 
360
353
  const mergeCommit = mergeResult.mergeCommit;
361
- /** @type {{ ok: boolean, timedOut?: boolean, error?: string } | null} */
362
- let syncResult = null;
363
- if (mergeResult.mode === "plumbing") {
364
- const baseSha = git(projectRoot, ["rev-parse", `${mergeCommit}^1`]);
365
- syncResult = syncPlumbingMergePathsToWorktree(projectRoot, baseSha, mergeCommit);
366
- }
354
+ const syncResult = syncMergeResultToCheckedOutBase(projectRoot, baseBranch, mergeResult, {
355
+ dirtyPaths: preMergeDirtyPaths,
356
+ });
367
357
 
368
358
  if (syncResult && !syncResult.ok) {
369
359
  appendJournalEvent(projectRoot, resolvedBatchId, "batch.salvage_integrate_failed", {
@@ -391,6 +381,11 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
391
381
  };
392
382
  }
393
383
 
384
+ const dirtyOverlapWarning = reportDirtyOverlap({
385
+ projectRoot, batchId: resolvedBatchId, baseBranch, orchBranch: taskBranch, mergeCommit,
386
+ skippedDirtyPaths: syncResult?.skippedDirtyPaths, laneNumber: laneNum,
387
+ });
388
+
394
389
  // Landed lane work clears the salvaged tasks' failure gate (#292 / SP-763).
395
390
  const heal = healAfterSalvageLand(projectRoot, resolvedBatchId, lane, mergeCommit);
396
391
 
@@ -419,6 +414,7 @@ export async function integrateSalvageableLane(projectRoot, batchId, laneNumber,
419
414
  healedTaskIds: heal.healedTaskIds,
420
415
  healError: heal.healError,
421
416
  gateOpenedBySalvage,
417
+ ...(dirtyOverlapWarning ? { warnings: [dirtyOverlapWarning] } : {}),
422
418
  headline: `Salvaged lane ${laneNum} (${taskBranch}) into ${baseBranch}`,
423
419
  suggestedCommand: "spine status --diagnose",
424
420
  };
@@ -3,7 +3,11 @@
3
3
  */
4
4
 
5
5
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
6
- import { resolveSequencePollMs } from "../config/spine-config-schema.mjs";
6
+ import {
7
+ resolveSequenceMaxWaitMs,
8
+ resolveSequencePollMs,
9
+ resolveSequenceStallMs,
10
+ } from "../config/spine-config-schema.mjs";
7
11
  import {
8
12
  formatPreflightHuman,
9
13
  runBatchPreflight,
@@ -67,6 +71,8 @@ export async function runSequence(ctx) {
67
71
  profile: profileOverride = null,
68
72
  pollIntervalMs: pollIntervalMsOverride,
69
73
  timeoutMs = 120_000,
74
+ maxWaitMs: maxWaitMsOverride,
75
+ stallMs: stallMsOverride,
70
76
  spineBin = null,
71
77
  startBatchFn = startBatch,
72
78
  } = ctx;
@@ -77,6 +83,12 @@ export async function runSequence(ctx) {
77
83
  const pollIntervalMs =
78
84
  pollIntervalMsOverride ??
79
85
  resolveSequencePollMs({ config: configResult.config ?? {} });
86
+ const maxWaitMs =
87
+ maxWaitMsOverride ??
88
+ resolveSequenceMaxWaitMs({ config: configResult.config ?? {} });
89
+ const stallMs =
90
+ stallMsOverride ??
91
+ resolveSequenceStallMs({ config: configResult.config ?? {} });
80
92
 
81
93
  let sequenceState = null;
82
94
  let effectiveFromWave = fromWave;
@@ -334,7 +346,7 @@ export async function runSequence(ctx) {
334
346
  batchId,
335
347
  diagnosis: reconcileBatch({ projectRoot }).diagnosis ?? null,
336
348
  }
337
- : await waitForSequenceBatchTerminal({ projectRoot, pollIntervalMs, timeoutMs, enginePid: detachedEnginePid ?? null });
349
+ : await waitForSequenceBatchTerminal({ projectRoot, pollIntervalMs, timeoutMs, maxWaitMs, stallMs, enginePid: detachedEnginePid ?? null });
338
350
 
339
351
  if (!wait.ok || isSequenceBatchFailure(wait.diagnosis)) {
340
352
  const reconciliation = wait.reconciliation ?? reconcileBatch({ projectRoot });
@@ -347,13 +359,19 @@ export async function runSequence(ctx) {
347
359
  continue;
348
360
  }
349
361
  if (!stopOnFailure) continue;
350
- return haltSequenceAndPersist(projectRoot, sequenceState, completedWaves, {
351
- waveIndex: wave.waveIndex,
352
- error: wait.error ?? "batch_failed",
353
- diagnosis: wait.diagnosis ?? null,
354
- batchId: wait.batchId ?? batchId,
362
+ return haltSequenceAndPersist(
363
+ projectRoot,
364
+ sequenceState,
355
365
  completedWaves,
356
- });
366
+ {
367
+ waveIndex: wave.waveIndex,
368
+ error: wait.error ?? "batch_failed",
369
+ diagnosis: wait.diagnosis ?? null,
370
+ batchId: wait.batchId ?? batchId,
371
+ completedWaves,
372
+ },
373
+ wait.suggestedCommand ? { suggestedCommand: wait.suggestedCommand } : {},
374
+ );
357
375
  }
358
376
 
359
377
  const land = runSequenceWaveLandLoop({ projectRoot, batchId: wait.batchId ?? batchId, autoApproveGate });
@@ -3,12 +3,17 @@
3
3
  */
4
4
 
5
5
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
6
- import { DEFAULT_SEQUENCE_POLL_MS } from "../config/spine-config-schema.mjs";
7
- import { isProcessAlive } from "../process/liveness.mjs";
6
+ import {
7
+ DEFAULT_SEQUENCE_MAX_WAIT_MS,
8
+ DEFAULT_SEQUENCE_POLL_MS,
9
+ DEFAULT_SEQUENCE_STALL_MS,
10
+ } from "../config/spine-config-schema.mjs";
11
+ import { isEngineProcessAlive, isProcessAlive } from "../process/liveness.mjs";
8
12
  import { approveIntegrateGate, loadGateRecord, maybeAutoApproveIntegrateGate } from "./gate.mjs";
9
13
  import { integrateOrchToBase } from "./integrate.mjs";
10
14
  import { completeBatch } from "./lifecycle.mjs";
11
15
  import { reconcileBatch } from "./reconcile.mjs";
16
+ import { readBatchEnginePid, readBatchEngineStartedAt } from "./state-guards.mjs";
12
17
  import { loadSpineBatchState } from "./state.mjs";
13
18
 
14
19
  const WAVE_BATCH_SETTLED_DIAGNOSES = new Set([
@@ -49,12 +54,28 @@ export async function waitForSequenceBatchTerminal({
49
54
  projectRoot,
50
55
  pollIntervalMs = DEFAULT_SEQUENCE_POLL_MS,
51
56
  timeoutMs = 120_000,
57
+ maxWaitMs = DEFAULT_SEQUENCE_MAX_WAIT_MS,
58
+ stallMs = DEFAULT_SEQUENCE_STALL_MS,
52
59
  enginePid = null,
53
60
  reconcileFn = reconcileBatch,
54
61
  }) {
55
- const deadline = Date.now() + timeoutMs;
62
+ const startedAt = Date.now();
63
+ const deadline = startedAt + timeoutMs;
64
+ const hardCap = startedAt + maxWaitMs;
65
+ let lastProgressAt = startedAt;
56
66
  let useLightReconcile = false;
57
67
  while (Date.now() < deadline || isEngineStillRunning(enginePid, projectRoot)) {
68
+ if (Date.now() >= hardCap) {
69
+ const reconciliation = reconcileFn({ projectRoot });
70
+ return {
71
+ ok: false,
72
+ error: "sequence_wait_timeout",
73
+ diagnosis: reconciliation.diagnosis ?? null,
74
+ reconciliation,
75
+ batchId: reconciliation.batchId ?? null,
76
+ suggestedCommand: "spine status --diagnose",
77
+ };
78
+ }
58
79
  const reconciliation = reconcileFn({ projectRoot, light: useLightReconcile });
59
80
  useLightReconcile = true;
60
81
  const diagnosis = reconciliation.diagnosis;
@@ -75,6 +96,20 @@ export async function waitForSequenceBatchTerminal({
75
96
  batchId: reconciliation.batchId ?? null,
76
97
  };
77
98
  }
99
+ const progressAt = newestProgressSignalMs(reconciliation);
100
+ if (progressAt != null && progressAt > lastProgressAt) {
101
+ lastProgressAt = progressAt;
102
+ }
103
+ if (Date.now() - lastProgressAt >= stallMs) {
104
+ return {
105
+ ok: false,
106
+ error: "engine_stalled",
107
+ diagnosis,
108
+ reconciliation,
109
+ batchId: reconciliation.batchId ?? null,
110
+ suggestedCommand: "spine status --diagnose",
111
+ };
112
+ }
78
113
  await sleep(pollIntervalMs);
79
114
  }
80
115
  const reconciliation = reconcileFn({ projectRoot });
@@ -88,14 +123,58 @@ export async function waitForSequenceBatchTerminal({
88
123
  }
89
124
 
90
125
  /**
91
- * Returns true when a detached engine PID is alive or the batch phase is active,
92
- * preventing sequence timeout while work is still in progress.
126
+ * Newest progress signal exposed by a reconciliation, in epoch ms: batch-state
127
+ * `updatedAt` or the latest journal event timestamp (lane heartbeats are
128
+ * journal `lane.heartbeat` events, so they are covered by the journal tail).
129
+ * Returns null when no signal is available (SP-802 / #307).
130
+ *
131
+ * @param {object} reconciliation
132
+ * @returns {number|null}
133
+ */
134
+ function newestProgressSignalMs(reconciliation) {
135
+ const signals = reconciliation?.signals ?? {};
136
+ /** @type {number|null} */
137
+ let newest = null;
138
+ const updatedAt = Number(signals.raw?.updatedAt);
139
+ if (Number.isFinite(updatedAt) && updatedAt > 0) {
140
+ newest = updatedAt;
141
+ }
142
+ const events = Array.isArray(signals.journalEvents) ? signals.journalEvents : [];
143
+ for (let index = events.length - 1; index >= 0; index -= 1) {
144
+ const ts = Date.parse(String(events[index]?.timestamp ?? ""));
145
+ if (Number.isFinite(ts) && ts > 0) {
146
+ if (newest == null || ts > newest) newest = ts;
147
+ break;
148
+ }
149
+ }
150
+ return newest;
151
+ }
152
+
153
+ /**
154
+ * Returns true when the batch engine is verifiably still running, so the wait
155
+ * extends past `timeoutMs` while work is in progress. PID-reuse-safe (SP-802 /
156
+ * #307, #259): the explicit `enginePid` is paired with the state's recorded
157
+ * `engineStartedAt` when the PIDs match; the state fallback uses the recorded
158
+ * PID + start time from `resilience`; otherwise it degrades to PID-only
159
+ * liveness.
160
+ *
161
+ * @param {number|null} enginePid
162
+ * @param {string} projectRoot
93
163
  */
94
164
  function isEngineStillRunning(enginePid, projectRoot) {
95
- if (enginePid && isProcessAlive(enginePid)) return true;
96
165
  const { raw } = loadSpineBatchState(projectRoot);
97
- const pid = raw?.enginePid ?? null;
98
- if (pid && isProcessAlive(pid)) return true;
166
+ const statePid = readBatchEnginePid(raw);
167
+ const stateStartedAt = readBatchEngineStartedAt(raw);
168
+ const pid = Number(enginePid);
169
+ if (Number.isFinite(pid) && pid > 0) {
170
+ if (statePid != null && statePid === pid) {
171
+ return isEngineProcessAlive(pid, stateStartedAt);
172
+ }
173
+ if (isProcessAlive(pid)) return true;
174
+ }
175
+ if (statePid != null) {
176
+ return isEngineProcessAlive(statePid, stateStartedAt);
177
+ }
99
178
  return false;
100
179
  }
101
180