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
package/README.md CHANGED
@@ -49,7 +49,7 @@ Primary monitor surfaces: **`spine status --diagnose`**, **`spine dashboard`** /
49
49
  | [pi](https://pi.dev) coding agent | ≥ 0.80.0 (`pi.minPiVersion`) | Yes |
50
50
  | Git (worktree support) | — | Yes |
51
51
 
52
- These are the Wave A floors ([#285](https://github.com/beettlle/pi-spine/issues/285)). `spine doctor` **warns** when the installed pi is below `pi.minPiVersion` ("pi version supported"). The optional peer `@earendil-works/pi-coding-agent` is developed and tested against `^0.87.1` (pinned in `devDependencies`; the `peerDependencies` range stays `*`).
52
+ These are the Wave A floors ([#285](https://github.com/beettlle/pi-spine/issues/285)). `spine doctor` **warns** when the installed pi is below `pi.minPiVersion` ("pi version supported"). The optional peer `@earendil-works/pi-coding-agent` is developed and tested against `^1.0.1` (pinned in `devDependencies`; the `peerDependencies` range stays `*`).
53
53
 
54
54
  ## Install
55
55
 
@@ -61,7 +61,14 @@ export async function runSpineReviewStep(options) {
61
61
  if (loaded.config) config = loaded.config;
62
62
  }
63
63
 
64
- const journal = options.journal ?? resolveBatchJournalContext();
64
+ // Only plan/code reviews may inherit the env-derived journal: those are the
65
+ // only types the worker tool requests (extensions/spine/worker-tools.ts), so
66
+ // the legit worker journal path is preserved. Final reviews are engine-owned
67
+ // and always run in-process with an explicit journal, so a CLI `--type final`
68
+ // that inherited worker env (e.g. a test run inside a worker) must not write
69
+ // to the live journal (#328).
70
+ const envJournal = reviewType === "final" ? undefined : resolveBatchJournalContext();
71
+ const journal = options.journal ?? envJournal;
65
72
 
66
73
  const result = await runStepReview({
67
74
  taskFolder,
@@ -317,13 +317,26 @@ async function runWorkerRunner() {
317
317
  const failTasks = String(process.env.SPINE_WORKER_STUB_FAIL_TASKS ?? "")
318
318
  .split(/[,\s]+/)
319
319
  .filter(Boolean);
320
- if (failTasks.includes(parsedTaskId)) {
320
+ // SP-809 (#329): after a quota fallback hop the worker host pins
321
+ // SPINE_AGENT_PROFILE_OVERRIDE to the fallback profile; when the test
322
+ // marks that profile as passing, the retry takes the normal stub path.
323
+ const passProfile = process.env.SPINE_WORKER_STUB_PASS_PROFILE;
324
+ const passOnFallback =
325
+ typeof passProfile === "string" &&
326
+ passProfile !== "" &&
327
+ passProfile === process.env.SPINE_AGENT_PROFILE_OVERRIDE;
328
+ if (failTasks.includes(parsedTaskId) && !passOnFallback) {
321
329
  const dirtyRel = process.env.SPINE_WORKER_STUB_DIRTY_FILE;
322
330
  if (dirtyRel && worktreePath) {
323
331
  const dirtyPath = path.join(worktreePath, dirtyRel);
324
332
  fs.mkdirSync(path.dirname(dirtyPath), { recursive: true });
325
333
  fs.writeFileSync(dirtyPath, `stub dirty ${new Date().toISOString()}\n`, "utf-8");
326
334
  }
335
+ // SP-806 (#329): optional provider payload forwarded on stderr so stub
336
+ // runs can drive quota classification in the worker host. Printed before
337
+ // the forced-failure line so the payload stays the terminal status-JSON.
338
+ const failOutput = process.env.SPINE_WORKER_STUB_FAIL_OUTPUT;
339
+ if (failOutput) console.error(failOutput);
327
340
  console.error(`stub worker forced failure for ${parsedTaskId}`);
328
341
  process.exit(1);
329
342
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.26.0",
3
+ "version": "2.27.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -72,7 +72,7 @@
72
72
  }
73
73
  },
74
74
  "devDependencies": {
75
- "@earendil-works/pi-coding-agent": "^0.87.1",
75
+ "@earendil-works/pi-coding-agent": "^1.0.1",
76
76
  "@types/node": "^22.20.4",
77
77
  "eslint": "^10.11.0",
78
78
  "globals": "^17.12.0",
@@ -81,6 +81,6 @@
81
81
  },
82
82
  "license": "MIT",
83
83
  "dependencies": {
84
- "micromatch": "^4.0.8"
84
+ "picomatch": "^4.0.7"
85
85
  }
86
86
  }
@@ -61,6 +61,7 @@ Invoke explicitly: `/skill:spine-release-operator` or "run a spine release cycle
61
61
  - **Do not** execute tasks outside the approved manifest scope
62
62
  - **Never** start Phase 4 (execute) without **recorded scope approval** — the release manifest must show `Operator approved scope: yes` from the Phase 2 gate. Refuse the first wave when approval is missing or `no` (F1, [#249](https://github.com/beettlle/pi-spine/issues/249))
63
63
  - **Never** mid-release-edit `.spine/spine-config.json` agent pins (`agents.worker.model` / `agents.reviewer.model`) while a batch is running or integrated work is still unpublished. Pin **one worker** per release; escalate models **only** on content/contract failure — never on quota/403 or launch storms, which make releases worse (F7, [#248](https://github.com/beettlle/pi-spine/issues/248)). To override mid-release, first record the reason and date in the release manifest
64
+ - **Distinguish quota fallback from escalation** ([#329](https://github.com/beettlle/pi-spine/issues/329), v2.27.0): `agents.quotaFallbackProfile` is **provider failover, not escalation** — it switches the batch to a fallback profile on a **different provider pool**, not to a stronger model. It is single-hop per batch, sticky once applied, journaled (`batch.quota_fallback_applied`), and never edits `.spine/spine-config.json`. Because it changes pool, not model strength, it is **allowed mid-release** and does not violate the #248 rule above — that rule still bans escalating models on quota/403 or launch storms. After a fallback fires, paste the `Agent pin override: yes (<date>, auto quota fallback <pool> -> <profile>, batch <id>)` line shown by `spine status --diagnose` into the release manifest (the override record the #248 rule requires)
64
65
  - **Heed** the doctor/preflight **quota-risk advisory** ([#251](https://github.com/beettlle/pi-spine/issues/251)): `spine doctor` surfaces `ok: true, warning: true` when escalate/hard worker pins target quota-constrained pools without headroom evidence, or recent run-metrics show launch-storm / quota-abort patterns. It is advisory only — never fails preflight — and does not change the mid-release pin-thrash ban above
65
66
  - **Always** push/sync `main` to `origin` after each land loop once the post-integrate regression gate is green — do not let `main` drift far ahead of `origin` during a release (F8, [#249](https://github.com/beettlle/pi-spine/issues/249))
66
67
  - **Always** close GitHub issues linked as `Closes #NNN` / `Closes: #NNN` **as soon as that task's work is on `main`** (after integrate + post-integrate `release:check` green) — do **not** defer closing until Phase 6 publish. Leave `Partial #NNN` / `Partial: #NNN` open. Phase 6 is only a final sweep for any still-open `Closes` links (v2.15.0 left #257–#261, #263 open after ship — avoid that)
@@ -275,6 +276,8 @@ Before the first wave, confirm the release manifest records **`Operator approved
275
276
 
276
277
  **Model pin:** one worker pin for the release — do not mid-release-edit `.spine/spine-config.json` agent pins. Escalate models only on content/contract failure, never quota/403 or launch storms (F7, [#248](https://github.com/beettlle/pi-spine/issues/248)). A doctor/preflight quota-risk escalate signal is intentionally **out of scope** for this release — deferred to a later release ([#248](https://github.com/beettlle/pi-spine/issues/248) optional AC).
277
278
 
279
+ **Quota fallback is provider failover, not escalation** ([#329](https://github.com/beettlle/pi-spine/issues/329), v2.27.0): when `agents.quotaFallbackProfile` names a profile on a different provider pool, the engine moves the batch to that pool automatically — once per batch, sticky, journaled, without editing `.spine/spine-config.json` — and retries each quota-exhausted task once in its lane worktree. This is the sanctioned mid-release response to quota exhaustion; it does not count as a pin override under the rule above. When it fires, record it in the release manifest by pasting the `Agent pin override: yes (<date>, auto quota fallback <pool> -> <profile>, batch <id>)` line from `spine status --diagnose`.
280
+
278
281
  **Detached-first:** See [agent-shell-batch-policy.md](../spine-autonomous-operator/references/agent-shell-batch-policy.md). Omit `--attached` for release waves unless the operator shell is a persistent interactive terminal that blocks until batch completion.
279
282
 
280
283
  **Scope:** manifest tasks only — build a comma-separated release scope ID list.
@@ -321,6 +321,9 @@ export function reconstructBatchStateFromRuntime(projectRoot, options = {}) {
321
321
  ...(priorResilience.forceMergedWaves
322
322
  ? { forceMergedWaves: priorResilience.forceMergedWaves }
323
323
  : {}),
324
+ // SP-808 (#329): the sticky quota-fallback hop must survive force-resume
325
+ // reconstruct so every later worker spawn keeps the override.
326
+ ...(priorResilience.quotaFallback ? { quotaFallback: priorResilience.quotaFallback } : {}),
324
327
  };
325
328
  rebuilt.currentWaveIndex = findResumableWave(rebuilt, computePendingTasks(rebuilt));
326
329
  rebuilt.updatedAt = Date.now();
@@ -5,7 +5,7 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { setTimeout as sleep } from "node:timers/promises";
8
- import micromatch from "micromatch";
8
+ import picomatch from "picomatch";
9
9
  import { parseAggregateLineCoverage } from "../../scripts/coverage-parse.mjs";
10
10
  import {
11
11
  isBaseFileScopeSatisfied,
@@ -264,7 +264,7 @@ function findArtifactMatch(worktreePath, artifactPattern) {
264
264
  stack.push({ abs: entryAbs, rel: entryRel });
265
265
  continue;
266
266
  }
267
- if (micromatch.isMatch(entryRel, normalized)) {
267
+ if (picomatch(normalized, { dot: true })(entryRel)) {
268
268
  return { ok: true, matchedPath: entryRel };
269
269
  }
270
270
  }
@@ -5,7 +5,7 @@
5
5
 
6
6
  import fs from "node:fs";
7
7
  import { execFileSync } from "node:child_process";
8
- import micromatch from "micromatch";
8
+ import picomatch from "picomatch";
9
9
  import { resolveContractMode } from "../tasks/packet/validate-contract.mjs";
10
10
  import {
11
11
  isBaseScopeSatisfied,
@@ -199,7 +199,7 @@ export function listChangedFiles(worktreePath, baseBranch = "main", sinceCommit
199
199
  * @param {string} pattern
200
200
  */
201
201
  export function matchesContractPattern(file, pattern) {
202
- return micromatch.isMatch(file, pattern, { dot: true });
202
+ return picomatch(pattern, { dot: true })(file);
203
203
  }
204
204
 
205
205
  /**
@@ -5,7 +5,7 @@
5
5
 
6
6
  import path from "node:path";
7
7
  import { execFileSync } from "node:child_process";
8
- import micromatch from "micromatch";
8
+ import picomatch from "picomatch";
9
9
  import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
10
10
 
11
11
  /**
@@ -13,7 +13,7 @@ import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
13
13
  * @param {string} pattern
14
14
  */
15
15
  function matchesPattern(file, pattern) {
16
- return micromatch.isMatch(file, pattern, { dot: true });
16
+ return picomatch(pattern, { dot: true })(file);
17
17
  }
18
18
 
19
19
  /**
@@ -4,6 +4,41 @@
4
4
  * Kept out of diagnosis.mjs so the parent stays under the phase23 LOC cap.
5
5
  */
6
6
 
7
+ /**
8
+ * True when the latest quota-exhaustion journal payload came from
9
+ * `batch.quota_fallback_exhausted` — the parallel arrays are unique to that
10
+ * event (SP-808), so a fallback hop that died too is distinguishable from a
11
+ * plain worker exhaustion without carrying the event type through the ctx.
12
+ *
13
+ * @param {object|null} lastQuotaExhausted
14
+ * @returns {boolean}
15
+ */
16
+ function isFallbackChainExhausted(lastQuotaExhausted) {
17
+ return Array.isArray(lastQuotaExhausted?.exhaustedPools);
18
+ }
19
+
20
+ /**
21
+ * Human-readable reset windows for the exhausted pool(s): a single
22
+ * "resets <raw>" for a worker exhaustion, or one per pool when the fallback
23
+ * chain died too (#329 wants the operator to see every window). Falls back to
24
+ * "reset time unknown" — the raw provider text carries no timezone, so it is
25
+ * shown verbatim rather than parsed into a wrong clock time.
26
+ *
27
+ * @param {object|null} lastQuotaExhausted
28
+ * @returns {string}
29
+ */
30
+ function quotaResetSummary(lastQuotaExhausted) {
31
+ if (isFallbackChainExhausted(lastQuotaExhausted)) {
32
+ const pools = /** @type {string[]} */ (lastQuotaExhausted.exhaustedPools);
33
+ const resets = Array.isArray(lastQuotaExhausted.resetAtRaw) ? lastQuotaExhausted.resetAtRaw : [];
34
+ return pools
35
+ .map((pool, index) => `${pool} resets ${resets[index] ?? "unknown"}`)
36
+ .join(", ");
37
+ }
38
+ const reset = lastQuotaExhausted?.resetAtRaw;
39
+ return typeof reset === "string" && reset ? `resets ${reset}` : "reset time unknown";
40
+ }
41
+
7
42
  /**
8
43
  * SBAR Background — short decision-relevant facts that explain the state the
9
44
  * assessment was derived from. Facts are additive; consumers that ignore
@@ -32,6 +67,27 @@ export function buildBackground(diagnosis, ctx = {}) {
32
67
  `Failed task: ${ctx.failedTaskId}${ctx.exitReason ? ` (exit: ${ctx.exitReason})` : ""}`,
33
68
  );
34
69
  }
70
+ // SP-810 (partial #329): when a fallback hop is active, operators must see
71
+ // which pool died, when it resets, and where the batch landed — plus the
72
+ // paste-ready manifest line the #248 pin policy requires them to record.
73
+ if (ctx.quotaFallback && typeof ctx.quotaFallback === "object" && ctx.quotaFallback.toProfile) {
74
+ const fallback = ctx.quotaFallback;
75
+ facts.push(
76
+ `Quota fallback active: ${fallback.exhaustedPool ?? "?"} exhausted (resets ${
77
+ fallback.resetAtRaw ?? "unknown"
78
+ }, provider local time) → ${fallback.toProfile} (${fallback.toModel ?? "?"}) since ${
79
+ fallback.at ?? "?"
80
+ }, triggered by ${fallback.triggerTaskId ?? "?"}`,
81
+ );
82
+ // Manifest text stays ASCII (`->`) exactly as operators paste it into the
83
+ // release manifest; the date is the YYYY-MM-DD slice of the hop timestamp.
84
+ const overrideDate = typeof fallback.at === "string" ? fallback.at.slice(0, 10) : "?";
85
+ facts.push(
86
+ `Agent pin override: yes (${overrideDate}, auto quota fallback ${
87
+ fallback.exhaustedPool ?? "?"
88
+ } -> ${fallback.toProfile}, batch ${ctx.batchId ?? "?"})`,
89
+ );
90
+ }
35
91
  if (ctx.launchFailureKind) {
36
92
  facts.push(`Launch failure kind: ${ctx.launchFailureKind}`);
37
93
  }
@@ -87,6 +143,24 @@ export function buildAssessmentReason(diagnosis, ctx = {}) {
87
143
  case "completed_manual":
88
144
  return "Work is already on the base branch while the batch record is still active — operator completed it manually";
89
145
  case "needs_retry":
146
+ // SP-810 (partial #329): a quota exhaustion with no fallback that can
147
+ // take over must not imply an immediate retry will work — show the
148
+ // reset window instead. Fallback is hopeless when no hop is persisted
149
+ // (unset/refused) or the fallback chain itself exhausted (stop event).
150
+ if (
151
+ ctx.failedTaskId &&
152
+ ctx.exitReason === "provider_quota_exhausted" &&
153
+ (ctx.quotaFallback == null || isFallbackChainExhausted(ctx.lastQuotaExhausted))
154
+ ) {
155
+ return `Task ${ctx.failedTaskId} exited "provider_quota_exhausted": provider quota is exhausted (${quotaResetSummary(
156
+ ctx.lastQuotaExhausted,
157
+ )}, provider local time) and no quota fallback can take over — an immediate retry hits the same quota limit`;
158
+ }
159
+ // Transient overload never falls back (#329) and clears on its own, so
160
+ // here a plain retry genuinely is the right move.
161
+ if (ctx.failedTaskId && ctx.exitReason === "provider_overloaded") {
162
+ return `Task ${ctx.failedTaskId} exited "provider_overloaded": transient provider overload — retry is reasonable`;
163
+ }
90
164
  if (ctx.failedTaskId && ctx.exitReason) {
91
165
  return `Task ${ctx.failedTaskId} exited "${ctx.exitReason}" without completing its contract, so the batch cannot proceed until it is retried`;
92
166
  }
@@ -3,6 +3,9 @@
3
3
  * Pending lane land diagnosis — lane `.DONE` without main land (#201 / SP-645).
4
4
  */
5
5
 
6
+ import { isEngineProcessAlive } from "../process/liveness.mjs";
7
+ import { readBatchEnginePid, readBatchEngineStartedAt } from "./state-guards.mjs";
8
+
6
9
  /**
7
10
  * Tasks with lane `.DONE` but not on main — lane commits never landed (#201 / SP-645).
8
11
  *
@@ -14,11 +17,41 @@ export function findPendingLaneLandTasks(tasks) {
14
17
  return tasks.filter((task) => task?.doneInLane === true && task?.doneOnMain !== true);
15
18
  }
16
19
 
20
+ /**
21
+ * Guard for #330 / SP-815: the batch engine is alive AND the raw batch state
22
+ * still shows live activity (phase "running" or a running task). Reconciled
23
+ * signals can already look terminal-success mid-wave because a lane `.DONE`
24
+ * is reconciled (`done_in_lane_terminal`) before the engine finishes code and
25
+ * final review — so salvage guidance must be suppressed until the engine
26
+ * exits or the state goes terminal. Both conditions must hold: a crashed
27
+ * engine with a stale running phase still deserves salvage guidance.
28
+ *
29
+ * @param {object|null|undefined} raw raw batch state (`signals.raw`)
30
+ * @param {object} [deps]
31
+ * @param {(raw: object) => boolean} [deps.isEngineAlive] injectable engine liveness probe
32
+ * @returns {boolean}
33
+ */
34
+ export function isLiveEngineMidTask(raw, deps = {}) {
35
+ if (!raw || typeof raw !== "object") return false;
36
+ const isEngineAlive =
37
+ deps.isEngineAlive ??
38
+ ((state) => isEngineProcessAlive(readBatchEnginePid(state), readBatchEngineStartedAt(state)));
39
+ if (!isEngineAlive(raw)) return false;
40
+ if (raw.phase === "running") return true;
41
+ const tasks = Array.isArray(raw.tasks) ? raw.tasks : [];
42
+ return tasks.some((task) => task?.status === "running");
43
+ }
44
+
17
45
  /**
18
46
  * @param {object} signals
47
+ * @param {object} [deps]
48
+ * @param {(raw: object) => boolean} [deps.isEngineAlive] injectable engine liveness probe
19
49
  * @returns {boolean}
20
50
  */
21
- export function shouldDiagnosePendingLaneLand(signals) {
51
+ export function shouldDiagnosePendingLaneLand(signals, deps = {}) {
52
+ // Live engine mid-task: the lane may be about to land under the engine
53
+ // itself — never suggest salvage while it is still running (#330 / SP-815).
54
+ if (isLiveEngineMidTask(signals?.raw, deps)) return false;
22
55
  const pending = findPendingLaneLandTasks(signals.tasks);
23
56
  if (pending.length === 0) return false;
24
57
  // Only when orch already appears merged — otherwise healthy pre-integrate
@@ -0,0 +1,153 @@
1
+ /**
2
+ * In-lane automatic single-hop quota fallback retry (SP-809, partial #329).
3
+ *
4
+ * Wraps one lane task run (`runOnce`) so a `provider_quota_exhausted` failure
5
+ * re-routes the batch onto the fallback profile exactly once and retries the
6
+ * task once in the same lane worktree, without an operator `spine batch retry`:
7
+ *
8
+ * - SP-807 (`../quota-fallback.mjs`) decides the action; SP-808
9
+ * (`./quota-fallback-state.mjs`) owns the persisted hop at
10
+ * `state.resilience.quotaFallback`, the journal events, and the sticky
11
+ * `SPINE_AGENT_PROFILE_OVERRIDE` the worker host re-applies to every later
12
+ * spawn;
13
+ * - the decide → apply section stays synchronous (no `await` between reading
14
+ * `state.resilience.quotaFallback` in `decideQuotaFallback` and the write at
15
+ * the top of `applyQuotaFallback`), so parallel lanes sharing the in-memory
16
+ * `state` in one engine process produce exactly one
17
+ * `batch.quota_fallback_applied` — the second lane sees the sticky hop and
18
+ * gets `retry` instead;
19
+ * - `stop` journals `batch.quota_fallback_exhausted` and returns the original
20
+ * failure; `none` returns it untouched (journal unchanged, pre-fallback
21
+ * behaviour); every non-quota classification and every `ok` result passes
22
+ * straight through;
23
+ * - the retry reuses the lane worktree (partial work kept) and runs `runOnce`
24
+ * exactly once more; a second quota failure is only journaled, never retried
25
+ * again (the SP-807 decision returns `stop/task_retry_spent` for a task
26
+ * already in `retriedTaskIds`).
27
+ *
28
+ * Matrix tasks, reviewer, and supervisor runs are out of scope by design.
29
+ */
30
+
31
+ import {
32
+ applyQuotaFallback,
33
+ recordQuotaFallbackExhausted,
34
+ recordQuotaFallbackRetry,
35
+ resolveEffectiveWorkerModel,
36
+ } from "./quota-fallback-state.mjs";
37
+ import { decideQuotaFallback } from "../quota-fallback.mjs";
38
+ import { resetTaskForRetry } from "../state.mjs";
39
+ import { saveEngineBatchState } from "../pause.mjs";
40
+
41
+ /**
42
+ * @typedef {import("../provider-quota.mjs").ProviderQuotaError} ProviderQuotaError
43
+ */
44
+
45
+ /**
46
+ * Pins `task.workerModel` to the model the next `runOnce()` will actually use,
47
+ * so run-metrics report the configured model before a hop and the fallback
48
+ * profile's model after it (SP-808 `buildTaskMetricRecord` prefers the field).
49
+ *
50
+ * @param {Record<string, any>} state
51
+ * @param {Record<string, any>|undefined} config
52
+ * @param {string} taskId
53
+ * @returns {void}
54
+ */
55
+ function pinTaskWorkerModel(state, config, taskId) {
56
+ const task = (state.tasks ?? []).find((/** @type {any} */ entry) => entry?.taskId === taskId);
57
+ if (task && typeof task === "object") {
58
+ task.workerModel = resolveEffectiveWorkerModel(config, state.resilience?.quotaFallback);
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Runs `runOnce` with automatic single-hop quota fallback (#329): decide
64
+ * synchronously on a `provider_quota_exhausted` failure, apply the persisted
65
+ * hop at most once per batch, reset the task, and retry once in the same lane
66
+ * worktree. Any second quota failure is only journaled (`stop`), never retried.
67
+ *
68
+ * @param {() => Promise<{ ok: boolean, [key: string]: any }>} runOnce One lane
69
+ * task run (the `runNonMatrixTaskOnLane` / `runResumedTaskOnLane` call).
70
+ * @param {object} params
71
+ * @param {string} params.projectRoot
72
+ * @param {string} params.batchId
73
+ * @param {Record<string, any>} params.state Live in-memory batch state (mutated in place).
74
+ * @param {string} params.taskId
75
+ * @param {Record<string, any>|undefined} params.config Resolved spine config.
76
+ * @param {string} params.workerBackend Resolved worker backend (SP-807 refuses `agentSession`).
77
+ * @param {Date|number} [params.now] Clock injection point (default `Date.now()`).
78
+ * @returns {Promise<{ ok: boolean, [key: string]: any }>} The retry result when
79
+ * a retry ran, otherwise the original `runOnce` result unchanged.
80
+ */
81
+ export async function runWithQuotaFallback(
82
+ runOnce,
83
+ { projectRoot, batchId, state, taskId, config, workerBackend, now = Date.now() },
84
+ ) {
85
+ pinTaskWorkerModel(state, config, taskId);
86
+ const result = await runOnce();
87
+ if (result.ok || result.workerResult?.classification !== "provider_quota_exhausted") {
88
+ return result;
89
+ }
90
+ const classification =
91
+ /** @type {ProviderQuotaError | null} */ (result.workerResult?.providerQuota ?? null);
92
+ // A quota exit without the SP-806 payload cannot drive a decision; the
93
+ // SP-807 truth table would answer `none/not_quota`, so bail out here.
94
+ if (!classification) {
95
+ return result;
96
+ }
97
+
98
+ // Synchronous decide → apply section: no `await` between the read inside
99
+ // decideQuotaFallback and the `state.resilience.quotaFallback` write at the
100
+ // top of applyQuotaFallback, so parallel lanes cannot both decide `apply`.
101
+ const decision = decideQuotaFallback({
102
+ config,
103
+ fallbackState: state.resilience?.quotaFallback ?? null,
104
+ classification,
105
+ taskId,
106
+ workerBackend,
107
+ });
108
+ if (decision.action === "stop") {
109
+ recordQuotaFallbackExhausted({ projectRoot, batchId, decision, taskId });
110
+ return result;
111
+ }
112
+ if (decision.action === "none") {
113
+ return result;
114
+ }
115
+ if (decision.action === "apply") {
116
+ await applyQuotaFallback({
117
+ projectRoot,
118
+ batchId,
119
+ state,
120
+ decision,
121
+ classification,
122
+ taskId,
123
+ now,
124
+ });
125
+ }
126
+
127
+ // `apply` and `retry` both retry the task once: record the consumed retry,
128
+ // reset the failed task for a fresh run (counters recomputed), persist, and
129
+ // pin the now-effective fallback model before the run so metrics stay true.
130
+ await recordQuotaFallbackRetry({ projectRoot, batchId, state, taskId });
131
+ resetTaskForRetry(state, taskId);
132
+ pinTaskWorkerModel(state, config, taskId);
133
+ await saveEngineBatchState(projectRoot, state);
134
+ const retried = await runOnce();
135
+ if (
136
+ !retried.ok &&
137
+ retried.workerResult?.classification === "provider_quota_exhausted"
138
+ ) {
139
+ // Decision runs once more only to journal exhaustion — the task is in
140
+ // `retriedTaskIds`, so SP-807 can only answer `stop`; never a second hop.
141
+ const second = decideQuotaFallback({
142
+ config,
143
+ fallbackState: state.resilience?.quotaFallback ?? null,
144
+ classification: /** @type {ProviderQuotaError | null} */ (retried.workerResult?.providerQuota ?? null),
145
+ taskId,
146
+ workerBackend,
147
+ });
148
+ if (second.action === "stop") {
149
+ recordQuotaFallbackExhausted({ projectRoot, batchId, decision: second, taskId });
150
+ }
151
+ }
152
+ return retried;
153
+ }