pi-spine 2.27.1 → 2.28.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 (64) hide show
  1. package/bin/spine-batch.mjs +46 -4
  2. package/bin/spine-cli/cli-args.mjs +117 -0
  3. package/bin/spine-gate.mjs +28 -21
  4. package/bin/spine-integrate.mjs +28 -7
  5. package/bin/spine-issue.mjs +2 -1
  6. package/bin/spine-settings.mjs +7 -9
  7. package/bin/spine-tasks.mjs +1 -0
  8. package/bin/spine-worker-runner.mjs +21 -8
  9. package/bin/spine.mjs +10 -3
  10. package/package.json +1 -1
  11. package/skills/create-spine-tasks/references/prompt-template.md +5 -0
  12. package/skills/spine-release-operator/SKILL.md +14 -2
  13. package/src/batch/contract-exec.mjs +2 -3
  14. package/src/batch/contract-task-start.mjs +23 -1
  15. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  16. package/src/batch/diagnosis-primary-failure.mjs +35 -0
  17. package/src/batch/engine-lanes/matrix-run.mjs +2 -0
  18. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  19. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  20. package/src/batch/engine-lanes/review-code.mjs +20 -0
  21. package/src/batch/engine-lanes/review-final.mjs +10 -2
  22. package/src/batch/engine-lanes/review-poll.mjs +33 -0
  23. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  24. package/src/batch/engine-lanes.mjs +18 -17
  25. package/src/batch/evidence-command.mjs +18 -21
  26. package/src/batch/evidence-exec.mjs +79 -0
  27. package/src/batch/journal.mjs +5 -3
  28. package/src/batch/metrics-rollup.mjs +98 -4
  29. package/src/batch/metrics.mjs +134 -9
  30. package/src/batch/provider-quota.mjs +174 -6
  31. package/src/batch/quota-fallback.mjs +87 -6
  32. package/src/batch/reconcile-classify.mjs +28 -1
  33. package/src/batch/reconcile-diagnosis-context.mjs +2 -0
  34. package/src/batch/resume-lane-reviews.mjs +11 -10
  35. package/src/batch/retry-profile.mjs +77 -0
  36. package/src/batch/retry.mjs +32 -1
  37. package/src/batch/review-step-run.mjs +4 -0
  38. package/src/batch/review-step.mjs +1 -0
  39. package/src/batch/sequence-wait.mjs +7 -5
  40. package/src/batch/state-io.mjs +29 -3
  41. package/src/batch/worker-heartbeat.mjs +10 -2
  42. package/src/batch/worker-host.mjs +1 -1
  43. package/src/batch/worker-prompt.mjs +4 -5
  44. package/src/cli/deps.mjs +3 -2
  45. package/src/config/agent-model-resolve.mjs +144 -8
  46. package/src/config/contract.mjs +20 -0
  47. package/src/config/model-family.mjs +60 -0
  48. package/src/config/preflight/discovery.mjs +1 -0
  49. package/src/config/settings-fields.mjs +15 -0
  50. package/src/config/spine-config-schema.mjs +49 -0
  51. package/src/doctor/agent-model-inherit.mjs +78 -1
  52. package/src/doctor/agent-template-drift.mjs +65 -0
  53. package/src/doctor/run-doctor-checks.mjs +8 -1
  54. package/src/doctor/stet-capacity.mjs +171 -0
  55. package/src/metrics/quota-cli.mjs +16 -0
  56. package/src/metrics/quota-probes.mjs +228 -31
  57. package/src/metrics/quota-snapshot.mjs +21 -2
  58. package/src/planner/graph.mjs +7 -5
  59. package/src/planner/pending.mjs +2 -2
  60. package/src/planner/scope.mjs +3 -3
  61. package/src/tasks/packet/parse-prompt.mjs +47 -0
  62. package/src/tasks/packet/validate-prompt.mjs +156 -1
  63. package/templates/agents/reviewer.md +3 -1
  64. package/templates/agents/worker.md +15 -19
@@ -4,6 +4,8 @@
4
4
  * Kept out of diagnosis.mjs so the parent stays under the phase23 LOC cap.
5
5
  */
6
6
 
7
+ import { QUOTA_FALLBACK_EXPIRY_GRACE_MS } from "./quota-fallback.mjs";
8
+
7
9
  /**
8
10
  * True when the latest quota-exhaustion journal payload came from
9
11
  * `batch.quota_fallback_exhausted` — the parallel arrays are unique to that
@@ -87,6 +89,22 @@ export function buildBackground(diagnosis, ctx = {}) {
87
89
  fallback.exhaustedPool ?? "?"
88
90
  } -> ${fallback.toProfile}, batch ${ctx.batchId ?? "?"})`,
89
91
  );
92
+ // SP-843 (#350): the hop is sticky until its reset time passes or the operator
93
+ // clears it — show which, and name the clear command once the fallback pool died too.
94
+ const expiresAtMs =
95
+ typeof fallback.resetAt === "number" && Number.isFinite(fallback.resetAt)
96
+ ? fallback.resetAt + QUOTA_FALLBACK_EXPIRY_GRACE_MS
97
+ : null;
98
+ facts.push(
99
+ expiresAtMs !== null
100
+ ? `Quota fallback expires ${new Date(expiresAtMs).toISOString()}`
101
+ : "Quota fallback has no parsable reset time (no automatic expiry)",
102
+ );
103
+ if (isFallbackChainExhausted(ctx.lastQuotaExhausted)) {
104
+ facts.push(
105
+ "Fallback pool is also exhausted: after the primary pool resets, run `spine batch quota-fallback clear` (paused/failed batch), then `spine batch retry <taskId>` / `spine batch resume`",
106
+ );
107
+ }
90
108
  }
91
109
  if (ctx.launchFailureKind) {
92
110
  facts.push(`Launch failure kind: ${ctx.launchFailureKind}`);
@@ -14,6 +14,31 @@ export const PRIMARY_TASK_FAILURE_EXIT_REASONS = new Set([
14
14
 
15
15
  const LANE_COMMIT_EXIT_REASONS = new Set(["DirtyWorktree", "lane_commit_failed"]);
16
16
 
17
+ /** Suggested `contract.testTimeoutMs` after a timeout: double the 10-minute default. */
18
+ const CONTRACT_TIMEOUT_SUGGESTED_MS = 20 * 60 * 1000;
19
+
20
+ /**
21
+ * True when the latest contract verification for `taskId` failed because its
22
+ * testCommand timed out (#369), so diagnosis can name the timeout instead of
23
+ * pointing at PROMPT.md scope.
24
+ *
25
+ * @param {Array<{ type?: string, payload?: Record<string, any> }>} journalEvents
26
+ * @param {string|null|undefined} taskId
27
+ */
28
+ export function isContractTimeoutFailure(journalEvents, taskId) {
29
+ if (!taskId || !Array.isArray(journalEvents)) return false;
30
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
31
+ const event = journalEvents[index];
32
+ if (event?.type !== "contract.verified" && event?.type !== "contract.failed") continue;
33
+ if (event.payload?.taskId !== taskId) continue;
34
+ const checks = Array.isArray(event.payload?.checks) ? event.payload.checks : [];
35
+ return checks.some(
36
+ (check) => check?.field === "testCommand" && check.ok === false && /timed out after/.test(String(check.message ?? "")),
37
+ );
38
+ }
39
+ return false;
40
+ }
41
+
17
42
  /**
18
43
  * @param {string|null|undefined} exitReason
19
44
  */
@@ -27,6 +52,7 @@ export function isPrimaryTaskFailureExitReason(exitReason) {
27
52
  * @param {string|null} [ctx.exitReason]
28
53
  * @param {string|null} [ctx.failedTaskId]
29
54
  * @param {boolean} [ctx.mergeGitignoredFailure]
55
+ * @param {boolean} [ctx.contractTimedOut]
30
56
  */
31
57
  export function buildPrimaryFailureHeadline(batchLabel, ctx = {}) {
32
58
  if (LANE_COMMIT_EXIT_REASONS.has(ctx.exitReason ?? "")) {
@@ -49,6 +75,10 @@ export function buildPrimaryFailureHeadline(batchLabel, ctx = {}) {
49
75
  ? `${batchLabel} task ${ctx.failedTaskId} exhausted final review attempts — fix scope or implementation, then retry`
50
76
  : `${batchLabel} review attempts exhausted — fix scope or implementation, then retry`;
51
77
  }
78
+ if (ctx.exitReason === "contract_failed" && ctx.contractTimedOut) {
79
+ const subject = ctx.failedTaskId ? `task ${ctx.failedTaskId} contract testCommand` : "contract testCommand";
80
+ return `${batchLabel} ${subject} timed out — raise contract.testTimeoutMs or speed up the command, then retry`;
81
+ }
52
82
  if (ctx.exitReason === "contract_failed") {
53
83
  return ctx.failedTaskId
54
84
  ? `${batchLabel} task ${ctx.failedTaskId} failed contract verification — fix PROMPT.md scope, then retry`
@@ -95,6 +125,7 @@ export function buildDirtyWorktreeSuggestedCommand(ctx = {}) {
95
125
  * @param {string|null} [ctx.exitReason]
96
126
  * @param {string|null} [ctx.failedTaskId]
97
127
  * @param {string} [ctx.tasksRoot]
128
+ * @param {boolean} [ctx.contractTimedOut]
98
129
  */
99
130
  export function buildPrimaryFailureSuggestedCommand(ctx = {}) {
100
131
  if (LANE_COMMIT_EXIT_REASONS.has(ctx.exitReason ?? "")) {
@@ -110,6 +141,10 @@ export function buildPrimaryFailureSuggestedCommand(ctx = {}) {
110
141
  ? `spine batch retry ${ctx.failedTaskId}`
111
142
  : "spine status --diagnose";
112
143
  }
144
+ if (ctx.exitReason === "contract_failed" && ctx.contractTimedOut) {
145
+ const retry = ctx.failedTaskId ? `spine batch retry ${ctx.failedTaskId}` : "spine batch resume";
146
+ return `spine settings set contract.testTimeoutMs ${CONTRACT_TIMEOUT_SUGGESTED_MS} && ${retry}`;
147
+ }
113
148
  if (ctx.exitReason === "contract_failed") {
114
149
  const tasksRoot = ctx.tasksRoot ?? "spine-tasks";
115
150
  return ctx.failedTaskId
@@ -322,6 +322,8 @@ export async function runMatrixSubLane({
322
322
  const verify = await verifyContract(worktreePath, contract, {
323
323
  matrixRow: values,
324
324
  baseBranch,
325
+ contract: config?.contract,
326
+ contractTestMaxBuffer: config?.contractTestMaxBuffer,
325
327
  });
326
328
  if (verify.ok) {
327
329
  result = {
@@ -25,11 +25,16 @@
25
25
  * again (the SP-807 decision returns `stop/task_retry_spent` for a task
26
26
  * already in `retriedTaskIds`).
27
27
  *
28
+ * - an active hop whose parsed reset time (plus grace) has passed is cleared
29
+ * before the run and again before each decision (SP-843, #350), so the task
30
+ * spawns on the primary profile and a later exhaustion may hop again.
31
+ *
28
32
  * Matrix tasks, reviewer, and supervisor runs are out of scope by design.
29
33
  */
30
34
 
31
35
  import {
32
36
  applyQuotaFallback,
37
+ clearExpiredQuotaFallback,
33
38
  recordQuotaFallbackExhausted,
34
39
  recordQuotaFallbackRetry,
35
40
  resolveEffectiveWorkerModel,
@@ -82,6 +87,7 @@ export async function runWithQuotaFallback(
82
87
  runOnce,
83
88
  { projectRoot, batchId, state, taskId, config, workerBackend, now = Date.now() },
84
89
  ) {
90
+ await clearExpiredQuotaFallback({ projectRoot, batchId, state, now });
85
91
  pinTaskWorkerModel(state, config, taskId);
86
92
  const result = await runOnce();
87
93
  if (result.ok || result.workerResult?.classification !== "provider_quota_exhausted") {
@@ -95,6 +101,10 @@ export async function runWithQuotaFallback(
95
101
  return result;
96
102
  }
97
103
 
104
+ // A long task can outlive the hop; clear it first so the decision below sees
105
+ // the primary pool as active (this is the only `await` before the decision).
106
+ await clearExpiredQuotaFallback({ projectRoot, batchId, state, now });
107
+
98
108
  // Synchronous decide → apply section: no `await` between the read inside
99
109
  // decideQuotaFallback and the `state.resilience.quotaFallback` write at the
100
110
  // top of applyQuotaFallback, so parallel lanes cannot both decide `apply`.
@@ -104,6 +114,7 @@ export async function runWithQuotaFallback(
104
114
  classification,
105
115
  taskId,
106
116
  workerBackend,
117
+ now,
107
118
  });
108
119
  if (decision.action === "stop") {
109
120
  recordQuotaFallbackExhausted({ projectRoot, batchId, decision, taskId });
@@ -11,6 +11,9 @@
11
11
  * `task.quota_fallback_retry`;
12
12
  * - `recordQuotaFallbackExhausted` journals `batch.quota_fallback_exhausted`
13
13
  * with every exhausted pool and its reset text;
14
+ * - `clearExpiredQuotaFallback` / `clearQuotaFallbackByOperator` delete the hop
15
+ * (reset time passed, or explicit `spine batch quota-fallback clear`) and
16
+ * journal `batch.quota_fallback_cleared` once (SP-843, #350);
14
17
  * - `quotaFallbackWorkerEnv` / `resolveEffectiveWorkerModel` /
15
18
  * `loadQuotaFallbackForWorker` let `runWorker` re-apply the persisted hop to
16
19
  * every later worker spawn (sticky override) and report the model actually
@@ -23,8 +26,13 @@
23
26
 
24
27
  import { appendJournalEvent } from "../journal.mjs";
25
28
  import { saveEngineBatchState } from "../pause.mjs";
26
- import { buildQuotaFallbackState, markQuotaFallbackRetry } from "../quota-fallback.mjs";
27
- import { loadSpineBatchState } from "../state-io.mjs";
29
+ import {
30
+ buildQuotaFallbackState,
31
+ isQuotaFallbackExpired,
32
+ markQuotaFallbackRetry,
33
+ } from "../quota-fallback.mjs";
34
+ import { loadMutableBatch } from "../retry.mjs";
35
+ import { loadSpineBatchState, updateSpineBatchState } from "../state-io.mjs";
28
36
 
29
37
  /** @typedef {import("../quota-fallback.mjs").QuotaFallbackState} QuotaFallbackState */
30
38
  /** @typedef {import("../quota-fallback.mjs").QuotaFallbackApplyResult} QuotaFallbackApplyResult */
@@ -67,6 +75,140 @@ export async function applyQuotaFallback({ projectRoot, batchId, state, decision
67
75
  return fallbackState;
68
76
  }
69
77
 
78
+ /**
79
+ * Journals `batch.quota_fallback_cleared` for a hop that was just deleted.
80
+ *
81
+ * @param {object} params
82
+ * @param {string} params.projectRoot
83
+ * @param {string} params.batchId
84
+ * @param {"expired"|"operator"} params.reason
85
+ * @param {QuotaFallbackState} params.fallbackState The deleted hop.
86
+ */
87
+ function journalQuotaFallbackCleared({ projectRoot, batchId, reason, fallbackState }) {
88
+ appendJournalEvent(projectRoot, batchId, "batch.quota_fallback_cleared", {
89
+ reason,
90
+ fromProfile: fallbackState.fromProfile ?? null,
91
+ toProfile: fallbackState.toProfile ?? null,
92
+ exhaustedPool: fallbackState.exhaustedPool ?? null,
93
+ resetAt: fallbackState.resetAt ?? null,
94
+ });
95
+ }
96
+
97
+ /**
98
+ * Clears the hop when its parsed reset time (plus grace) has passed: deletes
99
+ * `state.resilience.quotaFallback`, persists, and journals
100
+ * `batch.quota_fallback_cleared` with `reason: "expired"` exactly once. The
101
+ * in-memory delete happens before the first `await`, so parallel lanes sharing
102
+ * `state` in one engine process cannot both journal the clear. A hop with no
103
+ * parsable reset time never expires.
104
+ *
105
+ * @param {object} params
106
+ * @param {string} params.projectRoot
107
+ * @param {string} params.batchId
108
+ * @param {Record<string, any>} params.state Live batch state (mutated in place, then persisted).
109
+ * @param {Date|number} [params.now] Clock injection point (default `Date.now()`).
110
+ * @returns {Promise<QuotaFallbackState|null>} The cleared hop, or null when nothing expired.
111
+ */
112
+ export async function clearExpiredQuotaFallback({ projectRoot, batchId, state, now = Date.now() }) {
113
+ const fallbackState = state.resilience?.quotaFallback;
114
+ if (!fallbackState || typeof fallbackState !== "object" || !isQuotaFallbackExpired(fallbackState, now)) {
115
+ return null;
116
+ }
117
+ delete state.resilience.quotaFallback;
118
+ await saveEngineBatchState(projectRoot, state);
119
+ journalQuotaFallbackCleared({ projectRoot, batchId, reason: "expired", fallbackState });
120
+ return fallbackState;
121
+ }
122
+
123
+ /** Batch phases in which the operator may clear the hop (the engine is not mutating state). */
124
+ const OPERATOR_CLEAR_PHASES = new Set(["paused", "failed", "needs_retry"]);
125
+
126
+ /**
127
+ * Operator `spine batch quota-fallback clear`: deletes the hop from a batch that
128
+ * is not running and journals `batch.quota_fallback_cleared` with
129
+ * `reason: "operator"`. Refuses while the batch runs (the engine would rewrite
130
+ * the hop from its in-memory state) and when no hop is active.
131
+ *
132
+ * @param {object} params
133
+ * @param {string} params.projectRoot
134
+ * @returns {{ ok: boolean, exitCode: number, error?: string, output: string, batchId?: string, phase?: string, cleared?: QuotaFallbackState, nextCommands?: string[] }}
135
+ */
136
+ export function clearQuotaFallbackByOperator({ projectRoot }) {
137
+ const loaded = loadMutableBatch(projectRoot);
138
+ if (!loaded.ok) return loaded.result;
139
+ const state = /** @type {Record<string, any>} */ (loaded.state);
140
+ const batchId = String(state.batchId ?? "");
141
+ const phase = String(state.phase ?? "");
142
+
143
+ if (!OPERATOR_CLEAR_PHASES.has(phase)) {
144
+ return {
145
+ ok: false,
146
+ exitCode: 1,
147
+ error: "cannot_clear_quota_fallback",
148
+ output: `Cannot clear the quota fallback while batch phase is ${phase}. Pause the batch first (paused, failed, or needs_retry batches only).\n`,
149
+ batchId,
150
+ phase,
151
+ };
152
+ }
153
+ const fallbackState = state.resilience?.quotaFallback;
154
+ if (!fallbackState || typeof fallbackState !== "object") {
155
+ return {
156
+ ok: false,
157
+ exitCode: 1,
158
+ error: "no_quota_fallback",
159
+ output: `No quota fallback is active for batch ${batchId}.\n`,
160
+ batchId,
161
+ phase,
162
+ };
163
+ }
164
+
165
+ const updated = updateSpineBatchState(projectRoot, (draft) => {
166
+ if (!draft.resilience?.quotaFallback) return false;
167
+ delete draft.resilience.quotaFallback;
168
+ return true;
169
+ });
170
+ if (!updated.ok) {
171
+ return {
172
+ ok: false,
173
+ exitCode: 1,
174
+ error: updated.reason ?? "state_write_failed",
175
+ output: `Could not clear the quota fallback: ${updated.reason ?? "state write failed"}.\n`,
176
+ batchId,
177
+ phase,
178
+ };
179
+ }
180
+ if (!updated.changed) {
181
+ return {
182
+ ok: false,
183
+ exitCode: 1,
184
+ error: "no_quota_fallback",
185
+ output: `No quota fallback is active for batch ${batchId}.\n`,
186
+ batchId,
187
+ phase,
188
+ };
189
+ }
190
+
191
+ journalQuotaFallbackCleared({ projectRoot, batchId, reason: "operator", fallbackState });
192
+ const failedTaskIds = (state.tasks ?? [])
193
+ .filter((/** @type {any} */ task) => task?.status === "failed")
194
+ .map((/** @type {any} */ task) => String(task.taskId));
195
+ const nextCommands = [
196
+ ...failedTaskIds.map((/** @type {string} */ taskId) => `spine batch retry ${taskId}`),
197
+ "spine batch resume",
198
+ ];
199
+ return {
200
+ ok: true,
201
+ exitCode: 0,
202
+ output:
203
+ `Cleared quota fallback for batch ${batchId} (was ${fallbackState.exhaustedPool ?? "?"} → ${fallbackState.toProfile ?? "?"}).\n` +
204
+ `Next: ${nextCommands.join(" , then ")}\n`,
205
+ batchId,
206
+ phase,
207
+ cleared: fallbackState,
208
+ nextCommands,
209
+ };
210
+ }
211
+
70
212
  /**
71
213
  * Records that a task consumed its one auto-retry onto the fallback pool:
72
214
  * appends the taskId to the persisted state (SP-807 `markQuotaFallbackRetry`,
@@ -159,22 +301,26 @@ export function resolveEffectiveWorkerModel(config, fallbackState) {
159
301
  * Read-only load of the persisted quota fallback for a worker spawn
160
302
  * (`runWorker` must never write batch state). Returns the fallback state when
161
303
  * the on-disk batch state belongs to `batchId` and carries one; `null` when
162
- * the state file is missing, unreadable, stale (different batch), or has no
163
- * active hop — in every case the caller behaves as if no override exists.
304
+ * the state file is missing, unreadable, stale (different batch), has no
305
+ * active hop, or the hop is expired at `now` (SP-843) — in every case the
306
+ * caller behaves as if no override exists. The expired hop is only ignored
307
+ * here; the engine deletes and journals it via {@link clearExpiredQuotaFallback}.
164
308
  *
165
309
  * @param {object} params
166
310
  * @param {string} params.projectRoot
167
311
  * @param {string} params.batchId
312
+ * @param {Date|number} [params.now] Clock injection point (default `Date.now()`).
168
313
  * @returns {QuotaFallbackState|null}
169
314
  */
170
- export function loadQuotaFallbackForWorker({ projectRoot, batchId }) {
315
+ export function loadQuotaFallbackForWorker({ projectRoot, batchId, now = Date.now() }) {
171
316
  if (!projectRoot || !batchId) return null;
172
317
  const loaded = loadSpineBatchState(projectRoot);
173
318
  const state = loaded.raw;
174
319
  if (!state || typeof state !== "object") return null;
175
320
  if (String(state.batchId ?? "") !== String(batchId)) return null;
176
321
  const fallback = state.resilience?.quotaFallback;
177
- return fallback && typeof fallback === "object" ? fallback : null;
322
+ if (!fallback || typeof fallback !== "object") return null;
323
+ return isQuotaFallbackExpired(fallback, now) ? null : fallback;
178
324
  }
179
325
 
180
326
  /**
@@ -190,10 +336,11 @@ export function loadQuotaFallbackForWorker({ projectRoot, batchId }) {
190
336
  * @param {string} [params.batchId]
191
337
  * @param {object|undefined} params.config Resolved spine config.
192
338
  * @param {Record<string, string>} [params.extraEnv] Caller-supplied child env.
339
+ * @param {Date|number} [params.now] Clock injection point (default `Date.now()`).
193
340
  * @returns {{ fallback: QuotaFallbackState|null, workerModel: string|undefined, extraEnv: Record<string, string> }}
194
341
  */
195
- export function resolveWorkerQuotaFallbackContext({ projectRoot, batchId, config, extraEnv }) {
196
- const fallback = projectRoot && batchId ? loadQuotaFallbackForWorker({ projectRoot, batchId }) : null;
342
+ export function resolveWorkerQuotaFallbackContext({ projectRoot, batchId, config, extraEnv, now = Date.now() }) {
343
+ const fallback = projectRoot && batchId ? loadQuotaFallbackForWorker({ projectRoot, batchId, now }) : null;
197
344
  return {
198
345
  fallback,
199
346
  workerModel: resolveEffectiveWorkerModel(config, fallback),
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { recordLaneTaskMetric } from "./queue.mjs";
6
6
  import { REVIEW_DEFAULTS } from "../../config/defaults.mjs";
7
+ import { isValidCommitSha, resolveTaskStartCommit } from "../contract-task-start.mjs";
7
8
  import { appendJournalEvent, readJournalEvents } from "../journal.mjs";
8
9
  import {
9
10
  recomputeTaskCounters,
@@ -35,6 +36,7 @@ import {
35
36
  * @param {number} [params.attempt]
36
37
  * @param {Record<string, any>} [params.journal]
37
38
  * @param {{ next: () => string } | null} [params.stubVerdicts]
39
+ * @param {string|null} [params.baseline] Validated task start commit (#343).
38
40
  * @returns {Promise<{ ok: boolean, [key: string]: any }>}
39
41
  */
40
42
  export async function runEngineCodeReview({
@@ -44,6 +46,7 @@ export async function runEngineCodeReview({
44
46
  attempt = 1,
45
47
  journal,
46
48
  stubVerdicts = null,
49
+ baseline = null,
47
50
  }) {
48
51
  const reviewLevel = readReviewLevel(taskFolder);
49
52
  if (!shouldRunCodeReview({ reviewLevel })) {
@@ -113,6 +116,7 @@ export async function runEngineCodeReview({
113
116
  reviewType: "code",
114
117
  config,
115
118
  journal,
119
+ ...(isValidCommitSha(baseline) ? { baseline } : {}),
116
120
  });
117
121
  }
118
122
 
@@ -224,6 +228,21 @@ export async function runCodeReviewPhase({
224
228
 
225
229
  const stubVerdicts = shouldUseReviewStub() ? createPhaseStubVerdictQueue("code") : null;
226
230
 
231
+ // #343: workers commit per step, so diff against the task start commit, not the working tree.
232
+ const baseline = resolveTaskStartCommit({
233
+ journal: journalEvents,
234
+ taskId: task.taskId,
235
+ laneId: lane.laneId,
236
+ batchId,
237
+ worktreePath: wt,
238
+ });
239
+ if (!baseline) {
240
+ appendJournalEvent(projectRoot, batchId, "review.baseline_missing", {
241
+ taskId: task.taskId,
242
+ reviewType: "code",
243
+ });
244
+ }
245
+
227
246
  return await runReviewPollLoop({
228
247
  reviewType: "code",
229
248
  passVerdict: "APPROVE",
@@ -234,6 +253,7 @@ export async function runCodeReviewPhase({
234
253
  runEngineCodeReview(/** @type {any} */ ({ ...params, stubVerdicts })),
235
254
  recordReviewTaskFailure: recordCodeReviewTaskFailure,
236
255
  invalidVerdictOutput: "code review artifact missing APPROVE or REVISE verdict",
256
+ beforeReview: async () => ({ extraReviewParams: baseline ? { baseline } : {} }),
237
257
  journalEvents,
238
258
  projectRoot,
239
259
  state,
@@ -199,6 +199,8 @@ function recordFinalReviewTaskFailure({
199
199
  task.status = "failed";
200
200
  task.endedAt = Date.now();
201
201
  task.exitReason = exitReason;
202
+ // SP-837 (#325): surface the final verdict on the worker task metric record.
203
+ if (verdict != null) task.finalVerdict = verdict;
202
204
  updateSegmentForTask(state, taskId, "failed");
203
205
  recomputeTaskCounters(state);
204
206
  saveSpineBatchState(projectRoot, state);
@@ -347,9 +349,12 @@ export async function runFinalReviewPhase({
347
349
  journalEvents,
348
350
  worktreePath: wt,
349
351
  });
350
- if (honoredResult) return honoredResult;
352
+ if (honoredResult) {
353
+ task.finalVerdict = honoredResult.verdict;
354
+ return honoredResult;
355
+ }
351
356
 
352
- return await runReviewPollLoop({
357
+ const pollResult = await runReviewPollLoop({
353
358
  reviewType: "final",
354
359
  passVerdict: "PASS",
355
360
  attemptField: "finalAttempts",
@@ -388,4 +393,7 @@ export async function runFinalReviewPhase({
388
393
  laneCorrelationId,
389
394
  fileScopePaths,
390
395
  });
396
+ // SP-837 (#325): REVISE/REPLAN/invalid verdicts are set by recordFinalReviewTaskFailure.
397
+ if (pollResult.ok && pollResult.verdict === "PASS") task.finalVerdict = "PASS";
398
+ return pollResult;
391
399
  }
@@ -10,6 +10,7 @@ import fs from "node:fs";
10
10
  import path from "node:path";
11
11
  import { recordLaneTaskMetric } from "./queue.mjs";
12
12
  import { appendJournalEvent } from "../journal.mjs";
13
+ import { recordReviewMetric } from "../metrics.mjs";
13
14
  import {
14
15
  recomputeTaskCounters,
15
16
  saveSpineBatchState,
@@ -317,6 +318,7 @@ export async function runReviewPollLoop({
317
318
  extraReviewParams = gate?.extraReviewParams ?? {};
318
319
  }
319
320
 
321
+ const reviewStartedAt = Date.now();
320
322
  const reviewResult = await runEngineReview({
321
323
  taskFolder: taskFolderInWorktree,
322
324
  worktreePath: wt,
@@ -333,6 +335,24 @@ export async function runReviewPollLoop({
333
335
  : reviewResult.reason === REVIEW_PROVIDER_ERROR_REASON
334
336
  ? `${reviewType}_review_provider_error`
335
337
  : `${reviewType}_review_spawn_failed`;
338
+ // SP-837 (#325): one reviewer row per spawn failure / timeout / provider error.
339
+ recordReviewMetric({
340
+ projectRoot,
341
+ config,
342
+ batchId,
343
+ taskId,
344
+ laneNumber,
345
+ reviewType,
346
+ attempt: reviewAttempt + 1,
347
+ durationMs: Date.now() - reviewStartedAt,
348
+ outcome:
349
+ reviewResult.reason === REVIEW_TIMEOUT_REASON
350
+ ? "timeout"
351
+ : reviewResult.reason === REVIEW_PROVIDER_ERROR_REASON
352
+ ? "provider_error"
353
+ : "spawn_failed",
354
+ failureReason: typeof reviewResult.reason === "string" ? reviewResult.reason : undefined,
355
+ });
336
356
  recordReviewTaskFailure({
337
357
  projectRoot,
338
358
  state,
@@ -368,6 +388,19 @@ export async function runReviewPollLoop({
368
388
  artifactPath: reviewResult.artifactPath,
369
389
  [attemptKey]: reviewAttempt + 1,
370
390
  });
391
+ // SP-837 (#325): one reviewer row per recorded verdict (attempt is 1-based).
392
+ recordReviewMetric({
393
+ projectRoot,
394
+ config,
395
+ batchId,
396
+ taskId,
397
+ laneNumber,
398
+ reviewType,
399
+ verdict: typeof reviewResult.verdict === "string" ? reviewResult.verdict : undefined,
400
+ attempt: reviewAttempt + 1,
401
+ durationMs: Date.now() - reviewStartedAt,
402
+ outcome: "verdict",
403
+ });
371
404
 
372
405
  if (reviewResult.verdict === passVerdict) {
373
406
  task[attemptField] = reviewAttempt + 1;