pi-spine 2.35.0 → 2.36.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.
@@ -0,0 +1,325 @@
1
+ /**
2
+ * Wave-level VL slot-pool dispatch (SP-903 / #358).
3
+ *
4
+ * Replaces the engine's in-wave tick barrier: instead of running each
5
+ * planner tick to a `Promise.all` stop, a physical slot pool of
6
+ * `1..lanes.maxParallel` starts the next ready virtual lane (VL) whenever a
7
+ * slot frees and the VL's scopes do not overlap currently running work.
8
+ * Planner `ticks` stay plan-preview-only.
9
+ *
10
+ * Guarantees (locked by the SP-897 helper, re-checked at dispatch time):
11
+ *
12
+ * 1. `lanes.maxParallel` caps in-flight VLs via `createVlSlotPool`.
13
+ * 2. Two scope-overlapping VLs never run concurrently (`selectReadyVl`
14
+ * skips blockers; the freed slot journals a `lane.slot_conflict_wait`).
15
+ * 3. Same-VL tasks stay serial on the lane bound to the VL's slot — a VL
16
+ * holds at most one slot at a time.
17
+ * 4. Wave barrier and merge eligibility stay with the engine caller: this
18
+ * module returns after every dispatched VL settles.
19
+ *
20
+ * VL→slot binding updates `task.laneNumber` to the physical slot before the
21
+ * first run persists state, so merge lane-branch affinity matches the
22
+ * runtime binding (SP-898 hardens persistence/consumer semantics).
23
+ */
24
+
25
+ import crypto from "node:crypto";
26
+ import fs from "node:fs";
27
+ import path from "node:path";
28
+
29
+ import { appendJournalEvent } from "../journal.mjs";
30
+ import { adoptPauseIfRequested } from "../pause.mjs";
31
+ import { applyVlSlotLaneBinding } from "../engine-scope.mjs";
32
+ import { loadTaskFileScopePaths, runTaskOnLane, skipTaskDoneOnDisk } from "../engine-lanes.mjs";
33
+ import {
34
+ buildConflictWaitPayload,
35
+ createVlSlotPool,
36
+ selectReadyVl,
37
+ VL_SLOT_CONFLICT_WAIT_EVENT,
38
+ } from "./vl-slot-dispatch.mjs";
39
+
40
+ /**
41
+ * One dispatch-ready virtual lane for a wave.
42
+ *
43
+ * @typedef {import("./vl-slot-dispatch.mjs").VlDispatchEntry} WaveVlEntry
44
+ */
45
+
46
+ /**
47
+ * Concrete VL entry built by `buildWaveVlQueue` (strict field shapes —
48
+ * `VlDispatchEntry` marks scopes/taskIds optional for helper inputs).
49
+ *
50
+ * @typedef {{ vlId: string, scopes: string[], taskIds: string[] }} BuiltVlEntry
51
+ */
52
+
53
+ /**
54
+ * Build a wave's VL dispatch queue.
55
+ *
56
+ * Groups each wave task onto the virtual lane the planner assigned via
57
+ * `wave.laneAssignments[taskId].virtualLane`, preserving planner packing:
58
+ * same-VL tasks keep their serial queue order, and per-VL `scopes` are the
59
+ * accumulated packet file scopes so dispatch-time overlap checks
60
+ * (`selectReadyVl`) can never run two scope-overlapping VLs concurrently.
61
+ * Tasks the old tick loop skipped — ids absent from `state.tasks` (planner
62
+ * matrix row expansions) or without a discovered packet — stay skipped.
63
+ * Tasks without a planner assignment (hand-built plan) get their own VL in
64
+ * wave order; dispatch-time overlap checks still serialize any overlaps.
65
+ *
66
+ * @param {object} params
67
+ * @param {{ index: number, taskIds?: string[], laneAssignments?: Record<string, { virtualLane?: number } | undefined> }} params.wave
68
+ * @param {Record<string, { fileScope?: string[] } | undefined>} params.planTasks `plan.tasks` keyed by top-level task id.
69
+ * @param {Array<{ taskId: string, folderPath: string }>} params.discovered Discovered task packets.
70
+ * @returns {WaveVlEntry[]} Ready VLs in dispatch-priority order (planner VL order).
71
+ */
72
+ export function buildWaveVlQueue({ wave, planTasks, discovered }) {
73
+ /** @type {Map<string, BuiltVlEntry>} */
74
+ const vlById = new Map();
75
+ /** @type {BuiltVlEntry[]} */
76
+ const vlQueue = [];
77
+
78
+ /**
79
+ * @param {string} taskId
80
+ * @returns {BuiltVlEntry}
81
+ */
82
+ const vlForTask = (taskId) => {
83
+ const assignment = wave.laneAssignments?.[taskId];
84
+ const vlKey = Number.isInteger(assignment?.virtualLane) ? `vl-${assignment?.virtualLane}` : `vl-task:${taskId}`;
85
+ let vl = vlById.get(vlKey);
86
+ if (!vl) {
87
+ vl = { vlId: vlKey, scopes: [], taskIds: [] };
88
+ vlById.set(vlKey, vl);
89
+ vlQueue.push(vl);
90
+ }
91
+ return vl;
92
+ };
93
+
94
+ for (const taskId of wave.taskIds ?? []) {
95
+ const taskFound = discovered.find((/** @type {{ taskId: string }} */ item) => item.taskId === taskId);
96
+ if (!taskFound) continue; // planner matrix row expansions skip like the tick loop did
97
+
98
+ const parentTaskId = taskId.split("[")[0];
99
+ const planScope = planTasks?.[parentTaskId]?.fileScope;
100
+ let scopes;
101
+ if (Array.isArray(planScope)) {
102
+ scopes = planScope;
103
+ } else {
104
+ // Packet load fallback for plans without plan.tasks metadata.
105
+ const scopeResult = loadTaskFileScopePaths(taskFound.folderPath);
106
+ if (!scopeResult.ok) continue;
107
+ scopes = scopeResult.fileScopePaths ?? [];
108
+ }
109
+
110
+ const vl = vlForTask(taskId);
111
+ for (const scope of scopes) {
112
+ if (!vl.scopes.includes(scope)) vl.scopes.push(scope);
113
+ }
114
+ vl.taskIds.push(taskId);
115
+ }
116
+
117
+ return vlQueue;
118
+ }
119
+
120
+ /**
121
+ * Dispatch a wave's VLs onto the physical slot pool and wait until every
122
+ * dispatched VL settles (wave barrier). Pauses are honored at safe points
123
+ * only — when no VL is mid-run. Abort (a task result with `aborted`) stops
124
+ * new dispatches and lets in-flight VLs drain, matching the tick-loop
125
+ * behavior this replaces. A thrown run error surfaces as `status: "error"`
126
+ * after the in-flight VLs drain.
127
+ *
128
+ * @param {object} params
129
+ * @param {{ index: number, taskIds?: string[], laneAssignments?: Record<string, { virtualLane?: number } | undefined> }} params.wave
130
+ * @param {Record<string, { fileScope?: string[] } | undefined>} params.planTasks
131
+ * @param {Array<{ taskId: string, folderPath: string }>} params.discovered
132
+ * @param {Record<string, any>} params.state Batch state (tasks + lanes mutated in place).
133
+ * @param {Record<string, any>} params.config Loaded spine config (`lanes.maxParallel`).
134
+ * @param {string} params.projectRoot
135
+ * @param {string} params.batchId
136
+ * @param {string} params.baseBranch
137
+ * @returns {Promise<{ status: "completed", aborted: boolean } | { status: "paused" } | { status: "error", error: Error }>}
138
+ */
139
+ export async function runWaveVlDispatch({
140
+ wave,
141
+ planTasks,
142
+ discovered,
143
+ state,
144
+ config,
145
+ projectRoot,
146
+ batchId,
147
+ baseBranch,
148
+ }) {
149
+ const vlQueue = buildWaveVlQueue({ wave, planTasks, discovered });
150
+ const slotPool = createVlSlotPool(config?.lanes?.maxParallel ?? 1);
151
+ /** @type {WaveVlEntry[]} */
152
+ const readyVls = [...vlQueue];
153
+ /** @type {WaveVlEntry[]} */
154
+ const runningVls = [];
155
+ /** @type {Set<Promise<{ ok: boolean, aborted?: boolean }>>} */
156
+ const inFlightVls = new Set();
157
+ let batchAborted = false;
158
+ /** @type {Error | null} */
159
+ let waveError = null;
160
+
161
+ /**
162
+ * Free a VL's slot, drop it from the running set, and surface a worker
163
+ * error (first error wins) without rejecting the tracked completion.
164
+ *
165
+ * @param {WaveVlEntry} vl
166
+ * @param {number} slot
167
+ * @param {Promise<{ ok: boolean, aborted?: boolean }>} completion
168
+ * @param {{ ok: boolean, aborted?: boolean }} outcome
169
+ * @param {Error} [error]
170
+ * @returns {{ ok: boolean, aborted?: boolean }}
171
+ */
172
+ const settleVlSlot = (vl, slot, completion, outcome, error) => {
173
+ slotPool.release(slot);
174
+ const runningIndex = runningVls.indexOf(vl);
175
+ if (runningIndex >= 0) runningVls.splice(runningIndex, 1);
176
+ inFlightVls.delete(completion);
177
+ if (error && !waveError) waveError = error;
178
+ return outcome;
179
+ };
180
+
181
+ /**
182
+ * Run one VL's serial task queue on the physical lane bound to `slot`.
183
+ * Stops the queue early on abort; a thrown error rejects and is
184
+ * converted to a batch error by the settle handler.
185
+ *
186
+ * @param {WaveVlEntry} vl
187
+ * @param {number} slot
188
+ * @returns {Promise<{ ok: boolean, aborted?: boolean }>}
189
+ */
190
+ const runVlOnSlot = async (vl, slot) => {
191
+ const lane = state.lanes.find((/** @type {{ laneNumber: number }} */ entry) => entry.laneNumber === slot);
192
+ if (!lane) throw new Error(`no lane provisioned for slot ${slot}`);
193
+ const laneMeta = /** @type {{ laneId?: string; correlationId?: string }} */ (lane);
194
+ // VL→slot bind (SP-898 / #358): persist the runtime binding before any
195
+ // run persists state — task.laneNumber, lane.taskIds, the journal, and
196
+ // saved batch state move together, so merge / resume / dashboard
197
+ // consumers see the physical slot instead of the provisional plan-time
198
+ // lane. A running task is never rebound (live binding preserved).
199
+ applyVlSlotLaneBinding({
200
+ state,
201
+ taskIds: vl.taskIds ?? [],
202
+ slot,
203
+ projectRoot,
204
+ batchId,
205
+ waveIndex: wave.index,
206
+ correlationId: laneMeta.correlationId ?? null,
207
+ });
208
+ /** @type {Array<{ taskId: string, run: () => Promise<{ ok: boolean, aborted?: boolean }> | { ok: boolean, aborted?: boolean, skipped?: boolean } }>} */
209
+ const runs = [];
210
+
211
+ for (const taskId of vl.taskIds ?? []) {
212
+ const task = state.tasks.find((/** @type {{ taskId: string }} */ entry) => entry.taskId === taskId);
213
+ const entry = discovered.find((/** @type {{ taskId: string }} */ item) => item.taskId === taskId);
214
+ if (!task || !entry) continue;
215
+
216
+ const taskFolderRel = path.relative(projectRoot, entry.folderPath);
217
+ const doneOnDisk = fs.existsSync(path.join(entry.folderPath, ".DONE"));
218
+ const laneCorrelationId = lane.correlationId ?? crypto.randomUUID();
219
+
220
+ runs.push({
221
+ taskId,
222
+ run: doneOnDisk
223
+ ? () =>
224
+ skipTaskDoneOnDisk({
225
+ projectRoot,
226
+ state,
227
+ batchId,
228
+ task,
229
+ lane,
230
+ taskFolderPath: entry.folderPath,
231
+ laneCorrelationId,
232
+ })
233
+ : () =>
234
+ runTaskOnLane({
235
+ projectRoot,
236
+ state,
237
+ batchId,
238
+ baseBranch,
239
+ config,
240
+ task,
241
+ lane,
242
+ taskFolderRel,
243
+ laneCorrelationId,
244
+ }).then((result) => {
245
+ if ("aborted" in result && result.aborted) batchAborted = true;
246
+ return result;
247
+ }),
248
+ });
249
+ }
250
+
251
+ // Multi-task VL serialization was journaled at bind time —
252
+ // `applyVlSlotLaneBinding` emits `lane.tasks_serialized` for every
253
+ // multi-task VL, rebind or not. No duplicate emission here.
254
+
255
+ for (const { run } of runs) {
256
+ if (batchAborted) return { ok: false, aborted: true };
257
+ const result = await run();
258
+ if (result && result.aborted) {
259
+ return { ok: false, aborted: true };
260
+ }
261
+ }
262
+ return { ok: true };
263
+ };
264
+
265
+ while (readyVls.length > 0 || inFlightVls.size > 0) {
266
+ // Pauses are honored at safe points only: no VL mid-run.
267
+ if (inFlightVls.size === 0 && !batchAborted && !waveError) {
268
+ const pauseAtDispatch = await adoptPauseIfRequested({ projectRoot, state, batchId });
269
+ if (pauseAtDispatch.stop) {
270
+ return { status: "paused" };
271
+ }
272
+ }
273
+
274
+ if (!batchAborted && !waveError && readyVls.length > 0) {
275
+ const slot = slotPool.tryAcquire();
276
+ if (slot !== null) {
277
+ const selection = selectReadyVl(readyVls, runningVls);
278
+ if (selection.status === "dispatch" && selection.vl) {
279
+ const vl = selection.vl;
280
+ const readyIndex = readyVls.indexOf(vl);
281
+ if (readyIndex >= 0) readyVls.splice(readyIndex, 1);
282
+ runningVls.push(vl);
283
+ /** @type {Promise<{ ok: boolean, aborted?: boolean }>} */
284
+ const completion = runVlOnSlot(vl, slot).then(
285
+ (outcome) => settleVlSlot(vl, slot, completion, outcome),
286
+ (error) =>
287
+ settleVlSlot(vl, slot, completion, { ok: false }, error instanceof Error ? error : new Error(String(error))),
288
+ );
289
+ inFlightVls.add(completion);
290
+ continue;
291
+ }
292
+ // Slot free but no dispatchable VL: scope conflicts or same-VL
293
+ // serial queues are journalable (SP-897 payload).
294
+ if (selection.status === "conflict-wait") {
295
+ appendJournalEvent(
296
+ projectRoot,
297
+ batchId,
298
+ VL_SLOT_CONFLICT_WAIT_EVENT,
299
+ buildConflictWaitPayload({
300
+ slot,
301
+ blocked: selection.blocked,
302
+ waitingOn: selection.waitingOn,
303
+ runningVlIds: runningVls.map((running) => running.vlId ?? null),
304
+ readyCount: readyVls.length,
305
+ }),
306
+ );
307
+ }
308
+ slotPool.release(slot);
309
+ }
310
+ }
311
+
312
+ if (inFlightVls.size > 0) {
313
+ // Slot pool full (or nothing dispatchable): wait for a running VL
314
+ // to free its slot, then re-select.
315
+ await Promise.race([...inFlightVls]);
316
+ } else if (readyVls.length === 0 || batchAborted || waveError) {
317
+ break;
318
+ }
319
+ }
320
+
321
+ if (waveError) {
322
+ return { status: "error", error: waveError };
323
+ }
324
+ return { status: "completed", aborted: batchAborted };
325
+ }
@@ -163,6 +163,14 @@ export function maxLaneNumberForPlan(plan) {
163
163
  }
164
164
 
165
165
  /**
166
+ * Plan-time lane assignments from the planner's tick layout.
167
+ *
168
+ * Advisory under slot-pool dispatch (#358): planner `ticks` stay
169
+ * preview-only — the physical slot a VL's tasks actually run on is bound at
170
+ * dispatch time (`applyVlSlotLaneBinding`), which may differ from this
171
+ * sticky plan-time layout. Callers must treat these values as provisional
172
+ * until the first VL→slot bind persists the runtime binding.
173
+ *
166
174
  * @param {object} plan
167
175
  * @returns {Map<string, { laneNumber: number, waveIndex: number, tickIndex: number }>}
168
176
  */
@@ -186,6 +194,114 @@ export function buildTaskLaneAssignments(plan) {
186
194
  return map;
187
195
  }
188
196
 
197
+ /**
198
+ * Result of `applyVlSlotLaneBinding`.
199
+ *
200
+ * @typedef {Object} VlSlotBindingResult
201
+ * @property {string[]} changed Task ids whose laneNumber moved to the slot.
202
+ * @property {string[]} boundTaskIds VL task ids present in batch state.
203
+ */
204
+
205
+ /**
206
+ * Bind a VL's task queue to the physical slot it was dispatched onto
207
+ * (SP-898 / #358): `task.laneNumber`, the slot lane's `taskIds`, the journal,
208
+ * and the persisted batch state all move together before the first run
209
+ * persists state, so merge / resume / dashboard consumers key off the runtime
210
+ * binding instead of the provisional plan-time layout.
211
+ *
212
+ * Guarantees:
213
+ *
214
+ * 1. A task already `running` is never rebound — a live binding is not
215
+ * overwritten (same-VL serial queue semantics).
216
+ * 2. Unchanged bindings are left untouched; only actual moves journal/save.
217
+ * 3. The slot lane's `taskIds` reflect the VL's serial queue (resume replays
218
+ * `lane.taskIds`), and the task is dropped from other lanes' queues.
219
+ * 4. The binding is journaled as `lane.tasks_serialized` — an event the
220
+ * structural journal rebuild already understands — so rebuild/reconstruct
221
+ * paths see the runtime binding even before any `task.started` exists.
222
+ * Multi-task VLs always journal (serialization is meaningful regardless
223
+ * of rebind); single-task VLs journal only when they actually moved.
224
+ *
225
+ * @param {object} params
226
+ * @param {Record<string, any>} params.state Batch state (tasks + lanes mutated in place).
227
+ * @param {string[]} params.taskIds VL serial task queue.
228
+ * @param {number} params.slot Physical slot the VL was dispatched onto.
229
+ * @param {string} [params.projectRoot] Required for journal/state persistence.
230
+ * @param {string} [params.batchId] Required for journal/state persistence.
231
+ * @param {number|null} [params.waveIndex] Wave the VL was dispatched in.
232
+ * @param {string|null} [params.correlationId] Lane correlation id for the journal event.
233
+ * @returns {VlSlotBindingResult}
234
+ */
235
+ export function applyVlSlotLaneBinding({
236
+ state,
237
+ taskIds,
238
+ slot,
239
+ projectRoot,
240
+ batchId,
241
+ waveIndex = null,
242
+ correlationId = null,
243
+ }) {
244
+ const laneNumber = Number(slot);
245
+ if (!Number.isInteger(laneNumber) || laneNumber < 1) {
246
+ return { changed: [], boundTaskIds: [] };
247
+ }
248
+ const lane = (state.lanes ?? []).find(
249
+ (/** @type {{ laneNumber: number }} */ entry) => entry?.laneNumber === laneNumber,
250
+ );
251
+ /** @type {string[]} */
252
+ const boundTaskIds = [];
253
+ /** @type {string[]} */
254
+ const changed = [];
255
+
256
+ for (const taskId of Array.isArray(taskIds) ? taskIds : []) {
257
+ const task = (state.tasks ?? []).find(
258
+ (/** @type {{ taskId: string }} */ entry) => entry?.taskId === taskId,
259
+ );
260
+ if (!task) continue;
261
+ boundTaskIds.push(task.taskId);
262
+ // A running task is mid-flight on its current slot — never overwrite a
263
+ // live binding; plan-time values stay provisional until first bind.
264
+ if (task.status === "running") continue;
265
+ if (Number(task.laneNumber) === laneNumber) continue;
266
+ task.laneNumber = laneNumber;
267
+ changed.push(task.taskId);
268
+ }
269
+
270
+ if (lane && changed.length > 0) {
271
+ if (!Array.isArray(lane.taskIds)) lane.taskIds = [];
272
+ for (const taskId of changed) {
273
+ for (const other of state.lanes ?? []) {
274
+ if (other === lane || other?.laneNumber === laneNumber) continue;
275
+ const index = Array.isArray(other.taskIds) ? other.taskIds.indexOf(taskId) : -1;
276
+ if (index >= 0) other.taskIds.splice(index, 1);
277
+ }
278
+ if (!lane.taskIds.includes(taskId)) lane.taskIds.push(taskId);
279
+ }
280
+ }
281
+
282
+ const canPersist = Boolean(projectRoot && batchId);
283
+ if (canPersist && (changed.length > 0 || boundTaskIds.length > 1)) {
284
+ // Explicit `payload` object (not spread options): appendJournalEvent
285
+ // strips `laneNumber` as a META_KEY from spread options, but the
286
+ // structural rebuild reads `payload.laneNumber` on this event — the
287
+ // explicit form is what makes the bind reconstructable from journal.
288
+ appendJournalEvent(projectRoot, batchId, "lane.tasks_serialized", {
289
+ laneId: lane?.laneId ?? `lane-${laneNumber}`,
290
+ correlationId: correlationId ?? null,
291
+ payload: {
292
+ laneNumber,
293
+ waveIndex,
294
+ taskIds: boundTaskIds,
295
+ },
296
+ });
297
+ }
298
+ if (canPersist && changed.length > 0) {
299
+ saveSpineBatchState(projectRoot, state);
300
+ }
301
+
302
+ return { changed, boundTaskIds };
303
+ }
304
+
189
305
  /**
190
306
  * @param {object[]} failedTasks
191
307
  * @param {object[]} pendingTasks
@@ -1,8 +1,6 @@
1
1
  // @ts-check
2
2
  /** pi-spine batch engine (Phase 2 single-lane, Phase 3 multi-lane + §17.4 merge policy). */
3
3
 
4
- import fs from "node:fs";
5
- import path from "node:path";
6
4
  import crypto from "node:crypto";
7
5
  import { discoverTasks } from "../tasks/packet/discover.mjs";
8
6
  import { buildPlan } from "../planner/index.mjs";
@@ -45,11 +43,10 @@ import {
45
43
  buildTasksAndLanesFromPlan,
46
44
  mergeWaveLanesToOrch,
47
45
  removeAllMatrixSubLaneWorktrees,
48
- runTaskOnLane,
49
- skipTaskDoneOnDisk,
50
46
  transitionPhase,
51
47
  } from "./engine-lanes.mjs";
52
48
  import { buildEnginePausedResult, rejectNestedBatchStart } from "./batch-guards.mjs";
49
+ import { runWaveVlDispatch } from "./engine-lanes/vl-wave-dispatch.mjs";
53
50
 
54
51
  export {
55
52
  assessWaveMergeEligibility,
@@ -67,6 +64,7 @@ export { detectNestedWorkerContext } from "./batch-guards.mjs";
67
64
 
68
65
  /** @typedef {Omit<ReturnType<typeof createInitialBatchState>, "endedAt" | "lastError"> & { endedAt: number | null; lastError: string | null }} SpineBatchState */
69
66
 
67
+
70
68
  /**
71
69
  * @param {{ projectRoot: string, scope?: string, dryRun?: boolean, skipPreflight?: boolean, forceSuperseded?: boolean, waveFilter?: number|null }} options
72
70
  */
@@ -271,98 +269,33 @@ export async function startBatch({
271
269
  state.currentWaveIndex = wave.index;
272
270
  await saveEngineBatchState(projectRoot, state);
273
271
 
274
- for (const tick of wave.ticks ?? []) {
275
- const pauseAtTick = await adoptPauseIfRequested({ projectRoot, state, batchId });
276
- if (pauseAtTick.stop) {
277
- return buildEnginePausedResult(batchId);
278
- }
279
- /** @type {Map<number, { lane: object, runs: Array<{ taskId: string, run: () => Promise<{ ok: boolean, aborted?: boolean }> | { ok: boolean, aborted?: boolean, skipped?: boolean } }> }>} */
280
- const runsByLane = new Map();
281
-
282
- for (let laneInTick = 0; laneInTick < (tick.lanes?.length ?? 0); laneInTick++) {
283
- const tickTaskIds = tick.lanes[laneInTick] ?? [];
284
- if (tickTaskIds.length === 0) continue;
285
-
286
- const laneNumber = laneInTick + 1;
287
- const lane = state.lanes.find((/** @type {{ laneNumber: number }} */ entry) => entry.laneNumber === laneNumber);
288
- if (!lane) continue;
289
-
290
- if (!runsByLane.has(laneNumber)) {
291
- runsByLane.set(laneNumber, { lane, runs: [] });
292
- }
293
- const laneQueue = runsByLane.get(laneNumber);
294
-
295
- for (const taskId of tickTaskIds) {
296
- const task = state.tasks.find((/** @type {{ taskId: string }} */ entry) => entry.taskId === taskId);
297
- const entry = discovered.find((/** @type {{ taskId: string }} */ item) => item.taskId === taskId);
298
- if (!task || !entry) continue;
299
-
300
- const taskFolderRel = path.relative(projectRoot, entry.folderPath);
301
- const doneOnDisk = fs.existsSync(path.join(entry.folderPath, ".DONE"));
302
- const laneCorrelationId = lane.correlationId ?? crypto.randomUUID();
303
-
304
- const run = doneOnDisk
305
- ? () =>
306
- skipTaskDoneOnDisk({
307
- projectRoot,
308
- state,
309
- batchId,
310
- task,
311
- lane,
312
- taskFolderPath: entry.folderPath,
313
- laneCorrelationId,
314
- })
315
- : () =>
316
- runTaskOnLane({
317
- projectRoot,
318
- state,
319
- batchId,
320
- baseBranch,
321
- config,
322
- task,
323
- lane,
324
- taskFolderRel,
325
- laneCorrelationId,
326
- }).then((result) => {
327
- if ("aborted" in result && result.aborted) batchAborted = true;
328
- return result;
329
- });
330
-
331
- if (laneQueue) {
332
- laneQueue.runs.push({ taskId, run });
333
- }
334
- }
335
- }
336
-
337
- const laneExecutions = [...runsByLane.entries()].map(async ([laneNumber, { lane, runs }]) => {
338
- const laneMeta = /** @type {{ laneId?: string; correlationId?: string }} */ (lane);
339
- if (runs.length > 1) {
340
- appendJournalEvent(projectRoot, batchId, "lane.tasks_serialized", {
341
- laneNumber,
342
- laneId: laneMeta.laneId,
343
- waveIndex: wave.index,
344
- tickIndex: tick.index,
345
- taskIds: runs.map((entry) => entry.taskId),
346
- correlationId: laneMeta.correlationId ?? null,
347
- });
348
- }
349
-
350
- for (const { run } of runs) {
351
- const result = await run();
352
- if (result.aborted) {
353
- return result;
354
- }
355
- }
356
- return { ok: true };
357
- });
358
-
359
- await Promise.all(laneExecutions);
360
- if (batchAborted) break;
272
+ // SP-903 (#358): slot-pool dispatch replaces the in-wave tick
273
+ // barrier — VL selection, overlap serialization, slot pooling,
274
+ // conflict-wait journaling, and the VL→slot laneNumber bind live
275
+ // in engine-lanes/vl-wave-dispatch.mjs. Planner `ticks` stay
276
+ // plan-preview-only; wave barrier and merge eligibility below
277
+ // are unchanged.
278
+ const dispatchResult = await runWaveVlDispatch({
279
+ wave,
280
+ planTasks: effectivePlan.tasks ?? {},
281
+ discovered,
282
+ state,
283
+ config,
284
+ projectRoot,
285
+ batchId,
286
+ baseBranch,
287
+ });
288
+ if (dispatchResult.status === "paused") {
289
+ return buildEnginePausedResult(batchId);
290
+ }
291
+ if (dispatchResult.status === "error") {
292
+ throw dispatchResult.error;
293
+ }
294
+ if (dispatchResult.aborted) batchAborted = true;
361
295
 
362
- const pauseAfterTick = await adoptPauseIfRequested({ projectRoot, state, batchId });
363
- if (pauseAfterTick.stop) {
364
- return buildEnginePausedResult(batchId);
365
- }
296
+ const pauseAfterWaveWork = await adoptPauseIfRequested({ projectRoot, state, batchId });
297
+ if (pauseAfterWaveWork.stop) {
298
+ return buildEnginePausedResult(batchId);
366
299
  }
367
300
 
368
301
  if (batchAborted) {