pi-spine 2.27.1 → 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 (46) 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 +16 -3
  4. package/package.json +1 -1
  5. package/skills/create-spine-tasks/references/prompt-template.md +5 -0
  6. package/skills/spine-release-operator/SKILL.md +14 -2
  7. package/src/batch/contract-task-start.mjs +23 -1
  8. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  9. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  10. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  11. package/src/batch/engine-lanes/review-code.mjs +20 -0
  12. package/src/batch/engine-lanes/review-final.mjs +10 -2
  13. package/src/batch/engine-lanes/review-poll.mjs +33 -0
  14. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  15. package/src/batch/engine-lanes.mjs +18 -17
  16. package/src/batch/journal.mjs +5 -3
  17. package/src/batch/metrics-rollup.mjs +98 -4
  18. package/src/batch/metrics.mjs +134 -9
  19. package/src/batch/provider-quota.mjs +155 -6
  20. package/src/batch/quota-fallback.mjs +87 -6
  21. package/src/batch/resume-lane-reviews.mjs +11 -10
  22. package/src/batch/retry-profile.mjs +77 -0
  23. package/src/batch/retry.mjs +32 -1
  24. package/src/batch/review-step-run.mjs +4 -0
  25. package/src/batch/review-step.mjs +1 -0
  26. package/src/batch/worker-heartbeat.mjs +10 -2
  27. package/src/batch/worker-host.mjs +1 -1
  28. package/src/batch/worker-prompt.mjs +4 -5
  29. package/src/cli/deps.mjs +3 -2
  30. package/src/config/agent-model-resolve.mjs +144 -8
  31. package/src/config/model-family.mjs +60 -0
  32. package/src/config/preflight/discovery.mjs +1 -0
  33. package/src/config/settings-fields.mjs +6 -0
  34. package/src/config/spine-config-schema.mjs +49 -0
  35. package/src/doctor/agent-model-inherit.mjs +78 -1
  36. package/src/doctor/run-doctor-checks.mjs +4 -1
  37. package/src/metrics/quota-cli.mjs +16 -0
  38. package/src/metrics/quota-probes.mjs +228 -31
  39. package/src/metrics/quota-snapshot.mjs +21 -2
  40. package/src/planner/graph.mjs +7 -5
  41. package/src/planner/pending.mjs +2 -2
  42. package/src/planner/scope.mjs +3 -3
  43. package/src/tasks/packet/parse-prompt.mjs +47 -0
  44. package/src/tasks/packet/validate-prompt.mjs +156 -1
  45. package/templates/agents/reviewer.md +3 -1
  46. package/templates/agents/worker.md +15 -19
@@ -13,6 +13,7 @@ import { forceMergeWave, startBatch } from "../src/batch/engine.mjs";
13
13
  import { parseBatchStartWaveFilter } from "../src/planner/wave-scope.mjs";
14
14
  import { pauseBatch } from "../src/batch/pause.mjs";
15
15
  import { resumeBatch } from "../src/batch/resume.mjs";
16
+ import { clearQuotaFallbackByOperator } from "../src/batch/engine-lanes/quota-fallback-state.mjs";
16
17
  import { retryTask, skipTask } from "../src/batch/retry.mjs";
17
18
  import { retryTaskRow, skipTaskRow, parseMatrixRowRef } from "../src/batch/retry-row.mjs";
18
19
  import { reconcileBatch } from "../src/batch/reconcile.mjs";
@@ -32,6 +33,7 @@ const BATCH_FLAG_VALUE_TAKERS = new Set([
32
33
  "--batch",
33
34
  "--reason",
34
35
  "--lane",
36
+ "--profile",
35
37
  ]);
36
38
 
37
39
  /**
@@ -39,8 +41,11 @@ const BATCH_FLAG_VALUE_TAKERS = new Set([
39
41
  */
40
42
  export function printBatchHelp() {
41
43
  return (
42
- "Usage: spine batch start <scope>|pause|resume|retry <taskId|[rowId]>|skip <taskId|[rowId]>|force-merge [--wave N]|salvage|abort|dismiss|complete [--batch ID] [--lane N] [--integrate] [--yes] [--reason TEXT] [--hard] [--force] [--force-superseded] [--attached] [--dry-run] [--wave N] [--through-wave N] [--skip-preflight] [--detect-manual-merge] [--json]\n" +
44
+ "Usage: spine batch start <scope>|pause|resume|retry <taskId|[rowId]> [--profile NAME] [--no-escalate]|skip <taskId|[rowId]>|force-merge [--wave N]|salvage|quota-fallback clear|abort|dismiss|complete [--batch ID] [--lane N] [--integrate] [--yes] [--reason TEXT] [--hard] [--force] [--force-superseded] [--attached] [--dry-run] [--wave N] [--through-wave N] [--skip-preflight] [--detect-manual-merge] [--json]\n" +
43
45
  " Row identity: retry/skip 'SP-X[rowId]' targets one matrix row; plain SP-X targets the whole task.\n" +
46
+ " retry --profile NAME Retry on another agents.profiles entry (content/contract failures only; quota/infra failures use agents.quotaFallbackProfile)\n" +
47
+ " retry --no-escalate Skip agents.escalatePolicy for this retry\n" +
48
+ " quota-fallback clear Delete the active quota fallback hop so workers return to the primary profile (paused/failed batches only)\n" +
44
49
  " abort --dry-run Preview abort (reason/archive target); does not archive, journal, or clear live batch\n"
45
50
  );
46
51
  }
@@ -67,6 +72,7 @@ export function isBatchHelpRequest(args) {
67
72
  "skip",
68
73
  "force-merge",
69
74
  "salvage",
75
+ "quota-fallback",
70
76
  ].includes(token),
71
77
  );
72
78
  if (subcommand && args.includes("help")) {
@@ -169,6 +175,12 @@ export function parseBatchArgs(args) {
169
175
  laneNumber = Number(args[laneIdx + 1]);
170
176
  }
171
177
 
178
+ let profile = null;
179
+ const profileIdx = args.indexOf("--profile");
180
+ if (profileIdx >= 0 && args[profileIdx + 1] && !args[profileIdx + 1].startsWith("--")) {
181
+ profile = args[profileIdx + 1];
182
+ }
183
+
172
184
  const subcommand =
173
185
  args.find(
174
186
  (t) =>
@@ -181,7 +193,8 @@ export function parseBatchArgs(args) {
181
193
  t === "retry" ||
182
194
  t === "skip" ||
183
195
  t === "force-merge" ||
184
- t === "salvage",
196
+ t === "salvage" ||
197
+ t === "quota-fallback",
185
198
  ) ?? null;
186
199
 
187
200
  let waveFilter = null;
@@ -218,6 +231,9 @@ export function parseBatchArgs(args) {
218
231
  forceSuperseded,
219
232
  integrate,
220
233
  yes,
234
+ profile,
235
+ profileFlag: flags.has("--profile"),
236
+ noEscalate: flags.has("--no-escalate"),
221
237
  batchId,
222
238
  reason,
223
239
  waveIndex,
@@ -351,13 +367,27 @@ export async function runSpineBatch(options) {
351
367
  if (!parsed.taskId) {
352
368
  return {
353
369
  exitCode: 1,
354
- output: "Usage: spine batch retry <taskId> | <taskId>[rowId] [--json]\n",
370
+ output: "Usage: spine batch retry <taskId> [--profile <name>] [--no-escalate] | <taskId>[rowId] [--json]\n",
355
371
  };
356
372
  }
373
+ if (parsed.profileFlag && !parsed.profile) {
374
+ return { exitCode: 1, output: "Usage: spine batch retry <taskId> --profile <name>\n" };
375
+ }
357
376
  const rowRef = parseMatrixRowRef(parsed.taskId);
377
+ if (rowRef && parsed.profileFlag) {
378
+ return {
379
+ exitCode: 1,
380
+ output: "--profile applies to whole-task retry; retry the task (SP-X) instead of a matrix row.\n",
381
+ };
382
+ }
358
383
  const result = rowRef
359
384
  ? retryTaskRow({ projectRoot, taskId: rowRef.taskId, rowId: rowRef.rowId })
360
- : retryTask({ projectRoot, taskId: parsed.taskId });
385
+ : retryTask({
386
+ projectRoot,
387
+ taskId: parsed.taskId,
388
+ profile: parsed.profile,
389
+ noEscalate: parsed.noEscalate,
390
+ });
361
391
  if (parsed.json) {
362
392
  return {
363
393
  exitCode: result.exitCode ?? (result.ok ? 0 : 1),
@@ -383,6 +413,18 @@ export async function runSpineBatch(options) {
383
413
  };
384
414
  }
385
415
 
416
+ if (parsed.subcommand === "quota-fallback") {
417
+ if (parsed.scope !== "clear") {
418
+ return { exitCode: 1, output: "Usage: spine batch quota-fallback clear [--json]\n" };
419
+ }
420
+ const result = clearQuotaFallbackByOperator({ projectRoot });
421
+ return {
422
+ exitCode: result.exitCode ?? (result.ok ? 0 : 1),
423
+ output: parsed.json ? `${JSON.stringify(result, null, 2)}\n` : result.output,
424
+ result,
425
+ };
426
+ }
427
+
386
428
  if (parsed.subcommand === "skip") {
387
429
  if (!parsed.taskId) {
388
430
  return {
@@ -217,6 +217,7 @@ export async function runSpineTasksValidate({
217
217
 
218
218
  const packet = loadTaskPacket(discoveredTask.folderPath, {
219
219
  contract: config.contract,
220
+ agents: config.agents,
220
221
  });
221
222
  const failure = collectPromptValidationFailure(packet, taskId);
222
223
  /** @type {string[]} */
@@ -42,7 +42,7 @@ import {
42
42
  isPiExtensionConflictOutput,
43
43
  shouldWorkerUsePiNoExtensions,
44
44
  } from "../src/doctor/pi-extension-conflict.mjs";
45
- import { parseContract, parsePrompt } from "../src/tasks/packet/parse-prompt.mjs";
45
+ import { PROMPT_THINKING_LEVELS, parseContract, parsePrompt } from "../src/tasks/packet/parse-prompt.mjs";
46
46
 
47
47
  /**
48
48
  * Actionable hint when pi worker spawn fails on duplicate extension tool registration.
@@ -66,13 +66,26 @@ function buildReviewJournal() {
66
66
 
67
67
  /**
68
68
  * Append worker model/thinking flags from spine-config (mirrors reviewer spawn in review.mjs).
69
+ * `SPINE_WORKER_THINKING_OVERRIDE` (per-task `**Thinking:**`, SP-835 / #340) wins over
70
+ * `agents.worker.thinking`; invalid values warn on stderr and are ignored.
69
71
  *
70
72
  * @param {string[]} piArgs
71
73
  * @param {object} [config]
74
+ * @param {Record<string, string|undefined>} [env] Defaults to `process.env`.
72
75
  */
73
- export function appendWorkerAgentModelArgs(piArgs, config = {}) {
76
+ export function appendWorkerAgentModelArgs(piArgs, config = {}, env = process.env) {
74
77
  const workerModel = config?.agents?.worker?.model;
75
- const workerThinking = config?.agents?.worker?.thinking;
78
+ let workerThinking = config?.agents?.worker?.thinking;
79
+ const thinkingOverride = env?.SPINE_WORKER_THINKING_OVERRIDE?.trim();
80
+ if (thinkingOverride) {
81
+ if (PROMPT_THINKING_LEVELS.includes(thinkingOverride)) {
82
+ workerThinking = thinkingOverride;
83
+ } else {
84
+ console.error(
85
+ `SPINE_WORKER_THINKING_OVERRIDE="${thinkingOverride}" ignored (expected ${PROMPT_THINKING_LEVELS.join("|")})`,
86
+ );
87
+ }
88
+ }
76
89
  if (workerModel && workerModel !== "inherit") {
77
90
  piArgs.push("--model", workerModel);
78
91
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.27.1",
3
+ "version": "2.28.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -14,6 +14,11 @@ Deterministic commands use the [execute-task variant](#execute-task-variant) ins
14
14
  **Created:** [YYYY-MM-DD]
15
15
  **Size:** [S | M | L]
16
16
  **Type:** [llm | execute]
17
+ **Profile:** [optional — worker profile name from `agents.profiles`]
18
+ **Thinking:** [optional — off | minimal | low | medium | high | xhigh]
19
+ **Reviewer Profile:** [optional — profile from `agents.profiles` whose `reviewer` block judges this task]
20
+
21
+ > **Agent header fields (#355):** All three are optional; omit them to use `agents.activeProfile`. Names allow `A-Z a-z 0-9 . _ -`. Engine reviews resolve the reviewer per task: `**Reviewer Profile:**` → `agents.profiles.<worker profile>.reviewerProfile` → `agents.reviewerProfile` → `agents.reviewer`, skipping any reviewer in the same model family as the worker. When no cross-family reviewer remains, the task fails with `review_blocked` before any reviewer spawns. `**Profile:**` feeds that resolution today; the worker spawn does not yet apply `**Profile:**` or `**Thinking:**`. See the operator runbook, "Reviewer profiles".
17
22
 
18
23
  ## Review Level: [0-2] ([None | Plan Only | Plan and Code])
19
24
 
@@ -10,6 +10,16 @@ You are the **pi-spine release operator**. Drive a **curated release cycle** fro
10
10
 
11
11
  Invoke explicitly: `/skill:spine-release-operator` or "run a spine release cycle for v1.5.1".
12
12
 
13
+ ## Spine CLI binary (repo checkout inside pi-spine only)
14
+
15
+ Every `spine …` command in this skill means the CLI from **this pi-spine checkout**, not the global install. The release cycle is the dogfood run for unreleased `main`; the global `spine` (npm `-g`, `pi install npm:pi-spine`) stays on the last published release because `main` can be unstable between releases. Other projects keep using the published global.
16
+
17
+ - Run `node bin/spine.mjs <args>` from the pi-spine repo root (batch start/resume/retry, wait, gate, integrate, doctor, preflight, plan, tasks validate, status).
18
+ - The engine resolves its worker runner and reviewer code from the package that launched it (`PACKAGE_ROOT`), so the binary you start a batch with decides which engine code runs.
19
+ - After each integrate, `npm install` on `main` (already required) keeps the checkout runnable; the next batch picks up the new engine automatically.
20
+ - Verify after a detached start: `ps -o command= -p <enginePid>` must show `<repo>/bin/spine.mjs`, not `/opt/homebrew/...` or `node_modules/pi-spine`.
21
+ - Never `npm link` the checkout or point the global at it; do not reinstall the global mid-release. Upgrade the global only after publish (Phase 6).
22
+
13
23
  **Not** for executing all pending tasks — use `spine-autonomous-operator` for that. This skill selects a **subset** fitting the release profile.
14
24
 
15
25
  ## Skill boundaries
@@ -62,7 +72,7 @@ Invoke explicitly: `/skill:spine-release-operator` or "run a spine release cycle
62
72
  - **Do not** execute tasks outside the approved manifest scope
63
73
  - **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))
64
74
  - **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
65
- - **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)
75
+ - **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, sticky once applied until it expires after the primary pool's parsed reset time or you run `spine batch quota-fallback clear` ([#350](https://github.com/beettlle/pi-spine/issues/350); journaled `batch.quota_fallback_cleared`), 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)
66
76
  - **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
67
77
  - **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))
68
78
  - **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)
@@ -291,7 +301,7 @@ Before the first wave, confirm the release manifest records **`Operator approved
291
301
 
292
302
  **Reviewer isolation:** reviewers no longer load user extensions — they spawn with `pi -ne` by default (v2.27.1, [#334](https://github.com/beettlle/pi-spine/issues/334)), so extension overrides matter only when `agents.reviewer.loadUserExtensions` is `true`. If a review spawn or provider failure hits a task whose `.DONE` is already in the lane, recover by re-review (`spine batch retry <taskId>` → `spine batch resume`), not salvage — salvage lands unreviewed work and is a last resort.
293
303
 
294
- **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`.
304
+ **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 until the primary pool's reset time passes or `spine batch quota-fallback clear` runs (#350), 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`.
295
305
 
296
306
  **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.
297
307
 
@@ -592,6 +602,8 @@ When `release.yml` fails: `gh run view <run-id> --log-failed`, then follow the s
592
602
 
593
603
  Post-publish smoke (**only after stage success and 2FA approve**): `scripts/post-publish-smoke.sh <version>` — bounded retry on registry lag (F9, [#247](https://github.com/beettlle/pi-spine/issues/247)). If retries exhaust, **STOP** and investigate; manual steps in [references/publish-recovery.md](references/publish-recovery.md#post-publish-smoke).
594
604
 
605
+ After smoke passes, upgrade the machine's global install to the new release (the only point the global changes): `npm install -g pi-spine@<version>`, then `spine --version` must print `<version>`. If pi loads the extension via `npm:pi-spine`, run `pi update` as well.
606
+
595
607
  Update `spine-tasks/CONTEXT.md` release note (version + date).
596
608
 
597
609
  ### Close remaining GitHub issues (final sweep)
@@ -5,6 +5,19 @@
5
5
 
6
6
  import { execFileSync } from "node:child_process";
7
7
 
8
+ const COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/i;
9
+
10
+ /**
11
+ * Hex-only commit SHA check (7-40 chars). Rejects option-like values (leading `-`)
12
+ * before they reach git argv or reviewer prompts (#313, #343).
13
+ *
14
+ * @param {unknown} value
15
+ * @returns {value is string}
16
+ */
17
+ export function isValidCommitSha(value) {
18
+ return typeof value === "string" && COMMIT_SHA_PATTERN.test(value);
19
+ }
20
+
8
21
  const PAYLOAD_COMMIT_KEYS = ["taskStartCommit", "startCommit", "commitSha", "headCommit", "laneBranchHead"];
9
22
 
10
23
  /**
@@ -178,7 +191,16 @@ function findFirstTaskStarted(journal, taskId, laneId, batchId) {
178
191
  * @param {{ journal: object[], taskId: string, laneId?: string|null, batchId?: string|null, worktreePath?: string|null }} options
179
192
  * @returns {string|null}
180
193
  */
181
- export function resolveTaskStartCommit({ journal, taskId, laneId, batchId, worktreePath }) {
194
+ export function resolveTaskStartCommit(options) {
195
+ const commit = resolveRawTaskStartCommit(options);
196
+ return isValidCommitSha(commit) ? commit : null;
197
+ }
198
+
199
+ /**
200
+ * @param {{ journal: object[], taskId: string, laneId?: string|null, batchId?: string|null, worktreePath?: string|null }} options
201
+ * @returns {string|null}
202
+ */
203
+ function resolveRawTaskStartCommit({ journal, taskId, laneId, batchId, worktreePath }) {
182
204
  if (!Array.isArray(journal) || !taskId) {
183
205
  return null;
184
206
  }
@@ -4,6 +4,8 @@
4
4
  * Kept out of diagnosis.mjs so the parent stays under the phase23 LOC cap.
5
5
  */
6
6
 
7
+ import { QUOTA_FALLBACK_EXPIRY_GRACE_MS } from "./quota-fallback.mjs";
8
+
7
9
  /**
8
10
  * True when the latest quota-exhaustion journal payload came from
9
11
  * `batch.quota_fallback_exhausted` — the parallel arrays are unique to that
@@ -87,6 +89,22 @@ export function buildBackground(diagnosis, ctx = {}) {
87
89
  fallback.exhaustedPool ?? "?"
88
90
  } -> ${fallback.toProfile}, batch ${ctx.batchId ?? "?"})`,
89
91
  );
92
+ // SP-843 (#350): the hop is sticky until its reset time passes or the operator
93
+ // clears it — show which, and name the clear command once the fallback pool died too.
94
+ const expiresAtMs =
95
+ typeof fallback.resetAt === "number" && Number.isFinite(fallback.resetAt)
96
+ ? fallback.resetAt + QUOTA_FALLBACK_EXPIRY_GRACE_MS
97
+ : null;
98
+ facts.push(
99
+ expiresAtMs !== null
100
+ ? `Quota fallback expires ${new Date(expiresAtMs).toISOString()}`
101
+ : "Quota fallback has no parsable reset time (no automatic expiry)",
102
+ );
103
+ if (isFallbackChainExhausted(ctx.lastQuotaExhausted)) {
104
+ facts.push(
105
+ "Fallback pool is also exhausted: after the primary pool resets, run `spine batch quota-fallback clear` (paused/failed batch), then `spine batch retry <taskId>` / `spine batch resume`",
106
+ );
107
+ }
90
108
  }
91
109
  if (ctx.launchFailureKind) {
92
110
  facts.push(`Launch failure kind: ${ctx.launchFailureKind}`);
@@ -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
  }