pi-spine 2.26.0 → 2.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-review-step.mjs +8 -1
  3. package/bin/spine-worker-runner.mjs +14 -1
  4. package/package.json +3 -3
  5. package/skills/spine-release-operator/SKILL.md +3 -0
  6. package/src/batch/batch-meta-reconstruct.mjs +3 -0
  7. package/src/batch/contract-exec.mjs +2 -2
  8. package/src/batch/contract-parse.mjs +2 -2
  9. package/src/batch/contract-prelanded.mjs +2 -2
  10. package/src/batch/diagnosis-handoff-packet.mjs +74 -0
  11. package/src/batch/diagnosis-pending-lane.mjs +34 -1
  12. package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
  13. package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
  14. package/src/batch/engine-lanes/review-code.mjs +1 -0
  15. package/src/batch/engine-lanes/review-final.mjs +83 -46
  16. package/src/batch/engine-lanes/review-plan.mjs +22 -2
  17. package/src/batch/engine-lanes/review-poll.mjs +47 -1
  18. package/src/batch/engine-lanes.mjs +6 -7
  19. package/src/batch/journal.mjs +15 -0
  20. package/src/batch/metrics.mjs +13 -1
  21. package/src/batch/provider-quota.mjs +220 -0
  22. package/src/batch/quota-fallback.mjs +319 -0
  23. package/src/batch/reconcile-diagnosis-context.mjs +22 -0
  24. package/src/batch/resume-multi-queue.mjs +25 -10
  25. package/src/batch/review-artifacts.mjs +93 -15
  26. package/src/batch/review-spawn-retry.mjs +106 -0
  27. package/src/batch/review-spawn.mjs +48 -2
  28. package/src/batch/review-step-run.mjs +96 -6
  29. package/src/batch/reviewer-output.mjs +162 -0
  30. package/src/batch/worker-host.mjs +49 -3
  31. package/src/config/cursor-rules/discover.mjs +2 -2
  32. package/src/config/cursor-rules/match-globs.mjs +6 -4
  33. package/src/config/env-overrides.mjs +41 -4
  34. package/src/config/settings-fields.mjs +6 -0
  35. package/src/config/spine-config-schema.mjs +24 -0
  36. package/src/doctor/quota-risk.mjs +45 -0
  37. package/src/planner/file-scope.mjs +6 -6
  38. package/src/tasks/packet/validate-contract.mjs +3 -3
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Persisted quota-fallback state helpers (SP-808, partial #329).
3
+ *
4
+ * SP-807 (`../quota-fallback.mjs`) decides and shapes the single-hop fallback;
5
+ * this module owns the side effects the engine lane paths need (SP-809 wires
6
+ * the calls):
7
+ *
8
+ * - `applyQuotaFallback` persists `state.resilience.quotaFallback` and
9
+ * journals `batch.quota_fallback_applied` exactly once per hop;
10
+ * - `recordQuotaFallbackRetry` appends the retried task and journals
11
+ * `task.quota_fallback_retry`;
12
+ * - `recordQuotaFallbackExhausted` journals `batch.quota_fallback_exhausted`
13
+ * with every exhausted pool and its reset text;
14
+ * - `quotaFallbackWorkerEnv` / `resolveEffectiveWorkerModel` /
15
+ * `loadQuotaFallbackForWorker` let `runWorker` re-apply the persisted hop to
16
+ * every later worker spawn (sticky override) and report the model actually
17
+ * used, all read-only.
18
+ *
19
+ * Persistence uses `saveEngineBatchState` — the same saver the engine lane
20
+ * paths use (`engine-lanes/matrix-run.mjs`) — so an operator pause already on
21
+ * disk or in the journal is never clobbered by the whole-file write.
22
+ */
23
+
24
+ import { appendJournalEvent } from "../journal.mjs";
25
+ import { saveEngineBatchState } from "../pause.mjs";
26
+ import { buildQuotaFallbackState, markQuotaFallbackRetry } from "../quota-fallback.mjs";
27
+ import { loadSpineBatchState } from "../state-io.mjs";
28
+
29
+ /** @typedef {import("../quota-fallback.mjs").QuotaFallbackState} QuotaFallbackState */
30
+ /** @typedef {import("../quota-fallback.mjs").QuotaFallbackApplyResult} QuotaFallbackApplyResult */
31
+ /** @typedef {import("../quota-fallback.mjs").QuotaFallbackStopResult} QuotaFallbackStopResult */
32
+ /** @typedef {import("../provider-quota.mjs").ProviderQuotaError} ProviderQuotaError */
33
+
34
+ /**
35
+ * Applies the single quota-fallback hop: builds the persisted state from the
36
+ * SP-807 `apply` decision, stores it at `state.resilience.quotaFallback`,
37
+ * persists the batch state, and journals `batch.quota_fallback_applied`. The
38
+ * hop is sticky — callers must invoke this at most once per batch (the SP-807
39
+ * decision layer refuses a second hop while a fallback state exists).
40
+ *
41
+ * @param {object} params
42
+ * @param {string} params.projectRoot
43
+ * @param {string} params.batchId
44
+ * @param {Record<string, any>} params.state Live batch state (mutated in place, then persisted).
45
+ * @param {QuotaFallbackApplyResult} params.decision An `apply` result from `decideQuotaFallback`.
46
+ * @param {ProviderQuotaError} params.classification Classification that produced the decision.
47
+ * @param {string} params.taskId Task whose failure triggered the hop.
48
+ * @param {Date|number} params.now Clock injection point.
49
+ * @returns {Promise<QuotaFallbackState>} The persisted fallback state.
50
+ */
51
+ export async function applyQuotaFallback({ projectRoot, batchId, state, decision, classification, taskId, now }) {
52
+ const fallbackState = buildQuotaFallbackState(decision, { classification, taskId, now });
53
+ if (!state.resilience || typeof state.resilience !== "object") {
54
+ state.resilience = {};
55
+ }
56
+ state.resilience.quotaFallback = fallbackState;
57
+ await saveEngineBatchState(projectRoot, state);
58
+ appendJournalEvent(projectRoot, batchId, "batch.quota_fallback_applied", {
59
+ fromProfile: fallbackState.fromProfile,
60
+ toProfile: fallbackState.toProfile,
61
+ fromModel: fallbackState.fromModel,
62
+ toModel: fallbackState.toModel,
63
+ exhaustedPool: fallbackState.exhaustedPool,
64
+ resetAtRaw: fallbackState.resetAtRaw,
65
+ taskIds: [taskId],
66
+ });
67
+ return fallbackState;
68
+ }
69
+
70
+ /**
71
+ * Records that a task consumed its one auto-retry onto the fallback pool:
72
+ * appends the taskId to the persisted state (SP-807 `markQuotaFallbackRetry`,
73
+ * idempotent), persists, and journals `task.quota_fallback_retry` with the
74
+ * fallback destination.
75
+ *
76
+ * @param {object} params
77
+ * @param {string} params.projectRoot
78
+ * @param {string} params.batchId
79
+ * @param {Record<string, any>} params.state Live batch state carrying `resilience.quotaFallback`.
80
+ * @param {string} params.taskId Task that was retried.
81
+ * @returns {Promise<QuotaFallbackState>} The evolved fallback state.
82
+ */
83
+ export async function recordQuotaFallbackRetry({ projectRoot, batchId, state, taskId }) {
84
+ if (!state.resilience || typeof state.resilience !== "object") {
85
+ state.resilience = {};
86
+ }
87
+ const fallbackState = markQuotaFallbackRetry(state.resilience.quotaFallback, taskId);
88
+ state.resilience.quotaFallback = fallbackState;
89
+ await saveEngineBatchState(projectRoot, state);
90
+ appendJournalEvent(projectRoot, batchId, "task.quota_fallback_retry", {
91
+ taskId,
92
+ toProfile: fallbackState.toProfile,
93
+ toModel: fallbackState.toModel,
94
+ });
95
+ return fallbackState;
96
+ }
97
+
98
+ /**
99
+ * Journals `batch.quota_fallback_exhausted` for a SP-807 `stop` decision. The
100
+ * payload carries every exhausted pool and its index-aligned raw reset text
101
+ * (#329: the operator must see both reset windows when the fallback pool dies
102
+ * too). Pure journal side effect — no state mutation.
103
+ *
104
+ * @param {object} params
105
+ * @param {string} params.projectRoot
106
+ * @param {string} params.batchId
107
+ * @param {QuotaFallbackStopResult} params.decision A `stop` result from `decideQuotaFallback`.
108
+ * @param {string} params.taskId Task whose failure produced the stop.
109
+ */
110
+ export function recordQuotaFallbackExhausted({ projectRoot, batchId, decision, taskId }) {
111
+ appendJournalEvent(projectRoot, batchId, "batch.quota_fallback_exhausted", {
112
+ taskId,
113
+ reason: decision.reason,
114
+ exhaustedPools: Array.isArray(decision.exhaustedPools) ? [...decision.exhaustedPools] : [],
115
+ resetAtRaw: Array.isArray(decision.resetAtRaw) ? [...decision.resetAtRaw] : [],
116
+ });
117
+ }
118
+
119
+ /**
120
+ * Maps a persisted fallback state to the child-env override every later worker
121
+ * spawn must receive (SP-805 resolves `SPINE_AGENT_PROFILE_OVERRIDE` at config
122
+ * load). Returns `{}` when no hop is active so callers can merge blindly.
123
+ *
124
+ * @param {QuotaFallbackState|null|undefined} fallbackState
125
+ * @returns {Record<string, string>}
126
+ */
127
+ export function quotaFallbackWorkerEnv(fallbackState) {
128
+ const toProfile = typeof fallbackState?.toProfile === "string" ? fallbackState.toProfile.trim() : "";
129
+ if (!toProfile) return {};
130
+ return { SPINE_AGENT_PROFILE_OVERRIDE: toProfile };
131
+ }
132
+
133
+ /**
134
+ * Resolves the worker model that is actually in effect: when a fallback hop is
135
+ * active, the fallback profile's worker model; otherwise the configured worker
136
+ * model. Used for quota classification and for the journaled `model` field so
137
+ * both tell the truth after a hop. Returns `undefined` when neither source
138
+ * yields a string (matching the pre-SP-808 `typeof === "string"` contract).
139
+ *
140
+ * @param {object|undefined} config Resolved spine config.
141
+ * @param {QuotaFallbackState|null|undefined} fallbackState
142
+ * @returns {string|undefined}
143
+ */
144
+ export function resolveEffectiveWorkerModel(config, fallbackState) {
145
+ // The config arrives untyped; read the narrow slice this helper needs.
146
+ const cfg = /** @type {{ agents?: { profiles?: Record<string, any>, worker?: { model?: unknown } } }} */ (config ?? {});
147
+ const toProfile = typeof fallbackState?.toProfile === "string" ? fallbackState.toProfile.trim() : "";
148
+ if (toProfile) {
149
+ const profileModel = cfg.agents?.profiles?.[toProfile]?.worker?.model;
150
+ if (typeof profileModel === "string" && profileModel !== "") {
151
+ return profileModel;
152
+ }
153
+ }
154
+ const configured = cfg.agents?.worker?.model;
155
+ return typeof configured === "string" ? configured : undefined;
156
+ }
157
+
158
+ /**
159
+ * Read-only load of the persisted quota fallback for a worker spawn
160
+ * (`runWorker` must never write batch state). Returns the fallback state when
161
+ * 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.
164
+ *
165
+ * @param {object} params
166
+ * @param {string} params.projectRoot
167
+ * @param {string} params.batchId
168
+ * @returns {QuotaFallbackState|null}
169
+ */
170
+ export function loadQuotaFallbackForWorker({ projectRoot, batchId }) {
171
+ if (!projectRoot || !batchId) return null;
172
+ const loaded = loadSpineBatchState(projectRoot);
173
+ const state = loaded.raw;
174
+ if (!state || typeof state !== "object") return null;
175
+ if (String(state.batchId ?? "") !== String(batchId)) return null;
176
+ const fallback = state.resilience?.quotaFallback;
177
+ return fallback && typeof fallback === "object" ? fallback : null;
178
+ }
179
+
180
+ /**
181
+ * One-call resolution of everything `runWorker` needs for the sticky
182
+ * override: the persisted fallback (read-only), the effective worker model
183
+ * (fallback profile model when a hop is active, else the configured worker
184
+ * model), and the child env with the profile override merged UNDER the
185
+ * caller's `extraEnv` (caller keys win — e.g. matrix row identity, #229).
186
+ * Kept here so `worker-host.mjs` stays under its 500-LOC module cap.
187
+ *
188
+ * @param {object} params
189
+ * @param {string} [params.projectRoot]
190
+ * @param {string} [params.batchId]
191
+ * @param {object|undefined} params.config Resolved spine config.
192
+ * @param {Record<string, string>} [params.extraEnv] Caller-supplied child env.
193
+ * @returns {{ fallback: QuotaFallbackState|null, workerModel: string|undefined, extraEnv: Record<string, string> }}
194
+ */
195
+ export function resolveWorkerQuotaFallbackContext({ projectRoot, batchId, config, extraEnv }) {
196
+ const fallback = projectRoot && batchId ? loadQuotaFallbackForWorker({ projectRoot, batchId }) : null;
197
+ return {
198
+ fallback,
199
+ workerModel: resolveEffectiveWorkerModel(config, fallback),
200
+ extraEnv: { ...quotaFallbackWorkerEnv(fallback), ...(extraEnv ?? {}) },
201
+ };
202
+ }
@@ -218,6 +218,7 @@ export async function runCodeReviewPhase({
218
218
  laneCorrelationId,
219
219
  taskFolder: taskFolderInWorktree,
220
220
  journalEvents,
221
+ worktreePath: wt,
221
222
  });
222
223
  if (honoredResult) return honoredResult;
223
224
 
@@ -260,6 +260,77 @@ export async function runFinalReviewPhase({
260
260
  const stubVerdicts = shouldUseReviewStub() ? createPhaseStubVerdictQueue("final") : null;
261
261
 
262
262
  const journalEvents = readJournalEvents(projectRoot, batchId);
263
+
264
+ // SP-813 / #328: contract verification must run before the honor fast path
265
+ // so a task can never complete through an honored final-review verdict
266
+ // without `contract.verified` in the journal. The result computed here is
267
+ // consumed by the first poll-loop iteration (contractVerifiedPending) so
268
+ // the contract is verified exactly once per phase entry; rework iterations
269
+ // re-verify as before. Respects shouldRunContractVerifyForWorker, so stub
270
+ // batches (and contracts without verifiable fields) keep skipping.
271
+ let contractVerifyResult =
272
+ /** @type {{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }>, retries?: number } | null} */ (
273
+ null
274
+ );
275
+ let contractVerifiedPending = false;
276
+ const runContractVerifyGate = async () => {
277
+ contractVerifyResult = null;
278
+ contractVerifiedPending = true;
279
+ const promptMarkdown = fs.readFileSync(path.join(taskFolderInWorktree, "PROMPT.md"), "utf-8");
280
+ const parsedContract = parseContract(promptMarkdown);
281
+ if (shouldRunContractVerifyForWorker(promptMarkdown, parsedContract, config)) {
282
+ const events = readJournalEvents(projectRoot, batchId);
283
+ const sinceCommit = resolveTaskStartCommit({
284
+ journal: events,
285
+ taskId,
286
+ laneId: lane.laneId,
287
+ batchId,
288
+ worktreePath: wt,
289
+ });
290
+ const result = await verifyContract(wt, parsedContract, {
291
+ ...config,
292
+ baseBranch,
293
+ sinceCommit: sinceCommit ?? undefined,
294
+ projectRoot,
295
+ batchId,
296
+ taskId,
297
+ taskFolder: taskFolderInWorktree,
298
+ });
299
+ contractVerifyResult = result;
300
+ task.contractOk = result.ok;
301
+ saveSpineBatchState(projectRoot, state);
302
+ appendJournalEvent(projectRoot, batchId, "contract.verified", {
303
+ taskId,
304
+ laneNumber,
305
+ laneId: lane.laneId,
306
+ correlationId: laneCorrelationId,
307
+ ok: result.ok,
308
+ checks: result.checks,
309
+ });
310
+ if (!result.ok) {
311
+ removeDoneFile(taskFolderInWorktree);
312
+ recordContractVerifyTaskFailure({
313
+ projectRoot,
314
+ state,
315
+ batchId,
316
+ task,
317
+ lane,
318
+ laneCorrelationId,
319
+ contractVerifyResult: result,
320
+ config,
321
+ taskFolder: taskFolderInWorktree,
322
+ });
323
+ return { contractFailed: true };
324
+ }
325
+ }
326
+ return { contractFailed: false };
327
+ };
328
+
329
+ const preHonorContractGate = await runContractVerifyGate();
330
+ if (preHonorContractGate.contractFailed) {
331
+ return { ok: false, exitReason: "contract_failed", verdict: "CONTRACT_FAIL" };
332
+ }
333
+
263
334
  const honoredResult = honorCompletedReview({
264
335
  reviewType: "final",
265
336
  passVerdict: "PASS",
@@ -274,6 +345,7 @@ export async function runFinalReviewPhase({
274
345
  laneCorrelationId,
275
346
  taskFolder: taskFolderInWorktree,
276
347
  journalEvents,
348
+ worktreePath: wt,
277
349
  });
278
350
  if (honoredResult) return honoredResult;
279
351
 
@@ -289,52 +361,17 @@ export async function runFinalReviewPhase({
289
361
  invalidVerdictOutput: "final review artifact missing PASS, REVISE, or REPLAN verdict",
290
362
  allowReplan: true,
291
363
  beforeReview: async () => {
292
- let contractVerifyResult = null;
293
- const promptMarkdown = fs.readFileSync(path.join(taskFolderInWorktree, "PROMPT.md"), "utf-8");
294
- const parsedContract = parseContract(promptMarkdown);
295
- if (shouldRunContractVerifyForWorker(promptMarkdown, parsedContract, config)) {
296
- const events = readJournalEvents(projectRoot, batchId);
297
- const sinceCommit = resolveTaskStartCommit({
298
- journal: events,
299
- taskId,
300
- laneId: lane.laneId,
301
- batchId,
302
- worktreePath: wt,
303
- });
304
- contractVerifyResult = await verifyContract(wt, parsedContract, {
305
- ...config,
306
- baseBranch,
307
- sinceCommit: sinceCommit ?? undefined,
308
- projectRoot,
309
- batchId,
310
- taskId,
311
- taskFolder: taskFolderInWorktree,
312
- });
313
- task.contractOk = contractVerifyResult.ok;
314
- saveSpineBatchState(projectRoot, state);
315
- appendJournalEvent(projectRoot, batchId, "contract.verified", {
316
- taskId,
317
- laneNumber,
318
- laneId: lane.laneId,
319
- correlationId: laneCorrelationId,
320
- ok: contractVerifyResult.ok,
321
- checks: contractVerifyResult.checks,
322
- });
323
- if (!contractVerifyResult.ok) {
324
- removeDoneFile(taskFolderInWorktree);
325
- recordContractVerifyTaskFailure({
326
- projectRoot,
327
- state,
328
- batchId,
329
- task,
330
- lane,
331
- laneCorrelationId,
332
- contractVerifyResult,
333
- config,
334
- taskFolder: taskFolderInWorktree,
335
- });
336
- return { abort: { ok: false, exitReason: "contract_failed", verdict: "CONTRACT_FAIL" } };
337
- }
364
+ if (contractVerifiedPending) {
365
+ // Consume the phase-entry verification so the first poll iteration
366
+ // does not double-verify; later rework iterations run the full gate.
367
+ contractVerifiedPending = false;
368
+ return { extraReviewParams: { contractVerifyResult } };
369
+ }
370
+ const gate = await runContractVerifyGate();
371
+ if (gate.contractFailed) {
372
+ return {
373
+ abort: { ok: false, exitReason: "contract_failed", verdict: "CONTRACT_FAIL" },
374
+ };
338
375
  }
339
376
  return { extraReviewParams: { contractVerifyResult } };
340
377
  },
@@ -23,6 +23,7 @@ import {
23
23
  readReviewLevel,
24
24
  runStepReview,
25
25
  } from "../review.mjs";
26
+ import { isHonorableReviewEvent } from "../review-artifacts.mjs";
26
27
  import { honorCompletedReview, runReviewPollLoop } from "./review-poll.mjs";
27
28
  import {
28
29
  createPhaseStubVerdictQueue,
@@ -52,15 +53,26 @@ function findPlanReviewStepNumber(taskFolder) {
52
53
 
53
54
  /**
54
55
  * Resolve an existing worker or lane plan review from journal and/or artifacts.
55
- * Mirrors findCompletedCodeReview with reviewType "plan" (SP-695).
56
+ * Mirrors findCompletedCodeReview with reviewType "plan" (SP-695), including
57
+ * the honor guard for untrusted journal verdicts (SP-813 / #328).
56
58
  *
57
59
  * @param {object} params
58
60
  * @param {string} params.taskFolder
59
61
  * @param {Array<Record<string, any>>} [params.journalEvents]
60
62
  * @param {string} [params.taskId]
63
+ * @param {string} [params.worktreePath] Lane worktree used to resolve relative artifact paths.
64
+ * @param {boolean} [params.stubMode] Whether the batch runs in review-stub mode (see isHonorableReviewEvent).
65
+ * @param {(event: Record<string, any>, reason: string) => void} [params.onReject] Invoked once per journal event refused by the honor guard.
61
66
  * @returns {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
62
67
  */
63
- function findCompletedPlanReview({ taskFolder, journalEvents = [], taskId }) {
68
+ function findCompletedPlanReview({
69
+ taskFolder,
70
+ journalEvents = [],
71
+ taskId,
72
+ worktreePath,
73
+ stubMode,
74
+ onReject,
75
+ }) {
64
76
  /** @type {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
65
77
  let journalMatch = null;
66
78
  for (let index = 0; index < journalEvents.length; index += 1) {
@@ -71,6 +83,13 @@ function findCompletedPlanReview({ taskFolder, journalEvents = [], taskId }) {
71
83
  if (payload.reviewType !== "plan") continue;
72
84
  const verdict = normalizeCodeVerdict(payload.verdict);
73
85
  if (!verdict) continue;
86
+ const honorGuard = isHonorableReviewEvent(event, { taskFolder, worktreePath, stubMode });
87
+ if (!honorGuard.ok) {
88
+ // Untrusted event: skip it exactly as if it were absent so the scan
89
+ // still honors a later trustworthy event or the artifact fallback.
90
+ if (typeof onReject === "function") onReject(event, honorGuard.reason);
91
+ continue;
92
+ }
74
93
  journalMatch = {
75
94
  verdict,
76
95
  feedback: typeof payload.feedback === "string" ? payload.feedback : "",
@@ -313,6 +332,7 @@ export async function runPlanReviewPhase({
313
332
  laneCorrelationId,
314
333
  taskFolder: taskFolderInWorktree,
315
334
  journalEvents,
335
+ worktreePath: wt,
316
336
  });
317
337
  if (honoredResult) return honoredResult;
318
338
 
@@ -22,6 +22,7 @@ import {
22
22
  resolveReviewPassKind,
23
23
  shouldEmitReviewResumed,
24
24
  } from "../review.mjs";
25
+ import { shouldUseReviewStub } from "./review-stub.mjs";
25
26
 
26
27
  /**
27
28
  * @param {string} taskFolder
@@ -112,6 +113,7 @@ export function appendReviewHonorJournalEvents({
112
113
  * @param {string} params.laneCorrelationId
113
114
  * @param {string} params.taskFolder
114
115
  * @param {Array<Record<string, any>>} params.journalEvents
116
+ * @param {string} [params.worktreePath] Lane worktree; resolves relative journal artifact paths for the honor guard.
115
117
  * @returns {{ ok: boolean, [key: string]: any } | null}
116
118
  */
117
119
  export function honorCompletedReview({
@@ -128,11 +130,55 @@ export function honorCompletedReview({
128
130
  laneCorrelationId,
129
131
  taskFolder,
130
132
  journalEvents,
133
+ worktreePath,
131
134
  }) {
132
135
  const taskId = task.taskId;
133
136
  const laneNumber = lane.laneNumber;
134
137
  const reviewAttempt = task[attemptField] ?? 0;
135
- const honored = findCompletedReview({ taskFolder, journalEvents, taskId });
138
+ // #328: only honor verdicts the batch can trust. stubMode is computed once
139
+ // here (the caller of the finders) and passed down, covering both
140
+ // SPINE_WORKER_STUB and SPINE_REVIEW_STUB engine-stub modes.
141
+ const stubMode = shouldUseReviewStub();
142
+ const rejectedSourceIds = new Set(
143
+ journalEvents
144
+ .filter(
145
+ (event) =>
146
+ event.type === "review.honor_rejected" &&
147
+ (event.taskId === undefined || event.taskId === taskId),
148
+ )
149
+ .map((event) => event.payload?.sourceEventId)
150
+ .filter((id) => typeof id === "string" && id),
151
+ );
152
+ const honored = findCompletedReview({
153
+ taskFolder,
154
+ journalEvents,
155
+ taskId,
156
+ worktreePath,
157
+ stubMode,
158
+ onReject: (
159
+ /** @type {Record<string, any>} */ event,
160
+ /** @type {string} */ reason,
161
+ ) => {
162
+ const payload =
163
+ event.payload && typeof event.payload === "object" ? event.payload : {};
164
+ const sourceEventId =
165
+ typeof event.eventId === "string" && event.eventId ? event.eventId : event.timestamp;
166
+ // Dedupe by source event id so a rejected event journals once, not on
167
+ // every phase entry that rescans the journal.
168
+ if (rejectedSourceIds.has(sourceEventId)) return;
169
+ rejectedSourceIds.add(sourceEventId);
170
+ appendJournalEvent(projectRoot, batchId, "review.honor_rejected", {
171
+ taskId,
172
+ laneNumber,
173
+ laneId: lane.laneId,
174
+ correlationId: laneCorrelationId,
175
+ reviewType,
176
+ reason,
177
+ artifactPath: typeof payload.artifactPath === "string" ? payload.artifactPath : "",
178
+ sourceEventId,
179
+ });
180
+ },
181
+ });
136
182
  if (honored?.verdict !== passVerdict) return null;
137
183
 
138
184
  const honorJournalEvent = resolveReviewHonorJournalEvent({
@@ -31,12 +31,10 @@ import { runWorker } from "./worker-host.mjs";
31
31
  import { runCodeReviewPhase, runFinalReviewPhase, runPlanReviewPhase } from "./engine-lanes/review.mjs";
32
32
  import { ensureLaneSyncedForSharedScopeDeps } from "./engine-lanes/orch-sync.mjs";
33
33
  import { resolveWorktreeSetupIgnorePaths } from "../config/spine-config-load.mjs";
34
- import {
35
- acquireLaneSlot,
36
- loadMatrixTaskRows,
37
- releaseLaneSlot,
38
- } from "./engine-lanes/matrix.mjs";
34
+ import { resolveWorkerBackend } from "../config/worker-backend.mjs";
35
+ import { acquireLaneSlot, loadMatrixTaskRows, releaseLaneSlot } from "./engine-lanes/matrix.mjs";
39
36
  import { runMatrixTaskOnLane } from "./engine-lanes/matrix-run.mjs";
37
+ import { runWithQuotaFallback } from "./engine-lanes/quota-fallback-run.mjs";
40
38
 
41
39
  export {
42
40
  buildTasksAndLanesFromPlan,
@@ -160,7 +158,8 @@ export async function runTaskOnLane({
160
158
 
161
159
  const laneSlot = await acquireLaneSlot(state, config?.lanes?.maxParallel ?? 1);
162
160
  try {
163
- return await runNonMatrixTaskOnLane({
161
+ // SP-809 (#329): single-hop quota fallback retry wraps the lane run.
162
+ return await runWithQuotaFallback(() => runNonMatrixTaskOnLane({
164
163
  projectRoot,
165
164
  state,
166
165
  batchId,
@@ -171,7 +170,7 @@ export async function runTaskOnLane({
171
170
  taskFolderRel,
172
171
  laneCorrelationId,
173
172
  fileScopePaths,
174
- });
173
+ }), { projectRoot, batchId, state, taskId: task.taskId, config, workerBackend: resolveWorkerBackend(config) });
175
174
  } finally {
176
175
  releaseLaneSlot(state, laneSlot);
177
176
  }
@@ -348,6 +348,17 @@ export function summarizeJournalEvent(event) {
348
348
  if (payload.reason) parts.push(String(payload.reason));
349
349
  if (payload.error) parts.push(String(payload.error).slice(0, 80));
350
350
  if (payload.classification) parts.push(String(payload.classification));
351
+ // SP-810 (partial #329): quota-fallback fields operators act on.
352
+ if (payload.fromProfile && payload.toProfile) parts.push(`${payload.fromProfile} → ${payload.toProfile}`);
353
+ if (payload.poolId) parts.push(`pool ${payload.poolId}`);
354
+ if (Array.isArray(payload.exhaustedPools) && payload.exhaustedPools.length > 0) parts.push(`exhausted: ${payload.exhaustedPools.join(", ")}`);
355
+ const quotaReset = payload.resetAtRaw;
356
+ if (typeof quotaReset === "string" && quotaReset) {
357
+ parts.push(`resets ${quotaReset}`);
358
+ } else if (Array.isArray(quotaReset) && quotaReset.length > 0) {
359
+ parts.push(`resets ${quotaReset.map((reset) => reset ?? "unknown").join(" / ")}`);
360
+ }
361
+ if (Array.isArray(payload.taskIds) && payload.taskIds.length > 0) parts.push(`task(s): ${payload.taskIds.join(", ")}`);
351
362
  if (payload.workerPhase) parts.push(`phase ${payload.workerPhase}`);
352
363
  if (payload.dirtyPathCount != null && event.type === "lane.progress_snapshot") {
353
364
  parts.push(`${payload.dirtyPathCount} dirty path(s)`);
@@ -428,6 +439,10 @@ export function extractJournalDiagnosisHints(events) {
428
439
  "batch.merge_blocked",
429
440
  "task.failed",
430
441
  "matrix.task_failed",
442
+ // SP-810 (partial #329): quota events decide retry-vs-wait — rank with failures.
443
+ "batch.quota_fallback_applied",
444
+ "batch.quota_fallback_exhausted",
445
+ "worker.quota_exhausted",
431
446
  "review.crash_recovered",
432
447
  "review.skipped_fresh_artifact",
433
448
  "review.resumed",
@@ -133,7 +133,14 @@ export function buildTaskMetricRecord({ batchId, task, config = {}, taskFolder,
133
133
  batchId,
134
134
  taskId: task.taskId,
135
135
  agentRole: "worker",
136
- model: typeof worker.model === "string" ? worker.model : "inherit",
136
+ // SP-808 (#329): SP-809 pins task.workerModel to the model actually used
137
+ // (fallback profile after a hop); prefer it over the batch-start config.
138
+ model:
139
+ typeof task.workerModel === "string" && task.workerModel !== ""
140
+ ? task.workerModel
141
+ : typeof worker.model === "string"
142
+ ? worker.model
143
+ : "inherit",
137
144
  thinking:
138
145
  worker.thinking === "off" ||
139
146
  worker.thinking === "low" ||
@@ -155,6 +162,11 @@ export function buildTaskMetricRecord({ batchId, task, config = {}, taskFolder,
155
162
  if (task.exitReason) record.exitReason = task.exitReason;
156
163
  if (task.exitReason === "contract_failed") record.failureKind = "contract";
157
164
  if (task.exitReason === "review_exhausted") record.failureKind = "reviewer";
165
+ // SP-806 (#329): provider quota/overload exits carry their own failure kind
166
+ // so doctor quota-risk signals can fire on run-metrics without extra config.
167
+ if (task.exitReason === "provider_quota_exhausted" || task.exitReason === "provider_overloaded") {
168
+ record.failureKind = "quota";
169
+ }
158
170
  if (reviewLevel > 0) record.reviewLevel = reviewLevel;
159
171
  if (task.finalVerdict != null) record.finalVerdict = task.finalVerdict;
160
172
  if (task.finalAttempts != null) record.finalAttempts = task.finalAttempts;