pi-spine 2.27.0 → 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.
- package/bin/spine-batch.mjs +46 -4
- package/bin/spine-tasks.mjs +1 -0
- package/bin/spine-worker-runner.mjs +17 -3
- package/package.json +1 -1
- 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 +77 -8
- package/skills/spine-release-operator/SKILL.md +43 -52
- 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/contract-task-start.mjs +23 -1
- package/src/batch/diagnosis-alternatives.mjs +16 -1
- package/src/batch/diagnosis-handoff-packet.mjs +18 -0
- package/src/batch/diagnosis-pending-lane.mjs +18 -0
- 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 +11 -0
- package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
- package/src/batch/engine-lanes/review-code.mjs +20 -0
- package/src/batch/engine-lanes/review-final.mjs +10 -2
- package/src/batch/engine-lanes/review-poll.mjs +37 -1
- package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
- package/src/batch/engine-lanes.mjs +18 -18
- 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 +5 -3
- package/src/batch/metrics-rollup.mjs +98 -4
- package/src/batch/metrics.mjs +134 -9
- package/src/batch/provider-quota.mjs +156 -7
- package/src/batch/quota-fallback.mjs +87 -6
- package/src/batch/reconcile-diagnosis.mjs +24 -77
- package/src/batch/resume-lane-reviews.mjs +11 -10
- package/src/batch/retry-profile.mjs +77 -0
- package/src/batch/retry.mjs +32 -1
- package/src/batch/review-artifacts.mjs +3 -2
- package/src/batch/review-level-effective.mjs +19 -0
- package/src/batch/review-spawn.mjs +12 -1
- package/src/batch/review-step-run.mjs +18 -2
- package/src/batch/review-step.mjs +1 -0
- package/src/batch/reviewer-provider-error.mjs +153 -0
- package/src/batch/worker-heartbeat.mjs +10 -2
- package/src/batch/worker-host.mjs +1 -1
- package/src/batch/worker-prompt.mjs +9 -7
- package/src/cli/deps.mjs +3 -2
- package/src/config/agent-model-resolve.mjs +144 -8
- package/src/config/cursor-rules/discover.mjs +38 -1
- package/src/config/model-family.mjs +60 -0
- package/src/config/preflight/discovery.mjs +1 -0
- package/src/config/settings-fields.mjs +11 -0
- package/src/config/spine-config-schema.mjs +87 -0
- package/src/doctor/agent-model-inherit.mjs +78 -1
- package/src/doctor/pi-extension-hooks.mjs +322 -0
- package/src/doctor/run-doctor-checks.mjs +18 -2
- package/src/metrics/quota-cli.mjs +16 -0
- package/src/metrics/quota-probes.mjs +228 -31
- package/src/metrics/quota-snapshot.mjs +21 -2
- package/src/planner/graph.mjs +7 -5
- package/src/planner/pending.mjs +2 -2
- package/src/planner/scope.mjs +3 -3
- package/src/tasks/packet/parse-prompt.mjs +47 -0
- package/src/tasks/packet/validate-prompt.mjs +167 -2
- package/src/tasks/validate-contract-warn.mjs +16 -0
- package/templates/agents/reviewer.md +3 -1
- package/templates/agents/worker.md +15 -19
- package/templates/spine-config.json +1 -1
|
@@ -23,7 +23,7 @@ import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
|
|
|
23
23
|
* @property {ProviderQuotaKind} kind Why the output was classified.
|
|
24
24
|
* @property {string} poolId Shared quota pool the model belongs to (`resolvePoolId`).
|
|
25
25
|
* @property {number|null} httpStatus Three-digit HTTP status preceding the JSON payload, when present.
|
|
26
|
-
* @property {string|null} providerCode z.ai `code` or
|
|
26
|
+
* @property {string|null} providerCode z.ai `code`, Kimi/Anthropic `error.type`, or Google `error.status` of the matched rule, when matched.
|
|
27
27
|
* @property {string|null} resetAtRaw Raw text after "reset at" in the provider message (z.ai), when present.
|
|
28
28
|
* @property {null} resetAt Always null for now: the z.ai reset text carries no timezone (UTC+8 is inferred, not confirmed — #329).
|
|
29
29
|
* @property {string} message Provider message string, truncated to 300 characters.
|
|
@@ -83,15 +83,49 @@ function extractBalancedObject(text, startIndex) {
|
|
|
83
83
|
}
|
|
84
84
|
|
|
85
85
|
/**
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
86
|
+
* Matches the opening of an unprefixed provider error envelope: Google /
|
|
87
|
+
* OpenAI style `{"error":{...}}` and Anthropic style `{"type":"error",...}`.
|
|
88
|
+
* The key must be the object's first member so arbitrary objects embedded in
|
|
89
|
+
* logs do not qualify.
|
|
90
|
+
*/
|
|
91
|
+
const BARE_ENVELOPE_PATTERN = /\{\s*"(?:error|type)"\s*:/g;
|
|
92
|
+
|
|
93
|
+
/** Anthropic SDK reports overload as HTTP 529; mid-stream SSE errors drop the prefix. */
|
|
94
|
+
const ANTHROPIC_OVERLOADED_STATUS = 529;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Derives the HTTP status of an unprefixed provider envelope, or null when
|
|
98
|
+
* the object is not a recognised provider error envelope (#351):
|
|
99
|
+
* - `{"error":{"code":<3-digit>,...}}` (Google) → `error.code`.
|
|
100
|
+
* - `{"type":"error","error":{"type":"overloaded_error",...}}` (Anthropic
|
|
101
|
+
* mid-stream SSE) → 529.
|
|
102
|
+
*
|
|
103
|
+
* @param {Record<string, any>} payload
|
|
104
|
+
* @returns {number|null}
|
|
105
|
+
*/
|
|
106
|
+
function bareEnvelopeStatus(payload) {
|
|
107
|
+
const error = payload.error && typeof payload.error === "object" ? payload.error : null;
|
|
108
|
+
if (!error) return null;
|
|
109
|
+
if (Number.isInteger(error.code) && error.code >= 100 && error.code <= 999) return error.code;
|
|
110
|
+
if (payload.type === "error" && error.type === "overloaded_error") return ANTHROPIC_OVERLOADED_STATUS;
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Collects every provider error JSON payload in the output, in order of
|
|
116
|
+
* appearance: status-prefixed payloads (`429 {...}`) plus unprefixed
|
|
117
|
+
* envelopes recognised by {@link bareEnvelopeStatus} (Google `ApiError`
|
|
118
|
+
* text, Anthropic mid-stream SSE). A bare envelope nested inside a
|
|
119
|
+
* status-prefixed payload is not collected separately. Fragments that do not
|
|
120
|
+
* parse as JSON objects are ignored — they are not provider payloads.
|
|
89
121
|
*
|
|
90
122
|
* @param {string} output
|
|
91
123
|
* @returns {{httpStatus: number, payload: Record<string, any>}[]}
|
|
92
124
|
*/
|
|
93
|
-
function collectStatusPayloads(output) {
|
|
125
|
+
export function collectStatusPayloads(output) {
|
|
94
126
|
const candidates = [];
|
|
127
|
+
/** @type {{start: number, end: number}[]} */
|
|
128
|
+
const prefixedRanges = [];
|
|
95
129
|
STATUS_JSON_PATTERN.lastIndex = 0;
|
|
96
130
|
let match;
|
|
97
131
|
while ((match = STATUS_JSON_PATTERN.exec(output)) !== null) {
|
|
@@ -101,13 +135,35 @@ function collectStatusPayloads(output) {
|
|
|
101
135
|
try {
|
|
102
136
|
const payload = JSON.parse(raw);
|
|
103
137
|
if (payload && typeof payload === "object" && !Array.isArray(payload)) {
|
|
104
|
-
candidates.push({ httpStatus: Number(match[1]), payload });
|
|
138
|
+
candidates.push({ httpStatus: Number(match[1]), payload, position: objectStart });
|
|
139
|
+
prefixedRanges.push({ start: objectStart, end: objectStart + raw.length });
|
|
105
140
|
}
|
|
106
141
|
} catch {
|
|
107
142
|
// Malformed JSON is not a provider payload; keep scanning.
|
|
108
143
|
}
|
|
109
144
|
}
|
|
110
|
-
|
|
145
|
+
|
|
146
|
+
BARE_ENVELOPE_PATTERN.lastIndex = 0;
|
|
147
|
+
while ((match = BARE_ENVELOPE_PATTERN.exec(output)) !== null) {
|
|
148
|
+
const objectStart = match.index;
|
|
149
|
+
if (prefixedRanges.some((range) => objectStart >= range.start && objectStart < range.end)) continue;
|
|
150
|
+
const raw = extractBalancedObject(output, objectStart);
|
|
151
|
+
if (raw === null) continue;
|
|
152
|
+
// Skip nested objects of this envelope whether or not it is accepted.
|
|
153
|
+
BARE_ENVELOPE_PATTERN.lastIndex = objectStart + raw.length;
|
|
154
|
+
try {
|
|
155
|
+
const payload = JSON.parse(raw);
|
|
156
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) continue;
|
|
157
|
+
const httpStatus = bareEnvelopeStatus(payload);
|
|
158
|
+
if (httpStatus !== null) candidates.push({ httpStatus, payload, position: objectStart });
|
|
159
|
+
} catch {
|
|
160
|
+
// Malformed JSON is not a provider payload; keep scanning.
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// "Last payload wins" must hold across both passes: order by position.
|
|
165
|
+
candidates.sort((a, b) => a.position - b.position);
|
|
166
|
+
return candidates.map(({ httpStatus, payload }) => ({ httpStatus, payload }));
|
|
111
167
|
}
|
|
112
168
|
|
|
113
169
|
/**
|
|
@@ -124,6 +180,47 @@ function extractResetAtRaw(message) {
|
|
|
124
180
|
return match[1].trim().replace(/[.!]+$/, "");
|
|
125
181
|
}
|
|
126
182
|
|
|
183
|
+
/** Google retry hints below this many seconds mean a short (per-minute) window. */
|
|
184
|
+
const GOOGLE_TRANSIENT_RETRY_SECONDS = 120;
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Parses a Google `RetryInfo.retryDelay` duration string such as `"34s"` or
|
|
188
|
+
* `"34.5s"` into seconds.
|
|
189
|
+
*
|
|
190
|
+
* @param {unknown} retryDelay
|
|
191
|
+
* @returns {number|null} Seconds, or null when absent or unparseable.
|
|
192
|
+
*/
|
|
193
|
+
function parseRetryDelaySeconds(retryDelay) {
|
|
194
|
+
if (typeof retryDelay !== "string") return null;
|
|
195
|
+
const match = retryDelay.trim().match(/^(\d+(?:\.\d+)?)s$/);
|
|
196
|
+
return match ? Number(match[1]) : null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Reads Google `error.details[]`: the `RetryInfo.retryDelay` string and
|
|
201
|
+
* whether any `QuotaFailure.violations[].quotaId` names a per-minute quota.
|
|
202
|
+
*
|
|
203
|
+
* @param {unknown} details
|
|
204
|
+
* @returns {{retryDelay: string|null, perMinute: boolean}}
|
|
205
|
+
*/
|
|
206
|
+
function readGoogleQuotaDetails(details) {
|
|
207
|
+
let retryDelay = null;
|
|
208
|
+
let perMinute = false;
|
|
209
|
+
if (!Array.isArray(details)) return { retryDelay, perMinute };
|
|
210
|
+
for (const detail of details) {
|
|
211
|
+
if (!detail || typeof detail !== "object") continue;
|
|
212
|
+
const type = typeof detail["@type"] === "string" ? detail["@type"] : "";
|
|
213
|
+
if (type.endsWith("google.rpc.RetryInfo") && typeof detail.retryDelay === "string") {
|
|
214
|
+
retryDelay = detail.retryDelay;
|
|
215
|
+
} else if (type.endsWith("google.rpc.QuotaFailure") && Array.isArray(detail.violations)) {
|
|
216
|
+
for (const violation of detail.violations) {
|
|
217
|
+
if (typeof violation?.quotaId === "string" && violation.quotaId.includes("PerMinute")) perMinute = true;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return { retryDelay, perMinute };
|
|
222
|
+
}
|
|
223
|
+
|
|
127
224
|
/**
|
|
128
225
|
* Applies the classification rules to a single payload. The HTTP status is
|
|
129
226
|
* part of every rule so unrelated 4xx/5xx output never matches; a payload
|
|
@@ -136,6 +233,13 @@ function extractResetAtRaw(message) {
|
|
|
136
233
|
* "usage limit" (billing-cycle exhaustion) → quota_exhausted.
|
|
137
234
|
* - Kimi 429, `error.type` "rate_limit_error", message mentions
|
|
138
235
|
* "currently overloaded" → transient_overload.
|
|
236
|
+
* - Google 429, `error.code` 429 + `error.status` "RESOURCE_EXHAUSTED" →
|
|
237
|
+
* transient_overload when a `QuotaFailure` quotaId contains "PerMinute" or
|
|
238
|
+
* `RetryInfo.retryDelay` < 120 s, else quota_exhausted (#351).
|
|
239
|
+
* - Anthropic 529 (or unprefixed SSE) `overloaded_error` → transient_overload;
|
|
240
|
+
* 429 `rate_limit_error` (not Kimi's "currently overloaded") →
|
|
241
|
+
* transient_overload; 400 `invalid_request_error` "credit balance is too
|
|
242
|
+
* low" → quota_exhausted (#351).
|
|
139
243
|
*
|
|
140
244
|
* @param {number} httpStatus
|
|
141
245
|
* @param {Record<string, any>} payload
|
|
@@ -182,6 +286,51 @@ function classifyPayload(httpStatus, payload) {
|
|
|
182
286
|
message: truncateMessage(errorMessage),
|
|
183
287
|
};
|
|
184
288
|
}
|
|
289
|
+
|
|
290
|
+
// Google: `{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","details":[...]}}`.
|
|
291
|
+
if (httpStatus === 429 && error.code === 429 && error.status === "RESOURCE_EXHAUSTED") {
|
|
292
|
+
const { retryDelay, perMinute } = readGoogleQuotaDetails(error.details);
|
|
293
|
+
const retrySeconds = parseRetryDelaySeconds(retryDelay);
|
|
294
|
+
const transient = perMinute || (retrySeconds !== null && retrySeconds < GOOGLE_TRANSIENT_RETRY_SECONDS);
|
|
295
|
+
return {
|
|
296
|
+
kind: transient ? "transient_overload" : "quota_exhausted",
|
|
297
|
+
providerCode: "RESOURCE_EXHAUSTED",
|
|
298
|
+
resetAtRaw: retryDelay !== null ? `retry in ${retryDelay}` : null,
|
|
299
|
+
message: truncateMessage(errorMessage),
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// Anthropic: `{"type":"error","error":{"type":...,"message":...}}`.
|
|
304
|
+
if (httpStatus === ANTHROPIC_OVERLOADED_STATUS && error.type === "overloaded_error") {
|
|
305
|
+
return {
|
|
306
|
+
kind: "transient_overload",
|
|
307
|
+
providerCode: "overloaded_error",
|
|
308
|
+
resetAtRaw: null,
|
|
309
|
+
message: truncateMessage(errorMessage),
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
if (httpStatus === 429 && error.type === "rate_limit_error") {
|
|
313
|
+
// Kimi's "currently overloaded" wording is handled (first) above; any
|
|
314
|
+
// other rate_limit_error is Anthropic's per-minute limit.
|
|
315
|
+
return {
|
|
316
|
+
kind: "transient_overload",
|
|
317
|
+
providerCode: "rate_limit_error",
|
|
318
|
+
resetAtRaw: null,
|
|
319
|
+
message: truncateMessage(errorMessage),
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
if (
|
|
323
|
+
httpStatus === 400 &&
|
|
324
|
+
error.type === "invalid_request_error" &&
|
|
325
|
+
errorMessage.toLowerCase().includes("credit balance is too low")
|
|
326
|
+
) {
|
|
327
|
+
return {
|
|
328
|
+
kind: "quota_exhausted",
|
|
329
|
+
providerCode: "credit_balance_too_low",
|
|
330
|
+
resetAtRaw: null,
|
|
331
|
+
message: truncateMessage(errorMessage),
|
|
332
|
+
};
|
|
333
|
+
}
|
|
185
334
|
return null;
|
|
186
335
|
}
|
|
187
336
|
|
|
@@ -7,7 +7,9 @@
|
|
|
7
7
|
* SP-804 classification, and the worker backend:
|
|
8
8
|
*
|
|
9
9
|
* - at most one hop per batch (sticky once applied — a second exhaustion can
|
|
10
|
-
* only re-route lanes still pinned to the old pool, never pick a new pool)
|
|
10
|
+
* only re-route lanes still pinned to the old pool, never pick a new pool)
|
|
11
|
+
* until the hop is cleared: it expires once its parsed reset time plus a
|
|
12
|
+
* grace window has passed, or the operator clears it (SP-843, #350);
|
|
11
13
|
* - one auto-retry per task (`retriedTaskIds`), so no task ping-pongs;
|
|
12
14
|
* - transient overload, an unset fallback key, and the in-process
|
|
13
15
|
* `agentSession` backend never fall back;
|
|
@@ -38,6 +40,7 @@ import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
|
|
|
38
40
|
* @property {string} toModel Worker model after the hop.
|
|
39
41
|
* @property {string} exhaustedPool Pool whose exhaustion triggered the hop.
|
|
40
42
|
* @property {string|null} resetAtRaw Raw provider reset text for that pool, when it had one.
|
|
43
|
+
* @property {number|null} [resetAt] Epoch ms the exhausted pool resets (SP-843), or null when `resetAtRaw` is not parsable. Absent on hops persisted before SP-843 (never expires).
|
|
41
44
|
* @property {string} triggerTaskId Task whose failure triggered the hop.
|
|
42
45
|
* @property {string} at ISO timestamp of the hop.
|
|
43
46
|
* @property {string[]} retriedTaskIds Tasks already auto-retried onto the fallback pool.
|
|
@@ -96,6 +99,73 @@ import { resolvePoolId } from "../metrics/quota-snapshot.mjs";
|
|
|
96
99
|
* @typedef {{ agents?: { activeProfile?: unknown, worker?: { model?: unknown }, profiles?: Record<string, any>, quotaFallbackProfile?: unknown } }} QuotaFallbackConfig
|
|
97
100
|
*/
|
|
98
101
|
|
|
102
|
+
/** Grace after the parsed reset time before the hop expires (provider clocks drift). */
|
|
103
|
+
export const QUOTA_FALLBACK_EXPIRY_GRACE_MS = 5 * 60 * 1000;
|
|
104
|
+
|
|
105
|
+
/** z.ai reset text carries no timezone; the provider's local time is assumed UTC+8 (#329). */
|
|
106
|
+
const ZAI_UTC_OFFSET_MS = 8 * 60 * 60 * 1000;
|
|
107
|
+
|
|
108
|
+
const ZAI_RESET_PATTERN = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
|
|
109
|
+
const RETRY_IN_PATTERN = /^retry in (\d+(?:\.\d+)?)s$/i;
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Parses the raw provider reset text into an epoch-ms reset time. Pure.
|
|
113
|
+
*
|
|
114
|
+
* - z.ai `YYYY-MM-DD HH:MM:SS` → that wall-clock time read as UTC+8;
|
|
115
|
+
* - Google `retry in <N>s` → `at + N*1000` (relative to when the error was seen);
|
|
116
|
+
* - anything else (Kimi `10pm PT`, blank, non-string, impossible dates) → `null`.
|
|
117
|
+
*
|
|
118
|
+
* @param {unknown} resetAtRaw
|
|
119
|
+
* @param {{ at?: Date|number|string|null }} [options] `at`: when the exhaustion was observed (hop time); needed for `retry in <N>s`.
|
|
120
|
+
* @returns {number|null}
|
|
121
|
+
*/
|
|
122
|
+
export function parseQuotaResetAt(resetAtRaw, { at = null } = {}) {
|
|
123
|
+
if (typeof resetAtRaw !== "string") return null;
|
|
124
|
+
const text = resetAtRaw.trim();
|
|
125
|
+
|
|
126
|
+
const zai = ZAI_RESET_PATTERN.exec(text);
|
|
127
|
+
if (zai) {
|
|
128
|
+
const [year, month, day, hour, minute, second] = zai.slice(1).map(Number);
|
|
129
|
+
const wall = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
|
|
130
|
+
// Date.UTC rolls impossible values over (month 13, Feb 31); reject them.
|
|
131
|
+
if (
|
|
132
|
+
wall.getUTCFullYear() !== year ||
|
|
133
|
+
wall.getUTCMonth() !== month - 1 ||
|
|
134
|
+
wall.getUTCDate() !== day ||
|
|
135
|
+
wall.getUTCHours() !== hour ||
|
|
136
|
+
wall.getUTCMinutes() !== minute ||
|
|
137
|
+
wall.getUTCSeconds() !== second
|
|
138
|
+
) {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
return wall.getTime() - ZAI_UTC_OFFSET_MS;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const relative = RETRY_IN_PATTERN.exec(text);
|
|
145
|
+
if (relative && at !== null && at !== undefined) {
|
|
146
|
+
const base = new Date(at).getTime();
|
|
147
|
+
if (!Number.isFinite(base)) return null;
|
|
148
|
+
return base + Math.round(Number(relative[1]) * 1000);
|
|
149
|
+
}
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* True when a persisted hop has a parsed reset time and `now` is past it plus
|
|
155
|
+
* {@link QUOTA_FALLBACK_EXPIRY_GRACE_MS}. A hop without a parsable reset
|
|
156
|
+
* (`resetAt` null/absent, including hops persisted before SP-843) never expires.
|
|
157
|
+
*
|
|
158
|
+
* @param {QuotaFallbackState|null|undefined} fallbackState
|
|
159
|
+
* @param {Date|number} now
|
|
160
|
+
* @returns {boolean}
|
|
161
|
+
*/
|
|
162
|
+
export function isQuotaFallbackExpired(fallbackState, now) {
|
|
163
|
+
const resetAt = fallbackState?.resetAt;
|
|
164
|
+
if (typeof resetAt !== "number" || !Number.isFinite(resetAt)) return false;
|
|
165
|
+
const nowMs = new Date(now).getTime();
|
|
166
|
+
return Number.isFinite(nowMs) && nowMs >= resetAt + QUOTA_FALLBACK_EXPIRY_GRACE_MS;
|
|
167
|
+
}
|
|
168
|
+
|
|
99
169
|
/**
|
|
100
170
|
* Reads `agents.quotaFallbackProfile` from a resolved config. An unset,
|
|
101
171
|
* non-string, or blank value disables fallback entirely (SP-805 lets `""`
|
|
@@ -162,7 +232,9 @@ function buildExhaustedReport(fallbackState, classification) {
|
|
|
162
232
|
* ignore child env pins, so fallback cannot reach them.
|
|
163
233
|
* 4. `stop/profile_missing` — fallback profile absent from `agents.profiles`
|
|
164
234
|
* (defensive: the schema normally rejects this; fail closed on drift).
|
|
165
|
-
* 5. Fallback already applied (sticky
|
|
235
|
+
* 5. Fallback already applied (sticky until it expires or is cleared; one
|
|
236
|
+
* hop at a time). A hop that is expired at `now` counts as cleared, so a
|
|
237
|
+
* later exhaustion can hop again (SP-843):
|
|
166
238
|
* `stop/task_retry_spent` when the task already used its auto-retry;
|
|
167
239
|
* `retry` when the classification hits the original pool (a lane still
|
|
168
240
|
* pinned there) — re-route it, no new hop; otherwise
|
|
@@ -181,16 +253,21 @@ function buildExhaustedReport(fallbackState, classification) {
|
|
|
181
253
|
* @param {string} [params.taskId] Task the classification came from.
|
|
182
254
|
* @param {string} [params.workerBackend] Resolved worker backend.
|
|
183
255
|
* @param {string[]} [params.probeExhaustedPools] Pools a live probe reported exhausted.
|
|
256
|
+
* @param {Date|number} [params.now] When set, an expired `fallbackState` is treated as cleared (SP-843). Omitted: no expiry check.
|
|
184
257
|
* @returns {QuotaFallbackDecision}
|
|
185
258
|
*/
|
|
186
259
|
export function decideQuotaFallback({
|
|
187
260
|
config,
|
|
188
|
-
fallbackState = null,
|
|
261
|
+
fallbackState: persistedFallbackState = null,
|
|
189
262
|
classification = null,
|
|
190
263
|
taskId,
|
|
191
264
|
workerBackend,
|
|
192
265
|
probeExhaustedPools,
|
|
266
|
+
now,
|
|
193
267
|
} = {}) {
|
|
268
|
+
const fallbackState =
|
|
269
|
+
now !== undefined && isQuotaFallbackExpired(persistedFallbackState, now) ? null : persistedFallbackState;
|
|
270
|
+
|
|
194
271
|
// Row 1 — no fallback target configured.
|
|
195
272
|
const toProfileName = readFallbackProfileName(config);
|
|
196
273
|
if (toProfileName === null) {
|
|
@@ -224,7 +301,8 @@ export function decideQuotaFallback({
|
|
|
224
301
|
return stop("profile_missing");
|
|
225
302
|
}
|
|
226
303
|
|
|
227
|
-
// Row 5 — sticky:
|
|
304
|
+
// Row 5 — sticky: while the hop is active, no second hop is decided. An
|
|
305
|
+
// expired or cleared hop is `null` here, so the batch may hop again.
|
|
228
306
|
if (fallbackState) {
|
|
229
307
|
const retriedTaskIds = Array.isArray(fallbackState.retriedTaskIds) ? fallbackState.retriedTaskIds : [];
|
|
230
308
|
if (taskId !== undefined && taskId !== null && retriedTaskIds.includes(taskId)) {
|
|
@@ -283,15 +361,18 @@ export function decideQuotaFallback({
|
|
|
283
361
|
* @returns {QuotaFallbackState}
|
|
284
362
|
*/
|
|
285
363
|
export function buildQuotaFallbackState(decision, { classification, taskId, now }) {
|
|
364
|
+
const at = new Date(now);
|
|
365
|
+
const resetAtRaw = typeof classification.resetAtRaw === "string" ? classification.resetAtRaw : null;
|
|
286
366
|
return {
|
|
287
367
|
fromProfile: decision.fromProfile,
|
|
288
368
|
toProfile: decision.toProfile,
|
|
289
369
|
fromModel: decision.fromModel,
|
|
290
370
|
toModel: decision.toModel,
|
|
291
371
|
exhaustedPool: decision.exhaustedPool,
|
|
292
|
-
resetAtRaw
|
|
372
|
+
resetAtRaw,
|
|
373
|
+
resetAt: parseQuotaResetAt(resetAtRaw, { at }),
|
|
293
374
|
triggerTaskId: taskId,
|
|
294
|
-
at:
|
|
375
|
+
at: at.toISOString(),
|
|
295
376
|
retriedTaskIds: [],
|
|
296
377
|
};
|
|
297
378
|
}
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
/** Diagnosis derivation (SP-596/SP-606 / #192). */
|
|
2
2
|
|
|
3
3
|
import { inferLaunchFailureKind } from "./diagnosis.mjs";
|
|
4
|
+
import {
|
|
5
|
+
REVIEW_INFRASTRUCTURE_EXIT_REASONS,
|
|
6
|
+
resolvePrimaryFailureExitReason,
|
|
7
|
+
resolveTaskPrimaryFailureExitReason,
|
|
8
|
+
} from "./diagnosis-review-infra.mjs";
|
|
4
9
|
import {
|
|
5
10
|
findPendingLaneLandTasks,
|
|
6
11
|
shouldDiagnosePendingLaneLand,
|
|
@@ -21,56 +26,6 @@ export {
|
|
|
21
26
|
laneTaskBranchForDiagnosis,
|
|
22
27
|
} from "./reconcile-diagnosis-enrich.mjs";
|
|
23
28
|
|
|
24
|
-
/**
|
|
25
|
-
* @param {unknown} rawTasks
|
|
26
|
-
* @param {string|null} failedTaskId
|
|
27
|
-
* @returns {string|null}
|
|
28
|
-
*/
|
|
29
|
-
function resolveFailedExitReason(rawTasks, failedTaskId) {
|
|
30
|
-
if (!failedTaskId || !Array.isArray(rawTasks)) return null;
|
|
31
|
-
const match = rawTasks.find((/** @type {any} */ entry) => {
|
|
32
|
-
if (!entry || typeof entry !== "object") return false;
|
|
33
|
-
return String(entry.taskId ?? entry.id ?? "") === failedTaskId;
|
|
34
|
-
});
|
|
35
|
-
if (!match || typeof match !== "object") return null;
|
|
36
|
-
const exitReason = /** @type {{ exitReason?: unknown }} */ (match).exitReason;
|
|
37
|
-
return typeof exitReason === "string" && exitReason ? exitReason : null;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* @param {string|null} failedTaskId
|
|
42
|
-
* @param {Record<string, any>} signals
|
|
43
|
-
* @returns {string|null}
|
|
44
|
-
*/
|
|
45
|
-
function resolvePrimaryFailureExitReason(failedTaskId, signals) {
|
|
46
|
-
const fromTask = resolveFailedExitReason(signals.raw?.tasks, failedTaskId);
|
|
47
|
-
if (fromTask) return fromTask;
|
|
48
|
-
if (!failedTaskId) return null;
|
|
49
|
-
if (Array.isArray(signals.segments)) {
|
|
50
|
-
const segment = signals.segments.find((/** @type {any} */ entry) => entry?.taskId === failedTaskId);
|
|
51
|
-
const classification = segment?.classification;
|
|
52
|
-
if (
|
|
53
|
-
typeof classification === "string" &&
|
|
54
|
-
classification &&
|
|
55
|
-
classification !== "terminal-failure"
|
|
56
|
-
) {
|
|
57
|
-
return classification;
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
if (Array.isArray(signals.journalEvents)) {
|
|
61
|
-
for (let index = signals.journalEvents.length - 1; index >= 0; index -= 1) {
|
|
62
|
-
const event = signals.journalEvents[index];
|
|
63
|
-
if (event.type !== "task.failed") continue;
|
|
64
|
-
const eventTaskId = event.taskId ?? event.payload?.taskId;
|
|
65
|
-
if (eventTaskId !== failedTaskId) continue;
|
|
66
|
-
const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
|
|
67
|
-
const reason = payload.exitReason ?? payload.classification;
|
|
68
|
-
if (typeof reason === "string" && reason) return reason;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
return null;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
29
|
/**
|
|
75
30
|
* @param {string|null} failedTaskId
|
|
76
31
|
* @param {string|null} exitReason
|
|
@@ -134,33 +89,24 @@ function hasNeedsReplanBlocker(signals) {
|
|
|
134
89
|
return tasks.some((/** @type {any} */ task) => task?.exitReason === "needs_replan");
|
|
135
90
|
}
|
|
136
91
|
|
|
137
|
-
/**
|
|
138
|
-
* Plan-review exit reasons where reviewer infrastructure failed after the
|
|
139
|
-
* worker had already completed its lane work (#291 / SP-762). Mirrors the
|
|
140
|
-
* SP-718 final-review distinction: spawn failure / timeout mean no verdict
|
|
141
|
-
* was produced — the implementation itself is not the failure.
|
|
142
|
-
*/
|
|
143
|
-
const POST_DONE_PLAN_REVIEW_EXIT_REASONS = new Set([
|
|
144
|
-
"plan_review_spawn_failed",
|
|
145
|
-
"plan_review_timeout",
|
|
146
|
-
]);
|
|
147
|
-
|
|
148
92
|
/**
|
|
149
93
|
* Failed task whose lane work already completed (done evidence / `.DONE` in
|
|
150
|
-
* the lane worktree) but whose engine plan
|
|
151
|
-
* out
|
|
152
|
-
*
|
|
94
|
+
* the lane worktree) but whose engine review (plan, code, or final) failed to
|
|
95
|
+
* spawn, timed out, or hit a provider error — no verdict was ever produced
|
|
96
|
+
* (SP-821 / #334). Such tasks get re-review guidance, not salvage: the retry
|
|
97
|
+
* command resumes at the review (`runWorker` no-ops on existing `.DONE`),
|
|
98
|
+
* whereas `salvage --integrate` lands code no reviewer saw. This reverses the
|
|
99
|
+
* SP-762 pending_lane_land mapping for the plan-review case (#291) and
|
|
100
|
+
* extends the shared reason set to code/final and provider errors.
|
|
153
101
|
*
|
|
154
102
|
* Parsed batch-state tasks drop `exitReason` (normalizeTasks), so the exit
|
|
155
103
|
* reason is resolved the same way deriveFailureContext resolves it: from the
|
|
156
104
|
* task entry when present, else raw state / journal `task.failed` events.
|
|
157
|
-
* The salvage command itself hard-gates on commits-ahead, so pointing at it
|
|
158
|
-
* without lane commits is safe (dry-run reports none salvageable).
|
|
159
105
|
*
|
|
160
106
|
* @param {Record<string, any>} signals
|
|
161
107
|
* @returns {Record<string, any>|null}
|
|
162
108
|
*/
|
|
163
|
-
function
|
|
109
|
+
function findPostDoneReviewInfraFailedTask(signals) {
|
|
164
110
|
const tasks = Array.isArray(signals.tasks) ? signals.tasks : [];
|
|
165
111
|
for (const task of tasks) {
|
|
166
112
|
if (String(task?.status ?? "").toLowerCase() !== "failed") continue;
|
|
@@ -170,9 +116,8 @@ function findPostDonePlanReviewSpawnFailedTask(signals) {
|
|
|
170
116
|
task?.doneFileFound === true ||
|
|
171
117
|
String(task?.classification ?? "").toLowerCase() === "terminal-success";
|
|
172
118
|
if (!hasDoneEvidence) continue;
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
if (!POST_DONE_PLAN_REVIEW_EXIT_REASONS.has(String(exitReason ?? ""))) continue;
|
|
119
|
+
const exitReason = resolveTaskPrimaryFailureExitReason(task, signals);
|
|
120
|
+
if (!REVIEW_INFRASTRUCTURE_EXIT_REASONS.has(String(exitReason ?? ""))) continue;
|
|
176
121
|
return task;
|
|
177
122
|
}
|
|
178
123
|
return null;
|
|
@@ -278,14 +223,16 @@ export function deriveDiagnosis(signals) {
|
|
|
278
223
|
if (doneMissing) {
|
|
279
224
|
return withFailureContext("worker_done_missing", failedTaskId, signals);
|
|
280
225
|
}
|
|
281
|
-
// Post-DONE
|
|
282
|
-
//
|
|
283
|
-
//
|
|
284
|
-
|
|
285
|
-
|
|
226
|
+
// Post-DONE review-infrastructure failure (plan/code/final spawn failure,
|
|
227
|
+
// timeout, or provider error): lane work is complete but no verdict was
|
|
228
|
+
// produced. Map to needs_retry — `spine batch retry` resumes at the review
|
|
229
|
+
// because runWorker no-ops on the existing lane .DONE. Salvage --integrate
|
|
230
|
+
// would land code no reviewer saw (SP-821 / #334, reversing SP-762).
|
|
231
|
+
const postDoneReviewInfraTask = findPostDoneReviewInfraFailedTask(signals);
|
|
232
|
+
if (postDoneReviewInfraTask) {
|
|
286
233
|
return withFailureContext(
|
|
287
|
-
"
|
|
288
|
-
|
|
234
|
+
"needs_retry",
|
|
235
|
+
postDoneReviewInfraTask.taskId ?? failedTaskId,
|
|
289
236
|
signals,
|
|
290
237
|
);
|
|
291
238
|
}
|
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Resume lane review phases — mirror engine-lanes review before lane commit (SP-359).
|
|
3
3
|
* Engine-owned plan review runs first for RL≥1 (SP-695 / #250).
|
|
4
|
+
* Resumed reviews use the same per-task effective reviewer config as a fresh run (SP-834 / #355).
|
|
4
5
|
*/
|
|
5
6
|
|
|
6
7
|
import { runCodeReviewPhase, runFinalReviewPhase, runPlanReviewPhase } from "./engine-lanes/review.mjs";
|
|
8
|
+
import { applyTaskReviewProfile } from "./engine-lanes/task-agent-profile.mjs";
|
|
7
9
|
|
|
8
10
|
/**
|
|
9
|
-
* @param {
|
|
11
|
+
* @param {Record<string, any>} params
|
|
10
12
|
*/
|
|
11
13
|
export async function runLaneReviewPhasesBeforeCommit(params) {
|
|
12
|
-
const
|
|
13
|
-
if (!
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
return runFinalReviewPhase(params);
|
|
14
|
+
const reviewProfile = await applyTaskReviewProfile(params);
|
|
15
|
+
if (!reviewProfile.ok) return reviewProfile;
|
|
16
|
+
const reviewParams = { ...params, config: reviewProfile.config };
|
|
17
|
+
const planReview = await runPlanReviewPhase(reviewParams);
|
|
18
|
+
if (!planReview.ok) return planReview;
|
|
19
|
+
const codeReview = await runCodeReviewPhase(reviewParams);
|
|
20
|
+
if (!codeReview.ok) return codeReview;
|
|
21
|
+
return runFinalReviewPhase(reviewParams);
|
|
21
22
|
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Retry profile escalation decision (SP-836 / #340).
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Failure classes (`task.exitReason`) that are content/contract failures: a stronger
|
|
7
|
+
* profile can plausibly fix them (SP-836 / #340). Everything else — provider quota/403,
|
|
8
|
+
* overload, launch, stall/orphan, `review_blocked`, reviewer spawn/provider errors — is a
|
|
9
|
+
* provider/infra failure and must never escalate (#248, #329; quota uses
|
|
10
|
+
* `agents.quotaFallbackProfile`).
|
|
11
|
+
*/
|
|
12
|
+
export const ESCALATION_ELIGIBLE_CLASSES = Object.freeze(["contract_failed", "review_exhausted"]);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {unknown} value
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/
|
|
18
|
+
function trimmedString(value) {
|
|
19
|
+
return typeof value === "string" ? value.trim() : "";
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Decide the `task.profileOverride` for a retry (SP-836 / #340). Pure: reads the
|
|
24
|
+
* failure class off the (not yet reset) task and the `agents` config.
|
|
25
|
+
*
|
|
26
|
+
* @param {object} params
|
|
27
|
+
* @param {Record<string, any>} params.task Batch-state task row, before `resetTaskForRetry`.
|
|
28
|
+
* @param {Record<string, any>|null} [params.config] Effective config.
|
|
29
|
+
* @param {string|null} [params.profile] Operator `--profile` value.
|
|
30
|
+
* @param {boolean} [params.noEscalate] Operator `--no-escalate`.
|
|
31
|
+
* @returns {{ ok: true, profileOverride: string|null, escalation: "manual"|"auto"|null, apply: boolean }
|
|
32
|
+
* | { ok: false, error: string, output: string }}
|
|
33
|
+
*/
|
|
34
|
+
export function resolveRetryProfileOverride({ task, config = null, profile = null, noEscalate = false }) {
|
|
35
|
+
const agents = config?.agents && typeof config.agents === "object" ? config.agents : {};
|
|
36
|
+
const profiles = agents.profiles && typeof agents.profiles === "object" ? agents.profiles : {};
|
|
37
|
+
const failureClass = trimmedString(task?.exitReason) || trimmedString(task?.classification);
|
|
38
|
+
const eligible = ESCALATION_ELIGIBLE_CLASSES.includes(failureClass);
|
|
39
|
+
const currentOverride = trimmedString(task?.profileOverride) || null;
|
|
40
|
+
|
|
41
|
+
const requested = trimmedString(profile);
|
|
42
|
+
if (profile != null) {
|
|
43
|
+
const defined = Object.keys(profiles);
|
|
44
|
+
if (requested === "" || !Object.hasOwn(profiles, requested)) {
|
|
45
|
+
return {
|
|
46
|
+
ok: false,
|
|
47
|
+
error: "unknown_profile",
|
|
48
|
+
output: `Unknown profile "${requested}". Defined profiles: ${defined.length > 0 ? defined.join(", ") : "(none)"}.\n`,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
if (!eligible) {
|
|
52
|
+
const label = failureClass || "unknown";
|
|
53
|
+
return {
|
|
54
|
+
ok: false,
|
|
55
|
+
error: "profile_ineligible",
|
|
56
|
+
output:
|
|
57
|
+
`--profile is for content/contract failures; ${label} is a provider/infra failure — ` +
|
|
58
|
+
"use agents.quotaFallbackProfile or retry without --profile\n",
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
return { ok: true, profileOverride: requested, escalation: "manual", apply: true };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const policy = agents.escalatePolicy;
|
|
65
|
+
const target = trimmedString(policy?.toProfile);
|
|
66
|
+
if (
|
|
67
|
+
noEscalate ||
|
|
68
|
+
!eligible ||
|
|
69
|
+
policy?.enabled !== true ||
|
|
70
|
+
target === "" ||
|
|
71
|
+
!Object.hasOwn(profiles, target) ||
|
|
72
|
+
currentOverride === target
|
|
73
|
+
) {
|
|
74
|
+
return { ok: true, profileOverride: currentOverride, escalation: null, apply: false };
|
|
75
|
+
}
|
|
76
|
+
return { ok: true, profileOverride: target, escalation: "auto", apply: true };
|
|
77
|
+
}
|