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
@@ -24,7 +24,7 @@
24
24
 
25
25
  import { homedir, tmpdir } from "node:os";
26
26
  import type { RouterConfig, RouterHost } from "../../router/config";
27
- import { resolveRouting } from "../../router/config";
27
+ import { resolveCandidates, resolveRouting } from "../../router/config";
28
28
  import { getActiveTiers } from "../../router/protocol";
29
29
  import {
30
30
  forgetDispatch,
@@ -41,7 +41,11 @@ import type { AcquireOutcomesOptions } from "./index";
41
41
  import { acquireOutcomes } from "./index";
42
42
  import { pricingState, tokenSampleFromEvent } from "./cost";
43
43
  import { resolveOutcomesDir } from "./persist";
44
+ import { roleTierOrder } from "../engine/ladders";
45
+ import type { SignalObservation, TierRung } from "./signals";
46
+ import { SIGNAL_MASS_CAPS, graderSignal, isSignalObservation, signalRow, tierOfModel, verdictSignal } from "./signals";
44
47
  import type {
48
+ AgentOrigin,
45
49
  AttemptSignal,
46
50
  Clock,
47
51
  LoggedRoutingMode,
@@ -55,9 +59,10 @@ import type {
55
59
  StepEndedTokens,
56
60
  StepSample,
57
61
  Verdict,
62
+ VerdictGrader,
58
63
  VerdictRow,
59
64
  } from "./types";
60
- import { LOG_ROW_VERSION, classifyAgentOrigin, makeKey, safeNow, splitModelRef } from "./types";
65
+ import { LOG_ROW_VERSION, classifyAgentOrigin, makeKey, normalizeVariant, safeNow, splitModelRef } from "./types";
61
66
 
62
67
  // ---------------------------------------------------------------------------
63
68
  // Settings
@@ -73,6 +78,26 @@ export interface IngestSettings {
73
78
  readonly tuning: OutcomeTuning;
74
79
  /** Ids of the active preset's router tier agents (origin `router`); every other agent is `host`. */
75
80
  readonly routerAgentIds: ReadonlySet<string>;
81
+ /**
82
+ * P1.4: agent names of the resolved role agents (origin `role`, key `class|role:<agent>|…`). Absent or empty in tiers
83
+ * mode and on v1, so keys stay `router`/`host` there. Filled by P2.1 from `resolveRoles`.
84
+ */
85
+ readonly roleAgentIds?: ReadonlySet<string>;
86
+ /**
87
+ * #84 P3.3 fix 2: the tier order of role dispatches (`roleTierOrder`, cheapest first) and its rungs, which rank a grader
88
+ * against the producer (plan §2.6: grader tier ≥ producer tier). Absent or empty: no grader is ever independent.
89
+ */
90
+ readonly tierOrder?: readonly string[];
91
+ readonly tierRungs?: readonly TierRung[];
92
+ }
93
+
94
+ /** The role tier order of `cfg` and its rungs (empty without a config). */
95
+ function tierLadderOf(cfg: RouterConfig | undefined): { readonly tierOrder: readonly string[]; readonly tierRungs: readonly TierRung[] } {
96
+ if (cfg === undefined) return { tierOrder: [], tierRungs: [] };
97
+ const tierOrder = Object.freeze([...roleTierOrder(cfg)]);
98
+ const tierRungs = Object.freeze(tierOrder.flatMap((tier) =>
99
+ resolveCandidates(tier, cfg).map((rung): TierRung => Object.freeze({ tier, model: rung.model, variant: rung.variant ?? null }))));
100
+ return { tierOrder, tierRungs };
76
101
  }
77
102
 
78
103
  const settingsCache = new WeakMap<RouterConfig, IngestSettings | null>();
@@ -98,6 +123,7 @@ export function ingestSettings(cfg: RouterConfig | undefined, host: RouterHost):
98
123
  maxEffectiveSamples: routing.outcomes.maxEffectiveSamples,
99
124
  }),
100
125
  routerAgentIds: new Set(cfg === undefined ? [] : Object.keys(getActiveTiers(cfg))),
126
+ ...tierLadderOf(cfg),
101
127
  });
102
128
  }
103
129
  if (cfg !== undefined) settingsCache.set(cfg, settings);
@@ -387,6 +413,15 @@ export interface IngestDeps {
387
413
  readonly acquire?: (options: AcquireOutcomesOptions) => OutcomesBundle;
388
414
  }
389
415
 
416
+ /** P1.4: options of {@link Ingest.onSignal}. */
417
+ export interface SignalOptions {
418
+ /**
419
+ * The decision id of the attempt the signal is about; the child's current registration must carry it, else nothing is
420
+ * written (a re-registered or evicted child). Required for `redispatch` (the previous attempt, `RedispatchMatch.previous`).
421
+ */
422
+ readonly expectDecisionID?: string;
423
+ }
424
+
390
425
  export interface Ingest {
391
426
  /**
392
427
  * `session.step.ended` (and `session.step.failed`, when it carries a cost or tokens) of a registered child. Awaits
@@ -400,10 +435,27 @@ export interface Ingest {
400
435
  * (QA-2.3-R2-1). Without an id every delivery is applied.
401
436
  */
402
437
  onExecutionEnded(childSessionID: string, eventId?: unknown): void;
403
- /** A verifier verdict for the child's current attempt. Never throws. */
404
- onVerdict(childSessionID: string, outcome: Verdict): void;
438
+ /**
439
+ * A verifier verdict for the child's current attempt. Never throws. `grader` (#84 P3.3 fix 2, `verdictGraderOf`; always passed,
440
+ * `undefined` = deterministic checks): the LLM grader that judged the verdict. Tier and host dispatches: the store and the
441
+ * verdict row take it either way, at full weight (unchanged, I1). A ROLE dispatch's grader verdict (plan §2.6, I6,
442
+ * QA-P33F2-1-1) moves the store at 0.5 with a verdict row and a `grader` signal row only when the grader is independent (tier
443
+ * ≥ the producer's and another model); otherwise nothing at all — no store change, no verdict row, no signal row.
444
+ */
445
+ onVerdict(childSessionID: string, outcome: Verdict, grader: VerdictGrader | undefined): void;
405
446
  /** A false refusal (zero tool calls) observed for the child's current attempt. Never throws. */
406
447
  onFalseRefusal(childSessionID: string): void;
448
+ /**
449
+ * P1.4: append a signal row (signals.ts) for the child's current attempt. Rows only: the Beta store, its decay and the
450
+ * verdict/refusal rows are untouched. `verdict` and `grader` are refused (`onVerdict` writes them when the store takes the
451
+ * verdict; QA-P33F2-1 N2);
452
+ * `redispatch` needs `expectDecisionID`. Gated like a verdict (registered, keyable, trusted class), except that the
453
+ * zero-mass kinds (`budget`, `authority`) are written under class `unknown` when the class is not trusted. The dispatch
454
+ * must have a decision id (the row annotates its decision row). One row per attempt and kind (C7: a repeat, even with
455
+ * another outcome, writes nothing). Returns whether a row was enqueued. Never throws. Optional only so that existing test
456
+ * doubles still satisfy `Ingest`; `createIngest` and {@link NOOP_INGEST} implement it.
457
+ */
458
+ onSignal?(childSessionID: string, observation: SignalObservation, options?: SignalOptions): boolean;
407
459
  /** A session was deleted: the child's open attempt is folded and its registry entry dropped; children of the session too. */
408
460
  onSessionGone(sessionID: string): void;
409
461
  /** Idle/deleted flush point (D15): coalesced and throttled by the flusher, never awaited. No-op without recorded data. */
@@ -421,6 +473,7 @@ export const NOOP_INGEST: Ingest = Object.freeze({
421
473
  onExecutionEnded: () => undefined,
422
474
  onVerdict: () => undefined,
423
475
  onFalseRefusal: () => undefined,
476
+ onSignal: () => false,
424
477
  onSessionGone: () => undefined,
425
478
  requestFlush: () => undefined,
426
479
  sweep: () => undefined,
@@ -452,6 +505,10 @@ interface Target {
452
505
  readonly record: DispatchRecord;
453
506
  readonly settings: IngestSettings;
454
507
  readonly key: OutcomeKey;
508
+ readonly origin: AgentOrigin;
509
+ /** `provider/model`. */
510
+ readonly model: string;
511
+ readonly variant: string;
455
512
  }
456
513
 
457
514
  export function createIngest(deps: IngestDeps): Ingest {
@@ -489,7 +546,7 @@ export function createIngest(deps: IngestDeps): Ingest {
489
546
  };
490
547
 
491
548
  /** Registered, trusted and keyable? Otherwise nothing may be recorded for the child. */
492
- const targetOf = (childSessionID: string): Target | null => {
549
+ const targetOf = (childSessionID: string, untrusted: "skip" | "unknown" = "skip"): Target | null => {
493
550
  // Registry first: most `session.step.ended` events belong to sessions that are not registered children
494
551
  // (the orchestrator's own), and the settings may cost a config fingerprint check.
495
552
  const record = lookupDispatch(childSessionID);
@@ -499,20 +556,22 @@ export function createIngest(deps: IngestDeps): Ingest {
499
556
  const settings = deps.settings();
500
557
  if (settings === null) return null;
501
558
  const confidence = record.facts.confidence;
559
+ const rawClass = record.facts.class;
502
560
  // Phase 1.2 handoff (QA-1.2-27): a class below the threshold is "unknown" for learning, not a class of
503
- // its own. No fallback class, no store call, no row.
504
- if (typeof confidence !== "number" || !Number.isFinite(confidence) || confidence < settings.minClassConfidence) {
505
- return null;
506
- }
507
- const cls = record.facts.class;
508
- if (typeof cls !== "string" || cls === "" || cls === "unknown") return null;
561
+ // its own. No fallback class, no store call, no row. P1.4 (`untrusted: "unknown"`): a zero-mass role signal
562
+ // (budget, authority) is still a row, keyed under class `unknown`; it never reaches the store.
563
+ const trusted =
564
+ typeof confidence === "number" && Number.isFinite(confidence) && confidence >= settings.minClassConfidence &&
565
+ typeof rawClass === "string" && rawClass !== "" && rawClass !== "unknown";
566
+ if (!trusted && untrusted === "skip") return null;
567
+ const cls = trusted ? rawClass : "unknown";
509
568
  if (record.model === null) return unkeyable(`${record.agent}|`, childSessionID, "the dispatch registered no model");
510
569
  const ref = splitModelRef(record.model);
511
570
  if (ref === null) return unkeyable(`${record.agent}|${record.model}`, childSessionID, `model "${record.model}" is not provider/model`);
512
571
  const variant = record.variant ?? ref.variant;
513
- const origin = classifyAgentOrigin(record.agent, settings.routerAgentIds);
572
+ const origin: AgentOrigin = settings.roleAgentIds?.has(record.agent) === true ? "role" : classifyAgentOrigin(record.agent, settings.routerAgentIds);
514
573
  const key = makeKey(cls, { origin, id: record.agent }, ref.provider, ref.model, variant);
515
- return { record, settings, key };
574
+ return { record, settings, key, origin, model: `${ref.provider}/${ref.model}`, variant: normalizeVariant(variant) };
516
575
  };
517
576
 
518
577
  // One warning per model reference (QA-2.1-12), not per child: every child of an unresolved agent says the same.
@@ -590,6 +649,55 @@ export function createIngest(deps: IngestDeps): Ingest {
590
649
  void current.bundle.release().catch((error: unknown) => warn("releasing the outcomes bundle failed", error));
591
650
  return true;
592
651
  };
652
+ /**
653
+ * P1.4: enqueue one signal row for the target's attempt: one per attempt and kind (C7, the store's one-observation
654
+ * rule), process-wide per outcomes directory. Needs the dispatch's decision id: without it there is no decision row
655
+ * to annotate and a pre-P1.4 reader would count the row as a dispatch (QA-P14-1-11).
656
+ */
657
+ const appendSignal = (target: Target, childSessionID: string, observation: SignalObservation, bundle: OutcomesBundle): boolean => {
658
+ const { record, settings, key } = target;
659
+ if (record.decisionID === null) return false;
660
+ if (!boundedAdd(signalled, `signal|${settings.outcomesDir}|${record.attemptId}|${observation.kind}`, SIGNAL_CAP)) return false;
661
+ bundle.flusher.enqueue(
662
+ signalRow(
663
+ {
664
+ ts: new Date(safeNow(now)).toISOString(),
665
+ sessionID: record.parentSessionID ?? "",
666
+ decisionID: record.decisionID,
667
+ mode: settings.engine,
668
+ childSessionID,
669
+ facts: record.facts,
670
+ chosen: { key, agent: record.agent, origin: target.origin, model: target.model, variant: target.variant },
671
+ step: record.step,
672
+ attemptID: record.attemptId,
673
+ ...(target.origin === "role" ? { role: record.agent } : {}),
674
+ ...(record.tier === null ? {} : { tier: record.tier }),
675
+ },
676
+ observation,
677
+ ),
678
+ );
679
+ return true;
680
+ };
681
+
682
+ /**
683
+ * #84 P3.3 fix 2 (plan §2.6, I6): the signal of a grader's verdict on the target's attempt. The grader's tier is the LOWER of
684
+ * the tier of the model it ran on (`tierOfModel`: a variant that is not a preset rung, as the host's `#default`, matches by
685
+ * model) and the tier the checker asked for (on the order, with a known model) — either one alone when the other is unknown
686
+ * (QA-P33F2-1 N3: a grader never ranks above either); the producer's is the registered tier, else its model's. `graderSignal`
687
+ * decides: independent (tier ≥ producer's, another model) → 0.5; unknown or not → none.
688
+ */
689
+ const graderSignalOf = (target: Target, outcome: Verdict, grader: VerdictGrader): SignalObservation | null => {
690
+ const tiers = target.settings.tierOrder ?? [];
691
+ const rungs = target.settings.tierRungs ?? [];
692
+ const requested = grader.model !== null && grader.tier !== null && tiers.includes(grader.tier) ? grader.tier : null;
693
+ const byModel = tierOfModel(grader.model, rungs);
694
+ const graderTier = byModel !== null && requested !== null
695
+ ? (tiers.indexOf(byModel) <= tiers.indexOf(requested) ? byModel : requested)
696
+ : (byModel ?? requested);
697
+ const producerTier = target.record.tier ?? tierOfModel(`${target.model}#${target.variant}`, rungs);
698
+ return graderSignal({ outcome, graderTier, graderModel: grader.model, producerTier, producerModel: target.model }, tiers);
699
+ };
700
+
593
701
  return {
594
702
  async onStepEnded(event: IngestEvent): Promise<void> {
595
703
  try {
@@ -678,7 +786,7 @@ export function createIngest(deps: IngestDeps): Ingest {
678
786
  }
679
787
  },
680
788
 
681
- onVerdict(childSessionID: string, outcome: Verdict): void {
789
+ onVerdict(childSessionID: string, outcome: Verdict, grader: VerdictGrader | undefined): void {
682
790
  try {
683
791
  const target = targetOf(childSessionID);
684
792
  if (target === null) return;
@@ -686,13 +794,25 @@ export function createIngest(deps: IngestDeps): Ingest {
686
794
  const bundle = bundleFor(settings);
687
795
  if (bundle === null) return;
688
796
  const attempt = record.attemptId;
797
+ // QA-P33F2-1-1 (plan §2.6, I6): a role dispatch's GRADER verdict counts only from an independent grader, and then at
798
+ // the grader's 0.5 — in the store that role routing reads (kernel) as in the rows. A grader that is not independent, or
799
+ // not known to be, moves nothing: no store observation, no verdict row, no signal row, and the attempt stays unscored
800
+ // (a later false refusal is then its first terminal signal, as in the store). Tier and host dispatches: unchanged (I1).
801
+ const graded = outcome !== "unverifiable" && target.origin === "role" && grader !== undefined
802
+ ? graderSignalOf(target, outcome, grader)
803
+ : undefined;
804
+ if (graded === null) {
805
+ touchDispatch(childSessionID, safeNow(now));
806
+ return;
807
+ }
689
808
  // Rows follow the store (QA-2.1-3): a verdict that moves nothing (the attempt was scored already, by a
690
809
  // verdict or a refusal) writes no row, or `routing:stats` would count outcomes the store never saw.
691
810
  // `unverifiable` moves nothing by design; it is a row only while the attempt is still unscored.
692
811
  if (outcome === "unverifiable") {
693
812
  if (scored.has(attempt) || !boundedAdd(signalled, `unverifiable|${attempt}`, SIGNAL_CAP)) return;
694
813
  } else {
695
- if (!bundle.store.recordVerdict(key, outcome, signalOf(record))) return;
814
+ const weight = graded === undefined ? undefined : graded.weight; // the grader's 0.5 (signals.ts SIGNAL_WEIGHTS.grader)
815
+ if (!bundle.store.recordVerdict(key, outcome, signalOf(record), weight)) return;
696
816
  boundedSet(scored, attempt, outcome, SIGNAL_CAP);
697
817
  }
698
818
  const row: VerdictRow = {
@@ -706,6 +826,12 @@ export function createIngest(deps: IngestDeps): Ingest {
706
826
  step: record.step,
707
827
  };
708
828
  bundle.flusher.enqueue(row);
829
+ // P1.4 (QA-P14-1-6): a role dispatch's verdict signal row follows the store: written only for a verdict it took.
830
+ // #84 P3.3 fix 2 (plan §2.6, I6): a grader's verdict is a `grader` signal (0.5, independent graders only), never `verdict`.
831
+ if (outcome !== "unverifiable" && target.origin === "role") {
832
+ const signal = graded ?? verdictSignal(outcome);
833
+ if (signal !== null) appendSignal(target, childSessionID, signal, bundle);
834
+ }
709
835
  touchDispatch(childSessionID, safeNow(now));
710
836
  } catch (error) {
711
837
  warn("verdict failed", error, { childSessionID });
@@ -743,6 +869,28 @@ export function createIngest(deps: IngestDeps): Ingest {
743
869
  warn("false refusal failed", error, { childSessionID });
744
870
  }
745
871
  },
872
+
873
+ onSignal(childSessionID: string, observation: SignalObservation, options: SignalOptions = {}): boolean {
874
+ try {
875
+ if (!isSignalObservation(observation)) return false;
876
+ // QA-P14-1-6: verdict rows follow the store; only onVerdict writes them. QA-P33F2-1 N2: grader rows too.
877
+ if (observation.kind === "verdict" || observation.kind === "grader") return false;
878
+ // QA-P14-1-5: a re-dispatch failure belongs to one earlier attempt and must name it.
879
+ if (observation.kind === "redispatch" && options.expectDecisionID === undefined) return false;
880
+ const caps = SIGNAL_MASS_CAPS[observation.kind];
881
+ const target = targetOf(childSessionID, caps.positive === 0 && caps.negative === 0 ? "unknown" : "skip");
882
+ if (target === null) return false;
883
+ if (options.expectDecisionID !== undefined && target.record.decisionID !== options.expectDecisionID) return false;
884
+ const bundle = bundleFor(target.settings);
885
+ if (bundle === null) return false;
886
+ if (!appendSignal(target, childSessionID, observation, bundle)) return false;
887
+ touchDispatch(childSessionID, safeNow(now));
888
+ return true;
889
+ } catch (error) {
890
+ warn("signal failed", error, { childSessionID });
891
+ return false;
892
+ }
893
+ },
746
894
  onSessionGone(sessionID: string): void {
747
895
  try {
748
896
  if (lookupDispatch(sessionID) !== undefined) {
@@ -34,6 +34,7 @@ import type {
34
34
  ReadRowsResult,
35
35
  RefusalRow,
36
36
  RouteChoice,
37
+ SignalKind,
37
38
  VerdictRow,
38
39
  WriteResult,
39
40
  } from "./types";
@@ -47,8 +48,10 @@ import {
47
48
  FLUSH_MIN_INTERVAL_MS,
48
49
  LADDER_STEP_KINDS,
49
50
  LOG_ROW_VERSION,
51
+ SIGNAL_KINDS,
50
52
  MAX_QUEUED_ROWS,
51
53
  MAX_CORRUPT_COPIES,
54
+ NEED_TERM_RE,
52
55
  OUTCOMES_CORRUPT_PREFIX,
53
56
  OUTCOMES_CORRUPT_RE,
54
57
  OUTCOMES_FILE,
@@ -258,6 +261,12 @@ const LOGGED_MODES: readonly string[] = ["shadow", "advise", "enforce"];
258
261
  const COST_UNITS: readonly string[] = ["usd", "ratio"];
259
262
  const VERDICT_VALUES: readonly string[] = ["pass", "fail", "unverifiable"];
260
263
 
264
+ const BINDINGS: readonly string[] = ["exact", "intersection", "unknown"];
265
+
266
+ function isStringArray(x: unknown): x is string[] {
267
+ return Array.isArray(x) && x.every((v): v is string => typeof v === "string");
268
+ }
269
+
261
270
  function isOutcomeKey(x: unknown): x is OutcomeKey {
262
271
  return typeof x === "string" && parseKey(x) !== null;
263
272
  }
@@ -270,7 +279,7 @@ function readChoice(x: unknown): RouteChoice | null {
270
279
  if (!isRec(x)) return null;
271
280
  const { key, agent, origin, model, variant } = x;
272
281
  if (!isOutcomeKey(key) || typeof agent !== "string" || typeof model !== "string" || typeof variant !== "string") return null;
273
- if (origin !== "router" && origin !== "host") return null;
282
+ if (origin !== "router" && origin !== "host" && origin !== "role") return null;
274
283
  return { key, agent, origin, model, variant };
275
284
  }
276
285
 
@@ -298,6 +307,8 @@ function readTrace(x: unknown): DecisionTrace | undefined {
298
307
  backend,
299
308
  ...(x.backendSkipped === "credentials" ? { backendSkipped: "credentials" as const } : {}),
300
309
  ...(argmin === null ? {} : { argmin }),
310
+ // QA-G-B-2-2 (D14): only well-shaped need terms; one that could carry prompt text (an older row's URL or path) is dropped.
311
+ ...(isStringArray(x.needTerms) ? { needTerms: x.needTerms.filter((term) => NEED_TERM_RE.test(term)) } : {}),
301
312
  };
302
313
  }
303
314
  function readLadderStep(x: unknown): (typeof LADDER_STEP_KINDS)[number] | null {
@@ -405,6 +416,17 @@ export function parseLogLine(line: string): LogRow | null {
405
416
  ...(trace === undefined ? {} : { trace }),
406
417
  ...(detection === undefined ? {} : { detection }),
407
418
  ...(capability === undefined ? {} : { capability }),
419
+ ...(typeof json.role === "string" ? { role: json.role } : {}),
420
+ ...(isStringArray(json.grant) ? { grant: [...json.grant] } : {}),
421
+ ...(isStringArray(json.boundsReasons) ? { boundsReasons: [...json.boundsReasons] } : {}),
422
+ ...(isFiniteNum(json.budgetUsed) ? { budgetUsed: json.budgetUsed } : {}),
423
+ ...(oneOf(SIGNAL_KINDS, json.signal) ? { signal: json.signal as SignalKind } : {}),
424
+ ...(typeof json.explore === "boolean" ? { explore: json.explore } : {}),
425
+ ...(isFiniteNum(json.propensity) ? { propensity: json.propensity } : {}),
426
+ ...(oneOf(BINDINGS, json.binding) ? { binding: json.binding as NonNullable<DecisionRow["binding"]> } : {}),
427
+ ...(typeof json.tier === "string" && json.tier !== "" ? { tier: json.tier } : {}),
428
+ ...(isFiniteNum(json.signalWeight) ? { signalWeight: json.signalWeight } : {}),
429
+ ...(typeof json.attemptID === "string" && json.attemptID !== "" ? { attemptID: json.attemptID } : {}),
408
430
  };
409
431
  return row;
410
432
  }