pi-spine 2.16.0 → 2.18.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 (47) hide show
  1. package/bin/spine-gate.mjs +8 -2
  2. package/package.json +1 -1
  3. package/skills/create-spine-tasks/SKILL.md +3 -1
  4. package/skills/create-spine-tasks/references/contract-template.md +12 -12
  5. package/skills/create-spine-tasks/references/prompt-template.md +8 -6
  6. package/skills/spine-autonomous-operator/SKILL.md +2 -0
  7. package/skills/spine-autonomous-operator/references/agent-shell-batch-policy.md +1 -1
  8. package/skills/spine-orchestrate-waves/SKILL.md +6 -4
  9. package/skills/spine-orchestrate-waves/references/outer-loop.md +16 -1
  10. package/skills/spine-release-operator/SKILL.md +3 -0
  11. package/skills/spine-release-operator/references/pi-async-orchestration.md +2 -1
  12. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +14 -0
  13. package/src/batch/batch-guards.mjs +14 -0
  14. package/src/batch/batch-meta-reconstruct.mjs +5 -2
  15. package/src/batch/diagnosis-worker-done-missing.mjs +12 -1
  16. package/src/batch/engine-lanes/matrix-run.mjs +122 -26
  17. package/src/batch/engine-lanes/merge.mjs +16 -11
  18. package/src/batch/engine-lanes/phase.mjs +45 -0
  19. package/src/batch/engine-lanes/queue.mjs +1 -1
  20. package/src/batch/engine-lanes.mjs +9 -37
  21. package/src/batch/engine.mjs +8 -16
  22. package/src/batch/gate.mjs +153 -6
  23. package/src/batch/heartbeat.mjs +18 -0
  24. package/src/batch/post-merge-finalize.mjs +128 -0
  25. package/src/batch/post-merge-limbo.mjs +14 -85
  26. package/src/batch/readers/spine-state.mjs +22 -1
  27. package/src/batch/readers/taskplane-state.mjs +22 -1
  28. package/src/batch/reconcile-batch.mjs +1 -1
  29. package/src/batch/resume-common.mjs +1 -1
  30. package/src/batch/resume-gate-reopen.mjs +50 -0
  31. package/src/batch/resume-multi-validate.mjs +43 -0
  32. package/src/batch/resume-multi.mjs +6 -2
  33. package/src/batch/resume-prompt-parse-fail.mjs +75 -0
  34. package/src/batch/resume.mjs +21 -40
  35. package/src/batch/review-spawn.mjs +4 -3
  36. package/src/batch/salvage-batch-integrate-gate.mjs +180 -0
  37. package/src/batch/salvage-batch-integrate.mjs +66 -4
  38. package/src/batch/worker-heartbeat.mjs +31 -6
  39. package/src/batch/worker-host.mjs +27 -1
  40. package/src/batch/worker-output.mjs +56 -0
  41. package/src/cli/journal-follow.mjs +3 -1
  42. package/src/cli/lane-logs.mjs +3 -1
  43. package/src/cli/settings-slash.mjs +2 -1
  44. package/src/config/worker-context.mjs +2 -1
  45. package/src/planner/matrix.mjs +24 -0
  46. package/src/tasks/analyze/index.mjs +2 -1
  47. package/src/tasks/validate-contract-warn.mjs +45 -0
@@ -0,0 +1,45 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Batch phase transition helpers for the engine-lanes facade.
4
+ * Leaf module: journals phase changes without importing resume/limbo/reconcile.
5
+ */
6
+
7
+ import { appendJournalEvent } from "../journal.mjs";
8
+
9
+ /**
10
+ * @param {string} fromPhase
11
+ * @param {string} toPhase
12
+ */
13
+ function phaseTransitionEventType(fromPhase, toPhase) {
14
+ if (fromPhase === "planning" && toPhase === "running") return "batch.started";
15
+ if (toPhase === "completed") return "batch.completed";
16
+ if (toPhase === "failed") return "batch.failed";
17
+ if (toPhase === "aborted") return "batch.aborted";
18
+ return null;
19
+ }
20
+
21
+ /**
22
+ * @param {object} params
23
+ */
24
+ function recordPhaseTransition({ projectRoot, batchId, fromPhase, toPhase, extra = {} }) {
25
+ const type = phaseTransitionEventType(fromPhase, toPhase);
26
+ if (!type) return;
27
+ appendJournalEvent(projectRoot, batchId, type, {
28
+ fromPhase,
29
+ toPhase,
30
+ ...extra,
31
+ });
32
+ }
33
+
34
+ export function transitionPhase(state, newPhase, ctx) {
35
+ const fromPhase = state.phase;
36
+ if (fromPhase === newPhase) return;
37
+ state.phase = newPhase;
38
+ recordPhaseTransition({
39
+ projectRoot: ctx.projectRoot,
40
+ batchId: ctx.batchId,
41
+ fromPhase,
42
+ toPhase: newPhase,
43
+ ...ctx.extra,
44
+ });
45
+ }
@@ -167,7 +167,7 @@ export function buildTasksAndLanesFromPlan({ plan, discovered, projectRoot, batc
167
167
  /**
168
168
  * @param {object} params
169
169
  */
170
- export async function skipTaskDoneOnDisk({
170
+ export function skipTaskDoneOnDisk({
171
171
  projectRoot,
172
172
  state,
173
173
  batchId,
@@ -1,6 +1,14 @@
1
1
  // @ts-nocheck
2
2
  /**
3
3
  * Lane task execution facade — re-exports split modules and phase transitions.
4
+ *
5
+ * Cycle-free ownership (#267 / SP-736): this facade participates in no batch import
6
+ * cycle and must stay that way. It must not import from the resume/limbo/reconcile
7
+ * cluster (resume-multi.mjs, post-merge-limbo.mjs, reconcile*.mjs, gate.mjs) —
8
+ * resume entry points (resume.mjs) import this facade, never the reverse. Lane-phase
9
+ * helpers live under engine-lanes/* leaves (queue, merge, review, matrix, commit,
10
+ * orch-sync). `tests/arch/import-cycles.test.mjs` enforces this with an empty
11
+ * ALLOWED_CLUSTER_CYCLES.
4
12
  */
5
13
 
6
14
  import fs from "node:fs";
@@ -80,43 +88,7 @@ export {
80
88
 
81
89
  export { runMatrixTaskOnLane, runMatrixSubLane } from "./engine-lanes/matrix-run.mjs";
82
90
 
83
- /**
84
- * @param {string} fromPhase
85
- * @param {string} toPhase
86
- */
87
- function phaseTransitionEventType(fromPhase, toPhase) {
88
- if (fromPhase === "planning" && toPhase === "running") return "batch.started";
89
- if (toPhase === "completed") return "batch.completed";
90
- if (toPhase === "failed") return "batch.failed";
91
- if (toPhase === "aborted") return "batch.aborted";
92
- return null;
93
- }
94
-
95
- /**
96
- * @param {object} params
97
- */
98
- function recordPhaseTransition({ projectRoot, batchId, fromPhase, toPhase, extra = {} }) {
99
- const type = phaseTransitionEventType(fromPhase, toPhase);
100
- if (!type) return;
101
- appendJournalEvent(projectRoot, batchId, type, {
102
- fromPhase,
103
- toPhase,
104
- ...extra,
105
- });
106
- }
107
-
108
- export function transitionPhase(state, newPhase, ctx) {
109
- const fromPhase = state.phase;
110
- if (fromPhase === newPhase) return;
111
- state.phase = newPhase;
112
- recordPhaseTransition({
113
- projectRoot: ctx.projectRoot,
114
- batchId: ctx.batchId,
115
- fromPhase,
116
- toPhase: newPhase,
117
- ...ctx.extra,
118
- });
119
- }
91
+ export { transitionPhase } from "./engine-lanes/phase.mjs";
120
92
 
121
93
  export async function runTaskOnLane({
122
94
  projectRoot,
@@ -10,7 +10,11 @@ import { runBatchPreflight, resolveTasksRoot } from "../config/spine-preflight-l
10
10
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
11
11
  import { integrateOrchToBase } from "./integrate.mjs";
12
12
  import { installAttachedEngineShutdownHandlers } from "./attached-engine-handoff.mjs";
13
- import { finalizeBatchForIntegrate, tryFinalizePostMergeLimbo } from "./post-merge-limbo.mjs";
13
+ import {
14
+ finalizeBatchForIntegrate,
15
+ maybeFinalizeAfterWaveMerge,
16
+ tryFinalizePostMergeLimbo,
17
+ } from "./post-merge-limbo.mjs";
14
18
  import { detectPostMergeLimboForResume } from "./resume-multi-validate.mjs";
15
19
  import { appendJournalEvent } from "./journal.mjs";
16
20
  import { persistBatchMetaFromStartState } from "./batch-meta.mjs";
@@ -45,20 +49,7 @@ import {
45
49
  skipTaskDoneOnDisk,
46
50
  transitionPhase,
47
51
  } from "./engine-lanes.mjs";
48
- import { rejectNestedBatchStart } from "./batch-guards.mjs";
49
-
50
- /**
51
- * @param {string} batchId
52
- */
53
- function buildEnginePausedResult(batchId) {
54
- return {
55
- ok: true,
56
- exitCode: 0,
57
- batchId,
58
- paused: true,
59
- output: "Batch paused.\n",
60
- };
61
- }
52
+ import { buildEnginePausedResult, rejectNestedBatchStart } from "./batch-guards.mjs";
62
53
 
63
54
  export {
64
55
  assessWaveMergeEligibility,
@@ -285,7 +276,7 @@ export async function startBatch({
285
276
  if (pauseAtTick.stop) {
286
277
  return buildEnginePausedResult(batchId);
287
278
  }
288
- /** @type {Map<number, { lane: object, runs: Array<{ taskId: string, run: () => Promise<{ ok: boolean, aborted?: boolean }> }> }>} */
279
+ /** @type {Map<number, { lane: object, runs: Array<{ taskId: string, run: () => Promise<{ ok: boolean, aborted?: boolean }> | { ok: boolean, aborted?: boolean, skipped?: boolean } }> }>} */
289
280
  const runsByLane = new Map();
290
281
 
291
282
  for (let laneInTick = 0; laneInTick < (tick.lanes?.length ?? 0); laneInTick++) {
@@ -430,6 +421,7 @@ export async function startBatch({
430
421
  baseBranch,
431
422
  orchBranch,
432
423
  waveIndex: wave.index,
424
+ finalizeAfterWaveMerge: maybeFinalizeAfterWaveMerge,
433
425
  });
434
426
  if (!mergeResult.ok) {
435
427
  return {
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import crypto from "node:crypto";
7
+ import fs from "node:fs";
7
8
  import { resolveGatePostureConfig } from "../config/gate-posture-config.mjs";
8
9
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
9
10
  import { writeJsonAtomic } from "../fs/atomic-write.mjs";
@@ -200,6 +201,133 @@ export function openIntegrateGateAfterBatchComplete(ctx) {
200
201
  };
201
202
  }
202
203
 
204
+ /**
205
+ * Remove a gate record so a fresh gate can be opened (SP-740 / #275).
206
+ * Supported counterpart to hand-deleting `gate.json` (runbook §5.2 pre-v2.18).
207
+ *
208
+ * @param {string} projectRoot
209
+ * @param {string} batchId
210
+ * @returns {boolean} true when an existing record was removed
211
+ */
212
+ export function removeGateRecord(projectRoot, batchId) {
213
+ const filePath = gateRecordPath(projectRoot, batchId);
214
+ if (!fs.existsSync(filePath)) return false;
215
+ fs.rmSync(filePath, { force: true });
216
+ return true;
217
+ }
218
+
219
+ /**
220
+ * Re-open the integrate gate for a completed batch (SP-740 / #275).
221
+ *
222
+ * After `stale_revision` (orch tip drift past the approved pin) or a removed gate
223
+ * record, completed-phase batches had no working re-open path: `spine batch resume
224
+ * --force` refuses phase=completed. Reopening removes the stale/decided record and
225
+ * routes through `openIntegrateGateAfterBatchComplete`, re-pinning `targetRevision`
226
+ * to the current orch tip and re-collecting evidence for a fresh approval.
227
+ *
228
+ * Fail-closed guarantees preserved: a gate that is approved or pending AND still
229
+ * pinned to the current orch tip is never invalidated here — approve/integrate
230
+ * instead. Only missing, stale-pin, or rejected records are replaced.
231
+ *
232
+ * @param {object} ctx
233
+ * @param {string} ctx.projectRoot
234
+ * @param {string} ctx.batchId
235
+ * @param {object|null} [ctx.batchState]
236
+ * @returns {{ ok: boolean, exitCode: number, reopened: boolean, reason: string, gate: object|null, headline: string, suggestedCommand: string, alternatives: string[], error?: string, extendedError?: string|null }}
237
+ */
238
+ export function reopenIntegrateGateForCompletedBatch(ctx) {
239
+ const { projectRoot, batchId, batchState = null } = ctx;
240
+ const state = batchState ?? loadBatchStateFile(projectRoot).raw ?? null;
241
+
242
+ if (String(state?.phase ?? "") !== "completed") {
243
+ return {
244
+ ok: false,
245
+ exitCode: 1,
246
+ reopened: false,
247
+ reason: "batch_not_completed",
248
+ gate: null,
249
+ headline: "Gate reopen requires a completed batch",
250
+ suggestedCommand: "spine status --diagnose",
251
+ alternatives: [],
252
+ error: `Batch ${batchId} is in phase ${String(state?.phase ?? "unknown")} — gate reopen only applies to completed batches`,
253
+ };
254
+ }
255
+
256
+ if (!state?.orchBranch) {
257
+ return {
258
+ ok: false,
259
+ exitCode: 1,
260
+ reopened: false,
261
+ reason: "no_orch_branch",
262
+ gate: null,
263
+ headline: "Gate reopen blocked — batch state has no orch branch",
264
+ suggestedCommand: "spine status --diagnose",
265
+ alternatives: [],
266
+ error: "batchState.orchBranch missing; cannot pin a fresh targetRevision",
267
+ };
268
+ }
269
+
270
+ const existing = loadGateRecord(projectRoot, batchId);
271
+ if (existing && (existing.status === "approved" || existing.status === "pending")) {
272
+ const pinCheck = validateGateTargetRevision(projectRoot, existing, state);
273
+ if (pinCheck.ok) {
274
+ const approved = String(existing.status) === "approved";
275
+ return {
276
+ ok: true,
277
+ exitCode: 0,
278
+ reopened: false,
279
+ reason: approved ? "gate_current" : "gate_pending",
280
+ gate: existing,
281
+ headline: approved
282
+ ? "Gate already approved and pinned to the current orch tip — nothing to reopen"
283
+ : "Gate already pending with a current pin — approve the existing record",
284
+ suggestedCommand: approved ? "spine integrate" : "spine gate approve",
285
+ alternatives: ["spine gate status"],
286
+ };
287
+ }
288
+ }
289
+
290
+ // Missing, stale-pin, or rejected record: clear the way and re-open with a fresh pin.
291
+ removeGateRecord(projectRoot, batchId);
292
+ appendJournalEvent(projectRoot, batchId, "gate.reopened", {
293
+ previousStatus: existing?.status ?? null,
294
+ previousTargetRevision: existing?.targetRevision ?? null,
295
+ source: "spine gate reopen",
296
+ });
297
+
298
+ const gateResult = openIntegrateGateAfterBatchComplete({
299
+ projectRoot,
300
+ batchId,
301
+ batchState: { ...state, phase: "completed" },
302
+ });
303
+
304
+ if (gateResult.skipped) {
305
+ return {
306
+ ok: false,
307
+ exitCode: 1,
308
+ reopened: false,
309
+ reason: gateResult.reason ?? "gate_open_skipped",
310
+ gate: null,
311
+ headline: "Gate reopen failed — integrate gate could not be opened",
312
+ suggestedCommand: "spine status --diagnose",
313
+ alternatives: [],
314
+ error: gateResult.reason ?? "openIntegrateGateAfterBatchComplete skipped",
315
+ };
316
+ }
317
+
318
+ return {
319
+ ok: true,
320
+ exitCode: 0,
321
+ reopened: true,
322
+ reason: "reopened",
323
+ gate: gateResult.gate,
324
+ extendedError: gateResult.extendedError ?? null,
325
+ headline: `Integrate gate re-opened — ${formatGateSummary(gateResult.gate)}; targetRevision re-pinned to current orch tip`,
326
+ suggestedCommand: "spine gate approve",
327
+ alternatives: ["spine gate status", "/spine-gate approve"],
328
+ };
329
+ }
330
+
203
331
  /**
204
332
  * @param {object} ctx
205
333
  * @param {string} ctx.projectRoot
@@ -210,12 +338,22 @@ export function getIntegrateGateStatus(ctx) {
210
338
  const gate = loadGateRecord(projectRoot, batchId);
211
339
 
212
340
  if (!gate) {
341
+ // SP-740 / #275: agree with `spine integrate` — a completed batch without a
342
+ // gate record has a working re-open path; non-completed batches keep the
343
+ // diagnose suggestion.
344
+ const completed =
345
+ String(loadBatchStateFile(projectRoot).raw?.phase ?? "") === "completed";
213
346
  return {
214
347
  ok: true,
215
348
  exitCode: 0,
216
349
  gate: null,
217
- headline: "No integrate gate on record",
218
- suggestedCommand: "spine status --diagnose",
350
+ headline: completed
351
+ ? "No integrate gate on record — batch completed; re-open and re-approve"
352
+ : "No integrate gate on record",
353
+ suggestedCommand: completed ? "spine gate reopen" : "spine status --diagnose",
354
+ alternatives: completed
355
+ ? ["spine batch resume --force", "spine status --diagnose"]
356
+ : [],
219
357
  };
220
358
  }
221
359
 
@@ -282,16 +420,25 @@ export function checkIntegrateGate(ctx) {
282
420
 
283
421
  const gate = loadGateRecord(projectRoot, batchId);
284
422
  if (!gate) {
285
- const error = "Integrate gate not opened — approve evidence before merging";
423
+ // SP-740 / #275: for completed batches point at the working re-open path so
424
+ // integrate and `spine gate status` agree. Blocker code / exitCode unchanged —
425
+ // automation switches on `missing_gate`, not display text.
426
+ const completed =
427
+ String((ctx.batchState ?? loadBatchStateFile(projectRoot).raw)?.phase ?? "") === "completed";
428
+ const error = completed
429
+ ? "Integrate gate not opened — re-open and re-approve the completed batch before merging"
430
+ : "Integrate gate not opened — approve evidence before merging";
286
431
  return {
287
432
  ok: false,
288
433
  required: true,
289
434
  exitCode: 2,
290
435
  failureClass: "GateBlocked",
291
436
  error,
292
- headline: "Integrate blocked — no gate record (run batch to completion or spine gate status)",
293
- suggestedCommand: "spine gate status",
294
- alternatives: ["/spine-gate"],
437
+ headline: completed
438
+ ? "Integrate blocked — no gate record (batch completed: spine gate reopen to re-open and re-approve)"
439
+ : "Integrate blocked — no gate record (run batch to completion or spine gate status)",
440
+ suggestedCommand: completed ? "spine gate reopen" : "spine gate status",
441
+ alternatives: completed ? ["spine gate status", "/spine-gate"] : ["/spine-gate"],
295
442
  blockers: [makeBlocker("missing_gate", error)],
296
443
  };
297
444
  }
@@ -279,6 +279,24 @@ export function activitySignalsChanged(prev, next) {
279
279
  return false;
280
280
  }
281
281
 
282
+ /**
283
+ * Static-null progress snapshot (issue #272): every progress signal is absent, so
284
+ * the snapshot carries no evidence of forward movement. Heartbeat emission or
285
+ * child-process liveness alone must not refresh the stall anchor while snapshots
286
+ * stay static-null, otherwise a hung worker slides the stall budget forever.
287
+ * @param {object | null | undefined} signals
288
+ * @returns {boolean}
289
+ */
290
+ export function isStaticNullProgressSnapshot(signals) {
291
+ if (!signals) return true;
292
+ return (
293
+ signals.statusMtimeMs == null &&
294
+ signals.lastCommitAtMs == null &&
295
+ signals.fileScopeMtimeMs == null &&
296
+ (signals.dirtyPaths?.length ?? 0) === 0
297
+ );
298
+ }
299
+
282
300
  /**
283
301
  * @param {object | null} prev
284
302
  * @param {object} next
@@ -0,0 +1,128 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Post-merge finalize leaf — wave-merge finalize hook without the limbo module graph (SP-734 / #267).
4
+ *
5
+ * Cycle-safe imports only (`journal.mjs`, `merge/wave-merge-state.mjs`). The heavy
6
+ * dependencies (`detectPostMergeLimboForResume` from resume-multi-validate.mjs and
7
+ * `tryFinalizePostMergeLimbo` from post-merge-limbo.mjs, which transitively pull in
8
+ * gate.mjs → reconcile → resume-multi) are injected via `createMaybeFinalizeAfterWaveMerge`
9
+ * so `engine-lanes/merge.mjs` never imports `post-merge-limbo.mjs`.
10
+ */
11
+
12
+ import { readJournalEvents } from "./journal.mjs";
13
+ import { recordWaveMergeResult } from "./merge/wave-merge-state.mjs";
14
+
15
+ /**
16
+ * Sync missing mergeResults rows from journal merge_completed events (SP-378, GitHub #59).
17
+ *
18
+ * @param {object} params
19
+ * @param {string} params.projectRoot
20
+ * @param {object} params.state
21
+ * @param {string} params.batchId
22
+ */
23
+ export function hydrateMergeResultsFromJournal({ projectRoot, state, batchId }) {
24
+ const totalWaves = Number(state.totalWaves ?? state.wavePlan?.length ?? 0);
25
+ if (!Number.isFinite(totalWaves) || totalWaves <= 0) {
26
+ return false;
27
+ }
28
+
29
+ const events = readJournalEvents(projectRoot, batchId);
30
+ const mergeCompleted = events.filter((event) => event.type === "batch.merge_completed");
31
+ if (mergeCompleted.length < 1) {
32
+ return false;
33
+ }
34
+
35
+ let changed = false;
36
+ for (let waveIndex = 0; waveIndex < totalWaves; waveIndex++) {
37
+ const waveEvents = mergeCompleted.filter(
38
+ (event) => Number(event.payload?.waveIndex ?? -1) === waveIndex,
39
+ );
40
+ if (waveEvents.length < 1) {
41
+ continue;
42
+ }
43
+
44
+ const existing = (state.mergeResults ?? []).find((entry) => entry?.waveIndex === waveIndex);
45
+ if (existing && String(existing.status ?? "") === "succeeded") {
46
+ continue;
47
+ }
48
+
49
+ const lastEvent = waveEvents.at(-1);
50
+ const mergeCommit =
51
+ typeof lastEvent?.payload?.mergeCommit === "string" ? lastEvent.payload.mergeCommit : null;
52
+ recordWaveMergeResult({
53
+ state,
54
+ waveIndex,
55
+ status: "succeeded",
56
+ mergeCommit,
57
+ });
58
+ changed = true;
59
+ }
60
+
61
+ return changed;
62
+ }
63
+
64
+ /**
65
+ * @param {object|null|undefined} state
66
+ * @param {number} waveIndex
67
+ */
68
+ export function isLastWaveIndex(state, waveIndex) {
69
+ if (!state || typeof state !== "object") return false;
70
+ const totalWaves = Number(state.totalWaves ?? state.wavePlan?.length ?? 0);
71
+ if (!Number.isFinite(totalWaves) || totalWaves <= 0) return false;
72
+ return waveIndex >= totalWaves - 1;
73
+ }
74
+
75
+ /**
76
+ * Build the post-wave-merge finalize hook with injected limbo dependencies (SP-734).
77
+ * Keeps `engine-lanes/merge.mjs` free of the post-merge-limbo → gate → reconcile →
78
+ * resume-multi import cycle: callers that already own the limbo graph inject the real
79
+ * implementations.
80
+ *
81
+ * @param {object} deps
82
+ * @param {(params: { projectRoot: string, state: object }) => boolean} deps.detectPostMergeLimbo
83
+ * @param {(params: object) => object|null} deps.tryFinalizeLimbo
84
+ * @returns {(params: object) => object|null}
85
+ */
86
+ export function createMaybeFinalizeAfterWaveMerge({ detectPostMergeLimbo, tryFinalizeLimbo }) {
87
+ /**
88
+ * Finalize immediately after the last wave merge so post-merge limbo never opens
89
+ * (SP-280, SP-281 — attached engine + resume orphan race).
90
+ *
91
+ * @param {object} params
92
+ * @param {string} params.projectRoot
93
+ * @param {object} params.state
94
+ * @param {string} params.batchId
95
+ * @param {string} params.orchBranch
96
+ * @param {number} params.waveIndex
97
+ * @param {boolean} [params.resumed]
98
+ * @param {boolean} [params.resumeForced]
99
+ */
100
+ return function maybeFinalizeAfterWaveMerge({
101
+ projectRoot,
102
+ state,
103
+ batchId,
104
+ orchBranch,
105
+ waveIndex,
106
+ resumed = false,
107
+ resumeForced = false,
108
+ }) {
109
+ if (String(state.phase ?? "") === "completed") {
110
+ return null;
111
+ }
112
+ hydrateMergeResultsFromJournal({ projectRoot, state, batchId: String(state.batchId ?? "") });
113
+ if (!isLastWaveIndex(state, waveIndex)) {
114
+ return null;
115
+ }
116
+ if (!detectPostMergeLimbo({ projectRoot, state })) {
117
+ return null;
118
+ }
119
+ return tryFinalizeLimbo({
120
+ projectRoot,
121
+ state,
122
+ batchId,
123
+ orchBranch,
124
+ resumed,
125
+ resumeForced,
126
+ });
127
+ };
128
+ }
@@ -11,9 +11,12 @@ import {
11
11
  } from "./detached-spawn.mjs";
12
12
  import { loadGateRecord, openIntegrateGateAfterBatchComplete } from "./gate.mjs";
13
13
  import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
14
- import { recordWaveMergeResult } from "./merge/wave-merge-state.mjs";
15
14
  import { detectPostMergeLimboForResume } from "./resume-multi-validate.mjs";
16
15
  import { isPostMergeLimbo } from "./limbo-detect.mjs";
16
+ import {
17
+ createMaybeFinalizeAfterWaveMerge,
18
+ hydrateMergeResultsFromJournal,
19
+ } from "./post-merge-finalize.mjs";
17
20
  import {
18
21
  clearBatchEnginePid,
19
22
  loadSpineBatchState,
@@ -22,6 +25,7 @@ import {
22
25
  } from "./state.mjs";
23
26
 
24
27
  export { isPostMergeLimbo } from "./limbo-detect.mjs";
28
+ export { hydrateMergeResultsFromJournal, isLastWaveIndex } from "./post-merge-finalize.mjs";
25
29
 
26
30
  const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
27
31
 
@@ -39,52 +43,8 @@ export function resolveDefaultSpineBin(spineBin) {
39
43
 
40
44
  /**
41
45
  * Sync missing mergeResults rows from journal merge_completed events (SP-378, GitHub #59).
42
- *
43
- * @param {object} params
44
- * @param {string} params.projectRoot
45
- * @param {object} params.state
46
- * @param {string} params.batchId
46
+ * Implementation lives in the `post-merge-finalize.mjs` leaf (SP-734); re-exported here.
47
47
  */
48
- export function hydrateMergeResultsFromJournal({ projectRoot, state, batchId }) {
49
- const totalWaves = Number(state.totalWaves ?? state.wavePlan?.length ?? 0);
50
- if (!Number.isFinite(totalWaves) || totalWaves <= 0) {
51
- return false;
52
- }
53
-
54
- const events = readJournalEvents(projectRoot, batchId);
55
- const mergeCompleted = events.filter((event) => event.type === "batch.merge_completed");
56
- if (mergeCompleted.length < 1) {
57
- return false;
58
- }
59
-
60
- let changed = false;
61
- for (let waveIndex = 0; waveIndex < totalWaves; waveIndex++) {
62
- const waveEvents = mergeCompleted.filter(
63
- (event) => Number(event.payload?.waveIndex ?? -1) === waveIndex,
64
- );
65
- if (waveEvents.length < 1) {
66
- continue;
67
- }
68
-
69
- const existing = (state.mergeResults ?? []).find((entry) => entry?.waveIndex === waveIndex);
70
- if (existing && String(existing.status ?? "") === "succeeded") {
71
- continue;
72
- }
73
-
74
- const lastEvent = waveEvents.at(-1);
75
- const mergeCommit =
76
- typeof lastEvent?.payload?.mergeCommit === "string" ? lastEvent.payload.mergeCommit : null;
77
- recordWaveMergeResult({
78
- state,
79
- waveIndex,
80
- status: "succeeded",
81
- mergeCommit,
82
- });
83
- changed = true;
84
- }
85
-
86
- return changed;
87
- }
88
48
 
89
49
  /**
90
50
  * @param {object} params
@@ -326,54 +286,23 @@ export function finalizeAttachedLandLoopBeforeExit({
326
286
  };
327
287
  }
328
288
 
329
- /**
330
- * @param {object|null|undefined} state
331
- * @param {number} waveIndex
332
- */
333
- export function isLastWaveIndex(state, waveIndex) {
334
- if (!state || typeof state !== "object") return false;
335
- const totalWaves = Number(state.totalWaves ?? state.wavePlan?.length ?? 0);
336
- if (!Number.isFinite(totalWaves) || totalWaves <= 0) return false;
337
- return waveIndex >= totalWaves - 1;
338
- }
339
-
340
289
  /**
341
290
  * Finalize immediately after the last wave merge so post-merge limbo never opens
342
291
  * (SP-280, SP-281 — attached engine + resume orphan race).
343
292
  *
293
+ * Built from the `post-merge-finalize.mjs` leaf with the limbo detection/finalize
294
+ * implementations injected (SP-734) so `engine-lanes/merge.mjs` can receive this hook
295
+ * without importing the limbo module graph.
296
+ *
344
297
  * @param {object} params
345
298
  * @param {boolean} [params.resumed]
346
299
  * @param {boolean} [params.resumeForced]
347
300
  * @returns {ReturnType<typeof finalizeBatchForIntegrate>|null}
348
301
  */
349
- export function maybeFinalizeAfterWaveMerge({
350
- projectRoot,
351
- state,
352
- batchId,
353
- orchBranch,
354
- waveIndex,
355
- resumed = false,
356
- resumeForced = false,
357
- }) {
358
- if (String(state.phase ?? "") === "completed") {
359
- return null;
360
- }
361
- hydrateMergeResultsFromJournal({ projectRoot, state, batchId: String(state.batchId ?? "") });
362
- if (!isLastWaveIndex(state, waveIndex)) {
363
- return null;
364
- }
365
- if (!detectPostMergeLimboForResume({ projectRoot, state })) {
366
- return null;
367
- }
368
- return tryFinalizePostMergeLimbo({
369
- projectRoot,
370
- state,
371
- batchId,
372
- orchBranch,
373
- resumed,
374
- resumeForced,
375
- });
376
- }
302
+ export const maybeFinalizeAfterWaveMerge = createMaybeFinalizeAfterWaveMerge({
303
+ detectPostMergeLimbo: detectPostMergeLimboForResume,
304
+ tryFinalizeLimbo: tryFinalizePostMergeLimbo,
305
+ });
377
306
 
378
307
  /**
379
308
  * Whether resume should take the post-merge limbo fast path (no worker re-run).
@@ -1,6 +1,27 @@
1
1
  // @ts-nocheck
2
2
  /**
3
3
  * Parse pi-spine batch-state.json (schema v1, tolerant reader).
4
+ *
5
+ * The normalized shape is declared locally so this reader stays a leaf in the batch import
6
+ * graph: a JSDoc type-import pointing at reconcile.mjs makes the arch cycle detector see a
7
+ * readers -> reconcile edge even though no runtime import exists (SP-735 / #267).
8
+ *
9
+ * @typedef {object} NormalizedBatchState
10
+ * @property {string} source
11
+ * @property {string} batchId
12
+ * @property {string} phase
13
+ * @property {string} baseBranch
14
+ * @property {string|null} orchBranch
15
+ * @property {unknown} startedAt
16
+ * @property {unknown} endedAt
17
+ * @property {number} failedTasks
18
+ * @property {number} succeededTasks
19
+ * @property {number} totalTasks
20
+ * @property {unknown[]} mergeResults
21
+ * @property {Array<object>} tasks
22
+ * @property {Array<object>} segments
23
+ * @property {Array<object>} lanes
24
+ * @property {Record<string, unknown>} raw
4
25
  */
5
26
 
6
27
  const TERMINAL_SUCCESS = new Set(["completed", "succeeded", "skipped"]);
@@ -9,7 +30,7 @@ const ACTIVE = new Set(["pending", "running"]);
9
30
 
10
31
  /**
11
32
  * @param {unknown} raw
12
- * @returns {import("../reconcile.mjs").NormalizedBatchState | null}
33
+ * @returns {NormalizedBatchState | null}
13
34
  */
14
35
  export function parseSpineBatchState(raw) {
15
36
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;