pi-spine 2.26.0 → 2.27.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/spine-review-step.mjs +8 -1
- package/bin/spine-worker-runner.mjs +15 -1
- package/package.json +3 -3
- package/skills/create-spine-tasks/SKILL.md +60 -33
- package/skills/create-spine-tasks/references/authoring-evidence.md +58 -0
- package/skills/create-spine-tasks/references/contract-template.md +52 -7
- package/skills/create-spine-tasks/references/prompt-template.md +72 -8
- package/skills/spine-release-operator/SKILL.md +33 -51
- package/skills/spine-release-operator/references/issue-intake-checklist.md +3 -1
- package/skills/spine-release-operator/references/pi-async-orchestration.md +13 -9
- package/skills/spine-release-operator/references/post-integrate-regression-gate.md +8 -1
- package/skills/spine-release-operator/references/publish-recovery.md +62 -0
- package/src/batch/batch-meta-reconstruct.mjs +3 -0
- package/src/batch/contract-exec.mjs +2 -2
- package/src/batch/contract-parse.mjs +2 -2
- package/src/batch/contract-prelanded.mjs +2 -2
- package/src/batch/diagnosis-alternatives.mjs +16 -1
- package/src/batch/diagnosis-handoff-packet.mjs +74 -0
- package/src/batch/diagnosis-pending-lane.mjs +52 -1
- package/src/batch/diagnosis-review-infra.mjs +144 -0
- package/src/batch/diagnosis-suggested-command.mjs +9 -0
- package/src/batch/diagnosis.mjs +19 -20
- package/src/batch/engine-lanes/merge.mjs +0 -8
- package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
- package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
- package/src/batch/engine-lanes/review-code.mjs +1 -0
- package/src/batch/engine-lanes/review-final.mjs +83 -46
- package/src/batch/engine-lanes/review-plan.mjs +22 -2
- package/src/batch/engine-lanes/review-poll.mjs +51 -2
- package/src/batch/engine-lanes.mjs +6 -8
- package/src/batch/gate-posture-approve.mjs +154 -15
- package/src/batch/integrate-path-delete.mjs +85 -0
- package/src/batch/integrate-worktree.mjs +20 -27
- package/src/batch/journal.mjs +15 -0
- package/src/batch/metrics.mjs +13 -1
- package/src/batch/provider-quota.mjs +220 -0
- package/src/batch/quota-fallback.mjs +319 -0
- package/src/batch/reconcile-diagnosis-context.mjs +22 -0
- package/src/batch/reconcile-diagnosis.mjs +24 -77
- package/src/batch/resume-multi-queue.mjs +25 -10
- package/src/batch/review-artifacts.mjs +96 -17
- package/src/batch/review-level-effective.mjs +19 -0
- package/src/batch/review-spawn-retry.mjs +106 -0
- package/src/batch/review-spawn.mjs +60 -3
- package/src/batch/review-step-run.mjs +110 -8
- package/src/batch/reviewer-output.mjs +162 -0
- package/src/batch/reviewer-provider-error.mjs +153 -0
- package/src/batch/worker-host.mjs +49 -3
- package/src/batch/worker-prompt.mjs +5 -2
- package/src/config/cursor-rules/discover.mjs +40 -3
- package/src/config/cursor-rules/match-globs.mjs +6 -4
- package/src/config/env-overrides.mjs +41 -4
- package/src/config/settings-fields.mjs +11 -0
- package/src/config/spine-config-schema.mjs +62 -0
- package/src/doctor/pi-extension-hooks.mjs +322 -0
- package/src/doctor/quota-risk.mjs +45 -0
- package/src/doctor/run-doctor-checks.mjs +14 -1
- package/src/planner/file-scope.mjs +6 -6
- package/src/tasks/packet/validate-contract.mjs +3 -3
- package/src/tasks/packet/validate-prompt.mjs +11 -1
- package/src/tasks/validate-contract-warn.mjs +16 -0
- package/templates/spine-config.json +1 -1
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Review-infrastructure exit reasons and failure-exit-reason resolution shared
|
|
3
|
+
* by `reconcile-diagnosis.mjs` and `diagnosis-pending-lane.mjs` (SP-821/#334).
|
|
4
|
+
* Leaf module — importing it from anywhere in `src/batch/` keeps the import
|
|
5
|
+
* graph acyclic (checked by tests/arch/import-cycles.test.mjs).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Exit reasons where reviewer *infrastructure* failed: the reviewer failed to
|
|
10
|
+
* spawn, timed out, or hit a provider error, so no verdict was produced. The
|
|
11
|
+
* implementation itself is not the failure (#291 / SP-718). Covers all three
|
|
12
|
+
* engine review types; the provider-error variants were added by SP-820.
|
|
13
|
+
*
|
|
14
|
+
* @type {ReadonlySet<string>}
|
|
15
|
+
*/
|
|
16
|
+
export const REVIEW_INFRASTRUCTURE_EXIT_REASONS = new Set([
|
|
17
|
+
"plan_review_spawn_failed",
|
|
18
|
+
"plan_review_timeout",
|
|
19
|
+
"plan_review_provider_error",
|
|
20
|
+
"code_review_spawn_failed",
|
|
21
|
+
"code_review_timeout",
|
|
22
|
+
"code_review_provider_error",
|
|
23
|
+
"final_review_spawn_failed",
|
|
24
|
+
"final_review_timeout",
|
|
25
|
+
"final_review_provider_error",
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {string|null|undefined} exitReason
|
|
30
|
+
* @returns {boolean}
|
|
31
|
+
*/
|
|
32
|
+
export function isReviewInfraExitReason(exitReason) {
|
|
33
|
+
return REVIEW_INFRASTRUCTURE_EXIT_REASONS.has(String(exitReason ?? ""));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Review type ("plan" | "code" | "final") for a review-infra exit reason.
|
|
38
|
+
*
|
|
39
|
+
* @param {string|null|undefined} exitReason
|
|
40
|
+
* @returns {string|null}
|
|
41
|
+
*/
|
|
42
|
+
export function resolveReviewInfraType(exitReason) {
|
|
43
|
+
const match = String(exitReason ?? "").match(/^(plan|code|final)_review_(?:spawn_failed|timeout|provider_error)$/);
|
|
44
|
+
return match ? (match[1] ?? null) : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {string|null|undefined} exitReason
|
|
49
|
+
* @returns {boolean}
|
|
50
|
+
*/
|
|
51
|
+
export function isReviewInfraProviderError(exitReason) {
|
|
52
|
+
return String(exitReason ?? "").endsWith("_provider_error");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @param {unknown} rawTasks
|
|
57
|
+
* @param {string|null} failedTaskId
|
|
58
|
+
* @returns {string|null}
|
|
59
|
+
*/
|
|
60
|
+
export function resolveFailedExitReason(rawTasks, failedTaskId) {
|
|
61
|
+
if (!failedTaskId || !Array.isArray(rawTasks)) return null;
|
|
62
|
+
const match = rawTasks.find((/** @type {any} */ entry) => {
|
|
63
|
+
if (!entry || typeof entry !== "object") return false;
|
|
64
|
+
return String(entry.taskId ?? entry.id ?? "") === failedTaskId;
|
|
65
|
+
});
|
|
66
|
+
if (!match || typeof match !== "object") return null;
|
|
67
|
+
const exitReason = /** @type {{ exitReason?: unknown }} */ (match).exitReason;
|
|
68
|
+
return typeof exitReason === "string" && exitReason ? exitReason : null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @param {string|null} failedTaskId
|
|
73
|
+
* @param {Record<string, any>} signals
|
|
74
|
+
* @returns {string|null}
|
|
75
|
+
*/
|
|
76
|
+
export function resolvePrimaryFailureExitReason(failedTaskId, signals) {
|
|
77
|
+
const fromTask = resolveFailedExitReason(signals.raw?.tasks, failedTaskId);
|
|
78
|
+
if (fromTask) return fromTask;
|
|
79
|
+
if (!failedTaskId) return null;
|
|
80
|
+
if (Array.isArray(signals.segments)) {
|
|
81
|
+
const segment = signals.segments.find((/** @type {any} */ entry) => entry?.taskId === failedTaskId);
|
|
82
|
+
const classification = segment?.classification;
|
|
83
|
+
if (
|
|
84
|
+
typeof classification === "string" &&
|
|
85
|
+
classification &&
|
|
86
|
+
classification !== "terminal-failure"
|
|
87
|
+
) {
|
|
88
|
+
return classification;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (Array.isArray(signals.journalEvents)) {
|
|
92
|
+
for (let index = signals.journalEvents.length - 1; index >= 0; index -= 1) {
|
|
93
|
+
const event = signals.journalEvents[index];
|
|
94
|
+
if (event.type !== "task.failed") continue;
|
|
95
|
+
const eventTaskId = event.taskId ?? event.payload?.taskId;
|
|
96
|
+
if (eventTaskId !== failedTaskId) continue;
|
|
97
|
+
const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
|
|
98
|
+
const reason = payload.exitReason ?? payload.classification;
|
|
99
|
+
if (typeof reason === "string" && reason) return reason;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Exit reason for a classified task entry: the entry's own `exitReason` when
|
|
107
|
+
* present, else the primary failure resolution (raw state → segments →
|
|
108
|
+
* journal `task.failed`). Parsed batch-state tasks drop `exitReason`
|
|
109
|
+
* (normalizeTasks), so the fallback keeps journal-only timelines working.
|
|
110
|
+
*
|
|
111
|
+
* @param {Record<string, any>|null|undefined} task
|
|
112
|
+
* @param {Record<string, any>} signals
|
|
113
|
+
* @returns {string|null}
|
|
114
|
+
*/
|
|
115
|
+
export function resolveTaskPrimaryFailureExitReason(task, signals) {
|
|
116
|
+
const fromTask = task?.exitReason;
|
|
117
|
+
if (typeof fromTask === "string" && fromTask) return fromTask;
|
|
118
|
+
return resolvePrimaryFailureExitReason(String(task?.taskId ?? ""), signals);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Headline for a needs_retry diagnosis caused by a review-infrastructure exit
|
|
123
|
+
* reason: the reviewer produced no verdict, so the review should re-run —
|
|
124
|
+
* not salvage-integrate unreviewed code (SP-821/#334, reversing SP-762).
|
|
125
|
+
* Provider-error variants point at `spine doctor` for launch diagnosis.
|
|
126
|
+
*
|
|
127
|
+
* @param {string} batchLabel
|
|
128
|
+
* @param {object} ctx
|
|
129
|
+
* @param {string|null} [ctx.exitReason]
|
|
130
|
+
* @param {string|null} [ctx.failedTaskId]
|
|
131
|
+
* @returns {string|null} null when `ctx.exitReason` is not a review-infra reason
|
|
132
|
+
*/
|
|
133
|
+
export function buildReviewInfraHeadline(batchLabel, ctx = {}) {
|
|
134
|
+
const exitReason = ctx.exitReason ?? "";
|
|
135
|
+
if (!isReviewInfraExitReason(exitReason)) return null;
|
|
136
|
+
const reviewType = resolveReviewInfraType(exitReason) ?? "review";
|
|
137
|
+
const providerError = isReviewInfraProviderError(exitReason);
|
|
138
|
+
const problem = providerError
|
|
139
|
+
? `${reviewType} review hit a provider error`
|
|
140
|
+
: `${reviewType} review produced no verdict`;
|
|
141
|
+
const taskSuffix = ctx.failedTaskId ? ` for task ${ctx.failedTaskId}` : "";
|
|
142
|
+
const doctorSuffix = providerError ? " — run spine doctor" : "";
|
|
143
|
+
return `${batchLabel} ${problem}${taskSuffix} (lane work is done) — re-run the review${doctorSuffix}`;
|
|
144
|
+
}
|
|
@@ -19,6 +19,7 @@ import { buildPrimaryFailureSuggestedCommand } from "./diagnosis-primary-failure
|
|
|
19
19
|
import { buildEngineOrphanParentExitSuggestedCommand } from "./diagnosis-parent-exit.mjs";
|
|
20
20
|
import { sanitizeRetrySuggestedCommand } from "./diagnosis-retry-command.mjs";
|
|
21
21
|
import { buildPendingLaneLandSuggestedCommand } from "./diagnosis-pending-lane.mjs";
|
|
22
|
+
import { isReviewInfraExitReason } from "./diagnosis-review-infra.mjs";
|
|
22
23
|
|
|
23
24
|
/**
|
|
24
25
|
* @param {string} diagnosis
|
|
@@ -89,6 +90,14 @@ export function buildSuggestedCommand(diagnosis, ctx = {}) {
|
|
|
89
90
|
if (ctx.launchFailureKind === "worktree_unhealthy") {
|
|
90
91
|
return "spine doctor";
|
|
91
92
|
}
|
|
93
|
+
// SP-821 / #334: review-infrastructure failures must re-run the review —
|
|
94
|
+
// `spine batch retry` resumes at the review (runWorker no-ops on the
|
|
95
|
+
// existing lane .DONE). Never a salvage command for these reasons.
|
|
96
|
+
if (isReviewInfraExitReason(ctx.exitReason)) {
|
|
97
|
+
return ctx.failedTaskId
|
|
98
|
+
? `spine batch retry ${ctx.failedTaskId}`
|
|
99
|
+
: "spine status --diagnose";
|
|
100
|
+
}
|
|
92
101
|
if (ctx.salvageRetryCommand) {
|
|
93
102
|
return sanitizeRetrySuggestedCommand(ctx.salvageRetryCommand, ctx.failedTaskId);
|
|
94
103
|
}
|
package/src/batch/diagnosis.mjs
CHANGED
|
@@ -67,6 +67,17 @@ export {
|
|
|
67
67
|
findPendingLaneLandTasks,
|
|
68
68
|
shouldDiagnosePendingLaneLand,
|
|
69
69
|
} from "./diagnosis-pending-lane.mjs";
|
|
70
|
+
import {
|
|
71
|
+
buildReviewInfraHeadline,
|
|
72
|
+
isReviewInfraExitReason,
|
|
73
|
+
} from "./diagnosis-review-infra.mjs";
|
|
74
|
+
export {
|
|
75
|
+
buildReviewInfraHeadline,
|
|
76
|
+
isReviewInfraExitReason,
|
|
77
|
+
isReviewInfraProviderError,
|
|
78
|
+
REVIEW_INFRASTRUCTURE_EXIT_REASONS,
|
|
79
|
+
resolveReviewInfraType,
|
|
80
|
+
} from "./diagnosis-review-infra.mjs";
|
|
70
81
|
export { buildSuggestedCommand } from "./diagnosis-suggested-command.mjs";
|
|
71
82
|
import { buildSuggestedCommand } from "./diagnosis-suggested-command.mjs";
|
|
72
83
|
export { buildBackground, buildAssessmentReason } from "./diagnosis-handoff-packet.mjs";
|
|
@@ -102,12 +113,6 @@ const NO_PAUSE_DIAGNOSES = new Set([
|
|
|
102
113
|
"integrate_isolated_ok",
|
|
103
114
|
"engine_still_running",
|
|
104
115
|
]);
|
|
105
|
-
const REVIEW_SPAWN_FAILURE_EXIT_REASONS = new Set([
|
|
106
|
-
"code_review_spawn_failed",
|
|
107
|
-
"code_review_timeout",
|
|
108
|
-
"final_review_spawn_failed",
|
|
109
|
-
"final_review_timeout",
|
|
110
|
-
]);
|
|
111
116
|
|
|
112
117
|
/**
|
|
113
118
|
* @param {string} diagnosis
|
|
@@ -176,20 +181,14 @@ export function buildHeadline(diagnosis, ctx = {}) {
|
|
|
176
181
|
if (ctx.launchFailureKind === "worktree_unhealthy") {
|
|
177
182
|
return `${batchLabel} failed at worker launch — repair lane worktree git, then retry`;
|
|
178
183
|
}
|
|
179
|
-
if (
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
: `${batchLabel} reviewer spawn timed out — retry`;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
return ctx.failedTaskId
|
|
191
|
-
? `${batchLabel} ${reviewKind} spawn failed for task ${ctx.failedTaskId} — retry`
|
|
192
|
-
: `${batchLabel} reviewer spawn failed — retry`;
|
|
184
|
+
if (isReviewInfraExitReason(ctx.exitReason)) {
|
|
185
|
+
// SP-821 / #334: reviewer infrastructure failed (spawn failure /
|
|
186
|
+
// timeout / provider error, plan+code+final) — no verdict was produced,
|
|
187
|
+
// so re-run the review rather than salvage-integrating unreviewed code.
|
|
188
|
+
return (
|
|
189
|
+
buildReviewInfraHeadline(batchLabel, ctx) ??
|
|
190
|
+
`${batchLabel} review produced no verdict — re-run the review`
|
|
191
|
+
);
|
|
193
192
|
}
|
|
194
193
|
if (ctx.salvageChangedFileCount > 0 && ctx.failedTaskId) {
|
|
195
194
|
return `${batchLabel} failed (${ctx.failedTaskId}): ${ctx.salvageChangedFileCount} uncommitted file(s) in scope`;
|
|
@@ -490,14 +490,6 @@ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
|
|
|
490
490
|
};
|
|
491
491
|
}
|
|
492
492
|
|
|
493
|
-
/**
|
|
494
|
-
* @deprecated use tryAutoResolveMergeConflicts
|
|
495
|
-
* @param {string} projectRoot
|
|
496
|
-
*/
|
|
497
|
-
export function tryAutoResolveRulesManifestMergeConflict(projectRoot) {
|
|
498
|
-
return tryAutoResolveMergeConflicts(projectRoot, {});
|
|
499
|
-
}
|
|
500
|
-
|
|
501
493
|
/**
|
|
502
494
|
* @param {string} projectRoot
|
|
503
495
|
* @param {string[]} args
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persisted quota-fallback state helpers (SP-808, partial #329).
|
|
3
|
+
*
|
|
4
|
+
* SP-807 (`../quota-fallback.mjs`) decides and shapes the single-hop fallback;
|
|
5
|
+
* this module owns the side effects the engine lane paths need (SP-809 wires
|
|
6
|
+
* the calls):
|
|
7
|
+
*
|
|
8
|
+
* - `applyQuotaFallback` persists `state.resilience.quotaFallback` and
|
|
9
|
+
* journals `batch.quota_fallback_applied` exactly once per hop;
|
|
10
|
+
* - `recordQuotaFallbackRetry` appends the retried task and journals
|
|
11
|
+
* `task.quota_fallback_retry`;
|
|
12
|
+
* - `recordQuotaFallbackExhausted` journals `batch.quota_fallback_exhausted`
|
|
13
|
+
* with every exhausted pool and its reset text;
|
|
14
|
+
* - `quotaFallbackWorkerEnv` / `resolveEffectiveWorkerModel` /
|
|
15
|
+
* `loadQuotaFallbackForWorker` let `runWorker` re-apply the persisted hop to
|
|
16
|
+
* every later worker spawn (sticky override) and report the model actually
|
|
17
|
+
* used, all read-only.
|
|
18
|
+
*
|
|
19
|
+
* Persistence uses `saveEngineBatchState` — the same saver the engine lane
|
|
20
|
+
* paths use (`engine-lanes/matrix-run.mjs`) — so an operator pause already on
|
|
21
|
+
* disk or in the journal is never clobbered by the whole-file write.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { appendJournalEvent } from "../journal.mjs";
|
|
25
|
+
import { saveEngineBatchState } from "../pause.mjs";
|
|
26
|
+
import { buildQuotaFallbackState, markQuotaFallbackRetry } from "../quota-fallback.mjs";
|
|
27
|
+
import { loadSpineBatchState } from "../state-io.mjs";
|
|
28
|
+
|
|
29
|
+
/** @typedef {import("../quota-fallback.mjs").QuotaFallbackState} QuotaFallbackState */
|
|
30
|
+
/** @typedef {import("../quota-fallback.mjs").QuotaFallbackApplyResult} QuotaFallbackApplyResult */
|
|
31
|
+
/** @typedef {import("../quota-fallback.mjs").QuotaFallbackStopResult} QuotaFallbackStopResult */
|
|
32
|
+
/** @typedef {import("../provider-quota.mjs").ProviderQuotaError} ProviderQuotaError */
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Applies the single quota-fallback hop: builds the persisted state from the
|
|
36
|
+
* SP-807 `apply` decision, stores it at `state.resilience.quotaFallback`,
|
|
37
|
+
* persists the batch state, and journals `batch.quota_fallback_applied`. The
|
|
38
|
+
* hop is sticky — callers must invoke this at most once per batch (the SP-807
|
|
39
|
+
* decision layer refuses a second hop while a fallback state exists).
|
|
40
|
+
*
|
|
41
|
+
* @param {object} params
|
|
42
|
+
* @param {string} params.projectRoot
|
|
43
|
+
* @param {string} params.batchId
|
|
44
|
+
* @param {Record<string, any>} params.state Live batch state (mutated in place, then persisted).
|
|
45
|
+
* @param {QuotaFallbackApplyResult} params.decision An `apply` result from `decideQuotaFallback`.
|
|
46
|
+
* @param {ProviderQuotaError} params.classification Classification that produced the decision.
|
|
47
|
+
* @param {string} params.taskId Task whose failure triggered the hop.
|
|
48
|
+
* @param {Date|number} params.now Clock injection point.
|
|
49
|
+
* @returns {Promise<QuotaFallbackState>} The persisted fallback state.
|
|
50
|
+
*/
|
|
51
|
+
export async function applyQuotaFallback({ projectRoot, batchId, state, decision, classification, taskId, now }) {
|
|
52
|
+
const fallbackState = buildQuotaFallbackState(decision, { classification, taskId, now });
|
|
53
|
+
if (!state.resilience || typeof state.resilience !== "object") {
|
|
54
|
+
state.resilience = {};
|
|
55
|
+
}
|
|
56
|
+
state.resilience.quotaFallback = fallbackState;
|
|
57
|
+
await saveEngineBatchState(projectRoot, state);
|
|
58
|
+
appendJournalEvent(projectRoot, batchId, "batch.quota_fallback_applied", {
|
|
59
|
+
fromProfile: fallbackState.fromProfile,
|
|
60
|
+
toProfile: fallbackState.toProfile,
|
|
61
|
+
fromModel: fallbackState.fromModel,
|
|
62
|
+
toModel: fallbackState.toModel,
|
|
63
|
+
exhaustedPool: fallbackState.exhaustedPool,
|
|
64
|
+
resetAtRaw: fallbackState.resetAtRaw,
|
|
65
|
+
taskIds: [taskId],
|
|
66
|
+
});
|
|
67
|
+
return fallbackState;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Records that a task consumed its one auto-retry onto the fallback pool:
|
|
72
|
+
* appends the taskId to the persisted state (SP-807 `markQuotaFallbackRetry`,
|
|
73
|
+
* idempotent), persists, and journals `task.quota_fallback_retry` with the
|
|
74
|
+
* fallback destination.
|
|
75
|
+
*
|
|
76
|
+
* @param {object} params
|
|
77
|
+
* @param {string} params.projectRoot
|
|
78
|
+
* @param {string} params.batchId
|
|
79
|
+
* @param {Record<string, any>} params.state Live batch state carrying `resilience.quotaFallback`.
|
|
80
|
+
* @param {string} params.taskId Task that was retried.
|
|
81
|
+
* @returns {Promise<QuotaFallbackState>} The evolved fallback state.
|
|
82
|
+
*/
|
|
83
|
+
export async function recordQuotaFallbackRetry({ projectRoot, batchId, state, taskId }) {
|
|
84
|
+
if (!state.resilience || typeof state.resilience !== "object") {
|
|
85
|
+
state.resilience = {};
|
|
86
|
+
}
|
|
87
|
+
const fallbackState = markQuotaFallbackRetry(state.resilience.quotaFallback, taskId);
|
|
88
|
+
state.resilience.quotaFallback = fallbackState;
|
|
89
|
+
await saveEngineBatchState(projectRoot, state);
|
|
90
|
+
appendJournalEvent(projectRoot, batchId, "task.quota_fallback_retry", {
|
|
91
|
+
taskId,
|
|
92
|
+
toProfile: fallbackState.toProfile,
|
|
93
|
+
toModel: fallbackState.toModel,
|
|
94
|
+
});
|
|
95
|
+
return fallbackState;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Journals `batch.quota_fallback_exhausted` for a SP-807 `stop` decision. The
|
|
100
|
+
* payload carries every exhausted pool and its index-aligned raw reset text
|
|
101
|
+
* (#329: the operator must see both reset windows when the fallback pool dies
|
|
102
|
+
* too). Pure journal side effect — no state mutation.
|
|
103
|
+
*
|
|
104
|
+
* @param {object} params
|
|
105
|
+
* @param {string} params.projectRoot
|
|
106
|
+
* @param {string} params.batchId
|
|
107
|
+
* @param {QuotaFallbackStopResult} params.decision A `stop` result from `decideQuotaFallback`.
|
|
108
|
+
* @param {string} params.taskId Task whose failure produced the stop.
|
|
109
|
+
*/
|
|
110
|
+
export function recordQuotaFallbackExhausted({ projectRoot, batchId, decision, taskId }) {
|
|
111
|
+
appendJournalEvent(projectRoot, batchId, "batch.quota_fallback_exhausted", {
|
|
112
|
+
taskId,
|
|
113
|
+
reason: decision.reason,
|
|
114
|
+
exhaustedPools: Array.isArray(decision.exhaustedPools) ? [...decision.exhaustedPools] : [],
|
|
115
|
+
resetAtRaw: Array.isArray(decision.resetAtRaw) ? [...decision.resetAtRaw] : [],
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Maps a persisted fallback state to the child-env override every later worker
|
|
121
|
+
* spawn must receive (SP-805 resolves `SPINE_AGENT_PROFILE_OVERRIDE` at config
|
|
122
|
+
* load). Returns `{}` when no hop is active so callers can merge blindly.
|
|
123
|
+
*
|
|
124
|
+
* @param {QuotaFallbackState|null|undefined} fallbackState
|
|
125
|
+
* @returns {Record<string, string>}
|
|
126
|
+
*/
|
|
127
|
+
export function quotaFallbackWorkerEnv(fallbackState) {
|
|
128
|
+
const toProfile = typeof fallbackState?.toProfile === "string" ? fallbackState.toProfile.trim() : "";
|
|
129
|
+
if (!toProfile) return {};
|
|
130
|
+
return { SPINE_AGENT_PROFILE_OVERRIDE: toProfile };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Resolves the worker model that is actually in effect: when a fallback hop is
|
|
135
|
+
* active, the fallback profile's worker model; otherwise the configured worker
|
|
136
|
+
* model. Used for quota classification and for the journaled `model` field so
|
|
137
|
+
* both tell the truth after a hop. Returns `undefined` when neither source
|
|
138
|
+
* yields a string (matching the pre-SP-808 `typeof === "string"` contract).
|
|
139
|
+
*
|
|
140
|
+
* @param {object|undefined} config Resolved spine config.
|
|
141
|
+
* @param {QuotaFallbackState|null|undefined} fallbackState
|
|
142
|
+
* @returns {string|undefined}
|
|
143
|
+
*/
|
|
144
|
+
export function resolveEffectiveWorkerModel(config, fallbackState) {
|
|
145
|
+
// The config arrives untyped; read the narrow slice this helper needs.
|
|
146
|
+
const cfg = /** @type {{ agents?: { profiles?: Record<string, any>, worker?: { model?: unknown } } }} */ (config ?? {});
|
|
147
|
+
const toProfile = typeof fallbackState?.toProfile === "string" ? fallbackState.toProfile.trim() : "";
|
|
148
|
+
if (toProfile) {
|
|
149
|
+
const profileModel = cfg.agents?.profiles?.[toProfile]?.worker?.model;
|
|
150
|
+
if (typeof profileModel === "string" && profileModel !== "") {
|
|
151
|
+
return profileModel;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const configured = cfg.agents?.worker?.model;
|
|
155
|
+
return typeof configured === "string" ? configured : undefined;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Read-only load of the persisted quota fallback for a worker spawn
|
|
160
|
+
* (`runWorker` must never write batch state). Returns the fallback state when
|
|
161
|
+
* the on-disk batch state belongs to `batchId` and carries one; `null` when
|
|
162
|
+
* the state file is missing, unreadable, stale (different batch), or has no
|
|
163
|
+
* active hop — in every case the caller behaves as if no override exists.
|
|
164
|
+
*
|
|
165
|
+
* @param {object} params
|
|
166
|
+
* @param {string} params.projectRoot
|
|
167
|
+
* @param {string} params.batchId
|
|
168
|
+
* @returns {QuotaFallbackState|null}
|
|
169
|
+
*/
|
|
170
|
+
export function loadQuotaFallbackForWorker({ projectRoot, batchId }) {
|
|
171
|
+
if (!projectRoot || !batchId) return null;
|
|
172
|
+
const loaded = loadSpineBatchState(projectRoot);
|
|
173
|
+
const state = loaded.raw;
|
|
174
|
+
if (!state || typeof state !== "object") return null;
|
|
175
|
+
if (String(state.batchId ?? "") !== String(batchId)) return null;
|
|
176
|
+
const fallback = state.resilience?.quotaFallback;
|
|
177
|
+
return fallback && typeof fallback === "object" ? fallback : null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* One-call resolution of everything `runWorker` needs for the sticky
|
|
182
|
+
* override: the persisted fallback (read-only), the effective worker model
|
|
183
|
+
* (fallback profile model when a hop is active, else the configured worker
|
|
184
|
+
* model), and the child env with the profile override merged UNDER the
|
|
185
|
+
* caller's `extraEnv` (caller keys win — e.g. matrix row identity, #229).
|
|
186
|
+
* Kept here so `worker-host.mjs` stays under its 500-LOC module cap.
|
|
187
|
+
*
|
|
188
|
+
* @param {object} params
|
|
189
|
+
* @param {string} [params.projectRoot]
|
|
190
|
+
* @param {string} [params.batchId]
|
|
191
|
+
* @param {object|undefined} params.config Resolved spine config.
|
|
192
|
+
* @param {Record<string, string>} [params.extraEnv] Caller-supplied child env.
|
|
193
|
+
* @returns {{ fallback: QuotaFallbackState|null, workerModel: string|undefined, extraEnv: Record<string, string> }}
|
|
194
|
+
*/
|
|
195
|
+
export function resolveWorkerQuotaFallbackContext({ projectRoot, batchId, config, extraEnv }) {
|
|
196
|
+
const fallback = projectRoot && batchId ? loadQuotaFallbackForWorker({ projectRoot, batchId }) : null;
|
|
197
|
+
return {
|
|
198
|
+
fallback,
|
|
199
|
+
workerModel: resolveEffectiveWorkerModel(config, fallback),
|
|
200
|
+
extraEnv: { ...quotaFallbackWorkerEnv(fallback), ...(extraEnv ?? {}) },
|
|
201
|
+
};
|
|
202
|
+
}
|