pi-spine 2.32.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.
@@ -115,48 +115,6 @@ export function syncPersistedClassifications({ projectRoot, state }) {
115
115
  return { changed };
116
116
  }
117
117
 
118
- /** @param {string} projectRoot */
119
- function isInsideGitRepo(projectRoot) {
120
- try {
121
- execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
122
- cwd: projectRoot,
123
- stdio: ["ignore", "pipe", "pipe"],
124
- timeout: 5000,
125
- });
126
- return true;
127
- } catch {
128
- return false;
129
- }
130
- }
131
-
132
- /** @param {string} projectRoot @param {string} ref */
133
- function gitRefExists(projectRoot, ref) {
134
- try {
135
- execFileSync("git", ["rev-parse", "--verify", ref], {
136
- cwd: projectRoot,
137
- stdio: ["ignore", "pipe", "pipe"],
138
- timeout: 5000,
139
- });
140
- return true;
141
- } catch {
142
- return false;
143
- }
144
- }
145
-
146
- /** @param {string} projectRoot @param {string} ancestor @param {string} descendant */
147
- function gitIsAncestor(projectRoot, ancestor, descendant) {
148
- try {
149
- execFileSync("git", ["merge-base", "--is-ancestor", ancestor, descendant], {
150
- cwd: projectRoot,
151
- stdio: ["ignore", "pipe", "pipe"],
152
- timeout: 5000,
153
- });
154
- return true;
155
- } catch {
156
- return false;
157
- }
158
- }
159
-
160
118
  /** @param {Record<string, any>} result @param {unknown} err @param {string} context */
161
119
  function recordGitInspectionError(result, err, context) {
162
120
  const message = err instanceof Error ? err.message : String(err);
@@ -166,30 +124,96 @@ function recordGitInspectionError(result, err, context) {
166
124
  : detail;
167
125
  }
168
126
 
169
- /** @param {string} projectRoot @param {string} batchId @returns {string[]} */
170
- function listOrchBranches(projectRoot, batchId) {
127
+ /**
128
+ * Distinguish a failed git probe from a definitive git answer (#310, fail closed).
129
+ *
130
+ * Empirically (verified against node's execFileSync): a definitive "no" — missing
131
+ * ref, not an ancestor, not a repository, missing object — exits 1 or 128 with a
132
+ * numeric `status`; a timeout surfaces as `code: "ETIMEDOUT"` + `signal: SIGTERM`;
133
+ * a missing binary is `code: "ENOENT"`. Only the latter classes are failures that
134
+ * must surface as inspection errors; ordinary "no" answers stay silent so
135
+ * reconcile does not cry git_unavailable on every repo without an orch branch.
136
+ *
137
+ * @param {unknown} err
138
+ * @returns {boolean} true when the failure is fatal (must be recorded)
139
+ */
140
+ function isFatalGitProbeFailure(err) {
141
+ if (!(err instanceof Error)) return true;
142
+ const e = /** @type {Record<string, any>} */ (err);
143
+ if (typeof e.code === "string") return true; // ETIMEDOUT, ENOENT, EACCES, …
144
+ if (e.signal) return true; // killed by signal — no definitive answer
145
+ const status = typeof e.status === "number" ? e.status : undefined;
146
+ return status !== 1 && status !== 128; // 1/128 = git ran and answered "no"
147
+ }
148
+
149
+ /**
150
+ * Run one read-only git probe (fail closed, #310). Returns execFileSync output
151
+ * (string when `capture`, truthy sentinel otherwise), or null when git answered
152
+ * "definitively no" (exit 1/128) OR the probe failed fatally. Fatal failures are
153
+ * recorded into `sink.gitInspectionError` via the existing pattern; callers keep
154
+ * their conservative false/[] semantics.
155
+ *
156
+ * @param {Record<string, any>|null} sink result object carrying gitInspectionError
157
+ * @param {string} context stable label recorded alongside the error
158
+ * @param {string} projectRoot
159
+ * @param {string[]} args git argv
160
+ * @param {boolean} [capture] capture stdout as string instead of Buffer
161
+ * @returns {string|Buffer|null}
162
+ */
163
+ function probeGit(sink, context, projectRoot, args, capture = false) {
171
164
  try {
172
- const output = execFileSync("git", ["branch", "-a", "--list", "*orch*"], {
173
- cwd: projectRoot,
174
- encoding: "utf-8",
175
- timeout: 5000,
176
- });
177
-
178
- return output
179
- .split(/\r?\n/)
180
- .map((line) => line.trim().replace(/^\*?\s+/, "").replace(/^remotes\/[^/]+\//, ""))
181
- .filter(Boolean)
182
- .filter((branch) => branch.includes(batchId));
183
- } catch {
184
- return [];
165
+ return capture
166
+ ? execFileSync("git", args, {
167
+ cwd: projectRoot,
168
+ encoding: "utf-8",
169
+ stdio: ["ignore", "pipe", "pipe"],
170
+ timeout: 5000,
171
+ })
172
+ : execFileSync("git", args, {
173
+ cwd: projectRoot,
174
+ stdio: ["ignore", "pipe", "pipe"],
175
+ timeout: 5000,
176
+ });
177
+ } catch (err) {
178
+ if (isFatalGitProbeFailure(err) && sink) {
179
+ recordGitInspectionError(sink, err, context);
180
+ }
181
+ return null;
185
182
  }
186
183
  }
187
184
 
185
+ /** @param {string} projectRoot @param {Record<string, any>} [sink] */
186
+ function isInsideGitRepo(projectRoot, sink) {
187
+ return probeGit(sink ?? null, "inside_work_tree", projectRoot, ["rev-parse", "--is-inside-work-tree"]) !== null;
188
+ }
189
+
190
+ /** @param {string} projectRoot @param {string} ref @param {Record<string, any>} [sink] */
191
+ function gitRefExists(projectRoot, ref, sink) {
192
+ return probeGit(sink ?? null, `ref_exists(${ref})`, projectRoot, ["rev-parse", "--verify", ref]) !== null;
193
+ }
194
+
195
+ /** @param {string} projectRoot @param {string} ancestor @param {string} descendant @param {Record<string, any>} [sink] */
196
+ function gitIsAncestor(projectRoot, ancestor, descendant, sink) {
197
+ return probeGit(sink ?? null, `is_ancestor(${ancestor}..${descendant})`, projectRoot, ["merge-base", "--is-ancestor", ancestor, descendant]) !== null;
198
+ }
199
+
200
+ /** @param {string} projectRoot @param {string} batchId @param {Record<string, any>} [sink] @returns {string[]} */
201
+ function listOrchBranches(projectRoot, batchId, sink) {
202
+ const output = probeGit(sink ?? null, "list_orch_branches", projectRoot, ["branch", "-a", "--list", "*orch*"], true);
203
+ if (typeof output !== "string") return [];
204
+
205
+ return output
206
+ .split(/\r?\n/)
207
+ .map((line) => line.trim().replace(/^\*?\s+/, "").replace(/^remotes\/[^/]+\//, ""))
208
+ .filter(Boolean)
209
+ .filter((branch) => branch.includes(batchId));
210
+ }
211
+
188
212
  /** @param {{ projectRoot: string, batchId: string, baseBranch: string, orchBranch: string|null }} ctx */
189
213
  export function inspectGitState(ctx) {
190
214
  const { projectRoot, batchId, baseBranch, orchBranch } = ctx;
191
215
  const result = /** @type {Record<string, any>} */ ({
192
- inGitRepo: isInsideGitRepo(projectRoot),
216
+ inGitRepo: false,
193
217
  baseBranch,
194
218
  orchBranch,
195
219
  orchBranches: [],
@@ -199,6 +223,7 @@ export function inspectGitState(ctx) {
199
223
  orchCommitsAhead: null,
200
224
  gitInspectionError: null,
201
225
  });
226
+ result.inGitRepo = isInsideGitRepo(projectRoot, result);
202
227
 
203
228
  if (!result.inGitRepo) return result;
204
229
 
@@ -207,25 +232,25 @@ export function inspectGitState(ctx) {
207
232
  return result;
208
233
  }
209
234
 
210
- const candidates = new Set(listOrchBranches(projectRoot, batchId));
235
+ const candidates = new Set(listOrchBranches(projectRoot, batchId, result));
211
236
  if (orchBranch) candidates.add(orchBranch);
212
- candidates.add(`orch/cdelgado-${batchId}`);
213
- candidates.add(`orch/spine-*-${batchId}`.replace("*", "operator"));
237
+ // Generic orch branch naming convention only — never per-user patterns (#310).
238
+ candidates.add(`orch/spine-${batchId}`);
214
239
 
215
240
  result.orchBranches = [...candidates].filter((branch) => !branch.includes("*"));
216
241
 
217
242
  for (const branch of result.orchBranches) {
218
- if (!gitRefExists(projectRoot, branch)) continue;
243
+ if (!gitRefExists(projectRoot, branch, result)) continue;
219
244
  result.orchBranchExists = true;
220
- if (gitIsAncestor(projectRoot, branch, baseBranch)) {
245
+ if (gitIsAncestor(projectRoot, branch, baseBranch, result)) {
221
246
  result.orchMergedToBase = true;
222
247
  result.mergedOrchBranch = branch;
223
248
  break;
224
249
  }
225
250
  }
226
251
 
227
- const resolvedOrch = orchBranch && gitRefExists(projectRoot, orchBranch) ? orchBranch : result.mergedOrchBranch;
228
- if (resolvedOrch && gitRefExists(projectRoot, resolvedOrch) && !result.orchMergedToBase) {
252
+ const resolvedOrch = orchBranch && gitRefExists(projectRoot, orchBranch, result) ? orchBranch : result.mergedOrchBranch;
253
+ if (resolvedOrch && gitRefExists(projectRoot, resolvedOrch, result) && !result.orchMergedToBase) {
229
254
  try {
230
255
  result.orchCommitsAhead = countCommitsAhead(projectRoot, baseBranch, resolvedOrch);
231
256
  } catch (err) {
@@ -258,90 +283,60 @@ export function inspectGitState(ctx) {
258
283
  return result;
259
284
  }
260
285
 
261
- /** @param {string} projectRoot @param {string} refA @param {string} refB @returns {string[]} */
262
- export function listGitChangedPaths(projectRoot, refA, refB) {
286
+ /** @param {string} projectRoot @param {string} refA @param {string} refB @param {Record<string, any>} [sink] @returns {string[]} */
287
+ export function listGitChangedPaths(projectRoot, refA, refB, sink) {
263
288
  if (!refA || !refB || refA === refB) return [];
264
- try {
265
- const output = execFileSync("git", ["diff", "--name-only", `${refA}..${refB}`], {
266
- cwd: projectRoot,
267
- encoding: "utf-8",
268
- stdio: ["ignore", "pipe", "pipe"],
269
- timeout: 5000,
270
- });
271
- return output
272
- .split(/\r?\n/)
273
- .map((line) => line.trim())
274
- .filter(Boolean);
275
- } catch {
276
- return [];
277
- }
289
+ const output = probeGit(sink ?? null, `changed_paths(${refA}..${refB})`, projectRoot, ["diff", "--name-only", `${refA}..${refB}`], true);
290
+ if (typeof output !== "string") return [];
291
+ return output
292
+ .split(/\r?\n/)
293
+ .map((line) => line.trim())
294
+ .filter(Boolean);
278
295
  }
279
296
 
280
297
  /** Paths from human commits since snapshot, excluding orch ancestry.
281
- * @param {string} projectRoot @param {string|null} snapshot @param {string|null} humanHead @param {string|null} orchBranch @returns {string[]}
298
+ * @param {string} projectRoot @param {string|null} snapshot @param {string|null} humanHead @param {string|null} orchBranch @param {Record<string, any>} [sink] @returns {string[]}
282
299
  */
283
- export function listHumanOnlyPaths(projectRoot, snapshot, humanHead, orchBranch) {
300
+ export function listHumanOnlyPaths(projectRoot, snapshot, humanHead, orchBranch, sink) {
284
301
  if (!snapshot || !humanHead || snapshot === humanHead) return [];
285
302
  const args = ["log", "--name-only", "--pretty=format:", `${snapshot}..${humanHead}`];
286
- if (orchBranch && gitRefExists(projectRoot, orchBranch)) {
303
+ if (orchBranch && gitRefExists(projectRoot, orchBranch, sink)) {
287
304
  args.push("--not", orchBranch);
288
305
  }
289
- try {
290
- const output = execFileSync("git", args, {
291
- cwd: projectRoot,
292
- encoding: "utf-8",
293
- stdio: ["ignore", "pipe", "pipe"],
294
- timeout: 5000,
295
- });
296
- return [...new Set(output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean))];
297
- } catch {
298
- return [];
299
- }
306
+ const output = probeGit(sink ?? null, `human_only_paths(${snapshot}..${humanHead})`, projectRoot, args, true);
307
+ if (typeof output !== "string") return [];
308
+ return [...new Set(output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean))];
300
309
  }
301
310
 
302
311
  /**
303
312
  * Paths touched on both sides only overlap when their contents differ: the same
304
313
  * template sync landing on main and orch is not a divergence. One `git diff`
305
- * call covers every candidate; a git failure keeps all candidates (fail closed).
314
+ * call covers every candidate; a definitive "no" answer narrows candidates,
315
+ * while a fatal failure (timeout, crash) keeps all candidates (fail closed) and
316
+ * is recorded into the inspection error (#310).
306
317
  *
307
318
  * @param {string} projectRoot @param {string} humanRef @param {string} orchRef @param {string[]} candidatePaths
319
+ * @param {Record<string, any>} [sink]
308
320
  * @returns {string[]}
309
321
  */
310
- function keepPathsWithDifferentContent(projectRoot, humanRef, orchRef, candidatePaths) {
322
+ function keepPathsWithDifferentContent(projectRoot, humanRef, orchRef, candidatePaths, sink) {
311
323
  if (candidatePaths.length === 0 || !orchRef) return candidatePaths;
312
- try {
313
- const output = execFileSync("git", ["diff", "--name-only", humanRef, orchRef, "--", ...candidatePaths], {
314
- cwd: projectRoot,
315
- encoding: "utf-8",
316
- stdio: ["ignore", "pipe", "pipe"],
317
- timeout: 5000,
318
- });
319
- const differing = new Set(output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
320
- return candidatePaths.filter((filePath) => differing.has(filePath));
321
- } catch {
322
- return candidatePaths;
323
- }
324
+ const output = probeGit(sink ?? null, `diff_content(${humanRef}..${orchRef})`, projectRoot, ["diff", "--name-only", humanRef, orchRef, "--", ...candidatePaths], true);
325
+ if (typeof output !== "string") return candidatePaths;
326
+ const differing = new Set(output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
327
+ return candidatePaths.filter((filePath) => differing.has(filePath));
324
328
  }
325
329
 
326
- /** @param {string} projectRoot @param {string} ref @param {string} filePath */
327
- function pathExistsAtRef(projectRoot, ref, filePath) {
328
- try {
329
- execFileSync("git", ["cat-file", "-e", `${ref}:${filePath}`], {
330
- cwd: projectRoot,
331
- stdio: ["ignore", "pipe", "pipe"],
332
- timeout: 5000,
333
- });
334
- return true;
335
- } catch {
336
- return false;
337
- }
330
+ /** @param {string} projectRoot @param {string} ref @param {string} filePath @param {Record<string, any>} [sink] */
331
+ function pathExistsAtRef(projectRoot, ref, filePath, sink) {
332
+ return probeGit(sink ?? null, `path_exists(${ref}:${filePath})`, projectRoot, ["cat-file", "-e", `${ref}:${filePath}`]) !== null;
338
333
  }
339
334
 
340
- /** @param {string} projectRoot @param {string} baseTip @param {string} snapshot */
341
- function humanCheckoutNeedsPathSync(projectRoot, baseTip, snapshot) {
342
- const landPaths = listGitChangedPaths(projectRoot, snapshot, baseTip);
335
+ /** @param {string} projectRoot @param {string} baseTip @param {string} snapshot @param {Record<string, any>} [sink] */
336
+ function humanCheckoutNeedsPathSync(projectRoot, baseTip, snapshot, sink) {
337
+ const landPaths = listGitChangedPaths(projectRoot, snapshot, baseTip, sink);
343
338
  for (const filePath of landPaths) {
344
- if (!pathExistsAtRef(projectRoot, baseTip, filePath)) continue;
339
+ if (!pathExistsAtRef(projectRoot, baseTip, filePath, sink)) continue;
345
340
  if (!fs.existsSync(path.join(projectRoot, filePath))) {
346
341
  return true;
347
342
  }
@@ -359,22 +354,11 @@ export function inspectHumanBaseSync(ctx) {
359
354
  const snapshot = String(baseBranchHeadAtStart ?? "").trim();
360
355
  if (!snapshot) return null;
361
356
 
362
- let baseTip = "";
363
- let humanHead = "";
364
- try {
365
- baseTip = execFileSync("git", ["rev-parse", baseBranch], {
366
- cwd: projectRoot,
367
- encoding: "utf-8",
368
- timeout: 5000,
369
- }).trim();
370
- humanHead = execFileSync("git", ["rev-parse", "HEAD"], {
371
- cwd: projectRoot,
372
- encoding: "utf-8",
373
- timeout: 5000,
374
- }).trim();
375
- } catch {
376
- return null;
377
- }
357
+ let baseTip = probeGit(git, `rev_parse(${baseBranch})`, projectRoot, ["rev-parse", baseBranch], true);
358
+ let humanHead = probeGit(git, "rev_parse(HEAD)", projectRoot, ["rev-parse", "HEAD"], true);
359
+ if (typeof baseTip !== "string" || typeof humanHead !== "string") return null;
360
+ baseTip = baseTip.trim();
361
+ humanHead = humanHead.trim();
378
362
 
379
363
  const integrateCompleted = Array.isArray(journalEvents)
380
364
  ? journalEvents.some((/** @type {any} */ event) => event.type === "integrate.completed")
@@ -382,34 +366,37 @@ export function inspectHumanBaseSync(ctx) {
382
366
  const landSucceeded =
383
367
  git.orchMergedToBase ||
384
368
  integrateCompleted ||
385
- (baseTip !== snapshot && gitIsAncestor(projectRoot, snapshot, baseTip));
369
+ (baseTip !== snapshot && gitIsAncestor(projectRoot, snapshot, baseTip, git));
386
370
 
387
371
  const resolvedOrch =
388
- orchBranch && gitRefExists(projectRoot, orchBranch)
372
+ orchBranch && gitRefExists(projectRoot, orchBranch, git)
389
373
  ? orchBranch
390
- : git.mergedOrchBranch && gitRefExists(projectRoot, git.mergedOrchBranch)
374
+ : git.mergedOrchBranch && gitRefExists(projectRoot, git.mergedOrchBranch, git)
391
375
  ? git.mergedOrchBranch
392
376
  : null;
393
377
 
394
378
  const branchResult = resolveCurrentGitBranch(projectRoot);
379
+ if (branchResult.error) {
380
+ recordGitInspectionError(git, new Error(branchResult.error), "current_branch");
381
+ }
395
382
  const onBaseBranch = branchResult.branch === baseBranch;
396
383
 
397
384
  const humanSinceSnapshot =
398
385
  onBaseBranch &&
399
- gitIsAncestor(projectRoot, snapshot, humanHead) &&
386
+ gitIsAncestor(projectRoot, snapshot, humanHead, git) &&
400
387
  humanHead !== snapshot;
401
388
  const humanPaths = humanSinceSnapshot
402
- ? listHumanOnlyPaths(projectRoot, snapshot, humanHead, resolvedOrch)
389
+ ? listHumanOnlyPaths(projectRoot, snapshot, humanHead, resolvedOrch, git)
403
390
  : [];
404
- const landPaths = landSucceeded ? listGitChangedPaths(projectRoot, snapshot, baseTip) : [];
391
+ const landPaths = landSucceeded ? listGitChangedPaths(projectRoot, snapshot, baseTip, git) : [];
405
392
  const orchPaths =
406
- resolvedOrch && gitRefExists(projectRoot, resolvedOrch)
407
- ? listGitChangedPaths(projectRoot, snapshot, resolvedOrch)
393
+ resolvedOrch && gitRefExists(projectRoot, resolvedOrch, git)
394
+ ? listGitChangedPaths(projectRoot, snapshot, resolvedOrch, git)
408
395
  : landPaths;
409
396
  const orchPathSet = new Set(orchPaths);
410
397
  const touchedByBoth = humanPaths.filter((filePath) => orchPathSet.has(filePath));
411
398
  const orchContentRef = resolvedOrch ?? baseTip;
412
- const overlapPaths = keepPathsWithDifferentContent(projectRoot, humanHead, orchContentRef, touchedByBoth);
399
+ const overlapPaths = keepPathsWithDifferentContent(projectRoot, humanHead, orchContentRef, touchedByBoth, git);
413
400
 
414
401
  if (overlapPaths.length > 0) {
415
402
  return {
@@ -428,24 +415,19 @@ export function inspectHumanBaseSync(ctx) {
428
415
  if (!landSucceeded) return null;
429
416
 
430
417
  const needsCommitSync =
431
- humanHead !== baseTip && onBaseBranch && gitIsAncestor(projectRoot, humanHead, baseTip);
418
+ humanHead !== baseTip && onBaseBranch && gitIsAncestor(projectRoot, humanHead, baseTip, git);
432
419
  const needsPathSync =
433
- onBaseBranch && humanHead === baseTip && humanCheckoutNeedsPathSync(projectRoot, baseTip, snapshot);
420
+ onBaseBranch && humanHead === baseTip && humanCheckoutNeedsPathSync(projectRoot, baseTip, snapshot, git);
434
421
 
435
422
  if (!needsCommitSync && !needsPathSync) {
436
423
  if (!onBaseBranch) {
437
- const mergeBase = (() => {
438
- try {
439
- return execFileSync("git", ["merge-base", humanHead, baseTip], {
440
- cwd: projectRoot,
441
- encoding: "utf-8",
442
- timeout: 5000,
443
- }).trim();
444
- } catch {
445
- return "";
446
- }
447
- })();
448
- if (mergeBase && mergeBase !== baseTip && gitIsAncestor(projectRoot, mergeBase, baseTip)) {
424
+ const mergeBase = probeGit(git, "merge_base", projectRoot, ["merge-base", humanHead, baseTip], true);
425
+ if (
426
+ typeof mergeBase === "string" &&
427
+ mergeBase.trim() &&
428
+ mergeBase.trim() !== baseTip &&
429
+ gitIsAncestor(projectRoot, mergeBase.trim(), baseTip, git)
430
+ ) {
449
431
  return {
450
432
  diagnosis: "integrate_isolated_ok",
451
433
  headline: `${baseBranch} advanced during batch; feature branch needs sync`,
@@ -18,6 +18,10 @@ import {
18
18
  redactWorkerOutput,
19
19
  resolveWorkerOutputConfig,
20
20
  } from "./worker-output.mjs";
21
+ import {
22
+ extractTextFromPiJsonStream,
23
+ sumUsageFromPiJsonStream,
24
+ } from "./pi-json-usage.mjs";
21
25
  import {
22
26
  parseTaskSizeFromFolder,
23
27
  resolveReviewArtifactPollIntervalMs,
@@ -115,6 +119,10 @@ function reviewerPiCommandExists(cmd) {
115
119
  * extensions, so reviewers keep read/bash/write. `agents.reviewer.loadUserExtensions: true`
116
120
  * opts back into user extensions.
117
121
  *
122
+ * SP-880 / #338: reviewers run `--mode json` so pi's per-message `usage`/`cost` reaches
123
+ * {@link spawnReviewerPi}, which sums it into the spawn result; human-readable reviewer text
124
+ * is recovered from the stream's `message_end` events instead of discarded.
125
+ *
118
126
  * @param {object} params
119
127
  */
120
128
  export function buildReviewerPiArgs({
@@ -133,7 +141,7 @@ export function buildReviewerPiArgs({
133
141
  if (config?.agents?.reviewer?.loadUserExtensions !== true) {
134
142
  piArgs.push("-ne");
135
143
  }
136
- piArgs.push("-p", "--no-session");
144
+ piArgs.push("-p", "--no-session", "--mode", "json");
137
145
  if (reviewerAgentPath && fs.existsSync(reviewerAgentPath)) {
138
146
  piArgs.push("--append-system-prompt", reviewerAgentPath);
139
147
  }
@@ -211,9 +219,38 @@ export function isEarlyArtifactHonorAllowed(reviewType, contractVerifyResult) {
211
219
  return true;
212
220
  }
213
221
 
222
+ /**
223
+ * Human-readable stdout tail for a reviewer spawn (SP-880 / #338).
224
+ *
225
+ * Reviewers run `pi --mode json`, so raw stdout is JSONL events. The tail
226
+ * carries the assistant text recovered from `message_end` events instead of
227
+ * JSON noise. When the stream yields no text — plain-text output, or a JSON
228
+ * stream cut before any assistant message ended — the raw (redacted) tail is
229
+ * kept so pre-stream diagnostics stay explainable.
230
+ *
231
+ * @param {string} raw
232
+ * @param {{ maxBytes: number }} outputConfig
233
+ * @returns {string}
234
+ */
235
+ function buildReviewerHumanStdoutTail(raw, outputConfig) {
236
+ if (!raw) return "";
237
+ let segments;
238
+ try {
239
+ segments = extractTextFromPiJsonStream(raw);
240
+ } catch {
241
+ segments = [];
242
+ }
243
+ if (segments.length === 0) return redactWorkerOutput(raw, outputConfig);
244
+ return redactWorkerOutput(segments.join("\n\n"), outputConfig);
245
+ }
246
+
214
247
  /**
215
248
  * @param {object} params
216
249
  * @returns {Promise<object>} Resolves with the reviewer spawn result (real async child-process wait).
250
+ *
251
+ * The result carries `usage` (`{tokensIn?, tokensOut?, estimatedUsd?}`, SP-880 / #338) summed
252
+ * from the pi JSON stream via the SP-878 parser whenever pi reported at least one finite
253
+ * value; the key is omitted entirely when pi reported none so rows never invent usage.
217
254
  */
218
255
  export function spawnReviewerPi({
219
256
  worktreePath,
@@ -271,6 +308,10 @@ export function spawnReviewerPi({
271
308
 
272
309
  let stdout = "";
273
310
  let stderr = "";
311
+ // Raw JSONL capture, bounded like stdout so a chatty reviewer child cannot
312
+ // grow engine memory without bound. Truncated leading/partial lines are
313
+ // skipped by the SP-878 parser (it ignores non-JSON records).
314
+ let jsonStream = "";
274
315
  let timedOut = false;
275
316
  let settled = false;
276
317
  let killTimer = /** @type {NodeJS.Timeout|undefined} */ (undefined);
@@ -282,18 +323,22 @@ export function spawnReviewerPi({
282
323
  clearTimeout(timer);
283
324
  clearInterval(pollTimer);
284
325
  clearTimeout(killTimer);
326
+ // SP-880 / #338: sum provider-reported usage from the JSON stream. Only
327
+ // finite values pi actually reported appear on the result — never invented.
328
+ const usage = sumUsageFromPiJsonStream(jsonStream);
285
329
  // Every result — including exit 0 — carries capture diagnostics so the
286
330
  // engine can journal them when the reviewer produced no artifact.
287
331
  resolve({
288
332
  durationMs: Date.now() - startedAtMs,
289
333
  stdoutTail: captureWorkerOutputTail(
290
- redactWorkerOutput(stdout, outputConfig),
334
+ buildReviewerHumanStdoutTail(stdout, outputConfig),
291
335
  outputConfig,
292
336
  ),
293
337
  stderrTail: captureWorkerOutputTail(
294
338
  redactWorkerOutput(stderr, outputConfig),
295
339
  outputConfig,
296
340
  ),
341
+ ...(Object.keys(usage).length > 0 ? { usage } : {}),
297
342
  ...result,
298
343
  });
299
344
  };
@@ -333,6 +378,7 @@ export function spawnReviewerPi({
333
378
 
334
379
  child.stdout?.on("data", (chunk) => {
335
380
  stdout = appendBoundedCapture(stdout, chunk, outputConfig.maxBytes);
381
+ jsonStream = appendBoundedCapture(jsonStream, chunk, outputConfig.maxBytes);
336
382
  });
337
383
 
338
384
  child.stderr?.on("data", (chunk) => {
@@ -156,6 +156,11 @@ export function buildReviewRequest({
156
156
  `- **Step being planned:** Step ${stepNumber}: ${stepName}`,
157
157
  `- **Worktree:** ${worktreePath}`,
158
158
  "",
159
+ "## Instructions",
160
+ "This is a POST-HOC plan review: it runs AFTER the worker finished, not before work begins (#331).",
161
+ "The engine spawns this review after the lane completes, so fully checked STATUS checkboxes and a `.DONE` marker are the expected state — they are NOT evidence of premature completion and must not trigger REVISE.",
162
+ "Judge the quality of the plan and its fit to the task PROMPT (scope, dependencies, risks, success criteria), not whether implementation already happened.",
163
+ "",
159
164
  "## Output",
160
165
  `Write your review to: \`${outputPath}\``,
161
166
  "Include `### Verdict: APPROVE` or `### Verdict: REVISE` and a JSON block.",
@@ -232,6 +232,9 @@ export async function runWorker({
232
232
 
233
233
  const workerBackend = useStub ? "subprocess" : resolveWorkerBackend(config);
234
234
  const workerMode = useStub ? "stub" : workerBackend === "agentSession" ? "agentSession" : "pi";
235
+ // Preflight failure shape shared by the guards below (keeps worker-host under the 500-LOC policy).
236
+ /** @param {string} classification @param {string} output */
237
+ const failPreflight = (classification, output) => ({ ok: false, exitCode: 1, mode: workerMode, output, classification, doneFound: false });
235
238
  const useLaunchScript = Boolean(
236
239
  projectRoot ? resolveWorkerLaunchScript(projectRoot, config) : null,
237
240
  );
@@ -249,21 +252,14 @@ export async function runWorker({
249
252
  phase: "preflight",
250
253
  });
251
254
  }
252
- return {
253
- ok: false,
254
- exitCode: 1,
255
- mode: workerMode,
256
- output: reviewCheck.error ?? "review tool unavailable",
257
- classification: "review_failed",
258
- doneFound: false,
259
- };
255
+ return failPreflight("review_failed", reviewCheck.error ?? "review tool unavailable");
260
256
  }
261
257
 
262
258
  const taskSize = parseTaskSizeFromFolder(taskFolder);
263
259
  const promptPath = path.join(taskFolder, "PROMPT.md");
264
260
  const promptText = fs.existsSync(promptPath) ? fs.readFileSync(promptPath, "utf-8") : "";
265
261
  const parsedPrompt = promptText ? parsePrompt(promptText) : null;
266
- const contract = promptText ? parseContract(promptText) : { stallTimeoutMinutes: null, extendGraceOnFileScope: null, runCommand: null, testCommand: null };
262
+ const contract = promptText ? parseContract(promptText) : { stallTimeoutMinutes: null, extendGraceOnFileScope: null, runCommand: null, testCommand: null, errors: [] };
267
263
  const stallConfig = resolveStallConfigForTask({ config, taskSize, contract });
268
264
  const piTimeoutMs = resolveWorkerPiTimeoutMs({ config, taskSize, contract });
269
265
  const startedAt = Date.now();
@@ -271,6 +267,18 @@ export async function runWorker({
271
267
  const isExecute = parsedPrompt?.type === "execute";
272
268
  const runCommand = contract.runCommand || contract.testCommand;
273
269
 
270
+ // SP-877 (#319): surface parseContract() errors — execute tasks fail closed at
271
+ // preflight instead of the guaranteed-failing `echo … && exit 1` fallback; pi
272
+ // workers proceed (the contract only feeds stall budgets, which tolerate nulls).
273
+ if (contract.errors.length > 0) {
274
+ const detail = contract.errors.join("; ");
275
+ if (projectRoot && batchId) {
276
+ appendJournalEvent(projectRoot, batchId, "worker.contract_parse_failed", { taskId, laneNumber, correlationId: laneCorrelationId, errors: contract.errors, phase: "preflight" });
277
+ }
278
+ if (isExecute) return failPreflight("contract_parse_failed", `Contract parse failed: ${detail}`);
279
+ console.error(`worker-host: contract parse issues for ${taskId ?? taskFolder}: ${detail}`);
280
+ }
281
+
274
282
  // #299 (SP-801): fail closed when the pi CLI is missing rather than silently
275
283
  // falling back to the stub. Placed after the review gate so review-tool
276
284
  // unavailability keeps its `review_failed` precedence, and scoped to
@@ -286,15 +294,7 @@ export async function runWorker({
286
294
  phase: "preflight",
287
295
  });
288
296
  }
289
- return {
290
- ok: false,
291
- exitCode: 1,
292
- mode: workerMode,
293
- output:
294
- "worker requires pi on PATH (fail closed); set SPINE_WORKER_STUB=1 only for stub runs",
295
- classification: "launch_failed",
296
- doneFound: false,
297
- };
297
+ return failPreflight("launch_failed", "worker requires pi on PATH (fail closed); set SPINE_WORKER_STUB=1 only for stub runs");
298
298
  }
299
299
 
300
300
  const child = isExecute