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
@@ -67,3 +67,17 @@ export function rejectNestedBatchStart(projectRoot) {
67
67
  `Parent batch: ${parentBatchId}, projectRoot: ${projectRoot}\n`,
68
68
  };
69
69
  }
70
+
71
+ /**
72
+ * @param {string} batchId
73
+ * @returns {{ ok: true, exitCode: 0, batchId: string, paused: true, output: string }}
74
+ */
75
+ export function buildEnginePausedResult(batchId) {
76
+ return {
77
+ ok: true,
78
+ exitCode: 0,
79
+ batchId,
80
+ paused: true,
81
+ output: "Batch paused.\n",
82
+ };
83
+ }
@@ -9,8 +9,11 @@ import { BATCH_META_FILENAME, batchMetaPath } from "./batch-meta.mjs";
9
9
  import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
10
10
  import { rebuildBatchStateFromJournal } from "./journal-rebuild.mjs";
11
11
  import { computePendingTasks, findResumableWave } from "./resume-validation.mjs";
12
- import { createInitialBatchState, clearBatchEnginePid, saveSpineBatchState } from "./state.mjs";
13
- import { loadSpineBatchState } from "./state-io.mjs";
12
+ // Leaf rewire (SP-735 / #267): state-io/state-guards are leaves; state.mjs stays only for
13
+ // createInitialBatchState, which is defined in the state facade.
14
+ import { createInitialBatchState } from "./state.mjs";
15
+ import { loadSpineBatchState, saveSpineBatchState } from "./state-io.mjs";
16
+ import { clearBatchEnginePid } from "./state-guards.mjs";
14
17
  import { laneTaskBranch, laneWorktreePath } from "./worktree.mjs";
15
18
 
16
19
  /**
@@ -0,0 +1,357 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Global inter-process lock for batch-state writers (SP-722 / GitHub #264).
4
+ *
5
+ * Serializes read-modify-write cycles on `.spine/batch-state.json`,
6
+ * `.spine/batch-history.json`, and abort-signal writes across the engine,
7
+ * supervisor, and CLI processes. Implemented as an exclusive lock file on
8
+ * `.spine/runtime/batch-state.lock` (temp write + `linkSync` publish) with
9
+ * PID-liveness stale breaking — the same primitive as the resume handoff
10
+ * lock, but scoped to state/history writes rather than resume ownership.
11
+ *
12
+ * Lock ordering (deadlock avoidance):
13
+ * 1. The per-batch resume handoff lock (`resume-handoff.lock`) MAY be held
14
+ * while acquiring this global lock (handoff → global is the only legal
15
+ * cross-lock order; see `attached-runner-reconcile.mjs`).
16
+ * 2. A holder of this global lock MUST NOT acquire the resume handoff lock.
17
+ * 3. Within this lock, batch-state writes happen before batch-history writes.
18
+ * 4. No nested acquisition from the same process: `withBatchStateLock` is
19
+ * re-entrant per process — a nested call runs `fn` directly instead of
20
+ * re-acquiring, so wrappers may freely compose (e.g. abort wraps a
21
+ * section that internally calls `appendBatchHistoryEntry`).
22
+ */
23
+
24
+ import crypto from "node:crypto";
25
+ import fs from "node:fs";
26
+ import path from "node:path";
27
+ import {
28
+ ENGINE_STARTTIME_TOLERANCE_MS,
29
+ isProcessAlive,
30
+ probeProcessStartTimeMs,
31
+ } from "../process/liveness.mjs";
32
+
33
+ export const BATCH_STATE_LOCK_REL = path.join(".spine", "runtime", "batch-state.lock");
34
+
35
+ /**
36
+ * Default bound on contention wait. Terminal lifecycle sections (complete /
37
+ * dismiss / abort) can hold the lock across worktree cleanup, so this is
38
+ * generous; normal state writes hold it for single-digit milliseconds.
39
+ */
40
+ const DEFAULT_TIMEOUT_MS = 30_000;
41
+
42
+ /** Poll interval while another process holds the lock. */
43
+ const POLL_INTERVAL_MS = 25;
44
+
45
+ /**
46
+ * Tolerance when comparing recorded process starttime to a live probe
47
+ * (PID-reuse detection). Reuse ENGINE_STARTTIME_TOLERANCE_MS so `ps lstart`
48
+ * second granularity cannot false-trigger.
49
+ */
50
+ const STARTTIME_TOLERANCE_MS = ENGINE_STARTTIME_TOLERANCE_MS;
51
+
52
+ /**
53
+ * Re-entrancy + ownership tracking keyed by canonical lock path.
54
+ * Value is the ownership token written into the lock file for this hold.
55
+ * Stored on `globalThis` so dynamic `import()` of this module and the static
56
+ * import from `state-io.mjs` always share one Map — under
57
+ * `--experimental-test-coverage`, duplicate module instances otherwise split
58
+ * re-entrancy tracking and `leakedSelf` unlinks the live lock mid-section
59
+ * (release:check coverage flake — concurrent writers 99/100).
60
+ * @type {Map<string, string>}
61
+ */
62
+ const HELD_BY_PROCESS_KEY = Symbol.for("pi-spine.batchStateLock.heldByThisProcess");
63
+ const heldByThisProcess = (() => {
64
+ const g = globalThis;
65
+ if (!(g[HELD_BY_PROCESS_KEY] instanceof Map)) {
66
+ g[HELD_BY_PROCESS_KEY] = new Map();
67
+ }
68
+ return /** @type {Map<string, string>} */ (g[HELD_BY_PROCESS_KEY]);
69
+ })();
70
+
71
+ /**
72
+ * Resolve a stable absolute lock path. Create `.spine/runtime` first, then
73
+ * `realpath` that directory so `/var` vs `/private/var` (macOS) cannot split
74
+ * the re-entrancy Map across two keys for the same inode. Nested
75
+ * `withBatchStateLock` (e.g. saveSpineBatchState under an outer hold) must
76
+ * see the same key or `leakedSelf` will unlink the live lock mid-section.
77
+ *
78
+ * @param {string} projectRoot
79
+ */
80
+ export function batchStateLockPath(projectRoot) {
81
+ const runtimeDir = path.resolve(projectRoot, ".spine", "runtime");
82
+ fs.mkdirSync(runtimeDir, { recursive: true });
83
+ let canonicalRuntime = runtimeDir;
84
+ try {
85
+ canonicalRuntime = fs.realpathSync(runtimeDir);
86
+ } catch {
87
+ canonicalRuntime = runtimeDir;
88
+ }
89
+ return path.join(canonicalRuntime, path.basename(BATCH_STATE_LOCK_REL));
90
+ }
91
+
92
+ /**
93
+ * Synchronous sleep for lock polling. All batch-state writers are sync, so
94
+ * the wait must block the thread without yielding to the event loop.
95
+ *
96
+ * @param {number} ms
97
+ */
98
+ function sleepSync(ms) {
99
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
100
+ }
101
+
102
+ /**
103
+ * @param {string} lockPath
104
+ * @param {string} reason
105
+ */
106
+ function logLockBreak(lockPath, reason) {
107
+ if (process.env.SPINE_LOCK_STEAL_LOG !== "1") return;
108
+ try {
109
+ fs.appendFileSync(
110
+ `${lockPath}.steals`,
111
+ `${Date.now()} pid=${process.pid} ${reason}\n`,
112
+ "utf-8",
113
+ );
114
+ } catch {
115
+ /* ignore diagnostic I/O */
116
+ }
117
+ }
118
+
119
+ /**
120
+ * @returns {string}
121
+ */
122
+ function newOwnershipToken() {
123
+ return crypto.randomBytes(16).toString("hex");
124
+ }
125
+
126
+ /**
127
+ * Single exclusive-create attempt.
128
+ *
129
+ * Publish via temp file + `linkSync` so waiters never observe an empty/partial
130
+ * lock from `wx` create-then-write (that race was parsed as "corrupt" and
131
+ * unlinked mid-hold — concurrent RMW lost updates).
132
+ *
133
+ * @param {string} lockPath
134
+ * @param {string} token
135
+ * @returns {boolean} true when the lock file was created by this call
136
+ */
137
+ function tryCreateLockFile(lockPath, token) {
138
+ /** @type {number|null} */
139
+ let processStartedAt = null;
140
+ try {
141
+ processStartedAt = probeProcessStartTimeMs(process.pid);
142
+ } catch {
143
+ processStartedAt = null;
144
+ }
145
+ // Never fall back to Date.now() for startedAt: wall-clock acquire time is
146
+ // not process starttime. Under load, ESM import can lag spawn by >2s; a
147
+ // later probe of the real starttime would look like PID reuse and steal
148
+ // the live lock (release:check flake — concurrent writers lost updates).
149
+ const payload = JSON.stringify({
150
+ pid: process.pid,
151
+ startedAt: processStartedAt,
152
+ token,
153
+ });
154
+ const tmpPath = `${lockPath}.${process.pid}.${token}.tmp`;
155
+ try {
156
+ fs.writeFileSync(tmpPath, payload, { encoding: "utf-8" });
157
+ try {
158
+ fs.linkSync(tmpPath, lockPath);
159
+ return true;
160
+ } catch (err) {
161
+ if (/** @type {NodeJS.ErrnoException} */ (err).code !== "EEXIST") {
162
+ throw err;
163
+ }
164
+ return false;
165
+ }
166
+ } finally {
167
+ try {
168
+ fs.unlinkSync(tmpPath);
169
+ } catch {
170
+ /* tmp already removed or never created */
171
+ }
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Break the lock when the recorded holder cannot still own it: dead PID,
177
+ * abandoned corrupt payload, same-process leak (no active holder), or a live
178
+ * PID whose OS starttime is newer than the recorded start (PID recycled).
179
+ *
180
+ * Never steals from a live holder on age alone — suite-load CPU starvation
181
+ * can keep a critical section alive for minutes without making the lock stale
182
+ * (release-check flake under full-suite load).
183
+ *
184
+ * @param {string} lockPath
185
+ */
186
+ function breakStaleLock(lockPath) {
187
+ /** @type {{ pid?: number, startedAt?: number, token?: string } | null} */
188
+ let holder = null;
189
+ let corrupt = false;
190
+ try {
191
+ holder = JSON.parse(fs.readFileSync(lockPath, "utf-8"));
192
+ if (!holder || typeof holder !== "object") corrupt = true;
193
+ } catch {
194
+ corrupt = true;
195
+ }
196
+
197
+ if (!fs.existsSync(lockPath)) {
198
+ // Lock vanished between attempts — nothing to break.
199
+ return;
200
+ }
201
+
202
+ if (corrupt) {
203
+ // Do not unlink on the first corrupt read: a concurrent `wx` writer can
204
+ // briefly expose an empty/partial file. Only clear leftovers that have
205
+ // been unreadable for a while (abandoned junk), otherwise waiters poll.
206
+ try {
207
+ const ageMs = Date.now() - fs.statSync(lockPath).mtimeMs;
208
+ if (ageMs < 2_000) {
209
+ return;
210
+ }
211
+ } catch {
212
+ return;
213
+ }
214
+ try {
215
+ logLockBreak(lockPath, "corrupt-stale");
216
+ fs.unlinkSync(lockPath);
217
+ } catch {
218
+ /* raced unlink */
219
+ }
220
+ return;
221
+ }
222
+
223
+ const holderPid = Number(holder?.pid);
224
+ if (!Number.isFinite(holderPid) || holderPid <= 0) {
225
+ try {
226
+ logLockBreak(lockPath, "invalid-pid");
227
+ fs.unlinkSync(lockPath);
228
+ } catch {
229
+ /* raced unlink */
230
+ }
231
+ return;
232
+ }
233
+
234
+ // Same-process "leak" only when we are not in an active hold. Prefer the
235
+ // ownership token over path-string equality so `/var` vs `/private/var`
236
+ // aliases cannot falsely clear a live outer hold during nested acquire.
237
+ if (holderPid === process.pid) {
238
+ const token = String(holder?.token ?? "");
239
+ const stillHeldByToken =
240
+ token.length > 0 && [...heldByThisProcess.values()].includes(token);
241
+ const stillHeldByPath = heldByThisProcess.has(lockPath);
242
+ if (stillHeldByToken || stillHeldByPath) {
243
+ return;
244
+ }
245
+ try {
246
+ logLockBreak(lockPath, `leakedSelf token=${token} mapSize=${heldByThisProcess.size}`);
247
+ fs.unlinkSync(lockPath);
248
+ } catch {
249
+ /* raced unlink */
250
+ }
251
+ return;
252
+ }
253
+
254
+ // Dead foreign PID: break immediately. Do NOT require a null `ps` probe —
255
+ // under suite load the PID is often recycled by an unrelated live process,
256
+ // and refusing to break left waiters stuck until timeout (stale-lock flake).
257
+ if (holderPid !== process.pid && !isProcessAlive(holderPid)) {
258
+ try {
259
+ logLockBreak(lockPath, `deadPid holder=${holderPid}`);
260
+ fs.unlinkSync(lockPath);
261
+ } catch {
262
+ /* raced unlink */
263
+ }
264
+ return;
265
+ }
266
+
267
+ // Live foreign PID: steal only when OS starttime proves the PID was
268
+ // recycled. Require liveStart *newer* than recorded start — wall-clock
269
+ // startedAt (legacy) is newer than real process start and must not steal.
270
+ // startedAt null (probe failed at acquire) → never steal from a live PID.
271
+ if (holderPid === process.pid) return;
272
+ if (isProcessAlive(holderPid)) {
273
+ const expectedStart = Number(holder?.startedAt);
274
+ if (!Number.isFinite(expectedStart) || expectedStart <= 0) return;
275
+ /** @type {number|null} */
276
+ let liveStart = null;
277
+ try {
278
+ liveStart = probeProcessStartTimeMs(holderPid);
279
+ } catch {
280
+ liveStart = null;
281
+ }
282
+ if (liveStart == null || !Number.isFinite(liveStart) || liveStart <= 0) return;
283
+ if (liveStart - expectedStart > STARTTIME_TOLERANCE_MS) {
284
+ try {
285
+ logLockBreak(lockPath, `pidRecycled holder=${holderPid}`);
286
+ fs.unlinkSync(lockPath);
287
+ } catch {
288
+ /* raced unlink */
289
+ }
290
+ }
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Release the lock file only when our ownership token still matches.
296
+ *
297
+ * @param {string} lockPath
298
+ * @param {string} token
299
+ */
300
+ function releaseLockFile(lockPath, token) {
301
+ try {
302
+ const holder = JSON.parse(fs.readFileSync(lockPath, "utf-8"));
303
+ if (String(holder?.token ?? "") === token) {
304
+ fs.unlinkSync(lockPath);
305
+ }
306
+ } catch {
307
+ // Release races (lock already broken/replaced) are safe to ignore.
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Run `fn` while holding the global batch-state lock.
313
+ *
314
+ * @param {string} projectRoot
315
+ * @param {() => unknown} fn
316
+ * @param {{ timeoutMs?: number }} [options]
317
+ * @returns {unknown} `fn`'s return value
318
+ */
319
+ export function withBatchStateLock(projectRoot, fn, options = {}) {
320
+ // batchStateLockPath mkdir+realpath so nested calls share one Map key.
321
+ const lockPath = batchStateLockPath(projectRoot);
322
+
323
+ // Re-entrant pass-through: same-process nesting must not self-deadlock.
324
+ if (heldByThisProcess.has(lockPath)) {
325
+ return fn();
326
+ }
327
+
328
+ const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : DEFAULT_TIMEOUT_MS;
329
+ const deadline = Date.now() + timeoutMs;
330
+ const token = newOwnershipToken();
331
+
332
+ for (;;) {
333
+ if (tryCreateLockFile(lockPath, token)) break;
334
+ breakStaleLock(lockPath);
335
+ if (Date.now() >= deadline) {
336
+ throw new Error(
337
+ `Timed out acquiring batch-state lock (${path.relative(projectRoot, lockPath)}) ` +
338
+ `after ${timeoutMs}ms — another spine process may be holding it`,
339
+ );
340
+ }
341
+ sleepSync(POLL_INTERVAL_MS);
342
+ }
343
+
344
+ heldByThisProcess.set(lockPath, token);
345
+ try {
346
+ return fn();
347
+ } finally {
348
+ // Unlink (token-gated) before clearing the re-entrancy map so a
349
+ // same-process contender cannot treat this file as leakedSelf and
350
+ // steal it while we still intend to release.
351
+ try {
352
+ releaseLockFile(lockPath, token);
353
+ } finally {
354
+ heldByThisProcess.delete(lockPath);
355
+ }
356
+ }
357
+ }
@@ -26,6 +26,12 @@ import {
26
26
  NPM_TEST_DASH_DASH_RE,
27
27
  TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT,
28
28
  } from "../tasks/validate-contract-warn.mjs";
29
+ import { formatRefusedContractMetacharMessage, isRefusedContractMetacharCommand } from "../tasks/packet/parse-prompt.mjs";
30
+
31
+ // Shared pre-spawn refusal envelope for the npm-scope (#187) and metachar (#268) guards.
32
+ function refusedBeforeSpawnResult(summary) {
33
+ return { ok: false, exitCode: 1, output: summary, summary, refusedBeforeSpawn: true };
34
+ }
29
35
 
30
36
  /** Default stdout/stderr capture limit for contract testCommand (issue #86). */
31
37
  export const CONTRACT_TEST_COMMAND_MAX_BUFFER = 10 * 1024 * 1024;
@@ -141,6 +147,8 @@ function formatRefusedNpmTestDashDashMessage(command) {
141
147
  return `Contract testCommand refused before spawn: npm test -- <path> is blocked at runtime (command: ${command}). ${TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT}`;
142
148
  }
143
149
 
150
+ /**
151
+
144
152
  /**
145
153
  * @param {string} worktreePath
146
154
  * @param {string} command
@@ -153,14 +161,10 @@ export function runContractTestCommand(worktreePath, command, options = {}) {
153
161
  }
154
162
 
155
163
  if (isRefusedNpmTestDashDashCommand(trimmed)) {
156
- const summary = formatRefusedNpmTestDashDashMessage(trimmed);
157
- return {
158
- ok: false,
159
- exitCode: 1,
160
- output: summary,
161
- summary,
162
- refusedBeforeSpawn: true,
163
- };
164
+ return refusedBeforeSpawnResult(formatRefusedNpmTestDashDashMessage(trimmed));
165
+ }
166
+ if (isRefusedContractMetacharCommand(trimmed)) {
167
+ return refusedBeforeSpawnResult(formatRefusedContractMetacharMessage(trimmed));
164
168
  }
165
169
 
166
170
  const maxBuffer = options.maxBuffer ?? CONTRACT_TEST_COMMAND_MAX_BUFFER;
@@ -27,7 +27,6 @@ import { recordWaveMergeResult } from "../merge/wave-merge-state.mjs";
27
27
  import { recordMergeBlocked } from "../lifecycle.mjs";
28
28
  import { appendJournalEvent } from "../journal.mjs";
29
29
  import { countCommitsAhead, gitPorcelain } from "../lane-commit.mjs";
30
- import { maybeFinalizeAfterWaveMerge } from "../post-merge-limbo.mjs";
31
30
  import { saveSpineBatchState } from "../state.mjs";
32
31
  import { loadTaskFileScopePaths } from "./queue.mjs";
33
32
  import { laneTaskBranch } from "../worktree.mjs";
@@ -606,9 +605,11 @@ export function mergeLaneToOrch({
606
605
  }
607
606
 
608
607
  /**
609
- * @param {object} params
608
+ * @param {object} params — includes optional `finalizeAfterWaveMerge(hookParams)` hook injected
609
+ * by callers that own the limbo graph (`maybeFinalizeAfterWaveMerge` from post-merge-limbo.mjs,
610
+ * SP-734). Omitted → skip post-wave-merge finalize.
610
611
  */
611
- export async function mergeWaveLanesToOrch({
612
+ export function mergeWaveLanesToOrch({
612
613
  projectRoot,
613
614
  state,
614
615
  batchId,
@@ -616,6 +617,7 @@ export async function mergeWaveLanesToOrch({
616
617
  orchBranch,
617
618
  waveIndex,
618
619
  resumed = false,
620
+ finalizeAfterWaveMerge = null,
619
621
  }) {
620
622
  const waveTaskIds = state.wavePlan?.[waveIndex] ?? [];
621
623
  const needsReplanTask = (state.tasks ?? []).find(
@@ -730,14 +732,17 @@ export async function mergeWaveLanesToOrch({
730
732
  });
731
733
  saveSpineBatchState(projectRoot, state);
732
734
 
733
- const finalizeResult = maybeFinalizeAfterWaveMerge({
734
- projectRoot,
735
- state,
736
- batchId,
737
- orchBranch,
738
- waveIndex,
739
- resumed,
740
- });
735
+ const finalizeResult =
736
+ typeof finalizeAfterWaveMerge === "function"
737
+ ? finalizeAfterWaveMerge({
738
+ projectRoot,
739
+ state,
740
+ batchId,
741
+ orchBranch,
742
+ waveIndex,
743
+ resumed,
744
+ })
745
+ : null;
741
746
 
742
747
  return {
743
748
  ok: true,
@@ -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,