opencode-model-router 2.2.0 → 2.4.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 (83) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +90 -12
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +24 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +1435 -44
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +496 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/guard/enforce.ts +186 -22
  13. package/src/guard/guards.ts +132 -6
  14. package/src/guard/store.ts +5 -0
  15. package/src/index.ts +1193 -56
  16. package/src/router/build-info.ts +151 -0
  17. package/src/router/config.ts +1611 -19
  18. package/src/router/dispatch-header.ts +46 -4
  19. package/src/router/git-tools.ts +1152 -0
  20. package/src/router/guard-profile.ts +100 -0
  21. package/src/router/plugin-agents.ts +433 -0
  22. package/src/router/prompts.ts +26 -1
  23. package/src/router/protocol.ts +180 -0
  24. package/src/router/read-only.ts +149 -0
  25. package/src/router/role-agents.ts +409 -0
  26. package/src/router/roles-config.ts +429 -0
  27. package/src/router/roles.ts +600 -0
  28. package/src/router/run-tools.ts +913 -0
  29. package/src/router/sensitive-paths.ts +101 -0
  30. package/src/router/sessions.ts +533 -9
  31. package/src/router/subagents.ts +28 -1
  32. package/src/routing/advisor/findings.ts +898 -0
  33. package/src/routing/advisor/index.ts +614 -0
  34. package/src/routing/classify/backends/host.ts +163 -0
  35. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  36. package/src/routing/classify/backends/shared.ts +741 -0
  37. package/src/routing/classify/backends/typesafe.ts +315 -0
  38. package/src/routing/classify/fences.ts +96 -0
  39. package/src/routing/classify/index.ts +594 -0
  40. package/src/routing/classify/route-line.ts +362 -0
  41. package/src/routing/classify/rules.ts +667 -0
  42. package/src/routing/classify/scrub.ts +214 -0
  43. package/src/routing/classify/state.ts +148 -0
  44. package/src/routing/classify/text.ts +20 -0
  45. package/src/routing/classify/types.ts +1310 -0
  46. package/src/routing/commands/annotate-plan.ts +652 -0
  47. package/src/routing/commands/stats.ts +134 -0
  48. package/src/routing/commands/v1-roles.ts +64 -0
  49. package/src/routing/engine/index.ts +32 -0
  50. package/src/routing/engine/kernel.ts +760 -0
  51. package/src/routing/engine/ladders.ts +802 -0
  52. package/src/routing/engine/plan.ts +404 -0
  53. package/src/routing/engine/protocol-line.ts +150 -0
  54. package/src/routing/engine/roles-taxonomy.ts +52 -0
  55. package/src/routing/engine/simulate.ts +167 -0
  56. package/src/routing/engine/types.ts +368 -0
  57. package/src/routing/file-lock.ts +53 -0
  58. package/src/routing/outcomes/beta.ts +147 -0
  59. package/src/routing/outcomes/cost.ts +313 -0
  60. package/src/routing/outcomes/index.ts +215 -0
  61. package/src/routing/outcomes/ingest.ts +960 -0
  62. package/src/routing/outcomes/persist.ts +1080 -0
  63. package/src/routing/outcomes/signals.ts +650 -0
  64. package/src/routing/outcomes/stats.ts +873 -0
  65. package/src/routing/outcomes/store.ts +673 -0
  66. package/src/routing/outcomes/types.ts +1093 -0
  67. package/src/routing/roles/authority.ts +495 -0
  68. package/src/routing/roles/binding.ts +543 -0
  69. package/src/routing/roles/policy.ts +416 -0
  70. package/src/routing/roles/work-root.ts +132 -0
  71. package/src/routing/wire/dispatch.ts +2088 -0
  72. package/src/routing/wire/hint.ts +222 -0
  73. package/src/routing/wire/host-info.ts +256 -0
  74. package/src/routing/wire/runtime.ts +348 -0
  75. package/src/v2.ts +40 -1
  76. package/src/verify/checker.ts +249 -7
  77. package/src/verify/deterministic.ts +10 -1
  78. package/src/verify/dispatch.ts +63 -6
  79. package/src/verify/dod.ts +127 -10
  80. package/src/verify/gate.ts +75 -7
  81. package/src/verify/types.ts +12 -0
  82. package/src/verify/wiring.ts +55 -10
  83. package/tiers.json +13 -5
@@ -0,0 +1,898 @@
1
+ /**
2
+ * Cost doctor findings (M8, plan F4, Phase 2.4.1): what the router's own configuration and the host's catalog say
3
+ * about money and reliability that the user can fix.
4
+ *
5
+ * Pure: no I/O, no clock, no host calls. Every check reads only what it is handed (the merged router config, a view of
6
+ * the host's agents and the host model catalog) and answers with {@link Finding}s. A check that cannot know (no
7
+ * catalog, no agent list) says nothing instead of guessing, and a check that throws is skipped and logged by
8
+ * {@link runChecks}'s caller (`runAdvisor`), never raised into a session.
9
+ *
10
+ * Never invents a model: a suggested model always comes from the catalog it was given, is enabled, active and priced (A1/A2), and
11
+ * for the host's title agent it passes the host's own `Model.small` predicate (text in and out). A finding says where its fix goes:
12
+ * `target: "host"` = the user's `opencode.json`, `target: "router"` = `opencode-model-router.overrides.jsonc`; a snippet is JSON for that
13
+ * file, nothing else.
14
+ */
15
+
16
+ import { readFileSync } from "node:fs";
17
+ import type { RouterConfig, TierConfig } from "../../router/config";
18
+ import { configPath, resolveCandidates, resolveClassifierForPreset, resolveRouting, resolveVariantSteps, validateConfig } from "../../router/config";
19
+ import { getActiveTiers } from "../../router/protocol";
20
+ import { buildEscalatePolicy } from "../../escalate/ladder";
21
+ import type { TierVariantInfo } from "../../escalate/ladder";
22
+ import { DEFAULT_VARIANT, catalogVariantIds, nextVariant, variantCovered, variantPosition, variantRank } from "../../escalate/variants";
23
+ import type { VariantLadder } from "../../escalate/variants";
24
+ import { CLASS_STATIC_TIER } from "../classify/types";
25
+ import { isUnpriced, selectPriceEntry } from "../outcomes/cost";
26
+ import type { RoleStatsTable } from "../outcomes/types";
27
+ import { resolveRoleTable } from "../../router/roles";
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // Types
31
+ // ---------------------------------------------------------------------------
32
+
33
+ /** `warning`: a misconfiguration that costs reliability or silently disables something; `saving`: a concrete way to spend less; `info`: explains a number. */
34
+ export type FindingSeverity = "warning" | "saving" | "info";
35
+
36
+ export const FINDING_IDS = [
37
+ "title-model-unset",
38
+ "model-not-in-catalog",
39
+ "no-tool-support",
40
+ "variant-not-offered",
41
+ "effort-not-offered",
42
+ "variant-effort",
43
+ "effort-variant-mismatch",
44
+ "rejected-candidates",
45
+ "foreign-candidates",
46
+ "covered-tier",
47
+ "variant-ladder-budget",
48
+ "attempts-without-variants",
49
+ "unpriced-model",
50
+ "subscription-pricing",
51
+ "native-role-unmatched-rung",
52
+ "tier-agent-unavailable",
53
+ "classifier-model-missing",
54
+ "role-separation",
55
+ "roles-on-legacy-host",
56
+ "role-budget-low",
57
+ "role-range-clamped",
58
+ "role-binding-unknown",
59
+ "native-explore-aliased",
60
+ "role-usage-share",
61
+ "roles-none-enabled",
62
+ ] as const;
63
+ export type FindingId = (typeof FINDING_IDS)[number];
64
+
65
+ /** Whose configuration the fix belongs to: the host's own (`opencode.json`) or this plugin's (`opencode-model-router.overrides.jsonc`). */
66
+ export type FindingTarget = "host" | "router";
67
+
68
+ /** Only the title agent's model is the host's; everything else is this plugin's configuration. */
69
+ export const FINDING_TARGET: Readonly<Record<FindingId, FindingTarget>> = {
70
+ "title-model-unset": "host",
71
+ "model-not-in-catalog": "router",
72
+ "no-tool-support": "router",
73
+ "variant-not-offered": "router",
74
+ "effort-not-offered": "router",
75
+ "variant-effort": "router",
76
+ "effort-variant-mismatch": "router",
77
+ "rejected-candidates": "router",
78
+ "foreign-candidates": "router",
79
+ "covered-tier": "router",
80
+ "variant-ladder-budget": "router",
81
+ "attempts-without-variants": "router",
82
+ "unpriced-model": "router",
83
+ "subscription-pricing": "router",
84
+ "native-role-unmatched-rung": "router",
85
+ "tier-agent-unavailable": "router",
86
+ "classifier-model-missing": "router",
87
+ "role-separation": "router",
88
+ "roles-on-legacy-host": "router",
89
+ "role-budget-low": "router",
90
+ "role-range-clamped": "router",
91
+ "role-binding-unknown": "router",
92
+ "native-explore-aliased": "router",
93
+ "role-usage-share": "router",
94
+ "roles-none-enabled": "router",
95
+ };
96
+
97
+ export interface Finding {
98
+ readonly id: FindingId;
99
+ readonly severity: FindingSeverity;
100
+ /** Which file the fix is for. */
101
+ readonly target: FindingTarget;
102
+ /** The agent, tier or model the finding is about (`""` for a global finding). */
103
+ readonly subject: string;
104
+ /** What is wrong and what it costs, in one or two sentences. */
105
+ readonly message: string;
106
+ /** A JSON snippet for the `target` file that fixes it, or `null` when there is nothing safe to suggest. */
107
+ readonly snippet: string | null;
108
+ /** The OpenCode v1 spelling of a host-target snippet (`agent.title.model` / `small_model`), or `null`. */
109
+ readonly snippetV1: string | null;
110
+ /** The finding concerns a tier of a bundled preset that the user has not modified (QA-2.4-5): listed in `/router`, never in a notice. */
111
+ readonly bundledTier: boolean;
112
+ /** May appear in a notice: a warning or a saving that is not about an unmodified bundled tier. */
113
+ readonly notify: boolean;
114
+ }
115
+
116
+ /** What a check produces: `runChecks` adds `target`, `snippetV1`, `bundledTier` and `notify`. */
117
+ type RawFinding = Omit<Finding, "target" | "snippetV1" | "bundledTier" | "notify"> & { readonly snippetV1?: string | null };
118
+
119
+ /** The slice of a host `Model.Info` the checks read (structural; extra fields are ignored). */
120
+ export interface AdvisorCatalogModel {
121
+ readonly providerID: string;
122
+ readonly id: string;
123
+ readonly enabled?: boolean;
124
+ readonly status?: string;
125
+ /** Model family (`claude-haiku`, `gpt-luna`, …): the host's small-model pick is by family. */
126
+ readonly family?: string;
127
+ readonly capabilities?: { readonly tools?: boolean; readonly input?: readonly string[]; readonly output?: readonly string[] } | null;
128
+ readonly variants?: ReadonlyArray<{ readonly id?: unknown } | null | undefined> | null;
129
+ readonly cost?: unknown;
130
+ readonly limit?: { readonly context?: unknown; readonly input?: unknown; readonly output?: unknown } | null;
131
+ }
132
+
133
+ export interface HostAgentView {
134
+ readonly id: string;
135
+ /** `provider/model[#variant]`, or `null` when the agent has no model of its own. */
136
+ readonly model: string | null;
137
+ /** `subagent`, `primary` or `all` as the host reports it; `null` when the record carries none of those (a check then says nothing about the agent). */
138
+ readonly mode: "subagent" | "primary" | "all" | null;
139
+ readonly hidden: boolean;
140
+ }
141
+
142
+ /** What the checks need to know of the host's own configuration: its agents (a missing `model` = unset) and the session's model. */
143
+ export interface HostConfigView {
144
+ readonly agents: readonly HostAgentView[];
145
+ /** The orchestrator's model (the host's "primary"); `null`/absent when not known yet. The host's title pick depends on its provider. */
146
+ readonly primary?: { readonly providerID: string; readonly modelID: string | null } | null;
147
+ }
148
+
149
+ /** Providers whose catalog prices are relative weights, not what is billed (D6). */
150
+ export const SUBSCRIPTION_PROVIDERS: readonly string[] = ["opencode", "opencode-go", "github-copilot"];
151
+
152
+ const SEVERITY_ORDER: Readonly<Record<FindingSeverity, number>> = { warning: 0, saving: 1, info: 2 };
153
+
154
+ // ---------------------------------------------------------------------------
155
+ // Helpers
156
+ // ---------------------------------------------------------------------------
157
+
158
+ /** `provider/model#variant` → `{ model: "provider/model", variant }`. */
159
+ export function splitModelRef(ref: string): { model: string; variant: string | null } {
160
+ const at = ref.indexOf("#");
161
+ return at < 0 ? { model: ref, variant: null } : { model: ref.slice(0, at), variant: ref.slice(at + 1) === "" ? null : ref.slice(at + 1) };
162
+ }
163
+
164
+ function providerOf(model: string): string {
165
+ const slash = model.indexOf("/");
166
+ return slash < 0 ? "" : model.slice(0, slash);
167
+ }
168
+
169
+ function index(catalog: readonly AdvisorCatalogModel[]): Map<string, AdvisorCatalogModel> {
170
+ const map = new Map<string, AdvisorCatalogModel>();
171
+ for (const model of catalog) map.set(`${model.providerID}/${model.id}`, model);
172
+ return map;
173
+ }
174
+
175
+ function usable(model: AdvisorCatalogModel): boolean {
176
+ return model.enabled === true && model.status !== "deprecated";
177
+ }
178
+
179
+ /** Catalog price of `model` as `input + output` USD per million tokens; `null` when unpriced (A1). */
180
+ function pricePerMillion(model: AdvisorCatalogModel): number | null {
181
+ if (isUnpriced(model.cost as Parameters<typeof isUnpriced>[0])) return null;
182
+ const entry = selectPriceEntry(model.cost as Parameters<typeof selectPriceEntry>[0], 0);
183
+ return entry === null ? null : entry.input + entry.output;
184
+ }
185
+
186
+ /**
187
+ * The host's own candidate test for a title model (`Model.small` at v2.0.22, `core/src/model.ts`): enabled, `status: "active"`, and text
188
+ * in AND out. Tool calls are not needed (a title is one text generation), so they are not required here (QA-2.4-11).
189
+ */
190
+ function titleEligible(model: AdvisorCatalogModel): boolean {
191
+ const input = model.capabilities?.input;
192
+ const output = model.capabilities?.output;
193
+ return (
194
+ model.enabled === true &&
195
+ model.status === "active" &&
196
+ Array.isArray(input) && input.some((item) => typeof item === "string" && item.startsWith("text")) &&
197
+ Array.isArray(output) && output.some((item) => typeof item === "string" && item.startsWith("text"))
198
+ );
199
+ }
200
+
201
+ /** The families the host's `Model.small` looks for, in its order of preference. */
202
+ export const HOST_SMALL_MODEL_FAMILIES: readonly string[] = ["gpt-luna", "gemini-flash-lite", "gemini-flash", "claude-haiku"];
203
+
204
+ /**
205
+ * What `Model.small(providerID)` would answer for this catalog: among the provider's eligible models, the first of
206
+ * {@link HOST_SMALL_MODEL_FAMILIES} that has one. `null` = the host finds none and a title is generated with the session's own model.
207
+ */
208
+ export function hostSmallModel(catalog: readonly AdvisorCatalogModel[], providerID: string): AdvisorCatalogModel | null {
209
+ const models = catalog.filter((model) => model.providerID === providerID && titleEligible(model));
210
+ for (const family of HOST_SMALL_MODEL_FAMILIES) {
211
+ const hit = models.find((model) => model.family === family);
212
+ if (hit !== undefined) return hit;
213
+ }
214
+ return null;
215
+ }
216
+
217
+ /**
218
+ * A2: the cheapest priced model the host would accept for the title agent (`titleEligible`). Ties break on `provider/id`, so the
219
+ * answer is stable. `null` when the catalog has none.
220
+ */
221
+ export function cheapestTitleModel(catalog: readonly AdvisorCatalogModel[]): { ref: string; model: AdvisorCatalogModel; price: number } | null {
222
+ let best: { ref: string; model: AdvisorCatalogModel; price: number } | null = null;
223
+ for (const model of catalog) {
224
+ if (!titleEligible(model)) continue;
225
+ const price = pricePerMillion(model);
226
+ if (price === null) continue;
227
+ const ref = `${model.providerID}/${model.id}`;
228
+ if (best === null || price < best.price || (price === best.price && ref < best.ref)) best = { ref, model, price };
229
+ }
230
+ return best;
231
+ }
232
+
233
+ function fmtPrice(model: AdvisorCatalogModel): string {
234
+ const entry = selectPriceEntry(model.cost as Parameters<typeof selectPriceEntry>[0], 0);
235
+ return entry === null ? "n/a" : `$${entry.input}/$${entry.output} per Mtok in/out`;
236
+ }
237
+
238
+ function json(value: unknown): string {
239
+ return JSON.stringify(value);
240
+ }
241
+
242
+ function isEffortConfigured(tier: TierConfig): boolean {
243
+ return tier.effort !== undefined || tier.thinking !== undefined || tier.reasoning !== undefined;
244
+ }
245
+
246
+ /** Every `(model, variant)` rung of every active tier, with the tier that owns it. */
247
+ function rungsOf(cfg: RouterConfig): Array<{ tier: string; model: string; variant: string | null; costRatio: number }> {
248
+ const rungs: Array<{ tier: string; model: string; variant: string | null; costRatio: number }> = [];
249
+ for (const name of Object.keys(getActiveTiers(cfg) ?? {})) {
250
+ for (const rung of resolveCandidates(name, cfg)) rungs.push({ tier: name, model: rung.model, variant: rung.variant ?? null, costRatio: rung.costRatio });
251
+ }
252
+ return rungs;
253
+ }
254
+
255
+ function activeTierEntries(cfg: RouterConfig): Array<[string, TierConfig]> {
256
+ return Object.entries(getActiveTiers(cfg) ?? {}).filter(([, tier]) => tier !== null && typeof tier === "object" && typeof tier.model === "string" && tier.model !== "");
257
+ }
258
+
259
+ /**
260
+ * What the role checks need beyond the config: the host generation (a roles setting is inert on v1) and the outcome statistics of the
261
+ * roles layer. Every field is optional; a check whose input is absent says nothing.
262
+ */
263
+ export interface AdvisorExtras {
264
+ /** `v1` makes `routing.delegation: roles` inert (info); absent = unknown: every role check stays silent. */
265
+ readonly host?: "v1" | "v2";
266
+ /** `summarizeRoles` over the window the caller cares about; `null`/absent = no statistics. */
267
+ readonly roleStats?: RoleStatsTable | null;
268
+ /** Dispatch rows WITHOUT a role in the same window (tier dispatches); with `roleStats` it gives the role usage share. */
269
+ readonly tierDispatches?: number;
270
+ }
271
+
272
+ /** A role whose budget ran out in at least this share of its dispatches (and at least {@link ROLE_STATS_MIN_DISPATCHES} of them) has a budget that is too low. */
273
+ export const ROLE_BUDGET_LOW_SHARE = 0.2;
274
+ /** Fewest dispatches a statistic needs before a finding is drawn from it. */
275
+ export const ROLE_STATS_MIN_DISPATCHES = 5;
276
+
277
+ interface CheckInput {
278
+ readonly extras: AdvisorExtras;
279
+ readonly cfg: RouterConfig;
280
+ readonly host: HostConfigView | null;
281
+ readonly catalog: readonly AdvisorCatalogModel[] | null;
282
+ /** Catalog by `provider/model`; `null` when the catalog is unknown or empty (a catalog check then says nothing). */
283
+ readonly byRef: ReadonlyMap<string, AdvisorCatalogModel> | null;
284
+ }
285
+
286
+ type Check = (input: CheckInput) => RawFinding[];
287
+
288
+ // ---------------------------------------------------------------------------
289
+ // Checks
290
+ // ---------------------------------------------------------------------------
291
+
292
+ /**
293
+ * F4, QA-2.4-1: the host picks a session title's model as `agents.title.model`, else `Model.small(<session's provider>)` (a small model of
294
+ * the SAME provider: gpt-luna, gemini-flash-lite, gemini-flash or claude-haiku), else the session's own model (v2.0.22
295
+ * `core/src/session/context.ts` `selectTitle`). So the only case where leaving it unset costs anything is the last one: the provider has
296
+ * no such model in the catalog. Everything else is silent: with a small model present the host already picks a cheap one, and without
297
+ * knowing the session's provider (or the catalog) the pick cannot be predicted. No consumer of a `summary` model was found in the host,
298
+ * so none is reported.
299
+ */
300
+ const titleModel: Check = ({ host, catalog }) => {
301
+ if (host === null || catalog === null) return [];
302
+ const title = host.agents.find((a) => a.id === "title");
303
+ if (title === undefined || title.model !== null) return [];
304
+ const primary = host.primary;
305
+ if (primary === null || primary === undefined) return [];
306
+ if (hostSmallModel(catalog, primary.providerID) !== null) return [];
307
+ // The host falls back to the primary itself, so that is the price to beat (never when the primary is unpriced: then no saving is claimed).
308
+ const cheapest = cheapestTitleModel(catalog);
309
+ if (cheapest === null) return [];
310
+ const primaryEntry = primary.modelID === null ? undefined : catalog.find((m) => m.providerID === primary.providerID && m.id === primary.modelID);
311
+ const primaryPrice = primaryEntry === undefined ? null : pricePerMillion(primaryEntry);
312
+ if (primaryPrice !== null && cheapest.price >= primaryPrice) return [];
313
+ const primaryRef = primary.modelID === null ? primary.providerID : `${primary.providerID}/${primary.modelID}`;
314
+ const subscription = SUBSCRIPTION_PROVIDERS.includes(cheapest.model.providerID);
315
+ return [{
316
+ id: "title-model-unset",
317
+ severity: "saving",
318
+ subject: "title",
319
+ message: `agents.title.model is unset and the host finds no small model of ${primary.providerID} in your catalog (it looks for ${HOST_SMALL_MODEL_FAMILIES.join(", ")} of the session's provider), so session titles are generated with the session's own model, ${primaryRef}${
320
+ primaryPrice === null ? "" : ` (${fmtPrice(primaryEntry as AdvisorCatalogModel)})`
321
+ }. The cheapest priced model the host accepts for it in your catalog is ${cheapest.ref} (${fmtPrice(cheapest.model)})${
322
+ subscription ? `; ${cheapest.model.providerID} is a subscription provider, so its catalog prices are relative weights, not billed amounts` : ""
323
+ }.`,
324
+ snippet: json({ agents: { title: { model: cheapest.ref } } }),
325
+ snippetV1: `${json({ agent: { title: { model: cheapest.ref } } })} or ${json({ small_model: cheapest.ref })}`,
326
+ }];
327
+ };
328
+
329
+ /** QA-1.1-9: every rung of every tier against the live catalog (existence, tool support, variant). */
330
+ const ladderCatalog: Check = ({ cfg, byRef }) => {
331
+ if (byRef === null) return [];
332
+ const findings: RawFinding[] = [];
333
+ const seen = new Set<string>();
334
+ for (const rung of rungsOf(cfg)) {
335
+ const entry = byRef.get(rung.model);
336
+ const key = `${rung.tier}|${rung.model}|${rung.variant ?? ""}`;
337
+ if (seen.has(key)) continue;
338
+ seen.add(key);
339
+ if (entry === undefined || !usable(entry)) {
340
+ findings.push({
341
+ id: "model-not-in-catalog",
342
+ severity: "warning",
343
+ subject: rung.tier,
344
+ message: `Tier ${rung.tier} uses ${rung.model}, which is ${entry === undefined ? "not in" : "not enabled or deprecated in"} the host's model catalog: a dispatch to it fails, and the engine cannot price or resume it.`,
345
+ snippet: null,
346
+ });
347
+ continue;
348
+ }
349
+ if (entry.capabilities?.tools === false) {
350
+ findings.push({
351
+ id: "no-tool-support",
352
+ severity: "warning",
353
+ subject: rung.tier,
354
+ message: `Tier ${rung.tier} uses ${rung.model}, which does not support tool calls; a subagent cannot read, edit or run anything on it.`,
355
+ snippet: null,
356
+ });
357
+ }
358
+ const ids = catalogVariantIds(entry);
359
+ if (rung.variant !== null && ids !== null && !ids.includes(rung.variant)) {
360
+ findings.push({
361
+ id: "variant-not-offered",
362
+ severity: "warning",
363
+ subject: rung.tier,
364
+ message: `Tier ${rung.tier} asks for ${rung.model}#${rung.variant}, but the catalog offers ${ids.length === 0 ? "no variants" : `only ${ids.join(", ")}`} for it: the variant is dropped, the tier takes no variant steps and cannot be resumed.`,
365
+ snippet: null,
366
+ });
367
+ }
368
+ }
369
+ for (const [name, tier] of activeTierEntries(cfg)) {
370
+ if (tier.effort === undefined) continue;
371
+ const entry = byRef.get(tier.model);
372
+ const ids = entry === undefined ? null : catalogVariantIds(entry);
373
+ if (ids !== null && ids.length > 0 && !ids.includes(tier.effort)) {
374
+ findings.push({
375
+ id: "effort-not-offered",
376
+ severity: "info",
377
+ subject: name,
378
+ message: `Tier ${name} sets effort ${tier.effort}, which is not one of ${tier.model}'s catalog variants (${ids.join(", ")}); the host may map it provider-specifically or ignore it.`,
379
+ snippet: null,
380
+ });
381
+ }
382
+ }
383
+ return findings;
384
+ };
385
+
386
+ /** Ladders the runner will walk: needs variant steps on (v2, `auto`) and a catalog. */
387
+ function variantInfos(cfg: RouterConfig, byRef: ReadonlyMap<string, AdvisorCatalogModel> | null): { perTier: Readonly<Record<string, TierVariantInfo>>; maxTotalAttempts: number; ladder: readonly string[] } | null {
388
+ if (byRef === null || resolveVariantSteps(cfg, "v2") !== "auto") return null;
389
+ const policy = buildEscalatePolicy(cfg, {
390
+ host: "v2",
391
+ variantSteps: "auto",
392
+ maxContextFraction: resolveRouting(cfg, "v2").sessionReuse.maxContextFraction,
393
+ catalog: (model) => byRef.get(model) ?? null,
394
+ });
395
+ return { perTier: policy.variants?.perTier ?? {}, maxTotalAttempts: policy.maxTotalAttempts, ladder: policy.ladder };
396
+ }
397
+
398
+ /** A20 / QA-2.3-13: a tier that sets `variant` AND `effort`/`thinking`/`reasoning` has an empty variant ladder. */
399
+ const variantWithEffort: Check = ({ cfg, byRef }) => {
400
+ if (resolveVariantSteps(cfg, "v2") !== "auto") return [];
401
+ const findings: RawFinding[] = [];
402
+ for (const [name, tier] of activeTierEntries(cfg)) {
403
+ if (typeof tier.variant !== "string" || tier.variant === "" || !isEffortConfigured(tier)) continue;
404
+ const entry = byRef?.get(tier.model);
405
+ const ids = entry === undefined ? null : catalogVariantIds(entry);
406
+ const above = (ids ?? []).filter((id) => variantRank(id) > variantRank(tier.variant as string));
407
+ const own = resolveCandidates(name, cfg)[0];
408
+ const snippet = ids === null || above.length === 0 || own === undefined
409
+ ? null
410
+ : json({ presets: { [cfg.activePreset]: { [name]: { candidates: [{ variant: tier.variant, costRatio: own.costRatio }, ...above.map((variant) => ({ variant }))] } } } });
411
+ findings.push({
412
+ id: "variant-effort",
413
+ severity: "warning",
414
+ subject: name,
415
+ message: `Tier ${name} sets variant ${tier.variant} together with ${[tier.effort !== undefined ? "effort" : null, tier.thinking !== undefined ? "thinking" : null, tier.reasoning !== undefined ? "reasoning" : null].filter((s) => s !== null).join("/")}: effort is delivered by the effort path only, so the tier has no variant steps, and an escalation across it starts a fresh session instead of resuming the child. Drop the effort setting from the tier and list its variants as \`candidates\`${
416
+ snippet === null ? "" : " (snippet: the variants the catalog offers above it; give each higher rung its own costRatio, it inherits the tier's otherwise, which understates it)"
417
+ }.`,
418
+ snippet,
419
+ });
420
+ }
421
+ return findings;
422
+ };
423
+
424
+ /**
425
+ * QA-3.2 (O-32-5, measured on the real OpenCode 2.0.22 host in Phase 3.2): a tier that sets `variant` AND a different `effort` runs the EFFORT
426
+ * on the wire (the agent's effort option wins over the stored variant: the child is stored `#medium` while the request carries `xhigh`), but
427
+ * the outcome keys, the decision rows and `routing:stats` name the VARIANT. The evidence is then filed under a rung that is not what ran.
428
+ Only while the engine records anything (`routing.engine` is not `static`).
429
+ * QA-3.2-R2-1: when variant steps are on (`auto`) `variant-effort` already fires for EVERY tier that sets `variant` together with an effort setting, and its fix
430
+ * (drop the effort setting, list the variants as candidates) removes this mismatch too; one warning per tier, not two, so this one only speaks while variant
431
+ * steps are off (`escalate.variantSteps: "none"`), where `variant-effort` is silent and the keys-versus-wire problem is all that is left.
432
+ * Measured on Anthropic Messages (the OpenAI Responses route was not measured for this).
433
+ */
434
+ const effortVariantMismatch: Check = ({ cfg, byRef }) => {
435
+ if (resolveRouting(cfg, "v2").engine === "static") return [];
436
+ if (resolveVariantSteps(cfg, "v2") === "auto") return []; // `variant-effort` covers these tiers and says the same fix
437
+ const findings: RawFinding[] = [];
438
+ for (const [name, tier] of activeTierEntries(cfg)) {
439
+ if (typeof tier.variant !== "string" || tier.variant === "" || typeof tier.effort !== "string" || tier.effort === tier.variant) continue;
440
+ const entry = byRef?.get(tier.model);
441
+ const ids = entry === undefined ? null : catalogVariantIds(entry);
442
+ const offered = ids === null || ids.includes(tier.effort);
443
+ findings.push({
444
+ id: "effort-variant-mismatch",
445
+ severity: "warning",
446
+ subject: name,
447
+ message: `Tier ${name} sets variant ${tier.variant} but effort ${tier.effort}: the request runs effort ${tier.effort} (the agent's effort option wins over the stored variant; measured on Anthropic Messages), while the outcome keys, the decision rows and routing:stats name ${tier.model}#${tier.variant}, so what this tier learns is filed under a rung that is not what runs. Make them agree: ${
448
+ offered ? `set variant to ${tier.effort} (snippet), or ` : ""
449
+ }drop the effort setting.`,
450
+ snippet: offered ? json({ presets: { [cfg.activePreset]: { [name]: { variant: tier.effort } } } }) : null,
451
+ });
452
+ }
453
+ return findings;
454
+ };
455
+
456
+ /** The variant steps a tier takes from its base, in order (the ladder itself also lists the base and the rungs below it). */
457
+ function stepsFrom(ladder: VariantLadder, base: string): string[] {
458
+ const steps: string[] = [];
459
+ let current: string | null = base === DEFAULT_VARIANT ? null : base;
460
+ for (let i = 0; i < ladder.variants.length; i += 1) {
461
+ const next = nextVariant(ladder, current);
462
+ if (next === null) break;
463
+ steps.push(next);
464
+ current = next;
465
+ }
466
+ return steps;
467
+ }
468
+
469
+ /** 1.5 handoff: rejected and foreign candidates, tiers a variant ladder covers, F5. */
470
+ const variantLadders: Check = ({ cfg, byRef }) => {
471
+ const infos = variantInfos(cfg, byRef);
472
+ if (infos === null) return [];
473
+ const findings: RawFinding[] = [];
474
+ for (const [name, info] of Object.entries(infos.perTier)) {
475
+ if (info.effortConfigured === true) continue; // reported by variantWithEffort
476
+ if (info.ladder.rejected.length > 0) {
477
+ findings.push({
478
+ id: "rejected-candidates",
479
+ severity: "warning",
480
+ subject: name,
481
+ message: `Tier ${name}: candidate variant${info.ladder.rejected.length > 1 ? "s" : ""} ${info.ladder.rejected.join(", ")} of ${info.model} ${info.ladder.rejected.length > 1 ? "are" : "is"} ignored (not offered by the catalog, unranked, or not above the previous rung). Variant steps walk ${info.ladder.variants.length === 0 ? "nothing" : info.ladder.variants.join(" → ")} (base ${info.base}).`,
482
+ snippet: null,
483
+ });
484
+ }
485
+ if (info.ladder.foreign.length > 0) {
486
+ findings.push({
487
+ id: "foreign-candidates",
488
+ severity: "info",
489
+ subject: name,
490
+ message: `Tier ${name}: candidate rung${info.ladder.foreign.length > 1 ? "s" : ""} on another model (${info.ladder.foreign.map((r) => `${r.model}${r.variant === null ? "" : `#${r.variant}`}`).join(", ")}) ${info.ladder.foreign.length > 1 ? "are" : "is"} never walked by variant steps (those stay on ${info.model}); the engine prices ${info.ladder.foreign.length > 1 ? "them" : "it"} as dispatch options only.`,
491
+ snippet: null,
492
+ });
493
+ }
494
+ const steps = stepsFrom(info.ladder, info.base);
495
+ if (steps.length >= infos.maxTotalAttempts - 1 && steps.length > 0) {
496
+ findings.push({
497
+ id: "variant-ladder-budget",
498
+ severity: "info",
499
+ subject: name,
500
+ message: `Tier ${name} has ${steps.length} variant steps (${[info.base, ...steps].join(" → ")}) and maxTotalAttempts is ${infos.maxTotalAttempts}: a failing delegation can spend its whole attempt budget on this tier's variants. The budget reserve still keeps an escalation reachable, but every variant of an unpriced model counts at the tier's costRatio unless you give it its own.`,
501
+ snippet: null,
502
+ });
503
+ }
504
+ }
505
+ // A tier skipped on escalation because an earlier tier on the same model already covers its base.
506
+ const order = infos.ladder.filter((name) => infos.perTier[name] !== undefined);
507
+ for (let i = 0; i < order.length; i += 1) {
508
+ const from = infos.perTier[order[i] as string] as TierVariantInfo;
509
+ if (from.effortConfigured === true) continue;
510
+ const fromSteps = stepsFrom(from.ladder, from.base);
511
+ const top = fromSteps.length === 0 ? from.base : (fromSteps[fromSteps.length - 1] as string);
512
+ const position = (variant: string): number => variantPosition(variant) ?? Number.POSITIVE_INFINITY;
513
+ for (let j = i + 1; j < order.length; j += 1) {
514
+ const to = infos.perTier[order[j] as string] as TierVariantInfo;
515
+ if (to.effortConfigured === true || to.model !== from.model) continue;
516
+ const toSteps = stepsFrom(to.ladder, to.base);
517
+ const toTop = toSteps.length === 0 ? to.base : (toSteps[toSteps.length - 1] as string);
518
+ if (variantCovered(to.base, top) && position(toTop) <= position(top)) {
519
+ findings.push({
520
+ id: "covered-tier",
521
+ severity: "info",
522
+ subject: order[j] as string,
523
+ message: `Tier ${order[j]} (${to.model}#${to.base}) is covered by tier ${order[i]}'s variant steps (up to #${top}): an escalation from ${order[i]} skips it and goes straight to the next tier that adds something.`,
524
+ snippet: null,
525
+ });
526
+ }
527
+ }
528
+ }
529
+ return findings;
530
+ };
531
+
532
+ /** F4: one attempt per tier and no variant steps = every failure pays for a bigger model. */
533
+ const attemptsWithoutVariants: Check = ({ cfg }) => {
534
+ const esc = cfg.enforcement?.escalate;
535
+ if (esc === undefined || esc === null) return [];
536
+ const perTier = esc.maxAttemptsPerTier ?? 1;
537
+ if (resolveVariantSteps(cfg, "v2") !== "none" || perTier !== 1) return [];
538
+ // QA-3.1-R2-5 (A20): variant steps exist only on tiers without effort/thinking/reasoning. When every ladder tier of the active preset
539
+ // sets one of those, turning variant steps on would change nothing, so the suggestion would be wrong.
540
+ const tiers = new Map(activeTierEntries(cfg));
541
+ const ladderTiers = buildEscalatePolicy(cfg).ladder.filter((name) => tiers.has(name)).map((name) => tiers.get(name) as TierConfig);
542
+ if (ladderTiers.length > 0 && ladderTiers.every(isEffortConfigured)) return [];
543
+ return [{
544
+ id: "attempts-without-variants",
545
+ severity: "info",
546
+ subject: "",
547
+ message: "enforcement.escalate.maxAttemptsPerTier is 1 and variantSteps is none: a failed verification re-runs the same rung once in a fresh child, then escalates to the next, more expensive tier; variant steps would retry a higher variant on the same session first, on tiers without effort/thinking/reasoning (a tier that sets one of those keeps the effort-bump path). Turn variant steps on (a `routing` block makes the default `auto`) or allow another attempt per tier.",
548
+ snippet: json({ enforcement: { escalate: { variantSteps: "auto" } } }),
549
+ }];
550
+ };
551
+
552
+ /** D5 / D6: unpriced ladder models and subscription providers. */
553
+ const pricing: Check = ({ cfg, byRef }) => {
554
+ if (byRef === null) return [];
555
+ const findings: RawFinding[] = [];
556
+ const models = [...new Set(rungsOf(cfg).map((r) => r.model))];
557
+ const unpriced = models.filter((m) => {
558
+ const entry = byRef.get(m);
559
+ return entry !== undefined && isUnpriced(entry.cost as Parameters<typeof isUnpriced>[0]);
560
+ });
561
+ if (unpriced.length > 0) {
562
+ findings.push({
563
+ id: "unpriced-model",
564
+ severity: "info",
565
+ subject: unpriced.join(", "),
566
+ message: `The catalog has no price for ${unpriced.join(", ")}: the engine compares candidates in costRatio units and reports no USD figure for them (a reported cost of 0 is treated as unknown). Token counts are still recorded.`,
567
+ snippet: null,
568
+ });
569
+ }
570
+ const subscription = [...new Set(models.map(providerOf))].filter((p) => SUBSCRIPTION_PROVIDERS.includes(p));
571
+ if (subscription.length > 0) {
572
+ findings.push({
573
+ id: "subscription-pricing",
574
+ severity: "info",
575
+ subject: subscription.join(", "),
576
+ message: `Provider${subscription.length > 1 ? "s" : ""} ${subscription.join(", ")} ${subscription.length > 1 ? "are" : "is a"} subscription provider${subscription.length > 1 ? "s" : ""}: catalog prices are not what is billed, so the engine uses them as relative weights only.`,
577
+ snippet: null,
578
+ });
579
+ }
580
+ return findings;
581
+ };
582
+
583
+ /** 1.4 handoff (E4): a role agent whose own model matches no rung of the preset is priced at its owning tier's first rung. */
584
+ const nativeRoles: Check = ({ cfg, host }) => {
585
+ if (host === null) return [];
586
+ const routing = resolveRouting(cfg, "v2");
587
+ if (routing.engine === "static") return [];
588
+ const rungKeys = new Set(rungsOf(cfg).map((r) => `${r.model}#${r.variant ?? DEFAULT_VARIANT}`));
589
+ const findings: RawFinding[] = [];
590
+ const reported = new Set<string>();
591
+ for (const [taskClass, agents] of Object.entries(routing.roles)) {
592
+ for (const id of agents) {
593
+ const agent = host.agents.find((a) => a.id === id);
594
+ if (agent === undefined || agent.model === null || agent.mode === null || agent.mode === "primary" || agent.hidden || reported.has(id)) continue;
595
+ const { model, variant } = splitModelRef(agent.model);
596
+ if (rungKeys.has(`${model}#${variant ?? DEFAULT_VARIANT}`)) continue;
597
+ reported.add(id);
598
+ const ownerName = CLASS_STATIC_TIER[taskClass as keyof typeof CLASS_STATIC_TIER] ?? cfg.defaultTier;
599
+ const owner = resolveCandidates(ownerName, cfg)[0];
600
+ findings.push({
601
+ id: "native-role-unmatched-rung",
602
+ severity: "info",
603
+ subject: id,
604
+ message: `Agent ${id} (role for ${taskClass}) runs ${agent.model}, which is not a rung of any tier, so the engine prices it at the first rung of tier ${ownerName}${owner === undefined ? "" : ` (${owner.costRatio}×)`}: an assumption, not its real cost. List it as a \`candidates\` rung with its own costRatio to price it properly.`,
605
+ snippet: null,
606
+ });
607
+ }
608
+ }
609
+ return findings;
610
+ };
611
+
612
+ /** 2.2 handoff: the engine routes to agents by id; a tier agent the host does not offer makes it inert for that tier. */
613
+ const tierAgents: Check = ({ cfg, host }) => {
614
+ if (host === null || host.agents.length === 0) return [];
615
+ const findings: RawFinding[] = [];
616
+ for (const [name] of activeTierEntries(cfg)) {
617
+ const agent = host.agents.find((a) => a.id === name);
618
+ if (agent !== undefined && (agent.mode === null || (agent.mode !== "primary" && !agent.hidden))) continue; // an unknown mode is not judged
619
+ findings.push({
620
+ id: "tier-agent-unavailable",
621
+ severity: "warning",
622
+ subject: name,
623
+ message: `The host offers no dispatchable subagent named ${name}${agent === undefined ? "" : agent.hidden ? " (it is hidden)" : " (it is a primary agent)"}: the engine cannot route a dispatch to this tier, and any \`ineligible: agent-unavailable\` reason in the decision log comes from this. Check that the plugin is registered and that no permission rule denies \`subagent:${name}\`.`,
624
+ snippet: null,
625
+ });
626
+ }
627
+ return findings;
628
+ };
629
+
630
+ /** QA-1.1-9: the `host` classifier backend names a catalog model. */
631
+ const classifierModel: Check = ({ cfg, byRef }) => {
632
+ if (byRef === null) return [];
633
+ const routing = resolveRouting(cfg, "v2");
634
+ const classifier = resolveClassifierForPreset(routing.classifier, cfg.activePreset);
635
+ if (classifier.backend !== "host" || classifier.model === null) return [];
636
+ const { model } = splitModelRef(classifier.model);
637
+ const entry = byRef.get(model);
638
+ if (entry !== undefined && usable(entry)) return [];
639
+ return [{
640
+ id: "classifier-model-missing",
641
+ severity: "warning",
642
+ subject: classifier.model,
643
+ message: `routing.classifier.model is ${classifier.model}, which is ${entry === undefined ? "not in" : "not enabled or deprecated in"} the host's model catalog: the classifier call fails and every dispatch falls back to the rules classifier.`,
644
+ snippet: null,
645
+ }];
646
+ };
647
+
648
+ // ---------------------------------------------------------------------------
649
+ // Roles checks (P2.2): all silent in tiers mode
650
+ // ---------------------------------------------------------------------------
651
+
652
+ function rolesMode(cfg: RouterConfig): boolean {
653
+ return cfg.routing?.delegation === "roles";
654
+ }
655
+
656
+ /** Roles mode on a host KNOWN to be v2. A missing `extras.host` is unknown, so the role checks say nothing (QA-P22-1-2). */
657
+ function rolesOnV2({ cfg, extras }: CheckInput): boolean {
658
+ return rolesMode(cfg) && extras.host === "v2";
659
+ }
660
+
661
+ /** The role table as v2 resolves it; `null` unless the config asks for roles mode and the host is known to be v2. */
662
+ function activeRoleTable(input: CheckInput): ReturnType<typeof resolveRoleTable> | null {
663
+ if (!rolesOnV2(input)) return null;
664
+ return resolveRoleTable(input.cfg, "v2");
665
+ }
666
+
667
+ /** Roles mode on v2 but every role is disabled or invalid: the orchestrator is given the tiers protocol. */
668
+ const rolesNoneEnabled: Check = (input) => {
669
+ const table = activeRoleTable(input);
670
+ if (table === null || table.roles.size > 0) return [];
671
+ return [{
672
+ id: "roles-none-enabled",
673
+ severity: "info",
674
+ subject: "",
675
+ message: "routing.delegation is `roles` but no role is enabled (all disabled or invalid), so the orchestrator is given the tier protocol instead. Enable a role under roleAgents, or set routing.delegation to `tiers`.",
676
+ snippet: null,
677
+ }];
678
+ };
679
+
680
+ /** A #81 `agents` entry named like a shipped role that breaks the separation rule (I4): dropped, the shipped role stays. */
681
+ const roleSeparation: Check = (input) => {
682
+ const table = activeRoleTable(input);
683
+ if (table === null) return [];
684
+ return table.droppedAgents.map((agent): RawFinding => {
685
+ const issue = table.issues.find((i) => i.path === `agents.${agent}`);
686
+ return {
687
+ id: "role-separation",
688
+ severity: "warning",
689
+ subject: agent,
690
+ message: `${issue?.message ?? `agents.${agent} breaks the separation rule`}. No role may combine write, exec and egress (I4): remove the agent from \`agents\` or narrow its permissions, otherwise the shipped ${agent} role runs instead of yours.`,
691
+ snippet: null,
692
+ };
693
+ });
694
+ };
695
+
696
+ /** `routing.delegation: roles` on OpenCode v1: inert there (the orchestrator keeps the tier protocol). */
697
+ const rolesOnLegacyHost: Check = ({ cfg, extras }) => {
698
+ if (extras.host !== "v1" || !rolesMode(cfg)) return [];
699
+ return [{
700
+ id: "roles-on-legacy-host",
701
+ severity: "info",
702
+ subject: "",
703
+ message: "routing.delegation is `roles`, which does nothing on OpenCode v1: the orchestrator keeps the tier protocol and no role agent is registered. It takes effect on OpenCode v2.",
704
+ snippet: null,
705
+ }];
706
+ };
707
+
708
+ /** A role's range or budget was placed on this preset's tiers or clamped (a notice of the role table). */
709
+ const roleRangeClamped: Check = (input) => {
710
+ const table = activeRoleTable(input);
711
+ if (table === null) return [];
712
+ return table.issues
713
+ .filter((i) => /^roleAgents\.[^.]+\.(tierRange|budget)(\.|$)/.test(i.path))
714
+ .map((i): RawFinding => ({
715
+ id: "role-range-clamped",
716
+ severity: "info",
717
+ subject: i.path.split(".")[1] ?? "",
718
+ message: i.message,
719
+ snippet: null,
720
+ }));
721
+ };
722
+
723
+ /** Host native `explore` is aliased to the `explorer` role in roles mode, so a `subagentTiers.explore` mapping no longer decides its model. */
724
+ const nativeExploreAliased: Check = (input) => {
725
+ const table = activeRoleTable(input);
726
+ if (table === null || !table.roles.has("explorer")) return [];
727
+ return [{
728
+ id: "native-explore-aliased",
729
+ severity: "info",
730
+ subject: "explore",
731
+ message: `In roles mode a dispatch of the host's native explore agent is aliased to the explorer role${input.cfg.subagentTiers?.explore === undefined ? "" : `, so subagentTiers.explore (${input.cfg.subagentTiers.explore}) no longer decides its model`}: the router picks the tier within the role's range.`,
732
+ snippet: null,
733
+ }];
734
+ };
735
+
736
+ /** A role spends its budget in a large share of its dispatches: the budget is too low for the work routed to it. */
737
+ const roleBudgetLow: Check = (input) => {
738
+ const stats = input.extras.roleStats;
739
+ if (stats === undefined || stats === null || !rolesOnV2(input)) return [];
740
+ const byRole = new Map<string, { dispatches: number; exhausted: number }>();
741
+ for (const row of stats.byRoleTier) {
742
+ const acc = byRole.get(row.role) ?? { dispatches: 0, exhausted: 0 };
743
+ acc.dispatches += row.dispatches;
744
+ acc.exhausted += row.budgetExhaustions;
745
+ byRole.set(row.role, acc);
746
+ }
747
+ const findings: RawFinding[] = [];
748
+ for (const [role, acc] of [...byRole].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
749
+ if (acc.dispatches < ROLE_STATS_MIN_DISPATCHES || acc.exhausted / acc.dispatches < ROLE_BUDGET_LOW_SHARE) continue;
750
+ findings.push({
751
+ id: "role-budget-low",
752
+ severity: "warning",
753
+ subject: role,
754
+ message: `Role ${role} ran out of budget in ${acc.exhausted} of ${acc.dispatches} dispatches (${Math.round((100 * acc.exhausted) / acc.dispatches)}%): its work needs more steps than roleAgents.${role}.budget allows, so it keeps returning NEED MORE: budget. Raise roleAgents.${role}.budget for the tiers it runs on.`,
755
+ snippet: null,
756
+ });
757
+ }
758
+ return findings;
759
+ };
760
+
761
+ /** Child sessions that could not be bound to a role dispatch: their outcomes are not attributed. */
762
+ const roleBindingUnknown: Check = (input) => {
763
+ const stats = input.extras.roleStats;
764
+ if (stats === undefined || stats === null || !rolesOnV2(input)) return [];
765
+ let total = stats.unattributed.unknownBindings;
766
+ for (const row of stats.byRoleTier) total += row.unknownBindings;
767
+ if (total <= 0) return [];
768
+ return [{
769
+ id: "role-binding-unknown",
770
+ severity: "warning",
771
+ subject: "",
772
+ message: `${total} child session${total === 1 ? "" : "s"} could not be bound to the role dispatch that created ${total === 1 ? "it" : "them"} (binding: unknown), so ${total === 1 ? "its" : "their"} outcomes and authority are not attributed. If this keeps happening the host's child-session events do not carry the parent link the router needs.`,
773
+ snippet: null,
774
+ }];
775
+ };
776
+
777
+ /** The share of role dispatches among all dispatches: tells whether the orchestrator follows the roles protocol or keeps naming tiers. */
778
+ const roleUsageShare: Check = (input) => {
779
+ const stats = input.extras.roleStats;
780
+ const tierDispatches = input.extras.tierDispatches;
781
+ if (stats === undefined || stats === null || tierDispatches === undefined || !rolesOnV2(input)) return [];
782
+ const roleDispatches = stats.byRoleTier.reduce((sum, row) => sum + row.dispatches, 0);
783
+ const total = roleDispatches + tierDispatches;
784
+ if (total < ROLE_STATS_MIN_DISPATCHES || tierDispatches === 0) return [];
785
+ return [{
786
+ id: "role-usage-share",
787
+ severity: "info",
788
+ subject: "",
789
+ message: `${roleDispatches} of ${total} dispatches (${Math.round((100 * roleDispatches) / total)}%) went to a role; ${tierDispatches} named a tier directly. Explicit tier dispatch keeps working; the roles protocol asks the orchestrator to name roles.`,
790
+ snippet: null,
791
+ }];
792
+ };
793
+
794
+ const CHECKS: ReadonlyArray<readonly [string, Check]> = [
795
+ ["title-model", titleModel],
796
+ ["ladder-catalog", ladderCatalog],
797
+ ["variant-effort", variantWithEffort],
798
+ ["effort-variant", effortVariantMismatch],
799
+ ["variant-ladders", variantLadders],
800
+ ["attempts", attemptsWithoutVariants],
801
+ ["pricing", pricing],
802
+ ["native-roles", nativeRoles],
803
+ ["tier-agents", tierAgents],
804
+ ["classifier-model", classifierModel],
805
+ ["role-separation", roleSeparation],
806
+ ["roles-on-legacy-host", rolesOnLegacyHost],
807
+ ["roles-none-enabled", rolesNoneEnabled],
808
+ ["role-range", roleRangeClamped],
809
+ ["native-explore", nativeExploreAliased],
810
+ ["role-budget", roleBudgetLow],
811
+ ["role-binding", roleBindingUnknown],
812
+ ["role-usage", roleUsageShare],
813
+ ];
814
+
815
+ /**
816
+ * The findings about the SHAPE of a tier's configuration (`subject` is a tier name of the active preset): what the shipped `tiers.json`
817
+ * defines for that tier is not the user's doing, so while the tier is exactly as shipped these are listed in `/router` and never announced
818
+ * (QA-2.4-R2-7). The findings about the user's ENVIRONMENT (`model-not-in-catalog`, `no-tool-support`, `variant-not-offered`,
819
+ * `tier-agent-unavailable`: the model is not offered, has no tools, the agent is not there) are real whoever wrote the tier, so they
820
+ * always notify.
821
+ */
822
+ const CONFIG_SHAPE: ReadonlySet<FindingId> = new Set<FindingId>([
823
+ "variant-effort",
824
+ "effort-variant-mismatch",
825
+ "rejected-candidates",
826
+ "foreign-candidates",
827
+ "covered-tier",
828
+ "variant-ladder-budget",
829
+ "effort-not-offered",
830
+ ]);
831
+
832
+ function stable(value: unknown): string {
833
+ if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
834
+ if (typeof value === "object" && value !== null) {
835
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable((value as Record<string, unknown>)[key])}`).join(",")}}`;
836
+ }
837
+ return JSON.stringify(value) ?? "null";
838
+ }
839
+
840
+ /**
841
+ * The shipped `tiers.json`, validated like any config, read once per loaded config: the memo is keyed by the `RouterConfig` object, and
842
+ * `loadConfig` hands out a new object on every reload, so a `tiers.json` the plugin update replaced is read again (QA-2.4-R2-11) while
843
+ * a config in use is not re-read on every check. `null` = unreadable (a tier is then not "bundled").
844
+ */
845
+ const bundledMemo = new WeakMap<RouterConfig, { readonly config: RouterConfig | null }>();
846
+
847
+ function bundledConfig(cfg: RouterConfig, onError: (check: string, error: unknown) => void): RouterConfig | null {
848
+ let memo = bundledMemo.get(cfg);
849
+ if (memo === undefined) {
850
+ try {
851
+ memo = { config: validateConfig(JSON.parse(readFileSync(configPath(), "utf-8"))) };
852
+ } catch (error) {
853
+ memo = { config: null };
854
+ onError("bundled-preset", error); // reported once per loaded config; every tier then counts as the user's own, so its findings still notify
855
+ }
856
+ bundledMemo.set(cfg, memo);
857
+ }
858
+ return memo.config;
859
+ }
860
+ /** The tier of the ACTIVE preset is exactly what the shipped `tiers.json` defines for that preset and tier (no override touched it). */
861
+ function isUnmodifiedBundledTier(cfg: RouterConfig, tierName: string, onError: (check: string, error: unknown) => void): boolean {
862
+ const live = cfg.presets[cfg.activePreset]?.[tierName];
863
+ const shipped = bundledConfig(cfg, onError)?.presets[cfg.activePreset]?.[tierName];
864
+ return live !== undefined && shipped !== undefined && stable(live) === stable(shipped);
865
+ }
866
+
867
+ /**
868
+ * Run every check. A throwing check is reported to `onError` and skipped; the rest still run. Findings come back sorted by
869
+ * severity (warning, saving, info), then by check order, so the list is stable.
870
+ */
871
+ export function runChecks(
872
+ cfg: RouterConfig,
873
+ host: HostConfigView | null,
874
+ catalog: readonly AdvisorCatalogModel[] | null,
875
+ onError: (check: string, error: unknown) => void,
876
+ extras: AdvisorExtras = {},
877
+ ): Finding[] {
878
+ const known = catalog !== null && catalog.length > 0 ? catalog : null;
879
+ const input: CheckInput = { cfg, host, catalog: known, byRef: known === null ? null : index(known), extras };
880
+ const out: Array<{ finding: Finding; order: number }> = [];
881
+ let order = 0;
882
+ for (const [name, check] of CHECKS) {
883
+ try {
884
+ for (const raw of check(input)) {
885
+ const bundledTier = CONFIG_SHAPE.has(raw.id) && isUnmodifiedBundledTier(cfg, raw.subject, onError);
886
+ out.push({
887
+ finding: { ...raw, target: FINDING_TARGET[raw.id], snippetV1: raw.snippetV1 ?? null, bundledTier, notify: raw.severity !== "info" && !bundledTier },
888
+ order: order++,
889
+ });
890
+ }
891
+ } catch (error) {
892
+ onError(name, error);
893
+ }
894
+ }
895
+ return out
896
+ .sort((a, b) => SEVERITY_ORDER[a.finding.severity] - SEVERITY_ORDER[b.finding.severity] || a.order - b.order)
897
+ .map((entry) => entry.finding);
898
+ }