opencode-model-router 2.3.0 → 2.5.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 (68) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +86 -11
  3. package/package.json +6 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1374 -24
  6. package/src/escalate/ladder.ts +12 -0
  7. package/src/guard/enforce.ts +186 -22
  8. package/src/guard/guards.ts +132 -6
  9. package/src/guard/store.ts +5 -0
  10. package/src/index.ts +718 -29
  11. package/src/router/config.ts +247 -1
  12. package/src/router/dispatch-header.ts +46 -4
  13. package/src/router/git-tools.ts +1152 -0
  14. package/src/router/guard-profile.ts +100 -0
  15. package/src/router/plugin-agents.ts +433 -0
  16. package/src/router/prompts.ts +26 -1
  17. package/src/router/protocol.ts +133 -0
  18. package/src/router/read-only.ts +149 -0
  19. package/src/router/role-agents.ts +409 -0
  20. package/src/router/roles-config.ts +429 -0
  21. package/src/router/roles.ts +600 -0
  22. package/src/router/run-tools.ts +913 -0
  23. package/src/router/sensitive-paths.ts +101 -0
  24. package/src/router/sessions.ts +92 -0
  25. package/src/router/subagents.ts +28 -1
  26. package/src/routing/advisor/findings.ts +193 -1
  27. package/src/routing/advisor/index.ts +13 -5
  28. package/src/routing/classify/index.ts +23 -5
  29. package/src/routing/classify/route-line.ts +67 -3
  30. package/src/routing/classify/rules.ts +80 -20
  31. package/src/routing/classify/types.ts +34 -4
  32. package/src/routing/commands/stats.ts +3 -0
  33. package/src/routing/engine/kernel.ts +163 -0
  34. package/src/routing/engine/ladders.ts +242 -1
  35. package/src/routing/engine/protocol-line.ts +17 -0
  36. package/src/routing/engine/roles-taxonomy.ts +52 -0
  37. package/src/routing/engine/types.ts +99 -1
  38. package/src/routing/outcomes/beta.ts +10 -4
  39. package/src/routing/outcomes/index.ts +44 -1
  40. package/src/routing/outcomes/ingest.ts +163 -15
  41. package/src/routing/outcomes/persist.ts +23 -1
  42. package/src/routing/outcomes/signals.ts +650 -0
  43. package/src/routing/outcomes/stats.ts +273 -2
  44. package/src/routing/outcomes/store.ts +25 -5
  45. package/src/routing/outcomes/types.ts +145 -6
  46. package/src/routing/roles/authority.ts +495 -0
  47. package/src/routing/roles/binding.ts +543 -0
  48. package/src/routing/roles/policy.ts +416 -0
  49. package/src/routing/roles/work-root.ts +132 -0
  50. package/src/routing/wire/dispatch.ts +1306 -17
  51. package/src/routing/wire/hint.ts +14 -0
  52. package/src/routing/wire/runtime.ts +117 -28
  53. package/src/tui/effort-channel.ts +220 -0
  54. package/src/tui/effort-rpc.ts +60 -0
  55. package/src/tui/host-types.ts +154 -0
  56. package/src/tui/opentui-solid.d.ts +16 -0
  57. package/src/tui/plugin.ts +1007 -0
  58. package/src/tui/status-model.ts +561 -0
  59. package/src/v2.ts +26 -1
  60. package/src/verify/checker.ts +249 -7
  61. package/src/verify/deterministic.ts +10 -1
  62. package/src/verify/dispatch.ts +63 -6
  63. package/src/verify/dod.ts +127 -10
  64. package/src/verify/gate.ts +75 -7
  65. package/src/verify/types.ts +12 -0
  66. package/src/verify/wiring.ts +55 -10
  67. package/tiers.json +13 -5
  68. package/tui.ts +4 -0
@@ -0,0 +1,101 @@
1
+ /** One filename policy for read approval, grep filtering and Git exclusions.
2
+ * Patterns are relative suffixes, matched at any depth (not a content scanner). */
3
+ const SSH_KEY_NAMES = ["id_rsa", "id_ed25519", "id_ecdsa", "id_dsa"] as const;
4
+ export const SENSITIVE_PATH_PATTERNS = [
5
+ "*.env", "*.env.*", "*.pem", "*.key", "*.p12", "*.pfx", "*.kdbx",
6
+ ...SSH_KEY_NAMES.flatMap(name => [name, `${name}.*`]),
7
+ ".npmrc", ".netrc", ".pgpass", ".git-credentials", "credentials.json",
8
+ ".aws/credentials", ".docker/config.json",
9
+ ".envrc", "*.ppk", "*.jks", "*.keystore", ".kube/config", "*.tfvars", "*.tfstate",
10
+ ".pypirc", ".vault-token", ".cargo/credentials*", ".config/gh/hosts.yml", "application_default_credentials.json",
11
+ ] as const;
12
+ // Public SSH keys are intentionally readable; backups/extensions other than
13
+ // exactly .pub remain sensitive. Helpers like id_rsa_helpers are not key names.
14
+ export const SENSITIVE_PATH_EXCEPTIONS = ["*.env.example", ...SSH_KEY_NAMES.map(name => `${name}.pub`)] as const;
15
+ const escape = (text: string) => text.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("*", "[^/]*");
16
+
17
+ export function isSensitivePath(path: string, platform: NodeJS.Platform = process.platform): boolean {
18
+ const normalized = path.replaceAll("\\", "/").split("/").filter(part => part !== "." && part !== "").join("/");
19
+ const matches = (pattern: string) => new RegExp(`(?:^|/)${escape(pattern)}$`, platform === "win32" ? "i" : "").test(normalized);
20
+ return !SENSITIVE_PATH_EXCEPTIONS.some(matches) && SENSITIVE_PATH_PATTERNS.some(matches);
21
+ }
22
+
23
+ // Host wildcard '*' spans separators; include basename, slash and backslash
24
+ // forms for v1 too. V2 normalizes separators and folds case on Windows itself.
25
+ const hostGlobs = (pattern: string) => [...new Set([pattern, pattern.replaceAll("/", "\\"), `*/${pattern}`, `*\\${pattern.replaceAll("/", "\\")}`])];
26
+ export const SENSITIVE_PERMISSION_GLOBS = SENSITIVE_PATH_PATTERNS.flatMap(hostGlobs);
27
+ export const SENSITIVE_PERMISSION_EXCEPTIONS = SENSITIVE_PATH_EXCEPTIONS.flatMap(hostGlobs);
28
+
29
+ /** Expand prefix* minus prefix+suffix: Git cannot re-include an excluded file. */
30
+ function exceptSuffix(prefix: string, suffix: string): string[] {
31
+ return [prefix, ...[...suffix].flatMap((char, i) => {
32
+ const start = `${prefix}${suffix.slice(0, i)}`;
33
+ return [`${start}[!${char}]*`, ...(i > 0 ? [start] : [])];
34
+ }), `${prefix}${suffix}?*`];
35
+ }
36
+
37
+ /** Preserve env examples and public SSH keys without re-including private files. */
38
+ export function sensitiveGitPathspecs(platform: NodeJS.Platform = process.platform): string[] {
39
+ return SENSITIVE_PATH_PATTERNS.flatMap(pattern => {
40
+ const exception = SENSITIVE_PATH_EXCEPTIONS.find(value => pattern.endsWith("*") && value.startsWith(pattern.slice(0, -1)));
41
+ return exception ? exceptSuffix(pattern.slice(0, -1), exception.slice(pattern.length - 1)) : [pattern];
42
+ })
43
+ .map(pattern => `:(exclude,glob${platform === "win32" ? ",icase" : ""})**/${pattern}`);
44
+ }
45
+
46
+ /** Native v1/v2 grep's grouped `path:\n Line N: text` format. Drop entire
47
+ * sensitive blocks, including continuations, rather than editing match text. */
48
+ export function filterSensitiveGrep(text: string): string {
49
+ let blocked = false;
50
+ let withheld = 0;
51
+ const kept: string[] = [];
52
+ for (const line of text.split(/\r?\n/)) {
53
+ if (line.startsWith("(Results are truncated")) { kept.push(line); continue; }
54
+ const header = /^(\S.*):$/.exec(line);
55
+ if (header) blocked = isSensitivePath(header[1]!);
56
+ if (blocked) {
57
+ if (/^\s+Line \d+:/.test(line)) withheld++;
58
+ continue;
59
+ }
60
+ kept.push(line);
61
+ }
62
+ if (!withheld) return text;
63
+ return `${kept.join("\n").trimEnd()}\n${withheld} matches in sensitive files withheld; use read (asks for approval)`;
64
+ }
65
+
66
+ /** Decode Git's C-quoted UTF-8 filenames (including octal bytes). */
67
+ function gitPath(value: string): string {
68
+ if (!value.startsWith('"')) return value;
69
+ const bytes: number[] = [];
70
+ const body = value.slice(1, -1);
71
+ for (let i = 0; i < body.length;) {
72
+ const octal = /^\\([0-7]{1,3})/.exec(body.slice(i));
73
+ if (octal) { bytes.push(parseInt(octal[1]!, 8)); i += octal[0].length; continue; }
74
+ if (body[i] === "\\") {
75
+ const next = body[i + 1] ?? "";
76
+ const escaped: Record<string, string> = { t: "\t", n: "\n", r: "\r", b: "\b", f: "\f", v: "\v", a: "\x07" };
77
+ bytes.push(...Buffer.from(escaped[next] ?? next)); i += 2; continue;
78
+ }
79
+ const char = String.fromCodePoint(body.codePointAt(i)!);
80
+ bytes.push(...Buffer.from(char)); i += char.length;
81
+ }
82
+ return Buffer.from(bytes).toString("utf8");
83
+ }
84
+
85
+ /** Backstop for rename/quoted-path diffs, including sections cut by the output
86
+ * bound. Fixed a/b prefixes are imposed by the Git argv builder. */
87
+ export function filterSensitiveDiff(text: string): string {
88
+ return text.split(/(?=^diff --(?:git|cc|combined) |^commit [0-9a-f]{40,64}(?:\s|$))/m).map(section => {
89
+ if (!/^diff --(?:git|cc|combined) /.test(section)) return section;
90
+ const header = section.split("\n", 1)[0]!;
91
+ const paths: string[] = [];
92
+ if (header.startsWith("diff --git ")) {
93
+ const pair = /^("(?:\\.|[^"\\])*"|a\/.*?) ("(?:\\.|[^"\\])*"|b\/.*)$/.exec(header.slice(11));
94
+ if (!pair) return "[router_git] unparseable diff section withheld; use read (asks for approval)\n";
95
+ paths.push(gitPath(pair[1]!).slice(2), gitPath(pair[2]!).slice(2));
96
+ } else paths.push(gitPath(header.replace(/^diff --(?:cc|combined) /, "")));
97
+ for (const match of section.matchAll(/^(?:rename|copy) (?:from|to) (.*)$/gm)) paths.push(gitPath(match[1]!));
98
+ return paths.some(path => isSensitivePath(path))
99
+ ? "[router_git] sensitive diff section withheld; use read (asks for approval)\n" : section;
100
+ }).join("");
101
+ }
@@ -3,6 +3,8 @@ import type { RouterConfig } from "./config";
3
3
  import { fingerprintToolCall } from "../guard/fingerprint";
4
4
  import { DEFAULT_IDLE_TTL_MS } from "./idle-sweep";
5
5
  import type { DecisionFacts, LadderStepKind } from "../routing/outcomes/types";
6
+ import type { ChangedFile } from "../verify/dispatch";
7
+ import type { ReferenceState } from "../verify/types";
6
8
 
7
9
  // ---------------------------------------------------------------------------
8
10
  // Types
@@ -376,6 +378,25 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
376
378
  return subagentCapState.get(sessionID)?.tierName ?? null;
377
379
  },
378
380
 
381
+ /**
382
+ * The current dispatch round's honoured cap: "none" only for CAP:none with a
383
+ * reason: line, else a number; null for an untracked session. A resume
384
+ * re-registers and replaces it (QA-P15-1-3: the guard's reader signal).
385
+ */
386
+ getCap(sessionID: string): Cap | null {
387
+ return subagentCapState.get(sessionID)?.cap ?? null;
388
+ },
389
+
390
+ /**
391
+ * The current round's read-only counter reached its cap (calls >= a numeric
392
+ * cap). Captured when a task returns, it validates a `NEED MORE: budget`
393
+ * claim (QA-P15-2-2); false for CAP:none and untracked sessions.
394
+ */
395
+ readCapReached(sessionID: string): boolean {
396
+ const state = subagentCapState.get(sessionID);
397
+ return state !== undefined && state.cap !== "none" && state.calls >= state.cap;
398
+ },
399
+
379
400
  /** Returns true when the session was classified as trivial at dispatch time. */
380
401
  isTrivial(sessionID: string): boolean {
381
402
  return subagentCapState.get(sessionID)?.trivial === true;
@@ -421,6 +442,21 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
421
442
  touch(sessionID);
422
443
  },
423
444
 
445
+ /**
446
+ * #84 QA-P21-3-1: a routed resume of a role child (the host gives no chat.message for it): start a new dispatch round of its
447
+ * read-only counter, as a same-tier re-registration does — calls back to 0, `seen` and totalCalls kept, the previous cap kept
448
+ * unless the resume names one. False (nothing done) when the child has no read-only cap state.
449
+ */
450
+ resumeRoleSession(sessionID: string, cap: Cap | null): boolean {
451
+ const existing = subagentCapState.get(sessionID);
452
+ if (existing === undefined) return false;
453
+ if (cap !== null) existing.cap = cap;
454
+ existing.calls = 0;
455
+ existing.dispatches += 1;
456
+ touch(sessionID);
457
+ return true;
458
+ },
459
+
424
460
  /** Remove a session from tracking (used to clean up delegate producer sessions). */
425
461
  unregister(sessionID: string): void {
426
462
  evict(sessionID);
@@ -584,6 +620,31 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
584
620
  /** `routing.detection` keys: how strongly the dispatch's acceptance checks detect a failure (D8). */
585
621
  export type DetectionDepth = "deterministic" | "grader" | "none";
586
622
 
623
+ /**
624
+ * #84 QA-G-B-1: what a role dispatch's verification was built from — the first `[acceptance]` block of its prompt (verbatim lines)
625
+ * and its whole-line `VERIFY:` / `VERIFY_WAIT:` directives — so a resume that names none of its own ("continue and finish") is
626
+ * verified, and its tier floor computed, on the same acceptance as the dispatch it resumes.
627
+ */
628
+ export interface CarriedVerification {
629
+ readonly block: string;
630
+ readonly directives: readonly string[];
631
+ /** QA-G-B N-a: the route line's `d=` claim of the dispatch that introduced the block; absent: none. */
632
+ readonly claim?: DetectionDepth;
633
+ /**
634
+ * QA-G-B-2-1: the change baseline of the child's attempts under this block — set by the gate of the attempt that introduced it
635
+ * (its dispatch reference and change set), widened by every later attempt that carried it. Absent until that gate ran.
636
+ */
637
+ readonly baseline?: VerificationBaseline;
638
+ }
639
+
640
+ /** QA-G-B-2-1: what a carried acceptance is judged against (see {@link CarriedVerification}.baseline). */
641
+ export interface VerificationBaseline {
642
+ /** The dispatch reference of the attempt that introduced the block (its pre-existing failures are excused; later ones not). */
643
+ readonly reference: ReferenceState;
644
+ /** Every file the child changed in that attempt and every later one under the block; "unavailable" once any set was unknown. */
645
+ readonly changed: readonly ChangedFile[] | "unavailable";
646
+ }
647
+
587
648
  export interface DispatchInput {
588
649
  /** Typed task facts of the dispatch (1.2 `TaskFacts` is assignable). */
589
650
  facts: DecisionFacts;
@@ -625,6 +686,8 @@ export interface DispatchInput {
625
686
  * resume or a ladder attempt is a new execution and starts from nothing.
626
687
  */
627
688
  keepExecution?: boolean;
689
+ /** #84 QA-G-B-1, role dispatches only: the verification its resumes carry ({@link CarriedVerification}). Absent: none. */
690
+ verification?: CarriedVerification | null;
628
691
  }
629
692
 
630
693
  export interface DispatchRecord {
@@ -646,6 +709,8 @@ export interface DispatchRecord {
646
709
  /** See `DispatchInput.outcomes`: false = ingestion was off where this child was registered. */
647
710
  readonly outcomes: boolean;
648
711
  readonly registeredAt: number;
712
+ /** See `DispatchInput.verification`; present only on a role dispatch that carries one. */
713
+ readonly verification?: CarriedVerification;
649
714
  }
650
715
 
651
716
  interface DispatchSlot {
@@ -715,6 +780,8 @@ export function rememberDispatch(
715
780
  step: input.step ?? "dispatch",
716
781
  outcomes: input.outcomes ?? true,
717
782
  registeredAt: nowMs,
783
+ // Only when there is one: every other record keeps its exact shape.
784
+ ...(input.verification === undefined || input.verification === null ? {} : { verification: frozenVerification(input.verification) }),
718
785
  });
719
786
  // Delete first so a re-registration moves to the young end of the insertion order.
720
787
  // QA-2.3-1a: a registration of the same execution keeps what was observed of it (see `DispatchInput.keepExecution`).
@@ -733,6 +800,31 @@ export function rememberDispatch(
733
800
  return record;
734
801
  }
735
802
 
803
+ /** A frozen copy of a carried verification; `claim` and `baseline` only when present (a record keeps its exact shape). */
804
+ function frozenVerification(v: CarriedVerification): CarriedVerification {
805
+ return Object.freeze({
806
+ block: v.block,
807
+ directives: Object.freeze([...v.directives]),
808
+ ...(v.claim === undefined ? {} : { claim: v.claim }),
809
+ ...(v.baseline === undefined ? {} : {
810
+ baseline: Object.freeze({
811
+ reference: v.baseline.reference,
812
+ changed: v.baseline.changed === "unavailable" ? "unavailable" as const : Object.freeze(v.baseline.changed.map((f) => Object.freeze({ ...f }))),
813
+ }),
814
+ }),
815
+ });
816
+ }
817
+
818
+ /**
819
+ * #84 QA-G-B-2-1: replace the carried verification of a child's CURRENT registration — the same attempt (no new attempt id, nothing
820
+ * observed of the execution is reset), only its verification baseline moves on. Nothing when the child is not registered.
821
+ */
822
+ export function updateDispatchVerification(childSessionID: string, verification: CarriedVerification): void {
823
+ const slot = dispatchRegistry.get(childSessionID);
824
+ if (slot === undefined) return;
825
+ slot.record = Object.freeze({ ...slot.record, verification: frozenVerification(verification) });
826
+ }
827
+
736
828
  /** The registered dispatch of a child session, or undefined (unknown, forgotten or swept). */
737
829
  export function lookupDispatch(childSessionID: string): DispatchRecord | undefined {
738
830
  return dispatchRegistry.get(childSessionID)?.record;
@@ -11,6 +11,15 @@ export interface SubagentOverride {
11
11
  variant: string | undefined;
12
12
  }
13
13
 
14
+ /**
15
+ * Set (non-enumerable, `true`) on the config object the v2 adapter hands to the
16
+ * `config` hook while host agents may still be missing: the "no such agent"
17
+ * notice then waits for its first prompt-time check.
18
+ */
19
+ /** v2 only: non-enumerable `Set<string>` of agent names that came from the host setup seed (host built-ins). */
20
+ export const HOST_SEED_AGENTS = Symbol.for("opencode-model-router.host-seed-agents");
21
+ export const DEFER_MISSING_SUBAGENT_NOTICE = Symbol.for("opencode-model-router.defer-missing-subagent-notice");
22
+
14
23
  function isPlainObject(v: unknown): v is Record<string, unknown> {
15
24
  return typeof v === "object" && v !== null && !Array.isArray(v);
16
25
  }
@@ -39,8 +48,15 @@ export function resolveSubagentOverrides(input: {
39
48
  tiers: Preset;
40
49
  /** The opencode config's `agent` record, when already populated. */
41
50
  existingAgents?: Record<string, unknown>;
51
+ /**
52
+ * Names defined by the router `agents` block (#81). Their `tier` wins, so a
53
+ * `subagentTiers` entry for one of them is skipped.
54
+ */
55
+ pluginAgents?: Record<string, unknown>;
56
+ /** Called for each skipped name whose agent does not exist (phantom) or is plugin-defined. */
57
+ onSkip?: (agentName: string, reason: "missing" | "plugin-agent") => void;
42
58
  }): Record<string, SubagentOverride> {
43
- const { subagentTiers, tiers, existingAgents } = input;
59
+ const { subagentTiers, tiers, existingAgents, pluginAgents, onSkip } = input;
44
60
  if (!isPlainObject(subagentTiers)) return {};
45
61
 
46
62
  const out: Record<string, SubagentOverride> = {};
@@ -55,6 +71,17 @@ export function resolveSubagentOverrides(input: {
55
71
  const tier = tiers[tierName];
56
72
  if (!tier || typeof tier.model !== "string" || tier.model === "") continue;
57
73
 
74
+ if (isPlainObject(pluginAgents) && Object.hasOwn(pluginAgents, agentName)) {
75
+ onSkip?.(agentName, "plugin-agent");
76
+ continue;
77
+ }
78
+ // A name that no agent record carries would be created from nothing: a
79
+ // phantom agent with only a model. Only checked when the record is known.
80
+ if (isPlainObject(existingAgents) && !Object.hasOwn(existingAgents, agentName)) {
81
+ onSkip?.(agentName, "missing");
82
+ continue;
83
+ }
84
+
58
85
  const existing = existingAgents?.[agentName];
59
86
  if (isPlainObject(existing) && typeof existing.mode === "string") {
60
87
  if (existing.mode !== "subagent") continue;
@@ -23,6 +23,8 @@ import { DEFAULT_VARIANT, catalogVariantIds, nextVariant, variantCovered, varian
23
23
  import type { VariantLadder } from "../../escalate/variants";
24
24
  import { CLASS_STATIC_TIER } from "../classify/types";
25
25
  import { isUnpriced, selectPriceEntry } from "../outcomes/cost";
26
+ import type { RoleStatsTable } from "../outcomes/types";
27
+ import { resolveRoleTable } from "../../router/roles";
26
28
 
27
29
  // ---------------------------------------------------------------------------
28
30
  // Types
@@ -49,6 +51,14 @@ export const FINDING_IDS = [
49
51
  "native-role-unmatched-rung",
50
52
  "tier-agent-unavailable",
51
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",
52
62
  ] as const;
53
63
  export type FindingId = (typeof FINDING_IDS)[number];
54
64
 
@@ -74,6 +84,14 @@ export const FINDING_TARGET: Readonly<Record<FindingId, FindingTarget>> = {
74
84
  "native-role-unmatched-rung": "router",
75
85
  "tier-agent-unavailable": "router",
76
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",
77
95
  };
78
96
 
79
97
  export interface Finding {
@@ -238,7 +256,26 @@ function activeTierEntries(cfg: RouterConfig): Array<[string, TierConfig]> {
238
256
  return Object.entries(getActiveTiers(cfg) ?? {}).filter(([, tier]) => tier !== null && typeof tier === "object" && typeof tier.model === "string" && tier.model !== "");
239
257
  }
240
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
+
241
277
  interface CheckInput {
278
+ readonly extras: AdvisorExtras;
242
279
  readonly cfg: RouterConfig;
243
280
  readonly host: HostConfigView | null;
244
281
  readonly catalog: readonly AdvisorCatalogModel[] | null;
@@ -608,6 +645,152 @@ const classifierModel: Check = ({ cfg, byRef }) => {
608
645
  }];
609
646
  };
610
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
+
611
794
  const CHECKS: ReadonlyArray<readonly [string, Check]> = [
612
795
  ["title-model", titleModel],
613
796
  ["ladder-catalog", ladderCatalog],
@@ -619,6 +802,14 @@ const CHECKS: ReadonlyArray<readonly [string, Check]> = [
619
802
  ["native-roles", nativeRoles],
620
803
  ["tier-agents", tierAgents],
621
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],
622
813
  ];
623
814
 
624
815
  /**
@@ -682,9 +873,10 @@ export function runChecks(
682
873
  host: HostConfigView | null,
683
874
  catalog: readonly AdvisorCatalogModel[] | null,
684
875
  onError: (check: string, error: unknown) => void,
876
+ extras: AdvisorExtras = {},
685
877
  ): Finding[] {
686
878
  const known = catalog !== null && catalog.length > 0 ? catalog : null;
687
- const input: CheckInput = { cfg, host, catalog: known, byRef: known === null ? null : index(known) };
879
+ const input: CheckInput = { cfg, host, catalog: known, byRef: known === null ? null : index(known), extras };
688
880
  const out: Array<{ finding: Finding; order: number }> = [];
689
881
  let order = 0;
690
882
  for (const [name, check] of CHECKS) {
@@ -27,10 +27,12 @@ import { nodePersistFs, renameWithRetry, resolveOutcomesDir } from "../outcomes/
27
27
  import type { PersistFs } from "../outcomes/types";
28
28
  import { agentModelRef } from "../wire/host-info";
29
29
  import { runChecks } from "./findings";
30
+ import type { AdvisorExtras } from "./findings";
30
31
  import type { AdvisorCatalogModel, Finding, FindingTarget, HostAgentView, HostConfigView } from "./findings";
31
32
 
32
33
  export { FINDING_IDS, FINDING_TARGET, HOST_SMALL_MODEL_FAMILIES, SUBSCRIPTION_PROVIDERS, cheapestTitleModel, hostSmallModel, splitModelRef } from "./findings";
33
- export type { AdvisorCatalogModel, Finding, FindingId, FindingSeverity, FindingTarget, HostAgentView, HostConfigView } from "./findings";
34
+ export { ROLE_BUDGET_LOW_SHARE, ROLE_STATS_MIN_DISPATCHES } from "./findings";
35
+ export type { AdvisorExtras, AdvisorCatalogModel, Finding, FindingId, FindingSeverity, FindingTarget, HostAgentView, HostConfigView } from "./findings";
34
36
 
35
37
  export interface AdvisorLogger {
36
38
  warn(message: string, extra?: Record<string, unknown>): void;
@@ -57,11 +59,12 @@ export function runAdvisor(
57
59
  hostConfig: HostConfigView | null,
58
60
  catalog: readonly AdvisorCatalogModel[] | null,
59
61
  logger?: AdvisorLogger,
62
+ extras: AdvisorExtras = {},
60
63
  ): Finding[] {
61
64
  try {
62
65
  return runChecks(cfg, hostConfig, catalog, (check, error) => {
63
66
  logger?.warn(`[router] cost doctor: check ${check} failed`, { error: describeError(error) });
64
- });
67
+ }, extras);
65
68
  } catch (error) {
66
69
  logger?.warn("[router] cost doctor: the advisor failed", { error: describeError(error) });
67
70
  return [];
@@ -318,7 +321,12 @@ export interface AdvisorNotifierDeps {
318
321
  readonly settings: () => AdvisorSettings | null;
319
322
  readonly config: () => RouterConfig;
320
323
  /** The host's agents and catalog; either may be `null` (unknown). May reject. */
321
- readonly gather: () => Promise<{ readonly host: HostConfigView | null; readonly catalog: readonly AdvisorCatalogModel[] | null }>;
324
+ readonly gather: () => Promise<{
325
+ readonly host: HostConfigView | null;
326
+ readonly catalog: readonly AdvisorCatalogModel[] | null;
327
+ /** Host generation and role statistics for the roles checks; absent = those checks stay silent. */
328
+ readonly extras?: AdvisorExtras;
329
+ }>;
322
330
  readonly logger: AdvisorLogger;
323
331
  readonly now?: () => number;
324
332
  readonly fs?: AdvisorFs;
@@ -435,8 +443,8 @@ export function createAdvisorNotifier(deps: AdvisorNotifierDeps): AdvisorNotifie
435
443
  };
436
444
 
437
445
  const produce = async (): Promise<{ text: string | null; keys: string[] }> => {
438
- const { host, catalog } = await deps.gather();
439
- const findings = runAdvisor(deps.config(), host, catalog, deps.logger);
446
+ const { host, catalog, extras } = await deps.gather();
447
+ const findings = runAdvisor(deps.config(), host, catalog, deps.logger, extras);
440
448
  return { text: noticeWorthy(findings) ? formatNotice(findings) : null, keys: keysOf(findings) };
441
449
  };
442
450
 
@@ -20,7 +20,9 @@ import {
20
20
  } from "./backends/shared";
21
21
  import { createTypeSafeBackend } from "./backends/typesafe";
22
22
  import { applyRouteLine, parseRouteLine, type RouteLinePositions } from "./route-line";
23
- import { analyzeRules } from "./rules";
23
+ import { analyzeRules, needMatchesOf, type NeedMatch } from "./rules";
24
+
25
+ export type { NeedMatch } from "./rules";
24
26
  import { hasCredentialSignal } from "./scrub";
25
27
  import { buildClassifierState, classifierStateRawParts } from "./state";
26
28
  import {
@@ -269,13 +271,27 @@ function routeLineOptions(deps: ClassifyDeps): { readonly positions: RouteLinePo
269
271
  return { positions: deps.routeLinePositions ?? "first" };
270
272
  }
271
273
 
272
- /** Steps 1–3: route line, rules, route line applied. */
273
- function prepare(input: ClassifyInput, deps: ClassifyDeps): Prepared {
274
- const parsed = parseRouteLine(typeof input.prompt === "string" ? input.prompt : "", routeLineOptions(deps));
274
+ /** The text the rules layer reads: the description, then the prompt without its route lines. */
275
+ function ruleTextOf(input: ClassifyInput, parsed: RouteLineParse): string {
275
276
  const description = typeof input.description === "string" ? input.description.trim() : "";
276
- const ruleText = [description.slice(0, RULES_MAX_CHARS), parsed.stripped.slice(0, RULES_MAX_CHARS)]
277
+ return [description.slice(0, RULES_MAX_CHARS), parsed.stripped.slice(0, RULES_MAX_CHARS)]
277
278
  .filter(Boolean)
278
279
  .join("\n");
280
+ }
281
+
282
+ /**
283
+ * #84 QA-G-B-3: the needs the rules layer finds in the text of `input` itself, and why (rules.ts `needMatchesOf` on the same text
284
+ * and `cwd` as `classify`; never the class-implied needs). Never calls a backend.
285
+ */
286
+ export function classifyNeedMatches(input: ClassifyInput, deps: Pick<ClassifyDeps, "routeLinePositions">): NeedMatch[] {
287
+ const parsed = parseRouteLine(typeof input.prompt === "string" ? input.prompt : "", { positions: deps.routeLinePositions ?? "first" });
288
+ return needMatchesOf(ruleTextOf(input, parsed), { ...(input.cwd === undefined ? {} : { cwd: input.cwd }) });
289
+ }
290
+
291
+ /** Steps 1–3: route line, rules, route line applied. */
292
+ function prepare(input: ClassifyInput, deps: ClassifyDeps): Prepared {
293
+ const parsed = parseRouteLine(typeof input.prompt === "string" ? input.prompt : "", routeLineOptions(deps));
294
+ const ruleText = ruleTextOf(input, parsed);
279
295
  const analysis = analyzeRules(ruleText, deps.cfg, { cwd: input.cwd });
280
296
  const rules = analysis.facts;
281
297
  const facts = parsed.line ? applyRouteLine(rules, parsed.line) : rules;
@@ -325,6 +341,8 @@ function resultOf(
325
341
  count: prepared.parsed.count,
326
342
  conflict: prepared.parsed.conflict,
327
343
  edgeOnly: prepared.parsed.edgeOnly,
344
+ // QA-P12-2-2 (P2.1): surface a malformed first route line; absent otherwise (tier rows copy only the three fields above).
345
+ ...(prepared.parsed.malformed === true ? { malformed: true as const } : {}),
328
346
  },
329
347
  ...(skipped ? { backendSkipped: skipped } : {}),
330
348
  backend: