pi-spine 2.15.0 → 2.17.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 (50) hide show
  1. package/package.json +1 -1
  2. package/skills/create-spine-tasks/SKILL.md +3 -1
  3. package/skills/create-spine-tasks/references/contract-template.md +12 -12
  4. package/skills/create-spine-tasks/references/prompt-template.md +8 -6
  5. package/skills/spine-autonomous-operator/SKILL.md +2 -0
  6. package/skills/spine-autonomous-operator/references/agent-shell-batch-policy.md +1 -1
  7. package/skills/spine-orchestrate-waves/SKILL.md +6 -4
  8. package/skills/spine-orchestrate-waves/references/outer-loop.md +16 -1
  9. package/skills/spine-release-operator/SKILL.md +63 -7
  10. package/skills/spine-release-operator/references/issue-intake-checklist.md +1 -1
  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 +15 -0
  13. package/src/batch/abort.mjs +82 -68
  14. package/src/batch/batch-guards.mjs +14 -0
  15. package/src/batch/batch-meta-reconstruct.mjs +5 -2
  16. package/src/batch/batch-state-lock.mjs +357 -0
  17. package/src/batch/contract-exec.mjs +12 -8
  18. package/src/batch/engine-lanes/merge.mjs +16 -11
  19. package/src/batch/engine-lanes/phase.mjs +45 -0
  20. package/src/batch/engine-lanes/queue.mjs +1 -1
  21. package/src/batch/engine-lanes/review-code.mjs +224 -0
  22. package/src/batch/engine-lanes/review-final.mjs +318 -0
  23. package/src/batch/engine-lanes/review-plan.mjs +315 -0
  24. package/src/batch/engine-lanes/review-poll.mjs +427 -0
  25. package/src/batch/engine-lanes/review-stub.mjs +146 -0
  26. package/src/batch/engine-lanes/review.mjs +4 -1532
  27. package/src/batch/engine-lanes.mjs +9 -37
  28. package/src/batch/engine.mjs +8 -16
  29. package/src/batch/lifecycle.mjs +106 -95
  30. package/src/batch/post-merge-finalize.mjs +128 -0
  31. package/src/batch/post-merge-limbo.mjs +14 -85
  32. package/src/batch/readers/spine-state.mjs +22 -1
  33. package/src/batch/readers/taskplane-state.mjs +22 -1
  34. package/src/batch/reconcile-batch.mjs +1 -1
  35. package/src/batch/resume-common.mjs +1 -1
  36. package/src/batch/resume-multi.mjs +6 -2
  37. package/src/batch/resume.mjs +1 -1
  38. package/src/batch/review-spawn.mjs +4 -3
  39. package/src/batch/state-io.mjs +55 -41
  40. package/src/cli/journal-follow.mjs +3 -1
  41. package/src/cli/lane-logs.mjs +3 -1
  42. package/src/cli/settings-slash.mjs +2 -1
  43. package/src/config/cursor-rules/profile.mjs +5 -1
  44. package/src/config/defaults.mjs +10 -1
  45. package/src/config/settings-fields.mjs +14 -0
  46. package/src/config/worker-context.mjs +2 -1
  47. package/src/planner/file-scope.mjs +109 -7
  48. package/src/tasks/analyze/index.mjs +16 -28
  49. package/src/tasks/packet/parse-prompt.mjs +138 -3
  50. package/src/tasks/validate-contract-warn.mjs +45 -0
@@ -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 {
@@ -21,6 +21,7 @@ import { appendJournalEvent } from "./journal.mjs";
21
21
  import { recordBatchTerminalMetric } from "./metrics.mjs";
22
22
  import { writeBatchPostMortem } from "./postmortem.mjs";
23
23
  import { appendBatchHistoryEntry, clearBatchEnginePid, saveSpineBatchState } from "./state.mjs";
24
+ import { withBatchStateLock } from "./batch-state-lock.mjs";
24
25
  import { loadBatchStateFile, parseBatchState, reconcileBatch } from "./reconcile.mjs";
25
26
  import { readAliveBatchEnginePid } from "./batch-state-io.mjs";
26
27
  import { terminateLaneWorkers } from "./worker-host.mjs";
@@ -206,55 +207,60 @@ export function dismissBatch(ctx) {
206
207
  force,
207
208
  });
208
209
  }
209
- const archivePath = archiveBatchState(projectRoot, batchId, loaded.raw);
210
- const postMortemPath = writeBatchPostMortem({
211
- projectRoot,
212
- batchState: loaded.raw,
213
- reconciliation,
214
- });
215
- const endedAt = Date.now();
216
- appendBatchHistoryEntry(projectRoot, {
217
- batchId,
218
- action: "dismissed",
219
- endedAt,
220
- diagnosis,
221
- reason: reason ?? null,
222
- archivePath: path.relative(projectRoot, archivePath),
223
- postMortemPath,
224
- });
225
- appendJournalEvent(projectRoot, batchId, "batch.dismissed", {
226
- diagnosis,
227
- reason: reason ?? null,
228
- archivePath: path.relative(projectRoot, archivePath),
229
- });
230
- const configResult = loadSpineConfig(projectRoot);
231
- const config = configResult.config ?? {};
232
- recordBatchTerminalMetric({
233
- projectRoot,
234
- batchId,
235
- batchState: { ...loaded.raw, endedAt },
236
- diagnosis: diagnosis ?? "dismissed",
237
- config,
238
- });
239
- cleanupBatchLaneWorktrees({
240
- projectRoot,
241
- batchId,
242
- batchState: loaded.raw,
243
- config,
244
- });
245
- clearCompletedBatchState(loaded.path, batchId);
246
- bumpDashboardInvalidateSignal(projectRoot, "batch_dismiss", batchId);
210
+ // Terminal dismiss write section under the global batch-state lock
211
+ // (SP-722 / #264): archive, history entry, and clearing the active state
212
+ // must not interleave with a concurrent engine save or resume writer.
213
+ return withBatchStateLock(projectRoot, () => {
214
+ const archivePath = archiveBatchState(projectRoot, batchId, loaded.raw);
215
+ const postMortemPath = writeBatchPostMortem({
216
+ projectRoot,
217
+ batchState: loaded.raw,
218
+ reconciliation,
219
+ });
220
+ const endedAt = Date.now();
221
+ appendBatchHistoryEntry(projectRoot, {
222
+ batchId,
223
+ action: "dismissed",
224
+ endedAt,
225
+ diagnosis,
226
+ reason: reason ?? null,
227
+ archivePath: path.relative(projectRoot, archivePath),
228
+ postMortemPath,
229
+ });
230
+ appendJournalEvent(projectRoot, batchId, "batch.dismissed", {
231
+ diagnosis,
232
+ reason: reason ?? null,
233
+ archivePath: path.relative(projectRoot, archivePath),
234
+ });
235
+ const configResult = loadSpineConfig(projectRoot);
236
+ const config = configResult.config ?? {};
237
+ recordBatchTerminalMetric({
238
+ projectRoot,
239
+ batchId,
240
+ batchState: { ...loaded.raw, endedAt },
241
+ diagnosis: diagnosis ?? "dismissed",
242
+ config,
243
+ });
244
+ cleanupBatchLaneWorktrees({
245
+ projectRoot,
246
+ batchId,
247
+ batchState: loaded.raw,
248
+ config,
249
+ });
250
+ clearCompletedBatchState(loaded.path, batchId);
251
+ bumpDashboardInvalidateSignal(projectRoot, "batch_dismiss", batchId);
247
252
 
248
- return {
249
- ok: true,
250
- exitCode: 0,
251
- batchId,
252
- diagnosis,
253
- headline: `Batch ${batchId} dismissed and archived`,
254
- suggestedCommand: "spine preflight",
255
- alternatives: ["spine plan all"],
256
- archivePath,
257
- };
253
+ return {
254
+ ok: true,
255
+ exitCode: 0,
256
+ batchId,
257
+ diagnosis,
258
+ headline: `Batch ${batchId} dismissed and archived`,
259
+ suggestedCommand: "spine preflight",
260
+ alternatives: ["spine plan all"],
261
+ archivePath,
262
+ };
263
+ });
258
264
  }
259
265
 
260
266
  /**
@@ -407,52 +413,57 @@ export function completeBatch(ctx) {
407
413
 
408
414
  terminateSupervisorIfRunning(projectRoot, batchId, "batch_complete");
409
415
 
410
- const archivePath = archiveBatchState(projectRoot, batchId, loaded.raw);
411
- const postMortemPath = writeBatchPostMortem({
412
- projectRoot,
413
- batchState: loaded.raw,
414
- reconciliation,
415
- });
416
- const endedAt = Date.now();
417
- appendBatchHistoryEntry(projectRoot, {
418
- batchId,
419
- action: "completed",
420
- endedAt,
421
- diagnosis: "completed",
422
- detectManualMerge,
423
- archivePath: path.relative(projectRoot, archivePath),
424
- postMortemPath,
425
- });
426
- appendJournalEvent(projectRoot, batchId, "batch.completed", {
427
- detectManualMerge,
428
- archivePath: path.relative(projectRoot, archivePath),
429
- lifecycle: "complete",
430
- });
431
- const configResult = loadSpineConfig(projectRoot);
432
- const config = configResult.config ?? {};
433
- recordBatchTerminalMetric({
434
- projectRoot,
435
- batchId,
436
- batchState: { ...loaded.raw, endedAt },
437
- diagnosis: "completed",
438
- config,
439
- });
440
- cleanupBatchLaneWorktrees({
441
- projectRoot,
442
- batchId,
443
- batchState: loaded.raw,
444
- config,
445
- });
446
- clearCompletedBatchState(loaded.path, batchId);
416
+ // Terminal complete write section under the global batch-state lock
417
+ // (SP-722 / #264): archive, history entry, and clearing the active state
418
+ // must not interleave with a concurrent engine save or resume writer.
419
+ return withBatchStateLock(projectRoot, () => {
420
+ const archivePath = archiveBatchState(projectRoot, batchId, loaded.raw);
421
+ const postMortemPath = writeBatchPostMortem({
422
+ projectRoot,
423
+ batchState: loaded.raw,
424
+ reconciliation,
425
+ });
426
+ const endedAt = Date.now();
427
+ appendBatchHistoryEntry(projectRoot, {
428
+ batchId,
429
+ action: "completed",
430
+ endedAt,
431
+ diagnosis: "completed",
432
+ detectManualMerge,
433
+ archivePath: path.relative(projectRoot, archivePath),
434
+ postMortemPath,
435
+ });
436
+ appendJournalEvent(projectRoot, batchId, "batch.completed", {
437
+ detectManualMerge,
438
+ archivePath: path.relative(projectRoot, archivePath),
439
+ lifecycle: "complete",
440
+ });
441
+ const configResult = loadSpineConfig(projectRoot);
442
+ const config = configResult.config ?? {};
443
+ recordBatchTerminalMetric({
444
+ projectRoot,
445
+ batchId,
446
+ batchState: { ...loaded.raw, endedAt },
447
+ diagnosis: "completed",
448
+ config,
449
+ });
450
+ cleanupBatchLaneWorktrees({
451
+ projectRoot,
452
+ batchId,
453
+ batchState: loaded.raw,
454
+ config,
455
+ });
456
+ clearCompletedBatchState(loaded.path, batchId);
447
457
 
448
- return {
449
- ok: true,
450
- exitCode: 0,
451
- batchId,
452
- diagnosis: "completed",
453
- headline: `Batch ${batchId} completed and archived`,
454
- suggestedCommand: "spine preflight",
455
- alternatives: ["spine plan all"],
456
- archivePath,
457
- };
458
+ return {
459
+ ok: true,
460
+ exitCode: 0,
461
+ batchId,
462
+ diagnosis: "completed",
463
+ headline: `Batch ${batchId} completed and archived`,
464
+ suggestedCommand: "spine preflight",
465
+ alternatives: ["spine plan all"],
466
+ archivePath,
467
+ };
468
+ });
458
469
  }
@@ -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;
@@ -1,6 +1,27 @@
1
1
  // @ts-nocheck
2
2
  /**
3
3
  * Parse Taskplane `.pi/batch-state.json` for dogfood reconciliation.
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", "done"]);
@@ -9,7 +30,7 @@ const ACTIVE = new Set(["pending", "running", "executing"]);
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 parseTaskplaneBatchState(raw) {
15
36
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
@@ -22,7 +22,7 @@ import { inferWorkerDoneMissingFailure } from "./diagnosis-worker-done-missing.m
22
22
  import { inferEngineOrphanCause } from "./diagnosis-parent-exit.mjs";
23
23
  import { findStubMarkedSucceededTask } from "./diagnosis-stub.mjs";
24
24
  import { detectOrphanRunning, journalEventsSinceResume } from "./orphan-detect.mjs";
25
- import { computePendingTasks } from "./resume-multi.mjs";
25
+ import { computePendingTasks } from "./resume-validation.mjs";
26
26
  import { computeStatusProgress } from "./status-json.mjs";
27
27
  import {
28
28
  detectBatchStateDrift,