pi-spine 2.25.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 (66) 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/abort.mjs +74 -38
  7. package/src/batch/attached-engine-handoff.mjs +2 -2
  8. package/src/batch/attached-runner-promote.mjs +1 -1
  9. package/src/batch/attached-runner-reconcile.mjs +1 -1
  10. package/src/batch/batch-meta-reconstruct.mjs +9 -1
  11. package/src/batch/batch-state-lock.mjs +173 -31
  12. package/src/batch/contract-exec.mjs +48 -47
  13. package/src/batch/contract-parse.mjs +2 -2
  14. package/src/batch/contract-prelanded.mjs +2 -2
  15. package/src/batch/contract-spawn.mjs +225 -0
  16. package/src/batch/contract-verify.mjs +2 -1
  17. package/src/batch/detached-wait.mjs +1 -1
  18. package/src/batch/diagnosis-handoff-packet.mjs +74 -0
  19. package/src/batch/diagnosis-pending-lane.mjs +34 -1
  20. package/src/batch/engine-lanes/matrix-run.mjs +6 -6
  21. package/src/batch/engine-lanes/merge.mjs +135 -34
  22. package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
  23. package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
  24. package/src/batch/engine-lanes/review-code.mjs +1 -0
  25. package/src/batch/engine-lanes/review-final.mjs +83 -46
  26. package/src/batch/engine-lanes/review-plan.mjs +22 -2
  27. package/src/batch/engine-lanes/review-poll.mjs +47 -1
  28. package/src/batch/engine-lanes.mjs +17 -16
  29. package/src/batch/engine.mjs +10 -10
  30. package/src/batch/journal.mjs +15 -0
  31. package/src/batch/lifecycle-archive.mjs +76 -1
  32. package/src/batch/lifecycle-cleanup.mjs +110 -0
  33. package/src/batch/lifecycle.mjs +100 -72
  34. package/src/batch/metrics.mjs +13 -1
  35. package/src/batch/parent-session-monitor.mjs +77 -70
  36. package/src/batch/pause.mjs +92 -25
  37. package/src/batch/post-merge-limbo.mjs +35 -5
  38. package/src/batch/provider-quota.mjs +220 -0
  39. package/src/batch/quota-fallback.mjs +319 -0
  40. package/src/batch/reconcile-diagnosis-context.mjs +22 -0
  41. package/src/batch/resume-gate-reopen.mjs +24 -8
  42. package/src/batch/resume-multi-queue.mjs +25 -10
  43. package/src/batch/resume-multi.mjs +1 -1
  44. package/src/batch/resume.mjs +1 -1
  45. package/src/batch/review-artifacts.mjs +93 -15
  46. package/src/batch/review-spawn-retry.mjs +106 -0
  47. package/src/batch/review-spawn.mjs +48 -2
  48. package/src/batch/review-step-run.mjs +96 -6
  49. package/src/batch/reviewer-output.mjs +162 -0
  50. package/src/batch/sequence-run.mjs +26 -8
  51. package/src/batch/sequence-wait.mjs +87 -8
  52. package/src/batch/state-guards.mjs +39 -7
  53. package/src/batch/state-io.mjs +131 -17
  54. package/src/batch/state.mjs +1 -0
  55. package/src/batch/worker-host.mjs +81 -7
  56. package/src/config/cursor-rules/discover.mjs +2 -2
  57. package/src/config/cursor-rules/match-globs.mjs +6 -4
  58. package/src/config/defaults.mjs +15 -1
  59. package/src/config/env-overrides.mjs +41 -4
  60. package/src/config/preflight/git-batch.mjs +47 -0
  61. package/src/config/settings-fields.mjs +6 -0
  62. package/src/config/spine-config-schema.mjs +91 -1
  63. package/src/doctor/quota-risk.mjs +45 -0
  64. package/src/fs/atomic-write.mjs +37 -1
  65. package/src/planner/file-scope.mjs +6 -6
  66. package/src/tasks/packet/validate-contract.mjs +3 -3
@@ -319,7 +319,7 @@ export async function runMatrixSubLane({
319
319
  } else {
320
320
  // Verify the contract per row (testCommand + fileScopeMustChange
321
321
  // substituted with this row's values). This is the per-row gate.
322
- const verify = verifyContract(worktreePath, contract, {
322
+ const verify = await verifyContract(worktreePath, contract, {
323
323
  matrixRow: values,
324
324
  baseBranch,
325
325
  });
@@ -534,7 +534,7 @@ export async function runMatrixTaskForResume({
534
534
  state.phase = "failed";
535
535
  state.endedAt = Date.now();
536
536
  state.lastError = String(output).slice(0, 500);
537
- saveEngineBatchState(projectRoot, state);
537
+ await saveEngineBatchState(projectRoot, state);
538
538
  return {
539
539
  isMatrix: true,
540
540
  ok: false,
@@ -673,7 +673,7 @@ export async function runMatrixTaskOnLane({
673
673
  skippedRowIds.push(row.rowId);
674
674
  }
675
675
  updateSegmentForTask(state, taskId, "running");
676
- saveEngineBatchState(projectRoot, state);
676
+ await saveEngineBatchState(projectRoot, state);
677
677
 
678
678
  appendJournalEvent(projectRoot, batchId, "task.started", {
679
679
  taskId,
@@ -708,7 +708,7 @@ export async function runMatrixTaskOnLane({
708
708
  const runningEntry = task.matrixRows.find((/** @type {any} */ m) => m.rowId === row.rowId);
709
709
  if (runningEntry) {
710
710
  runningEntry.status = "running";
711
- saveEngineBatchState(projectRoot, state);
711
+ await saveEngineBatchState(projectRoot, state);
712
712
  }
713
713
  try {
714
714
  return await runMatrixSubLane({
@@ -796,7 +796,7 @@ export async function runMatrixTaskOnLane({
796
796
  task.exitReason = `matrix_sub_lane_failed:${failedSummary}`;
797
797
  updateSegmentForTask(state, taskId, "failed");
798
798
  recomputeTaskCounters(state);
799
- saveEngineBatchState(projectRoot, state);
799
+ await saveEngineBatchState(projectRoot, state);
800
800
  recordMatrixEvent(projectRoot, batchId, "matrix.task_failed", {
801
801
  taskId,
802
802
  laneNumber,
@@ -873,7 +873,7 @@ export async function runMatrixTaskOnLane({
873
873
  task.exitReason = `matrix_row_merge_failed:${rowResult.rowId}`;
874
874
  updateSegmentForTask(state, taskId, "failed");
875
875
  recomputeTaskCounters(state);
876
- saveEngineBatchState(projectRoot, state);
876
+ await saveEngineBatchState(projectRoot, state);
877
877
  return {
878
878
  ok: false,
879
879
  workerResult: {
@@ -25,6 +25,8 @@ import {
25
25
  import { recordWaveMergeResult } from "../merge/wave-merge-state.mjs";
26
26
  import { recordMergeBlocked } from "../lifecycle.mjs";
27
27
  import { appendJournalEvent } from "../journal.mjs";
28
+ import { LANES_DEFAULTS } from "../../config/defaults.mjs";
29
+ import { loadSpineConfig } from "../../config/spine-config-load.mjs";
28
30
  import { countCommitsAhead, gitPorcelain } from "../lane-commit.mjs";
29
31
  import { saveSpineBatchState } from "../state.mjs";
30
32
  import { loadTaskFileScopePaths } from "./queue.mjs";
@@ -54,6 +56,22 @@ function abortInProgressMerge(projectRoot) {
54
56
  }
55
57
  }
56
58
 
59
+ /**
60
+ * Stderr text of a failed gitExec error (execFileSync attaches piped stderr as a
61
+ * Buffer); falls back to the error message when stderr is empty.
62
+ *
63
+ * @param {unknown} err
64
+ * @returns {string}
65
+ */
66
+ function gitStderrText(err) {
67
+ const stderr = /** @type {{ stderr?: unknown }} */ (err)?.stderr;
68
+ if (stderr != null) {
69
+ const text = Buffer.isBuffer(stderr) ? stderr.toString("utf-8") : String(stderr);
70
+ if (text.trim()) return text.trim();
71
+ }
72
+ return err instanceof Error ? err.message : String(err);
73
+ }
74
+
57
75
  /**
58
76
  * @param {string} projectRoot
59
77
  */
@@ -136,24 +154,46 @@ function pathInLaneFileScope(filePath, laneFileScopePaths) {
136
154
  }
137
155
 
138
156
  /**
139
- * @param {string} projectRoot
140
- * @param {string} mergeBase
141
- * @param {string} taskBranch
142
- * @returns {Set<string>}
157
+ * Lane number for fail-closed messages, derived from the laneTaskBranch naming
158
+ * convention (`task/spine-lane-<n>-<batchId>`). Null for foreign branch names.
159
+ *
160
+ * @param {string | undefined} taskBranch
161
+ * @returns {number | null}
143
162
  */
144
- function listBranchChangedFiles(projectRoot, mergeBase, taskBranch) {
145
- const output = git(projectRoot, ["diff", "--name-only", `${mergeBase}..${taskBranch}`], {
146
- throwOnError: false,
147
- });
148
- if (!output) return new Set();
149
- return new Set(
150
- output
151
- .split("\n")
152
- .map((line) => line.trim())
153
- .filter(Boolean),
163
+ function laneNumberFromTaskBranch(taskBranch) {
164
+ const match = typeof taskBranch === "string" ? /-lane-(\d+)-/.exec(taskBranch) : null;
165
+ return match ? Number(match[1]) : null;
166
+ }
167
+
168
+ /**
169
+ * Allow-listed out-of-scope paths keep prefer-orch auto-resolution (SP-798 / #304).
170
+ * Matched with the same glob helper `pathInLaneFileScope` uses so File Scope and
171
+ * allow-list patterns behave identically.
172
+ *
173
+ * @param {string} filePath
174
+ * @param {readonly string[] | string[]} allowList
175
+ */
176
+ function pathInOutOfScopeAllowList(filePath, allowList) {
177
+ if (!Array.isArray(allowList)) return false;
178
+ return allowList.some(
179
+ (pattern) => typeof pattern === "string" && matchesContractPattern(filePath, pattern),
154
180
  );
155
181
  }
156
182
 
183
+ /**
184
+ * Load `lanes.outOfScopeMergeAllowList` from the repo config, falling back to
185
+ * LANES_DEFAULTS when the repo has no spine config (bare fixtures).
186
+ *
187
+ * @param {string} projectRoot
188
+ * @returns {string[]}
189
+ */
190
+ function loadOutOfScopeMergeAllowList(projectRoot) {
191
+ const loaded = loadSpineConfig(projectRoot);
192
+ const configured = loaded.config?.lanes?.outOfScopeMergeAllowList;
193
+ if (Array.isArray(configured)) return configured.filter((pattern) => typeof pattern === "string");
194
+ return [...LANES_DEFAULTS.outOfScopeMergeAllowList];
195
+ }
196
+
157
197
  /**
158
198
  * @param {string} projectRoot
159
199
  */
@@ -185,24 +225,46 @@ function resolveRulesManifestMergeConflict(projectRoot) {
185
225
  }
186
226
 
187
227
  /**
188
- * Prefer orch (merge --ours) for stale dependency artifacts outside lane file scope.
228
+ * Auto-resolve an out-of-scope conflict only when the path is allow-listed via
229
+ * `lanes.outOfScopeMergeAllowList` (SP-798 / #304). A conflicted path is only ever
230
+ * conflicted because both sides changed it, so prefer-orch always discards lane work;
231
+ * the lane blob (`:3:<path>`) is captured first so the caller can journal what was
232
+ * dropped. Paths that are neither in File Scope nor allow-listed fail closed.
189
233
  *
190
234
  * @param {object} params
191
235
  * @param {string} params.projectRoot
192
236
  * @param {string} params.filePath
193
237
  * @param {string[]} params.laneFileScopePaths
194
- * @param {Set<string>} params.laneChangedFiles
238
+ * @param {string[]} params.outOfScopeAllowList
239
+ * @param {number | null} params.laneNumber
240
+ * @param {string} params.taskBranch
241
+ * @param {string} params.orchBranch
242
+ * @returns {{ ok: true, strategy: "prefer_orch_out_of_scope", discarded: { path: string, laneBlob: string | null }, skippedGitignoredPaths: string[] } | { ok: false, reason: string, failureClass?: string, error?: string }}
195
243
  */
196
244
  function tryAutoResolveOutOfScopeMergeConflict({
197
245
  projectRoot,
198
246
  filePath,
199
247
  laneFileScopePaths,
200
- laneChangedFiles: _laneChangedFiles,
248
+ outOfScopeAllowList,
249
+ laneNumber,
250
+ taskBranch,
251
+ orchBranch,
201
252
  }) {
202
253
  if (pathInLaneFileScope(filePath, laneFileScopePaths)) {
203
254
  return { ok: false, reason: "in_lane_file_scope" };
204
255
  }
256
+ if (!pathInOutOfScopeAllowList(filePath, outOfScopeAllowList)) {
257
+ return {
258
+ ok: false,
259
+ reason: "not_allow_listed",
260
+ failureClass: "MergeConflict",
261
+ error:
262
+ `Lane ${laneNumber ?? "?"} (${taskBranch}) changed out-of-scope path ${filePath} ` +
263
+ `that also changed on ${orchBranch}; add it to File Scope or lanes.outOfScopeMergeAllowList`,
264
+ };
265
+ }
205
266
 
267
+ const laneBlob = git(projectRoot, ["rev-parse", `:3:${filePath}`], { throwOnError: false });
206
268
  gitExec(projectRoot, ["checkout", "--ours", "--", filePath], { projectRoot });
207
269
  const { stageable, skipped } = filterGitignoredPaths(projectRoot, [filePath]);
208
270
  if (stageable.length > 0) {
@@ -216,6 +278,7 @@ function tryAutoResolveOutOfScopeMergeConflict({
216
278
  return {
217
279
  ok: true,
218
280
  strategy: "prefer_orch_out_of_scope",
281
+ discarded: { path: filePath, laneBlob },
219
282
  skippedGitignoredPaths: skipped,
220
283
  };
221
284
  }
@@ -252,7 +315,7 @@ function collectLaneWaveFileScope(state, laneNumber, waveTaskIds) {
252
315
  * @param {string} [options.taskBranch]
253
316
  * @param {string} [options.orchBranch]
254
317
  * @param {number} [options.waveIndex]
255
- * @returns {{ ok: true, autoResolved: true, generatedAt?: string, outOfScopePaths?: string[], adoptionDocPaths?: string[], skippedGitignoredPaths?: string[] } | { ok: false, error: string, failureClass?: string, outOfScopePaths?: string[], adoptionDocPaths?: string[], skippedGitignoredPaths?: string[] }}
318
+ * @returns {{ ok: true, autoResolved: true, generatedAt?: string, outOfScopePaths?: string[], adoptionDocPaths?: string[], discardedOutOfScope?: { path: string, laneBlob: string | null }[], skippedGitignoredPaths?: string[] } | { ok: false, error: string, failureClass?: string, outOfScopePaths?: string[], adoptionDocPaths?: string[], skippedGitignoredPaths?: string[] }}
256
319
  */
257
320
  export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
258
321
  const { laneFileScopePaths = [], taskBranch, orchBranch, waveIndex } = options;
@@ -275,17 +338,13 @@ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
275
338
  Boolean(taskBranch) &&
276
339
  Boolean(orchBranch);
277
340
 
278
- /** @type {Set<string>} */
279
- let laneChangedFiles = new Set();
280
- if (canResolveOutOfScope) {
281
- const mergeBase = git(projectRoot, ["merge-base", /** @type {string} */ (orchBranch), /** @type {string} */ (taskBranch)], {
282
- throwOnError: false,
283
- });
284
- if (mergeBase) {
285
- laneChangedFiles = listBranchChangedFiles(projectRoot, mergeBase, /** @type {string} */ (taskBranch));
286
- }
287
- }
341
+ const outOfScopeAllowList = canResolveOutOfScope
342
+ ? loadOutOfScopeMergeAllowList(projectRoot)
343
+ : [];
344
+ const laneNumber = laneNumberFromTaskBranch(taskBranch);
288
345
 
346
+ /** @type {{ path: string, laneBlob: string | null }[]} */
347
+ const discardedOutOfScope = [];
289
348
  /** @type {string[]} */
290
349
  const resolvedOutOfScope = [];
291
350
  /** @type {string[]} */
@@ -335,13 +394,26 @@ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
335
394
  projectRoot,
336
395
  filePath,
337
396
  laneFileScopePaths,
338
- laneChangedFiles,
397
+ outOfScopeAllowList,
398
+ laneNumber,
399
+ taskBranch: /** @type {string} */ (taskBranch),
400
+ orchBranch: /** @type {string} */ (orchBranch),
339
401
  });
340
402
  if (resolved.ok) {
341
403
  resolvedOutOfScope.push(filePath);
404
+ discardedOutOfScope.push(resolved.discarded);
342
405
  if (Array.isArray(resolved.skippedGitignoredPaths) && resolved.skippedGitignoredPaths.length > 0) {
343
406
  skippedGitignoredPaths.push(...resolved.skippedGitignoredPaths);
344
407
  }
408
+ } else if (resolved.reason === "not_allow_listed") {
409
+ // Lane-committed out-of-scope conflict — fail closed instead of discarding (#304).
410
+ return {
411
+ ok: false,
412
+ failureClass: "MergeConflict",
413
+ error: /** @type {string} */ (resolved.error),
414
+ outOfScopePaths: resolvedOutOfScope,
415
+ adoptionDocPaths: resolvedAutoMergeDocs,
416
+ };
345
417
  } else {
346
418
  remaining.push(filePath);
347
419
  }
@@ -356,6 +428,7 @@ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
356
428
  return {
357
429
  ...manifestResult,
358
430
  outOfScopePaths: resolvedOutOfScope,
431
+ discardedOutOfScope,
359
432
  skippedGitignoredPaths,
360
433
  };
361
434
  }
@@ -372,6 +445,7 @@ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
372
445
  return {
373
446
  ...manifestResult,
374
447
  outOfScopePaths: resolvedOutOfScope,
448
+ discardedOutOfScope,
375
449
  skippedGitignoredPaths,
376
450
  };
377
451
  }
@@ -382,6 +456,7 @@ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
382
456
  autoResolved: true,
383
457
  outOfScopePaths: resolvedOutOfScope,
384
458
  adoptionDocPaths: resolvedAutoMergeDocs,
459
+ discardedOutOfScope,
385
460
  skippedGitignoredPaths,
386
461
  };
387
462
  }
@@ -408,8 +483,8 @@ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
408
483
  failureClass: "MergeConflict",
409
484
  error:
410
485
  `merge conflict on ${remaining.join(", ")}; automatic resolution supports docs/adoption/*, ` +
411
- `docs/PRD.md, ${RULES_MANIFEST_REL_PATH}, and out-of-scope dependency drift ` +
412
- "(prefer orch when the lane did not commit the path)",
486
+ `docs/PRD.md, and ${RULES_MANIFEST_REL_PATH}; out-of-scope conflicts are only ` +
487
+ "auto-resolved when allow-listed via lanes.outOfScopeMergeAllowList",
413
488
  outOfScopePaths: resolvedOutOfScope,
414
489
  adoptionDocPaths: resolvedAutoMergeDocs,
415
490
  };
@@ -496,7 +571,7 @@ function resolveRulesManifestPreMergeDrift(projectRoot) {
496
571
  * @param {string[]} [params.laneFileScopePaths]
497
572
  * @param {string[]} [params.laneTaskFolders]
498
573
  * @param {number} [params.waveIndex]
499
- * @returns {{ ok: true, mergeCommit: string, commitsAhead: number } | { ok: false, failureClass?: string, error: string, outOfScopePaths?: string[], skippedGitignoredPaths?: string[] }}
574
+ * @returns {{ ok: true, mergeCommit: string, commitsAhead: number, discardedOutOfScope: { path: string, laneBlob: string | null }[] } | { ok: false, failureClass?: string, error: string, outOfScopePaths?: string[], skippedGitignoredPaths?: string[] }}
500
575
  */
501
576
  export function mergeLaneToOrch({
502
577
  projectRoot,
@@ -511,6 +586,8 @@ export function mergeLaneToOrch({
511
586
  }) {
512
587
  const previous = gitStrict(projectRoot, ["rev-parse", "--abbrev-ref", "HEAD"]);
513
588
  let mergeInProgress = false;
589
+ /** @type {{ path: string, laneBlob: string | null }[]} */
590
+ let discardedOutOfScope = [];
514
591
  try {
515
592
  const drift = resolveRulesManifestPreMergeDrift(projectRoot);
516
593
  if (!drift.ok) {
@@ -558,7 +635,17 @@ export function mergeLaneToOrch({
558
635
  "-m",
559
636
  `merge ${taskBranch} into ${orchBranch}`,
560
637
  ]);
561
- } catch {
638
+ } catch (mergeErr) {
639
+ // SP-798 / #304: only real conflicts (unmerged index entries) may run the
640
+ // auto-resolver; hook/lock/untracked-overwrite failures are MergeFailed.
641
+ if (listUnmergedPaths(projectRoot).length === 0) {
642
+ abortInProgressMerge(projectRoot);
643
+ return {
644
+ ok: false,
645
+ failureClass: "MergeFailed",
646
+ error: gitStderrText(mergeErr),
647
+ };
648
+ }
562
649
  mergeInProgress = true;
563
650
  const autoResolved = tryAutoResolveMergeConflicts(projectRoot, {
564
651
  laneFileScopePaths,
@@ -584,6 +671,9 @@ export function mergeLaneToOrch({
584
671
  skippedPaths: autoResolved.skippedGitignoredPaths,
585
672
  });
586
673
  }
674
+ discardedOutOfScope = Array.isArray(autoResolved.discardedOutOfScope)
675
+ ? autoResolved.discardedOutOfScope
676
+ : [];
587
677
  gitStrict(projectRoot, ["commit", "--no-edit"]);
588
678
  }
589
679
 
@@ -599,7 +689,7 @@ export function mergeLaneToOrch({
599
689
  };
600
690
  }
601
691
 
602
- return { ok: true, mergeCommit, commitsAhead };
692
+ return { ok: true, mergeCommit, commitsAhead, discardedOutOfScope };
603
693
  } catch (err) {
604
694
  if (mergeInProgress) {
605
695
  abortInProgressMerge(projectRoot);
@@ -749,6 +839,17 @@ export function mergeWaveLanesToOrch({
749
839
  };
750
840
  }
751
841
  lastMergeCommit = merge.mergeCommit;
842
+ if (Array.isArray(merge.discardedOutOfScope) && merge.discardedOutOfScope.length > 0) {
843
+ appendJournalEvent(projectRoot, batchId, "batch.merge_out_of_scope_discarded", {
844
+ laneNumber,
845
+ payload: {
846
+ laneNumber,
847
+ taskBranch,
848
+ paths: merge.discardedOutOfScope.map((entry) => entry.path),
849
+ laneBlobs: merge.discardedOutOfScope.map((entry) => entry.laneBlob),
850
+ },
851
+ });
852
+ }
752
853
  appendJournalEvent(projectRoot, batchId, "batch.merge_completed", {
753
854
  mergeCommit: merge.mergeCommit,
754
855
  laneNumber,
@@ -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
+ }