pi-spine 2.32.0 → 2.33.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.
@@ -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) {
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Flutter analyzer / build hygiene for lane worktrees (#78).
3
+ * Extracted from lane-dirty-check.mjs so that module stays under the LOC cap.
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+
9
+ /** Flutter build output dir that can pollute unscoped `flutter analyze` (#78). */
10
+ export const FLUTTER_BUILD_DIR = "build";
11
+
12
+ /**
13
+ * @param {string} segment
14
+ * @returns {boolean}
15
+ */
16
+ export function isUnscopedFlutterAnalyzeSegment(segment) {
17
+ const trimmed = String(segment ?? "").trim().toLowerCase();
18
+ if (!/\bflutter\s+analyze\b/.test(trimmed)) {
19
+ return false;
20
+ }
21
+
22
+ const match = trimmed.match(/\bflutter\s+analyze\b(.*)$/);
23
+ if (!match) {
24
+ return false;
25
+ }
26
+
27
+ const remainder = (match[1] ?? "").trim();
28
+ if (!remainder) {
29
+ return true;
30
+ }
31
+
32
+ for (const token of remainder.split(/\s+/)) {
33
+ if (token.startsWith("-")) {
34
+ continue;
35
+ }
36
+ return false;
37
+ }
38
+
39
+ return true;
40
+ }
41
+
42
+ /**
43
+ * True when testCommand invokes unscoped `flutter analyze` (whole project tree).
44
+ * Scoped forms like `flutter analyze lib test` are excluded.
45
+ *
46
+ * @param {string} command
47
+ * @returns {boolean}
48
+ */
49
+ export function isUnscopedFlutterAnalyzeCommand(command) {
50
+ const trimmed = String(command ?? "").trim();
51
+ if (!trimmed) {
52
+ return false;
53
+ }
54
+
55
+ const segments = trimmed
56
+ .split(/&&|;/)
57
+ .map((segment) => segment.trim())
58
+ .filter(Boolean);
59
+ return segments.some((segment) => isUnscopedFlutterAnalyzeSegment(segment));
60
+ }
61
+
62
+ /**
63
+ * True when testCommand combines flutter analyze with flutter test.
64
+ *
65
+ * @param {string} command
66
+ * @returns {boolean}
67
+ */
68
+ export function isFlutterAnalyzeTestCompoundCommand(command) {
69
+ const trimmed = String(command ?? "").trim().toLowerCase();
70
+ return /\bflutter\s+analyze\b/.test(trimmed) && /\bflutter\s+test\b/.test(trimmed);
71
+ }
72
+
73
+ /**
74
+ * Whether contract verify should remove `build/` before running testCommand.
75
+ *
76
+ * @param {string} testCommand
77
+ * @param {{ contract?: { flutterAnalyzerHygiene?: boolean } }} [config]
78
+ * @returns {boolean}
79
+ */
80
+ export function shouldCleanFlutterBuildBeforeAnalyze(testCommand, config = {}) {
81
+ const enabled = config?.contract?.flutterAnalyzerHygiene ?? true;
82
+ if (!enabled) {
83
+ return false;
84
+ }
85
+ return isUnscopedFlutterAnalyzeCommand(testCommand);
86
+ }
87
+
88
+ /**
89
+ * Remove stale Flutter build artifacts so unscoped analyze does not scan SourcePackages (#78).
90
+ *
91
+ * @param {string} worktreePath
92
+ * @param {{ enabled?: boolean }} [options]
93
+ * @returns {{ cleaned: boolean, buildDir?: string, reason?: string }}
94
+ */
95
+ export function sanitizeFlutterBuildBeforeAnalyze(worktreePath, { enabled = true } = {}) {
96
+ if (!enabled) {
97
+ return { cleaned: false, reason: "disabled" };
98
+ }
99
+
100
+ const buildPath = path.join(worktreePath, FLUTTER_BUILD_DIR);
101
+ if (!fs.existsSync(buildPath)) {
102
+ return { cleaned: false, reason: "no_build_dir" };
103
+ }
104
+
105
+ fs.rmSync(buildPath, { recursive: true, force: true });
106
+ return { cleaned: true, buildDir: FLUTTER_BUILD_DIR };
107
+ }
@@ -17,6 +17,7 @@ import {
17
17
  buildHeartbeatPayloadFields,
18
18
  buildProgressSnapshotPayload,
19
19
  } from "./heartbeat-subprocess.mjs";
20
+ import { isWorkerUsageSidecarPath } from "./worker-usage-sidecar.mjs";
20
21
 
21
22
  export {
22
23
  clearGitPorcelainDebounceCache,
@@ -146,6 +147,8 @@ export function resolveScopedDirtyPaths(worktreePath, fileScopePaths, taskFolder
146
147
  let filePath = line.length > 2 && line[2] === " " ? line.slice(3) : line.slice(2);
147
148
  filePath = filePath.trim();
148
149
  const renamed = filePath.includes(" -> ") ? filePath.split(" -> ").pop()?.trim() : filePath;
150
+ // SP-881 / #380: engine-owned usage sidecar is never salvageable product dirt.
151
+ if (renamed && isWorkerUsageSidecarPath(renamed)) continue;
149
152
  if (renamed && inScope(renamed)) dirty.add(renamed);
150
153
  }
151
154
  return [...dirty].sort();
@@ -6,8 +6,6 @@
6
6
  */
7
7
 
8
8
  import { execFileSync } from "node:child_process";
9
- import fs from "node:fs";
10
- import path from "node:path";
11
9
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
12
10
  import { resolveLaneCommitKeepPaths } from "../config/spine-config-schema.mjs";
13
11
  import { resolveWorktreeSetupHook } from "../config/worktree-setup-hook.mjs";
@@ -44,6 +42,21 @@ import {
44
42
  listTrackedPorcelainPaths,
45
43
  repairSetupHookSymlinkDrift,
46
44
  } from "./lane-dirty-check-git.mjs";
45
+ import { WORKER_USAGE_SIDECAR_FILENAME } from "./worker-usage-sidecar.mjs";
46
+
47
+ export {
48
+ WORKER_USAGE_SIDECAR_FILENAME,
49
+ isWorkerUsageSidecarPath,
50
+ } from "./worker-usage-sidecar.mjs";
51
+
52
+ export {
53
+ FLUTTER_BUILD_DIR,
54
+ isFlutterAnalyzeTestCompoundCommand,
55
+ isUnscopedFlutterAnalyzeCommand,
56
+ isUnscopedFlutterAnalyzeSegment,
57
+ sanitizeFlutterBuildBeforeAnalyze,
58
+ shouldCleanFlutterBuildBeforeAnalyze,
59
+ } from "./flutter-analyzer-hygiene.mjs";
47
60
 
48
61
  /**
49
62
  * Path segments for gitignored build artifacts that npm test and similar tools
@@ -64,108 +77,11 @@ export const GITIGNORED_ARTIFACT_MARKERS = [
64
77
  ".pi-smart-router/",
65
78
  "/.spine/runtime/",
66
79
  ".spine/runtime/",
80
+ // SP-881 / #380: engine-owned usage sidecar under task folders (must not salvage-thrash)
81
+ `/${WORKER_USAGE_SIDECAR_FILENAME}`,
82
+ WORKER_USAGE_SIDECAR_FILENAME,
67
83
  ];
68
84
 
69
- /** Flutter build output dir that can pollute unscoped `flutter analyze` (#78). */
70
- export const FLUTTER_BUILD_DIR = "build";
71
-
72
- /**
73
- * @param {string} segment
74
- * @returns {boolean}
75
- */
76
- export function isUnscopedFlutterAnalyzeSegment(segment) {
77
- const trimmed = String(segment ?? "").trim().toLowerCase();
78
- if (!/\bflutter\s+analyze\b/.test(trimmed)) {
79
- return false;
80
- }
81
-
82
- const match = trimmed.match(/\bflutter\s+analyze\b(.*)$/);
83
- if (!match) {
84
- return false;
85
- }
86
-
87
- const remainder = (match[1] ?? "").trim();
88
- if (!remainder) {
89
- return true;
90
- }
91
-
92
- for (const token of remainder.split(/\s+/)) {
93
- if (token.startsWith("-")) {
94
- continue;
95
- }
96
- return false;
97
- }
98
-
99
- return true;
100
- }
101
-
102
- /**
103
- * True when testCommand invokes unscoped `flutter analyze` (whole project tree).
104
- * Scoped forms like `flutter analyze lib test` are excluded.
105
- *
106
- * @param {string} command
107
- * @returns {boolean}
108
- */
109
- export function isUnscopedFlutterAnalyzeCommand(command) {
110
- const trimmed = String(command ?? "").trim();
111
- if (!trimmed) {
112
- return false;
113
- }
114
-
115
- const segments = trimmed
116
- .split(/&&|;/)
117
- .map((segment) => segment.trim())
118
- .filter(Boolean);
119
- return segments.some((segment) => isUnscopedFlutterAnalyzeSegment(segment));
120
- }
121
-
122
- /**
123
- * True when testCommand combines flutter analyze with flutter test.
124
- *
125
- * @param {string} command
126
- * @returns {boolean}
127
- */
128
- export function isFlutterAnalyzeTestCompoundCommand(command) {
129
- const trimmed = String(command ?? "").trim().toLowerCase();
130
- return /\bflutter\s+analyze\b/.test(trimmed) && /\bflutter\s+test\b/.test(trimmed);
131
- }
132
-
133
- /**
134
- * Whether contract verify should remove `build/` before running testCommand.
135
- *
136
- * @param {string} testCommand
137
- * @param {object} [config]
138
- * @returns {boolean}
139
- */
140
- export function shouldCleanFlutterBuildBeforeAnalyze(testCommand, config = {}) {
141
- const enabled = config?.contract?.flutterAnalyzerHygiene ?? true;
142
- if (!enabled) {
143
- return false;
144
- }
145
- return isUnscopedFlutterAnalyzeCommand(testCommand);
146
- }
147
-
148
- /**
149
- * Remove stale Flutter build artifacts so unscoped analyze does not scan SourcePackages (#78).
150
- *
151
- * @param {string} worktreePath
152
- * @param {{ enabled?: boolean }} [options]
153
- * @returns {{ cleaned: boolean, buildDir?: string, reason?: string }}
154
- */
155
- export function sanitizeFlutterBuildBeforeAnalyze(worktreePath, { enabled = true } = {}) {
156
- if (!enabled) {
157
- return { cleaned: false, reason: "disabled" };
158
- }
159
-
160
- const buildPath = path.join(worktreePath, FLUTTER_BUILD_DIR);
161
- if (!fs.existsSync(buildPath)) {
162
- return { cleaned: false, reason: "no_build_dir" };
163
- }
164
-
165
- fs.rmSync(buildPath, { recursive: true, force: true });
166
- return { cleaned: true, buildDir: FLUTTER_BUILD_DIR };
167
- }
168
-
169
85
  /**
170
86
  * Restore tracked and remove untracked out-of-scope coverage before lane commit.
171
87
  *
@@ -258,6 +258,9 @@ export function resolveReviewMetricPins(config, reviewType) {
258
258
  * @param {"verdict"|"spawn_failed"|"timeout"|"provider_error"|"blocked"} [params.outcome]
259
259
  * @param {string} [params.failureReason]
260
260
  * @param {number} [params.endedAtMs]
261
+ * @param {{ tokensIn?: number, tokensOut?: number, estimatedUsd?: number }} [params.usage]
262
+ * pi `--mode json` usage totals from the reviewer spawn (SP-880 / #338). Only finite
263
+ * values are copied; absent/NaN/Infinity are omitted so rows never invent usage.
261
264
  */
262
265
  export function buildReviewMetricRecord({
263
266
  batchId,
@@ -274,6 +277,7 @@ export function buildReviewMetricRecord({
274
277
  outcome = "verdict",
275
278
  failureReason,
276
279
  endedAtMs = Date.now(),
280
+ usage,
277
281
  }) {
278
282
  /** @type {Record<string, unknown>} */
279
283
  const record = {
@@ -297,6 +301,15 @@ export function buildReviewMetricRecord({
297
301
  if (Number.isFinite(attempt)) record.attempt = attempt;
298
302
  if (Number.isFinite(durationMs)) record.durationMs = Math.max(0, /** @type {number} */ (durationMs));
299
303
  if (typeof failureReason === "string" && failureReason !== "") record.failureReason = failureReason;
304
+ // SP-880 / #338: reviewer usage totals from the pi JSON stream. Same finite
305
+ // convention as task rows; keys stay absent when pi reported nothing. The
306
+ // metrics redaction allowlist (USAGE_KEYS) keeps these fields while redacting
307
+ // the rest of the record.
308
+ if (usage !== null && typeof usage === "object") {
309
+ if (Number.isFinite(usage.tokensIn)) record.tokensIn = usage.tokensIn;
310
+ if (Number.isFinite(usage.tokensOut)) record.tokensOut = usage.tokensOut;
311
+ if (Number.isFinite(usage.estimatedUsd)) record.estimatedUsd = usage.estimatedUsd;
312
+ }
300
313
 
301
314
  return sanitizeMetricRecord(record);
302
315
  }
@@ -328,6 +341,8 @@ export function appendReviewMetric(projectRoot, record, config = {}) {
328
341
  * @param {number} [params.durationMs]
329
342
  * @param {"verdict"|"spawn_failed"|"timeout"|"provider_error"|"blocked"} [params.outcome]
330
343
  * @param {string} [params.failureReason]
344
+ * @param {{ tokensIn?: number, tokensOut?: number, estimatedUsd?: number }} [params.usage]
345
+ * pi `--mode json` usage totals from the reviewer spawn result (SP-880 / #338).
331
346
  */
332
347
  export function recordReviewMetric({ projectRoot, config = {}, model, ...rest }) {
333
348
  if (!isMetricsEnabled(config)) return null;