pi-spine 2.31.0 → 2.33.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.
@@ -5,7 +5,6 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { setTimeout as sleep } from "node:timers/promises";
8
- import picomatch from "picomatch";
9
8
  import { parseAggregateLineCoverage } from "../../scripts/coverage-parse.mjs";
10
9
  import {
11
10
  isBaseFileScopeSatisfied,
@@ -24,6 +23,7 @@ import {
24
23
  import {
25
24
  NPM_TEST_DASH_DASH_RE,
26
25
  TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT,
26
+ findArtifactMatch,
27
27
  } from "../tasks/validate-contract-warn.mjs";
28
28
  import { formatRefusedContractMetacharMessage, isRefusedContractMetacharCommand } from "../tasks/packet/parse-prompt.mjs";
29
29
  import { buildContractTestEnv, runShellCommandAsync } from "./contract-spawn.mjs";
@@ -209,48 +209,6 @@ async function resolveLineCoverage(worktreePath, parsedContract, config, testCom
209
209
  return parseAggregateLineCoverage(output);
210
210
  }
211
211
 
212
- /**
213
- * @param {string} worktreePath
214
- * @param {string} artifactPattern
215
- * @returns {{ ok: boolean, matchedPath?: string }}
216
- */
217
- function findArtifactMatch(worktreePath, artifactPattern) {
218
- const normalized = String(artifactPattern ?? "").replace(/\\/g, "/");
219
- if (!normalized) {
220
- return { ok: false };
221
- }
222
-
223
- if (!/[*?[\]{}]/.test(normalized)) {
224
- const fullPath = path.join(worktreePath, normalized);
225
- return fs.existsSync(fullPath) ? { ok: true, matchedPath: normalized } : { ok: false };
226
- }
227
-
228
- const baseDir = path.dirname(normalized);
229
- const searchRoot = path.join(worktreePath, baseDir);
230
- if (!fs.existsSync(searchRoot)) {
231
- return { ok: false };
232
- }
233
-
234
- /** @type {Array<{ abs: string, rel: string }>} */
235
- const stack = [{ abs: searchRoot, rel: baseDir === "." ? "" : baseDir }];
236
- while (stack.length > 0) {
237
- const { abs, rel } = /** @type {{ abs: string, rel: string }} */ (stack.pop());
238
- for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
239
- const entryRel = rel ? `${rel}/${entry.name}` : entry.name;
240
- const entryAbs = path.join(abs, entry.name);
241
- if (entry.isDirectory()) {
242
- stack.push({ abs: entryAbs, rel: entryRel });
243
- continue;
244
- }
245
- if (picomatch(normalized, { dot: true })(entryRel)) {
246
- return { ok: true, matchedPath: entryRel };
247
- }
248
- }
249
- }
250
-
251
- return { ok: false };
252
- }
253
-
254
212
  /**
255
213
  * Prepare lane worktree before contract testCommand (Flutter analyzer hygiene #78).
256
214
  *
@@ -298,6 +256,29 @@ export async function verifyContract(worktreePath, parsedContract, config = {})
298
256
  maxBuffer: CONTRACT_TEST_COMMAND_MAX_BUFFER,
299
257
  });
300
258
  const indexAndWorktreeFiles = diffResult.exitCode === 0 ? diffResult.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean) : [];
259
+ // Fail-closed (#309): a failed/timed-out `git diff` must not pass must-not-change
260
+ // on an empty file list. Only enforced when the contract declares patterns —
261
+ // without patterns there is no scope to verify either way.
262
+ const mustNotChangePatterns = parsedContract.fileScopeMustNotChange ?? [];
263
+ const diffFailed = diffResult.exitCode !== 0;
264
+
265
+ // Fail-closed (#309): `listChangedFiles` (contract-parse.mjs) swallows git
266
+ // errors into an empty or partial committed-file list, so a failed committed
267
+ // lookup could let must-not-change pass on incomplete evidence. Re-run the
268
+ // same committed range with a visible exit code — gated on declared
269
+ // must-not-change patterns (same scoping as the diffFailed gate).
270
+ const scopedSince = String(sinceCommit ?? "").trim();
271
+ const committedRange = scopedSince ? `${scopedSince}..HEAD` : `${baseBranch}...HEAD`;
272
+ const committedProbeCommand = `git diff --name-only ${committedRange}`;
273
+ const committedProbe = mustNotChangePatterns.length > 0 &&
274
+ !isRefusedContractMetacharCommand(committedProbeCommand)
275
+ ? await runShellCommandAsync(worktreePath, committedProbeCommand, {
276
+ timeoutMs: 30 * 1000,
277
+ maxBuffer: CONTRACT_TEST_COMMAND_MAX_BUFFER,
278
+ })
279
+ : null;
280
+ const committedLookupFailed = mustNotChangePatterns.length > 0 &&
281
+ (committedProbe == null || committedProbe.exitCode !== 0);
301
282
 
302
283
  const changedFiles = [...new Set([...committedFiles, ...indexAndWorktreeFiles])];
303
284
 
@@ -424,21 +405,46 @@ export async function verifyContract(worktreePath, parsedContract, config = {})
424
405
  });
425
406
  }
426
407
 
427
- for (const pattern of parsedContract.fileScopeMustNotChange ?? []) {
428
- const forbidden = changedFiles.filter((file) => matchesContractPattern(file, pattern));
429
- if (forbidden.length === 0) {
430
- checks.push({
431
- field: "fileScopeMustNotChange",
432
- ok: true,
433
- message: `fileScopeMustNotChange respected: ${pattern}`,
434
- });
435
- } else {
436
- for (const file of forbidden) {
408
+ if (mustNotChangePatterns.length > 0 && (diffFailed || committedLookupFailed)) {
409
+ const failureReasons = [];
410
+ if (diffFailed) {
411
+ failureReasons.push(
412
+ `git diff --name-only HEAD failed (${
413
+ diffResult.timedOut ? "timed out" : `exit ${diffResult.exitCode}`
414
+ })`,
415
+ );
416
+ }
417
+ if (committedLookupFailed) {
418
+ failureReasons.push(
419
+ committedProbe == null
420
+ ? `git diff --name-only ${committedRange} refused (unsafe range)`
421
+ : `git diff --name-only ${committedRange} failed (${
422
+ committedProbe.timedOut ? "timed out" : `exit ${committedProbe.exitCode}`
423
+ })`,
424
+ );
425
+ }
426
+ checks.push({
427
+ field: "fileScopeMustNotChange",
428
+ ok: false,
429
+ message: `Contract fileScopeMustNotChange: ${failureReasons.join("; ")} — cannot verify must-not-change scope, failing closed (#309)`,
430
+ });
431
+ } else {
432
+ for (const pattern of mustNotChangePatterns) {
433
+ const forbidden = changedFiles.filter((file) => matchesContractPattern(file, pattern));
434
+ if (forbidden.length === 0) {
437
435
  checks.push({
438
436
  field: "fileScopeMustNotChange",
439
- ok: false,
440
- message: `Contract fileScopeMustNotChange: forbidden change ${file}`,
437
+ ok: true,
438
+ message: `fileScopeMustNotChange respected: ${pattern}`,
441
439
  });
440
+ } else {
441
+ for (const file of forbidden) {
442
+ checks.push({
443
+ field: "fileScopeMustNotChange",
444
+ ok: false,
445
+ message: `Contract fileScopeMustNotChange: forbidden change ${file}`,
446
+ });
447
+ }
442
448
  }
443
449
  }
444
450
  }
@@ -471,7 +477,9 @@ export async function verifyContract(worktreePath, parsedContract, config = {})
471
477
  ok: match.ok,
472
478
  message: match.ok
473
479
  ? `artifact exists: ${match.matchedPath ?? artifactPath}`
474
- : `Contract artifactsMustExist: missing ${artifactPath}`,
480
+ : match.unsafe
481
+ ? `Contract artifactsMustExist: rejected unsafe pattern ${artifactPath} — parent-directory traversal outside the lane worktree is not allowed (#309)`
482
+ : `Contract artifactsMustExist: missing ${artifactPath}`,
475
483
  });
476
484
  }
477
485
 
@@ -38,7 +38,9 @@ import {
38
38
  findContractCommandMetacharIssue,
39
39
  isRefusedContractMetacharCommand,
40
40
  parseContract,
41
+ parsePrompt,
41
42
  } from "../../tasks/packet/parse-prompt.mjs";
43
+ import { loadTaskPacket } from "../../tasks/packet/index.mjs";
42
44
  import { verifyContract } from "../contract-verify.mjs";
43
45
  import { gitExec } from "../git-exec.mjs";
44
46
 
@@ -54,6 +56,55 @@ export function readParentContract(parentTaskFolderAbs) {
54
56
  return parseContract(fs.readFileSync(promptPath, "utf-8"));
55
57
  }
56
58
 
59
+ /**
60
+ * Fail closed when a declared matrix packet fails to load (#311).
61
+ *
62
+ * `loadMatrixTaskRows` collapses every packet load error into `null`, which
63
+ * callers read as "not a matrix task" — silently demoting a matrix parent to
64
+ * plain worker mode, where its row fan-out never happens and raw `{matrix.*}`
65
+ * placeholders leak into the served prompt. When `loadMatrixTaskRows` returned
66
+ * null, re-load the packet here: if it throws and the raw PROMPT.md declares
67
+ * a `## Matrix` section, propagate a clear error instead of the silent
68
+ * demotion. Plain (non-matrix) packets keep the null → plain-worker behavior
69
+ * unchanged, and a missing PROMPT.md stays "not a task packet".
70
+ *
71
+ * @param {string} parentTaskFolderAbs Absolute parent task folder.
72
+ * @returns {void}
73
+ * @throws When the packet fails to load and the task declares `## Matrix`.
74
+ */
75
+ function assertMatrixPacketLoaded(parentTaskFolderAbs) {
76
+ const promptPath = path.join(parentTaskFolderAbs, "PROMPT.md");
77
+ if (!fs.existsSync(promptPath)) return;
78
+ let packetError = null;
79
+ try {
80
+ loadTaskPacket(parentTaskFolderAbs);
81
+ } catch (err) {
82
+ packetError = err;
83
+ }
84
+ if (!packetError) return;
85
+ const message = packetError instanceof Error ? packetError.message : String(packetError);
86
+ let rawPrompt = null;
87
+ try {
88
+ rawPrompt = fs.readFileSync(promptPath, "utf-8");
89
+ } catch {
90
+ rawPrompt = null;
91
+ }
92
+ if (rawPrompt === null) {
93
+ // PROMPT.md exists but is unreadable (e.g. a directory): the packet is
94
+ // broken and whether it declared matrix is unknowable — fail closed.
95
+ throw new Error(
96
+ `task packet failed to load: ${parentTaskFolderAbs} — ${message}. Refusing to proceed on an unreadable packet (#311).`,
97
+ { cause: packetError },
98
+ );
99
+ }
100
+ const declaresMatrix = Boolean(parsePrompt(rawPrompt).sections?.Matrix);
101
+ if (!declaresMatrix) return;
102
+ throw new Error(
103
+ `matrix packet failed to load: ${parentTaskFolderAbs} — ${message}. Refusing to demote a declared matrix task to plain worker mode (#311).`,
104
+ { cause: packetError },
105
+ );
106
+ }
107
+
57
108
  /**
58
109
  * Matrix-specific refusal copy for an execute row whose substituted command
59
110
  * contains shell metacharacters (#297). Deliberately distinct from the
@@ -513,8 +564,14 @@ export async function runMatrixTaskForResume({
513
564
  laneCorrelationId,
514
565
  fileScopePaths,
515
566
  }) {
516
- const matrix = loadMatrixTaskRows(path.join(projectRoot, taskFolderRel));
517
- if (!matrix) return { isMatrix: false };
567
+ const parentTaskFolderAbs = path.join(projectRoot, taskFolderRel);
568
+ const matrix = loadMatrixTaskRows(parentTaskFolderAbs);
569
+ if (!matrix) {
570
+ // Fail closed on a declared matrix packet that fails to load (#311);
571
+ // genuinely non-matrix packets still fall through to the plain path.
572
+ assertMatrixPacketLoaded(parentTaskFolderAbs);
573
+ return { isMatrix: false };
574
+ }
518
575
  const result = await runMatrixTaskOnLane({
519
576
  projectRoot,
520
577
  state,
@@ -705,14 +762,17 @@ export async function runMatrixTaskOnLane({
705
762
  // row's distinct lane identity. Always release so a crashed row cannot
706
763
  // leak a slot and stall the batch.
707
764
  const rowLaneNumber = await acquireLaneSlot(state, maxParallel);
708
- // Per-row live status (#230): flip to `running` only once the row actually
709
- // holds a slot, and persist so `spine status` sees it from another process.
710
- const runningEntry = task.matrixRows.find((/** @type {any} */ m) => m.rowId === row.rowId);
711
- if (runningEntry) {
712
- runningEntry.status = "running";
713
- await saveEngineBatchState(projectRoot, state);
714
- }
715
765
  try {
766
+ // Per-row live status (#230): flip to `running` only once the row actually
767
+ // holds a slot, and persist so `spine status` sees it from another process.
768
+ // Inside the try (#311): this save is the first operation that can throw
769
+ // while the slot is held — before SP-876 it ran outside the try, so a
770
+ // save failure leaked the slot and stalled the global pool.
771
+ const runningEntry = task.matrixRows.find((/** @type {any} */ m) => m.rowId === row.rowId);
772
+ if (runningEntry) {
773
+ runningEntry.status = "running";
774
+ await saveEngineBatchState(projectRoot, state);
775
+ }
716
776
  return await runMatrixSubLane({
717
777
  projectRoot,
718
778
  batchId,
@@ -4,9 +4,10 @@
4
4
  */
5
5
 
6
6
  import path from "node:path";
7
+ import fs from "node:fs";
7
8
  import { loadTaskPacket } from "../../tasks/packet/index.mjs";
8
9
  import { appendJournalEvent } from "../journal.mjs";
9
- import { recordTaskTerminalMetric } from "../metrics.mjs";
10
+ import { recordTaskTerminalMetric, resolveTaskMetricOutcome } from "../metrics.mjs";
10
11
  import { buildTaskLaneAssignments, countPlanTasks } from "../engine-scope.mjs";
11
12
  import {
12
13
  recordTaskSucceeded,
@@ -27,6 +28,12 @@ import { laneTaskBranch, laneWorktreePath } from "../worktree.mjs";
27
28
  * @param {{ laneNumber?: number }} [params.lane]
28
29
  */
29
30
  export function recordLaneTaskMetric({ projectRoot, batchId, task, config, taskFolder, lane }) {
31
+ // SP-879 (#338): attach provider-reported worker usage from the sidecar the
32
+ // runner wrote after the pi JSON run. Skipped tasks never ran a worker, so
33
+ // they must not inherit a stale committed sidecar from an earlier batch.
34
+ if (resolveTaskMetricOutcome(task) !== "skipped") {
35
+ attachTaskUsageFromSidecar({ taskFolder, task });
36
+ }
30
37
  const metricParams = {
31
38
  projectRoot,
32
39
  batchId,
@@ -38,6 +45,52 @@ export function recordLaneTaskMetric({ projectRoot, batchId, task, config, taskF
38
45
  recordTaskTerminalMetric(metricParams);
39
46
  }
40
47
 
48
+ /** Sidecar filename the worker runner writes after a pi JSON run (bin/spine-worker-runner.mjs). Keep both definitions in sync. */
49
+ const WORKER_USAGE_SIDECAR_FILENAME = "worker-usage.json";
50
+ const WORKER_USAGE_KEYS = ["tokensIn", "tokensOut", "estimatedUsd"];
51
+
52
+ /**
53
+ * Copy finite worker usage counters from the runner's `worker-usage.json`
54
+ * sidecar onto the task object before the metric record is built
55
+ * (`buildTaskMetricRecord` copies finite `task.tokens*` / `task.estimatedUsd`).
56
+ *
57
+ * Lenient by design: a missing, malformed, or partially valid sidecar never
58
+ * throws and never invents values — only present, finite, non-negative
59
+ * numbers are copied, and existing finite task fields win.
60
+ *
61
+ * @param {object} params
62
+ * @param {string} [params.taskFolder]
63
+ * @param {Record<string, any>} params.task
64
+ * @returns {boolean} true when at least one usage field was attached.
65
+ */
66
+ export function attachTaskUsageFromSidecar({ taskFolder, task }) {
67
+ if (!taskFolder || !task) return false;
68
+ const sidecarPath = path.join(taskFolder, WORKER_USAGE_SIDECAR_FILENAME);
69
+ let raw;
70
+ try {
71
+ if (!fs.existsSync(sidecarPath)) return false;
72
+ raw = fs.readFileSync(sidecarPath, "utf-8");
73
+ } catch {
74
+ return false;
75
+ }
76
+ let parsed;
77
+ try {
78
+ parsed = JSON.parse(raw);
79
+ } catch {
80
+ return false;
81
+ }
82
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return false;
83
+ let attached = false;
84
+ for (const key of WORKER_USAGE_KEYS) {
85
+ const value = parsed[key];
86
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0 && !Number.isFinite(task[key])) {
87
+ task[key] = value;
88
+ attached = true;
89
+ }
90
+ }
91
+ return attached;
92
+ }
93
+
41
94
  /**
42
95
  * @param {string} taskFolderPath
43
96
  * @returns {{ ok: true, fileScopePaths: string[] } | { ok: false, error: string, errors?: string[], promptPath: string }}
@@ -35,20 +35,47 @@ import {
35
35
  * Step number containing a plan review checkpoint marker, else the lowest step.
36
36
  * Local mirror of findCodeReviewStepNumber for the engine plan phase (SP-695).
37
37
  *
38
+ * SP-874 / #294: this is the LAST step of {@link findPlanReviewStepOrder} —
39
+ * the checkpoint (or fallback) step the phase reviews after the step-0
40
+ * (minimum-step) review has run and approved.
41
+ *
38
42
  * @param {string} taskFolder
39
43
  */
40
44
  function findPlanReviewStepNumber(taskFolder) {
45
+ return findPlanReviewStepOrder(taskFolder).at(-1) ?? 0;
46
+ }
47
+
48
+ /**
49
+ * Ordered plan-review steps for the engine phase (SP-874 / #294): the minimum
50
+ * step (step 0) first, then any explicit plan-review checkpoint step. A packet
51
+ * that declares a plan-review checkpoint at a later step must not silently
52
+ * drop the required step-0 plan review — step 0 is queued before the later
53
+ * checkpoint review so no later-step plan review runs while step 0 is
54
+ * unreviewed (#294 Expected item 1).
55
+ *
56
+ * - No PROMPT.md or no `### Step N` blocks → `[0]`.
57
+ * - No plan-review checkpoint marker → `[minStep]` (unchanged SP-695 fallback).
58
+ * - Checkpoint at C: `C > min` → `[min, C]`; `C <= min` → `[C]` (unchanged).
59
+ *
60
+ * @param {string} taskFolder
61
+ * @returns {number[]}
62
+ */
63
+ export function findPlanReviewStepOrder(taskFolder) {
41
64
  const promptPath = path.join(taskFolder, "PROMPT.md");
42
- if (!fs.existsSync(promptPath)) return 0;
65
+ if (!fs.existsSync(promptPath)) return [0];
43
66
  const content = fs.readFileSync(promptPath, "utf-8");
44
67
  const stepBlocks = [...content.matchAll(/###\s+Step\s+(\d+)[:\s][\s\S]*?(?=###\s+Step\s+\d+|$)/g)];
68
+ if (stepBlocks.length === 0) return [0];
69
+ const minStep = Math.min(...stepBlocks.map((match) => Number(match[1])));
70
+ let checkpointStep = null;
45
71
  for (const match of stepBlocks) {
46
72
  if (/plan[-\s]review\s+checkpoint/i.test(match[0])) {
47
- return Number(match[1]);
73
+ checkpointStep = Number(match[1]);
74
+ break;
48
75
  }
49
76
  }
50
- if (stepBlocks.length === 0) return 0;
51
- return Math.min(...stepBlocks.map((match) => Number(match[1])));
77
+ if (checkpointStep == null) return [minStep];
78
+ return checkpointStep > minStep ? [minStep, checkpointStep] : [checkpointStep];
52
79
  }
53
80
 
54
81
  /**
@@ -60,6 +87,7 @@ function findPlanReviewStepNumber(taskFolder) {
60
87
  * @param {string} params.taskFolder
61
88
  * @param {Array<Record<string, any>>} [params.journalEvents]
62
89
  * @param {string} [params.taskId]
90
+ * @param {number} [params.stepNumber] Restrict the scan to this step's verdict (SP-874 / #294 ordering).
63
91
  * @param {string} [params.worktreePath] Lane worktree used to resolve relative artifact paths.
64
92
  * @param {boolean} [params.stubMode] Whether the batch runs in review-stub mode (see isHonorableReviewEvent).
65
93
  * @param {(event: Record<string, any>, reason: string) => void} [params.onReject] Invoked once per journal event refused by the honor guard.
@@ -69,6 +97,7 @@ function findCompletedPlanReview({
69
97
  taskFolder,
70
98
  journalEvents = [],
71
99
  taskId,
100
+ stepNumber,
72
101
  worktreePath,
73
102
  stubMode,
74
103
  onReject,
@@ -81,6 +110,11 @@ function findCompletedPlanReview({
81
110
  if (event.type !== "review.completed") continue;
82
111
  const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
83
112
  if (payload.reviewType !== "plan") continue;
113
+ // SP-874 / #294 ordering: a later-step plan verdict must not satisfy an
114
+ // earlier step's gate — events that declare a step must match the scan's
115
+ // step exactly. Legacy events without a stepNumber cannot claim a later
116
+ // step and stay honorable for the phase's target step.
117
+ if (stepNumber != null && payload.stepNumber != null && payload.stepNumber !== stepNumber) continue;
84
118
  const verdict = normalizeCodeVerdict(payload.verdict);
85
119
  if (!verdict) continue;
86
120
  const honorGuard = isHonorableReviewEvent(event, { taskFolder, worktreePath, stubMode });
@@ -104,8 +138,8 @@ function findCompletedPlanReview({
104
138
  return result;
105
139
  }
106
140
 
107
- const stepNumber = findPlanReviewStepNumber(taskFolder);
108
- const latestArtifact = findLatestStepReviewArtifact(taskFolder, stepNumber);
141
+ const artifactStepNumber = stepNumber ?? findPlanReviewStepNumber(taskFolder);
142
+ const latestArtifact = findLatestStepReviewArtifact(taskFolder, artifactStepNumber);
109
143
  if (latestArtifact) {
110
144
  const reviewContent = fs.readFileSync(latestArtifact.artifactPath, "utf-8");
111
145
  const { verdict, feedback } = parseReviewVerdict(reviewContent, { reviewType: "plan" });
@@ -139,6 +173,7 @@ function findCompletedPlanReview({
139
173
  * @param {number} [params.attempt]
140
174
  * @param {Record<string, any>} [params.journal]
141
175
  * @param {{ next: () => string } | null} [params.stubVerdicts]
176
+ * @param {number} [params.planReviewStep] Explicit plan-review step override (SP-874 / #294 ordering); defaults to findPlanReviewStepNumber.
142
177
  * @returns {Promise<{ ok: boolean, [key: string]: any }>}
143
178
  */
144
179
  export async function runEnginePlanReview({
@@ -148,6 +183,7 @@ export async function runEnginePlanReview({
148
183
  attempt = 1,
149
184
  journal,
150
185
  stubVerdicts = null,
186
+ planReviewStep,
151
187
  }) {
152
188
  const reviewLevel = readReviewLevel(taskFolder);
153
189
  if (!isReviewTypeRequired(reviewLevel, "plan")) {
@@ -163,7 +199,7 @@ export async function runEnginePlanReview({
163
199
  };
164
200
  }
165
201
 
166
- const stepNumber = findPlanReviewStepNumber(taskFolder);
202
+ const stepNumber = planReviewStep ?? findPlanReviewStepNumber(taskFolder);
167
203
  const artifactPath = buildReviewArtifactPath(taskFolder, stepNumber);
168
204
  const useStub = shouldUseReviewStub();
169
205
 
@@ -280,6 +316,13 @@ function recordPlanReviewTaskFailure({
280
316
  * existing plan artifact/journal verdict, rework loop on REVISE, fail-closed
281
317
  * on exhaustion or invalid verdict.
282
318
  *
319
+ * SP-874 / #294: plan reviews are queued via findPlanReviewStepOrder — the
320
+ * step-0 (minimum-step) review is scheduled BEFORE any later-step
321
+ * (plan-review checkpoint) review for the same task/lane. Each queued step
322
+ * runs the honor fast-path then the review/rework poll loop; a spawn failure
323
+ * or exhausted rework loop at any step fails the task closed (the remaining
324
+ * schedule is not silently skipped).
325
+ *
283
326
  * Params: projectRoot, state, batchId, config, task, lane,
284
327
  * taskFolderInWorktree, wt, taskBranch, laneCorrelationId, fileScopePaths.
285
328
  * Loosely typed because callers may forward a shared params bag
@@ -315,48 +358,68 @@ export async function runPlanReviewPhase({
315
358
 
316
359
  // Materialize the stub queue once per phase and pass it via params so
317
360
  // parallel lanes never share or mutate process.env stub state (SP-728).
361
+ // The queue spans the whole ordered schedule (SP-874): verdicts pop in
362
+ // order across steps, never reset per step.
318
363
  const stubVerdicts = shouldUseReviewStub() ? createPhaseStubVerdictQueue("plan") : null;
319
364
 
320
- const journalEvents = readJournalEvents(projectRoot, batchId);
321
- const honoredResult = honorCompletedReview({
322
- reviewType: "plan",
323
- passVerdict: "APPROVE",
324
- attemptField: "planReviewAttempts",
325
- attemptKey: "planReviewAttempt",
326
- findCompletedReview: findCompletedPlanReview,
327
- projectRoot,
328
- state,
329
- batchId,
330
- task,
331
- lane,
332
- laneCorrelationId,
333
- taskFolder: taskFolderInWorktree,
334
- journalEvents,
335
- worktreePath: wt,
336
- });
337
- if (honoredResult) return honoredResult;
365
+ // SP-874 / #294: step 0 first, then any later plan-review checkpoint step.
366
+ const planReviewSteps = findPlanReviewStepOrder(taskFolderInWorktree);
338
367
 
339
- return await runReviewPollLoop({
340
- reviewType: "plan",
341
- passVerdict: "APPROVE",
342
- attemptField: "planReviewAttempts",
343
- attemptKey: "planReviewAttempt",
344
- maxAttempts: maxPlanReviewAttempts,
345
- runEngineReview: (params) =>
346
- runEnginePlanReview(/** @type {any} */ ({ ...params, stubVerdicts })),
347
- recordReviewTaskFailure: recordPlanReviewTaskFailure,
348
- invalidVerdictOutput: "plan review artifact missing APPROVE or REVISE verdict",
349
- journalEvents,
350
- projectRoot,
351
- state,
352
- batchId,
353
- config,
354
- task,
355
- lane,
356
- taskFolderInWorktree,
357
- wt,
358
- taskBranch,
359
- laneCorrelationId,
360
- fileScopePaths,
361
- });
368
+ /** @type {{ ok: boolean, [key: string]: any }} */
369
+ let phaseResult = { ok: true };
370
+ for (const planReviewStep of planReviewSteps) {
371
+ // Re-read per step so the next step's honor scan sees verdicts the
372
+ // previous step just recorded.
373
+ const journalEvents = readJournalEvents(projectRoot, batchId);
374
+ const honoredResult = honorCompletedReview({
375
+ reviewType: "plan",
376
+ passVerdict: "APPROVE",
377
+ attemptField: "planReviewAttempts",
378
+ attemptKey: "planReviewAttempt",
379
+ findCompletedReview: (/** @type {Record<string, any>} */ finderParams) =>
380
+ findCompletedPlanReview(/** @type {any} */ ({ ...finderParams, stepNumber: planReviewStep })),
381
+ projectRoot,
382
+ state,
383
+ batchId,
384
+ task,
385
+ lane,
386
+ laneCorrelationId,
387
+ taskFolder: taskFolderInWorktree,
388
+ journalEvents,
389
+ worktreePath: wt,
390
+ });
391
+ if (honoredResult) {
392
+ phaseResult = honoredResult;
393
+ continue;
394
+ }
395
+
396
+ phaseResult = await runReviewPollLoop({
397
+ reviewType: "plan",
398
+ passVerdict: "APPROVE",
399
+ attemptField: "planReviewAttempts",
400
+ attemptKey: "planReviewAttempt",
401
+ maxAttempts: maxPlanReviewAttempts,
402
+ runEngineReview: (params) =>
403
+ runEnginePlanReview(/** @type {any} */ ({ ...params, stubVerdicts, planReviewStep })),
404
+ recordReviewTaskFailure: recordPlanReviewTaskFailure,
405
+ invalidVerdictOutput: "plan review artifact missing APPROVE or REVISE verdict",
406
+ journalEvents,
407
+ projectRoot,
408
+ state,
409
+ batchId,
410
+ config,
411
+ task,
412
+ lane,
413
+ taskFolderInWorktree,
414
+ wt,
415
+ taskBranch,
416
+ laneCorrelationId,
417
+ fileScopePaths,
418
+ });
419
+ // Fail-closed (#294 item 2): a spawn failure, exhausted rework loop, or
420
+ // invalid verdict at any queued step stops the schedule — later-step
421
+ // plan reviews must not run while an earlier step is unreviewed.
422
+ if (!phaseResult.ok) return phaseResult;
423
+ }
424
+ return phaseResult;
362
425
  }
@@ -336,6 +336,8 @@ export async function runReviewPollLoop({
336
336
  ? `${reviewType}_review_provider_error`
337
337
  : `${reviewType}_review_spawn_failed`;
338
338
  // SP-837 (#325): one reviewer row per spawn failure / timeout / provider error.
339
+ // SP-880 (#338): forward spawn-result usage so failed reviewer spawns still
340
+ // attribute the tokens pi reported before failing (omitted when none).
339
341
  recordReviewMetric({
340
342
  projectRoot,
341
343
  config,
@@ -352,6 +354,7 @@ export async function runReviewPollLoop({
352
354
  ? "provider_error"
353
355
  : "spawn_failed",
354
356
  failureReason: typeof reviewResult.reason === "string" ? reviewResult.reason : undefined,
357
+ usage: reviewResult.usage,
355
358
  });
356
359
  recordReviewTaskFailure({
357
360
  projectRoot,
@@ -389,6 +392,8 @@ export async function runReviewPollLoop({
389
392
  [attemptKey]: reviewAttempt + 1,
390
393
  });
391
394
  // SP-837 (#325): one reviewer row per recorded verdict (attempt is 1-based).
395
+ // SP-880 (#338): usage rides on the engine-review result (originating from
396
+ // the reviewer pi JSON stream) so verdict rows attribute cost by role/model.
392
397
  recordReviewMetric({
393
398
  projectRoot,
394
399
  config,
@@ -400,6 +405,7 @@ export async function runReviewPollLoop({
400
405
  attempt: reviewAttempt + 1,
401
406
  durationMs: Date.now() - reviewStartedAt,
402
407
  outcome: "verdict",
408
+ usage: reviewResult.usage,
403
409
  });
404
410
 
405
411
  if (reviewResult.verdict === passVerdict) {