opencode-model-router 2.3.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 (61) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/README.md +56 -10
  3. package/package.json +1 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1322 -18
  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/v2.ts +26 -1
  54. package/src/verify/checker.ts +249 -7
  55. package/src/verify/deterministic.ts +10 -1
  56. package/src/verify/dispatch.ts +63 -6
  57. package/src/verify/dod.ts +127 -10
  58. package/src/verify/gate.ts +75 -7
  59. package/src/verify/types.ts +12 -0
  60. package/src/verify/wiring.ts +55 -10
  61. package/tiers.json +13 -5
@@ -17,12 +17,14 @@
17
17
  import {
18
18
  ROUTING_RESERVED_AGENTS,
19
19
  resolveCandidates,
20
+ resolveActiveTiers,
20
21
  resolvePresetName,
21
22
  type ResolvedRouting,
22
23
  type ResolvedCandidate,
23
24
  type RouterConfig,
24
25
  type TierConfig,
25
26
  } from "../../router/config";
27
+ import { presetTierOrder } from "../../router/roles";
26
28
  import { buildEscalatePolicy, type EscalatePolicy, type LadderSessionPolicyInput } from "../../escalate/ladder";
27
29
  import { variantCovered } from "../../escalate/variants";
28
30
  import { CLASS_STATIC_TIER, NEEDS, type Need, type TaskFacts } from "../classify/types";
@@ -37,6 +39,10 @@ import type {
37
39
  ExclusionReason,
38
40
  HostAgentInfo,
39
41
  Ladder,
42
+ PresetRung,
43
+ RoleLadder,
44
+ RoleLadderTier,
45
+ RoleWindow,
40
46
  } from "./types";
41
47
 
42
48
  // ---------------------------------------------------------------------------
@@ -202,7 +208,7 @@ function tryWarn(logger: LadderBuildInput["logger"], message: string): boolean {
202
208
  }
203
209
 
204
210
  /** QA-1.4-10: the catalog lookup is the caller's code; a failure makes the model unpriced (A1), never a throw. */
205
- function priced(input: LadderBuildInput, model: string): { readonly pricing?: ModelPricing } {
211
+ function priced(input: Pick<LadderBuildInput, "pricing" | "logger">, model: string): { readonly pricing?: ModelPricing } {
206
212
  if (input.pricing === undefined) return {};
207
213
  try {
208
214
  return { pricing: input.pricing(model) };
@@ -511,6 +517,241 @@ export function buildLadder(input: LadderBuildInput): Ladder {
511
517
  presetRungs: presetRungs.map((rung) => ({ model: rung.model, variant: rung.variant, rank: rung.rank })),
512
518
  };
513
519
  }
520
+
521
+ // ---------------------------------------------------------------------------
522
+ // Role ladders (role-tier-assurance plan §2.1, §2.3, P1.2 T1.2.3)
523
+ // ---------------------------------------------------------------------------
524
+
525
+ export interface RoleLadderInput {
526
+ readonly cfg: RouterConfig;
527
+ readonly facts: Pick<TaskFacts, "class" | "needs">;
528
+ /** The role agent (outcome-key origin `role`). */
529
+ readonly role: string;
530
+ /** `roles/policy.tierBounds(...)` computed with `tiers: escalateLadder(cfg)`. */
531
+ readonly window: RoleWindow;
532
+ /** The class's taxonomy tier; absent = `CLASS_STATIC_TIER[facts.class]` (`null` → the window floor). */
533
+ readonly classTier?: string | null;
534
+ readonly pricing?: (model: string) => ModelPricing;
535
+ readonly logger?: { warn(message: string): void };
536
+ /** The input the runner's policy is built with (same meaning as {@link LadderBuildInput.session}). */
537
+ readonly session?: LadderSessionPolicyInput;
538
+ }
539
+
540
+ interface WindowSpan {
541
+ readonly floor: number;
542
+ readonly ceiling: number;
543
+ readonly reasons: readonly string[];
544
+ }
545
+
546
+ /**
547
+ * The window on the escalate ladder `order`. Fail closed: a floor off the ladder places nothing (`null`, no candidate);
548
+ * a ceiling off the ladder or below the floor collapses to the floor (the narrowest window that keeps the floor).
549
+ */
550
+ function windowSpan(order: readonly string[], window: Pick<RoleWindow, "floor" | "ceiling">): WindowSpan | null {
551
+ const floor = order.indexOf(window.floor);
552
+ if (floor < 0) return null;
553
+ const ceiling = order.indexOf(window.ceiling);
554
+ if (ceiling < 0) return { floor, ceiling: floor, reasons: [`window:ceiling-off-ladder:${window.ceiling}`] };
555
+ if (ceiling < floor) return { floor, ceiling: floor, reasons: ["window:ceiling-below-floor"] };
556
+ return { floor, ceiling, reasons: [] };
557
+ }
558
+
559
+ /**
560
+ * The tier order of every role dispatch (QA-P12-1-5, plan R7): `presetTierOrder` of the active preset (cheapest to
561
+ * dearest by `costRatio`, else listing order — the order role tier ranges are placed on), restricted to tiers with at
562
+ * least one rung. Pass it as `tierBounds(..., { tiers })` AND build the
563
+ * ladder with the same `cfg`/`session` ({@link buildRoleLadder}, {@link roleEscalatePolicy} use it), so the window and
564
+ * the ladder can never disagree on tier names.
565
+ */
566
+ export function roleTierOrder(cfg: RouterConfig, _session?: LadderSessionPolicyInput): readonly string[] {
567
+ // One tier order for role ranges (`router/roles.ts`) and role ladders: the active preset's cost order. The only
568
+ // narrowing is the one every ladder applies: tiers without a rung are left out. The session never changes tiers.
569
+ return ladderOf(cfg, presetTierOrder(resolveActiveTiers(cfg)));
570
+ }
571
+
572
+ /**
573
+ * The escalation policy of a role dispatch, as the runtime escalates one (QA-G-B-6): after a verification FAIL the router raises
574
+ * the child to the NEXT tier of the role's range on its next resume (`roleEscalationAfterFail` / `nextRoleTier`, dispatch.ts) —
575
+ * one tier per FAIL, never a retry on the same tier, no variant step, no effort bump, no attempt or cost ceiling — and nothing
576
+ * above the ceiling. So: the ladder = the tiers of `[floor, ceiling]` on {@link roleTierOrder}, `floorTier` = the window floor
577
+ * (the runner never starts below the floor nor escalates above the ceiling, I2), `maxAttemptsPerTier` 0, `maxTotalAttempts` =
578
+ * one attempt per tier of the window, no `costMultiple`, `effortBump` or `variants`. {@link buildRoleLadder}'s simulated paths
579
+ * price role candidates with this one policy, so they price exactly the raise path the runtime takes (one attempt on each tier
580
+ * from the start tier up to the ceiling, each on the tier's base rung). `null` when the floor is not on the order: P2.1 then
581
+ * refuses the role dispatch — it never falls back to the unrestricted `buildEscalatePolicy`. (`session` only names the tier
582
+ * order's input; the session's variant steps never apply to a role dispatch.)
583
+ */
584
+ export function roleEscalatePolicy(
585
+ cfg: RouterConfig,
586
+ window: Pick<RoleWindow, "floor" | "ceiling">,
587
+ session?: LadderSessionPolicyInput,
588
+ ): EscalatePolicy | null {
589
+ const order = roleTierOrder(cfg, session);
590
+ const span = windowSpan(order, window);
591
+ if (span === null) return null;
592
+ const ladder = order.slice(span.floor, span.ceiling + 1);
593
+ return { ladder, floorTier: order[span.floor]!, maxAttemptsPerTier: 0, maxTotalAttempts: ladder.length, costMultiple: null };
594
+ }
595
+
596
+ /**
597
+ * Build the candidate graph of a role dispatch (T1.2.3).
598
+ *
599
+ * - Candidates: for every tier of the escalate ladder in `[floor, ceiling]` (tier order, then rung order), the rungs on
600
+ * the tier's own model (A25; other-model rungs are `not-modelled`), each run by the role agent (`origin: "role"`) at
601
+ * the tier's rank. A `model#variant` already listed on a lower tier is the same outcome key: kept once (`duplicate`).
602
+ * - Grants: every rung runs the same agent under the same dispatch grant, so `grants` = `facts.needs` (needs a grant
603
+ * cannot cover are reported by `grantFor` notes, not by the kernel's per-rung `needs` filter).
604
+ * - Paths: the attempts the runner makes under {@link roleEscalatePolicy} (`simulateRunner`), as indices into
605
+ * `[...candidates, ...reachable]`.
606
+ * - Static default: the class's taxonomy tier clamped into the window (`default:clamp:floor|ceiling`); no class tier or
607
+ * one off the ladder → the floor. Pin: `window.pinned` (re-clamped defensively, `pin:clamp`), reason `pinned:<tier>`.
608
+ *
609
+ * Never throws for well-typed input; a window that cannot be placed yields an empty ladder (`window:floor-off-ladder`).
610
+ */
611
+ export function buildRoleLadder(input: RoleLadderInput): RoleLadder {
612
+ const { cfg, facts, role } = input;
613
+ const order = roleTierOrder(cfg, input.session);
614
+ const agent: AgentRef = { origin: "role", id: role };
615
+ const grants: readonly Need[] = [...facts.needs];
616
+ const classTier = input.classTier !== undefined
617
+ ? input.classTier
618
+ : (Object.hasOwn(CLASS_STATIC_TIER, facts.class) ? CLASS_STATIC_TIER[facts.class] : null);
619
+ const classAt = typeof classTier === "string" ? order.indexOf(classTier) : -1;
620
+ const classRank = classAt >= 0 ? classAt : null;
621
+ const presetRungs: PresetRung[] = [];
622
+ order.forEach((tier, rank) => {
623
+ for (const rung of resolveCandidates(tier, cfg)) presetRungs.push({ model: rung.model, variant: normalizedVariant(rung.variant), rank });
624
+ });
625
+
626
+ const span = windowSpan(order, input.window);
627
+ // QA-P12-1-7: the one source of the window's policy (the same call the role runner makes).
628
+ const rolePolicy = roleEscalatePolicy(cfg, input.window, input.session);
629
+ if (span === null || rolePolicy === null) {
630
+ return {
631
+ role,
632
+ candidates: [],
633
+ next: [],
634
+ classRank,
635
+ excluded: [],
636
+ paths: [],
637
+ presetRungs,
638
+ floorRank: null,
639
+ ceilingRank: null,
640
+ tiers: [],
641
+ staticDefault: null,
642
+ pinnedIndex: null,
643
+ reasons: [`window:floor-off-ladder:${input.window.floor}`, "window:no-candidates"],
644
+ };
645
+ }
646
+
647
+ // --- candidates: the window's tiers, cheapest first --------------------------------------------------
648
+ const candidates: Candidate[] = [];
649
+ const excluded: ExcludedCandidate[] = [];
650
+ const tiers: RoleLadderTier[] = [];
651
+ const roleRung = (rung: { readonly model: string; readonly variant: string | null; readonly costRatio: number }, tier: string, rank: number): Candidate => ({
652
+ agent,
653
+ model: rung.model,
654
+ variant: normalizedVariant(rung.variant),
655
+ costRatio: rung.costRatio,
656
+ rank,
657
+ tier,
658
+ source: "role-range",
659
+ grants,
660
+ ...priced(input, rung.model),
661
+ });
662
+ for (let rank = span.floor; rank <= span.ceiling; rank++) {
663
+ const tier = order[rank]!;
664
+ const { kept, dropped } = modelledRungs(cfg, tier);
665
+ for (const rung of dropped) excluded.push({ agent, model: rung.model, variant: normalizedVariant(rung.variant), why: "not-modelled" });
666
+ let first: number | null = null;
667
+ for (const rung of kept) {
668
+ const candidate = roleRung({ model: rung.model, variant: normalizedVariant(rung.variant), costRatio: rung.costRatio }, tier, rank);
669
+ if (candidates.some((c) => sameRung(c, candidate))) {
670
+ excluded.push({ agent, model: candidate.model, variant: candidate.variant, why: "duplicate" });
671
+ continue;
672
+ }
673
+ first ??= candidates.length;
674
+ candidates.push(candidate);
675
+ }
676
+ tiers.push({ tier, rank, first });
677
+ }
678
+
679
+ // --- simulated runner paths under the window's policy ----------------------------------------------------
680
+ const reachable: Candidate[] = [];
681
+ const indexOfRung = (rung: RunnerRung): number | null => {
682
+ const same = (c: Candidate): boolean => c.tier === rung.tier && sameRung(c, rung);
683
+ const at = candidates.findIndex(same);
684
+ if (at >= 0) return at;
685
+ const known = reachable.findIndex(same);
686
+ if (known >= 0) return candidates.length + known;
687
+ const rank = order.indexOf(rung.tier);
688
+ if (rank < span.floor || rank > span.ceiling) return null; // unreachable under the window policy; defensive
689
+ reachable.push(roleRung(rung, rung.tier, rank));
690
+ return candidates.length + reachable.length - 1;
691
+ };
692
+ const paths = candidates.map((start) => {
693
+ const path: number[] = [];
694
+ for (const attempt of simulateRunner(rolePolicy, (tier) => tierBaseRung(cfg, tier), start)) {
695
+ const j = indexOfRung(attempt);
696
+ if (j === null) break;
697
+ path.push(j);
698
+ }
699
+ return path.length > 0 ? path : null;
700
+ });
701
+
702
+ // --- static default and pin --------------------------------------------------------------------------------
703
+ const reasons: string[] = [...span.reasons];
704
+ if (candidates.length === 0) reasons.push("window:no-candidates");
705
+ /** First candidate of the first tier at or above `rank` that has one, else of the highest tier below it. */
706
+ const candidateAt = (rank: number): number | null => {
707
+ for (const t of tiers) if (t.rank >= rank && t.first !== null) return t.first;
708
+ for (let i = tiers.length - 1; i >= 0; i--) if (tiers[i]!.first !== null) return tiers[i]!.first;
709
+ return null;
710
+ };
711
+ let target = span.floor;
712
+ if (classRank === null) reasons.push(typeof classTier === "string" ? `default:off-ladder:${classTier}` : "default:no-class-tier");
713
+ else if (classRank < span.floor) reasons.push("default:clamp:floor");
714
+ else if (classRank > span.ceiling) {
715
+ target = span.ceiling;
716
+ reasons.push("default:clamp:ceiling");
717
+ } else target = classRank;
718
+ const staticDefault = candidateAt(target);
719
+
720
+ let pinnedIndex: number | null = null;
721
+ const pin = input.window.pinned;
722
+ if (pin !== null) {
723
+ const at = order.indexOf(pin);
724
+ if (at < 0) reasons.push(`pin:off-ladder:${pin}`);
725
+ else {
726
+ const clamped = Math.min(Math.max(at, span.floor), span.ceiling);
727
+ if (clamped !== at) reasons.push("pin:clamp");
728
+ pinnedIndex = candidateAt(clamped);
729
+ if (pinnedIndex !== null) {
730
+ // QA-P12-1-8: say so when the dispatched rung is not on the requested tier (clamped, or a duplicate rung).
731
+ const got = candidates[pinnedIndex]!.tier;
732
+ reasons.push(got === pin ? `pinned:${pin}` : `pinned:${pin}->${got}`);
733
+ }
734
+ }
735
+ }
736
+
737
+ return {
738
+ role,
739
+ candidates,
740
+ next: candidates.map(() => null),
741
+ classRank,
742
+ excluded,
743
+ ...(reachable.length > 0 ? { reachable } : {}),
744
+ paths,
745
+ presetRungs,
746
+ floorRank: span.floor,
747
+ ceilingRank: span.ceiling,
748
+ tiers,
749
+ staticDefault,
750
+ pinnedIndex,
751
+ reasons,
752
+ };
753
+ }
754
+
514
755
  // ---------------------------------------------------------------------------
515
756
  // resolveChosen
516
757
  // ---------------------------------------------------------------------------
@@ -12,11 +12,15 @@
12
12
  * least {@link MIN_EVIDENCE_TO_MOVE} effective evidence. Priors alone can move a class in the kernel
13
13
  * (e.g. `margin: 0`), so the evidence gate is what keeps the line static until data exists.
14
14
  *
15
+ * v2 roles mode (plan #84 T2.2.1): with a non-empty role table the line maps class → role agent
16
+ * ({@link generateRolesTaxonomy}); tiers mode and v1 never pass one, so their line is unchanged.
17
+ *
15
18
  * Pure: no I/O, no clock, no randomness, no module state.
16
19
  */
17
20
 
18
21
  import type { ResolvedRouting, RouterConfig, RouterHost } from "../../router/config";
19
22
  import { buildTaskTaxonomy } from "../../router/protocol";
23
+ import type { RoleSpec } from "../../router/roles";
20
24
  import {
21
25
  CLASS_BASE_RISK,
22
26
  CLASS_IMPLIED_NEEDS,
@@ -28,6 +32,7 @@ import type { ModelPricing } from "../outcomes/types";
28
32
  import { MIN_EVIDENCE_TO_SWITCH_DOWN, decide, hasMinEvidence } from "./kernel";
29
33
  import { buildLadder, type LadderBuildInput, floorRankOf, resolveChosen, roleAgentExclusion, routerTierIds, tierRankOf } from "./ladders";
30
34
  import type { EngineStoreView, HostAgentInfo } from "./types";
35
+ import { generateRolesTaxonomy } from "./roles-taxonomy";
31
36
 
32
37
  /** `best` must carry evidence at least as strong as the prior before a class line moves (= `PRIOR_STRENGTH`). */
33
38
  export const MIN_EVIDENCE_TO_MOVE: number = MIN_EVIDENCE_TO_SWITCH_DOWN;
@@ -43,8 +48,16 @@ export interface TaxonomyInput {
43
48
  readonly session?: LadderBuildInput["session"];
44
49
  readonly parentModel?: string | null;
45
50
  readonly logger?: LadderBuildInput["logger"];
51
+ /**
52
+ * v2 roles mode (T2.2.1): the enabled role agents (`resolveRoles`). A non-empty table makes the line the
53
+ * class → role map of {@link generateRolesTaxonomy}; absent or empty, the tier line below is unchanged.
54
+ */
55
+ readonly roles?: ReadonlyMap<string, RoleSpec>;
46
56
  }
47
57
 
58
+ /** The class → role line lives in a leaf module (QA-P22-1-11); re-exported here as part of the `R:` line API. */
59
+ export { CLASS_ROLE_KIND, generateRolesTaxonomy } from "./roles-taxonomy";
60
+
48
61
  function ownRoleList(roles: Readonly<Record<string, readonly string[]>>, cls: string): readonly string[] {
49
62
  const list = Object.hasOwn(roles, cls) ? roles[cls] : undefined;
50
63
  return Array.isArray(list) ? [...new Set(list)] : [];
@@ -118,6 +131,10 @@ function v2Segments(input: TaxonomyInput, store: EngineStoreView): string[] {
118
131
  * line (`R: by class: …`) where the taxonomy would go, and only when it is non-empty.
119
132
  */
120
133
  export function generateTaxonomy(input: TaxonomyInput): string {
134
+ if (input.host === "v2" && input.roles !== undefined) {
135
+ const roleLine = generateRolesTaxonomy(input.roles);
136
+ if (roleLine !== "") return roleLine; // roles mode: class → role, never a tier
137
+ }
121
138
  const base = buildTaskTaxonomy(input.cfg);
122
139
  let segments: string[];
123
140
  if (input.host === "v1") {
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The roles-mode `R:` line (plan #84 T2.2.1): task class → role agent.
3
+ *
4
+ * A leaf module (QA-P22-1-11): it imports only `TASK_CLASSES` and types, so `src/router/protocol.ts` can build the
5
+ * roles protocol without importing the routing engine (`protocol-line.ts` imports `protocol.ts`, which would make a
6
+ * cycle). `protocol-line.ts` re-exports both names.
7
+ *
8
+ * Pure: no I/O, no clock, no randomness, no module state.
9
+ */
10
+
11
+ import type { RoleKind, RoleSpec } from "../../router/roles";
12
+ import { TASK_CLASSES, type TaskClass } from "../classify/types";
13
+
14
+ /**
15
+ * The role kind that does each task class in roles mode (plan §2.2). `runner` and `researcher` have no class of
16
+ * their own: the orchestrator picks them by intent (running checks, web research) from the role menu.
17
+ */
18
+ export const CLASS_ROLE_KIND: Readonly<Record<TaskClass, RoleKind>> = Object.freeze({
19
+ search: "explore",
20
+ recon: "explore",
21
+ mechanical: "implement",
22
+ implement: "implement",
23
+ debug: "implement",
24
+ design: "design",
25
+ review: "review",
26
+ other: "general",
27
+ });
28
+
29
+ /**
30
+ * The roles-mode `R:` line: each class → the enabled role agent of {@link CLASS_ROLE_KIND}, else `general`, else
31
+ * the class is left out. Classes sharing an agent are grouped (`search/recon→explorer`), in `TASK_CLASSES` order;
32
+ * of two enabled agents of one kind the first by name wins. Depends on the table only (no tiers, no models, no
33
+ * evidence), so the text is stable for the whole session. "" when no class has an agent.
34
+ */
35
+ export function generateRolesTaxonomy(roles: ReadonlyMap<string, RoleSpec>): string {
36
+ const byKind = new Map<RoleKind, string>();
37
+ for (const spec of roles.values()) {
38
+ if (spec.enabled !== true) continue;
39
+ const held = byKind.get(spec.kind);
40
+ if (held === undefined || spec.agent < held) byKind.set(spec.kind, spec.agent);
41
+ }
42
+ const groups = new Map<string, TaskClass[]>();
43
+ for (const cls of TASK_CLASSES) {
44
+ const agent = byKind.get(CLASS_ROLE_KIND[cls]) ?? byKind.get("general");
45
+ if (agent === undefined) continue;
46
+ const classes = groups.get(agent);
47
+ if (classes === undefined) groups.set(agent, [cls]);
48
+ else classes.push(cls);
49
+ }
50
+ if (groups.size === 0) return "";
51
+ return `R: ${[...groups].map(([agent, classes]) => `${classes.join("/")}→${agent}`).join(" ")}`;
52
+ }
@@ -14,7 +14,9 @@
14
14
  */
15
15
 
16
16
  import type { ResolvedRouting } from "../../router/config";
17
+ import type { ExplorationConfig } from "../../router/roles";
17
18
  import type { Detection, Need, TaskFacts } from "../classify/types";
19
+ import type { ClassifiedDispatch, EffectiveDetection } from "../roles/policy";
18
20
  import type {
19
21
  AgentRef,
20
22
  CostUnit,
@@ -34,7 +36,7 @@ import type {
34
36
  * - `role-tier-rung` — a `routing.roles` agent on a rung of the tier that owns the class
35
37
  * (applied at dispatch by a per-call `model` override).
36
38
  */
37
- export type CandidateSource = "tier" | "role-own-model" | "role-tier-rung";
39
+ export type CandidateSource = "tier" | "role-own-model" | "role-tier-rung" | "role-range";
38
40
 
39
41
  /** One `(agent, model#variant)` the engine may dispatch, with what the kernel needs to price it. */
40
42
  export interface Candidate {
@@ -268,3 +270,99 @@ export interface Decision {
268
270
  */
269
271
  readonly pickRank: number | null;
270
272
  }
273
+
274
+ // ---------------------------------------------------------------------------
275
+ // Role dispatches (role-tier-assurance plan §2.1, §2.3, P1.2 T1.2.3/T1.2.4) — additive
276
+ // ---------------------------------------------------------------------------
277
+
278
+ /**
279
+ * The tier window of one role dispatch, as `roles/policy.tierBounds` returns it (tier names of the escalate ladder):
280
+ * `floor`/`ceiling` already include the authority floor, `floorTier` and the running rung; `pinned` is the route-line
281
+ * `tier=` already lifted or clamped into the window (null = no pin).
282
+ */
283
+ export interface RoleWindow {
284
+ readonly floor: string;
285
+ readonly ceiling: string;
286
+ readonly pinned: string | null;
287
+ }
288
+
289
+ /** One tier of a role ladder: its rank on the escalate ladder and its first candidate (`null` when every rung was a duplicate). */
290
+ export interface RoleLadderTier {
291
+ readonly tier: string;
292
+ readonly rank: number;
293
+ readonly first: number | null;
294
+ }
295
+
296
+ /**
297
+ * The candidate graph of a role dispatch (T1.2.3): the rungs of every tier in `[floor, ceiling]`, all run by the role agent
298
+ * (`AgentRef` origin `role`, outcome keys `class|role:<agent>|provider/model#variant`). Every rung is priced through its
299
+ * simulated runner path under `ladders.roleEscalatePolicy` (the runtime's raise path: one tier per FAIL up to the ceiling).
300
+ */
301
+ export interface RoleLadder extends Ladder {
302
+ /** The role agent. */
303
+ readonly role: string;
304
+ /** Ranks of the window on the escalate ladder; `null` when the window could not be placed (then there are no candidates). */
305
+ readonly floorRank: number | null;
306
+ readonly ceilingRank: number | null;
307
+ readonly tiers: readonly RoleLadderTier[];
308
+ /** Candidate index of the static default: the class's taxonomy tier clamped into the window; `null` when there are no candidates. */
309
+ readonly staticDefault: number | null;
310
+ /** Candidate index of the pinned tier (`RoleWindow.pinned`); `null` when not pinned. */
311
+ readonly pinnedIndex: number | null;
312
+ /** Window, default and pin notes for the decision row (`default:clamp:floor`, `pinned:heavy`, ...). */
313
+ readonly reasons: readonly string[];
314
+ }
315
+
316
+ /** `routing.exploration` for one dispatch (T1.2.4): the rate (clamped to `[0, MAX_EXPLORATION_RATE]`) and the RNG seed. */
317
+ export interface RoleExploration extends Pick<ExplorationConfig, "rate"> {
318
+ /** The decision row's id: the only seed of the exploration draw (same id → same draw). */
319
+ readonly decisionID: string;
320
+ }
321
+
322
+ export interface RoleDecisionInput {
323
+ /**
324
+ * The classify result (`ClassifyResult` itself: `facts`, `trace.rules`, `trace.routeLine`). The kernel reads the
325
+ * EFFECTIVE risk and scope from it (`roles/policy.effectiveFactsOf`, raise-only, QA-P12-1-1): never-down, `U` and
326
+ * exploration use that risk.
327
+ */
328
+ readonly classified: ClassifiedDispatch;
329
+ readonly ladder: RoleLadder;
330
+ /**
331
+ * The EFFECTIVE detection (§2.1, A34; `roles/policy.effectiveDetection`): `deterministic` only when the router's own
332
+ * gate runs the checks. Never `ClassifyResult.detection` (the route line's claim).
333
+ */
334
+ readonly detection: EffectiveDetection;
335
+ /** `routing.engine`: only `enforce` applies a kernel switch or explores. */
336
+ readonly engine: ResolvedRouting["engine"];
337
+ readonly routing: KernelRouting;
338
+ readonly store: EngineStoreView | null;
339
+ /** A resume: the rung the child runs on. The dispatch never moves below it and is never switched or explored. */
340
+ readonly resume?: { readonly model: string; readonly variant: string | null } | null;
341
+ /** Absent/null or rate 0 = no exploration. */
342
+ readonly exploration?: RoleExploration | null;
343
+ readonly orchestrator?: OrchestratorCost | null;
344
+ readonly remainingTurns?: number;
345
+ }
346
+
347
+ export interface RoleDecision {
348
+ /** The kernel's decision with `chosen` = {@link base} (`pinned` = the window has a pin). */
349
+ readonly decision: Decision;
350
+ /** The policy's pick before the kernel: the pinned tier, else the static default, raised to the running rung on a resume. */
351
+ readonly base: Candidate | null;
352
+ /**
353
+ * What the router sets as the per-call model. `null` = no candidate (reason `window:no-candidates`): P2.1 REFUSES the
354
+ * role dispatch. It never falls back to `buildEscalatePolicy`/`buildLadder` or to a tier agent on its own (QA-P12-1-5).
355
+ */
356
+ readonly dispatch: Candidate | null;
357
+ /** `enforce` applied the kernel's switch (`dispatch` = `decision.target`); never on a resume, a pin or an exploration draw. */
358
+ readonly switched: boolean;
359
+ /** `dispatch` was drawn by exploration (reason `explore`). */
360
+ readonly explore: boolean;
361
+ /** Probability that this policy dispatches `dispatch` for this input, in (0, 1]; 1 when no draw was possible. */
362
+ readonly propensity: number;
363
+ /**
364
+ * `RoleLadder.reasons` plus `resume:running`, `resume:off-ladder` (raised to the running model's capability rank),
365
+ * `resume:off-ladder:lift` (unknown rank: raised to the window ceiling), `kept:resume`, `explore`.
366
+ */
367
+ readonly reasons: readonly string[];
368
+ }
@@ -94,13 +94,19 @@ export function capEvidence(state: BetaState, maxEffectiveSamples: number): Beta
94
94
  return { alpha: state.alpha * scale, beta: state.beta * scale, updatedAt: state.updatedAt };
95
95
  }
96
96
 
97
- /** D4: one observation. Decays the stored evidence to `now`, adds +1 to alpha (success) or beta, then caps. */
98
- export function observe(state: BetaState | undefined, success: boolean, now: number, tuning: OutcomeTuning): BetaState {
97
+ /**
98
+ * D4: one observation. Decays the stored evidence to `now`, adds `weight` (default 1) to alpha (success) or beta, then caps.
99
+ * #84 P3.3 fix 2 (QA-P33F2-1-1): an independent grader's verdict of a role dispatch weighs 0.5 (plan §2.6). QA-P33F2-2 N-b: a
100
+ * weight that is not a finite number in (0, 1] is no observation at all — the state comes back unchanged (an absent state as
101
+ * empty evidence) — so no caller can add more than one observation, nor turn a malformed weight into a full one.
102
+ */
103
+ export function observe(state: BetaState | undefined, success: boolean, now: number, tuning: OutcomeTuning, weight = 1): BetaState {
99
104
  const at = Number.isFinite(now) ? now : (state?.updatedAt ?? 0);
105
+ if (!(Number.isFinite(weight) && weight > 0 && weight <= 1)) return state ?? { alpha: 0, beta: 0, updatedAt: at };
100
106
  const base = decayTo(state ?? { alpha: 0, beta: 0, updatedAt: at }, at, tuning);
101
107
  const next: BetaState = success
102
- ? { alpha: base.alpha + 1, beta: base.beta, updatedAt: base.updatedAt }
103
- : { alpha: base.alpha, beta: base.beta + 1, updatedAt: base.updatedAt };
108
+ ? { alpha: base.alpha + weight, beta: base.beta, updatedAt: base.updatedAt }
109
+ : { alpha: base.alpha, beta: base.beta + weight, updatedAt: base.updatedAt };
104
110
  return capEvidence(next, tuning.maxEffectiveSamples);
105
111
  }
106
112
 
@@ -68,8 +68,51 @@ export {
68
68
  resolveOutcomesDir,
69
69
  } from "./persist";
70
70
 
71
- export { USAGE, parseStatsArgs, renderMarkdown, runStatsCli, summarize } from "./stats";
71
+ export { USAGE, hasRoleRows, parseStatsArgs, renderMarkdown, renderRoleMarkdown, runStatsCli, summarize, summarizeRoles } from "./stats";
72
72
  export type { ParseStatsResult, StatsArgs } from "./stats";
73
+ export {
74
+ REDISPATCH_MAX_EARLIER,
75
+ REDISPATCH_MIN_TOKENS,
76
+ REDISPATCH_SIMILARITY,
77
+ REDISPATCH_WINDOW_MS,
78
+ SAME_TASK_LINE_SHARE,
79
+ SIBLING_SHARED_MIN,
80
+ SIGNAL_MASS_CAPS,
81
+ SIGNAL_WEIGHTS,
82
+ detectRedispatch,
83
+ graderSignal,
84
+ isSignalObservation,
85
+ parseReturnPrefix,
86
+ returnSignal,
87
+ runSignal,
88
+ sameModel,
89
+ sharedLines,
90
+ signalMass,
91
+ signalReason,
92
+ signalRow,
93
+ signedWeight,
94
+ taskSection,
95
+ taskSimilarity,
96
+ tierOfModel,
97
+ tierRank,
98
+ verdictSignal,
99
+ } from "./signals";
100
+ export type {
101
+ DispatchText,
102
+ GraderVerdictInput,
103
+ GuardObservation,
104
+ RedispatchMatch,
105
+ RedispatchOptions,
106
+ ReturnContract,
107
+ ReturnPrefix,
108
+ ReturnSignalInput,
109
+ RunRecord,
110
+ RunSignalInput,
111
+ SignalObservation,
112
+ SignalOutcome,
113
+ SignalRowInput,
114
+ TierRung,
115
+ } from "./signals";
73
116
 
74
117
  export interface AcquireOutcomesOptions {
75
118
  /** Outcomes directory (already resolved with `resolveOutcomesDir`). */