pi-spine 2.26.0 → 2.27.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.
Files changed (63) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-review-step.mjs +8 -1
  3. package/bin/spine-worker-runner.mjs +15 -1
  4. package/package.json +3 -3
  5. package/skills/create-spine-tasks/SKILL.md +60 -33
  6. package/skills/create-spine-tasks/references/authoring-evidence.md +58 -0
  7. package/skills/create-spine-tasks/references/contract-template.md +52 -7
  8. package/skills/create-spine-tasks/references/prompt-template.md +72 -8
  9. package/skills/spine-release-operator/SKILL.md +33 -51
  10. package/skills/spine-release-operator/references/issue-intake-checklist.md +3 -1
  11. package/skills/spine-release-operator/references/pi-async-orchestration.md +13 -9
  12. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +8 -1
  13. package/skills/spine-release-operator/references/publish-recovery.md +62 -0
  14. package/src/batch/batch-meta-reconstruct.mjs +3 -0
  15. package/src/batch/contract-exec.mjs +2 -2
  16. package/src/batch/contract-parse.mjs +2 -2
  17. package/src/batch/contract-prelanded.mjs +2 -2
  18. package/src/batch/diagnosis-alternatives.mjs +16 -1
  19. package/src/batch/diagnosis-handoff-packet.mjs +74 -0
  20. package/src/batch/diagnosis-pending-lane.mjs +52 -1
  21. package/src/batch/diagnosis-review-infra.mjs +144 -0
  22. package/src/batch/diagnosis-suggested-command.mjs +9 -0
  23. package/src/batch/diagnosis.mjs +19 -20
  24. package/src/batch/engine-lanes/merge.mjs +0 -8
  25. package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
  26. package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
  27. package/src/batch/engine-lanes/review-code.mjs +1 -0
  28. package/src/batch/engine-lanes/review-final.mjs +83 -46
  29. package/src/batch/engine-lanes/review-plan.mjs +22 -2
  30. package/src/batch/engine-lanes/review-poll.mjs +51 -2
  31. package/src/batch/engine-lanes.mjs +6 -8
  32. package/src/batch/gate-posture-approve.mjs +154 -15
  33. package/src/batch/integrate-path-delete.mjs +85 -0
  34. package/src/batch/integrate-worktree.mjs +20 -27
  35. package/src/batch/journal.mjs +15 -0
  36. package/src/batch/metrics.mjs +13 -1
  37. package/src/batch/provider-quota.mjs +220 -0
  38. package/src/batch/quota-fallback.mjs +319 -0
  39. package/src/batch/reconcile-diagnosis-context.mjs +22 -0
  40. package/src/batch/reconcile-diagnosis.mjs +24 -77
  41. package/src/batch/resume-multi-queue.mjs +25 -10
  42. package/src/batch/review-artifacts.mjs +96 -17
  43. package/src/batch/review-level-effective.mjs +19 -0
  44. package/src/batch/review-spawn-retry.mjs +106 -0
  45. package/src/batch/review-spawn.mjs +60 -3
  46. package/src/batch/review-step-run.mjs +110 -8
  47. package/src/batch/reviewer-output.mjs +162 -0
  48. package/src/batch/reviewer-provider-error.mjs +153 -0
  49. package/src/batch/worker-host.mjs +49 -3
  50. package/src/batch/worker-prompt.mjs +5 -2
  51. package/src/config/cursor-rules/discover.mjs +40 -3
  52. package/src/config/cursor-rules/match-globs.mjs +6 -4
  53. package/src/config/env-overrides.mjs +41 -4
  54. package/src/config/settings-fields.mjs +11 -0
  55. package/src/config/spine-config-schema.mjs +62 -0
  56. package/src/doctor/pi-extension-hooks.mjs +322 -0
  57. package/src/doctor/quota-risk.mjs +45 -0
  58. package/src/doctor/run-doctor-checks.mjs +14 -1
  59. package/src/planner/file-scope.mjs +6 -6
  60. package/src/tasks/packet/validate-contract.mjs +3 -3
  61. package/src/tasks/packet/validate-prompt.mjs +11 -1
  62. package/src/tasks/validate-contract-warn.mjs +16 -0
  63. package/templates/spine-config.json +1 -1
@@ -1,14 +1,12 @@
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
- import { normalizeVerdict, parseReviewLevel, parseReviewVerdict } from "./review-shared.mjs";
7
+ import { normalizeVerdict, parseReviewVerdict } from "./review-shared.mjs";
8
+ import { effectiveReviewLevel } from "./review-level-effective.mjs";
9
+ import { shouldUseReviewStub } from "./engine-lanes/review-stub.mjs";
12
10
 
13
11
  /**
14
12
  * @param {string} taskFolder
@@ -16,7 +14,7 @@ import { normalizeVerdict, parseReviewLevel, parseReviewVerdict } from "./review
16
14
  export function readReviewLevel(taskFolder) {
17
15
  const promptPath = path.join(taskFolder, "PROMPT.md");
18
16
  if (!fs.existsSync(promptPath)) return 0;
19
- return parseReviewLevel(fs.readFileSync(promptPath, "utf-8"));
17
+ return effectiveReviewLevel(fs.readFileSync(promptPath, "utf-8"));
20
18
  }
21
19
 
22
20
  /**
@@ -70,16 +68,82 @@ export function findLatestStepReviewArtifact(taskFolder, stepNumber) {
70
68
  return candidates[0] ?? null;
71
69
  }
72
70
 
71
+ /**
72
+ * Realpath with a lexical fallback for missing targets — the guard must still
73
+ * classify a vanished foreign artifact, not crash on it.
74
+ * @param {string} candidatePath
75
+ */
76
+ function resolveRealPath(candidatePath) {
77
+ try {
78
+ return fs.realpathSync(candidatePath);
79
+ } catch {
80
+ return path.resolve(candidatePath);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * True when candidatePath is inside folderPath. Both sides are realpath-resolved
86
+ * so symlinks and /var vs /private/var aliases cannot smuggle a foreign artifact.
87
+ * @param {string} candidatePath
88
+ * @param {string} folderPath
89
+ */
90
+ function isPathInsideFolder(candidatePath, folderPath) {
91
+ if (!folderPath) return true;
92
+ const candidate = resolveRealPath(candidatePath);
93
+ const folder = resolveRealPath(folderPath);
94
+ return candidate === folder || candidate.startsWith(`${folder}${path.sep}`);
95
+ }
96
+
97
+ /**
98
+ * Trust predicate for journaled `review.completed` honors (SP-813 / #328).
99
+ * A live batch never honors: (a) `payload.stub === true` without
100
+ * `payload.honored === true` — a foreign stub verdict leaked into the live
101
+ * journal; the spawn-timeout honor (`honorReason: "spawn_timeout_with_done"`)
102
+ * journals `honored: true` in real batches and stays honorable. (b) an
103
+ * absolute `payload.artifactPath` outside the task folder. Relative paths are
104
+ * worker-relative to the lane worktree and always accepted. `stubMode` comes
105
+ * from the engine caller via `shouldUseReviewStub(env)`; when omitted it
106
+ * defaults to the process env so callers that predate the guard
107
+ * (review-step-run.mjs) keep their stub-batch behavior.
108
+ * @param {Record<string, any>} event
109
+ * @param {object} params
110
+ * @param {string} params.taskFolder
111
+ * @param {string} [params.worktreePath] Accepted for caller symmetry; relative artifact paths are worker-relative and always trusted.
112
+ * @param {boolean} [params.stubMode]
113
+ * @returns {{ ok: true } | { ok: false, reason: "stub_verdict_in_live_batch" | "artifact_outside_task_folder" }}
114
+ */
115
+ export function isHonorableReviewEvent(event, { taskFolder, worktreePath: _worktreePath, stubMode } = {}) {
116
+ const payload = event?.payload && typeof event.payload === "object" ? event.payload : {};
117
+ const effectiveStubMode = stubMode ?? shouldUseReviewStub();
118
+ if (payload.stub === true && payload.honored !== true && !effectiveStubMode) {
119
+ return { ok: false, reason: "stub_verdict_in_live_batch" };
120
+ }
121
+ const artifactPath = typeof payload.artifactPath === "string" ? payload.artifactPath : "";
122
+ if (artifactPath && path.isAbsolute(artifactPath) && !isPathInsideFolder(artifactPath, taskFolder)) {
123
+ return { ok: false, reason: "artifact_outside_task_folder" };
124
+ }
125
+ return { ok: true };
126
+ }
127
+
73
128
  /**
74
129
  * Resolve an existing worker or lane code review from journal and/or artifacts.
75
- *
76
130
  * @param {object} params
77
131
  * @param {string} params.taskFolder
78
132
  * @param {object[]} [params.journalEvents]
79
133
  * @param {string} [params.taskId]
134
+ * @param {string} [params.worktreePath] Lane worktree used to resolve relative artifact paths.
135
+ * @param {boolean} [params.stubMode] Whether the batch runs in review-stub mode (see isHonorableReviewEvent).
136
+ * @param {(event: Record<string, any>, reason: string) => void} [params.onReject] Invoked once per journal event refused by the honor guard.
80
137
  * @returns {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
81
138
  */
82
- export function findCompletedCodeReview({ taskFolder, journalEvents = [], taskId }) {
139
+ export function findCompletedCodeReview({
140
+ taskFolder,
141
+ journalEvents = [],
142
+ taskId,
143
+ worktreePath,
144
+ stubMode,
145
+ onReject,
146
+ }) {
83
147
  /** @type {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
84
148
  let journalMatch = null;
85
149
  for (let index = 0; index < journalEvents.length; index += 1) {
@@ -90,6 +154,12 @@ export function findCompletedCodeReview({ taskFolder, journalEvents = [], taskId
90
154
  if (payload.reviewType !== "code") continue;
91
155
  const verdict = normalizeVerdict(payload.verdict, "code");
92
156
  if (!verdict) continue;
157
+ const honorGuard = isHonorableReviewEvent(event, { taskFolder, worktreePath, stubMode });
158
+ if (!honorGuard.ok) {
159
+ // Skip untrusted events as if absent; later candidates still honor.
160
+ if (typeof onReject === "function") onReject(event, honorGuard.reason);
161
+ continue;
162
+ }
93
163
  journalMatch = {
94
164
  verdict,
95
165
  feedback: typeof payload.feedback === "string" ? payload.feedback : "",
@@ -135,7 +205,6 @@ export const REVIEW_HONOR_JOURNAL_EVENTS = {
135
205
 
136
206
  /**
137
207
  * True when operator retry or reconcile re-enters review with a still-valid prior verdict.
138
- *
139
208
  * @param {object} params
140
209
  * @param {object[]} params.journalEvents
141
210
  * @param {string} params.taskId
@@ -186,7 +255,6 @@ export function isRetryReconcileFreshReview({
186
255
 
187
256
  /**
188
257
  * True when journal shows a review spawn crash/failure that warrants crash_recovered.
189
- *
190
258
  * @param {object} params
191
259
  * @param {object[]} params.journalEvents
192
260
  * @param {string} params.taskId
@@ -222,7 +290,6 @@ export function hasReviewSpawnFailureForHonor({ journalEvents = [], taskId, revi
222
290
 
223
291
  /**
224
292
  * Resolve explicit journal event for honoring a completed review artifact.
225
- *
226
293
  * @param {object} params
227
294
  * @param {object[]} params.journalEvents
228
295
  * @param {string} params.taskId
@@ -255,7 +322,6 @@ export function resolveReviewHonorJournalEvent({
255
322
 
256
323
  /**
257
324
  * Map honor journal event to task.verdict_recorded reviewPassKind.
258
- *
259
325
  * @param {"review.crash_recovered"|"review.skipped_fresh_artifact"|null} honorJournalEvent
260
326
  * @returns {"recovered"|"fresh_skip"|"normal"}
261
327
  */
@@ -271,7 +337,6 @@ export function resolveReviewPassKind(honorJournalEvent) {
271
337
 
272
338
  /**
273
339
  * True when review should emit review.resumed before spawning after operator retry.
274
- *
275
340
  * @param {object} params
276
341
  * @param {object[]} params.journalEvents
277
342
  * @param {string} params.taskId
@@ -291,7 +356,6 @@ export function shouldEmitReviewResumed({ journalEvents = [], taskId }) {
291
356
 
292
357
  /**
293
358
  * Latest review honor/resume signal for diagnose and dashboard surfaces.
294
- *
295
359
  * @param {object[]} journalEvents
296
360
  * @param {string|null} [activeTaskId]
297
361
  * @returns {{ taskId: string, reviewType: string, kind: string, honorSource?: string, reviewPassKind?: string }|null}
@@ -365,14 +429,23 @@ export function findLatestFinalReviewArtifact(taskFolder) {
365
429
  /**
366
430
  * Resolve an existing worker or lane final review from journal and/or artifacts.
367
431
  * Honors PASS from journal `review.completed` or latest final artifact.
368
- *
369
432
  * @param {object} params
370
433
  * @param {string} params.taskFolder
371
434
  * @param {object[]} [params.journalEvents]
372
435
  * @param {string} [params.taskId]
436
+ * @param {string} [params.worktreePath] Lane worktree used to resolve relative artifact paths.
437
+ * @param {boolean} [params.stubMode] Whether the batch runs in review-stub mode (see isHonorableReviewEvent).
438
+ * @param {(event: Record<string, any>, reason: string) => void} [params.onReject] Invoked once per journal event refused by the honor guard.
373
439
  * @returns {{ verdict: "PASS"|"REVISE"|"REPLAN", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
374
440
  */
375
- export function findCompletedFinalReview({ taskFolder, journalEvents = [], taskId }) {
441
+ export function findCompletedFinalReview({
442
+ taskFolder,
443
+ journalEvents = [],
444
+ taskId,
445
+ worktreePath,
446
+ stubMode,
447
+ onReject,
448
+ }) {
376
449
  /** @type {{ verdict: "PASS"|"REVISE"|"REPLAN", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
377
450
  let journalMatch = null;
378
451
  for (let index = 0; index < journalEvents.length; index += 1) {
@@ -383,6 +456,12 @@ export function findCompletedFinalReview({ taskFolder, journalEvents = [], taskI
383
456
  if (payload.reviewType !== "final") continue;
384
457
  const verdict = normalizeVerdict(payload.verdict, "final");
385
458
  if (!verdict) continue;
459
+ const honorGuard = isHonorableReviewEvent(event, { taskFolder, worktreePath, stubMode });
460
+ if (!honorGuard.ok) {
461
+ // Skip untrusted events as if absent; later candidates still honor.
462
+ if (typeof onReject === "function") onReject(event, honorGuard.reason);
463
+ continue;
464
+ }
386
465
  journalMatch = {
387
466
  verdict,
388
467
  feedback: typeof payload.feedback === "string" ? payload.feedback : "",
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Effective review level for a task packet (SP-827 / #336).
3
+ *
4
+ * `**Type:** execute` packets run no reviewers (operator runbook §2.5), so
5
+ * their effective review level is 0 regardless of the declared level. `llm`
6
+ * packets return their declared level unchanged.
7
+ */
8
+
9
+ import { parsePrompt } from "../tasks/packet/parse-prompt.mjs";
10
+ import { parseReviewLevel } from "./review-shared.mjs";
11
+
12
+ /**
13
+ * @param {string} markdown PROMPT.md contents
14
+ * @returns {number}
15
+ */
16
+ export function effectiveReviewLevel(markdown) {
17
+ if (parsePrompt(markdown).type === "execute") return 0;
18
+ return parseReviewLevel(markdown);
19
+ }
@@ -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;
@@ -87,6 +108,13 @@ function reviewerPiCommandExists(cmd) {
87
108
  }
88
109
 
89
110
  /**
111
+ * Build the argv for a reviewer `pi` spawn.
112
+ *
113
+ * SP-819 / #334: reviewers pass `-ne` (pi `--no-extensions`) by default so operator-installed
114
+ * pi extensions (e.g. context-rewriting hooks) cannot break review runs. Core tools are not
115
+ * extensions, so reviewers keep read/bash/write. `agents.reviewer.loadUserExtensions: true`
116
+ * opts back into user extensions.
117
+ *
90
118
  * @param {object} params
91
119
  */
92
120
  export function buildReviewerPiArgs({
@@ -101,7 +129,11 @@ export function buildReviewerPiArgs({
101
129
  const reviewerModel = resolveReviewerModelPin(config, reviewType);
102
130
  const reviewerThinking = resolveReviewerThinkingPin(config, reviewType);
103
131
 
104
- const piArgs = ["-p", "--no-session"];
132
+ const piArgs = [];
133
+ if (config?.agents?.reviewer?.loadUserExtensions !== true) {
134
+ piArgs.push("-ne");
135
+ }
136
+ piArgs.push("-p", "--no-session");
105
137
  if (reviewerAgentPath && fs.existsSync(reviewerAgentPath)) {
106
138
  piArgs.push("--append-system-prompt", reviewerAgentPath);
107
139
  }
@@ -199,6 +231,9 @@ export function spawnReviewerPi({
199
231
  spawnFailed: true,
200
232
  exitCode: 127,
201
233
  error: "pi not available for reviewer spawn",
234
+ durationMs: 0,
235
+ stdoutTail: "",
236
+ stderrTail: "",
202
237
  });
203
238
  }
204
239
 
@@ -220,16 +255,21 @@ export function spawnReviewerPi({
220
255
  });
221
256
  const pollIntervalMs = resolveReviewArtifactPollIntervalMs({ config });
222
257
  const quiescenceMs = resolveReviewArtifactQuiescenceMs({ config });
258
+ // Reviewer output capture reuses the worker output policy (redaction + tail
259
+ // caps) so spawn diagnostics obey the same conventions as worker logs.
260
+ const outputConfig = resolveWorkerOutputConfig(config);
223
261
  /** @type {ArtifactPollState} */
224
262
  const artifactPollState = { lastMtimeMs: null, quiescentSinceMs: null };
225
263
 
226
264
  return new Promise((resolve) => {
265
+ const startedAtMs = Date.now();
227
266
  const child = spawn("pi", piArgs, {
228
267
  cwd: worktreePath || path.dirname(taskFolder),
229
268
  env: buildReviewerChildEnv({ taskFolder, worktreePath }),
230
269
  stdio: ["ignore", "pipe", "pipe"],
231
270
  });
232
271
 
272
+ let stdout = "";
233
273
  let stderr = "";
234
274
  let timedOut = false;
235
275
  let settled = false;
@@ -242,7 +282,20 @@ export function spawnReviewerPi({
242
282
  clearTimeout(timer);
243
283
  clearInterval(pollTimer);
244
284
  clearTimeout(killTimer);
245
- resolve(result);
285
+ // Every result — including exit 0 — carries capture diagnostics so the
286
+ // engine can journal them when the reviewer produced no artifact.
287
+ resolve({
288
+ durationMs: Date.now() - startedAtMs,
289
+ stdoutTail: captureWorkerOutputTail(
290
+ redactWorkerOutput(stdout, outputConfig),
291
+ outputConfig,
292
+ ),
293
+ stderrTail: captureWorkerOutputTail(
294
+ redactWorkerOutput(stderr, outputConfig),
295
+ outputConfig,
296
+ ),
297
+ ...result,
298
+ });
246
299
  };
247
300
 
248
301
  const terminateHungChild = () => {
@@ -278,8 +331,12 @@ export function spawnReviewerPi({
278
331
  });
279
332
  };
280
333
 
334
+ child.stdout?.on("data", (chunk) => {
335
+ stdout = appendBoundedCapture(stdout, chunk, outputConfig.maxBytes);
336
+ });
337
+
281
338
  child.stderr?.on("data", (chunk) => {
282
- stderr += String(chunk);
339
+ stderr = appendBoundedCapture(stderr, chunk, outputConfig.maxBytes);
283
340
  });
284
341
 
285
342
  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,
@@ -35,10 +43,20 @@ import {
35
43
  journalReviewEvent,
36
44
  writeStubReviewArtifact,
37
45
  } from "./review-step.mjs";
46
+ import {
47
+ classifyReviewerSpawnFailure,
48
+ providerErrorFields,
49
+ } from "./reviewer-provider-error.mjs";
38
50
 
39
51
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
40
52
  const PACKAGE_ROOT = path.resolve(__dirname, "../..");
41
53
 
54
+ export {
55
+ REVIEW_SPAWN_MAX_ATTEMPTS,
56
+ REVIEW_SPAWN_RETRY_REASON_NO_ARTIFACT,
57
+ REVIEW_SPAWN_RETRY_REASON_SPAWN_FAILED,
58
+ };
59
+
42
60
  /**
43
61
  * @param {object} params
44
62
  */
@@ -213,7 +231,7 @@ export async function runStepReview({
213
231
  });
214
232
  }
215
233
 
216
- const spawnResult = await spawnReviewerPi({
234
+ const spawnParams = {
217
235
  worktreePath,
218
236
  taskFolder,
219
237
  reviewPrompt,
@@ -222,18 +240,65 @@ export async function runStepReview({
222
240
  artifactPath,
223
241
  reviewType,
224
242
  contractVerifyResult,
225
- });
243
+ };
244
+ let spawnResult = await spawnReviewerPi(spawnParams);
226
245
 
227
- if (spawnResult.honored && spawnResult.honorReason === ARTIFACT_READY_HONOR_REASON) {
228
- return completeReviewFromHonoredArtifact({
229
- artifactPath: spawnResult.artifactPath ?? artifactPath,
230
- reviewType,
246
+ /** @returns {ReturnType<typeof runStepReview>|null} */
247
+ const completeIfHonored = () =>
248
+ spawnResult.honored && spawnResult.honorReason === ARTIFACT_READY_HONOR_REASON
249
+ ? completeReviewFromHonoredArtifact({
250
+ artifactPath: spawnResult.artifactPath ?? artifactPath,
251
+ reviewType,
252
+ journal,
253
+ stepNumber,
254
+ reviewLevel,
255
+ })
256
+ : null;
257
+
258
+ const honoredFirstAttempt = completeIfHonored();
259
+ if (honoredFirstAttempt) return honoredFirstAttempt;
260
+
261
+ // One bounded re-spawn for transient no-artifact exits and non-timeout
262
+ // spawn failures (SP-814 / #332): journal the retry with diagnostics, then
263
+ // spawn again with the same prompt and artifact path.
264
+ let attempt = 1;
265
+ while (
266
+ attempt < REVIEW_SPAWN_MAX_ATTEMPTS &&
267
+ isReviewSpawnRetryEligible({ spawnResult, artifactPath })
268
+ ) {
269
+ const failedAttempt = attempt;
270
+ const log = persistReviewerLogForAttempt({
231
271
  journal,
272
+ taskFolder,
232
273
  stepNumber,
274
+ reviewType,
275
+ attempt: failedAttempt,
276
+ spawnResult,
277
+ config,
278
+ });
279
+ journalReviewEvent("review.spawn_retry", journal, {
280
+ stepNumber,
281
+ reviewType,
233
282
  reviewLevel,
283
+ attempt: failedAttempt + 1,
284
+ reason: spawnResult.spawnFailed
285
+ ? (spawnResult.reason ?? REVIEW_SPAWN_RETRY_REASON_SPAWN_FAILED)
286
+ : REVIEW_SPAWN_RETRY_REASON_NO_ARTIFACT,
287
+ exitCode: spawnResult.exitCode ?? 0,
288
+ durationMs: spawnResult.durationMs ?? null,
289
+ ...(log?.logRef ? { reviewerOutputLogRef: log.logRef } : {}),
234
290
  });
291
+ spawnResult = await spawnReviewerPi(spawnParams);
292
+ attempt += 1;
293
+ const honoredRetry = completeIfHonored();
294
+ if (honoredRetry) return honoredRetry;
235
295
  }
236
296
 
297
+ // SP-820 / #334: classify the terminal attempt once, after the SP-814
298
+ // re-spawn loop. A set `reason` means a dedicated path (nested-spawn guard
299
+ // returned above; timeout keeps `review_timeout`) — those stay unchanged.
300
+ const providerError = spawnResult.reason ? null : classifyReviewerSpawnFailure(spawnResult);
301
+
237
302
  if (spawnResult.spawnFailed) {
238
303
  if (spawnResult.reason === NESTED_REVIEW_SPAWN_REASON) {
239
304
  return completeNestedReviewSpawnSkipped({
@@ -259,6 +324,19 @@ export async function runStepReview({
259
324
  return honored;
260
325
  }
261
326
 
327
+ const log = persistReviewerLogForAttempt({
328
+ journal,
329
+ taskFolder,
330
+ stepNumber,
331
+ reviewType,
332
+ attempt,
333
+ spawnResult,
334
+ config,
335
+ });
336
+ const diagnostics = {
337
+ ...buildSpawnFailureDiagnostics(spawnResult, config),
338
+ ...(log?.logRef ? { reviewerOutputLogRef: log.logRef } : {}),
339
+ };
262
340
  journalReviewEvent("review.failed", journal, {
263
341
  stepNumber,
264
342
  reviewType,
@@ -266,7 +344,9 @@ export async function runStepReview({
266
344
  error: spawnResult.error,
267
345
  spawnFailed: true,
268
346
  exitCode: spawnResult.exitCode,
269
- ...(spawnResult.reason ? { reason: spawnResult.reason } : {}),
347
+ ...(spawnResult.reason && !providerError ? { reason: spawnResult.reason } : {}),
348
+ ...providerErrorFields(providerError),
349
+ ...diagnostics,
270
350
  });
271
351
  return {
272
352
  ok: false,
@@ -278,18 +358,38 @@ export async function runStepReview({
278
358
  spawnFailed: true,
279
359
  error: spawnResult.error,
280
360
  exitCode: spawnResult.exitCode ?? 1,
281
- reason: spawnResult.reason,
361
+ ...(providerError ? providerErrorFields(providerError) : { reason: spawnResult.reason }),
362
+ ...diagnostics,
282
363
  };
283
364
  }
284
365
 
285
366
  if (!fs.existsSync(artifactPath)) {
286
367
  const error = "reviewer exited but produced no artifact";
368
+ const log = persistReviewerLogForAttempt({
369
+ journal,
370
+ taskFolder,
371
+ stepNumber,
372
+ reviewType,
373
+ attempt,
374
+ spawnResult,
375
+ config,
376
+ });
377
+ const diagnostics = {
378
+ ...buildSpawnFailureDiagnostics(spawnResult, config),
379
+ ...(log?.logRef ? { reviewerOutputLogRef: log.logRef } : {}),
380
+ };
381
+ // The payload carries the reviewer's real exit code (typically 0) while
382
+ // the returned result keeps a non-zero exit code: the CLI and worker
383
+ // tools treat result exit 0 as success and must still fail closed.
287
384
  journalReviewEvent("review.failed", journal, {
288
385
  stepNumber,
289
386
  reviewType,
290
387
  reviewLevel,
291
388
  error,
292
389
  spawnFailed: true,
390
+ exitCode: spawnResult.exitCode ?? 0,
391
+ ...providerErrorFields(providerError),
392
+ ...diagnostics,
293
393
  });
294
394
  return {
295
395
  ok: false,
@@ -301,6 +401,8 @@ export async function runStepReview({
301
401
  spawnFailed: true,
302
402
  error,
303
403
  exitCode: 1,
404
+ ...providerErrorFields(providerError),
405
+ ...diagnostics,
304
406
  };
305
407
  }
306
408