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
@@ -0,0 +1,319 @@
1
+ /**
2
+ * Pure decision and state helpers for single-hop provider quota fallback
3
+ * (SP-807, partial #329).
4
+ *
5
+ * `decideQuotaFallback` encodes the #329 fallback rules as a truth table over
6
+ * the resolved config, the batch's `state.resilience.quotaFallback` state, the
7
+ * SP-804 classification, and the worker backend:
8
+ *
9
+ * - at most one hop per batch (sticky once applied — a second exhaustion can
10
+ * only re-route lanes still pinned to the old pool, never pick a new pool);
11
+ * - one auto-retry per task (`retriedTaskIds`), so no task ping-pongs;
12
+ * - transient overload, an unset fallback key, and the in-process
13
+ * `agentSession` backend never fall back;
14
+ * - same-pool and probe-reported-exhausted fallback targets are refused.
15
+ *
16
+ * Everything here is pure: no state reads/writes, no journal, no probes, no
17
+ * clocks (the caller passes `now` in). The engine wiring lands in SP-809.
18
+ * `agents.escalatePolicy` is deliberately not consulted (#329 alternatives:
19
+ * fallback is not escalation) and only a single fallback profile is supported.
20
+ */
21
+ import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
22
+
23
+ /**
24
+ * @typedef {import("./provider-quota.mjs").ProviderQuotaError} ProviderQuotaError
25
+ */
26
+
27
+ /** @typedef {"apply"|"retry"|"stop"|"none"} QuotaFallbackAction */
28
+
29
+ /**
30
+ * Persisted fallback hop for a batch, stored by the engine at
31
+ * `state.resilience.quotaFallback`. Its presence alone means the hop already
32
+ * happened — no second hop is ever decided.
33
+ *
34
+ * @typedef {object} QuotaFallbackState
35
+ * @property {string|null} fromProfile Profile active when the hop was applied.
36
+ * @property {string} toProfile Fallback profile the batch moved to.
37
+ * @property {string|null} fromModel Worker model before the hop.
38
+ * @property {string} toModel Worker model after the hop.
39
+ * @property {string} exhaustedPool Pool whose exhaustion triggered the hop.
40
+ * @property {string|null} resetAtRaw Raw provider reset text for that pool, when it had one.
41
+ * @property {string} triggerTaskId Task whose failure triggered the hop.
42
+ * @property {string} at ISO timestamp of the hop.
43
+ * @property {string[]} retriedTaskIds Tasks already auto-retried onto the fallback pool.
44
+ */
45
+
46
+ /**
47
+ * Early-out result: the batch must keep running as configured.
48
+ *
49
+ * @typedef {object} QuotaFallbackNoneResult
50
+ * @property {"none"} action
51
+ * @property {"disabled"|"not_quota"|"backend_unsupported"} reason
52
+ */
53
+
54
+ /**
55
+ * Terminal result: the fallback chain is exhausted (or misconfigured); no hop
56
+ * and no retry. Carries every pool exhausted so far so the caller can report
57
+ * both reset times (#329 wants the operator to see each window).
58
+ *
59
+ * @typedef {object} QuotaFallbackStopResult
60
+ * @property {"stop"} action
61
+ * @property {"profile_missing"|"task_retry_spent"|"fallback_pool_exhausted"|"fallback_model_unresolved"|"same_pool"|"probe_exhausted"} reason
62
+ * @property {string[]} exhaustedPools Pools exhausted so far — recorded hop pool first (when present), current classification last.
63
+ * @property {(string|null)[]} resetAtRaw Reset text per pool, index-aligned with `exhaustedPools`.
64
+ */
65
+
66
+ /**
67
+ * Re-route result: a lane still pinned to the old pool hit the same
68
+ * exhaustion; retry it onto the already-applied fallback (no new hop).
69
+ *
70
+ * @typedef {object} QuotaFallbackRetryResult
71
+ * @property {"retry"} action
72
+ * @property {string} toProfile
73
+ * @property {string} toModel
74
+ */
75
+
76
+ /**
77
+ * Apply result: move the batch to the fallback profile (the single hop).
78
+ *
79
+ * @typedef {object} QuotaFallbackApplyResult
80
+ * @property {"apply"} action
81
+ * @property {string|null} fromProfile
82
+ * @property {string} toProfile
83
+ * @property {string|null} fromModel
84
+ * @property {string} toModel
85
+ * @property {string} exhaustedPool
86
+ * @property {string} toPool
87
+ */
88
+
89
+ /** @typedef {QuotaFallbackApplyResult|QuotaFallbackRetryResult|QuotaFallbackStopResult|QuotaFallbackNoneResult} QuotaFallbackDecision */
90
+
91
+ /**
92
+ * Structural slice of the resolved spine config this module reads. The config
93
+ * arrives untyped from config loading; this keeps checkJs honest without
94
+ * pulling in the full config schema.
95
+ *
96
+ * @typedef {{ agents?: { activeProfile?: unknown, worker?: { model?: unknown }, profiles?: Record<string, any>, quotaFallbackProfile?: unknown } }} QuotaFallbackConfig
97
+ */
98
+
99
+ /**
100
+ * Reads `agents.quotaFallbackProfile` from a resolved config. An unset,
101
+ * non-string, or blank value disables fallback entirely (SP-805 lets `""`
102
+ * clear the key).
103
+ *
104
+ * @param {QuotaFallbackConfig|undefined} config
105
+ * @returns {string|null} Profile name, or null when fallback is disabled.
106
+ */
107
+ function readFallbackProfileName(config) {
108
+ const raw = config?.agents?.quotaFallbackProfile;
109
+ if (typeof raw !== "string") return null;
110
+ const trimmed = raw.trim();
111
+ return trimmed === "" ? null : trimmed;
112
+ }
113
+
114
+ /**
115
+ * Looks up a profile by name using the same membership rule as the config
116
+ * schema (`Object.prototype.hasOwnProperty` on a plain object), so inherited
117
+ * or malformed entries cannot fabricate a fallback target.
118
+ *
119
+ * @param {QuotaFallbackConfig|undefined} config
120
+ * @param {string} name
121
+ * @returns {{ worker?: { model?: unknown } } | null}
122
+ */
123
+ function lookupProfile(config, name) {
124
+ const profiles = config?.agents?.profiles;
125
+ if (!profiles || typeof profiles !== "object") return null;
126
+ if (!Object.prototype.hasOwnProperty.call(profiles, name)) return null;
127
+ const profile = profiles[name];
128
+ return profile && typeof profile === "object" ? /** @type {{ worker?: { model?: unknown } }} */ (profile) : null;
129
+ }
130
+
131
+ /**
132
+ * Builds the parallel `exhaustedPools`/`resetAtRaw` report carried by every
133
+ * stop result: the pool/reset recorded in the fallback state (when a hop
134
+ * already happened), then the current classification's. Entries are appended
135
+ * verbatim — a same-pool repeat keeps both reset readings, the later one
136
+ * being the newer window — and stay index-aligned.
137
+ *
138
+ * @param {QuotaFallbackState|null} fallbackState
139
+ * @param {ProviderQuotaError} classification
140
+ * @returns {{exhaustedPools: string[], resetAtRaw: (string|null)[]}}
141
+ */
142
+ function buildExhaustedReport(fallbackState, classification) {
143
+ const exhaustedPools = [];
144
+ const resetAtRaw = [];
145
+ if (fallbackState) {
146
+ exhaustedPools.push(fallbackState.exhaustedPool);
147
+ resetAtRaw.push(typeof fallbackState.resetAtRaw === "string" ? fallbackState.resetAtRaw : null);
148
+ }
149
+ exhaustedPools.push(classification.poolId);
150
+ resetAtRaw.push(typeof classification.resetAtRaw === "string" ? classification.resetAtRaw : null);
151
+ return { exhaustedPools, resetAtRaw };
152
+ }
153
+
154
+ /**
155
+ * Decides what the engine should do about a provider quota exhaustion, as a
156
+ * pure function of its arguments. Precedence (first match wins):
157
+ *
158
+ * 1. `none/disabled` — `agents.quotaFallbackProfile` unset or blank.
159
+ * 2. `none/not_quota` — no classification, or not `quota_exhausted`
160
+ * (transient overload never falls back, even mid-fallback).
161
+ * 3. `none/backend_unsupported` — `agentSession` workers run in-process and
162
+ * ignore child env pins, so fallback cannot reach them.
163
+ * 4. `stop/profile_missing` — fallback profile absent from `agents.profiles`
164
+ * (defensive: the schema normally rejects this; fail closed on drift).
165
+ * 5. Fallback already applied (sticky, one hop per batch):
166
+ * `stop/task_retry_spent` when the task already used its auto-retry;
167
+ * `retry` when the classification hits the original pool (a lane still
168
+ * pinned there) — re-route it, no new hop; otherwise
169
+ * `stop/fallback_pool_exhausted` (the fallback pool died too).
170
+ * 6. `stop/fallback_model_unresolved` — fallback profile has no usable
171
+ * worker model (`missing`/`inherit`).
172
+ * 7. `stop/same_pool` — fallback model shares the exhausted pool.
173
+ * 8. `stop/probe_exhausted` — a live probe already reported the fallback
174
+ * pool exhausted.
175
+ * 9. `apply` — perform the single hop.
176
+ *
177
+ * @param {object} [params]
178
+ * @param {QuotaFallbackConfig} [params.config] Resolved spine config.
179
+ * @param {QuotaFallbackState|null} [params.fallbackState] `state.resilience.quotaFallback ?? null`.
180
+ * @param {ProviderQuotaError|null} [params.classification] SP-804 result.
181
+ * @param {string} [params.taskId] Task the classification came from.
182
+ * @param {string} [params.workerBackend] Resolved worker backend.
183
+ * @param {string[]} [params.probeExhaustedPools] Pools a live probe reported exhausted.
184
+ * @returns {QuotaFallbackDecision}
185
+ */
186
+ export function decideQuotaFallback({
187
+ config,
188
+ fallbackState = null,
189
+ classification = null,
190
+ taskId,
191
+ workerBackend,
192
+ probeExhaustedPools,
193
+ } = {}) {
194
+ // Row 1 — no fallback target configured.
195
+ const toProfileName = readFallbackProfileName(config);
196
+ if (toProfileName === null) {
197
+ return { action: "none", reason: "disabled" };
198
+ }
199
+
200
+ // Row 2 — transient overload and everything non-quota stays on the active profile.
201
+ if (!classification || classification.kind !== "quota_exhausted") {
202
+ return { action: "none", reason: "not_quota" };
203
+ }
204
+
205
+ // Row 3 — the in-process backend ignores child env, so a hop could not take effect.
206
+ if (workerBackend === "agentSession") {
207
+ return { action: "none", reason: "backend_unsupported" };
208
+ }
209
+
210
+ /** Stop results report every pool exhausted so far so callers can show both reset times. */
211
+ /**
212
+ * @param {QuotaFallbackStopResult["reason"]} reason
213
+ * @returns {QuotaFallbackStopResult}
214
+ */
215
+ const stop = (reason) => ({
216
+ action: "stop",
217
+ reason,
218
+ ...buildExhaustedReport(fallbackState, classification),
219
+ });
220
+
221
+ // Row 4 — fail closed on config drift instead of guessing a target.
222
+ const targetProfile = lookupProfile(config, toProfileName);
223
+ if (targetProfile === null) {
224
+ return stop("profile_missing");
225
+ }
226
+
227
+ // Row 5 — sticky: once the hop happened, no second hop is ever decided.
228
+ if (fallbackState) {
229
+ const retriedTaskIds = Array.isArray(fallbackState.retriedTaskIds) ? fallbackState.retriedTaskIds : [];
230
+ if (taskId !== undefined && taskId !== null && retriedTaskIds.includes(taskId)) {
231
+ return stop("task_retry_spent");
232
+ }
233
+ if (classification.poolId === fallbackState.exhaustedPool) {
234
+ // A lane pinned to the old pool hit the same exhaustion: re-route it
235
+ // to the fallback that is already applied (recorded in the state, so
236
+ // later config edits cannot change the destination mid-batch).
237
+ return { action: "retry", toProfile: fallbackState.toProfile, toModel: fallbackState.toModel };
238
+ }
239
+ return stop("fallback_pool_exhausted");
240
+ }
241
+
242
+ // Row 6 — `inherit`/missing resolves to the "unknown" pool, which can never
243
+ // be a real destination, so it is refused before any pool comparison.
244
+ const toModel = typeof targetProfile.worker?.model === "string" ? targetProfile.worker.model : null;
245
+ if (toModel === null || toModel === "inherit") {
246
+ return stop("fallback_model_unresolved");
247
+ }
248
+
249
+ // Row 7 — a fallback inside the exhausted pool buys nothing.
250
+ const toPool = resolvePoolId(toModel);
251
+ if (toPool === classification.poolId) {
252
+ return stop("same_pool");
253
+ }
254
+
255
+ // Row 8 — trust the live probe over blind configuration.
256
+ const probes = Array.isArray(probeExhaustedPools) ? probeExhaustedPools : [];
257
+ if (probes.includes(toPool)) {
258
+ return stop("probe_exhausted");
259
+ }
260
+
261
+ // Row 9 — the single hop.
262
+ return {
263
+ action: "apply",
264
+ fromProfile: typeof config?.agents?.activeProfile === "string" ? config.agents.activeProfile : null,
265
+ toProfile: toProfileName,
266
+ fromModel: typeof config?.agents?.worker?.model === "string" ? config.agents.worker.model : null,
267
+ toModel,
268
+ exhaustedPool: classification.poolId,
269
+ toPool,
270
+ };
271
+ }
272
+
273
+ /**
274
+ * Builds the persisted fallback state from an `apply` decision. Pure: the
275
+ * timestamp comes from the injected `now`, and the returned object shares no
276
+ * references with the decision or classification.
277
+ *
278
+ * @param {QuotaFallbackApplyResult} decision An `apply` result from {@link decideQuotaFallback}.
279
+ * @param {object} params
280
+ * @param {ProviderQuotaError} params.classification The classification that produced the decision.
281
+ * @param {string} params.taskId Task whose failure triggered the hop.
282
+ * @param {Date|number} params.now Injection point for the clock.
283
+ * @returns {QuotaFallbackState}
284
+ */
285
+ export function buildQuotaFallbackState(decision, { classification, taskId, now }) {
286
+ return {
287
+ fromProfile: decision.fromProfile,
288
+ toProfile: decision.toProfile,
289
+ fromModel: decision.fromModel,
290
+ toModel: decision.toModel,
291
+ exhaustedPool: decision.exhaustedPool,
292
+ resetAtRaw: typeof classification.resetAtRaw === "string" ? classification.resetAtRaw : null,
293
+ triggerTaskId: taskId,
294
+ at: new Date(now).toISOString(),
295
+ retriedTaskIds: [],
296
+ };
297
+ }
298
+
299
+ /**
300
+ * Records that a task consumed its one auto-retry onto the fallback pool.
301
+ * Pure: returns a new state object and never mutates the input; appending an
302
+ * already-recorded task is a no-op duplicate-wise (idempotent).
303
+ *
304
+ * @param {QuotaFallbackState} fallbackState State to evolve (must be an object).
305
+ * @param {string} taskId Task that was retried.
306
+ * @returns {QuotaFallbackState}
307
+ * @throws {TypeError} When `fallbackState` is not an object, so a missing hop
308
+ * cannot silently produce an empty-looking state.
309
+ */
310
+ export function markQuotaFallbackRetry(fallbackState, taskId) {
311
+ if (!fallbackState || typeof fallbackState !== "object") {
312
+ throw new TypeError("markQuotaFallbackRetry requires a QuotaFallbackState object");
313
+ }
314
+ const retriedTaskIds = Array.isArray(fallbackState.retriedTaskIds) ? fallbackState.retriedTaskIds : [];
315
+ if (retriedTaskIds.includes(taskId)) {
316
+ return { ...fallbackState, retriedTaskIds: [...retriedTaskIds] };
317
+ }
318
+ return { ...fallbackState, retriedTaskIds: [...retriedTaskIds, taskId] };
319
+ }
@@ -42,6 +42,26 @@ export function buildReconcileDiagnosisContext(params) {
42
42
 
43
43
  const pendingLaneLandTasks = findPendingLaneLandTasks(classifiedTasks);
44
44
 
45
+ // SP-810 (partial #329): surface the persisted quota-fallback hop and the
46
+ // latest quota-exhaustion journal payload so SBAR Background/Assessment can
47
+ // tell operators the real quota situation. Journal events are reused from
48
+ // signals.journalEvents (reconcileBatch already read them) — never a second
49
+ // journal read here. Payloads follow the SP-808 shapes: worker.quota_exhausted
50
+ // carries a single poolId/resetAtRaw; batch.quota_fallback_exhausted carries
51
+ // parallel exhaustedPools[]/resetAtRaw[] arrays.
52
+ const quotaFallbackRaw = signals.raw?.resilience?.quotaFallback;
53
+ const quotaFallback = quotaFallbackRaw && typeof quotaFallbackRaw === "object" ? quotaFallbackRaw : null;
54
+ const journalEvents = Array.isArray(signals.journalEvents) ? signals.journalEvents : [];
55
+ let lastQuotaExhausted = null;
56
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
57
+ const event = journalEvents[index];
58
+ if (event?.type !== "worker.quota_exhausted" && event?.type !== "batch.quota_fallback_exhausted") {
59
+ continue;
60
+ }
61
+ lastQuotaExhausted = event.payload && typeof event.payload === "object" ? event.payload : {};
62
+ break;
63
+ }
64
+
45
65
  return {
46
66
  batchId: batch.batchId,
47
67
  baseBranch: batch.baseBranch ?? git.baseBranch ?? "main",
@@ -49,6 +69,8 @@ export function buildReconcileDiagnosisContext(params) {
49
69
  phase: batch.phase,
50
70
  failedTasks: signals.failedTasks,
51
71
  failedTaskId,
72
+ quotaFallback,
73
+ lastQuotaExhausted,
52
74
  driftTaskStatus,
53
75
  exitReason,
54
76
  launchFailureKind: resolvedLaunchFailureKind,
@@ -1,6 +1,11 @@
1
1
  /** Diagnosis derivation (SP-596/SP-606 / #192). */
2
2
 
3
3
  import { inferLaunchFailureKind } from "./diagnosis.mjs";
4
+ import {
5
+ REVIEW_INFRASTRUCTURE_EXIT_REASONS,
6
+ resolvePrimaryFailureExitReason,
7
+ resolveTaskPrimaryFailureExitReason,
8
+ } from "./diagnosis-review-infra.mjs";
4
9
  import {
5
10
  findPendingLaneLandTasks,
6
11
  shouldDiagnosePendingLaneLand,
@@ -21,56 +26,6 @@ export {
21
26
  laneTaskBranchForDiagnosis,
22
27
  } from "./reconcile-diagnosis-enrich.mjs";
23
28
 
24
- /**
25
- * @param {unknown} rawTasks
26
- * @param {string|null} failedTaskId
27
- * @returns {string|null}
28
- */
29
- function resolveFailedExitReason(rawTasks, failedTaskId) {
30
- if (!failedTaskId || !Array.isArray(rawTasks)) return null;
31
- const match = rawTasks.find((/** @type {any} */ entry) => {
32
- if (!entry || typeof entry !== "object") return false;
33
- return String(entry.taskId ?? entry.id ?? "") === failedTaskId;
34
- });
35
- if (!match || typeof match !== "object") return null;
36
- const exitReason = /** @type {{ exitReason?: unknown }} */ (match).exitReason;
37
- return typeof exitReason === "string" && exitReason ? exitReason : null;
38
- }
39
-
40
- /**
41
- * @param {string|null} failedTaskId
42
- * @param {Record<string, any>} signals
43
- * @returns {string|null}
44
- */
45
- function resolvePrimaryFailureExitReason(failedTaskId, signals) {
46
- const fromTask = resolveFailedExitReason(signals.raw?.tasks, failedTaskId);
47
- if (fromTask) return fromTask;
48
- if (!failedTaskId) return null;
49
- if (Array.isArray(signals.segments)) {
50
- const segment = signals.segments.find((/** @type {any} */ entry) => entry?.taskId === failedTaskId);
51
- const classification = segment?.classification;
52
- if (
53
- typeof classification === "string" &&
54
- classification &&
55
- classification !== "terminal-failure"
56
- ) {
57
- return classification;
58
- }
59
- }
60
- if (Array.isArray(signals.journalEvents)) {
61
- for (let index = signals.journalEvents.length - 1; index >= 0; index -= 1) {
62
- const event = signals.journalEvents[index];
63
- if (event.type !== "task.failed") continue;
64
- const eventTaskId = event.taskId ?? event.payload?.taskId;
65
- if (eventTaskId !== failedTaskId) continue;
66
- const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
67
- const reason = payload.exitReason ?? payload.classification;
68
- if (typeof reason === "string" && reason) return reason;
69
- }
70
- }
71
- return null;
72
- }
73
-
74
29
  /**
75
30
  * @param {string|null} failedTaskId
76
31
  * @param {string|null} exitReason
@@ -134,33 +89,24 @@ function hasNeedsReplanBlocker(signals) {
134
89
  return tasks.some((/** @type {any} */ task) => task?.exitReason === "needs_replan");
135
90
  }
136
91
 
137
- /**
138
- * Plan-review exit reasons where reviewer infrastructure failed after the
139
- * worker had already completed its lane work (#291 / SP-762). Mirrors the
140
- * SP-718 final-review distinction: spawn failure / timeout mean no verdict
141
- * was produced — the implementation itself is not the failure.
142
- */
143
- const POST_DONE_PLAN_REVIEW_EXIT_REASONS = new Set([
144
- "plan_review_spawn_failed",
145
- "plan_review_timeout",
146
- ]);
147
-
148
92
  /**
149
93
  * Failed task whose lane work already completed (done evidence / `.DONE` in
150
- * the lane worktree) but whose engine plan review failed to spawn or timed
151
- * out. Such tasks are salvageable land-loop candidates — a full worker retry
152
- * would re-run expensive work that is already on disk (#291 / SP-762).
94
+ * the lane worktree) but whose engine review (plan, code, or final) failed to
95
+ * spawn, timed out, or hit a provider error — no verdict was ever produced
96
+ * (SP-821 / #334). Such tasks get re-review guidance, not salvage: the retry
97
+ * command resumes at the review (`runWorker` no-ops on existing `.DONE`),
98
+ * whereas `salvage --integrate` lands code no reviewer saw. This reverses the
99
+ * SP-762 pending_lane_land mapping for the plan-review case (#291) and
100
+ * extends the shared reason set to code/final and provider errors.
153
101
  *
154
102
  * Parsed batch-state tasks drop `exitReason` (normalizeTasks), so the exit
155
103
  * reason is resolved the same way deriveFailureContext resolves it: from the
156
104
  * task entry when present, else raw state / journal `task.failed` events.
157
- * The salvage command itself hard-gates on commits-ahead, so pointing at it
158
- * without lane commits is safe (dry-run reports none salvageable).
159
105
  *
160
106
  * @param {Record<string, any>} signals
161
107
  * @returns {Record<string, any>|null}
162
108
  */
163
- function findPostDonePlanReviewSpawnFailedTask(signals) {
109
+ function findPostDoneReviewInfraFailedTask(signals) {
164
110
  const tasks = Array.isArray(signals.tasks) ? signals.tasks : [];
165
111
  for (const task of tasks) {
166
112
  if (String(task?.status ?? "").toLowerCase() !== "failed") continue;
@@ -170,9 +116,8 @@ function findPostDonePlanReviewSpawnFailedTask(signals) {
170
116
  task?.doneFileFound === true ||
171
117
  String(task?.classification ?? "").toLowerCase() === "terminal-success";
172
118
  if (!hasDoneEvidence) continue;
173
- const taskId = String(task?.taskId ?? "");
174
- const exitReason = task?.exitReason ?? resolvePrimaryFailureExitReason(taskId, signals);
175
- if (!POST_DONE_PLAN_REVIEW_EXIT_REASONS.has(String(exitReason ?? ""))) continue;
119
+ const exitReason = resolveTaskPrimaryFailureExitReason(task, signals);
120
+ if (!REVIEW_INFRASTRUCTURE_EXIT_REASONS.has(String(exitReason ?? ""))) continue;
176
121
  return task;
177
122
  }
178
123
  return null;
@@ -278,14 +223,16 @@ export function deriveDiagnosis(signals) {
278
223
  if (doneMissing) {
279
224
  return withFailureContext("worker_done_missing", failedTaskId, signals);
280
225
  }
281
- // Post-DONE plan-review spawn failure: lane work is complete, so map to
282
- // pending_lane_land (salvage / land-loop guidance) instead of needs_retry,
283
- // whose retry language would force an expensive worker re-run (#291 / SP-762).
284
- const postDonePlanReviewTask = findPostDonePlanReviewSpawnFailedTask(signals);
285
- if (postDonePlanReviewTask) {
226
+ // Post-DONE review-infrastructure failure (plan/code/final spawn failure,
227
+ // timeout, or provider error): lane work is complete but no verdict was
228
+ // produced. Map to needs_retry — `spine batch retry` resumes at the review
229
+ // because runWorker no-ops on the existing lane .DONE. Salvage --integrate
230
+ // would land code no reviewer saw (SP-821 / #334, reversing SP-762).
231
+ const postDoneReviewInfraTask = findPostDoneReviewInfraFailedTask(signals);
232
+ if (postDoneReviewInfraTask) {
286
233
  return withFailureContext(
287
- "pending_lane_land",
288
- postDonePlanReviewTask.taskId ?? failedTaskId,
234
+ "needs_retry",
235
+ postDoneReviewInfraTask.taskId ?? failedTaskId,
289
236
  signals,
290
237
  );
291
238
  }
@@ -17,6 +17,8 @@ import {
17
17
  markTaskCompleteFromDisk,
18
18
  runResumedTaskOnLane,
19
19
  } from "./resume-multi-lanes.mjs";
20
+ import { runWithQuotaFallback } from "./engine-lanes/quota-fallback-run.mjs";
21
+ import { resolveWorkerBackend } from "../config/worker-backend.mjs";
20
22
 
21
23
  /**
22
24
  * Build lane queues and run all tasks in a resume wave.
@@ -113,17 +115,30 @@ export async function executeResumeWave({
113
115
 
114
116
  laneQueue.runs.push({
115
117
  taskId,
118
+ // SP-809 (#329): the resumed path gets the same single-hop quota
119
+ // fallback retry as the normal lane path.
116
120
  run: () =>
117
- runResumedTaskOnLane({
118
- projectRoot,
119
- state,
120
- batchId,
121
- config,
122
- task,
123
- lane,
124
- taskFolderRel,
125
- laneCorrelationId,
126
- }).then((result) => {
121
+ runWithQuotaFallback(
122
+ () =>
123
+ runResumedTaskOnLane({
124
+ projectRoot,
125
+ state,
126
+ batchId,
127
+ config,
128
+ task,
129
+ lane,
130
+ taskFolderRel,
131
+ laneCorrelationId,
132
+ }),
133
+ {
134
+ projectRoot,
135
+ batchId,
136
+ state,
137
+ taskId,
138
+ config,
139
+ workerBackend: resolveWorkerBackend(config),
140
+ },
141
+ ).then((result) => {
127
142
  if (result.aborted) batchAborted = true;
128
143
  return result;
129
144
  }),