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
@@ -10,22 +10,30 @@
10
10
  import type {
11
11
  ClassStatsRow,
12
12
  CostUnit,
13
+ CostUnitRow,
13
14
  DecisionRow,
14
15
  KeyStatsRow,
15
16
  LogRow,
17
+ MeanStat,
16
18
  OutcomeKey,
17
19
  OutcomeStoreView,
18
20
  RatioCell,
19
21
  RefusalRow,
20
22
  ResumeFreshRow,
23
+ RoleStatsTable,
24
+ RoleTierStatsRow,
21
25
  SavingsRow,
26
+ SignalKind,
27
+ SignalKindStats,
22
28
  StatsCliIO,
23
29
  StatsTable,
24
30
  StatsWindow,
31
+ TokenMeans,
25
32
  VerdictRow,
26
33
  } from "./types";
27
- import { DECISIONS_MAX_GENERATIONS, FLOOR_LIFT_REASON, LADDER_STEP_KINDS, STATS_EXIT } from "./types";
34
+ import { DECISIONS_MAX_GENERATIONS, FLOOR_LIFT_REASON, LADDER_STEP_KINDS, SIGNAL_KINDS, STATS_EXIT, isAnnotationRow, parseKey } from "./types";
28
35
  import { createOutcomeStore } from "./store";
36
+ import { signalMass } from "./signals";
29
37
 
30
38
  // ---------------------------------------------------------------------------
31
39
  // summarize
@@ -85,8 +93,10 @@ export function summarize(store: OutcomeStoreView | null, rows: readonly LogRow[
85
93
  // An append may reach disk before reporting failure; retrying that batch must not inflate rates.
86
94
  // Decisions keep their first row. Signals dedupe per outcome, before windowing and joins:
87
95
  // a later decisive verdict must still replace an earlier unverifiable verdict (R2-9).
96
+ // P1.4: annotation rows (role signals, bindings) are not dispatches; they never reach the tier-mode numbers.
88
97
  const seen = new Set<string>();
89
98
  rows = rows.filter((row) => {
99
+ if (isAnnotationRow(row)) return false;
90
100
  const id = JSON.stringify(row.kind === "decision"
91
101
  ? [row.kind, row.decisionID]
92
102
  : [row.kind, row.decisionID, row.attemptID, row.kind === "verdict" ? row.verdict : row.overrides ?? null]);
@@ -304,6 +314,228 @@ export function summarize(store: OutcomeStoreView | null, rows: readonly LogRow[
304
314
  };
305
315
  }
306
316
 
317
+ // ---------------------------------------------------------------------------
318
+ // summarizeRoles (P1.4): role × tier statistics; computation only, rendering is P2.2
319
+ // ---------------------------------------------------------------------------
320
+
321
+ const UNKNOWN_TIER = "unknown";
322
+
323
+ /**
324
+ * Role of a decision row: its `role`, else the agent of its dispatched key when that key has origin `role` (QA-P14-2-5:
325
+ * a role dispatch row written without `role` is still the role's; P2.1 should write `role` anyway).
326
+ */
327
+ function roleOf(row: DecisionRow): string | undefined {
328
+ if (row.role !== undefined) return row.role;
329
+ const parts = parseKey(dispatchedKey(row));
330
+ return parts !== null && parts.agent.origin === "role" ? parts.agent.id : undefined;
331
+ }
332
+
333
+ interface RoleTierAcc {
334
+ readonly role: string;
335
+ readonly tier: string;
336
+ dispatches: number;
337
+ explored: number;
338
+ unknownBindings: number;
339
+ readonly signals: Map<SignalKind, { pass: number; fail: number; none: number; positive: number; negative: number }>;
340
+ readonly keys: Set<OutcomeKey>;
341
+ readonly costs: Map<CostUnit, number[]>;
342
+ }
343
+
344
+ /** Ascending-order sum, so a total never depends on the row order. */
345
+ function stableSum(values: readonly number[]): number {
346
+ return [...values].sort((a, b) => a - b).reduce((sum, x) => sum + x, 0);
347
+ }
348
+
349
+ function pooledTokens(store: OutcomeStoreView, keys: ReadonlySet<OutcomeKey>): TokenMeans | null {
350
+ let n = 0;
351
+ const sums = { input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0 };
352
+ for (const key of [...keys].sort(compareCodeUnits)) {
353
+ const t = store.cost(key).tokens;
354
+ if (t.n <= 0) continue;
355
+ n += t.n;
356
+ sums.input += t.input * t.n;
357
+ sums.output += t.output * t.n;
358
+ sums.reasoning += t.reasoning * t.n;
359
+ sums.cacheRead += t.cacheRead * t.n;
360
+ sums.cacheWrite += t.cacheWrite * t.n;
361
+ }
362
+ if (n === 0) return null;
363
+ return {
364
+ n,
365
+ input: sums.input / n,
366
+ output: sums.output / n,
367
+ reasoning: sums.reasoning / n,
368
+ cacheRead: sums.cacheRead / n,
369
+ cacheWrite: sums.cacheWrite / n,
370
+ };
371
+ }
372
+
373
+ function pooledUSD(store: OutcomeStoreView, keys: ReadonlySet<OutcomeKey>): MeanStat | null {
374
+ let n = 0;
375
+ let sum = 0;
376
+ for (const key of [...keys].sort(compareCodeUnits)) {
377
+ const m = store.cost(key).measuredUSD;
378
+ if (m.n <= 0) continue;
379
+ n += m.n;
380
+ sum += m.mean * m.n;
381
+ }
382
+ return n === 0 ? null : { mean: sum / n, n };
383
+ }
384
+
385
+ /**
386
+ * Role × tier statistics over `since ≤ ts < until`. Only rows of role dispatches count: a dispatch row is a non-annotation
387
+ * `dispatch` decision row with a role (`role`, else a role-origin dispatched key: {@link roleOf}); signal rows and unknown-binding rows are attributed to the role
388
+ * and tier of the dispatch row they join on `decisionID` (any window: the dispatch may precede the window), else to their
389
+ * own `role`/`tier`. Rows are deduplicated like `summarize` (C7): the first dispatch row per decision id, and identical
390
+ * annotation rows once. Signal masses are clamped per kind (`signalMass`): I6 and I7 hold whatever a row claims.
391
+ * Tokens and USD come from the store (lifetime per attempt, like `KeyStatsRow.measuredUSD`).
392
+ */
393
+ export function summarizeRoles(store: OutcomeStoreView | null, rows: readonly LogRow[], window: StatsWindow): RoleStatsTable {
394
+ const since = finiteOrNull(window.since);
395
+ const until = finiteOrNull(window.until);
396
+ const inWindow = (row: LogRow): boolean => {
397
+ const t = Date.parse(row.ts);
398
+ return Number.isFinite(t) && (since === null || t >= since) && (until === null || t < until);
399
+ };
400
+
401
+ const dispatchByID = new Map<string, DecisionRow>();
402
+ const annotations: DecisionRow[] = [];
403
+ const seenNotes = new Set<string>();
404
+ // Residual QA-P14-1-6: a refusal that records `overrides: "pass"` turned the attempt's store pass into a failure (as
405
+ // `summarize` moves that pass to a fail). The attempt's `verdict:pass` signal then counts as a failure of 1, and its
406
+ // `grader:pass` signal (#84 P3.3 fix 2: grader verdicts follow the store too) as a failure of the grader's 0.5. Every row
407
+ // handed in, not only the window: the refusal may land in another window than the signal.
408
+ const converted = new Set<string>();
409
+ for (const row of rows) if (row.kind === "refusal" && row.overrides === "pass") converted.add(row.attemptID);
410
+ for (const row of rows) {
411
+ if (row.kind !== "decision") continue;
412
+ if (isAnnotationRow(row)) {
413
+ // Signals: one row per attempt and kind, first wins (ingest's own identity and the store's one-observation rule);
414
+ // `attemptID` when the row carries it, else the child session. Other annotations: per attempt and reason.
415
+ const attempt = row.attemptID ?? row.childSessionID;
416
+ const id = JSON.stringify(row.signal !== undefined
417
+ ? ["signal", row.decisionID, attempt, row.signal]
418
+ : ["note", row.decisionID, attempt, row.reason, row.binding ?? null]);
419
+ if (seenNotes.has(id)) continue;
420
+ seenNotes.add(id);
421
+ annotations.push(row);
422
+ } else if (!dispatchByID.has(row.decisionID)) {
423
+ dispatchByID.set(row.decisionID, row);
424
+ }
425
+ }
426
+
427
+ const buckets = new Map<string, RoleTierAcc>();
428
+ const bucket = (role: string, tier: string): RoleTierAcc => {
429
+ const id = JSON.stringify([role, tier]);
430
+ let acc = buckets.get(id);
431
+ if (acc === undefined) {
432
+ acc = { role, tier, dispatches: 0, explored: 0, unknownBindings: 0, signals: new Map(), keys: new Set(), costs: new Map() };
433
+ buckets.set(id, acc);
434
+ }
435
+ return acc;
436
+ };
437
+ /**
438
+ * Role and tier of an annotation: when its dispatch row exists, that row's role AND tier only (a dispatch without a role
439
+ * is tier mode: unattributed); else the annotation's own. Null without a role.
440
+ */
441
+ const placeOf = (row: DecisionRow): RoleTierAcc | null => {
442
+ const dispatch = dispatchByID.get(row.decisionID);
443
+ const source = dispatch ?? row;
444
+ const role = roleOf(source);
445
+ if (role === undefined) return null;
446
+ return bucket(role, source.tier ?? UNKNOWN_TIER);
447
+ };
448
+
449
+ const unknownBindingSeen = new Set<string>();
450
+ const noteUnknownBinding = (row: DecisionRow, acc: RoleTierAcc | null): boolean => {
451
+ if (row.binding !== "unknown") return false;
452
+ const id = JSON.stringify([row.decisionID, row.childSessionID]);
453
+ if (unknownBindingSeen.has(id)) return false;
454
+ unknownBindingSeen.add(id);
455
+ if (acc !== null) acc.unknownBindings += 1;
456
+ return acc === null;
457
+ };
458
+
459
+ let unattributedSignals = 0;
460
+ let unattributedBindings = 0;
461
+ for (const row of dispatchByID.values()) {
462
+ const role = roleOf(row);
463
+ if (!inWindow(row) || role === undefined) continue;
464
+ const acc = bucket(role, row.tier ?? UNKNOWN_TIER);
465
+ if (noteUnknownBinding(row, acc)) unattributedBindings += 1;
466
+ if (row.step !== "dispatch") continue;
467
+ acc.dispatches += 1;
468
+ if (row.explore === true) acc.explored += 1;
469
+ const key = dispatchedKey(row);
470
+ acc.keys.add(key);
471
+ const cost = row.costs[key];
472
+ if (typeof cost === "number" && Number.isFinite(cost)) {
473
+ const list = acc.costs.get(row.unit) ?? [];
474
+ list.push(cost);
475
+ acc.costs.set(row.unit, list);
476
+ }
477
+ }
478
+ for (const row of annotations) {
479
+ if (!inWindow(row)) continue;
480
+ const acc = placeOf(row);
481
+ if (noteUnknownBinding(row, acc)) unattributedBindings += 1;
482
+ const kind = row.signal;
483
+ if (kind === undefined) continue;
484
+ if (acc === null) {
485
+ unattributedSignals += 1;
486
+ continue;
487
+ }
488
+ const cell = acc.signals.get(kind) ?? { pass: 0, fail: 0, none: 0, positive: 0, negative: 0 };
489
+ const overridden = (kind === "verdict" || kind === "grader") && row.attemptID !== undefined && converted.has(row.attemptID) && (row.signalWeight ?? 0) > 0;
490
+ const mass = signalMass(kind, overridden ? -1 : row.signalWeight);
491
+ if (mass.positive > 0) cell.pass += 1;
492
+ else if (mass.negative > 0) cell.fail += 1;
493
+ else cell.none += 1;
494
+ cell.positive += mass.positive;
495
+ cell.negative += mass.negative;
496
+ acc.signals.set(kind, cell);
497
+ }
498
+
499
+ const byRoleTier: RoleTierStatsRow[] = [...buckets.values()]
500
+ .sort((a, b) => compareCodeUnits(a.role, b.role) || compareCodeUnits(a.tier, b.tier))
501
+ .map((acc) => {
502
+ const signals: SignalKindStats[] = SIGNAL_KINDS.map((kind) => ({
503
+ kind,
504
+ ...(acc.signals.get(kind) ?? { pass: 0, fail: 0, none: 0, positive: 0, negative: 0 }),
505
+ }));
506
+ const costUnits: CostUnitRow[] = [...acc.costs.keys()].sort(compareCodeUnits).map((unit) => {
507
+ const list = acc.costs.get(unit) ?? [];
508
+ return { unit, total: stableSum(list), rows: list.length };
509
+ });
510
+ const count = (kind: SignalKind): number => {
511
+ const s = acc.signals.get(kind);
512
+ return s === undefined ? 0 : s.pass + s.fail + s.none;
513
+ };
514
+ return {
515
+ role: acc.role,
516
+ tier: acc.tier,
517
+ dispatches: acc.dispatches,
518
+ signals,
519
+ positiveMass: stableSum(signals.map((s) => s.positive)),
520
+ negativeMass: stableSum(signals.map((s) => s.negative)),
521
+ budgetExhaustions: count("budget"),
522
+ authorityRequests: count("authority"),
523
+ unknownBindings: acc.unknownBindings,
524
+ explored: acc.explored,
525
+ tokensPerDispatch: store === null ? null : pooledTokens(store, acc.keys),
526
+ measuredUSD: store === null ? null : pooledUSD(store, acc.keys),
527
+ costUnits,
528
+ };
529
+ });
530
+
531
+ return {
532
+ version: 1,
533
+ window: { since: isoOrNull(since), until: isoOrNull(until) },
534
+ byRoleTier,
535
+ unattributed: { signals: unattributedSignals, unknownBindings: unattributedBindings },
536
+ };
537
+ }
538
+
307
539
  // ---------------------------------------------------------------------------
308
540
  // renderMarkdown
309
541
  // ---------------------------------------------------------------------------
@@ -424,6 +656,37 @@ export function renderMarkdown(table: StatsTable): string {
424
656
  return blocks.join("\n\n") + "\n";
425
657
  }
426
658
 
659
+ /**
660
+ * True when the log has role rows: a role dispatch bucket, or an unknown-binding row (only role dispatches are bound). Unattributed
661
+ * SIGNAL rows do not count: tier-origin verdict/run signals are written in every mode, so tier-only logs render exactly as before.
662
+ */
663
+ export function hasRoleRows(table: RoleStatsTable): boolean {
664
+ return table.byRoleTier.length > 0 || table.unattributed.unknownBindings > 0;
665
+ }
666
+
667
+ /** P2.2: the role × tier section appended to the report when the log has role rows. Same determinism rules as {@link renderMarkdown}. */
668
+ export function renderRoleMarkdown(table: RoleStatsTable): string {
669
+ const rows =
670
+ table.byRoleTier.length === 0
671
+ ? "_none_"
672
+ : [
673
+ "| Role | Tier | Dispatches | Pass | Fail | +mass | -mass | Budget exhaustions | Authority requests | Unknown bindings | Explored | Tokens/dispatch (in/out) | USD/attempt (lifetime) |",
674
+ "|---|---|---|---|---|---|---|---|---|---|---|---|---|",
675
+ ...table.byRoleTier.map((r) => {
676
+ const pass = r.signals.reduce((sum, s) => sum + s.pass, 0);
677
+ const fail = r.signals.reduce((sum, s) => sum + s.fail, 0);
678
+ const tokens = r.tokensPerDispatch === null ? "n/a" : `${fix(r.tokensPerDispatch.input, 0)}/${fix(r.tokensPerDispatch.output, 0)} (n=${r.tokensPerDispatch.n})`;
679
+ const usd = r.measuredUSD === null ? "n/a" : `${fmtUSD(r.measuredUSD.mean)} (n=${r.measuredUSD.n})`;
680
+ return `| ${cell(r.role)} | ${cell(r.tier)} | ${r.dispatches} | ${pass} | ${fail} | ${fix(r.positiveMass, 2)} | ${fix(r.negativeMass, 2)} | ${r.budgetExhaustions} | ${r.authorityRequests} | ${r.unknownBindings} | ${r.explored} | ${tokens} | ${usd} |`;
681
+ }),
682
+ ].join("\n");
683
+ const blocks = ["### By role × tier", rows];
684
+ if (table.unattributed.signals > 0 || table.unattributed.unknownBindings > 0) {
685
+ blocks.push(`_Not attributed to a role: ${table.unattributed.signals} signal row(s), ${table.unattributed.unknownBindings} unknown binding(s)._`);
686
+ }
687
+ return blocks.join("\n\n") + "\n";
688
+ }
689
+
427
690
  // ---------------------------------------------------------------------------
428
691
  // Arguments and CLI
429
692
  // ---------------------------------------------------------------------------
@@ -589,7 +852,15 @@ export async function runStatsCli(argv: readonly string[], io: StatsCliIO): Prom
589
852
  }
590
853
 
591
854
  const table = summarize(store, read.rows, { since: args.since, until: args.until });
592
- io.stdout(args.json ? JSON.stringify(table, null, 2) + "\n" : renderMarkdown(table));
855
+ const roles = summarizeRoles(store, read.rows, { since: args.since, until: args.until });
856
+ const withRoles = hasRoleRows(roles);
857
+ io.stdout(
858
+ args.json
859
+ ? JSON.stringify(withRoles ? { ...table, roles } : table, null, 2) + "\n"
860
+ : withRoles
861
+ ? `${renderMarkdown(table)}\n${renderRoleMarkdown(roles)}`
862
+ : renderMarkdown(table),
863
+ );
593
864
  return STATS_EXIT.ok;
594
865
  } catch (error) {
595
866
  try {
@@ -89,6 +89,8 @@ interface ScoredInfo {
89
89
  readonly at: number;
90
90
  /** The scoring signal was a `variant` step. */
91
91
  readonly variant: boolean;
92
+ /** QA-P33F2-1-1: the Beta weight the observation carried (1, or 0.5 for an independent grader); absent = 1. */
93
+ readonly weight?: number;
92
94
  }
93
95
 
94
96
  // ---------------------------------------------------------------------------
@@ -418,8 +420,10 @@ export function createOutcomeStore(options: OutcomeStoreOptions = {}): OutcomeSt
418
420
  });
419
421
  },
420
422
 
421
- recordVerdict(key: OutcomeKey, verdict: Verdict, signal: AttemptSignal): boolean {
423
+ recordVerdict(key: OutcomeKey, verdict: Verdict, signal: AttemptSignal, weight = 1): boolean {
422
424
  if (verdict !== "pass" && verdict !== "fail") return false;
425
+ // QA-P33F2-1-1: a weighted observation (an independent grader's 0.5) never weighs more than one, nor nothing.
426
+ if (!(Number.isFinite(weight) && weight > 0 && weight <= 1)) return false;
423
427
  const previous = scored.get(signal.attemptID);
424
428
  if (previous !== undefined) {
425
429
  remember(scored, signal.attemptID, previous, maxScored);
@@ -430,7 +434,7 @@ export function createOutcomeStore(options: OutcomeStoreOptions = {}): OutcomeSt
430
434
  const pass = verdict === "pass";
431
435
  const variant = signal.step === "variant";
432
436
  const t = clockNow();
433
- entry.beta = observe(entry.beta, pass, t, tuning);
437
+ entry.beta = observe(entry.beta, pass, t, tuning, weight);
434
438
  const c = entry.counts;
435
439
  entry.counts = {
436
440
  pass: c.pass + (pass ? 1 : 0),
@@ -439,7 +443,7 @@ export function createOutcomeStore(options: OutcomeStoreOptions = {}): OutcomeSt
439
443
  variantPass: c.variantPass + (variant && pass ? 1 : 0),
440
444
  variantFail: c.variantFail + (variant && !pass ? 1 : 0),
441
445
  };
442
- remember(scored, signal.attemptID, { key, kind: pass ? "pass" : "fail", at: t, variant }, maxScored);
446
+ remember(scored, signal.attemptID, { key, kind: pass ? "pass" : "fail", at: t, variant, ...(weight === 1 ? {} : { weight }) }, maxScored);
443
447
  revision += 1;
444
448
  return true;
445
449
  },
@@ -464,7 +468,8 @@ export function createOutcomeStore(options: OutcomeStoreOptions = {}): OutcomeSt
464
468
  // of alpha (floored at 0; an approximation once the cap has rescaled the evidence) and move the
465
469
  // counters pass → fail.
466
470
  const decayed = decayTo(entry.beta, t, tuning);
467
- const contribution = decayFactor(t - previous.at, tuning.halfLifeDays);
471
+ // QA-P33F2-1-1: a weighted pass (an independent grader's 0.5) gives back only what it added.
472
+ const contribution = decayFactor(t - previous.at, tuning.halfLifeDays) * (previous.weight ?? 1);
468
473
  entry.beta = capEvidence(
469
474
  { alpha: Math.max(0, decayed.alpha - contribution), beta: decayed.beta + 1, updatedAt: decayed.updatedAt },
470
475
  tuning.maxEffectiveSamples,
@@ -480,7 +485,22 @@ export function createOutcomeStore(options: OutcomeStoreOptions = {}): OutcomeSt
480
485
  remember(scored, signal.attemptID, { key, kind: "refusal", at: t, variant: previous.variant }, maxScored);
481
486
  return true;
482
487
  }
483
- // Already a failure (fail verdict or an earlier refusal): lifetime counter only.
488
+ const weight = previous.weight ?? 1;
489
+ if (previous.kind === "fail" && previous.key === key && weight < 1) {
490
+ // QA-P33F2-2 N-a: a weighted failure (an independent grader's 0.5) is topped up to a full failure, as a refusal after
491
+ // a weighted pass ends at one: beta gains 1 − weight × decay, so the attempt weighs one failure now. The fail is already
492
+ // counted; only the lifetime refusal counter moves. Recorded as the refusal, so a repeat tops up nothing.
493
+ const decayed = decayTo(entry.beta, t, tuning);
494
+ const topUp = Math.max(0, 1 - weight * decayFactor(t - previous.at, tuning.halfLifeDays));
495
+ entry.beta = capEvidence(
496
+ { alpha: decayed.alpha, beta: decayed.beta + topUp, updatedAt: decayed.updatedAt },
497
+ tuning.maxEffectiveSamples,
498
+ );
499
+ entry.counts = { ...c, falseRefusals: c.falseRefusals + 1 };
500
+ remember(scored, signal.attemptID, { key, kind: "refusal", at: t, variant: previous.variant }, maxScored);
501
+ return true;
502
+ }
503
+ // Already a full failure (fail verdict or an earlier refusal): lifetime counter only.
484
504
  entry.counts = { ...c, falseRefusals: c.falseRefusals + 1 };
485
505
  remember(scored, signal.attemptID, previous, maxScored);
486
506
  return false;
@@ -40,6 +40,22 @@ export function verdictOf(verdict: Pick<VerificationVerdict, "pass" | "outcome">
40
40
  return verdict.outcome ?? (verdict.pass ? "pass" : "fail");
41
41
  }
42
42
 
43
+ /** #84 P3.3 fix 2: the LLM grader of a gate verdict — the tier the checker asked for and its model (null: unknown). */
44
+ export interface VerdictGrader {
45
+ readonly tier: string | null;
46
+ readonly model: string | null;
47
+ }
48
+
49
+ /**
50
+ * Who judged a gate verdict, for `Ingest.onVerdict` (plan §2.6, I6): a `checker` verdict was judged by an LLM grader — its
51
+ * `grader` (verify/types.ts), else an unknown one (no tier, no model: never independent) — and any other verdict by deterministic
52
+ * checks (`undefined`).
53
+ */
54
+ export function verdictGraderOf(verdict: Pick<VerificationVerdict, "method" | "grader">): VerdictGrader | undefined {
55
+ if (verdict.method !== "checker") return undefined;
56
+ return { tier: verdict.grader?.tier ?? null, model: verdict.grader?.model ?? null };
57
+ }
58
+
43
59
  /**
44
60
  * Kind of attempt a row or signal belongs to. `dispatch` = an orchestrator dispatch routed in
45
61
  * `execute.before` (2.2); the others are `delegate` ladder attempts (1.5 / 2.3): `variant` = same model,
@@ -63,7 +79,13 @@ export type LoggedRoutingMode = "shadow" | "advise" | "enforce";
63
79
  * (native `explore`/`general`, or user-defined in opencode.json) is `host`. The origin is part of the
64
80
  * key, so a router tier and a native agent with the same id never share evidence.
65
81
  */
66
- export type AgentOrigin = "router" | "host";
82
+ export type AgentOrigin = "router" | "host" | "role";
83
+
84
+ /** Kind of signal an outcome observation carries (role/tier assurance, plan §2.4). */
85
+ export type SignalKind = "verdict" | "run" | "grader" | "incomplete" | "budget" | "authority" | "redispatch";
86
+
87
+ /** Fixed order of signal kinds (persistence validation, statistics). */
88
+ export const SIGNAL_KINDS: readonly SignalKind[] = ["verdict", "run", "grader", "incomplete", "budget", "authority", "redispatch"];
67
89
 
68
90
  export interface AgentRef {
69
91
  readonly origin: AgentOrigin;
@@ -79,7 +101,8 @@ export const UNKNOWN_PART = "unknown";
79
101
 
80
102
  /**
81
103
  * Canonical outcome key, e.g. `implement|router:medium|anthropic/claude-sonnet-5-5#medium` or
82
- * `search|host:explore|anthropic/claude-haiku-4-5#default`. Build it only with {@link makeKey}.
104
+ * `search|host:explore|anthropic/claude-haiku-4-5#default`. A role-origin key is
105
+ * `class|role:<agent>|provider/model#variant`. Build it only with {@link makeKey}.
83
106
  */
84
107
  export type OutcomeKey = `${string}|${string}:${string}|${string}/${string}#${string}`;
85
108
 
@@ -166,7 +189,7 @@ export function parseKey(key: string): OutcomeKeyParts | null {
166
189
  const colon = agentSeg.indexOf(":");
167
190
  if (colon < 0) return null;
168
191
  const origin = agentSeg.slice(0, colon);
169
- if (origin !== "router" && origin !== "host") return null;
192
+ if (origin !== "router" && origin !== "host" && origin !== "role") return null;
170
193
 
171
194
  const hash = modelSeg.lastIndexOf("#");
172
195
  if (hash < 0) return null;
@@ -368,7 +391,11 @@ export interface AttemptSignal {
368
391
  readonly step: LadderStepKind;
369
392
  }
370
393
 
371
- /** Lifetime raw counters (integers, never decayed). */
394
+ /**
395
+ * Lifetime raw counters (integers, never decayed). QA-G-B N2: `pass`/`fail` (and `variantPass`/`variantFail`) count scored
396
+ * VERDICTS, one per attempt whatever its weight — an independent grader's 0.5 observation adds 1 here, as a deterministic
397
+ * verdict does. The evidence mass (0.5 vs 1) lives in `beta` only; read these as "how many verdicts", never as evidence.
398
+ */
372
399
  export interface OutcomeCounts {
373
400
  readonly pass: number;
374
401
  readonly fail: number;
@@ -408,8 +435,12 @@ export interface OutcomeStore {
408
435
  readonly revision: number;
409
436
  /** Hot reload of `routing.outcomes` (applied lazily on the next read/write). */
410
437
  configure(tuning: Partial<OutcomeTuning>): void;
411
- /** D4: pass → success, fail → failure, unverifiable → strict no-op. Returns whether the Beta changed. */
412
- recordVerdict(key: OutcomeKey, verdict: Verdict, signal: AttemptSignal): boolean;
438
+ /**
439
+ * D4: pass → success, fail → failure, unverifiable → strict no-op. Returns whether the Beta changed. `weight` (QA-P33F2-1-1,
440
+ * default 1): the observation's Beta weight in (0, 1] — an independent grader's verdict of a role dispatch weighs 0.5 (plan
441
+ * §2.6); any other value records nothing. The lifetime counters count the verdict once whatever its weight.
442
+ */
443
+ recordVerdict(key: OutcomeKey, verdict: Verdict, signal: AttemptSignal, weight?: number): boolean;
413
444
  /** D4: a false refusal is a failure of the key. Returns whether the Beta changed. */
414
445
  recordFalseRefusal(key: OutcomeKey, signal: AttemptSignal): boolean;
415
446
  /** Accumulate one step into its attempt; a `final` step folds the attempt into `cost(key)`. */
@@ -533,8 +564,21 @@ export interface DecisionTrace {
533
564
  * cheapest option the engine could not trust yet. `routing:stats` counts these to show where the gate holds it back.
534
565
  */
535
566
  readonly argmin?: RouteChoice;
567
+ /**
568
+ * #84 QA-G-B-3 (3), role dispatches only: why each need of `facts.needs` could be there — the classifier's matched terms
569
+ * (`edit:create`, `external_dir:<path>`, `shell:implied-by-network`), `<need>:route-line`, `<need>:class=<class>` and, on a resume,
570
+ * `<need>:resumed-dispatch`. Before any narrowing: `facts.needs` is what was decided.
571
+ */
572
+ readonly needTerms?: readonly string[];
536
573
  }
537
574
 
575
+ /**
576
+ * #84 QA-G-B-2-2 (D14): the shape of one `DecisionTrace.needTerms` entry — `<need>:<label>` with a vocabulary word, a term id,
577
+ * a placeholder (`url`, `path`) or a router label (`route-line`, `class=<c>`, `implied-by-<need>`, `resumed-dispatch`). An entry
578
+ * of any other shape could carry prompt text and is dropped when a row is read.
579
+ */
580
+ export const NEED_TERM_RE = /^[a-z_]+:[a-z0-9=_ -]{1,48}$/;
581
+
538
582
  /** One routed dispatch (2.2) or one ladder attempt (2.3). Fields of §0.11 plus kind/v/decisionID/step/resume. */
539
583
  export interface DecisionRow extends LogRowBase {
540
584
  readonly kind: "decision";
@@ -566,6 +610,49 @@ export interface DecisionRow extends LogRowBase {
566
610
  readonly detection?: DecisionDetection;
567
611
  /** A34 (QA-G-B8): capability ranks of the pick and of what the host was handed. Absent on older rows and on ladder attempts. */
568
612
  readonly capability?: DecisionCapability;
613
+ /** Role/tier assurance (plan §2.4), all optional; absent on older rows. Agent name of the role the dispatch ran as. */
614
+ readonly role?: string;
615
+ /** Sorted authority action names granted to the dispatch. */
616
+ readonly grant?: readonly string[];
617
+ /** Bounds that limited the dispatch. */
618
+ readonly boundsReasons?: readonly string[];
619
+ /** Budget consumed by the attempt. */
620
+ readonly budgetUsed?: number;
621
+ /** Signal kind this row carries. */
622
+ readonly signal?: SignalKind;
623
+ /** The pick was an exploration draw. */
624
+ readonly explore?: boolean;
625
+ /** Probability with which the pick was drawn. */
626
+ readonly propensity?: number;
627
+ /** How the grant was bound to the child's permissions. */
628
+ readonly binding?: "exact" | "intersection" | "unknown";
629
+ /** P1.4: preset tier the dispatch ran at (role × tier statistics; the outcome key does not name it). */
630
+ readonly tier?: string;
631
+ /**
632
+ * P1.4: signed evidence mass of a signal row (`signal` set): > 0 success, < 0 failure, 0 recorded without mass
633
+ * (budget, authority). Readers clamp it per kind (signals.ts `signalMass`), so a row can never carry more than §2.6 allows.
634
+ */
635
+ readonly signalWeight?: number;
636
+ /** P1.4: the attempt an annotation row belongs to (ingest dedupes signals per attempt and kind; statistics do too). */
637
+ readonly attemptID?: string;
638
+ }
639
+
640
+ /**
641
+ * Reason prefix of a decision row written AFTER its dispatch to annotate it (an outcome signal, a binding): it shares the
642
+ * dispatch's `decisionID` and is never a dispatch of its own. `summarize` leaves every annotation row out.
643
+ */
644
+ export const ANNOTATION_REASON = "note:";
645
+
646
+ /** Reason prefix of a signal row: `note:signal:<kind>:<pass|fail|none>`. */
647
+ export const SIGNAL_REASON = "note:signal:";
648
+
649
+ /**
650
+ * A decision row that annotates a dispatch: its reason starts with {@link ANNOTATION_REASON} (the prefix alone decides;
651
+ * a `signal` field on a row with any other reason is just a field of a dispatch row). Readers before P1.4 drop annotation
652
+ * rows only through the C7 decision-id dedupe, so downgrading past P1.4 is unsupported (CHANGELOG, P3.2).
653
+ */
654
+ export function isAnnotationRow(row: LogRow): boolean {
655
+ return row.kind === "decision" && row.reason.startsWith(ANNOTATION_REASON);
569
656
  }
570
657
 
571
658
  /** The `[acceptance]` depth vocabulary of 1.2 (`Detection`), restated here so this module keeps no runtime import. */
@@ -940,6 +1027,58 @@ export interface StatsTable {
940
1027
  readonly neverDown: { readonly below: number; readonly recorded: number };
941
1028
  }
942
1029
 
1030
+ /** One signal kind of a role × tier bucket. Masses are clamped per kind (I6: no positive mass from self-report; I7: none for budget/authority). */
1031
+ export interface SignalKindStats {
1032
+ readonly kind: SignalKind;
1033
+ readonly pass: number;
1034
+ readonly fail: number;
1035
+ /** Rows recorded without mass (budget, authority, or a row without a weight). */
1036
+ readonly none: number;
1037
+ readonly positive: number;
1038
+ readonly negative: number;
1039
+ }
1040
+
1041
+ /** Σ of the dispatched key's `costs` entry over the bucket's dispatch rows of one unit. Units are never summed together. */
1042
+ export interface CostUnitRow {
1043
+ readonly unit: CostUnit;
1044
+ readonly total: number;
1045
+ readonly rows: number;
1046
+ }
1047
+
1048
+ /** P1.4: statistics of one role × tier bucket over the window (rendering is P2.2). */
1049
+ export interface RoleTierStatsRow {
1050
+ readonly role: string;
1051
+ /** Preset tier of the dispatch rows (`DecisionRow.tier`); `unknown` when a row carries none. */
1052
+ readonly tier: string;
1053
+ /** Windowed `dispatch` rows of the role at this tier (fresh and resumed; annotation rows excluded). */
1054
+ readonly dispatches: number;
1055
+ /** Fixed order: SIGNAL_KINDS. */
1056
+ readonly signals: readonly SignalKindStats[];
1057
+ readonly positiveMass: number;
1058
+ readonly negativeMass: number;
1059
+ readonly budgetExhaustions: number;
1060
+ readonly authorityRequests: number;
1061
+ readonly unknownBindings: number;
1062
+ /** Dispatch rows drawn by exploration (`explore: true`). */
1063
+ readonly explored: number;
1064
+ /** n-weighted store token means per attempt over the bucket's dispatched keys (lifetime, not windowed); null without samples. */
1065
+ readonly tokensPerDispatch: TokenMeans | null;
1066
+ /** n-weighted store `measuredUSD` per attempt over the bucket's dispatched keys (lifetime); null without samples. */
1067
+ readonly measuredUSD: MeanStat | null;
1068
+ /** One entry per unit present, sorted by unit name. */
1069
+ readonly costUnits: readonly CostUnitRow[];
1070
+ }
1071
+
1072
+ /** P1.4: role × tier statistics. Rows without a role (tier mode) are not counted here; `summarize` is unchanged for them. */
1073
+ export interface RoleStatsTable {
1074
+ readonly version: 1;
1075
+ readonly window: { readonly since: string | null; readonly until: string | null };
1076
+ /** Sorted by role, then tier. */
1077
+ readonly byRoleTier: readonly RoleTierStatsRow[];
1078
+ /** Windowed signal and unknown-binding rows whose dispatch has no role (or no decision row to join). */
1079
+ readonly unattributed: { readonly signals: number; readonly unknownBindings: number };
1080
+ }
1081
+
943
1082
  /** What the CLI reads from a directory (a Persister satisfies it). */
944
1083
  export type StatsSource = Pick<Persister, "dir" | "load" | "readRows">;
945
1084