pi-spine 2.12.2 → 2.13.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.
@@ -20,8 +20,10 @@ import { runWorker } from "../worker-host.mjs";
20
20
  import {
21
21
  buildFinalReviewArtifactPath,
22
22
  buildReviewArtifactPath,
23
+ isReviewTypeRequired,
23
24
  normalizeCodeVerdict,
24
25
  normalizeFinalVerdict,
26
+ parseReviewVerdict,
25
27
  shouldRunCodeReview,
26
28
  shouldRunFinalReview,
27
29
  } from "../review-shared.mjs";
@@ -30,6 +32,7 @@ import {
30
32
  findCompletedCodeReview,
31
33
  findCompletedFinalReview,
32
34
  findFinalReviewStepNumber,
35
+ findLatestStepReviewArtifact,
33
36
  readReviewLevel,
34
37
  REVIEW_TIMEOUT_REASON,
35
38
  resolveReviewHonorJournalEvent,
@@ -161,6 +164,198 @@ export async function runEngineFinalReview({
161
164
  });
162
165
  }
163
166
 
167
+ /**
168
+ * @returns {"APPROVE"|"REVISE"}
169
+ */
170
+ function resolvePlanStubVerdict() {
171
+ const queue = process.env.SPINE_ENGINE_PLAN_STUB_VERDICTS;
172
+ if (queue) {
173
+ const parts = queue.split(",").map((entry) => entry.trim()).filter(Boolean);
174
+ const verdict = parts.shift() ?? "APPROVE";
175
+ process.env.SPINE_ENGINE_PLAN_STUB_VERDICTS = parts.join(",");
176
+ return normalizeCodeVerdict(verdict) ?? "APPROVE";
177
+ }
178
+ const single = process.env.SPINE_ENGINE_PLAN_STUB_VERDICT ?? "APPROVE";
179
+ return normalizeCodeVerdict(single) ?? "APPROVE";
180
+ }
181
+
182
+ /**
183
+ * Step number containing a plan review checkpoint marker, else the lowest step.
184
+ * Local mirror of findCodeReviewStepNumber for the engine plan phase (SP-695).
185
+ *
186
+ * @param {string} taskFolder
187
+ */
188
+ function findPlanReviewStepNumber(taskFolder) {
189
+ const promptPath = path.join(taskFolder, "PROMPT.md");
190
+ if (!fs.existsSync(promptPath)) return 0;
191
+ const content = fs.readFileSync(promptPath, "utf-8");
192
+ const stepBlocks = [...content.matchAll(/###\s+Step\s+(\d+)[:\s][\s\S]*?(?=###\s+Step\s+\d+|$)/g)];
193
+ for (const match of stepBlocks) {
194
+ if (/plan[-\s]review\s+checkpoint/i.test(match[0])) {
195
+ return Number(match[1]);
196
+ }
197
+ }
198
+ if (stepBlocks.length === 0) return 0;
199
+ return Math.min(...stepBlocks.map((match) => Number(match[1])));
200
+ }
201
+
202
+ /**
203
+ * Resolve an existing worker or lane plan review from journal and/or artifacts.
204
+ * Mirrors findCompletedCodeReview with reviewType "plan" (SP-695).
205
+ *
206
+ * @param {object} params
207
+ * @param {string} params.taskFolder
208
+ * @param {object[]} [params.journalEvents]
209
+ * @param {string} [params.taskId]
210
+ * @returns {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
211
+ */
212
+ function findCompletedPlanReview({ taskFolder, journalEvents = [], taskId }) {
213
+ /** @type {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
214
+ let journalMatch = null;
215
+ for (let index = 0; index < journalEvents.length; index += 1) {
216
+ const event = journalEvents[index];
217
+ if (taskId && event.taskId !== taskId) continue;
218
+ if (event.type !== "review.completed") continue;
219
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
220
+ if (payload.reviewType !== "plan") continue;
221
+ const verdict = normalizeCodeVerdict(payload.verdict);
222
+ if (!verdict) continue;
223
+ journalMatch = {
224
+ verdict,
225
+ feedback: typeof payload.feedback === "string" ? payload.feedback : "",
226
+ artifactPath: typeof payload.artifactPath === "string" ? payload.artifactPath : "",
227
+ source: "journal",
228
+ seq: index,
229
+ };
230
+ }
231
+
232
+ if (journalMatch?.verdict === "APPROVE") {
233
+ const { seq: _seq, ...result } = journalMatch;
234
+ return result;
235
+ }
236
+
237
+ const stepNumber = findPlanReviewStepNumber(taskFolder);
238
+ const latestArtifact = findLatestStepReviewArtifact(taskFolder, stepNumber);
239
+ if (latestArtifact) {
240
+ const reviewContent = fs.readFileSync(latestArtifact.artifactPath, "utf-8");
241
+ const { verdict, feedback } = parseReviewVerdict(reviewContent, { reviewType: "plan" });
242
+ if (verdict) {
243
+ const artifactMatch = {
244
+ verdict,
245
+ feedback,
246
+ artifactPath: latestArtifact.artifactPath,
247
+ source: /** @type {"artifact"} */ ("artifact"),
248
+ };
249
+ if (verdict === "APPROVE") return artifactMatch;
250
+ if (!journalMatch) return artifactMatch;
251
+ }
252
+ }
253
+
254
+ if (!journalMatch) return null;
255
+ const { seq: _seq, ...result } = journalMatch;
256
+ return result;
257
+ }
258
+
259
+ /**
260
+ * Engine-owned plan review — mirror of runEngineCodeReview with reviewType "plan".
261
+ * Uses agents.reviewer.plan pins via runStepReview → buildReviewerPiArgs (SP-695 / #250).
262
+ *
263
+ * @param {object} params
264
+ */
265
+ export async function runEnginePlanReview({
266
+ taskFolder,
267
+ worktreePath,
268
+ config = {},
269
+ attempt = 1,
270
+ journal,
271
+ }) {
272
+ const reviewLevel = readReviewLevel(taskFolder);
273
+ if (!isReviewTypeRequired(reviewLevel, "plan")) {
274
+ return {
275
+ ok: true,
276
+ skipped: true,
277
+ reviewLevel,
278
+ verdict: null,
279
+ feedback: "",
280
+ artifactPath: "",
281
+ spawnFailed: false,
282
+ exitCode: 0,
283
+ };
284
+ }
285
+
286
+ const stepNumber = findPlanReviewStepNumber(taskFolder);
287
+ const artifactPath = buildReviewArtifactPath(taskFolder, stepNumber);
288
+ const useStub =
289
+ process.env.SPINE_REVIEW_STUB === "1" ||
290
+ process.env.SPINE_REVIEW_STUB === "true" ||
291
+ process.env.SPINE_WORKER_STUB === "1";
292
+
293
+ if (useStub) {
294
+ const verdict = resolvePlanStubVerdict();
295
+ const feedback =
296
+ verdict === "REVISE" ? "Stub reviewer requested changes." : "Stub reviewer approved.";
297
+ if (journal?.projectRoot && journal?.batchId) {
298
+ appendJournalEvent(journal.projectRoot, journal.batchId, "review.started", {
299
+ taskId: journal.taskId,
300
+ laneNumber: journal.laneNumber,
301
+ correlationId: journal.correlationId,
302
+ stepNumber,
303
+ reviewType: "plan",
304
+ reviewLevel,
305
+ artifactPath,
306
+ });
307
+ }
308
+ fs.mkdirSync(path.dirname(artifactPath), { recursive: true });
309
+ const body = [
310
+ "## Plan Review",
311
+ "",
312
+ `### Verdict: ${verdict}`,
313
+ "",
314
+ "### Summary",
315
+ feedback,
316
+ "",
317
+ "```json",
318
+ JSON.stringify({ verdict, feedback }, null, 2),
319
+ "```",
320
+ "",
321
+ ].join("\n");
322
+ fs.writeFileSync(artifactPath, body, "utf-8");
323
+ if (journal?.projectRoot && journal?.batchId) {
324
+ appendJournalEvent(journal.projectRoot, journal.batchId, "review.completed", {
325
+ taskId: journal.taskId,
326
+ laneNumber: journal.laneNumber,
327
+ correlationId: journal.correlationId,
328
+ stepNumber,
329
+ reviewType: "plan",
330
+ reviewLevel,
331
+ verdict,
332
+ artifactPath,
333
+ stub: true,
334
+ });
335
+ }
336
+ return {
337
+ ok: verdict === "APPROVE",
338
+ skipped: false,
339
+ reviewLevel,
340
+ verdict,
341
+ feedback,
342
+ artifactPath,
343
+ spawnFailed: false,
344
+ exitCode: verdict === "APPROVE" ? 0 : 2,
345
+ attempt,
346
+ };
347
+ }
348
+
349
+ return await runStepReview({
350
+ taskFolder,
351
+ worktreePath,
352
+ stepNumber,
353
+ reviewType: "plan",
354
+ config,
355
+ journal,
356
+ });
357
+ }
358
+
164
359
  /**
165
360
  * @param {object} params
166
361
  */
@@ -361,6 +556,49 @@ function recordFinalReviewTaskFailure({
361
556
  });
362
557
  }
363
558
 
559
+ /**
560
+ * @param {object} params
561
+ */
562
+ function recordPlanReviewTaskFailure({
563
+ projectRoot,
564
+ state,
565
+ batchId,
566
+ task,
567
+ lane,
568
+ laneCorrelationId,
569
+ exitReason,
570
+ verdict,
571
+ planReviewAttempt,
572
+ config,
573
+ taskFolder,
574
+ }) {
575
+ const taskId = task.taskId;
576
+ const laneNumber = lane.laneNumber;
577
+ task.status = "failed";
578
+ task.endedAt = Date.now();
579
+ task.exitReason = exitReason;
580
+ updateSegmentForTask(state, taskId, "failed");
581
+ recomputeTaskCounters(state);
582
+ saveSpineBatchState(projectRoot, state);
583
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
584
+ taskId,
585
+ laneNumber,
586
+ laneId: lane.laneId,
587
+ correlationId: laneCorrelationId,
588
+ classification: exitReason,
589
+ exitCode: 1,
590
+ planVerdict: verdict ?? null,
591
+ planReviewAttempt,
592
+ });
593
+ recordLaneTaskMetric({
594
+ projectRoot,
595
+ batchId,
596
+ task,
597
+ config,
598
+ taskFolder,
599
+ });
600
+ }
601
+
364
602
  /**
365
603
  * @param {object} params
366
604
  */
@@ -442,6 +680,14 @@ function appendReviewHonorJournalEvents({
442
680
  reviewPassKind: resolveReviewPassKind(honorJournalEvent),
443
681
  };
444
682
 
683
+ if (reviewType === "plan") {
684
+ appendJournalEvent(projectRoot, batchId, honorJournalEvent, {
685
+ ...basePayload,
686
+ planReviewAttempt: reviewAttempt,
687
+ });
688
+ return;
689
+ }
690
+
445
691
  if (reviewType === "code") {
446
692
  appendJournalEvent(projectRoot, batchId, honorJournalEvent, {
447
693
  ...basePayload,
@@ -1034,4 +1280,264 @@ async function runFinalReviewPhase({
1034
1280
  }
1035
1281
  }
1036
1282
 
1037
- export { runCodeReviewPhase, runFinalReviewPhase };
1283
+ /**
1284
+ * Engine-owned plan review phase after worker success (SP-695 / #250).
1285
+ * Mirrors runCodeReviewPhase: RL gate (plan required for RL≥1), honor of an
1286
+ * existing plan artifact/journal verdict, rework loop on REVISE, fail-closed
1287
+ * on exhaustion or invalid verdict.
1288
+ *
1289
+ * @param {object} params
1290
+ */
1291
+ async function runPlanReviewPhase({
1292
+ projectRoot,
1293
+ state,
1294
+ batchId,
1295
+ config,
1296
+ task,
1297
+ lane,
1298
+ taskFolderInWorktree,
1299
+ wt,
1300
+ taskBranch,
1301
+ laneCorrelationId,
1302
+ fileScopePaths,
1303
+ }) {
1304
+ const taskId = task.taskId;
1305
+ const laneNumber = lane.laneNumber;
1306
+ const reviewLevel = readReviewLevel(taskFolderInWorktree);
1307
+ if (!isReviewTypeRequired(reviewLevel, "plan")) {
1308
+ return { ok: true, skipped: true };
1309
+ }
1310
+
1311
+ const maxPlanReviewAttempts = config?.review?.maxFinalAttempts ?? REVIEW_DEFAULTS.maxFinalAttempts;
1312
+ let planReviewAttempt = task.planReviewAttempts ?? 0;
1313
+
1314
+ const journalEvents = readJournalEvents(projectRoot, batchId);
1315
+ const honored = findCompletedPlanReview({
1316
+ taskFolder: taskFolderInWorktree,
1317
+ journalEvents,
1318
+ taskId,
1319
+ });
1320
+ if (honored?.verdict === "APPROVE") {
1321
+ const honorJournalEvent = resolveReviewHonorJournalEvent({
1322
+ journalEvents,
1323
+ taskId,
1324
+ reviewType: "plan",
1325
+ honorSource: honored.source,
1326
+ reviewAttempt: planReviewAttempt,
1327
+ });
1328
+ appendReviewHonorJournalEvents({
1329
+ projectRoot,
1330
+ batchId,
1331
+ task,
1332
+ lane,
1333
+ laneCorrelationId,
1334
+ reviewType: "plan",
1335
+ reviewAttempt: planReviewAttempt,
1336
+ honored,
1337
+ honorJournalEvent,
1338
+ });
1339
+ appendJournalEvent(projectRoot, batchId, "task.verdict_recorded", {
1340
+ taskId,
1341
+ laneNumber,
1342
+ laneId: lane.laneId,
1343
+ correlationId: laneCorrelationId,
1344
+ reviewType: "plan",
1345
+ verdict: "APPROVE",
1346
+ feedback: honored.feedback,
1347
+ artifactPath: honored.artifactPath,
1348
+ planReviewAttempt: planReviewAttempt + 1,
1349
+ honored: true,
1350
+ honorSource: honored.source,
1351
+ reviewPassKind: resolveReviewPassKind(honorJournalEvent),
1352
+ });
1353
+ task.planReviewAttempts = planReviewAttempt + 1;
1354
+ saveSpineBatchState(projectRoot, state);
1355
+ return { ok: true, verdict: "APPROVE", planReviewAttempt: planReviewAttempt + 1, honored: true };
1356
+ }
1357
+
1358
+ const journal = {
1359
+ projectRoot,
1360
+ batchId,
1361
+ taskId,
1362
+ laneNumber,
1363
+ correlationId: laneCorrelationId,
1364
+ };
1365
+
1366
+ let reviewResumedEmitted = false;
1367
+
1368
+ while (true) {
1369
+ if (
1370
+ !reviewResumedEmitted &&
1371
+ shouldEmitReviewResumed({ journalEvents, taskId })
1372
+ ) {
1373
+ appendJournalEvent(projectRoot, batchId, "review.resumed", {
1374
+ taskId,
1375
+ laneNumber,
1376
+ laneId: lane.laneId,
1377
+ correlationId: laneCorrelationId,
1378
+ reviewType: "plan",
1379
+ planReviewAttempt: planReviewAttempt + 1,
1380
+ });
1381
+ reviewResumedEmitted = true;
1382
+ }
1383
+
1384
+ const reviewResult = await runEnginePlanReview({
1385
+ taskFolder: taskFolderInWorktree,
1386
+ worktreePath: wt,
1387
+ config,
1388
+ attempt: planReviewAttempt + 1,
1389
+ journal,
1390
+ });
1391
+
1392
+ if (reviewResult.spawnFailed) {
1393
+ const spawnExitReason =
1394
+ reviewResult.reason === REVIEW_TIMEOUT_REASON
1395
+ ? "plan_review_timeout"
1396
+ : "plan_review_spawn_failed";
1397
+ recordPlanReviewTaskFailure({
1398
+ projectRoot,
1399
+ state,
1400
+ batchId,
1401
+ task,
1402
+ lane,
1403
+ laneCorrelationId,
1404
+ exitReason: spawnExitReason,
1405
+ verdict: null,
1406
+ planReviewAttempt,
1407
+ config,
1408
+ taskFolder: taskFolderInWorktree,
1409
+ });
1410
+ return {
1411
+ ok: false,
1412
+ error: spawnExitReason,
1413
+ output: reviewResult.error ?? "plan review spawn failed",
1414
+ };
1415
+ }
1416
+
1417
+ if (reviewResult.skipped) {
1418
+ return { ok: true, skipped: true };
1419
+ }
1420
+
1421
+ appendJournalEvent(projectRoot, batchId, "task.verdict_recorded", {
1422
+ taskId,
1423
+ laneNumber,
1424
+ laneId: lane.laneId,
1425
+ correlationId: laneCorrelationId,
1426
+ reviewType: "plan",
1427
+ verdict: reviewResult.verdict,
1428
+ feedback: reviewResult.feedback,
1429
+ artifactPath: reviewResult.artifactPath,
1430
+ planReviewAttempt: planReviewAttempt + 1,
1431
+ });
1432
+
1433
+ if (reviewResult.verdict === "APPROVE") {
1434
+ task.planReviewAttempts = planReviewAttempt + 1;
1435
+ saveSpineBatchState(projectRoot, state);
1436
+ return { ok: true, verdict: "APPROVE", planReviewAttempt: planReviewAttempt + 1 };
1437
+ }
1438
+
1439
+ if (reviewResult.verdict === "REVISE") {
1440
+ planReviewAttempt++;
1441
+ task.planReviewAttempts = planReviewAttempt;
1442
+ saveSpineBatchState(projectRoot, state);
1443
+
1444
+ if (planReviewAttempt >= maxPlanReviewAttempts) {
1445
+ removeDoneFile(taskFolderInWorktree);
1446
+ appendJournalEvent(projectRoot, batchId, "review.exhausted", {
1447
+ taskId,
1448
+ laneNumber,
1449
+ laneId: lane.laneId,
1450
+ correlationId: laneCorrelationId,
1451
+ planReviewAttempt,
1452
+ maxPlanReviewAttempts,
1453
+ reviewType: "plan",
1454
+ });
1455
+ recordPlanReviewTaskFailure({
1456
+ projectRoot,
1457
+ state,
1458
+ batchId,
1459
+ task,
1460
+ lane,
1461
+ laneCorrelationId,
1462
+ exitReason: "review_exhausted",
1463
+ verdict: "REVISE",
1464
+ planReviewAttempt,
1465
+ config,
1466
+ taskFolder: taskFolderInWorktree,
1467
+ });
1468
+ return { ok: false, exitReason: "review_exhausted", verdict: "REVISE" };
1469
+ }
1470
+
1471
+ removeDoneFile(taskFolderInWorktree);
1472
+ const reworkResult = await runWorker({
1473
+ worktreePath: wt,
1474
+ taskFolder: taskFolderInWorktree,
1475
+ projectRoot,
1476
+ batchId,
1477
+ laneNumber,
1478
+ taskId,
1479
+ laneBranch: taskBranch,
1480
+ laneCorrelationId,
1481
+ fileScopePaths,
1482
+ config,
1483
+ onHeartbeat: (timestamp) => {
1484
+ lane.lastHeartbeatAt = timestamp;
1485
+ saveSpineBatchState(projectRoot, state);
1486
+ },
1487
+ onWorkerPid: (pid) => {
1488
+ if (pid > 0) {
1489
+ lane.workerPid = pid;
1490
+ saveSpineBatchState(projectRoot, state);
1491
+ }
1492
+ },
1493
+ });
1494
+ if (!reworkResult.ok) {
1495
+ const aborted = reworkResult.classification === "aborted";
1496
+ task.status = aborted ? "aborted" : "failed";
1497
+ task.endedAt = Date.now();
1498
+ task.exitReason = reworkResult.classification ?? "worker_failed";
1499
+ updateSegmentForTask(state, taskId, aborted ? "aborted" : "failed");
1500
+ recomputeTaskCounters(state);
1501
+ saveSpineBatchState(projectRoot, state);
1502
+ recordLaneTaskMetric({
1503
+ projectRoot,
1504
+ batchId,
1505
+ task,
1506
+ config,
1507
+ taskFolder: taskFolderInWorktree,
1508
+ });
1509
+ return { ok: false, aborted, workerResult: reworkResult };
1510
+ }
1511
+
1512
+ appendJournalEvent(projectRoot, batchId, "lane.completed", {
1513
+ laneNumber,
1514
+ laneId: lane.laneId,
1515
+ taskId,
1516
+ correlationId: laneCorrelationId,
1517
+ phase: "plan_rework",
1518
+ });
1519
+ continue;
1520
+ }
1521
+
1522
+ recordPlanReviewTaskFailure({
1523
+ projectRoot,
1524
+ state,
1525
+ batchId,
1526
+ task,
1527
+ lane,
1528
+ laneCorrelationId,
1529
+ exitReason: "plan_review_invalid_verdict",
1530
+ verdict: reviewResult.verdict,
1531
+ planReviewAttempt,
1532
+ config,
1533
+ taskFolder: taskFolderInWorktree,
1534
+ });
1535
+ return {
1536
+ ok: false,
1537
+ error: "plan_review_invalid_verdict",
1538
+ output: "plan review artifact missing APPROVE or REVISE verdict",
1539
+ };
1540
+ }
1541
+ }
1542
+
1543
+ export { runCodeReviewPhase, runFinalReviewPhase, runPlanReviewPhase };
@@ -21,11 +21,15 @@ import {
21
21
  updateSegmentForTask,
22
22
  } from "./state.mjs";
23
23
  import { runWorker } from "./worker-host.mjs";
24
- import { runCodeReviewPhase, runFinalReviewPhase } from "./engine-lanes/review.mjs";
24
+ import { runCodeReviewPhase, runFinalReviewPhase, runPlanReviewPhase } from "./engine-lanes/review.mjs";
25
25
  import { ensureLaneSyncedForSharedScopeDeps } from "./engine-lanes/orch-sync.mjs";
26
26
  import { resolveWorktreeSetupIgnorePaths } from "../config/spine-config-load.mjs";
27
- import { loadMatrixTaskRows } from "./engine-lanes/matrix.mjs";
28
- import { runMatrixTaskOnLane, matrixRowConcurrencyLimit } from "./engine-lanes/matrix-run.mjs";
27
+ import {
28
+ acquireLaneSlot,
29
+ loadMatrixTaskRows,
30
+ releaseLaneSlot,
31
+ } from "./engine-lanes/matrix.mjs";
32
+ import { runMatrixTaskOnLane } from "./engine-lanes/matrix-run.mjs";
29
33
 
30
34
  export {
31
35
  buildTasksAndLanesFromPlan,
@@ -40,6 +44,7 @@ export {
40
44
  shouldRunFinalReview,
41
45
  runEngineFinalReview,
42
46
  runEngineCodeReview,
47
+ runEnginePlanReview,
43
48
  } from "./engine-lanes/review.mjs";
44
49
 
45
50
  export {
@@ -57,6 +62,7 @@ export {
57
62
  } from "./engine-lanes/orch-sync.mjs";
58
63
 
59
64
  export {
65
+ acquireLaneSlot,
60
66
  aggregateMatrixOutcomes,
61
67
  isMatrixSubLaneWorktreeDir,
62
68
  loadMatrixTaskRows,
@@ -64,6 +70,7 @@ export {
64
70
  matrixWorktreeDir,
65
71
  matrixWorktreePath,
66
72
  provisionMatrixSubLaneWorktree,
73
+ releaseLaneSlot,
67
74
  removeAllMatrixSubLaneWorktrees,
68
75
  removeMatrixSubLaneWorktree,
69
76
  runConcurrent,
@@ -71,7 +78,7 @@ export {
71
78
  runShellInDir,
72
79
  } from "./engine-lanes/matrix.mjs";
73
80
 
74
- export { runMatrixTaskOnLane, runMatrixSubLane, matrixRowConcurrencyLimit } from "./engine-lanes/matrix-run.mjs";
81
+ export { runMatrixTaskOnLane, runMatrixSubLane } from "./engine-lanes/matrix-run.mjs";
75
82
 
76
83
  /**
77
84
  * @param {string} fromPhase
@@ -122,11 +129,6 @@ export async function runTaskOnLane({
122
129
  taskFolderRel,
123
130
  laneCorrelationId,
124
131
  }) {
125
- const taskId = task.taskId;
126
- const laneNumber = lane.laneNumber;
127
- const wt = lane.worktreePath;
128
- const taskBranch = lane.branch;
129
- const taskFolderInWorktree = path.join(wt, taskFolderRel);
130
132
  const scopeResult = loadTaskFileScopePaths(path.join(projectRoot, taskFolderRel));
131
133
  if (!scopeResult.ok) {
132
134
  return recordPromptParseFailure({
@@ -143,19 +145,14 @@ export async function runTaskOnLane({
143
145
  }
144
146
  const fileScopePaths = scopeResult.fileScopePaths;
145
147
 
146
- // Matrix tasks fan out into per-row sub-lane worktrees (SP-671 / #217).
147
- // Non-matrix tasks fall through to the single-worker path below.
148
+ // Matrix tasks fan out into per-row lane-pool competitors (SP-697 / #228,
149
+ // supersedes the SP-690 nested throttle). The parent lane is NOT held during
150
+ // the sweep: each active row acquires a slot from the global pool inside
151
+ // runMatrixTaskOnLane. Non-matrix tasks hold one slot for their whole
152
+ // duration below, so rows and sibling lanes compete for the same pool and
153
+ // global in-flight workers never exceed `lanes.maxParallel`.
148
154
  const matrixRows = loadMatrixTaskRows(path.join(projectRoot, taskFolderRel));
149
155
  if (matrixRows) {
150
- // SP-690 / #227: the parent matrix task already occupies this lane, so its
151
- // nested rows must not reuse the parent's slot. Cap rows to the remaining
152
- // free slots so global in-flight workers (siblings + rows) stay within
153
- // `lanes.maxParallel`. Interim invariant — #228 first-class row scheduling
154
- // supersedes it.
155
- const matrixMaxParallel = matrixRowConcurrencyLimit(
156
- config?.lanes?.maxParallel ?? 1,
157
- 1,
158
- );
159
156
  return runMatrixTaskOnLane({
160
157
  projectRoot,
161
158
  state,
@@ -168,10 +165,52 @@ export async function runTaskOnLane({
168
165
  laneCorrelationId,
169
166
  fileScopePaths,
170
167
  matrix: matrixRows,
171
- maxParallel: matrixMaxParallel,
168
+ maxParallel: config?.lanes?.maxParallel ?? 1,
172
169
  });
173
170
  }
174
171
 
172
+ const laneSlot = await acquireLaneSlot(state, config?.lanes?.maxParallel ?? 1);
173
+ try {
174
+ return await runNonMatrixTaskOnLane({
175
+ projectRoot,
176
+ state,
177
+ batchId,
178
+ baseBranch,
179
+ config,
180
+ task,
181
+ lane,
182
+ taskFolderRel,
183
+ laneCorrelationId,
184
+ fileScopePaths,
185
+ });
186
+ } finally {
187
+ releaseLaneSlot(state, laneSlot);
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Single-worker (non-matrix) lane task path. Caller holds a global lane slot
193
+ * for the duration of this call.
194
+ *
195
+ * @param {object} params
196
+ */
197
+ async function runNonMatrixTaskOnLane({
198
+ projectRoot,
199
+ state,
200
+ batchId,
201
+ baseBranch,
202
+ config,
203
+ task,
204
+ lane,
205
+ taskFolderRel,
206
+ laneCorrelationId,
207
+ fileScopePaths,
208
+ }) {
209
+ const taskId = task.taskId;
210
+ const laneNumber = lane.laneNumber;
211
+ const wt = lane.worktreePath;
212
+ const taskBranch = lane.branch;
213
+ const taskFolderInWorktree = path.join(wt, taskFolderRel);
175
214
  const syncResult = ensureLaneSyncedForSharedScopeDeps({
176
215
  projectRoot,
177
216
  state,
@@ -349,6 +388,23 @@ export async function runTaskOnLane({
349
388
  correlationId: laneCorrelationId,
350
389
  });
351
390
 
391
+ const planReview = await runPlanReviewPhase({
392
+ projectRoot,
393
+ state,
394
+ batchId,
395
+ config,
396
+ task,
397
+ lane,
398
+ taskFolderInWorktree,
399
+ wt,
400
+ taskBranch,
401
+ laneCorrelationId,
402
+ fileScopePaths,
403
+ });
404
+ if (!planReview.ok) {
405
+ return planReview;
406
+ }
407
+
352
408
  const codeReview = await runCodeReviewPhase({
353
409
  projectRoot,
354
410
  state,