pi-spine 2.26.0 → 2.27.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.
Files changed (38) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-review-step.mjs +8 -1
  3. package/bin/spine-worker-runner.mjs +14 -1
  4. package/package.json +3 -3
  5. package/skills/spine-release-operator/SKILL.md +3 -0
  6. package/src/batch/batch-meta-reconstruct.mjs +3 -0
  7. package/src/batch/contract-exec.mjs +2 -2
  8. package/src/batch/contract-parse.mjs +2 -2
  9. package/src/batch/contract-prelanded.mjs +2 -2
  10. package/src/batch/diagnosis-handoff-packet.mjs +74 -0
  11. package/src/batch/diagnosis-pending-lane.mjs +34 -1
  12. package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
  13. package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
  14. package/src/batch/engine-lanes/review-code.mjs +1 -0
  15. package/src/batch/engine-lanes/review-final.mjs +83 -46
  16. package/src/batch/engine-lanes/review-plan.mjs +22 -2
  17. package/src/batch/engine-lanes/review-poll.mjs +47 -1
  18. package/src/batch/engine-lanes.mjs +6 -7
  19. package/src/batch/journal.mjs +15 -0
  20. package/src/batch/metrics.mjs +13 -1
  21. package/src/batch/provider-quota.mjs +220 -0
  22. package/src/batch/quota-fallback.mjs +319 -0
  23. package/src/batch/reconcile-diagnosis-context.mjs +22 -0
  24. package/src/batch/resume-multi-queue.mjs +25 -10
  25. package/src/batch/review-artifacts.mjs +93 -15
  26. package/src/batch/review-spawn-retry.mjs +106 -0
  27. package/src/batch/review-spawn.mjs +48 -2
  28. package/src/batch/review-step-run.mjs +96 -6
  29. package/src/batch/reviewer-output.mjs +162 -0
  30. package/src/batch/worker-host.mjs +49 -3
  31. package/src/config/cursor-rules/discover.mjs +2 -2
  32. package/src/config/cursor-rules/match-globs.mjs +6 -4
  33. package/src/config/env-overrides.mjs +41 -4
  34. package/src/config/settings-fields.mjs +6 -0
  35. package/src/config/spine-config-schema.mjs +24 -0
  36. package/src/doctor/quota-risk.mjs +45 -0
  37. package/src/planner/file-scope.mjs +6 -6
  38. package/src/tasks/packet/validate-contract.mjs +3 -3
@@ -1,14 +1,11 @@
1
1
  // @ts-nocheck
2
- /**
3
- * Review artifact discovery, level parsing, and honor-signal helpers.
4
- * SP-579 extraction from review.mjs; spawn wiring stays in review.mjs (SP-597).
5
- */
6
-
2
+ /* Review artifact discovery, level parsing, honor signals. SP-579 extraction from review.mjs. */
7
3
  import fs from "node:fs";
8
4
  import path from "node:path";
9
5
  import { detectOrphanedReviewStarted } from "./journal-rebuild.mjs";
10
6
  import { NESTED_REVIEW_SPAWN_REASON } from "./review-spawn.mjs";
11
7
  import { normalizeVerdict, parseReviewLevel, parseReviewVerdict } from "./review-shared.mjs";
8
+ import { shouldUseReviewStub } from "./engine-lanes/review-stub.mjs";
12
9
 
13
10
  /**
14
11
  * @param {string} taskFolder
@@ -70,16 +67,82 @@ export function findLatestStepReviewArtifact(taskFolder, stepNumber) {
70
67
  return candidates[0] ?? null;
71
68
  }
72
69
 
70
+ /**
71
+ * Realpath with a lexical fallback for missing targets — the guard must still
72
+ * classify a vanished foreign artifact, not crash on it.
73
+ * @param {string} candidatePath
74
+ */
75
+ function resolveRealPath(candidatePath) {
76
+ try {
77
+ return fs.realpathSync(candidatePath);
78
+ } catch {
79
+ return path.resolve(candidatePath);
80
+ }
81
+ }
82
+
83
+ /**
84
+ * True when candidatePath is inside folderPath. Both sides are realpath-resolved
85
+ * so symlinks and /var vs /private/var aliases cannot smuggle a foreign artifact.
86
+ * @param {string} candidatePath
87
+ * @param {string} folderPath
88
+ */
89
+ function isPathInsideFolder(candidatePath, folderPath) {
90
+ if (!folderPath) return true;
91
+ const candidate = resolveRealPath(candidatePath);
92
+ const folder = resolveRealPath(folderPath);
93
+ return candidate === folder || candidate.startsWith(`${folder}${path.sep}`);
94
+ }
95
+
96
+ /**
97
+ * Trust predicate for journaled `review.completed` honors (SP-813 / #328).
98
+ * A live batch never honors: (a) `payload.stub === true` without
99
+ * `payload.honored === true` — a foreign stub verdict leaked into the live
100
+ * journal; the spawn-timeout honor (`honorReason: "spawn_timeout_with_done"`)
101
+ * journals `honored: true` in real batches and stays honorable. (b) an
102
+ * absolute `payload.artifactPath` outside the task folder. Relative paths are
103
+ * worker-relative to the lane worktree and always accepted. `stubMode` comes
104
+ * from the engine caller via `shouldUseReviewStub(env)`; when omitted it
105
+ * defaults to the process env so callers that predate the guard
106
+ * (review-step-run.mjs) keep their stub-batch behavior.
107
+ * @param {Record<string, any>} event
108
+ * @param {object} params
109
+ * @param {string} params.taskFolder
110
+ * @param {string} [params.worktreePath] Accepted for caller symmetry; relative artifact paths are worker-relative and always trusted.
111
+ * @param {boolean} [params.stubMode]
112
+ * @returns {{ ok: true } | { ok: false, reason: "stub_verdict_in_live_batch" | "artifact_outside_task_folder" }}
113
+ */
114
+ export function isHonorableReviewEvent(event, { taskFolder, worktreePath: _worktreePath, stubMode } = {}) {
115
+ const payload = event?.payload && typeof event.payload === "object" ? event.payload : {};
116
+ const effectiveStubMode = stubMode ?? shouldUseReviewStub();
117
+ if (payload.stub === true && payload.honored !== true && !effectiveStubMode) {
118
+ return { ok: false, reason: "stub_verdict_in_live_batch" };
119
+ }
120
+ const artifactPath = typeof payload.artifactPath === "string" ? payload.artifactPath : "";
121
+ if (artifactPath && path.isAbsolute(artifactPath) && !isPathInsideFolder(artifactPath, taskFolder)) {
122
+ return { ok: false, reason: "artifact_outside_task_folder" };
123
+ }
124
+ return { ok: true };
125
+ }
126
+
73
127
  /**
74
128
  * Resolve an existing worker or lane code review from journal and/or artifacts.
75
- *
76
129
  * @param {object} params
77
130
  * @param {string} params.taskFolder
78
131
  * @param {object[]} [params.journalEvents]
79
132
  * @param {string} [params.taskId]
133
+ * @param {string} [params.worktreePath] Lane worktree used to resolve relative artifact paths.
134
+ * @param {boolean} [params.stubMode] Whether the batch runs in review-stub mode (see isHonorableReviewEvent).
135
+ * @param {(event: Record<string, any>, reason: string) => void} [params.onReject] Invoked once per journal event refused by the honor guard.
80
136
  * @returns {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
81
137
  */
82
- export function findCompletedCodeReview({ taskFolder, journalEvents = [], taskId }) {
138
+ export function findCompletedCodeReview({
139
+ taskFolder,
140
+ journalEvents = [],
141
+ taskId,
142
+ worktreePath,
143
+ stubMode,
144
+ onReject,
145
+ }) {
83
146
  /** @type {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
84
147
  let journalMatch = null;
85
148
  for (let index = 0; index < journalEvents.length; index += 1) {
@@ -90,6 +153,12 @@ export function findCompletedCodeReview({ taskFolder, journalEvents = [], taskId
90
153
  if (payload.reviewType !== "code") continue;
91
154
  const verdict = normalizeVerdict(payload.verdict, "code");
92
155
  if (!verdict) continue;
156
+ const honorGuard = isHonorableReviewEvent(event, { taskFolder, worktreePath, stubMode });
157
+ if (!honorGuard.ok) {
158
+ // Skip untrusted events as if absent; later candidates still honor.
159
+ if (typeof onReject === "function") onReject(event, honorGuard.reason);
160
+ continue;
161
+ }
93
162
  journalMatch = {
94
163
  verdict,
95
164
  feedback: typeof payload.feedback === "string" ? payload.feedback : "",
@@ -135,7 +204,6 @@ export const REVIEW_HONOR_JOURNAL_EVENTS = {
135
204
 
136
205
  /**
137
206
  * True when operator retry or reconcile re-enters review with a still-valid prior verdict.
138
- *
139
207
  * @param {object} params
140
208
  * @param {object[]} params.journalEvents
141
209
  * @param {string} params.taskId
@@ -186,7 +254,6 @@ export function isRetryReconcileFreshReview({
186
254
 
187
255
  /**
188
256
  * True when journal shows a review spawn crash/failure that warrants crash_recovered.
189
- *
190
257
  * @param {object} params
191
258
  * @param {object[]} params.journalEvents
192
259
  * @param {string} params.taskId
@@ -222,7 +289,6 @@ export function hasReviewSpawnFailureForHonor({ journalEvents = [], taskId, revi
222
289
 
223
290
  /**
224
291
  * Resolve explicit journal event for honoring a completed review artifact.
225
- *
226
292
  * @param {object} params
227
293
  * @param {object[]} params.journalEvents
228
294
  * @param {string} params.taskId
@@ -255,7 +321,6 @@ export function resolveReviewHonorJournalEvent({
255
321
 
256
322
  /**
257
323
  * Map honor journal event to task.verdict_recorded reviewPassKind.
258
- *
259
324
  * @param {"review.crash_recovered"|"review.skipped_fresh_artifact"|null} honorJournalEvent
260
325
  * @returns {"recovered"|"fresh_skip"|"normal"}
261
326
  */
@@ -271,7 +336,6 @@ export function resolveReviewPassKind(honorJournalEvent) {
271
336
 
272
337
  /**
273
338
  * True when review should emit review.resumed before spawning after operator retry.
274
- *
275
339
  * @param {object} params
276
340
  * @param {object[]} params.journalEvents
277
341
  * @param {string} params.taskId
@@ -291,7 +355,6 @@ export function shouldEmitReviewResumed({ journalEvents = [], taskId }) {
291
355
 
292
356
  /**
293
357
  * Latest review honor/resume signal for diagnose and dashboard surfaces.
294
- *
295
358
  * @param {object[]} journalEvents
296
359
  * @param {string|null} [activeTaskId]
297
360
  * @returns {{ taskId: string, reviewType: string, kind: string, honorSource?: string, reviewPassKind?: string }|null}
@@ -365,14 +428,23 @@ export function findLatestFinalReviewArtifact(taskFolder) {
365
428
  /**
366
429
  * Resolve an existing worker or lane final review from journal and/or artifacts.
367
430
  * Honors PASS from journal `review.completed` or latest final artifact.
368
- *
369
431
  * @param {object} params
370
432
  * @param {string} params.taskFolder
371
433
  * @param {object[]} [params.journalEvents]
372
434
  * @param {string} [params.taskId]
435
+ * @param {string} [params.worktreePath] Lane worktree used to resolve relative artifact paths.
436
+ * @param {boolean} [params.stubMode] Whether the batch runs in review-stub mode (see isHonorableReviewEvent).
437
+ * @param {(event: Record<string, any>, reason: string) => void} [params.onReject] Invoked once per journal event refused by the honor guard.
373
438
  * @returns {{ verdict: "PASS"|"REVISE"|"REPLAN", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
374
439
  */
375
- export function findCompletedFinalReview({ taskFolder, journalEvents = [], taskId }) {
440
+ export function findCompletedFinalReview({
441
+ taskFolder,
442
+ journalEvents = [],
443
+ taskId,
444
+ worktreePath,
445
+ stubMode,
446
+ onReject,
447
+ }) {
376
448
  /** @type {{ verdict: "PASS"|"REVISE"|"REPLAN", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
377
449
  let journalMatch = null;
378
450
  for (let index = 0; index < journalEvents.length; index += 1) {
@@ -383,6 +455,12 @@ export function findCompletedFinalReview({ taskFolder, journalEvents = [], taskI
383
455
  if (payload.reviewType !== "final") continue;
384
456
  const verdict = normalizeVerdict(payload.verdict, "final");
385
457
  if (!verdict) continue;
458
+ const honorGuard = isHonorableReviewEvent(event, { taskFolder, worktreePath, stubMode });
459
+ if (!honorGuard.ok) {
460
+ // Skip untrusted events as if absent; later candidates still honor.
461
+ if (typeof onReject === "function") onReject(event, honorGuard.reason);
462
+ continue;
463
+ }
386
464
  journalMatch = {
387
465
  verdict,
388
466
  feedback: typeof payload.feedback === "string" ? payload.feedback : "",
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Reviewer re-spawn policy and failure diagnostics for runStepReview (SP-814 / #332).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import {
8
+ NESTED_REVIEW_SPAWN_REASON,
9
+ REVIEW_SPAWN_TIMEOUT_EXIT_CODE,
10
+ REVIEW_TIMEOUT_REASON,
11
+ } from "./review-spawn.mjs";
12
+ import { buildReviewerOutputTail, persistReviewerOutputLog } from "./reviewer-output.mjs";
13
+
14
+ /**
15
+ * @typedef {import("./reviewer-output.mjs").ReviewerSpawnResult & {
16
+ * honored?: boolean,
17
+ * reason?: string,
18
+ * }} ReviewSpawnAttemptResult
19
+ */
20
+
21
+ /** Bounded automatic re-spawn budget for reviewer children (SP-814 / #332). */
22
+ export const REVIEW_SPAWN_MAX_ATTEMPTS = 2;
23
+
24
+ /** `review.spawn_retry` reason when the reviewer exited 0 without an artifact. */
25
+ export const REVIEW_SPAWN_RETRY_REASON_NO_ARTIFACT = "no_artifact";
26
+
27
+ /** `review.spawn_retry` reason fallback for a non-timeout spawn failure. */
28
+ export const REVIEW_SPAWN_RETRY_REASON_SPAWN_FAILED = "spawn_failed";
29
+
30
+ /**
31
+ * A reviewer attempt may be re-spawned once when it exited 0 without writing
32
+ * the artifact, or failed for a reason other than a timeout (exit 124 /
33
+ * `review_timeout`) or the nested-spawn guard — those keep their dedicated
34
+ * honor/skip paths so engine classification is unchanged (SP-814 / #332).
35
+ *
36
+ * @param {object} params
37
+ * @param {ReviewSpawnAttemptResult|null|undefined} params.spawnResult
38
+ * @param {string} params.artifactPath
39
+ * @returns {boolean}
40
+ */
41
+ export function isReviewSpawnRetryEligible({ spawnResult, artifactPath }) {
42
+ if (!spawnResult || spawnResult.honored) return false;
43
+ if (spawnResult.reason === NESTED_REVIEW_SPAWN_REASON) return false;
44
+ if (spawnResult.reason === REVIEW_TIMEOUT_REASON) return false;
45
+ if (spawnResult.exitCode === REVIEW_SPAWN_TIMEOUT_EXIT_CODE) return false;
46
+ if (spawnResult.spawnFailed) return true;
47
+ return !fs.existsSync(artifactPath);
48
+ }
49
+
50
+ /**
51
+ * Persist the reviewer log for a failed attempt when the journal context is
52
+ * available. Log persistence must never fail the review path itself, so a
53
+ * write error degrades to `null` (the journal event still carries outputTail).
54
+ *
55
+ * @param {object} params
56
+ * @param {{ projectRoot?: string, batchId?: string, laneNumber?: number, taskId?: string }|null|undefined} params.journal
57
+ * @param {string} params.taskFolder
58
+ * @param {number} params.stepNumber
59
+ * @param {string} params.reviewType
60
+ * @param {number} params.attempt
61
+ * @param {ReviewSpawnAttemptResult} params.spawnResult
62
+ * @param {object} [params.config]
63
+ * @returns {{ logPath: string, logRef: string }|null}
64
+ */
65
+ export function persistReviewerLogForAttempt({
66
+ journal,
67
+ taskFolder,
68
+ stepNumber,
69
+ reviewType,
70
+ attempt,
71
+ spawnResult,
72
+ config,
73
+ }) {
74
+ if (!journal?.projectRoot || !journal?.batchId) return null;
75
+ try {
76
+ return persistReviewerOutputLog({
77
+ projectRoot: journal.projectRoot,
78
+ batchId: journal.batchId,
79
+ laneNumber: journal.laneNumber ?? 1,
80
+ taskId: journal.taskId ?? path.basename(taskFolder),
81
+ reviewType,
82
+ stepNumber,
83
+ attempt,
84
+ spawnResult,
85
+ config,
86
+ });
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Diagnostics shared by the `review.failed` payload and the returned result:
94
+ * reviewer duration plus a redacted combined output tail (≤ 2 KB).
95
+ *
96
+ * @param {ReviewSpawnAttemptResult} spawnResult
97
+ * @param {object} [config]
98
+ * @returns {{ durationMs?: number, outputTail?: string }}
99
+ */
100
+ export function buildSpawnFailureDiagnostics(spawnResult, config) {
101
+ const outputTail = buildReviewerOutputTail(spawnResult, config);
102
+ return {
103
+ ...(typeof spawnResult?.durationMs === "number" ? { durationMs: spawnResult.durationMs } : {}),
104
+ ...(outputTail ? { outputTail } : {}),
105
+ };
106
+ }
@@ -13,6 +13,11 @@ import {
13
13
  resolveReviewerModelPin,
14
14
  resolveReviewerThinkingPin,
15
15
  } from "../config/agent-model-resolve.mjs";
16
+ import {
17
+ captureWorkerOutputTail,
18
+ redactWorkerOutput,
19
+ resolveWorkerOutputConfig,
20
+ } from "./worker-output.mjs";
16
21
  import {
17
22
  parseTaskSizeFromFolder,
18
23
  resolveReviewArtifactPollIntervalMs,
@@ -35,6 +40,22 @@ export const DEFAULT_REVIEW_SPAWN_TIMEOUT_MS = 90 * 60 * 1000;
35
40
  /** Grace period after SIGTERM before SIGKILL on hung reviewer children. */
36
41
  const REVIEW_SPAWN_KILL_GRACE_MS = 5_000;
37
42
 
43
+ /**
44
+ * Append a stdout/stderr chunk while keeping only the trailing `maxBytes` so a
45
+ * chatty reviewer child cannot grow engine memory without bound (SP-814 / #332).
46
+ * Mirrors the worker output tail budget from `resolveWorkerOutputConfig`.
47
+ *
48
+ * @param {string} current
49
+ * @param {string|Buffer} chunk
50
+ * @param {number} maxBytes
51
+ */
52
+ function appendBoundedCapture(current, chunk, maxBytes) {
53
+ const next = current + String(chunk);
54
+ const encoded = Buffer.from(next, "utf-8");
55
+ if (encoded.byteLength <= maxBytes) return next;
56
+ return encoded.subarray(encoded.byteLength - maxBytes).toString("utf-8");
57
+ }
58
+
38
59
  /** Set by {@link buildWorkerChildEnv} when the batch engine launches a pi worker child. */
39
60
  export function isActiveWorkerSession() {
40
61
  const marker = process.env.SPINE_WORKER_RUNNER;
@@ -199,6 +220,9 @@ export function spawnReviewerPi({
199
220
  spawnFailed: true,
200
221
  exitCode: 127,
201
222
  error: "pi not available for reviewer spawn",
223
+ durationMs: 0,
224
+ stdoutTail: "",
225
+ stderrTail: "",
202
226
  });
203
227
  }
204
228
 
@@ -220,16 +244,21 @@ export function spawnReviewerPi({
220
244
  });
221
245
  const pollIntervalMs = resolveReviewArtifactPollIntervalMs({ config });
222
246
  const quiescenceMs = resolveReviewArtifactQuiescenceMs({ config });
247
+ // Reviewer output capture reuses the worker output policy (redaction + tail
248
+ // caps) so spawn diagnostics obey the same conventions as worker logs.
249
+ const outputConfig = resolveWorkerOutputConfig(config);
223
250
  /** @type {ArtifactPollState} */
224
251
  const artifactPollState = { lastMtimeMs: null, quiescentSinceMs: null };
225
252
 
226
253
  return new Promise((resolve) => {
254
+ const startedAtMs = Date.now();
227
255
  const child = spawn("pi", piArgs, {
228
256
  cwd: worktreePath || path.dirname(taskFolder),
229
257
  env: buildReviewerChildEnv({ taskFolder, worktreePath }),
230
258
  stdio: ["ignore", "pipe", "pipe"],
231
259
  });
232
260
 
261
+ let stdout = "";
233
262
  let stderr = "";
234
263
  let timedOut = false;
235
264
  let settled = false;
@@ -242,7 +271,20 @@ export function spawnReviewerPi({
242
271
  clearTimeout(timer);
243
272
  clearInterval(pollTimer);
244
273
  clearTimeout(killTimer);
245
- resolve(result);
274
+ // Every result — including exit 0 — carries capture diagnostics so the
275
+ // engine can journal them when the reviewer produced no artifact.
276
+ resolve({
277
+ durationMs: Date.now() - startedAtMs,
278
+ stdoutTail: captureWorkerOutputTail(
279
+ redactWorkerOutput(stdout, outputConfig),
280
+ outputConfig,
281
+ ),
282
+ stderrTail: captureWorkerOutputTail(
283
+ redactWorkerOutput(stderr, outputConfig),
284
+ outputConfig,
285
+ ),
286
+ ...result,
287
+ });
246
288
  };
247
289
 
248
290
  const terminateHungChild = () => {
@@ -278,8 +320,12 @@ export function spawnReviewerPi({
278
320
  });
279
321
  };
280
322
 
323
+ child.stdout?.on("data", (chunk) => {
324
+ stdout = appendBoundedCapture(stdout, chunk, outputConfig.maxBytes);
325
+ });
326
+
281
327
  child.stderr?.on("data", (chunk) => {
282
- stderr += String(chunk);
328
+ stderr = appendBoundedCapture(stderr, chunk, outputConfig.maxBytes);
283
329
  });
284
330
 
285
331
  const pollTimer = setInterval(checkArtifact, pollIntervalMs);
@@ -13,6 +13,14 @@ import {
13
13
  shouldBlockNestedReviewerSpawn,
14
14
  spawnReviewerPi,
15
15
  } from "./review-spawn.mjs";
16
+ import {
17
+ REVIEW_SPAWN_MAX_ATTEMPTS,
18
+ REVIEW_SPAWN_RETRY_REASON_NO_ARTIFACT,
19
+ REVIEW_SPAWN_RETRY_REASON_SPAWN_FAILED,
20
+ buildSpawnFailureDiagnostics,
21
+ isReviewSpawnRetryEligible,
22
+ persistReviewerLogForAttempt,
23
+ } from "./review-spawn-retry.mjs";
16
24
  import {
17
25
  buildFinalReviewArtifactPath,
18
26
  buildReviewArtifactPath,
@@ -39,6 +47,12 @@ import {
39
47
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
40
48
  const PACKAGE_ROOT = path.resolve(__dirname, "../..");
41
49
 
50
+ export {
51
+ REVIEW_SPAWN_MAX_ATTEMPTS,
52
+ REVIEW_SPAWN_RETRY_REASON_NO_ARTIFACT,
53
+ REVIEW_SPAWN_RETRY_REASON_SPAWN_FAILED,
54
+ };
55
+
42
56
  /**
43
57
  * @param {object} params
44
58
  */
@@ -213,7 +227,7 @@ export async function runStepReview({
213
227
  });
214
228
  }
215
229
 
216
- const spawnResult = await spawnReviewerPi({
230
+ const spawnParams = {
217
231
  worktreePath,
218
232
  taskFolder,
219
233
  reviewPrompt,
@@ -222,16 +236,58 @@ export async function runStepReview({
222
236
  artifactPath,
223
237
  reviewType,
224
238
  contractVerifyResult,
225
- });
239
+ };
240
+ let spawnResult = await spawnReviewerPi(spawnParams);
226
241
 
227
- if (spawnResult.honored && spawnResult.honorReason === ARTIFACT_READY_HONOR_REASON) {
228
- return completeReviewFromHonoredArtifact({
229
- artifactPath: spawnResult.artifactPath ?? artifactPath,
230
- reviewType,
242
+ /** @returns {ReturnType<typeof runStepReview>|null} */
243
+ const completeIfHonored = () =>
244
+ spawnResult.honored && spawnResult.honorReason === ARTIFACT_READY_HONOR_REASON
245
+ ? completeReviewFromHonoredArtifact({
246
+ artifactPath: spawnResult.artifactPath ?? artifactPath,
247
+ reviewType,
248
+ journal,
249
+ stepNumber,
250
+ reviewLevel,
251
+ })
252
+ : null;
253
+
254
+ const honoredFirstAttempt = completeIfHonored();
255
+ if (honoredFirstAttempt) return honoredFirstAttempt;
256
+
257
+ // One bounded re-spawn for transient no-artifact exits and non-timeout
258
+ // spawn failures (SP-814 / #332): journal the retry with diagnostics, then
259
+ // spawn again with the same prompt and artifact path.
260
+ let attempt = 1;
261
+ while (
262
+ attempt < REVIEW_SPAWN_MAX_ATTEMPTS &&
263
+ isReviewSpawnRetryEligible({ spawnResult, artifactPath })
264
+ ) {
265
+ const failedAttempt = attempt;
266
+ const log = persistReviewerLogForAttempt({
231
267
  journal,
268
+ taskFolder,
232
269
  stepNumber,
270
+ reviewType,
271
+ attempt: failedAttempt,
272
+ spawnResult,
273
+ config,
274
+ });
275
+ journalReviewEvent("review.spawn_retry", journal, {
276
+ stepNumber,
277
+ reviewType,
233
278
  reviewLevel,
279
+ attempt: failedAttempt + 1,
280
+ reason: spawnResult.spawnFailed
281
+ ? (spawnResult.reason ?? REVIEW_SPAWN_RETRY_REASON_SPAWN_FAILED)
282
+ : REVIEW_SPAWN_RETRY_REASON_NO_ARTIFACT,
283
+ exitCode: spawnResult.exitCode ?? 0,
284
+ durationMs: spawnResult.durationMs ?? null,
285
+ ...(log?.logRef ? { reviewerOutputLogRef: log.logRef } : {}),
234
286
  });
287
+ spawnResult = await spawnReviewerPi(spawnParams);
288
+ attempt += 1;
289
+ const honoredRetry = completeIfHonored();
290
+ if (honoredRetry) return honoredRetry;
235
291
  }
236
292
 
237
293
  if (spawnResult.spawnFailed) {
@@ -259,6 +315,19 @@ export async function runStepReview({
259
315
  return honored;
260
316
  }
261
317
 
318
+ const log = persistReviewerLogForAttempt({
319
+ journal,
320
+ taskFolder,
321
+ stepNumber,
322
+ reviewType,
323
+ attempt,
324
+ spawnResult,
325
+ config,
326
+ });
327
+ const diagnostics = {
328
+ ...buildSpawnFailureDiagnostics(spawnResult, config),
329
+ ...(log?.logRef ? { reviewerOutputLogRef: log.logRef } : {}),
330
+ };
262
331
  journalReviewEvent("review.failed", journal, {
263
332
  stepNumber,
264
333
  reviewType,
@@ -267,6 +336,7 @@ export async function runStepReview({
267
336
  spawnFailed: true,
268
337
  exitCode: spawnResult.exitCode,
269
338
  ...(spawnResult.reason ? { reason: spawnResult.reason } : {}),
339
+ ...diagnostics,
270
340
  });
271
341
  return {
272
342
  ok: false,
@@ -279,17 +349,36 @@ export async function runStepReview({
279
349
  error: spawnResult.error,
280
350
  exitCode: spawnResult.exitCode ?? 1,
281
351
  reason: spawnResult.reason,
352
+ ...diagnostics,
282
353
  };
283
354
  }
284
355
 
285
356
  if (!fs.existsSync(artifactPath)) {
286
357
  const error = "reviewer exited but produced no artifact";
358
+ const log = persistReviewerLogForAttempt({
359
+ journal,
360
+ taskFolder,
361
+ stepNumber,
362
+ reviewType,
363
+ attempt,
364
+ spawnResult,
365
+ config,
366
+ });
367
+ const diagnostics = {
368
+ ...buildSpawnFailureDiagnostics(spawnResult, config),
369
+ ...(log?.logRef ? { reviewerOutputLogRef: log.logRef } : {}),
370
+ };
371
+ // The payload carries the reviewer's real exit code (typically 0) while
372
+ // the returned result keeps a non-zero exit code: the CLI and worker
373
+ // tools treat result exit 0 as success and must still fail closed.
287
374
  journalReviewEvent("review.failed", journal, {
288
375
  stepNumber,
289
376
  reviewType,
290
377
  reviewLevel,
291
378
  error,
292
379
  spawnFailed: true,
380
+ exitCode: spawnResult.exitCode ?? 0,
381
+ ...diagnostics,
293
382
  });
294
383
  return {
295
384
  ok: false,
@@ -301,6 +390,7 @@ export async function runStepReview({
301
390
  spawnFailed: true,
302
391
  error,
303
392
  exitCode: 1,
393
+ ...diagnostics,
304
394
  };
305
395
  }
306
396