pi-spine 2.27.0 → 2.28.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 (71) hide show
  1. package/bin/spine-batch.mjs +46 -4
  2. package/bin/spine-tasks.mjs +1 -0
  3. package/bin/spine-worker-runner.mjs +17 -3
  4. package/package.json +1 -1
  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 +77 -8
  9. package/skills/spine-release-operator/SKILL.md +43 -52
  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/contract-task-start.mjs +23 -1
  15. package/src/batch/diagnosis-alternatives.mjs +16 -1
  16. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  17. package/src/batch/diagnosis-pending-lane.mjs +18 -0
  18. package/src/batch/diagnosis-review-infra.mjs +144 -0
  19. package/src/batch/diagnosis-suggested-command.mjs +9 -0
  20. package/src/batch/diagnosis.mjs +19 -20
  21. package/src/batch/engine-lanes/merge.mjs +0 -8
  22. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  23. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  24. package/src/batch/engine-lanes/review-code.mjs +20 -0
  25. package/src/batch/engine-lanes/review-final.mjs +10 -2
  26. package/src/batch/engine-lanes/review-poll.mjs +37 -1
  27. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  28. package/src/batch/engine-lanes.mjs +18 -18
  29. package/src/batch/gate-posture-approve.mjs +154 -15
  30. package/src/batch/integrate-path-delete.mjs +85 -0
  31. package/src/batch/integrate-worktree.mjs +20 -27
  32. package/src/batch/journal.mjs +5 -3
  33. package/src/batch/metrics-rollup.mjs +98 -4
  34. package/src/batch/metrics.mjs +134 -9
  35. package/src/batch/provider-quota.mjs +156 -7
  36. package/src/batch/quota-fallback.mjs +87 -6
  37. package/src/batch/reconcile-diagnosis.mjs +24 -77
  38. package/src/batch/resume-lane-reviews.mjs +11 -10
  39. package/src/batch/retry-profile.mjs +77 -0
  40. package/src/batch/retry.mjs +32 -1
  41. package/src/batch/review-artifacts.mjs +3 -2
  42. package/src/batch/review-level-effective.mjs +19 -0
  43. package/src/batch/review-spawn.mjs +12 -1
  44. package/src/batch/review-step-run.mjs +18 -2
  45. package/src/batch/review-step.mjs +1 -0
  46. package/src/batch/reviewer-provider-error.mjs +153 -0
  47. package/src/batch/worker-heartbeat.mjs +10 -2
  48. package/src/batch/worker-host.mjs +1 -1
  49. package/src/batch/worker-prompt.mjs +9 -7
  50. package/src/cli/deps.mjs +3 -2
  51. package/src/config/agent-model-resolve.mjs +144 -8
  52. package/src/config/cursor-rules/discover.mjs +38 -1
  53. package/src/config/model-family.mjs +60 -0
  54. package/src/config/preflight/discovery.mjs +1 -0
  55. package/src/config/settings-fields.mjs +11 -0
  56. package/src/config/spine-config-schema.mjs +87 -0
  57. package/src/doctor/agent-model-inherit.mjs +78 -1
  58. package/src/doctor/pi-extension-hooks.mjs +322 -0
  59. package/src/doctor/run-doctor-checks.mjs +18 -2
  60. package/src/metrics/quota-cli.mjs +16 -0
  61. package/src/metrics/quota-probes.mjs +228 -31
  62. package/src/metrics/quota-snapshot.mjs +21 -2
  63. package/src/planner/graph.mjs +7 -5
  64. package/src/planner/pending.mjs +2 -2
  65. package/src/planner/scope.mjs +3 -3
  66. package/src/tasks/packet/parse-prompt.mjs +47 -0
  67. package/src/tasks/packet/validate-prompt.mjs +167 -2
  68. package/src/tasks/validate-contract-warn.mjs +16 -0
  69. package/templates/agents/reviewer.md +3 -1
  70. package/templates/agents/worker.md +15 -19
  71. package/templates/spine-config.json +1 -1
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Review-infrastructure exit reasons and failure-exit-reason resolution shared
3
+ * by `reconcile-diagnosis.mjs` and `diagnosis-pending-lane.mjs` (SP-821/#334).
4
+ * Leaf module — importing it from anywhere in `src/batch/` keeps the import
5
+ * graph acyclic (checked by tests/arch/import-cycles.test.mjs).
6
+ */
7
+
8
+ /**
9
+ * Exit reasons where reviewer *infrastructure* failed: the reviewer failed to
10
+ * spawn, timed out, or hit a provider error, so no verdict was produced. The
11
+ * implementation itself is not the failure (#291 / SP-718). Covers all three
12
+ * engine review types; the provider-error variants were added by SP-820.
13
+ *
14
+ * @type {ReadonlySet<string>}
15
+ */
16
+ export const REVIEW_INFRASTRUCTURE_EXIT_REASONS = new Set([
17
+ "plan_review_spawn_failed",
18
+ "plan_review_timeout",
19
+ "plan_review_provider_error",
20
+ "code_review_spawn_failed",
21
+ "code_review_timeout",
22
+ "code_review_provider_error",
23
+ "final_review_spawn_failed",
24
+ "final_review_timeout",
25
+ "final_review_provider_error",
26
+ ]);
27
+
28
+ /**
29
+ * @param {string|null|undefined} exitReason
30
+ * @returns {boolean}
31
+ */
32
+ export function isReviewInfraExitReason(exitReason) {
33
+ return REVIEW_INFRASTRUCTURE_EXIT_REASONS.has(String(exitReason ?? ""));
34
+ }
35
+
36
+ /**
37
+ * Review type ("plan" | "code" | "final") for a review-infra exit reason.
38
+ *
39
+ * @param {string|null|undefined} exitReason
40
+ * @returns {string|null}
41
+ */
42
+ export function resolveReviewInfraType(exitReason) {
43
+ const match = String(exitReason ?? "").match(/^(plan|code|final)_review_(?:spawn_failed|timeout|provider_error)$/);
44
+ return match ? (match[1] ?? null) : null;
45
+ }
46
+
47
+ /**
48
+ * @param {string|null|undefined} exitReason
49
+ * @returns {boolean}
50
+ */
51
+ export function isReviewInfraProviderError(exitReason) {
52
+ return String(exitReason ?? "").endsWith("_provider_error");
53
+ }
54
+
55
+ /**
56
+ * @param {unknown} rawTasks
57
+ * @param {string|null} failedTaskId
58
+ * @returns {string|null}
59
+ */
60
+ export function resolveFailedExitReason(rawTasks, failedTaskId) {
61
+ if (!failedTaskId || !Array.isArray(rawTasks)) return null;
62
+ const match = rawTasks.find((/** @type {any} */ entry) => {
63
+ if (!entry || typeof entry !== "object") return false;
64
+ return String(entry.taskId ?? entry.id ?? "") === failedTaskId;
65
+ });
66
+ if (!match || typeof match !== "object") return null;
67
+ const exitReason = /** @type {{ exitReason?: unknown }} */ (match).exitReason;
68
+ return typeof exitReason === "string" && exitReason ? exitReason : null;
69
+ }
70
+
71
+ /**
72
+ * @param {string|null} failedTaskId
73
+ * @param {Record<string, any>} signals
74
+ * @returns {string|null}
75
+ */
76
+ export function resolvePrimaryFailureExitReason(failedTaskId, signals) {
77
+ const fromTask = resolveFailedExitReason(signals.raw?.tasks, failedTaskId);
78
+ if (fromTask) return fromTask;
79
+ if (!failedTaskId) return null;
80
+ if (Array.isArray(signals.segments)) {
81
+ const segment = signals.segments.find((/** @type {any} */ entry) => entry?.taskId === failedTaskId);
82
+ const classification = segment?.classification;
83
+ if (
84
+ typeof classification === "string" &&
85
+ classification &&
86
+ classification !== "terminal-failure"
87
+ ) {
88
+ return classification;
89
+ }
90
+ }
91
+ if (Array.isArray(signals.journalEvents)) {
92
+ for (let index = signals.journalEvents.length - 1; index >= 0; index -= 1) {
93
+ const event = signals.journalEvents[index];
94
+ if (event.type !== "task.failed") continue;
95
+ const eventTaskId = event.taskId ?? event.payload?.taskId;
96
+ if (eventTaskId !== failedTaskId) continue;
97
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
98
+ const reason = payload.exitReason ?? payload.classification;
99
+ if (typeof reason === "string" && reason) return reason;
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * Exit reason for a classified task entry: the entry's own `exitReason` when
107
+ * present, else the primary failure resolution (raw state → segments →
108
+ * journal `task.failed`). Parsed batch-state tasks drop `exitReason`
109
+ * (normalizeTasks), so the fallback keeps journal-only timelines working.
110
+ *
111
+ * @param {Record<string, any>|null|undefined} task
112
+ * @param {Record<string, any>} signals
113
+ * @returns {string|null}
114
+ */
115
+ export function resolveTaskPrimaryFailureExitReason(task, signals) {
116
+ const fromTask = task?.exitReason;
117
+ if (typeof fromTask === "string" && fromTask) return fromTask;
118
+ return resolvePrimaryFailureExitReason(String(task?.taskId ?? ""), signals);
119
+ }
120
+
121
+ /**
122
+ * Headline for a needs_retry diagnosis caused by a review-infrastructure exit
123
+ * reason: the reviewer produced no verdict, so the review should re-run —
124
+ * not salvage-integrate unreviewed code (SP-821/#334, reversing SP-762).
125
+ * Provider-error variants point at `spine doctor` for launch diagnosis.
126
+ *
127
+ * @param {string} batchLabel
128
+ * @param {object} ctx
129
+ * @param {string|null} [ctx.exitReason]
130
+ * @param {string|null} [ctx.failedTaskId]
131
+ * @returns {string|null} null when `ctx.exitReason` is not a review-infra reason
132
+ */
133
+ export function buildReviewInfraHeadline(batchLabel, ctx = {}) {
134
+ const exitReason = ctx.exitReason ?? "";
135
+ if (!isReviewInfraExitReason(exitReason)) return null;
136
+ const reviewType = resolveReviewInfraType(exitReason) ?? "review";
137
+ const providerError = isReviewInfraProviderError(exitReason);
138
+ const problem = providerError
139
+ ? `${reviewType} review hit a provider error`
140
+ : `${reviewType} review produced no verdict`;
141
+ const taskSuffix = ctx.failedTaskId ? ` for task ${ctx.failedTaskId}` : "";
142
+ const doctorSuffix = providerError ? " — run spine doctor" : "";
143
+ return `${batchLabel} ${problem}${taskSuffix} (lane work is done) — re-run the review${doctorSuffix}`;
144
+ }
@@ -19,6 +19,7 @@ import { buildPrimaryFailureSuggestedCommand } from "./diagnosis-primary-failure
19
19
  import { buildEngineOrphanParentExitSuggestedCommand } from "./diagnosis-parent-exit.mjs";
20
20
  import { sanitizeRetrySuggestedCommand } from "./diagnosis-retry-command.mjs";
21
21
  import { buildPendingLaneLandSuggestedCommand } from "./diagnosis-pending-lane.mjs";
22
+ import { isReviewInfraExitReason } from "./diagnosis-review-infra.mjs";
22
23
 
23
24
  /**
24
25
  * @param {string} diagnosis
@@ -89,6 +90,14 @@ export function buildSuggestedCommand(diagnosis, ctx = {}) {
89
90
  if (ctx.launchFailureKind === "worktree_unhealthy") {
90
91
  return "spine doctor";
91
92
  }
93
+ // SP-821 / #334: review-infrastructure failures must re-run the review —
94
+ // `spine batch retry` resumes at the review (runWorker no-ops on the
95
+ // existing lane .DONE). Never a salvage command for these reasons.
96
+ if (isReviewInfraExitReason(ctx.exitReason)) {
97
+ return ctx.failedTaskId
98
+ ? `spine batch retry ${ctx.failedTaskId}`
99
+ : "spine status --diagnose";
100
+ }
92
101
  if (ctx.salvageRetryCommand) {
93
102
  return sanitizeRetrySuggestedCommand(ctx.salvageRetryCommand, ctx.failedTaskId);
94
103
  }
@@ -67,6 +67,17 @@ export {
67
67
  findPendingLaneLandTasks,
68
68
  shouldDiagnosePendingLaneLand,
69
69
  } from "./diagnosis-pending-lane.mjs";
70
+ import {
71
+ buildReviewInfraHeadline,
72
+ isReviewInfraExitReason,
73
+ } from "./diagnosis-review-infra.mjs";
74
+ export {
75
+ buildReviewInfraHeadline,
76
+ isReviewInfraExitReason,
77
+ isReviewInfraProviderError,
78
+ REVIEW_INFRASTRUCTURE_EXIT_REASONS,
79
+ resolveReviewInfraType,
80
+ } from "./diagnosis-review-infra.mjs";
70
81
  export { buildSuggestedCommand } from "./diagnosis-suggested-command.mjs";
71
82
  import { buildSuggestedCommand } from "./diagnosis-suggested-command.mjs";
72
83
  export { buildBackground, buildAssessmentReason } from "./diagnosis-handoff-packet.mjs";
@@ -102,12 +113,6 @@ const NO_PAUSE_DIAGNOSES = new Set([
102
113
  "integrate_isolated_ok",
103
114
  "engine_still_running",
104
115
  ]);
105
- const REVIEW_SPAWN_FAILURE_EXIT_REASONS = new Set([
106
- "code_review_spawn_failed",
107
- "code_review_timeout",
108
- "final_review_spawn_failed",
109
- "final_review_timeout",
110
- ]);
111
116
 
112
117
  /**
113
118
  * @param {string} diagnosis
@@ -176,20 +181,14 @@ export function buildHeadline(diagnosis, ctx = {}) {
176
181
  if (ctx.launchFailureKind === "worktree_unhealthy") {
177
182
  return `${batchLabel} failed at worker launch — repair lane worktree git, then retry`;
178
183
  }
179
- if (REVIEW_SPAWN_FAILURE_EXIT_REASONS.has(ctx.exitReason ?? "")) {
180
- const isFinal = ctx.exitReason.startsWith("final_review");
181
- const isTimeout = ctx.exitReason.endsWith("_timeout");
182
- const reviewKind = isFinal ? "final review" : "code review";
183
-
184
- if (isTimeout) {
185
- return ctx.failedTaskId
186
- ? `${batchLabel} ${reviewKind} timed out for task ${ctx.failedTaskId} — retry or increase SPINE_REVIEW_TIMEOUT_MS`
187
- : `${batchLabel} reviewer spawn timed out — retry`;
188
- }
189
-
190
- return ctx.failedTaskId
191
- ? `${batchLabel} ${reviewKind} spawn failed for task ${ctx.failedTaskId} — retry`
192
- : `${batchLabel} reviewer spawn failed — retry`;
184
+ if (isReviewInfraExitReason(ctx.exitReason)) {
185
+ // SP-821 / #334: reviewer infrastructure failed (spawn failure /
186
+ // timeout / provider error, plan+code+final) — no verdict was produced,
187
+ // so re-run the review rather than salvage-integrating unreviewed code.
188
+ return (
189
+ buildReviewInfraHeadline(batchLabel, ctx) ??
190
+ `${batchLabel} review produced no verdict — re-run the review`
191
+ );
193
192
  }
194
193
  if (ctx.salvageChangedFileCount > 0 && ctx.failedTaskId) {
195
194
  return `${batchLabel} failed (${ctx.failedTaskId}): ${ctx.salvageChangedFileCount} uncommitted file(s) in scope`;
@@ -490,14 +490,6 @@ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
490
490
  };
491
491
  }
492
492
 
493
- /**
494
- * @deprecated use tryAutoResolveMergeConflicts
495
- * @param {string} projectRoot
496
- */
497
- export function tryAutoResolveRulesManifestMergeConflict(projectRoot) {
498
- return tryAutoResolveMergeConflicts(projectRoot, {});
499
- }
500
-
501
493
  /**
502
494
  * @param {string} projectRoot
503
495
  * @param {string[]} args
@@ -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,
@@ -23,6 +24,7 @@ import {
23
24
  shouldEmitReviewResumed,
24
25
  } from "../review.mjs";
25
26
  import { shouldUseReviewStub } from "./review-stub.mjs";
27
+ import { REVIEW_PROVIDER_ERROR_REASON } from "../reviewer-provider-error.mjs";
26
28
 
27
29
  /**
28
30
  * @param {string} taskFolder
@@ -316,6 +318,7 @@ export async function runReviewPollLoop({
316
318
  extraReviewParams = gate?.extraReviewParams ?? {};
317
319
  }
318
320
 
321
+ const reviewStartedAt = Date.now();
319
322
  const reviewResult = await runEngineReview({
320
323
  taskFolder: taskFolderInWorktree,
321
324
  worktreePath: wt,
@@ -329,7 +332,27 @@ export async function runReviewPollLoop({
329
332
  const spawnExitReason =
330
333
  reviewResult.reason === REVIEW_TIMEOUT_REASON
331
334
  ? `${reviewType}_review_timeout`
332
- : `${reviewType}_review_spawn_failed`;
335
+ : reviewResult.reason === REVIEW_PROVIDER_ERROR_REASON
336
+ ? `${reviewType}_review_provider_error`
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
+ });
333
356
  recordReviewTaskFailure({
334
357
  projectRoot,
335
358
  state,
@@ -365,6 +388,19 @@ export async function runReviewPollLoop({
365
388
  artifactPath: reviewResult.artifactPath,
366
389
  [attemptKey]: reviewAttempt + 1,
367
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
+ });
368
404
 
369
405
  if (reviewResult.verdict === passVerdict) {
370
406
  task[attemptField] = reviewAttempt + 1;