pi-spine 2.35.0 → 2.36.1

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.
@@ -1,16 +1,48 @@
1
1
  // @ts-nocheck
2
2
  /**
3
- * Per-lane queue wiring for multi-task resume waves (extracted from resume-multi-lanes.mjs).
3
+ * VL slot-pool wiring for multi-task resume waves (SP-899 / #358 partial).
4
+ *
5
+ * Replaces the pre-#358 sticky per-lane resume queues (`Promise.all` across
6
+ * `task.laneNumber` lane queues — the same barrier pattern the engine tick
7
+ * loop had): on resume after pause/orphan, remaining ready virtual lanes
8
+ * (VLs) dispatch onto free physical slots `1..lanes.maxParallel` using the
9
+ * SP-897 helper API (`createVlSlotPool` / `selectReadyVl`) — the same rules
10
+ * as the SP-903 start path (`engine-lanes/vl-wave-dispatch.mjs`):
11
+ *
12
+ * 1. `lanes.maxParallel` caps in-flight VLs via the physical slot pool.
13
+ * 2. Two scope-overlapping VLs never run concurrently (`selectReadyVl`
14
+ * skips blockers; a freed slot journals `lane.slot_conflict_wait`).
15
+ * 3. Same-VL serial ordering: a VL holds at most one slot; its remaining
16
+ * tasks drain serially behind the running task (mid-run steal across a
17
+ * VL queue stays out of scope, #358).
18
+ * 4. No tick barriers: a VL that finishes early frees its slot immediately
19
+ * for the next dispatchable VL (uneven completion).
20
+ *
21
+ * Resume has no persisted `wave.laneAssignments` (planner-only field), so
22
+ * ready VLs are rebuilt from packet file scopes with the planner's own
23
+ * greedy packing predicate (`fileScopesOverlap` via `scopesOverlap`): tasks
24
+ * whose scopes overlap share one VL/serial queue; disjoint tasks get
25
+ * separate VLs and may run in parallel on different slots. Tasks whose
26
+ * packet scope cannot be re-read dispatch with empty scopes (never overlap
27
+ * — resume must not silently drop tasks the way the start path skips them).
28
+ *
29
+ * VL→slot binding (merge affinity): merge keys off
30
+ * `task.laneNumber === lane.laneNumber`, so a re-run task rebinds to its
31
+ * dispatch slot before the run persists state (SP-903 pattern). Already
32
+ * complete tasks keep their sticky lane — their committed evidence lives on
33
+ * that lane's branch.
4
34
  */
5
35
 
6
36
  import path from "node:path";
7
37
  import crypto from "node:crypto";
8
38
  import {
39
+ loadResumeFileScopePaths,
9
40
  resolveTaskFolderInWorktree,
10
41
  taskAlreadyComplete,
11
42
  taskTerminalSuccessInBatch,
12
43
  } from "./resume-common.mjs";
13
44
  import { appendJournalEvent } from "./journal.mjs";
45
+ import { rebindTasksToLane } from "./engine-scope.mjs";
14
46
  import { laneTaskBranch } from "./worktree.mjs";
15
47
  import { isTaskResumable } from "./resume-multi-validate.mjs";
16
48
  import {
@@ -18,10 +50,24 @@ import {
18
50
  runResumedTaskOnLane,
19
51
  } from "./resume-multi-lanes.mjs";
20
52
  import { runWithQuotaFallback } from "./engine-lanes/quota-fallback-run.mjs";
53
+ import {
54
+ buildConflictWaitPayload,
55
+ createVlSlotPool,
56
+ selectReadyVl,
57
+ scopesOverlap,
58
+ VL_SLOT_CONFLICT_WAIT_EVENT,
59
+ } from "./engine-lanes/vl-slot-dispatch.mjs";
21
60
  import { resolveWorkerBackend } from "../config/worker-backend.mjs";
22
61
 
23
62
  /**
24
- * Build lane queues and run all tasks in a resume wave.
63
+ * Build resume VL queue entries for one wave and run them through the
64
+ * physical slot pool.
65
+ *
66
+ * Classification (per wave task, same filters as the sticky queue):
67
+ * terminal-success tasks skip; already-complete tasks queue a disk-marking
68
+ * run on their sticky lane; non-resumable tasks skip; remaining resumable
69
+ * tasks greedy-pack into VLs by file-scope overlap and dispatch onto free
70
+ * slots.
25
71
  *
26
72
  * @param {object} params
27
73
  * @returns {Promise<{ ok: true, waveResults: object[], batchAborted: boolean } | { ok: false, result: object }>}
@@ -36,17 +82,63 @@ export async function executeResumeWave({
36
82
  waveTaskIds,
37
83
  events,
38
84
  }) {
39
- /** @type {Map<number, { lane: object, runs: Array<{ taskId: string, run: () => Promise<object> }> }>} */
40
- const runsByLane = new Map();
85
+ const lanes = state.lanes ?? [];
86
+ // Slot pool positions map onto provisioned lanes in laneNumber order, so
87
+ // slot N always resolves to a real lane even when legacy state provisioned
88
+ // fewer lanes than the current config maxParallel.
89
+ const provisionedLanes = [...lanes].sort(
90
+ (a, b) => Number(a?.laneNumber ?? 0) - Number(b?.laneNumber ?? 0),
91
+ );
41
92
  let batchAborted = false;
42
93
 
94
+ /**
95
+ * Ready VL entries in dispatch-priority (wave) order.
96
+ *
97
+ * @type {Array<{ vlId: string, scopes: string[], tasks: Array<{ taskId: string, bindsSlot: boolean, run: (slotLane: object, slotCorrelationId: string) => Promise<object> }> }>}
98
+ */
99
+ const vlQueue = [];
100
+
101
+ /**
102
+ * Resumable-task run: single-hop quota fallback retry (SP-809) wraps the
103
+ * resumed lane run; an aborted result flags the batch (abort short-
104
+ * circuit) exactly like the sticky queue did.
105
+ *
106
+ * @param {object} task
107
+ * @param {string} taskFolderRel
108
+ * @returns {(slotLane: object, slotCorrelationId: string) => Promise<object>}
109
+ */
110
+ const makeResumableRun = (task, taskFolderRel) => async (slotLane, slotCorrelationId) =>
111
+ runWithQuotaFallback(
112
+ () =>
113
+ runResumedTaskOnLane({
114
+ projectRoot,
115
+ state,
116
+ batchId,
117
+ config,
118
+ task,
119
+ lane: slotLane,
120
+ taskFolderRel,
121
+ laneCorrelationId: slotCorrelationId,
122
+ }),
123
+ {
124
+ projectRoot,
125
+ batchId,
126
+ state,
127
+ taskId: task.taskId,
128
+ config,
129
+ workerBackend: resolveWorkerBackend(config),
130
+ },
131
+ ).then((result) => {
132
+ if (result?.aborted) batchAborted = true;
133
+ return result;
134
+ });
135
+
43
136
  for (const taskId of waveTaskIds) {
44
137
  const task = (state.tasks ?? []).find((entry) => entry?.taskId === taskId);
45
138
  if (!task) continue;
46
139
 
47
- const laneNumber = task.laneNumber;
48
- const lane = (state.lanes ?? []).find((entry) => entry.laneNumber === laneNumber);
49
- if (!lane) {
140
+ const stickyLane = lanes.find((entry) => entry.laneNumber === task.laneNumber);
141
+ if (!stickyLane) {
50
142
  return {
51
143
  ok: false,
52
144
  result: {
@@ -55,7 +147,7 @@ export async function executeResumeWave({
55
147
  batchId,
56
148
  taskId,
57
149
  error: "lane_not_found",
58
- output: `No lane assigned for task ${taskId} (lane ${laneNumber}).\n`,
150
+ output: `No lane assigned for task ${taskId} (lane ${task.laneNumber}).\n`,
59
151
  },
60
152
  };
61
153
  }
@@ -68,17 +160,12 @@ export async function executeResumeWave({
68
160
  const taskFolderInWorktree = resolveTaskFolderInWorktree({
69
161
  projectRoot,
70
162
  task,
71
- lane,
163
+ lane: stickyLane,
72
164
  tasksRootRel,
73
165
  batchId,
74
166
  });
75
- const laneCorrelationId = lane.correlationId ?? crypto.randomUUID();
76
- lane.correlationId = laneCorrelationId;
77
-
78
- if (!runsByLane.has(laneNumber)) {
79
- runsByLane.set(laneNumber, { lane, runs: [] });
80
- }
81
- const laneQueue = runsByLane.get(laneNumber);
167
+ const laneCorrelationId = stickyLane.correlationId ?? crypto.randomUUID();
168
+ stickyLane.correlationId = laneCorrelationId;
82
169
 
83
170
  if (
84
171
  taskTerminalSuccessInBatch({
@@ -91,20 +178,30 @@ export async function executeResumeWave({
91
178
  }
92
179
 
93
180
  if (taskAlreadyComplete({ taskFolder: taskFolderInWorktree, events, task })) {
94
- laneQueue.runs.push({
95
- taskId,
96
- run: () =>
97
- markTaskCompleteFromDisk({
98
- projectRoot,
99
- state,
100
- batchId,
101
- config,
102
- task,
103
- lane,
104
- taskBranch: lane.branch ?? laneTaskBranch(batchId, laneNumber),
105
- taskFolderInWorktree,
106
- laneCorrelationId,
107
- }),
181
+ // Disk-marking run on the sticky lane: evidence and committed work
182
+ // live on that lane's branch, so no VL→slot rebind. Empty scopes —
183
+ // a complete-marking never conflicts with running work.
184
+ vlQueue.push({
185
+ vlId: `vl-resume-done:${taskId}`,
186
+ scopes: [],
187
+ tasks: [
188
+ {
189
+ taskId,
190
+ bindsSlot: false,
191
+ run: async () =>
192
+ markTaskCompleteFromDisk({
193
+ projectRoot,
194
+ state,
195
+ batchId,
196
+ config,
197
+ task,
198
+ lane: stickyLane,
199
+ taskBranch: stickyLane.branch ?? laneTaskBranch(batchId, stickyLane.laneNumber),
200
+ taskFolderInWorktree,
201
+ laneCorrelationId,
202
+ }),
203
+ },
204
+ ],
108
205
  });
109
206
  continue;
110
207
  }
@@ -113,62 +210,169 @@ export async function executeResumeWave({
113
210
  continue;
114
211
  }
115
212
 
116
- laneQueue.runs.push({
213
+ // Resumable task: greedy-pack into the first VL whose scopes overlap
214
+ // (planner packing predicate), else open a new VL. Tasks whose packet
215
+ // scope cannot be re-read dispatch with empty scopes rather than
216
+ // being dropped from the wave.
217
+ const scopeResult = loadResumeFileScopePaths(path.join(projectRoot, taskFolderRel));
218
+ const scopes = scopeResult.ok ? scopeResult.fileScopePaths ?? [] : [];
219
+ const targetVl = vlQueue.find((vl) => scopesOverlap(scopes, vl.scopes));
220
+ const queuedTask = {
117
221
  taskId,
118
- // SP-809 (#329): the resumed path gets the same single-hop quota
119
- // fallback retry as the normal lane path.
120
- run: () =>
121
- runWithQuotaFallback(
122
- () =>
123
- runResumedTaskOnLane({
124
- projectRoot,
125
- state,
126
- batchId,
127
- config,
128
- task,
129
- lane,
130
- taskFolderRel,
131
- laneCorrelationId,
132
- }),
133
- {
134
- projectRoot,
135
- batchId,
136
- state,
137
- taskId,
138
- config,
139
- workerBackend: resolveWorkerBackend(config),
140
- },
141
- ).then((result) => {
142
- if (result.aborted) batchAborted = true;
143
- return result;
144
- }),
145
- });
222
+ bindsSlot: true,
223
+ run: makeResumableRun(task, taskFolderRel),
224
+ };
225
+ if (targetVl) {
226
+ targetVl.tasks.push(queuedTask);
227
+ for (const scope of scopes) {
228
+ if (!targetVl.scopes.includes(scope)) targetVl.scopes.push(scope);
229
+ }
230
+ } else {
231
+ vlQueue.push({
232
+ vlId: `vl-resume:${taskId}`,
233
+ scopes: [...scopes],
234
+ tasks: [queuedTask],
235
+ });
236
+ }
146
237
  }
147
238
 
148
- const laneExecutions = [...runsByLane.entries()].map(async ([laneNumber, { lane, runs }]) => {
149
- if (runs.length > 1) {
239
+ const slotPool = createVlSlotPool(
240
+ // `lanes.maxParallel` caps in-flight VLs; the pool never exceeds the
241
+ // provisioned lanes so a slot always maps to a lane worktree (resumed
242
+ // batches may predate a maxParallel increase — fail closed to the
243
+ // provisioned lanes instead of dispatching into a missing worktree).
244
+ Math.min(config?.lanes?.maxParallel ?? 1, Math.max(1, provisionedLanes.length)),
245
+ );
246
+ /** @type {typeof vlQueue} */
247
+ const readyVls = [...vlQueue];
248
+ /** @type {Array<{ vlId: string, scopes: string[], tasks: unknown[] }>} */
249
+ const runningVls = [];
250
+ /** @type {Set<Promise<object[]>>} */
251
+ const inFlightVls = new Set();
252
+ /** @type {object[]} */
253
+ const waveResults = [];
254
+ /** @type {Error | null} */
255
+ let runError = null;
256
+
257
+ /**
258
+ * Free a VL's slot, drop it from the running set, collect its results,
259
+ * and surface a thrown run error (first error wins) without rejecting
260
+ * the tracked completion.
261
+ */
262
+ const settleVlSlot = (vl, slot, completion, results, error) => {
263
+ slotPool.release(slot);
264
+ const runningIndex = runningVls.indexOf(vl);
265
+ if (runningIndex >= 0) runningVls.splice(runningIndex, 1);
266
+ inFlightVls.delete(completion);
267
+ if (error && !runError) runError = error;
268
+ if (Array.isArray(results)) waveResults.push(...results);
269
+ return results;
270
+ };
271
+
272
+ /**
273
+ * Run one VL's serial task queue on the physical lane bound to `slot`.
274
+ * Aborts (and a prior run error) short-circuit the queue's remaining
275
+ * tasks; a thrown run error rejects and is converted to a batch engine
276
+ * error by the settle handler.
277
+ *
278
+ * @returns {Promise<object[]>}
279
+ */
280
+ const runVlOnSlot = async (vl, slot) => {
281
+ const slotLane = provisionedLanes[slot - 1] ?? null;
282
+ if (!slotLane) throw new Error(`no lane provisioned for slot ${slot} (resume dispatch)`);
283
+
284
+ // VL→slot bind (SP-903 pattern): merge (and downstream resume/
285
+ // dashboard consumers) key off `task.laneNumber`, so the runtime
286
+ // binding must replace the plan-time sticky value before any run
287
+ // persists state. The helper also moves the task out of the sticky
288
+ // lane's `taskIds`; batch-state validation rejects the mismatch (#397).
289
+ // Already-complete tasks keep their sticky lane.
290
+ rebindTasksToLane({
291
+ state,
292
+ taskIds: vl.tasks.filter((queued) => queued.bindsSlot).map((queued) => queued.taskId),
293
+ laneNumber: slotLane.laneNumber,
294
+ });
295
+ const slotCorrelationId = slotLane.correlationId ?? crypto.randomUUID();
296
+ slotLane.correlationId = slotCorrelationId;
297
+
298
+ if (vl.tasks.length > 1) {
150
299
  appendJournalEvent(projectRoot, batchId, "lane.tasks_serialized", {
151
- laneNumber,
152
- laneId: lane.laneId,
300
+ laneNumber: slotLane.laneNumber,
301
+ laneId: slotLane.laneId,
153
302
  waveIndex,
154
- taskIds: runs.map((entry) => entry.taskId),
155
- correlationId: lane.correlationId ?? null,
303
+ taskIds: vl.tasks.map((queued) => queued.taskId),
304
+ correlationId: slotCorrelationId,
156
305
  });
157
306
  }
158
307
 
159
308
  /** @type {object[]} */
160
- const laneResults = [];
161
- for (const { run } of runs) {
162
- const result = await run();
163
- laneResults.push(result);
164
- if (result.aborted) {
165
- batchAborted = true;
166
- return laneResults;
309
+ const results = [];
310
+ for (const queued of vl.tasks) {
311
+ if (batchAborted || runError) return results;
312
+ results.push(await queued.run(slotLane, slotCorrelationId));
313
+ }
314
+ return results;
315
+ };
316
+
317
+ while (readyVls.length > 0 || inFlightVls.size > 0) {
318
+ if (!batchAborted && !runError && readyVls.length > 0) {
319
+ const slot = slotPool.tryAcquire();
320
+ if (slot !== null) {
321
+ const selection = selectReadyVl(readyVls, runningVls);
322
+ if (selection.status === "dispatch" && selection.vl) {
323
+ const vl = selection.vl;
324
+ const readyIndex = readyVls.indexOf(vl);
325
+ if (readyIndex >= 0) readyVls.splice(readyIndex, 1);
326
+ runningVls.push(vl);
327
+ /** @type {Promise<object[]>} */
328
+ const completion = runVlOnSlot(vl, slot).then(
329
+ (outcome) => settleVlSlot(vl, slot, completion, outcome),
330
+ (error) =>
331
+ settleVlSlot(
332
+ vl,
333
+ slot,
334
+ completion,
335
+ [],
336
+ error instanceof Error ? error : new Error(String(error)),
337
+ ),
338
+ );
339
+ inFlightVls.add(completion);
340
+ continue;
341
+ }
342
+ // Slot free but no dispatchable VL: scope conflicts or same-VL
343
+ // serial queues are journalable (SP-897 payload).
344
+ if (selection.status === "conflict-wait") {
345
+ appendJournalEvent(
346
+ projectRoot,
347
+ batchId,
348
+ VL_SLOT_CONFLICT_WAIT_EVENT,
349
+ buildConflictWaitPayload({
350
+ slot,
351
+ blocked: selection.blocked,
352
+ waitingOn: selection.waitingOn,
353
+ runningVlIds: runningVls.map((running) => running.vlId ?? null),
354
+ readyCount: readyVls.length,
355
+ }),
356
+ );
357
+ }
358
+ slotPool.release(slot);
167
359
  }
168
360
  }
169
- return laneResults;
170
- });
171
361
 
172
- const waveResults = (await Promise.all(laneExecutions)).flat();
362
+ if (inFlightVls.size > 0) {
363
+ // Slot pool full (or nothing dispatchable): wait for a running VL
364
+ // to free its slot, then re-select.
365
+ await Promise.race([...inFlightVls]);
366
+ } else if (readyVls.length === 0 || batchAborted || runError) {
367
+ break;
368
+ }
369
+ }
370
+
371
+ if (runError) {
372
+ // Preserve the sticky-queue contract: a thrown run error propagates to
373
+ // resume-multi's engine error handler (failBatchFromEngineError) after
374
+ // in-flight VLs drain.
375
+ throw runError;
376
+ }
173
377
  return { ok: true, waveResults, batchAborted };
174
378
  }
@@ -5,6 +5,7 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { readJournalTail, summarizeJournalEvent } from "../batch/journal.mjs";
8
+ import { VL_SLOT_CONFLICT_WAIT_EVENT } from "../batch/engine-lanes/vl-slot-dispatch.mjs";
8
9
  import {
9
10
  deriveLanesThroughput,
10
11
  emptyLaneThroughputStats,
@@ -39,8 +40,25 @@ const ACTIVITY_PHASE_LABELS = {
39
40
  final_review: "final review",
40
41
  rework: "rework",
41
42
  failed: "failed",
43
+ conflict_wait: "conflict wait",
42
44
  };
43
45
 
46
+ /**
47
+ * Lane-scoped journal events that prove the physical slot holds (or just
48
+ * took) work: a VL bind, a live worker/task, or an open review running on
49
+ * the lane. Used to decide whether a `lane.slot_conflict_wait` for the slot
50
+ * is still the newest truth (free + blocked) or has been superseded by a
51
+ * fresh dispatch (SP-901 / #327).
52
+ *
53
+ * @type {Set<string>}
54
+ */
55
+ const LANE_SLOT_OCCUPANCY_EVENTS = new Set([
56
+ "lane.tasks_serialized",
57
+ "task.started",
58
+ "lane.heartbeat",
59
+ "review.started",
60
+ ]);
61
+
44
62
  export function truncateWorktreePath(worktreePath) {
45
63
  if (!worktreePath) return null;
46
64
  const parts = String(worktreePath).split(/[/\\]/).filter(Boolean);
@@ -58,7 +76,7 @@ export function heartbeatAgeSeconds(lastHeartbeatAt, now = Date.now()) {
58
76
  return Math.max(0, Math.floor((now - ts) / 1000));
59
77
  }
60
78
 
61
- export function classifyLaneStatus({ lane, classifiedTasks, stallConfig, now = Date.now(), diagnosis = null }) {
79
+ export function classifyLaneStatus({ lane, classifiedTasks, stallConfig, now = Date.now(), diagnosis = null, conflictWaitActive = false }) {
62
80
  const taskIds = lane.taskIds ?? [];
63
81
  const tasks = classifiedTasks.filter((task) => taskIds.includes(task.taskId));
64
82
 
@@ -87,6 +105,12 @@ export function classifyLaneStatus({ lane, classifiedTasks, stallConfig, now = D
87
105
  );
88
106
  if (!hasActive) return "completed";
89
107
 
108
+ // SP-901 (#327/#358): a free slot whose ready work is blocked only by a
109
+ // file-scope conflict is not live "running" and not "stale" (nothing is
110
+ // hung — progress resumes when the conflicting VL settles). Diagnosed
111
+ // lanes keep their batch-level status above.
112
+ if (conflictWaitActive) return "conflict_wait";
113
+
90
114
  let referenceMs = null;
91
115
  if (lane.lastHeartbeatAt != null) {
92
116
  referenceMs =
@@ -204,11 +228,64 @@ function taskHasReworkMarker(laneNumber, taskId, journalEvents) {
204
228
  return false;
205
229
  }
206
230
 
231
+ /**
232
+ * Latest conflict-wait state for a physical slot (SP-901 / #327, #358 display AC).
233
+ *
234
+ * Slot-pool dispatch journals `lane.slot_conflict_wait` (payload `slot` = the
235
+ * free physical slot) each time a slot is free but every remaining ready VL
236
+ * is blocked by a file-scope conflict or a same-VL serial queue. A slot is
237
+ * conflict-waiting only while that event is the newest slot-relevant journal
238
+ * signal: any newer lane-scoped occupancy event (bind, task start, worker
239
+ * heartbeat, open review) means the slot took work and the wait is over.
240
+ *
241
+ * @param {number} laneNumber Physical slot / lane row number.
242
+ * @param {Array<object>} journalEvents Journal events in append order.
243
+ * @returns {{ active: boolean, payload: object | null }} `active` is true
244
+ * only when a conflict-wait for this slot is newer than any occupancy
245
+ * signal for the lane; `payload` is the raw conflict-wait event payload.
246
+ */
247
+ export function resolveLaneConflictWait(laneNumber, journalEvents) {
248
+ const events = journalEvents ?? [];
249
+ for (let i = events.length - 1; i >= 0; i -= 1) {
250
+ const event = events[i];
251
+ if (event.type === VL_SLOT_CONFLICT_WAIT_EVENT) {
252
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
253
+ if (Number(payload.slot) === laneNumber) {
254
+ return { active: true, payload };
255
+ }
256
+ continue; // conflict-wait for a different slot — irrelevant here
257
+ }
258
+ if (LANE_SLOT_OCCUPANCY_EVENTS.has(event.type) && laneEventMatches(laneNumber, event)) {
259
+ return { active: false, payload: null }; // slot took work after the wait
260
+ }
261
+ }
262
+ return { active: false, payload: null };
263
+ }
264
+
265
+ /**
266
+ * @param {object} params
267
+ * @param {object} [params.conflictWait] Result of `resolveLaneConflictWait`.
268
+ * @returns {{ slot: number | null, reason: string, blockedByOverlap: object[], queuedBehindRunning: Array<string | number | null>, runningVlIds: Array<string | number | null>, readyCount: number } | null}
269
+ */
270
+ function formatConflictWaitDetail(conflictWait) {
271
+ if (!conflictWait?.active || !conflictWait.payload) return null;
272
+ const payload = conflictWait.payload;
273
+ return {
274
+ slot: payload.slot != null ? Number(payload.slot) : null,
275
+ reason: typeof payload.reason === "string" ? payload.reason : "scope_conflict",
276
+ blockedByOverlap: Array.isArray(payload.blockedByOverlap) ? payload.blockedByOverlap : [],
277
+ queuedBehindRunning: Array.isArray(payload.queuedBehindRunning) ? payload.queuedBehindRunning : [],
278
+ runningVlIds: Array.isArray(payload.runningVlIds) ? payload.runningVlIds : [],
279
+ readyCount: Number(payload.readyCount) || 0,
280
+ };
281
+ }
282
+
207
283
  export function resolveLaneActivityPhase({
208
284
  laneNumber,
209
285
  activeTaskIds = [],
210
286
  classifiedTasks = [],
211
287
  journalEvents = [],
288
+ conflictWait = null,
212
289
  }) {
213
290
  const activeIds = new Set((activeTaskIds ?? []).map(String));
214
291
  if (activeIds.size === 0) {
@@ -248,6 +325,13 @@ export function resolveLaneActivityPhase({
248
325
  }
249
326
  }
250
327
 
328
+ // SP-901 (#327): a slot whose newest signal is a conflict-wait has no live
329
+ // worker — do not fall through to heartbeat/worker phases that read as
330
+ // "running" at a round barrier.
331
+ if (conflictWait?.active) {
332
+ return { activityPhase: "conflict_wait", activityPhaseLabel: ACTIVITY_PHASE_LABELS.conflict_wait };
333
+ }
334
+
251
335
  const heartbeatMeta = resolveLaneHeartbeatMeta(laneNumber, events);
252
336
  if (heartbeatMeta.workerPhase === "launching") {
253
337
  return { activityPhase: "launching", activityPhaseLabel: ACTIVITY_PHASE_LABELS.launching };
@@ -432,11 +516,13 @@ export function buildLaneRows({
432
516
  laneTaskIds: lane.taskIds ?? [],
433
517
  });
434
518
  const activeTaskIds = computeActiveTaskIdsForLane({ lane, classifiedTasks, currentWaveTaskIds });
519
+ const conflictWait = resolveLaneConflictWait(lane.laneNumber, journalEvents);
435
520
  const activity = resolveLaneActivityPhase({
436
521
  laneNumber: lane.laneNumber,
437
522
  activeTaskIds,
438
523
  classifiedTasks,
439
524
  journalEvents,
525
+ conflictWait,
440
526
  });
441
527
  const throughput =
442
528
  throughputByLane.get(lane.laneNumber) ?? emptyLaneThroughputStats();
@@ -454,12 +540,21 @@ export function buildLaneRows({
454
540
  return {
455
541
  laneId: lane.laneId ?? `lane-${lane.laneNumber}`,
456
542
  laneNumber: lane.laneNumber,
457
- status: classifyLaneStatus({ lane, classifiedTasks, stallConfig, now, diagnosis }),
543
+ status: classifyLaneStatus({
544
+ lane,
545
+ classifiedTasks,
546
+ stallConfig,
547
+ now,
548
+ diagnosis,
549
+ conflictWaitActive: conflictWait.active,
550
+ }),
458
551
  activeTaskIds,
459
552
  runningTaskId,
460
553
  queuedTaskIds,
461
554
  activityPhase: activity.activityPhase,
462
555
  activityPhaseLabel: activity.activityPhaseLabel,
556
+ conflictWait: conflictWait.active,
557
+ conflictWaitDetail: formatConflictWaitDetail(conflictWait),
463
558
  taskIds: lane.taskIds ?? [],
464
559
  heartbeatAgeSeconds: heartbeatAgeSecondsValue,
465
560
  heartbeatKind: heartbeatMeta.heartbeatKind,