pi-spine 2.27.1 → 2.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/bin/spine-batch.mjs +46 -4
  2. package/bin/spine-tasks.mjs +1 -0
  3. package/bin/spine-worker-runner.mjs +16 -3
  4. package/package.json +1 -1
  5. package/skills/create-spine-tasks/references/prompt-template.md +5 -0
  6. package/skills/spine-release-operator/SKILL.md +14 -2
  7. package/src/batch/contract-task-start.mjs +23 -1
  8. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  9. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  10. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  11. package/src/batch/engine-lanes/review-code.mjs +20 -0
  12. package/src/batch/engine-lanes/review-final.mjs +10 -2
  13. package/src/batch/engine-lanes/review-poll.mjs +33 -0
  14. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  15. package/src/batch/engine-lanes.mjs +18 -17
  16. package/src/batch/journal.mjs +5 -3
  17. package/src/batch/metrics-rollup.mjs +98 -4
  18. package/src/batch/metrics.mjs +134 -9
  19. package/src/batch/provider-quota.mjs +155 -6
  20. package/src/batch/quota-fallback.mjs +87 -6
  21. package/src/batch/resume-lane-reviews.mjs +11 -10
  22. package/src/batch/retry-profile.mjs +77 -0
  23. package/src/batch/retry.mjs +32 -1
  24. package/src/batch/review-step-run.mjs +4 -0
  25. package/src/batch/review-step.mjs +1 -0
  26. package/src/batch/worker-heartbeat.mjs +10 -2
  27. package/src/batch/worker-host.mjs +1 -1
  28. package/src/batch/worker-prompt.mjs +4 -5
  29. package/src/cli/deps.mjs +3 -2
  30. package/src/config/agent-model-resolve.mjs +144 -8
  31. package/src/config/model-family.mjs +60 -0
  32. package/src/config/preflight/discovery.mjs +1 -0
  33. package/src/config/settings-fields.mjs +6 -0
  34. package/src/config/spine-config-schema.mjs +49 -0
  35. package/src/doctor/agent-model-inherit.mjs +78 -1
  36. package/src/doctor/run-doctor-checks.mjs +4 -1
  37. package/src/metrics/quota-cli.mjs +16 -0
  38. package/src/metrics/quota-probes.mjs +228 -31
  39. package/src/metrics/quota-snapshot.mjs +21 -2
  40. package/src/planner/graph.mjs +7 -5
  41. package/src/planner/pending.mjs +2 -2
  42. package/src/planner/scope.mjs +3 -3
  43. package/src/tasks/packet/parse-prompt.mjs +47 -0
  44. package/src/tasks/packet/validate-prompt.mjs +156 -1
  45. package/templates/agents/reviewer.md +3 -1
  46. package/templates/agents/worker.md +15 -19
@@ -6,6 +6,7 @@
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { execFileSync } from "node:child_process";
9
+ import { resolveReviewerModelPin, resolveReviewerThinkingPin } from "../config/agent-model-resolve.mjs";
9
10
  import { METRICS_DEFAULTS } from "../config/defaults.mjs";
10
11
  import { redactSecretsDeep } from "../util/secret-redact.mjs";
11
12
  import { readReviewLevel } from "./review.mjs";
@@ -13,6 +14,7 @@ import { readReviewLevel } from "./review.mjs";
13
14
  // Metrics additionally redacts prompt text (worker prompts may embed
14
15
  // secrets) while preserving usage counters for cost rollup.
15
16
  const METRICS_REDACT_KEY_PATTERN = /key|token|secret|password|prompt/i;
17
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
16
18
  const USAGE_KEYS = new Set(["tokensIn", "tokensOut", "estimatedUsd"]);
17
19
 
18
20
  /**
@@ -141,18 +143,16 @@ export function buildTaskMetricRecord({ batchId, task, config = {}, taskFolder,
141
143
  : typeof worker.model === "string"
142
144
  ? worker.model
143
145
  : "inherit",
144
- thinking:
145
- worker.thinking === "off" ||
146
- worker.thinking === "low" ||
147
- worker.thinking === "medium" ||
148
- worker.thinking === "high"
149
- ? worker.thinking
150
- : "high",
146
+ // SP-835 (#340): prefer the per-attempt pin (`**Thinking:**` / profile) over batch-start config.
147
+ thinking: [task.workerThinking, worker.thinking].find((level) => THINKING_LEVELS.includes(level)) ?? "high",
151
148
  startedAt: new Date(startedMs).toISOString(),
152
149
  endedAt: new Date(endedMs).toISOString(),
153
150
  outcome: resolveTaskMetricOutcome(task),
154
151
  };
155
152
 
153
+ if (typeof task.workerProfile === "string" && task.workerProfile !== "") {
154
+ record.profile = task.workerProfile;
155
+ }
156
156
  if (Number.isFinite(resolvedLaneNumber) && resolvedLaneNumber > 0) {
157
157
  record.laneNumber = resolvedLaneNumber;
158
158
  }
@@ -216,6 +216,126 @@ export function recordTaskTerminalMetric({
216
216
  return appendTaskMetric(projectRoot, record, config);
217
217
  }
218
218
 
219
+ /** Reviewer row outcomes: a recorded verdict, or why no verdict was produced. */
220
+ export const REVIEW_METRIC_OUTCOMES = Object.freeze([
221
+ "verdict",
222
+ "spawn_failed",
223
+ "timeout",
224
+ "provider_error",
225
+ "blocked",
226
+ ]);
227
+
228
+ /**
229
+ * Effective reviewer pins for a review type on the config the review ran with
230
+ * (`"inherit"` when the pin resolves to null).
231
+ *
232
+ * @param {object} config
233
+ * @param {"plan"|"code"|"final"} reviewType
234
+ * @returns {{ model: string, thinking: string }}
235
+ */
236
+ export function resolveReviewMetricPins(config, reviewType) {
237
+ return {
238
+ model: resolveReviewerModelPin(config, reviewType) ?? "inherit",
239
+ thinking: resolveReviewerThinkingPin(config, reviewType) ?? "inherit",
240
+ };
241
+ }
242
+
243
+ /**
244
+ * One `recordType: "review"` row per reviewer verdict or reviewer failure (SP-837 / #325).
245
+ *
246
+ * @param {object} params
247
+ * @param {string} params.batchId
248
+ * @param {string} params.taskId
249
+ * @param {number} [params.laneNumber]
250
+ * @param {"plan"|"code"|"final"} params.reviewType
251
+ * @param {number} [params.stepNumber] Plan/code review step (code/plan reviews are per task today).
252
+ * @param {string} [params.model]
253
+ * @param {string} [params.thinking]
254
+ * @param {string} [params.profile]
255
+ * @param {string} [params.verdict] Recorded verdict (APPROVE/PASS/REVISE/REPLAN) for `outcome: "verdict"`.
256
+ * @param {number} [params.attempt] 1-based review attempt index.
257
+ * @param {number} [params.durationMs]
258
+ * @param {"verdict"|"spawn_failed"|"timeout"|"provider_error"|"blocked"} [params.outcome]
259
+ * @param {string} [params.failureReason]
260
+ * @param {number} [params.endedAtMs]
261
+ */
262
+ export function buildReviewMetricRecord({
263
+ batchId,
264
+ taskId,
265
+ laneNumber,
266
+ reviewType,
267
+ stepNumber,
268
+ model,
269
+ thinking,
270
+ profile,
271
+ verdict,
272
+ attempt,
273
+ durationMs,
274
+ outcome = "verdict",
275
+ failureReason,
276
+ endedAtMs = Date.now(),
277
+ }) {
278
+ /** @type {Record<string, unknown>} */
279
+ const record = {
280
+ recordType: "review",
281
+ schemaVersion: 1,
282
+ batchId,
283
+ taskId,
284
+ agentRole: "reviewer",
285
+ role: "reviewer",
286
+ reviewType,
287
+ model: typeof model === "string" && model !== "" ? model : "inherit",
288
+ thinking: THINKING_LEVELS.includes(/** @type {string} */ (thinking)) ? thinking : "inherit",
289
+ endedAt: new Date(endedAtMs).toISOString(),
290
+ outcome: REVIEW_METRIC_OUTCOMES.includes(outcome) ? outcome : "verdict",
291
+ };
292
+
293
+ if (Number.isFinite(laneNumber) && /** @type {number} */ (laneNumber) > 0) record.laneNumber = laneNumber;
294
+ if (Number.isFinite(stepNumber)) record.stepNumber = stepNumber;
295
+ if (typeof profile === "string" && profile !== "") record.profile = profile;
296
+ if (typeof verdict === "string" && verdict !== "") record.verdict = verdict;
297
+ if (Number.isFinite(attempt)) record.attempt = attempt;
298
+ if (Number.isFinite(durationMs)) record.durationMs = Math.max(0, /** @type {number} */ (durationMs));
299
+ if (typeof failureReason === "string" && failureReason !== "") record.failureReason = failureReason;
300
+
301
+ return sanitizeMetricRecord(record);
302
+ }
303
+
304
+ /**
305
+ * @param {string} projectRoot
306
+ * @param {object} record
307
+ * @param {object} [config]
308
+ */
309
+ export function appendReviewMetric(projectRoot, record, config = {}) {
310
+ return appendTaskMetric(projectRoot, record, config);
311
+ }
312
+
313
+ /**
314
+ * Build and append a reviewer row, resolving model/thinking from the pins on
315
+ * the config the review ran with. No-op when `metrics.enabled` is false.
316
+ *
317
+ * @param {object} params
318
+ * @param {string} params.projectRoot
319
+ * @param {object} [params.config] Per-task review config (effective reviewer pins).
320
+ * @param {"plan"|"code"|"final"} params.reviewType
321
+ * @param {string} params.batchId
322
+ * @param {string} params.taskId
323
+ * @param {number} [params.laneNumber]
324
+ * @param {number} [params.stepNumber]
325
+ * @param {string} [params.model] Overrides the config-resolved model.
326
+ * @param {string} [params.verdict]
327
+ * @param {number} [params.attempt]
328
+ * @param {number} [params.durationMs]
329
+ * @param {"verdict"|"spawn_failed"|"timeout"|"provider_error"|"blocked"} [params.outcome]
330
+ * @param {string} [params.failureReason]
331
+ */
332
+ export function recordReviewMetric({ projectRoot, config = {}, model, ...rest }) {
333
+ if (!isMetricsEnabled(config)) return null;
334
+ const pins = resolveReviewMetricPins(config, rest.reviewType);
335
+ const record = buildReviewMetricRecord({ ...rest, model: model ?? pins.model, thinking: pins.thinking });
336
+ return appendReviewMetric(projectRoot, record, config);
337
+ }
338
+
219
339
  /**
220
340
  * @param {object} params
221
341
  * @param {string} params.batchId
@@ -322,10 +442,15 @@ export function formatMetricsTable(lines) {
322
442
 
323
443
  const header = ["Type", "Batch", "Task", "Outcome", "Diagnosis", "Ended"];
324
444
  const rows = lines.map((line) => [
325
- line.recordType ?? "—",
445
+ line.recordType === "review" && typeof line.reviewType === "string"
446
+ ? `review:${line.reviewType}`
447
+ : (line.recordType ?? "—"),
326
448
  line.batchId ?? "—",
327
449
  line.taskId ?? "—",
328
- line.outcome ?? line.diagnosis ?? "—",
450
+ (line.recordType === "review" && line.outcome === "verdict" ? line.verdict : null) ??
451
+ line.outcome ??
452
+ line.diagnosis ??
453
+ "—",
329
454
  line.diagnosis ?? "—",
330
455
  line.endedAt ?? "—",
331
456
  ]);
@@ -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 Kimi `error.type` of the matched rule, when matched.
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
- * Collects every status-prefixed JSON payload in the output, in order of
87
- * appearance. Fragments that do not parse as JSON objects are ignored — they
88
- * are not provider payloads.
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
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 @@ export 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
- return candidates;
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, one hop per batch):
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: once the hop happened, no second hop is ever decided.
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: typeof classification.resetAtRaw === "string" ? classification.resetAtRaw : null,
372
+ resetAtRaw,
373
+ resetAt: parseQuotaResetAt(resetAtRaw, { at }),
293
374
  triggerTaskId: taskId,
294
- at: new Date(now).toISOString(),
375
+ at: at.toISOString(),
295
376
  retriedTaskIds: [],
296
377
  };
297
378
  }
@@ -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 {object} params
11
+ * @param {Record<string, any>} params
10
12
  */
11
13
  export async function runLaneReviewPhasesBeforeCommit(params) {
12
- const planReview = await runPlanReviewPhase(params);
13
- if (!planReview.ok) {
14
- return planReview;
15
- }
16
- const codeReview = await runCodeReviewPhase(params);
17
- if (!codeReview.ok) {
18
- return codeReview;
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
+ }