pi-spine 1.1.0 → 1.2.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 (102) hide show
  1. package/bin/spine-batch.mjs +160 -53
  2. package/bin/spine-cli/batch.mjs +3 -3
  3. package/bin/spine-cli/lane-logs.mjs +24 -0
  4. package/bin/spine-cli/scenarios.mjs +298 -0
  5. package/bin/spine-cli/wait.mjs +30 -0
  6. package/bin/spine-cli/watch.mjs +27 -0
  7. package/bin/spine-issue.mjs +196 -0
  8. package/bin/spine-journal.mjs +1 -0
  9. package/bin/spine-run.mjs +30 -0
  10. package/bin/spine-status.mjs +19 -1
  11. package/bin/spine-tasks.mjs +16 -2
  12. package/bin/spine-worker-runner.mjs +10 -10
  13. package/bin/spine.mjs +49 -1
  14. package/package.json +1 -1
  15. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  16. package/src/batch/abort.mjs +2 -11
  17. package/src/batch/agent-session-worker.mjs +45 -5
  18. package/src/batch/attached-engine-handoff.mjs +188 -0
  19. package/src/batch/attached-runner.mjs +312 -0
  20. package/src/batch/contract-prelanded.mjs +180 -0
  21. package/src/batch/contract-verify.mjs +140 -2
  22. package/src/batch/detached-start.mjs +66 -2
  23. package/src/batch/diagnosis-alternatives.mjs +46 -0
  24. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  25. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  26. package/src/batch/diagnosis-stub.mjs +109 -0
  27. package/src/batch/diagnosis-task-done.mjs +110 -0
  28. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  29. package/src/batch/diagnosis.mjs +135 -68
  30. package/src/batch/engine-lanes/merge.mjs +110 -82
  31. package/src/batch/engine-lanes/queue.mjs +4 -1
  32. package/src/batch/engine-lanes/watch.mjs +29 -0
  33. package/src/batch/engine-lanes.mjs +1 -0
  34. package/src/batch/engine-scope.mjs +11 -1
  35. package/src/batch/engine.mjs +79 -24
  36. package/src/batch/evidence.mjs +78 -15
  37. package/src/batch/gate.mjs +43 -14
  38. package/src/batch/git-helpers.mjs +96 -0
  39. package/src/batch/heartbeat.mjs +73 -7
  40. package/src/batch/integrate.mjs +2 -4
  41. package/src/batch/journal.mjs +3 -0
  42. package/src/batch/lane-commit.mjs +90 -5
  43. package/src/batch/lifecycle.mjs +130 -3
  44. package/src/batch/macro-phase.mjs +226 -0
  45. package/src/batch/merge/adoption-doc-merge.mjs +93 -10
  46. package/src/batch/merge/wave-merge-state.mjs +3 -0
  47. package/src/batch/metrics.mjs +74 -5
  48. package/src/batch/orphan-detect.mjs +74 -0
  49. package/src/batch/pause.mjs +223 -0
  50. package/src/batch/post-merge-limbo.mjs +264 -8
  51. package/src/batch/reconcile.mjs +429 -54
  52. package/src/batch/resume-common.mjs +5 -1
  53. package/src/batch/resume-lane-reviews.mjs +16 -0
  54. package/src/batch/resume-multi-lanes.mjs +56 -1
  55. package/src/batch/resume-multi-validate.mjs +67 -6
  56. package/src/batch/resume-multi.mjs +9 -4
  57. package/src/batch/resume.mjs +52 -45
  58. package/src/batch/retry.mjs +56 -5
  59. package/src/batch/review-spawn.mjs +8 -2
  60. package/src/batch/rules-manifest-drift.mjs +157 -0
  61. package/src/batch/salvage.mjs +2 -1
  62. package/src/batch/sequence.mjs +454 -0
  63. package/src/batch/state.mjs +18 -3
  64. package/src/batch/status-json.mjs +67 -0
  65. package/src/batch/task-stall-budget.mjs +22 -10
  66. package/src/batch/worker-host.mjs +95 -7
  67. package/src/batch/worker-output.mjs +196 -3
  68. package/src/cli/issue-draft.mjs +180 -0
  69. package/src/cli/journal-follow.mjs +239 -0
  70. package/src/cli/lane-logs.mjs +291 -0
  71. package/src/cli/sequence.mjs +108 -0
  72. package/src/cli/settings-set.mjs +2 -21
  73. package/src/cli/wait.mjs +187 -0
  74. package/src/cli/watch.mjs +160 -0
  75. package/src/config/agent-model-resolve.mjs +48 -0
  76. package/src/config/cursor-rules/discover.mjs +3 -21
  77. package/src/config/defaults.mjs +7 -1
  78. package/src/config/settings-fields.mjs +48 -0
  79. package/src/config/spine-init-constants.mjs +1 -0
  80. package/src/config/spine-preflight-lib.mjs +471 -16
  81. package/src/dashboard/lane-throughput.mjs +351 -0
  82. package/src/dashboard/public/dashboard.css +25 -1
  83. package/src/dashboard/public/dashboard.js +223 -18
  84. package/src/dashboard/public/index.html +14 -2
  85. package/src/dashboard/server.mjs +4 -0
  86. package/src/dashboard/snapshot.mjs +215 -1
  87. package/src/dashboard/view.mjs +170 -17
  88. package/src/doctor/agent-model-inherit.mjs +61 -6
  89. package/src/doctor/run-doctor-checks.mjs +26 -1
  90. package/src/doctor/sequence-safety.mjs +57 -0
  91. package/src/doctor/stale-worktrees.mjs +102 -0
  92. package/src/fixtures/scenario-registry.mjs +194 -0
  93. package/src/fs/atomic-write.mjs +49 -0
  94. package/src/planner/file-scope.mjs +246 -0
  95. package/src/planner/format-plan.mjs +9 -7
  96. package/src/planner/index.mjs +6 -2
  97. package/src/planner/wave-scope.mjs +136 -0
  98. package/src/planner/waves.mjs +133 -0
  99. package/src/tasks/packet/index.mjs +1 -0
  100. package/src/tasks/packet/parse-prompt.mjs +42 -1
  101. package/src/tasks/packet/validate-prompt.mjs +124 -0
  102. package/templates/spine-config.json +8 -1
@@ -97,6 +97,68 @@ export function journalEventsSinceResume(events, raw) {
97
97
  return events;
98
98
  }
99
99
 
100
+ /**
101
+ * @param {unknown} event
102
+ * @returns {string|null}
103
+ */
104
+ function eventTaskId(event) {
105
+ if (!event || typeof event !== "object") return null;
106
+ const direct = /** @type {{ taskId?: unknown }} */ (event).taskId;
107
+ if (typeof direct === "string" && direct) return direct;
108
+ const payload = /** @type {{ payload?: { taskId?: unknown } }} */ (event).payload;
109
+ const nested = payload?.taskId;
110
+ return typeof nested === "string" && nested ? nested : null;
111
+ }
112
+
113
+ /**
114
+ * @param {unknown} event
115
+ * @returns {number|null}
116
+ */
117
+ function eventLaneNumber(event) {
118
+ if (!event || typeof event !== "object") return null;
119
+ const direct = /** @type {{ laneNumber?: unknown, payload?: { laneNumber?: unknown } }} */ (
120
+ event
121
+ ).laneNumber;
122
+ if (direct != null && Number.isFinite(Number(direct))) return Number(direct);
123
+ const payload = /** @type {{ payload?: { laneNumber?: unknown } }} */ (event).payload?.laneNumber;
124
+ return payload != null && Number.isFinite(Number(payload)) ? Number(payload) : null;
125
+ }
126
+
127
+ /**
128
+ * Running task is inside task.started → first lane.heartbeat debounce (SP-345 / #36).
129
+ * Stale workerPid from a prior lane handoff must not trigger worker_orphaned mid-start.
130
+ *
131
+ * @param {object[]} journalEvents
132
+ * @param {string} taskId
133
+ * @param {number|null|undefined} laneNumber
134
+ */
135
+ export function journalTaskAwaitingFirstHeartbeat(journalEvents, taskId, laneNumber) {
136
+ if (!Array.isArray(journalEvents) || !taskId) return false;
137
+
138
+ let lastStartedIndex = -1;
139
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
140
+ const event = journalEvents[index];
141
+ if (String(event?.type ?? "") !== "task.started") continue;
142
+ if (eventTaskId(event) !== taskId) continue;
143
+ if (laneNumber != null) {
144
+ const eventLane = eventLaneNumber(event);
145
+ if (eventLane != null && eventLane !== Number(laneNumber)) continue;
146
+ }
147
+ lastStartedIndex = index;
148
+ break;
149
+ }
150
+
151
+ if (lastStartedIndex < 0) return false;
152
+
153
+ for (let index = lastStartedIndex + 1; index < journalEvents.length; index += 1) {
154
+ const event = journalEvents[index];
155
+ if (String(event?.type ?? "") !== "lane.heartbeat") continue;
156
+ if (eventTaskId(event) === taskId) return false;
157
+ }
158
+
159
+ return true;
160
+ }
161
+
100
162
  /**
101
163
  * Worker exited (post-done grace or natural exit) but engine still owns code/final review.
102
164
  *
@@ -170,6 +232,18 @@ export function detectOrphanRunning(ctx) {
170
232
  if (journalIndicatesEngineOwnedContinuation(scopedJournalEvents, task.taskId)) {
171
233
  continue;
172
234
  }
235
+ if (
236
+ journalTaskAwaitingFirstHeartbeat(
237
+ scopedJournalEvents,
238
+ task.taskId,
239
+ task.laneNumber,
240
+ )
241
+ ) {
242
+ const enginePid = readBatchEnginePid(ctx.raw);
243
+ if (enginePid != null && isProcessAlive(enginePid)) {
244
+ continue;
245
+ }
246
+ }
173
247
  /** @type {OrphanRunningSignal} */
174
248
  return {
175
249
  kind: "lane",
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Batch pause CLI with attached-engine confirmation (SP-376, GitHub #57).
3
+ * Engine pause propagation helpers (SP-375).
4
+ */
5
+
6
+ import { isProcessAlive } from "../process/liveness.mjs";
7
+ import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
8
+ import { recordResumePhaseTransition } from "./resume-common.mjs";
9
+ import {
10
+ loadSpineBatchState,
11
+ readBatchEnginePid,
12
+ saveSpineBatchState,
13
+ } from "./state.mjs";
14
+
15
+ /** Grace period for attached engine to persist phase: paused (SP-376). */
16
+ export const PAUSE_CONFIRM_GRACE_MS = 3_000;
17
+
18
+ /** Poll interval while waiting for pause confirmation. */
19
+ export const PAUSE_CONFIRM_POLL_MS = 100;
20
+
21
+ /**
22
+ * True when the latest batch.paused journal event is newer than the latest batch.resumed.
23
+ *
24
+ * @param {string} projectRoot
25
+ * @param {string} batchId
26
+ */
27
+ export function isOperatorPauseActive(projectRoot, batchId) {
28
+ const events = readJournalEvents(projectRoot, batchId);
29
+ let lastPauseIdx = -1;
30
+ let lastResumeIdx = -1;
31
+ for (let i = 0; i < events.length; i++) {
32
+ const type = String(events[i].type ?? "");
33
+ if (type === "batch.paused") lastPauseIdx = i;
34
+ if (type === "batch.resumed") lastResumeIdx = i;
35
+ }
36
+ return lastPauseIdx >= 0 && lastPauseIdx > lastResumeIdx;
37
+ }
38
+
39
+ /**
40
+ * Adopt operator pause from disk or journal so engine saves do not clobber phase: paused.
41
+ *
42
+ * @param {string} projectRoot
43
+ * @param {object} state
44
+ * @returns {boolean}
45
+ */
46
+ export function mergeEngineStateWithDiskPause(projectRoot, state) {
47
+ const loaded = loadSpineBatchState(projectRoot);
48
+ const diskPhase = String(loaded.raw?.phase ?? "");
49
+ const batchId = String(state.batchId ?? loaded.raw?.batchId ?? "");
50
+ if (diskPhase === "paused") {
51
+ state.phase = "paused";
52
+ return true;
53
+ }
54
+ if (batchId && isOperatorPauseActive(projectRoot, batchId)) {
55
+ state.phase = "paused";
56
+ return true;
57
+ }
58
+ return false;
59
+ }
60
+
61
+ /**
62
+ * Persist engine state while honoring an operator pause already on disk or in the journal.
63
+ *
64
+ * @param {string} projectRoot
65
+ * @param {object} state
66
+ * @param {{ bypassWriteGuard?: boolean }} [options]
67
+ */
68
+ export function saveEngineBatchState(projectRoot, state, options = {}) {
69
+ mergeEngineStateWithDiskPause(projectRoot, state);
70
+ return saveSpineBatchState(projectRoot, state, options);
71
+ }
72
+
73
+ /**
74
+ * Re-assert phase: paused on disk when the operator paused but a running engine overwrote it.
75
+ *
76
+ * @param {string} projectRoot
77
+ * @returns {boolean}
78
+ */
79
+ export function enforceOperatorPauseOnDisk(projectRoot) {
80
+ const loaded = loadSpineBatchState(projectRoot);
81
+ if (!loaded.raw) return false;
82
+ const batchId = String(loaded.raw.batchId ?? "");
83
+ if (!batchId || !isOperatorPauseActive(projectRoot, batchId)) return false;
84
+ if (loaded.raw.phase === "paused") return true;
85
+ loaded.raw.phase = "paused";
86
+ saveSpineBatchState(projectRoot, loaded.raw, { bypassWriteGuard: true });
87
+ return true;
88
+ }
89
+
90
+ /**
91
+ * @param {object} params
92
+ * @param {string} params.projectRoot
93
+ * @param {object} params.state
94
+ * @param {string} params.batchId
95
+ * @returns {{ stop: boolean }}
96
+ */
97
+ export function adoptPauseIfRequested({ projectRoot, state, batchId }) {
98
+ const paused = mergeEngineStateWithDiskPause(projectRoot, state);
99
+ if (!paused) return { stop: false };
100
+ saveEngineBatchState(projectRoot, state);
101
+ appendJournalEvent(projectRoot, batchId, "engine.pause_observed", {
102
+ enginePid: process.pid,
103
+ });
104
+ return { stop: true };
105
+ }
106
+
107
+ /**
108
+ * @param {number} ms
109
+ * @returns {Promise<void>}
110
+ */
111
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
112
+
113
+ /**
114
+ * @param {object} params
115
+ * @param {string} params.projectRoot
116
+ * @param {number} [params.confirmGraceMs]
117
+ * @param {number} [params.pollIntervalMs]
118
+ * @param {(ms: number) => Promise<void>} [params.sleepFn]
119
+ */
120
+ export async function waitForPauseConfirmation({
121
+ projectRoot,
122
+ confirmGraceMs,
123
+ pollIntervalMs,
124
+ sleepFn = defaultSleep,
125
+ }) {
126
+ const deadline = Date.now() + confirmGraceMs;
127
+ while (Date.now() < deadline) {
128
+ const currentPhase = String(loadSpineBatchState(projectRoot).raw?.phase ?? "");
129
+ if (currentPhase === "paused") {
130
+ return true;
131
+ }
132
+ const remaining = deadline - Date.now();
133
+ if (remaining <= 0) {
134
+ break;
135
+ }
136
+ await sleepFn(Math.min(pollIntervalMs, remaining));
137
+ }
138
+ return String(loadSpineBatchState(projectRoot).raw?.phase ?? "") === "paused";
139
+ }
140
+
141
+ /**
142
+ * @param {object} params
143
+ * @param {string} params.projectRoot
144
+ * @param {number} [params.confirmGraceMs]
145
+ * @param {number} [params.pollIntervalMs]
146
+ * @param {(ms: number) => Promise<void>} [params.sleepFn]
147
+ */
148
+ export async function pauseBatch({
149
+ projectRoot,
150
+ confirmGraceMs = PAUSE_CONFIRM_GRACE_MS,
151
+ pollIntervalMs = PAUSE_CONFIRM_POLL_MS,
152
+ sleepFn = defaultSleep,
153
+ }) {
154
+ const loaded = loadSpineBatchState(projectRoot);
155
+ if (!loaded.raw) {
156
+ return { ok: false, exitCode: 1, error: "no_active_batch", output: "No active pi-spine batch.\n" };
157
+ }
158
+
159
+ const state = loaded.raw;
160
+ const phase = String(state.phase ?? "");
161
+ if (phase !== "running" && phase !== "planning") {
162
+ return {
163
+ ok: false,
164
+ exitCode: 1,
165
+ error: "cannot_pause",
166
+ output: `Cannot pause batch in phase ${phase}. Only running or planning batches can be paused.\n`,
167
+ batchId: state.batchId,
168
+ phase,
169
+ };
170
+ }
171
+
172
+ const fromPhase = phase;
173
+ const batchId = state.batchId;
174
+ const enginePid = readBatchEnginePid(state);
175
+ const attachedEngineAlive =
176
+ enginePid != null && enginePid !== process.pid && isProcessAlive(enginePid);
177
+
178
+ state.phase = "paused";
179
+ saveSpineBatchState(projectRoot, state);
180
+ recordResumePhaseTransition(projectRoot, batchId, fromPhase, "paused");
181
+
182
+ if (attachedEngineAlive) {
183
+ const confirmed = await waitForPauseConfirmation({
184
+ projectRoot,
185
+ confirmGraceMs,
186
+ pollIntervalMs,
187
+ sleepFn,
188
+ });
189
+
190
+ if (!confirmed) {
191
+ const current = loadSpineBatchState(projectRoot).raw;
192
+ const currentPhase = String(current?.phase ?? "unknown");
193
+ appendJournalEvent(projectRoot, batchId, "batch.pause_failed", {
194
+ fromPhase,
195
+ enginePid,
196
+ observedPhase: currentPhase,
197
+ graceMs: confirmGraceMs,
198
+ });
199
+ const output =
200
+ `Pause not confirmed: batch-state phase is still "${currentPhase}" after ${confirmGraceMs}ms.\n` +
201
+ `Journal recorded batch.paused but attached engine (PID ${enginePid}) did not persist phase: paused.\n` +
202
+ "Stop the attached engine or wait for the current step to finish, then run spine batch pause again.\n" +
203
+ "spine batch retry is blocked while phase is running — retry only after phase is paused.\n";
204
+ return {
205
+ ok: false,
206
+ exitCode: 1,
207
+ error: "pause_not_confirmed",
208
+ output,
209
+ batchId,
210
+ phase: currentPhase,
211
+ enginePid,
212
+ };
213
+ }
214
+ }
215
+
216
+ return {
217
+ ok: true,
218
+ exitCode: 0,
219
+ batchId,
220
+ phase: "paused",
221
+ output: `Batch ${batchId} paused. No new tasks will be scheduled.\n → spine batch resume\n`,
222
+ };
223
+ }
@@ -2,9 +2,27 @@
2
2
  * Post-merge limbo detection — merges done, tasks succeeded, phase still running (SP-204).
3
3
  */
4
4
 
5
- import { openIntegrateGateAfterBatchComplete } from "./gate.mjs";
6
- import { appendJournalEvent } from "./journal.mjs";
7
- import { saveSpineBatchState } from "./state.mjs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import {
8
+ buildAttachedBatchResumeArgv,
9
+ spawnDetachedBatchEngine,
10
+ } from "./detached-start.mjs";
11
+ import { loadGateRecord, openIntegrateGateAfterBatchComplete } from "./gate.mjs";
12
+ import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
13
+ import { recordWaveMergeResult } from "./merge/wave-merge-state.mjs";
14
+ import { detectPostMergeLimboForResume } from "./resume-multi-validate.mjs";
15
+ import {
16
+ clearBatchEnginePid,
17
+ loadSpineBatchState,
18
+ recordBatchEnginePid,
19
+ saveSpineBatchState,
20
+ } from "./state.mjs";
21
+
22
+ const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
23
+
24
+ /** @type {boolean} */
25
+ let attachedExitFinalizeInFlight = false;
8
26
 
9
27
  /**
10
28
  * @param {object|null|undefined} state
@@ -34,6 +52,191 @@ export function isPostMergeLimbo(state, git = {}) {
34
52
  return true;
35
53
  }
36
54
 
55
+ /**
56
+ * @param {string} [spineBin]
57
+ */
58
+ export function resolveDefaultSpineBin(spineBin) {
59
+ if (spineBin && path.isAbsolute(spineBin)) return spineBin;
60
+ if (spineBin) return path.resolve(spineBin);
61
+ return path.join(PACKAGE_ROOT, "bin", "spine.mjs");
62
+ }
63
+
64
+ /**
65
+ * Sync missing mergeResults rows from journal merge_completed events (SP-378, GitHub #59).
66
+ *
67
+ * @param {object} params
68
+ * @param {string} params.projectRoot
69
+ * @param {object} params.state
70
+ * @param {string} params.batchId
71
+ */
72
+ export function hydrateMergeResultsFromJournal({ projectRoot, state, batchId }) {
73
+ const totalWaves = Number(state.totalWaves ?? state.wavePlan?.length ?? 0);
74
+ if (!Number.isFinite(totalWaves) || totalWaves <= 0) {
75
+ return false;
76
+ }
77
+
78
+ const events = readJournalEvents(projectRoot, batchId);
79
+ const mergeCompleted = events.filter((event) => event.type === "batch.merge_completed");
80
+ if (mergeCompleted.length < 1) {
81
+ return false;
82
+ }
83
+
84
+ let changed = false;
85
+ for (let waveIndex = 0; waveIndex < totalWaves; waveIndex++) {
86
+ const waveEvents = mergeCompleted.filter(
87
+ (event) => Number(event.payload?.waveIndex ?? -1) === waveIndex,
88
+ );
89
+ if (waveEvents.length < 1) {
90
+ continue;
91
+ }
92
+
93
+ const existing = (state.mergeResults ?? []).find((entry) => entry?.waveIndex === waveIndex);
94
+ if (existing && String(existing.status ?? "") === "succeeded") {
95
+ continue;
96
+ }
97
+
98
+ const lastEvent = waveEvents.at(-1);
99
+ const mergeCommit =
100
+ typeof lastEvent?.payload?.mergeCommit === "string" ? lastEvent.payload.mergeCommit : null;
101
+ recordWaveMergeResult({
102
+ state,
103
+ waveIndex,
104
+ status: "succeeded",
105
+ mergeCommit,
106
+ });
107
+ changed = true;
108
+ }
109
+
110
+ return changed;
111
+ }
112
+
113
+ /**
114
+ * @param {object} params
115
+ * @param {string} params.projectRoot
116
+ * @param {object} params.state
117
+ * @param {string} params.batchId
118
+ */
119
+ function postMergeLimboGateMissing({ projectRoot, state, batchId }) {
120
+ if (String(state.phase ?? "") === "completed") return false;
121
+ hydrateMergeResultsFromJournal({ projectRoot, state, batchId });
122
+ if (!detectPostMergeLimboForResume({ projectRoot, state })) return false;
123
+ return loadGateRecord(projectRoot, batchId) == null;
124
+ }
125
+
126
+ /**
127
+ * Finalize post-merge limbo in-process when journal/state show last wave merged (SP-378).
128
+ *
129
+ * @param {object} params
130
+ * @param {string} params.projectRoot
131
+ * @param {object} params.state
132
+ * @param {string} params.batchId
133
+ * @param {string} params.orchBranch
134
+ */
135
+ export function finalizeAttachedPostMergeLimbo({ projectRoot, state, batchId, orchBranch }) {
136
+ if (!postMergeLimboGateMissing({ projectRoot, state, batchId })) {
137
+ return null;
138
+ }
139
+ return tryFinalizePostMergeLimbo({
140
+ projectRoot,
141
+ state,
142
+ batchId,
143
+ orchBranch,
144
+ resumed: false,
145
+ });
146
+ }
147
+
148
+ /**
149
+ * Open integrate gate or spawn detached resume before attached engine exit (SP-378, GitHub #59).
150
+ *
151
+ * @param {object} params
152
+ * @param {string} params.projectRoot
153
+ * @param {string} [params.spineBin]
154
+ * @param {string} [params.signal]
155
+ */
156
+ export function finalizeAttachedLandLoopBeforeExit({
157
+ projectRoot,
158
+ spineBin,
159
+ signal = "SIGTERM",
160
+ }) {
161
+ if (attachedExitFinalizeInFlight) {
162
+ return { handled: false, reason: "finalize_in_flight" };
163
+ }
164
+ attachedExitFinalizeInFlight = true;
165
+
166
+ const loaded = loadSpineBatchState(projectRoot);
167
+ if (!loaded.raw) {
168
+ attachedExitFinalizeInFlight = false;
169
+ return { handled: false, reason: "no_active_batch" };
170
+ }
171
+
172
+ const state = loaded.raw;
173
+ const batchId = String(state.batchId ?? "");
174
+ const orchBranch = String(state.orchBranch ?? "");
175
+
176
+ if (String(state.phase ?? "") === "completed" || loadGateRecord(projectRoot, batchId)) {
177
+ attachedExitFinalizeInFlight = false;
178
+ return { handled: true, action: "already_finalized", batchId };
179
+ }
180
+
181
+ hydrateMergeResultsFromJournal({ projectRoot, state, batchId });
182
+ if (!detectPostMergeLimboForResume({ projectRoot, state })) {
183
+ attachedExitFinalizeInFlight = false;
184
+ return { handled: false, reason: "not_post_merge_limbo", batchId };
185
+ }
186
+
187
+ const finalizeResult = finalizeAttachedPostMergeLimbo({
188
+ projectRoot,
189
+ state,
190
+ batchId,
191
+ orchBranch,
192
+ });
193
+ if (finalizeResult?.ok) {
194
+ clearBatchEnginePid(state);
195
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
196
+ appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
197
+ signal,
198
+ action: "finalized_in_process",
199
+ });
200
+ attachedExitFinalizeInFlight = false;
201
+ return {
202
+ handled: true,
203
+ action: "finalized_in_process",
204
+ batchId,
205
+ result: finalizeResult,
206
+ };
207
+ }
208
+
209
+ const resolvedSpineBin = resolveDefaultSpineBin(spineBin);
210
+ const argv = buildAttachedBatchResumeArgv({ force: false });
211
+ const { enginePid, logPath } = spawnDetachedBatchEngine({
212
+ projectRoot,
213
+ spineBin: resolvedSpineBin,
214
+ argv,
215
+ });
216
+
217
+ const fresh = loadSpineBatchState(projectRoot);
218
+ if (fresh.raw && enginePid) {
219
+ recordBatchEnginePid(fresh.raw, enginePid);
220
+ saveSpineBatchState(projectRoot, fresh.raw, { bypassWriteGuard: true });
221
+ }
222
+
223
+ appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
224
+ signal,
225
+ action: "detached_resume_spawned",
226
+ enginePid,
227
+ logPath,
228
+ });
229
+
230
+ attachedExitFinalizeInFlight = false;
231
+ return {
232
+ handled: true,
233
+ action: "detached_resume_spawned",
234
+ batchId,
235
+ enginePid,
236
+ logPath,
237
+ };
238
+ }
239
+
37
240
  /**
38
241
  * @param {object|null|undefined} state
39
242
  * @param {number} waveIndex
@@ -66,10 +269,52 @@ export function maybeFinalizeAfterWaveMerge({
66
269
  if (String(state.phase ?? "") === "completed") {
67
270
  return null;
68
271
  }
272
+ hydrateMergeResultsFromJournal({ projectRoot, state, batchId: String(state.batchId ?? "") });
69
273
  if (!isLastWaveIndex(state, waveIndex)) {
70
274
  return null;
71
275
  }
72
- if (!isPostMergeLimbo(state)) {
276
+ if (!detectPostMergeLimboForResume({ projectRoot, state })) {
277
+ return null;
278
+ }
279
+ return tryFinalizePostMergeLimbo({
280
+ projectRoot,
281
+ state,
282
+ batchId,
283
+ orchBranch,
284
+ resumed,
285
+ resumeForced,
286
+ });
287
+ }
288
+
289
+ /**
290
+ * Whether resume should take the post-merge limbo fast path (no worker re-run).
291
+ *
292
+ * @param {object|null|undefined} state
293
+ */
294
+ export function shouldResumePostMergeLimbo(state) {
295
+ if (!state || typeof state !== "object") return false;
296
+ if (String(state.phase ?? "") === "completed") return false;
297
+ return isPostMergeLimbo(state);
298
+ }
299
+
300
+ /**
301
+ * Idempotent finalize when batch is in post-merge limbo (SP-280, SP-316).
302
+ *
303
+ * @param {object} params
304
+ */
305
+ export function tryFinalizePostMergeLimbo({
306
+ projectRoot,
307
+ state,
308
+ batchId,
309
+ orchBranch,
310
+ resumed = false,
311
+ resumeForced = false,
312
+ }) {
313
+ if (String(state.phase ?? "") === "completed") {
314
+ return null;
315
+ }
316
+ hydrateMergeResultsFromJournal({ projectRoot, state, batchId: String(state.batchId ?? "") });
317
+ if (!detectPostMergeLimboForResume({ projectRoot, state })) {
73
318
  return null;
74
319
  }
75
320
  return finalizeBatchForIntegrate({
@@ -105,7 +350,7 @@ export function finalizeBatchForIntegrate({
105
350
  state.endedAt = Date.now();
106
351
  }
107
352
 
108
- openIntegrateGateAfterBatchComplete({
353
+ const gateResult = openIntegrateGateAfterBatchComplete({
109
354
  projectRoot,
110
355
  batchId,
111
356
  batchState: { ...state, phase: "completed" },
@@ -113,7 +358,6 @@ export function finalizeBatchForIntegrate({
113
358
 
114
359
  if (!alreadyCompleted) {
115
360
  state.phase = "completed";
116
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
117
361
  appendJournalEvent(projectRoot, batchId, "batch.completed", {
118
362
  taskIds,
119
363
  mergeCommit: state.mergeResults?.at(-1)?.mergeCommit,
@@ -121,10 +365,22 @@ export function finalizeBatchForIntegrate({
121
365
  postMergeLimbo: !resumed,
122
366
  resumeForced,
123
367
  });
124
- } else {
125
- saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
126
368
  }
127
369
 
370
+ clearBatchEnginePid(state);
371
+
372
+ const gateRecord = loadGateRecord(projectRoot, batchId);
373
+ if (gateRecord) {
374
+ appendJournalEvent(projectRoot, batchId, "batch.land_loop_finalized", {
375
+ resumed,
376
+ resumeForced,
377
+ gateId: gateRecord.gateId ?? gateResult?.gate?.gateId ?? null,
378
+ source: resumed ? "resume_fast_path" : "engine_land_loop",
379
+ });
380
+ }
381
+
382
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
383
+
128
384
  const completionLabel = resumed ? "resumed and completed" : "completed";
129
385
  const nextSteps = resumed
130
386
  ? " → spine gate approve\n → spine integrate\n → spine batch complete\n"