pi-spine 2.26.0 → 2.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-review-step.mjs +8 -1
  3. package/bin/spine-worker-runner.mjs +14 -1
  4. package/package.json +3 -3
  5. package/skills/spine-release-operator/SKILL.md +3 -0
  6. package/src/batch/batch-meta-reconstruct.mjs +3 -0
  7. package/src/batch/contract-exec.mjs +2 -2
  8. package/src/batch/contract-parse.mjs +2 -2
  9. package/src/batch/contract-prelanded.mjs +2 -2
  10. package/src/batch/diagnosis-handoff-packet.mjs +74 -0
  11. package/src/batch/diagnosis-pending-lane.mjs +34 -1
  12. package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
  13. package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
  14. package/src/batch/engine-lanes/review-code.mjs +1 -0
  15. package/src/batch/engine-lanes/review-final.mjs +83 -46
  16. package/src/batch/engine-lanes/review-plan.mjs +22 -2
  17. package/src/batch/engine-lanes/review-poll.mjs +47 -1
  18. package/src/batch/engine-lanes.mjs +6 -7
  19. package/src/batch/journal.mjs +15 -0
  20. package/src/batch/metrics.mjs +13 -1
  21. package/src/batch/provider-quota.mjs +220 -0
  22. package/src/batch/quota-fallback.mjs +319 -0
  23. package/src/batch/reconcile-diagnosis-context.mjs +22 -0
  24. package/src/batch/resume-multi-queue.mjs +25 -10
  25. package/src/batch/review-artifacts.mjs +93 -15
  26. package/src/batch/review-spawn-retry.mjs +106 -0
  27. package/src/batch/review-spawn.mjs +48 -2
  28. package/src/batch/review-step-run.mjs +96 -6
  29. package/src/batch/reviewer-output.mjs +162 -0
  30. package/src/batch/worker-host.mjs +49 -3
  31. package/src/config/cursor-rules/discover.mjs +2 -2
  32. package/src/config/cursor-rules/match-globs.mjs +6 -4
  33. package/src/config/env-overrides.mjs +41 -4
  34. package/src/config/settings-fields.mjs +6 -0
  35. package/src/config/spine-config-schema.mjs +24 -0
  36. package/src/doctor/quota-risk.mjs +45 -0
  37. package/src/planner/file-scope.mjs +6 -6
  38. package/src/tasks/packet/validate-contract.mjs +3 -3
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Reviewer output log persistence (SP-814 / #332).
3
+ *
4
+ * Every failed reviewer attempt leaves a bounded, redacted log next to the
5
+ * worker output logs under `.spine/runtime/<batchId>/lanes/lane-<n>/`. The
6
+ * helpers reuse the worker output conventions from `worker-output.mjs`
7
+ * (redaction, tail caps, atomic writes) without modifying that module, which
8
+ * sits at its line-count policy cap.
9
+ */
10
+
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import { writeTextAtomic } from "../fs/atomic-write.mjs";
14
+ import {
15
+ captureWorkerOutputTail,
16
+ redactWorkerOutput,
17
+ resolveWorkerOutputConfig,
18
+ } from "./worker-output.mjs";
19
+
20
+ /** Diagnostic output tail budget for `review.failed` payloads (SP-814 / #332). */
21
+ export const REVIEWER_FAILURE_OUTPUT_TAIL_MAX_BYTES = 2048;
22
+
23
+ /**
24
+ * Shape of the `spawnReviewerPi` result consumed by the log helpers.
25
+ *
26
+ * @typedef {object} ReviewerSpawnResult
27
+ * @property {boolean} [spawnFailed]
28
+ * @property {number} [exitCode]
29
+ * @property {number} [durationMs]
30
+ * @property {string} [stdoutTail]
31
+ * @property {string} [stderrTail]
32
+ */
33
+
34
+ /**
35
+ * Absolute path of the reviewer output log for one (task, reviewType) pair.
36
+ *
37
+ * @param {string} projectRoot
38
+ * @param {string} batchId
39
+ * @param {number} laneNumber
40
+ * @param {string} taskId
41
+ * @param {string} reviewType
42
+ */
43
+ export function reviewerOutputLogPath(projectRoot, batchId, laneNumber, taskId, reviewType) {
44
+ return path.join(
45
+ projectRoot,
46
+ ".spine",
47
+ "runtime",
48
+ batchId,
49
+ "lanes",
50
+ `lane-${laneNumber}`,
51
+ `reviewer-output-${taskId}-${reviewType}.log`,
52
+ );
53
+ }
54
+
55
+ /**
56
+ * Root-relative journal/log reference for the reviewer output log.
57
+ *
58
+ * @param {string} batchId
59
+ * @param {number} laneNumber
60
+ * @param {string} taskId
61
+ * @param {string} reviewType
62
+ */
63
+ export function reviewerOutputLogRef(batchId, laneNumber, taskId, reviewType) {
64
+ return path.join(
65
+ ".spine",
66
+ "runtime",
67
+ batchId,
68
+ "lanes",
69
+ `lane-${laneNumber}`,
70
+ `reviewer-output-${taskId}-${reviewType}.log`,
71
+ );
72
+ }
73
+
74
+ /**
75
+ * Combined stderr + stdout diagnostic tail (redacted, ≤ 2 KB) for failure
76
+ * payloads. Stderr leads because reviewer diagnostics conventionally land
77
+ * there; stdout follows so silent reviewer exits stay explainable.
78
+ *
79
+ * @param {ReviewerSpawnResult} spawnResult Result from `spawnReviewerPi`.
80
+ * @param {object} [config]
81
+ */
82
+ export function buildReviewerOutputTail(spawnResult, config = {}) {
83
+ const outputConfig = resolveWorkerOutputConfig(config);
84
+ const stderrTail = redactWorkerOutput(spawnResult?.stderrTail ?? "", outputConfig).trim();
85
+ const stdoutTail = redactWorkerOutput(spawnResult?.stdoutTail ?? "", outputConfig).trim();
86
+
87
+ const parts = [];
88
+ if (stderrTail) parts.push(`--- stderr ---\n${stderrTail}`);
89
+ if (stdoutTail) parts.push(`--- stdout ---\n${stdoutTail}`);
90
+ const joined = parts.join("\n");
91
+ if (!joined) return "";
92
+
93
+ const tailConfig = { ...outputConfig, maxBytes: REVIEWER_FAILURE_OUTPUT_TAIL_MAX_BYTES };
94
+ return captureWorkerOutputTail(joined, tailConfig);
95
+ }
96
+
97
+ /**
98
+ * Append one redacted, tail-capped attempt section to the reviewer log for a
99
+ * (task, reviewType) pair. One file per pair: attempts append so a re-spawn
100
+ * never erases the previous attempt's diagnostics.
101
+ *
102
+ * @param {object} params
103
+ * @param {string} params.projectRoot
104
+ * @param {string} params.batchId
105
+ * @param {number} params.laneNumber
106
+ * @param {string} params.taskId
107
+ * @param {string} params.reviewType
108
+ * @param {number|null} [params.stepNumber]
109
+ * @param {number} [params.attempt]
110
+ * @param {ReviewerSpawnResult} [params.spawnResult] Result from `spawnReviewerPi`.
111
+ * @param {object} [params.config]
112
+ * @returns {{ logPath: string, logRef: string }|null}
113
+ */
114
+ export function persistReviewerOutputLog({
115
+ projectRoot,
116
+ batchId,
117
+ laneNumber,
118
+ taskId,
119
+ reviewType,
120
+ stepNumber = null,
121
+ attempt = 1,
122
+ spawnResult = {},
123
+ config = {},
124
+ }) {
125
+ const outputConfig = resolveWorkerOutputConfig(config);
126
+ const stderrTail = captureWorkerOutputTail(
127
+ redactWorkerOutput(spawnResult.stderrTail ?? "", outputConfig),
128
+ outputConfig,
129
+ );
130
+ const stdoutTail = captureWorkerOutputTail(
131
+ redactWorkerOutput(spawnResult.stdoutTail ?? "", outputConfig),
132
+ outputConfig,
133
+ );
134
+
135
+ const header = [
136
+ `# reviewer attempt ${attempt} — ${new Date().toISOString()}`,
137
+ `taskId=${taskId} reviewType=${reviewType} step=${stepNumber ?? "?"}`,
138
+ `spawnFailed=${spawnResult.spawnFailed === true} exitCode=${
139
+ spawnResult.exitCode ?? "null"
140
+ } durationMs=${spawnResult.durationMs ?? "null"}`,
141
+ ].join("\n");
142
+ const section = [
143
+ header,
144
+ "--- stderr ---",
145
+ stderrTail.trim() || "(empty)",
146
+ "--- stdout ---",
147
+ stdoutTail.trim() || "(empty)",
148
+ ].join("\n");
149
+
150
+ const logPath = reviewerOutputLogPath(projectRoot, batchId, laneNumber, taskId, reviewType);
151
+ let previous = "";
152
+ if (fs.existsSync(logPath)) {
153
+ previous = fs.readFileSync(logPath, "utf-8").trim();
154
+ }
155
+ const content = previous ? `${previous}\n\n${section}\n` : `${section}\n`;
156
+ writeTextAtomic(logPath, content);
157
+
158
+ return {
159
+ logPath,
160
+ logRef: reviewerOutputLogRef(batchId, laneNumber, taskId, reviewType),
161
+ };
162
+ }
@@ -12,6 +12,8 @@ import {
12
12
  } from "./task-stall-budget.mjs";
13
13
  import { parseContract, parsePrompt } from "../tasks/packet/parse-prompt.mjs";
14
14
  import { appendJournalEvent } from "./journal.mjs";
15
+ import { classifyProviderQuotaError } from "./provider-quota.mjs";
16
+ import { resolveWorkerQuotaFallbackContext } from "./engine-lanes/quota-fallback-state.mjs";
15
17
  import { assertReviewToolAvailable } from "./review.mjs";
16
18
  import {
17
19
  finalizeWorkerOutput,
@@ -49,6 +51,36 @@ const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
49
51
  */
50
52
  const WORKER_TIMEOUT_EXIT_CODE = 124;
51
53
 
54
+ /**
55
+ * Reclassify a plain `failed` worker exit as a provider quota/overload exit
56
+ * when forwarded output matches a known provider payload, and journal
57
+ * `worker.quota_exhausted` for quota-exhausted exits (#329, SP-806). Aborted,
58
+ * stall, launch and review failures keep their meaning; overload is not
59
+ * journaled. Callers must run this after finalizeWorkerOutput so output
60
+ * capture still sees the original `failed` (shouldCaptureWorkerOutput matches
61
+ * the literal) while consumers receive the provider-quota exit reason.
62
+ *
63
+ * @param {{ classification: string, rawOutput: string, workerModel?: string, projectRoot?: string, batchId?: string, taskId?: string, laneNumber?: number, laneCorrelationId?: string }} params
64
+ * @returns {{ classification: string, providerQuota: import("./provider-quota.mjs").ProviderQuotaError | null }}
65
+ */
66
+ function applyProviderQuotaClassification({ classification, rawOutput, workerModel, projectRoot, batchId, taskId, laneNumber, laneCorrelationId }) {
67
+ if (classification !== "failed") return { classification, providerQuota: null };
68
+ // SP-808 (#329): the caller resolves the effective model (fallback profile
69
+ // when a hop is active) so classification and the journal tell the truth.
70
+ const model = typeof workerModel === "string" ? workerModel : undefined;
71
+ const providerQuota = classifyProviderQuotaError(rawOutput, model);
72
+ if (!providerQuota) return { classification, providerQuota: null };
73
+ if (providerQuota.kind === "quota_exhausted" && projectRoot && batchId) {
74
+ appendJournalEvent(projectRoot, batchId, "worker.quota_exhausted", {
75
+ taskId, laneNumber, correlationId: laneCorrelationId, poolId: providerQuota.poolId,
76
+ providerCode: providerQuota.providerCode, httpStatus: providerQuota.httpStatus,
77
+ resetAtRaw: providerQuota.resetAtRaw, ...(model ? { model } : {}),
78
+ });
79
+ }
80
+ const reclassified = providerQuota.kind === "quota_exhausted" ? "provider_quota_exhausted" : "provider_overloaded";
81
+ return { classification: reclassified, providerQuota };
82
+ }
83
+
52
84
  /**
53
85
  * Force-terminate lane worker process trees tracked in batch state.
54
86
  * Reaps nested `pi` grandchildren, not only the tracked runner PID (SP-609 / #194).
@@ -99,6 +131,7 @@ function sleep(ms) {
99
131
  * @param {string} [params.taskId]
100
132
  * @param {string} [params.laneCorrelationId]
101
133
  * @param {object} [params.config]
134
+ * @param {string} [params.workerModel] Effective worker model (SP-808).
102
135
  * @param {number} [params.stallDeadline]
103
136
  * @param {object} [params.signals]
104
137
  */
@@ -114,6 +147,7 @@ function buildWorkerFailureResult({
114
147
  taskId,
115
148
  laneCorrelationId,
116
149
  config,
150
+ workerModel,
117
151
  stallDeadline,
118
152
  signals,
119
153
  }) {
@@ -131,6 +165,8 @@ function buildWorkerFailureResult({
131
165
  signals,
132
166
  config,
133
167
  });
168
+ // SP-806 (#329): post-finalize reclassification (see helper doc).
169
+ const quotaOutcome = applyProviderQuotaClassification({ classification, rawOutput, workerModel, projectRoot, batchId, taskId, laneNumber, laneCorrelationId });
134
170
  return {
135
171
  ok: false,
136
172
  exitCode,
@@ -138,8 +174,9 @@ function buildWorkerFailureResult({
138
174
  output: finalized.output,
139
175
  workerOutputLogPath: finalized.logPath,
140
176
  workerOutputLogRef: finalized.logRef,
141
- classification,
177
+ classification: quotaOutcome.classification,
142
178
  doneFound,
179
+ ...(quotaOutcome.providerQuota ? { providerQuota: quotaOutcome.providerQuota } : {}),
143
180
  };
144
181
  }
145
182
 
@@ -183,6 +220,9 @@ export async function runWorker({
183
220
  return { ok: true, exitCode: 0, mode: "already-done" };
184
221
  }
185
222
 
223
+ // SP-808 (#329): sticky quota fallback — read-only load; caller extraEnv wins.
224
+ const quotaCtx = resolveWorkerQuotaFallbackContext({ projectRoot, batchId, config, extraEnv });
225
+
186
226
  const stubExplicit =
187
227
  process.env.SPINE_WORKER_STUB === "1" || process.env.SPINE_WORKER_STUB === "true";
188
228
  // #299 (SP-801): the stub is opt-in only. The old implicit fallback
@@ -284,7 +324,7 @@ export async function runWorker({
284
324
  fileScopePaths,
285
325
  config,
286
326
  workerBackendDeps,
287
- extraEnv,
327
+ extraEnv: quotaCtx.extraEnv,
288
328
  });
289
329
  const workerChild = /** @type {WorkerChildHandle} */ (child);
290
330
  let childPastPreflight = isExecute ? true : !useLaunchScript;
@@ -337,6 +377,7 @@ export async function runWorker({
337
377
  taskId,
338
378
  laneCorrelationId,
339
379
  config,
380
+ workerModel: quotaCtx.workerModel,
340
381
  }),
341
382
  });
342
383
 
@@ -389,6 +430,7 @@ export async function runWorker({
389
430
  taskId,
390
431
  laneCorrelationId,
391
432
  config,
433
+ workerModel: quotaCtx.workerModel,
392
434
  });
393
435
  }
394
436
  // SP-738 (#273): the runner exits 124 when the `pi` spawn hit its wall-clock
@@ -440,6 +482,9 @@ export async function runWorker({
440
482
  config,
441
483
  });
442
484
 
485
+ // SP-806 (#329): main post-spawn failure path — post-finalize
486
+ // reclassification (see helper doc); only plain `failed` exits can match.
487
+ const quotaOutcome = applyProviderQuotaClassification({ classification, rawOutput: output, workerModel: quotaCtx.workerModel, projectRoot, batchId, taskId, laneNumber, laneCorrelationId });
443
488
  return {
444
489
  ok,
445
490
  exitCode,
@@ -447,7 +492,8 @@ export async function runWorker({
447
492
  output: finalized.output,
448
493
  workerOutputLogPath: finalized.logPath,
449
494
  workerOutputLogRef: finalized.logRef,
450
- classification,
495
+ classification: quotaOutcome.classification,
451
496
  doneFound,
497
+ ...(quotaOutcome.providerQuota ? { providerQuota: quotaOutcome.providerQuota } : {}),
452
498
  };
453
499
  }
@@ -7,7 +7,7 @@ import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { execFileSync } from "node:child_process";
9
9
 
10
- import micromatch from "micromatch";
10
+ import picomatch from "picomatch";
11
11
 
12
12
  import { writeJsonAtomic } from "../../fs/atomic-write.mjs";
13
13
 
@@ -97,7 +97,7 @@ export function getCursorRuleExclusionReason(discovery, relPath) {
97
97
  }
98
98
 
99
99
  for (const target of matchTargets) {
100
- if (micromatch.isMatch(target, discovery.excludePatterns)) {
100
+ if (picomatch(discovery.excludePatterns)(target)) {
101
101
  return "excludePattern";
102
102
  }
103
103
  }
@@ -1,9 +1,9 @@
1
1
  // @ts-nocheck
2
2
  /**
3
- * Micromatch helpers for PROMPT File Scope vs rule globs (SP-091).
3
+ * Glob helpers for PROMPT File Scope vs rule globs (SP-091).
4
4
  */
5
5
 
6
- import micromatch from "micromatch";
6
+ import picomatch from "picomatch";
7
7
 
8
8
  /** Synthetic extensions used when expanding directory or wildcard scope entries. */
9
9
  export const SYNTHETIC_PROBE_EXTENSIONS = Object.freeze([
@@ -120,11 +120,13 @@ export function ruleGlobsMatchFileScope(globs, fileScope) {
120
120
  return true;
121
121
  }
122
122
 
123
- if (scopeEntries.some((entry) => micromatch.isMatch(entry, glob))) {
123
+ const isMatch = picomatch(glob);
124
+
125
+ if (scopeEntries.some((entry) => isMatch(entry))) {
124
126
  return true;
125
127
  }
126
128
 
127
- if (probes.some((probe) => micromatch.isMatch(probe, glob))) {
129
+ if (probes.some((probe) => isMatch(probe))) {
128
130
  return true;
129
131
  }
130
132
  }
@@ -14,13 +14,18 @@ import { validateSettingValue } from "./settings-fields.mjs";
14
14
  * @typedef {object} EnvOverrideSpec
15
15
  * @property {string} envVar
16
16
  * @property {string} configPath Dotted path (e.g. paths.tasksRoot)
17
- * @property {"tasksRoot" | "maxParallel"} kind
17
+ * @property {"tasksRoot" | "maxParallel" | "agentProfile"} kind
18
18
  */
19
19
 
20
20
  /** @type {readonly EnvOverrideSpec[]} */
21
21
  export const ENV_OVERRIDE_SPECS = Object.freeze([
22
22
  { envVar: "SPINE_TASKS_ROOT", configPath: "paths.tasksRoot", kind: "tasksRoot" },
23
23
  { envVar: "SPINE_MAX_LANES", configPath: "lanes.maxParallel", kind: "maxParallel" },
24
+ {
25
+ envVar: "SPINE_AGENT_PROFILE_OVERRIDE",
26
+ configPath: "agents.activeProfile",
27
+ kind: "agentProfile",
28
+ },
24
29
  ]);
25
30
 
26
31
  /**
@@ -120,6 +125,7 @@ export function resolveTasksRootPath(projectRoot, config) {
120
125
  * config: object,
121
126
  * sources: Record<string, ConfigValueSource>,
122
127
  * envVars: Record<string, string>,
128
+ * warnings: Record<string, string>,
123
129
  * } | { ok: false, error: { code: string, message: string, suggestedCommand?: string } }}
124
130
  */
125
131
  export function applyEnvOverrides(config, projectRoot, env = process.env) {
@@ -127,6 +133,9 @@ export function applyEnvOverrides(config, projectRoot, env = process.env) {
127
133
  const sources = {};
128
134
  /** @type {Record<string, string>} */
129
135
  const envVars = {};
136
+ /** Reasons an env var was ignored (e.g. unknown agent profile), keyed by config path. */
137
+ /** @type {Record<string, string>} */
138
+ const warnings = {};
130
139
 
131
140
  for (const spec of ENV_OVERRIDE_SPECS) {
132
141
  sources[spec.configPath] = "file";
@@ -158,6 +167,28 @@ export function applyEnvOverrides(config, projectRoot, env = process.env) {
158
167
  continue;
159
168
  }
160
169
 
170
+ if (spec.kind === "agentProfile") {
171
+ // Schema validation ran on the file config before env overrides, so the override must
172
+ // check profile membership itself. Unknown names are ignored (soft-fail) so a stale
173
+ // export from a previous run cannot break config load; the reason is recorded for display.
174
+ const requested = String(raw).trim();
175
+ const profiles = merged?.agents?.profiles;
176
+ if (
177
+ profiles == null ||
178
+ typeof profiles !== "object" ||
179
+ Array.isArray(profiles) ||
180
+ !Object.prototype.hasOwnProperty.call(profiles, requested)
181
+ ) {
182
+ warnings[spec.configPath] =
183
+ `${spec.envVar} ignored: unknown profile "${requested}"`;
184
+ continue;
185
+ }
186
+ setValueAtPath(merged, spec.configPath, requested);
187
+ sources[spec.configPath] = "env";
188
+ envVars[spec.configPath] = spec.envVar;
189
+ continue;
190
+ }
191
+
161
192
  if (spec.kind === "maxParallel") {
162
193
  const validated = validateSettingValue("lanes.maxParallel", raw);
163
194
  if (!validated.ok) {
@@ -176,7 +207,7 @@ export function applyEnvOverrides(config, projectRoot, env = process.env) {
176
207
  }
177
208
  }
178
209
 
179
- return { ok: true, config: merged, sources, envVars };
210
+ return { ok: true, config: merged, sources, envVars, warnings };
180
211
  }
181
212
 
182
213
  /**
@@ -196,13 +227,19 @@ export function listEnvAwareDisplayFields() {
196
227
  * @param {Record<string, string> | undefined} envVars
197
228
  * @param {string} configPath
198
229
  * @param {unknown} value
230
+ * @param {Record<string, string> | undefined} [warnings] Reasons an env override was ignored,
231
+ * keyed by config path (e.g. an unknown SPINE_AGENT_PROFILE_OVERRIDE profile).
199
232
  * @returns {string}
200
233
  */
201
- export function formatConfigSourceDetail(sources, envVars, configPath, value) {
234
+ export function formatConfigSourceDetail(sources, envVars, configPath, value, warnings) {
202
235
  const display = value === undefined || value === null ? "(not set)" : String(value);
203
236
  const source = sources?.[configPath] ?? "file";
237
+ const warning = warnings?.[configPath];
204
238
  if (source === "env" && envVars?.[configPath]) {
205
- return `${display} (source: env, ${envVars[configPath]})`;
239
+ return `${display} (source: env, ${envVars[configPath]}${warning ? `, ${warning}` : ""})`;
240
+ }
241
+ if (warning) {
242
+ return `${display} (source: ${source}, ${warning})`;
206
243
  }
207
244
  return `${display} (source: ${source})`;
208
245
  }
@@ -151,6 +151,12 @@ export const SETTINGS_FIELDS = Object.freeze([
151
151
  type: "string",
152
152
  optional: true,
153
153
  },
154
+ {
155
+ path: "agents.quotaFallbackProfile",
156
+ label: "Quota fallback agent model profile",
157
+ type: "string",
158
+ optional: true,
159
+ },
154
160
  {
155
161
  path: "dashboard.port",
156
162
  label: "Dashboard port",
@@ -296,6 +296,30 @@ export function validateAgentProfilesConfig(config) {
296
296
  }
297
297
  }
298
298
 
299
+ // SP-805 / #329: profile used when quota fallback kicks in; same membership rule as activeProfile.
300
+ const quotaFallbackProfile = agents.quotaFallbackProfile;
301
+ if (quotaFallbackProfile != null) {
302
+ if (typeof quotaFallbackProfile !== "string") {
303
+ return {
304
+ code: "CONFIG_AGENT_PROFILE_INVALID",
305
+ message: "agents.quotaFallbackProfile must be a string when set",
306
+ suggestedCommand: "spine settings set agents.quotaFallbackProfile default",
307
+ };
308
+ }
309
+ const fallbackTarget = quotaFallbackProfile.trim();
310
+ // An empty string unsets the fallback profile; otherwise it must name a real profile.
311
+ if (
312
+ fallbackTarget !== "" &&
313
+ (!isPlainObject(profiles) || !Object.prototype.hasOwnProperty.call(profiles, fallbackTarget))
314
+ ) {
315
+ return {
316
+ code: "CONFIG_AGENT_PROFILE_INVALID",
317
+ message: `agents.quotaFallbackProfile "${fallbackTarget}" does not match a defined agents.profiles entry`,
318
+ suggestedCommand: "spine settings set agents.quotaFallbackProfile default",
319
+ };
320
+ }
321
+ }
322
+
299
323
  const escalatePolicy = agents.escalatePolicy;
300
324
  if (escalatePolicy != null) {
301
325
  if (!isPlainObject(escalatePolicy)) {
@@ -71,6 +71,17 @@ export function collectQuotaPinTargets(config = {}) {
71
71
  });
72
72
  }
73
73
 
74
+ // SP-810: the quota fallback profile worker is a fallback-path pin — when
75
+ // the engine falls back to it, its pool must have headroom too.
76
+ const fallbackProfile =
77
+ typeof agents.quotaFallbackProfile === "string" ? agents.quotaFallbackProfile.trim() : "";
78
+ if (fallbackProfile && agents.profiles?.[fallbackProfile]) {
79
+ candidates.push({
80
+ model: agents.profiles[fallbackProfile]?.worker?.model,
81
+ source: `agents.profiles.${fallbackProfile}.worker.model (quota fallback)`,
82
+ });
83
+ }
84
+
74
85
  /** @type {QuotaPinTarget[]} */
75
86
  const targets = [];
76
87
  const seen = new Set();
@@ -88,6 +99,37 @@ export function collectQuotaPinTargets(config = {}) {
88
99
  return targets;
89
100
  }
90
101
 
102
+ /**
103
+ * SP-810: detect a quota fallback profile pinned to the same provider pool
104
+ * as the active worker. Falling back within one exhausted pool can never
105
+ * help, so surface it as an advisory. Advisory only — never fails preflight.
106
+ *
107
+ * @param {object} [config]
108
+ * @returns {string | null}
109
+ */
110
+ export function detectSamePoolQuotaFallback(config = {}) {
111
+ const agents = config?.agents;
112
+ if (!agents || typeof agents !== "object") return null;
113
+
114
+ const fallbackProfile =
115
+ typeof agents.quotaFallbackProfile === "string" ? agents.quotaFallbackProfile.trim() : "";
116
+ if (!fallbackProfile || !agents.profiles?.[fallbackProfile]) return null;
117
+
118
+ const fallbackModel = agents.profiles[fallbackProfile]?.worker?.model;
119
+ // The active worker is the active profile's worker pin when set, else the
120
+ // base worker pin — mirroring how the engine resolves the worker model.
121
+ const activeProfile = typeof agents.activeProfile === "string" ? agents.activeProfile.trim() : "";
122
+ const activeModel =
123
+ (activeProfile && agents.profiles?.[activeProfile]?.worker?.model) || agents.worker?.model;
124
+ if (typeof fallbackModel !== "string" || typeof activeModel !== "string") return null;
125
+
126
+ const fallbackPool = resolvePoolId(fallbackModel.trim());
127
+ const activePool = resolvePoolId(activeModel.trim());
128
+ if (fallbackPool === "unknown" || fallbackPool !== activePool) return null;
129
+
130
+ return `agents.quotaFallbackProfile ${fallbackProfile} uses the same quota pool (${fallbackPool}) as the active worker — fallback can never help`;
131
+ }
132
+
91
133
  /**
92
134
  * Evaluate headroom evidence for one pool from an optional probe result.
93
135
  * Degrades closed: absent probes/auth mean "no headroom evidence", never an
@@ -207,6 +249,9 @@ export function buildQuotaRiskDoctorCheck({ config = {}, probeResults, metricsLi
207
249
  const signals = detectQuotaRiskSignals(metricsLines, { now });
208
250
  risks.push(...signals);
209
251
 
252
+ const samePoolAdvisory = detectSamePoolQuotaFallback(config);
253
+ if (samePoolAdvisory) risks.push(samePoolAdvisory);
254
+
210
255
  if (risks.length === 0) {
211
256
  const detail =
212
257
  targets.length === 0
@@ -6,7 +6,7 @@
6
6
  * parallel lane assignment would risk merge conflicts.
7
7
  */
8
8
 
9
- import micromatch from 'micromatch';
9
+ import picomatch from 'picomatch';
10
10
 
11
11
  /** Synthetic basename used when expanding globs into concrete probe paths. */
12
12
  const PROBE_BASENAME = '__probe__';
@@ -36,7 +36,7 @@ const SYNTHETIC_PROBE_EXTENSIONS = Object.freeze([
36
36
  const MAX_BRACE_EXPANSIONS = 32;
37
37
 
38
38
  /**
39
- * Expand `{a,b}` brace groups into concrete entry variants (micromatch-style).
39
+ * Expand `{a,b}` brace groups into concrete entry variants (picomatch-style).
40
40
  * Nested groups are expanded recursively; expansion stops at
41
41
  * MAX_BRACE_EXPANSIONS so probe generation stays bounded.
42
42
  *
@@ -264,18 +264,18 @@ export function fileScopePatternsOverlap(leftPattern, rightPattern) {
264
264
  const matchOpts = { dot: true };
265
265
 
266
266
  for (const probe of leftProbes) {
267
- if (micromatch.isMatch(probe, rightEntry, matchOpts)) return true;
267
+ if (picomatch(rightEntry, matchOpts)(probe)) return true;
268
268
  }
269
269
 
270
270
  for (const probe of rightProbes) {
271
- if (micromatch.isMatch(probe, leftEntry, matchOpts)) return true;
271
+ if (picomatch(leftEntry, matchOpts)(probe)) return true;
272
272
  }
273
273
 
274
- if (!patternHasGlobMeta(leftEntry) && micromatch.isMatch(leftEntry, rightEntry, matchOpts)) {
274
+ if (!patternHasGlobMeta(leftEntry) && picomatch(rightEntry, matchOpts)(leftEntry)) {
275
275
  return true;
276
276
  }
277
277
 
278
- if (!patternHasGlobMeta(rightEntry) && micromatch.isMatch(rightEntry, leftEntry, matchOpts)) {
278
+ if (!patternHasGlobMeta(rightEntry) && picomatch(leftEntry, matchOpts)(rightEntry)) {
279
279
  return true;
280
280
  }
281
281
 
@@ -3,7 +3,7 @@
3
3
  * Validate-time checks for PROMPT.md `## Contract` tables (handoff §4.4).
4
4
  */
5
5
 
6
- import micromatch from "micromatch";
6
+ import picomatch from "picomatch";
7
7
 
8
8
  import { matchesContractPattern } from "../../batch/contract-verify.mjs";
9
9
  import {
@@ -235,8 +235,8 @@ function isValidContractGlob(pattern) {
235
235
  }
236
236
 
237
237
  try {
238
- micromatch.isMatch(GLOB_PROBE, trimmed);
239
- micromatch.isMatch(trimmed, GLOB_PROBE);
238
+ picomatch(trimmed)(GLOB_PROBE);
239
+ picomatch(GLOB_PROBE)(trimmed);
240
240
  return true;
241
241
  } catch {
242
242
  return false;