opencode-model-router 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +90 -12
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +24 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +1435 -44
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +496 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/guard/enforce.ts +186 -22
  13. package/src/guard/guards.ts +132 -6
  14. package/src/guard/store.ts +5 -0
  15. package/src/index.ts +1193 -56
  16. package/src/router/build-info.ts +151 -0
  17. package/src/router/config.ts +1611 -19
  18. package/src/router/dispatch-header.ts +46 -4
  19. package/src/router/git-tools.ts +1152 -0
  20. package/src/router/guard-profile.ts +100 -0
  21. package/src/router/plugin-agents.ts +433 -0
  22. package/src/router/prompts.ts +26 -1
  23. package/src/router/protocol.ts +180 -0
  24. package/src/router/read-only.ts +149 -0
  25. package/src/router/role-agents.ts +409 -0
  26. package/src/router/roles-config.ts +429 -0
  27. package/src/router/roles.ts +600 -0
  28. package/src/router/run-tools.ts +913 -0
  29. package/src/router/sensitive-paths.ts +101 -0
  30. package/src/router/sessions.ts +533 -9
  31. package/src/router/subagents.ts +28 -1
  32. package/src/routing/advisor/findings.ts +898 -0
  33. package/src/routing/advisor/index.ts +614 -0
  34. package/src/routing/classify/backends/host.ts +163 -0
  35. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  36. package/src/routing/classify/backends/shared.ts +741 -0
  37. package/src/routing/classify/backends/typesafe.ts +315 -0
  38. package/src/routing/classify/fences.ts +96 -0
  39. package/src/routing/classify/index.ts +594 -0
  40. package/src/routing/classify/route-line.ts +362 -0
  41. package/src/routing/classify/rules.ts +667 -0
  42. package/src/routing/classify/scrub.ts +214 -0
  43. package/src/routing/classify/state.ts +148 -0
  44. package/src/routing/classify/text.ts +20 -0
  45. package/src/routing/classify/types.ts +1310 -0
  46. package/src/routing/commands/annotate-plan.ts +652 -0
  47. package/src/routing/commands/stats.ts +134 -0
  48. package/src/routing/commands/v1-roles.ts +64 -0
  49. package/src/routing/engine/index.ts +32 -0
  50. package/src/routing/engine/kernel.ts +760 -0
  51. package/src/routing/engine/ladders.ts +802 -0
  52. package/src/routing/engine/plan.ts +404 -0
  53. package/src/routing/engine/protocol-line.ts +150 -0
  54. package/src/routing/engine/roles-taxonomy.ts +52 -0
  55. package/src/routing/engine/simulate.ts +167 -0
  56. package/src/routing/engine/types.ts +368 -0
  57. package/src/routing/file-lock.ts +53 -0
  58. package/src/routing/outcomes/beta.ts +147 -0
  59. package/src/routing/outcomes/cost.ts +313 -0
  60. package/src/routing/outcomes/index.ts +215 -0
  61. package/src/routing/outcomes/ingest.ts +960 -0
  62. package/src/routing/outcomes/persist.ts +1080 -0
  63. package/src/routing/outcomes/signals.ts +650 -0
  64. package/src/routing/outcomes/stats.ts +873 -0
  65. package/src/routing/outcomes/store.ts +673 -0
  66. package/src/routing/outcomes/types.ts +1093 -0
  67. package/src/routing/roles/authority.ts +495 -0
  68. package/src/routing/roles/binding.ts +543 -0
  69. package/src/routing/roles/policy.ts +416 -0
  70. package/src/routing/roles/work-root.ts +132 -0
  71. package/src/routing/wire/dispatch.ts +2088 -0
  72. package/src/routing/wire/hint.ts +222 -0
  73. package/src/routing/wire/host-info.ts +256 -0
  74. package/src/routing/wire/runtime.ts +348 -0
  75. package/src/v2.ts +40 -1
  76. package/src/verify/checker.ts +249 -7
  77. package/src/verify/deterministic.ts +10 -1
  78. package/src/verify/dispatch.ts +63 -6
  79. package/src/verify/dod.ts +127 -10
  80. package/src/verify/gate.ts +75 -7
  81. package/src/verify/types.ts +12 -0
  82. package/src/verify/wiring.ts +55 -10
  83. package/tiers.json +13 -5
@@ -0,0 +1,1093 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Outcome store and cost accounting (M3) — shared types, outcome keys and persistence constants.
3
+ //
4
+ // Design: D:\git\opencode-model-router\docs\qa\cost-aware-routing\phase-1.3.md "Design (1.3.1)".
5
+ // Pure module: no I/O and no runtime import. Every module under src/routing/outcomes/ must stay
6
+ // runnable under Node's type stripping (scripts/routing-stats.ts runs without tsx), so:
7
+ // - type-only symbols are imported/re-exported with `import type` / `export type`;
8
+ // - no enum, namespace, parameter property or `import x = require(...)`;
9
+ // - runtime imports stay inside src/routing/outcomes/ (plus `node:` builtins in persist.ts).
10
+ // ---------------------------------------------------------------------------
11
+
12
+ import type { Verdict as VerificationVerdict } from "../../verify/types";
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // Primitives
16
+ // ---------------------------------------------------------------------------
17
+
18
+ /** Injected clock: epoch milliseconds. Defaults to `Date.now` in the implementations. */
19
+ export type Clock = () => number;
20
+
21
+ /** One reading of an injected clock; a non-finite reading (NaN, ±Infinity) falls back to `Date.now()` (QA-1.3-7). */
22
+ export function safeNow(clock: Clock): number {
23
+ const t = clock();
24
+ return Number.isFinite(t) ? t : Date.now();
25
+ }
26
+
27
+ /** D5: the unit every candidate of one decision is compared in. Never mixed. */
28
+ export type CostUnit = "usd" | "ratio";
29
+
30
+ /** D4: verified outcome of one attempt. `unverifiable` updates nothing in the store. */
31
+ export type Verdict = "pass" | "fail" | "unverifiable";
32
+
33
+ type Equals<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
34
+ type AssertTrue<T extends true> = T;
35
+ /** Compile-time guard: `Verdict` stays identical to the verifier's `outcome` union (src/verify/types.ts:14). */
36
+ export type VerdictMatchesVerifier = AssertTrue<Equals<Verdict, NonNullable<VerificationVerdict["outcome"]>>>;
37
+
38
+ /** Outcome of a verifier verdict, derived exactly like the existing call sites (`outcome ?? (pass ? "pass" : "fail")`). */
39
+ export function verdictOf(verdict: Pick<VerificationVerdict, "pass" | "outcome">): Verdict {
40
+ return verdict.outcome ?? (verdict.pass ? "pass" : "fail");
41
+ }
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
+
59
+ /**
60
+ * Kind of attempt a row or signal belongs to. `dispatch` = an orchestrator dispatch routed in
61
+ * `execute.before` (2.2); the others are `delegate` ladder attempts (1.5 / 2.3): `variant` = same model,
62
+ * next variant (D10); `retry` = within-tier retry (existing effortBump path); `escalate` = next model/agent.
63
+ */
64
+ export type LadderStepKind = "dispatch" | "variant" | "retry" | "escalate";
65
+
66
+ /** Fixed rendering order of ladder step kinds (stats, markdown). */
67
+ export const LADDER_STEP_KINDS: readonly LadderStepKind[] = ["dispatch", "variant", "retry", "escalate"];
68
+
69
+ /** Modes that write decision rows. `static` writes nothing (§1.2, D2). */
70
+ export type LoggedRoutingMode = "shadow" | "advise" | "enforce";
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // Outcome keys — `${class}|${agent}|${provider}/${model}#${variant ?? "default"}`
74
+ // ---------------------------------------------------------------------------
75
+
76
+ /**
77
+ * Where an agent's behaviour comes from. A router tier agent (`fast`, `medium`, ... of the active
78
+ * preset; system prompt and model set by this plugin) is `router`; every other agent the host knows
79
+ * (native `explore`/`general`, or user-defined in opencode.json) is `host`. The origin is part of the
80
+ * key, so a router tier and a native agent with the same id never share evidence.
81
+ */
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"];
89
+
90
+ export interface AgentRef {
91
+ readonly origin: AgentOrigin;
92
+ readonly id: string;
93
+ }
94
+
95
+ /** Variant stored for a child dispatched without a variant (amendment A9). */
96
+ export const DEFAULT_VARIANT = "default";
97
+ /** Class stored when the class segment is empty (TaskClass catch-all of 1.2). */
98
+ export const FALLBACK_CLASS = "other";
99
+ /** Stored for an empty agent id, provider or model (makeKey never throws on the hot path). */
100
+ export const UNKNOWN_PART = "unknown";
101
+
102
+ /**
103
+ * Canonical outcome key, e.g. `implement|router:medium|anthropic/claude-sonnet-5-5#medium` or
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}.
106
+ */
107
+ export type OutcomeKey = `${string}|${string}:${string}|${string}/${string}#${string}`;
108
+
109
+ export interface OutcomeKeyParts {
110
+ readonly cls: string;
111
+ readonly agent: AgentRef;
112
+ readonly provider: string;
113
+ readonly model: string;
114
+ readonly variant: string;
115
+ }
116
+
117
+ const ESCAPES: Readonly<Record<string, string>> = {
118
+ "%": "%25",
119
+ "|": "%7C",
120
+ "#": "%23",
121
+ ":": "%3A",
122
+ "/": "%2F",
123
+ };
124
+ const UNESCAPES: Readonly<Record<string, string>> = {
125
+ "%25": "%",
126
+ "%7C": "|",
127
+ "%23": "#",
128
+ "%3A": ":",
129
+ "%2F": "/",
130
+ };
131
+ /** Characters escaped in class, agent id, provider and variant segments. */
132
+ const STRICT_CHARS = "%|#:/";
133
+ /** Characters escaped in the model segment (model ids may contain `/` and `:`). */
134
+ const MODEL_CHARS = "%|#";
135
+
136
+ function escapePart(value: string, chars: string): string {
137
+ let out = "";
138
+ for (const ch of value) out += chars.includes(ch) ? (ESCAPES[ch] ?? ch) : ch;
139
+ return out;
140
+ }
141
+
142
+ function unescapePart(value: string): string | null {
143
+ let out = "";
144
+ for (let i = 0; i < value.length; i++) {
145
+ const ch = value[i];
146
+ if (ch !== "%") {
147
+ out += ch;
148
+ continue;
149
+ }
150
+ const decoded = UNESCAPES[value.slice(i, i + 3)];
151
+ if (decoded === undefined) return null;
152
+ out += decoded;
153
+ i += 2;
154
+ }
155
+ return out;
156
+ }
157
+
158
+ /** A9: absent or empty variant → `"default"`. Other values are kept verbatim (catalog ids are case-sensitive). */
159
+ export function normalizeVariant(variant: string | null | undefined): string {
160
+ return variant === undefined || variant === null || variant === "" ? DEFAULT_VARIANT : variant;
161
+ }
162
+
163
+ /**
164
+ * Build the outcome key. Never throws: empty class → `other`, empty agent id/provider/model →
165
+ * `unknown`, empty variant → `default`. Delimiters inside a part are percent-escaped so that
166
+ * `parseKey(makeKey(...))` round-trips every input.
167
+ */
168
+ export function makeKey(
169
+ cls: string,
170
+ agent: AgentRef,
171
+ provider: string,
172
+ model: string,
173
+ variant?: string | null,
174
+ ): OutcomeKey {
175
+ const c = escapePart(cls === "" ? FALLBACK_CLASS : cls, STRICT_CHARS);
176
+ const a = escapePart(agent.id === "" ? UNKNOWN_PART : agent.id, STRICT_CHARS);
177
+ const p = escapePart(provider === "" ? UNKNOWN_PART : provider, STRICT_CHARS);
178
+ const m = escapePart(model === "" ? UNKNOWN_PART : model, MODEL_CHARS);
179
+ const v = escapePart(normalizeVariant(variant), STRICT_CHARS);
180
+ return `${c}|${agent.origin}:${a}|${p}/${m}#${v}` as OutcomeKey;
181
+ }
182
+
183
+ /** Inverse of {@link makeKey}; `null` unless `makeKey(parts) === key` (anything makeKey cannot produce). */
184
+ export function parseKey(key: string): OutcomeKeyParts | null {
185
+ const segments = key.split("|");
186
+ if (segments.length !== 3) return null;
187
+ const [clsSeg, agentSeg, modelSeg] = segments as [string, string, string];
188
+
189
+ const colon = agentSeg.indexOf(":");
190
+ if (colon < 0) return null;
191
+ const origin = agentSeg.slice(0, colon);
192
+ if (origin !== "router" && origin !== "host" && origin !== "role") return null;
193
+
194
+ const hash = modelSeg.lastIndexOf("#");
195
+ if (hash < 0) return null;
196
+ const providerModel = modelSeg.slice(0, hash);
197
+ const slash = providerModel.indexOf("/");
198
+ if (slash < 0) return null;
199
+
200
+ const cls = unescapePart(clsSeg);
201
+ const id = unescapePart(agentSeg.slice(colon + 1));
202
+ const provider = unescapePart(providerModel.slice(0, slash));
203
+ const model = unescapePart(providerModel.slice(slash + 1));
204
+ const variant = unescapePart(modelSeg.slice(hash + 1));
205
+ if (!cls || !id || !provider || !model || !variant) return null;
206
+ const parts: OutcomeKeyParts = { cls, agent: { origin, id }, provider, model, variant };
207
+ // Canonical form only (QA-1.3-12): a key that makeKey would not have produced (an unescaped `:`/`/` in
208
+ // a strict part, lowercase `%7c`, ...) would otherwise alias a canonical key in the store.
209
+ return makeKey(cls, parts.agent, provider, model, variant) === key ? parts : null;
210
+ }
211
+
212
+ /** `"provider/model"` or `"provider/model#variant"` (host `subagent` model syntax) → parts; `null` when malformed. */
213
+ export function splitModelRef(
214
+ ref: string,
215
+ ): { readonly provider: string; readonly model: string; readonly variant: string | null } | null {
216
+ const slash = ref.indexOf("/");
217
+ if (slash <= 0) return null;
218
+ const hash = ref.lastIndexOf("#");
219
+ const end = hash > slash ? hash : ref.length;
220
+ const model = ref.slice(slash + 1, end);
221
+ if (model === "") return null;
222
+ const variant = hash > slash ? ref.slice(hash + 1) : null;
223
+ return { provider: ref.slice(0, slash), model, variant: variant === "" ? null : variant };
224
+ }
225
+
226
+ /** Origin rule: an id that names a router tier agent of the active preset is `router`; anything else is `host`. */
227
+ export function classifyAgentOrigin(
228
+ agentId: string,
229
+ routerAgentIds: ReadonlySet<string> | readonly string[],
230
+ ): AgentOrigin {
231
+ const isRouter = isIdList(routerAgentIds) ? routerAgentIds.includes(agentId) : routerAgentIds.has(agentId);
232
+ return isRouter ? "router" : "host";
233
+ }
234
+
235
+ function isIdList(ids: ReadonlySet<string> | readonly string[]): ids is readonly string[] {
236
+ return Array.isArray(ids);
237
+ }
238
+
239
+ // ---------------------------------------------------------------------------
240
+ // Beta posteriors (beta.ts) — D4, D7, decay, effective-sample cap
241
+ // ---------------------------------------------------------------------------
242
+
243
+ /** `routing.outcomes` tuning (1.1 validates: halfLifeDays ∈ [1, 365], maxEffectiveSamples ∈ [5, 1000]). */
244
+ export interface OutcomeTuning {
245
+ readonly halfLifeDays: number;
246
+ readonly maxEffectiveSamples: number;
247
+ }
248
+
249
+ export const DEFAULT_OUTCOME_TUNING: OutcomeTuning = Object.freeze({ halfLifeDays: 14, maxEffectiveSamples: 50 });
250
+
251
+ /**
252
+ * Stored evidence of one key: decayed pseudo-counts of successes (`alpha`) and failures (`beta`),
253
+ * **prior excluded** (the D7 prior depends on the live rank and is added on read). `updatedAt` is the
254
+ * epoch-ms instant the counts are expressed at; it never moves backwards.
255
+ */
256
+ export interface BetaState {
257
+ readonly alpha: number;
258
+ readonly beta: number;
259
+ readonly updatedAt: number;
260
+ }
261
+
262
+ /** D7 prior pseudo-counts; `alpha + beta = 5`. */
263
+ export interface BetaPrior {
264
+ readonly alpha: number;
265
+ readonly beta: number;
266
+ }
267
+
268
+ /** Posterior at read time: prior + evidence decayed to `now` and capped. Always proper (alpha, beta > 0). */
269
+ export interface Posterior {
270
+ readonly alpha: number;
271
+ readonly beta: number;
272
+ /** alpha / (alpha + beta) — the `p_k` of D8. */
273
+ readonly mean: number;
274
+ /** Effective evidence count after decay and cap (prior excluded). */
275
+ readonly n: number;
276
+ readonly prior: BetaPrior;
277
+ }
278
+
279
+ // ---------------------------------------------------------------------------
280
+ // Cost accounting (cost.ts) — D5, D6, A1, A10
281
+ // ---------------------------------------------------------------------------
282
+
283
+ /** One catalog price entry (`Model.Cost`; USD per million tokens). A10: `tier` selects by input size. */
284
+ export interface ModelPriceEntry {
285
+ readonly tier?: { readonly type: "context"; readonly size: number };
286
+ readonly input: number;
287
+ readonly output: number;
288
+ readonly cache?: { readonly read?: number; readonly write?: number };
289
+ }
290
+
291
+ /** Catalog `cost` of a model as delivered by the host (array) or by user config (object or array). */
292
+ export type ModelPricing = ModelPriceEntry | readonly ModelPriceEntry[] | null | undefined;
293
+
294
+ /** A1: `unpriced` = no valid entry, or every price field of every entry is 0 (also: model absent from the catalog). */
295
+ export type PricingState = "priced" | "unpriced";
296
+
297
+ /** `session.step.ended` `data.tokens` as observed in S3. */
298
+ export interface StepEndedTokens {
299
+ readonly input: number;
300
+ readonly output: number;
301
+ readonly reasoning: number;
302
+ readonly cache: { readonly read: number; readonly write: number };
303
+ }
304
+
305
+ /** Flattened token counts (one step, or the sum over an attempt's steps). */
306
+ export interface TokenSample {
307
+ readonly input: number;
308
+ readonly output: number;
309
+ readonly reasoning: number;
310
+ readonly cacheRead: number;
311
+ readonly cacheWrite: number;
312
+ }
313
+
314
+ /** Running mean: exact arithmetic mean while n ≤ maxEffectiveSamples, then EWMA with weight 1/maxEffectiveSamples. `mean` is 0 when n = 0. */
315
+ export interface MeanStat {
316
+ readonly mean: number;
317
+ /** Samples folded in (uncapped integer). */
318
+ readonly n: number;
319
+ }
320
+
321
+ /** Per-field means of per-attempt token sums. */
322
+ export interface TokenMeans {
323
+ readonly n: number;
324
+ readonly input: number;
325
+ readonly output: number;
326
+ readonly reasoning: number;
327
+ readonly cacheRead: number;
328
+ readonly cacheWrite: number;
329
+ }
330
+
331
+ /** Per-key cost statistics. One sample = one attempt (a child session's steps for one dispatch or ladder step). */
332
+ export interface CostStats {
333
+ /** USD per attempt; attempts with any `null` step cost (D6/A1) are excluded. */
334
+ readonly measuredUSD: MeanStat;
335
+ /** Attempts folded whose USD is unknown (unpriced model). */
336
+ readonly unpricedAttempts: number;
337
+ /** Token sums per attempt, every attempt (tokens are kept for unpriced models, A1). */
338
+ readonly tokens: TokenMeans;
339
+ /** Steps per attempt. */
340
+ readonly steps: MeanStat;
341
+ /** `tokens.output` of the attempt's final step (the text handed back to the orchestrator; D8 `tax`). */
342
+ readonly finalMessageTokens: MeanStat;
343
+ }
344
+
345
+ /** One `session.step.ended` for a registered child, as handed to `OutcomeStore.recordStep`. */
346
+ export interface StepSample {
347
+ /** Opaque attempt id from the dispatch registry (2.1), e.g. `${childSessionID}:${attemptIndex}`. */
348
+ readonly attemptID: string;
349
+ /** Raw `data.cost` (host-computed USD). */
350
+ readonly cost: number;
351
+ /** `pricingState(catalog cost of the attempt's model)`; the store applies D6 with it. */
352
+ readonly pricing: PricingState;
353
+ readonly tokens: TokenSample;
354
+ /** `data.finish !== "tool-calls"`: the attempt handed back its final message with this step. */
355
+ readonly final: boolean;
356
+ }
357
+
358
+ /** In-memory accumulator of an attempt still receiving steps (never persisted). */
359
+ export interface OpenAttempt {
360
+ readonly key: OutcomeKey;
361
+ readonly attemptID: string;
362
+ readonly steps: number;
363
+ /** Sum of non-null step USD. Meaningful only when `usdKnown`. */
364
+ readonly usd: number;
365
+ /** false as soon as one step's USD is null. */
366
+ readonly usdKnown: boolean;
367
+ readonly tokens: TokenSample;
368
+ /** Output tokens of the final step; null until a final step arrives. */
369
+ readonly finalOutput: number | null;
370
+ readonly lastStepAt: number;
371
+ }
372
+
373
+ /** Input of the D5 unit rule. */
374
+ export interface UnitCandidate {
375
+ readonly key: OutcomeKey;
376
+ /** Catalog pricing usable for an estimate (`pricingState(...) === "priced"`). */
377
+ readonly priced: boolean;
378
+ /** `cost(key).measuredUSD` (non-null samples only). */
379
+ readonly measuredUSD: MeanStat;
380
+ /** Token samples available to price (`cost(key).tokens.n`, else the class profile's n). */
381
+ readonly tokenSamples: number;
382
+ }
383
+
384
+ // ---------------------------------------------------------------------------
385
+ // Store (store.ts)
386
+ // ---------------------------------------------------------------------------
387
+
388
+ /** Identifies the attempt an outcome signal belongs to; one attempt contributes at most one Beta observation. */
389
+ export interface AttemptSignal {
390
+ readonly attemptID: string;
391
+ readonly step: LadderStepKind;
392
+ }
393
+
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
+ */
399
+ export interface OutcomeCounts {
400
+ readonly pass: number;
401
+ readonly fail: number;
402
+ readonly falseRefusals: number;
403
+ /** Verdicts of `variant` attempts (variant-step successes, §0.11). */
404
+ readonly variantPass: number;
405
+ readonly variantFail: number;
406
+ }
407
+
408
+ export interface OutcomeEntrySnapshot {
409
+ readonly beta: BetaState;
410
+ readonly counts: OutcomeCounts;
411
+ readonly cost: CostStats;
412
+ }
413
+
414
+ /** Store state as persisted (open attempts and dedupe sets excluded). `entries` keys are OutcomeKeys, sorted. */
415
+ export interface OutcomeSnapshot {
416
+ readonly version: typeof OUTCOMES_SCHEMA_VERSION;
417
+ readonly entries: Readonly<Record<string, OutcomeEntrySnapshot>>;
418
+ }
419
+
420
+ export interface SnapshotLoadReport {
421
+ readonly accepted: number;
422
+ readonly dropped: number;
423
+ }
424
+
425
+ export interface OutcomeStoreOptions extends Partial<OutcomeTuning> {
426
+ readonly now?: Clock;
427
+ /** Open attempts kept before the oldest is folded early (default 256). */
428
+ readonly maxOpenAttempts?: number;
429
+ /** Attempt ids remembered for single-observation dedupe (default 4096, LRU). */
430
+ readonly maxScoredAttempts?: number;
431
+ }
432
+
433
+ export interface OutcomeStore {
434
+ /** Bumps on every change a snapshot would show; the flusher persists when it moved. */
435
+ readonly revision: number;
436
+ /** Hot reload of `routing.outcomes` (applied lazily on the next read/write). */
437
+ configure(tuning: Partial<OutcomeTuning>): void;
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;
444
+ /** D4: a false refusal is a failure of the key. Returns whether the Beta changed. */
445
+ recordFalseRefusal(key: OutcomeKey, signal: AttemptSignal): boolean;
446
+ /** Accumulate one step into its attempt; a `final` step folds the attempt into `cost(key)`. */
447
+ recordStep(key: OutcomeKey, step: StepSample): void;
448
+ /** Fold an open attempt without a final step (child gone/aborted). No-op when unknown. */
449
+ closeAttempt(attemptID: string): void;
450
+ /** Fold open attempts idle for ≥ maxIdleMs (default 30 min); returns how many were folded. */
451
+ sweepAttempts(maxIdleMs?: number): number;
452
+ /** Prior (default: same-rank `Beta(4, 1)`) + decayed, capped evidence. Unknown key → the prior. */
453
+ posterior(key: OutcomeKey, prior?: BetaPrior): Posterior;
454
+ /** Cost statistics; unknown key → empty stats (all n = 0). */
455
+ cost(key: OutcomeKey): CostStats;
456
+ /** n-weighted token means over every key of the class; null when the class has no token sample. */
457
+ classTokenProfile(cls: string): TokenMeans | null;
458
+ keys(): OutcomeKey[];
459
+ snapshot(): OutcomeSnapshot;
460
+ /** `replace` (default) swaps the persisted state; `merge` adds disk evidence to in-memory evidence. */
461
+ fromSnapshot(snapshot: OutcomeSnapshot, options?: { readonly mode?: "replace" | "merge" }): SnapshotLoadReport;
462
+ /**
463
+ * QA-1.3-4: another process rewrote the store file. Adds `disk − baseline` (what the other writer added since
464
+ * this process last synced, `baseline`) to the live state, so the next save writes `disk + (memory − baseline)`.
465
+ */
466
+ mergeForeign(disk: OutcomeSnapshot, baseline: OutcomeSnapshot): SnapshotLoadReport;
467
+ }
468
+
469
+ /** What stats needs from a store. */
470
+ export type OutcomeStoreView = Pick<OutcomeStore, "cost" | "keys">;
471
+
472
+ // ---------------------------------------------------------------------------
473
+ // Decision log rows (decisions.jsonl) — §0.11 "What is measured", D15, D18
474
+ // ---------------------------------------------------------------------------
475
+
476
+ /** Structural view of 1.2's `TaskFacts` (assignable from it). */
477
+ export interface DecisionFacts {
478
+ readonly class: string;
479
+ readonly risk: string;
480
+ readonly scope: string;
481
+ readonly needs: readonly string[];
482
+ readonly confidence: number;
483
+ readonly source: string;
484
+ }
485
+
486
+ export interface RouteChoice {
487
+ readonly key: OutcomeKey;
488
+ readonly agent: string;
489
+ readonly origin: AgentOrigin;
490
+ /** `provider/model`. */
491
+ readonly model: string;
492
+ /** Normalized variant (`default` when none). */
493
+ readonly variant: string;
494
+ }
495
+
496
+ export const LOG_ROW_VERSION = 1;
497
+
498
+ /**
499
+ * Reason prefix of a decision row whose dispatch was lifted to `enforcement.escalate.floorTier` by the 2.2 adapter (QA-2.2-7).
500
+ * It is policy, not a decision the engine took on evidence, so D17's "switched and failed" does not count it.
501
+ */
502
+ export const FLOOR_LIFT_REASON = "lift:floor";
503
+
504
+ /**
505
+ * Reason prefix of a decision row whose dispatch resumed an existing child (`task_id`/`sessionID`): the engine never switches such a
506
+ * dispatch in any mode (plan amendment A30), so `switched` is false and the kernel's own decision is only logged. `routing:stats` keeps
507
+ * these rows out of every routing metric and reports them on their own line.
508
+ */
509
+ export const RESUME_REASON = "kept:resume";
510
+
511
+ /**
512
+ * Reason prefix of a resume that repeats the orchestrator's original pick of a child the router moved (a floor lift, an evidence switch):
513
+ * the host would switch the child back to that pick, so `enforce` sends the resume to the agent/model the child runs (plan amendment A30,
514
+ * QA-2.4-R3-1). Still a `kept:resume` row (`startsWith(RESUME_REASON)`), `switched` false, outside every routing metric.
515
+ */
516
+ export const RESUME_RUNNING_REASON = "kept:resume:running";
517
+
518
+ /**
519
+ * Reason prefix of a PINNED resume that repeats the original pick of a child the router moved (QA-3.2-12, found on the real host in 3.2): the
520
+ * dispatch is sent as named and the host moves the child, so the row says `kept:resume:pinned` and not that it was sent to the running agent.
521
+ * Still a `kept:resume` row (`startsWith(RESUME_REASON)`), `switched` false, outside every routing metric.
522
+ */
523
+ export const RESUME_PINNED_REASON = "kept:resume:pinned";
524
+
525
+ /**
526
+ * Reason prefix of a resume that repeats the original pick of a child the router moved, where the A30 rewrite to the running agent was
527
+ * REFUSED (plan amendment A34, QA-G-B3): the resume is sent as named (and lifted to `floorTier` in `enforce` when it would fall below it).
528
+ * The suffix says why: {@link RESUME_NAMED_NEEDS_REASON} or {@link RESUME_NAMED_NEVER_DOWN_REASON}. Still a `kept:resume` row
529
+ * (`startsWith(RESUME_REASON)`), `switched` false, outside every routing metric.
530
+ */
531
+ export const RESUME_NAMED_REASON = "kept:resume:named";
532
+
533
+ /** A34: the running agent's evaluated permissions do not cover the resume's `needs`, or it is no longer startable by the parent. */
534
+ export const RESUME_NAMED_NEEDS_REASON = "kept:resume:named:needs";
535
+
536
+ /** A34: the running agent is below the named pick's capability rank on high-risk work without detection (D9 never down). */
537
+ export const RESUME_NAMED_NEVER_DOWN_REASON = "kept:resume:named:never-down";
538
+
539
+ interface LogRowBase {
540
+ readonly v: typeof LOG_ROW_VERSION;
541
+ /** ISO-8601 UTC (`new Date(now()).toISOString()`). */
542
+ readonly ts: string;
543
+ /** Parent (orchestrator) session. */
544
+ readonly sessionID: string;
545
+ }
546
+
547
+ /**
548
+ * What the classifier saw for one dispatch (1.2 `ClassifyTrace`, trimmed to what the log needs): how many route lines the
549
+ * prompt carried, and what the model backend did. Optional: ladder-attempt rows have none.
550
+ */
551
+ export interface DecisionTrace {
552
+ readonly routeLines: { readonly count: number; readonly conflict: boolean; readonly edgeOnly: boolean };
553
+ readonly backend: {
554
+ readonly id: string;
555
+ readonly status: string;
556
+ readonly latencyMs: number;
557
+ readonly label?: string;
558
+ readonly rejected?: true;
559
+ readonly disagrees?: true;
560
+ } | null;
561
+ readonly backendSkipped?: "credentials";
562
+ /**
563
+ * A27: the argmin BEFORE the evidence filter, written only when the filter removed it (it differs from `best`): the
564
+ * cheapest option the engine could not trust yet. `routing:stats` counts these to show where the gate holds it back.
565
+ */
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[];
573
+ }
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
+
582
+ /** One routed dispatch (2.2) or one ladder attempt (2.3). Fields of §0.11 plus kind/v/decisionID/step/resume. */
583
+ export interface DecisionRow extends LogRowBase {
584
+ readonly kind: "decision";
585
+ /** Unique per row; verdict/refusal rows reference it. */
586
+ readonly decisionID: string;
587
+ readonly mode: LoggedRoutingMode;
588
+ /** Known for resumed children; null for a fresh dispatch decided before the host creates the child. */
589
+ readonly childSessionID: string | null;
590
+ readonly facts: DecisionFacts;
591
+ /** The orchestrator's pick (ladder attempts: the ladder's pick). */
592
+ readonly chosen: RouteChoice;
593
+ /** Engine argmin; null when no candidate survived filtering. */
594
+ readonly best: RouteChoice | null;
595
+ /** `enforce` replaced `chosen` with `best`. The dispatched key is `switched ? best.key : chosen.key`. */
596
+ readonly switched: boolean;
597
+ readonly pinned: boolean;
598
+ readonly unit: CostUnit;
599
+ /** C(k) per candidate key, in `unit`; finite numbers only. */
600
+ readonly costs: Readonly<Record<string, number>>;
601
+ /** 1.4 `Decision.confidence` ∈ [0, 1]. */
602
+ readonly confidence: number;
603
+ readonly reason: string;
604
+ readonly step: LadderStepKind;
605
+ /** The attempt reuses an existing child session (D11 resume, or a `sessionID`/`task_id` dispatch). */
606
+ readonly resume: boolean;
607
+ /** Classifier trace of a routed dispatch (2.2; Phase 1.2 handoff): route-line count/conflict and the backend outcome. */
608
+ readonly trace?: DecisionTrace;
609
+ /** A34 (QA-G-B8): the verification depth the dispatch was decided with. Absent on older rows and on ladder attempts. */
610
+ readonly detection?: DecisionDetection;
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. */
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);
656
+ }
657
+
658
+ /** The `[acceptance]` depth vocabulary of 1.2 (`Detection`), restated here so this module keeps no runtime import. */
659
+ export type LoggedDetection = "deterministic" | "grader" | "none";
660
+
661
+ /** A34 (QA-G-B8): what detection a routed dispatch was decided with. */
662
+ export interface DecisionDetection {
663
+ /** The value the kernel used: the weaker of the route line's `d=` and the prompt's own `[acceptance]` block (QA-G-B2). */
664
+ readonly effective: LoggedDetection;
665
+ /** The route line's `d=` claim, written only when it differs from `effective` (a claim the prompt did not back). */
666
+ readonly claimed?: LoggedDetection;
667
+ }
668
+
669
+ /**
670
+ * A34 (QA-G-B8): capability ranks (`kernel.capabilityRank`, positions on the escalate ladder). `pick`: the orchestrator's pick (the
671
+ * highest preset rank of its model, never below its candidate rank). `dispatched`: what the host was handed (the final input after the
672
+ * legacy hook). `null` = unknown (no preset rung on that model and not a candidate, or nothing resolvable). `routing:stats` counts the
673
+ * high-risk `d=none` rows whose `dispatched < pick` (D9 never-down: expected 0).
674
+ */
675
+ export interface DecisionCapability {
676
+ readonly pick: number | null;
677
+ readonly dispatched: number | null;
678
+ }
679
+
680
+ export interface VerdictRow extends LogRowBase {
681
+ readonly kind: "verdict";
682
+ readonly decisionID: string | null;
683
+ readonly childSessionID: string;
684
+ readonly attemptID: string;
685
+ readonly key: OutcomeKey;
686
+ readonly verdict: Verdict;
687
+ readonly step: LadderStepKind;
688
+ }
689
+
690
+ export interface RefusalRow extends LogRowBase {
691
+ readonly kind: "refusal";
692
+ readonly decisionID: string | null;
693
+ readonly childSessionID: string;
694
+ readonly attemptID: string;
695
+ readonly key: OutcomeKey;
696
+ readonly step: LadderStepKind;
697
+ /**
698
+ * Set when this refusal turned an earlier `pass` verdict of the same attempt into a failure (C5, QA-1.3-6,
699
+ * QA-2.1-3). `routing:stats` then moves that pass to a fail, as the store did.
700
+ */
701
+ readonly overrides?: "pass";
702
+ }
703
+
704
+ export type LogRow = DecisionRow | VerdictRow | RefusalRow;
705
+
706
+ // ---------------------------------------------------------------------------
707
+ // Persistence (persist.ts) — D15, A3
708
+ // ---------------------------------------------------------------------------
709
+
710
+ export const OUTCOMES_SCHEMA_ID = "opencode-model-router.outcomes";
711
+ export const OUTCOMES_SCHEMA_VERSION = 1;
712
+ /** Default directory name under `os.tmpdir()`: the `*.scorecard.log` directory located in 0.P.2. */
713
+ export const DEFAULT_OUTCOMES_DIRNAME = "opencode-model-router-trajectory";
714
+ export const OUTCOMES_FILE = "outcomes.json";
715
+ /** Quarantined unparseable/malformed stores: `outcomes.corrupt.<YYYYMMDDTHHMMSSmmmZ>-<pid>.json` (QA-1.3-11). */
716
+ export const OUTCOMES_CORRUPT_PREFIX = "outcomes.corrupt.";
717
+ export const OUTCOMES_CORRUPT_RE = /^outcomes\.corrupt\.(\d{8}T\d{9}Z)-(\d+)\.json$/;
718
+ /** Quarantine copies kept (the newest ones). */
719
+ export const MAX_CORRUPT_COPIES = 3;
720
+ /** Prefix of temp files used by the atomic write (`outcomes.json.tmp-<pid>-<seq>`). */
721
+ export const OUTCOMES_TMP_PREFIX = "outcomes.json.tmp-";
722
+ export const DECISIONS_FILE = "decisions.jsonl";
723
+ /** Rotated generations: `decisions.<YYYYMMDDTHHMMSSmmmZ>-<pid>.jsonl`. */
724
+ export const DECISIONS_ROTATED_RE = /^decisions\.(\d{8}T\d{9}Z)-(\d+)\.jsonl$/;
725
+ /** D15: rotate before the live log would exceed 5 MiB. */
726
+ export const DECISIONS_MAX_BYTES = 5 * 1024 * 1024;
727
+ export const DECISIONS_MAX_GENERATIONS = 3;
728
+ /** D15: at most one flush per 30 s. */
729
+ export const FLUSH_MIN_INTERVAL_MS = 30_000;
730
+ export const FLUSH_BATCH_ROWS = 1_000;
731
+ export const MAX_QUEUED_ROWS = 5_000;
732
+ /** Windows rename retries on EPERM/EBUSY/EACCES (≈ 465 ms worst case, off the hot path). */
733
+ export const RENAME_RETRY_DELAYS_MS: readonly number[] = [15, 30, 60, 120, 240];
734
+ export const STALE_TMP_MS = 60 * 60 * 1000;
735
+
736
+ /** Persisted envelope of `outcomes.json`. */
737
+ export interface OutcomesFile {
738
+ readonly schema: typeof OUTCOMES_SCHEMA_ID;
739
+ readonly version: number;
740
+ readonly savedAt: string;
741
+ readonly entries: Readonly<Record<string, OutcomeEntrySnapshot>>;
742
+ }
743
+
744
+ export interface PersistStat {
745
+ readonly size: number;
746
+ readonly mtimeMs: number;
747
+ }
748
+
749
+ /** Injected file system. Thrown errors carry a Node `code` (`ENOENT`, `EPERM`, `EBUSY`, ...). */
750
+ export interface PersistFs {
751
+ /** Exclusive create (`wx`); false only when already present. */
752
+ createExclusive(path: string, data: string): Promise<boolean>;
753
+ /** `mkdir -p`; an existing directory is not an error. */
754
+ mkdirp(dir: string): Promise<void>;
755
+ /** UTF-8 content; null when the file does not exist. */
756
+ readText(path: string): Promise<string | null>;
757
+ /** Create/truncate, write, fsync, close. */
758
+ writeDurable(path: string, data: string): Promise<void>;
759
+ /** One append call (O_APPEND), creating the file when absent. */
760
+ appendText(path: string, data: string): Promise<void>;
761
+ /** Replaces an existing target. */
762
+ rename(from: string, to: string): Promise<void>;
763
+ /** ENOENT is not an error. */
764
+ unlink(path: string): Promise<void>;
765
+ /** null when the file does not exist. */
766
+ stat(path: string): Promise<PersistStat | null>;
767
+ /** Entry names; [] when the directory does not exist. */
768
+ readdir(dir: string): Promise<string[]>;
769
+ }
770
+
771
+ /** Structural subset of the plugin logger. */
772
+ export interface OutcomeLogger {
773
+ warn(message: string, extra?: Record<string, unknown>): void;
774
+ info?(message: string, extra?: Record<string, unknown>): void;
775
+ }
776
+
777
+ export interface PersistDeps {
778
+ readonly fs: PersistFs;
779
+ readonly now: Clock;
780
+ readonly sleep: (ms: number) => Promise<void>;
781
+ readonly logger: OutcomeLogger;
782
+ readonly pid: number;
783
+ }
784
+
785
+ export interface PersisterOptions {
786
+ readonly maxBytes?: number;
787
+ readonly maxGenerations?: number;
788
+ readonly renameRetryDelaysMs?: readonly number[];
789
+ }
790
+
791
+ /**
792
+ * `missing` = no file (fresh store, not an error); `corrupt` = unparseable JSON or a malformed version-1
793
+ * envelope (quarantined); `unsupported-version` = a file this plugin must not touch: a newer version, another
794
+ * schema or a non-numeric version (read-only, never quarantined).
795
+ */
796
+ export type LoadStatus = "ok" | "missing" | "corrupt" | "unsupported-version";
797
+
798
+ export interface LoadResult {
799
+ readonly status: LoadStatus;
800
+ /** Valid entries (empty unless `ok`). */
801
+ readonly snapshot: OutcomeSnapshot;
802
+ /** Entries dropped by validation (status stays `ok`). */
803
+ readonly dropped: number;
804
+ readonly savedAt: string | null;
805
+ /** Human-readable reason for any status other than `ok`/`missing`, or for dropped entries. */
806
+ readonly message: string | null;
807
+ }
808
+
809
+ export type WriteResult =
810
+ | { readonly ok: true }
811
+ | {
812
+ readonly ok: false;
813
+ readonly error: string;
814
+ readonly code?: string;
815
+ /** The store on disk must not be overwritten by this plugin (newer/unrecognized/unreadable): no retry will help (QA-1.3-2). */
816
+ readonly readOnly?: true;
817
+ };
818
+
819
+ export interface ReadRowsResult {
820
+ /** Oldest generation first, file order within a file. */
821
+ readonly rows: LogRow[];
822
+ /** Lines that failed JSON parsing or row validation (a torn last line after a crash is expected). */
823
+ readonly skipped: number;
824
+ readonly files: string[];
825
+ /** Earliest `ts` among the valid rows (the log keeps only the newest generations, so older history is gone); null without rows. */
826
+ readonly oldestTs: string | null;
827
+ /** Rotated generations that were read (0 = the log never rotated, or its older generations were pruned and none remain). */
828
+ readonly generations: number;
829
+ }
830
+
831
+ /**
832
+ * Result of checking `outcomes.json` for another writer (QA-1.3-4, QA-1.3-18):
833
+ * - `unchanged`: nothing to merge (file untouched, removed, not ours, or unparseable and already moved aside);
834
+ * - `merge`: another process wrote it: its content, and the baseline this process last synced with
835
+ * (`disk − baseline` is what the other writer added);
836
+ * - `skip`: the file could not be read, so the snapshot must not be written this round.
837
+ */
838
+ export type ForeignCheck =
839
+ | { readonly status: "unchanged" }
840
+ | { readonly status: "merge"; readonly disk: OutcomeSnapshot; readonly baseline: OutcomeSnapshot }
841
+ | { readonly status: "skip"; readonly reason: string };
842
+
843
+ export interface Persister {
844
+ /** Serialize the entire read/merge/save transaction, not just its final rename. */
845
+ withSnapshotLock(run: () => Promise<void>): Promise<boolean>;
846
+ readonly dir: string;
847
+ readonly outcomesPath: string;
848
+ readonly decisionsPath: string;
849
+ /**
850
+ * Never throws. `quarantine: true` (plugin) moves an unparseable or malformed version-1 file to a unique
851
+ * `outcomes.corrupt.<stamp>-<pid>.json`; a file that is not ours (other schema or a newer version) is never
852
+ * moved or overwritten. The CLI passes false.
853
+ */
854
+ load(options?: { readonly quarantine?: boolean }): Promise<LoadResult>;
855
+ /** Atomic: temp file + durable write + rename (with Windows retries). Never throws; the old file survives any failure. */
856
+ saveSnapshot(snapshot: OutcomeSnapshot): Promise<WriteResult>;
857
+ /** One append per call; rotates first when the live log would pass `maxBytes`. Never throws. */
858
+ appendRows(rows: readonly LogRow[]): Promise<WriteResult>;
859
+ /** Every generation, oldest first. Never throws. */
860
+ readRows(): Promise<ReadRowsResult>;
861
+ /**
862
+ * Has another process rewritten `outcomes.json` since this persister last loaded or wrote it? The mtime is
863
+ * recorded only after the new content was read and parsed; an unparseable file is moved aside (quarantined)
864
+ * before it can be overwritten; a read failure is `skip`. Never throws.
865
+ */
866
+ readForeignWrites(force?: boolean): Promise<ForeignCheck>;
867
+ }
868
+
869
+ /** Injected timers; the real implementation `unref()`s them so they never keep a process alive. */
870
+ export interface FlushScheduler {
871
+ setTimer(fn: () => void, ms: number): unknown;
872
+ clearTimer(handle: unknown): void;
873
+ }
874
+
875
+ export interface FlusherDeps {
876
+ readonly now: Clock;
877
+ readonly scheduler: FlushScheduler;
878
+ readonly logger: OutcomeLogger;
879
+ /** Every flush waits for this first (the initial disk load), so a snapshot is never taken before it merged. Must not reject. */
880
+ readonly ready?: Promise<unknown>;
881
+ }
882
+
883
+ export interface FlusherOptions {
884
+ readonly minIntervalMs?: number;
885
+ readonly batchRows?: number;
886
+ readonly maxQueuedRows?: number;
887
+ }
888
+
889
+ /** Coalescing, throttled writer. Hooks only call `enqueue`/`requestFlush` (no await, no I/O on the hot path). */
890
+ export interface OutcomeFlusher {
891
+ readonly pendingRows: number;
892
+ /** O(1) push; never I/O, never throws; requests a flush. */
893
+ enqueue(row: LogRow): void;
894
+ /** Coalesced with any in-flight/scheduled flush, throttled to one per `minIntervalMs`. Never rejects. */
895
+ requestFlush(): Promise<void>;
896
+ /** Bypasses the throttle (shutdown, tests); still serialized with an in-flight flush. Never rejects. */
897
+ flushNow(): Promise<void>;
898
+ /** flushNow, then cancel timers; later calls are no-ops. */
899
+ dispose(): Promise<void>;
900
+ }
901
+
902
+ /** Process-wide bundle per outcomes directory (A3: one store and one writer per process). */
903
+ export interface OutcomesBundle {
904
+ readonly dir: string;
905
+ readonly store: OutcomeStore;
906
+ readonly persister: Persister;
907
+ readonly flusher: OutcomeFlusher;
908
+ /** Resolves when the on-disk snapshot has been merged into the store. Never rejects. */
909
+ readonly ready: Promise<LoadResult>;
910
+ /** Drop this holder's reference; the last release disposes the flusher. */
911
+ release(): Promise<void>;
912
+ }
913
+
914
+ // ---------------------------------------------------------------------------
915
+ // Statistics (stats.ts) — 1.3.3, D18
916
+ // ---------------------------------------------------------------------------
917
+
918
+ /** Epoch-ms window: `since ≤ ts < until`; null = unbounded. */
919
+ export interface StatsWindow {
920
+ readonly since: number | null;
921
+ readonly until: number | null;
922
+ }
923
+
924
+ /** A rate with its parts; `rate` is null (rendered `n/a`) when `den` is 0. */
925
+ export interface RatioCell {
926
+ readonly num: number;
927
+ readonly den: number;
928
+ readonly rate: number | null;
929
+ }
930
+
931
+ export interface ClassStatsRow {
932
+ readonly class: string;
933
+ readonly dispatches: number;
934
+ }
935
+
936
+ export interface KeyStatsRow {
937
+ readonly key: OutcomeKey;
938
+ /** Windowed `dispatch` rows whose dispatched key is this key. */
939
+ readonly dispatches: number;
940
+ /** Windowed decision rows of any step whose dispatched key is this key. */
941
+ readonly attempts: number;
942
+ readonly pass: number;
943
+ readonly fail: number;
944
+ readonly unverifiable: number;
945
+ /** pass / (pass + fail). */
946
+ readonly passRate: RatioCell;
947
+ readonly falseRefusals: number;
948
+ /** falseRefusals / attempts. */
949
+ readonly refusalRate: RatioCell;
950
+ /** Store `cost(key).measuredUSD` (lifetime, per attempt, not windowed); null when n = 0. Rendered as USD/attempt (lifetime). */
951
+ readonly measuredUSD: MeanStat | null;
952
+ }
953
+
954
+ /** Estimated savings Σ C(chosen) − C(best) over non-pinned dispatch rows of one unit. Units are never summed together. */
955
+ export interface SavingsRow {
956
+ readonly unit: CostUnit;
957
+ readonly total: number;
958
+ readonly rows: number;
959
+ }
960
+
961
+ export interface ResumeFreshRow {
962
+ readonly step: LadderStepKind;
963
+ readonly resume: number;
964
+ readonly fresh: number;
965
+ }
966
+
967
+ /** Exactly the columns of plan 1.3.3 (+ `switched.failed` for D17, see the design). */
968
+ export interface StatsTable {
969
+ readonly version: 1;
970
+ /** ISO strings of the window bounds; null = unbounded. */
971
+ readonly window: { readonly since: string | null; readonly until: string | null };
972
+ readonly dispatches: number;
973
+ /** Dispatch rows written by the 2.2 router (QA-INT-2): every dispatch row but the delegate runner's first attempts. */
974
+ readonly routed: number;
975
+ /** First attempts of `delegate` (the runner's recorder rows, decision ids `ladder-…`): not routed by the engine. */
976
+ readonly delegateFirstAttempts: number;
977
+ /** Dispatches lifted to `floorTier` by the adapter (`lift:floor`, QA-2.2-R2-3): policy, outside the switched and savings numbers. */
978
+ readonly floorLifts: number;
979
+ readonly pinned: number;
980
+ readonly byClass: readonly ClassStatsRow[];
981
+ readonly byKey: readonly KeyStatsRow[];
982
+ /** best == chosen over non-pinned dispatch rows with a non-null best. */
983
+ readonly agreement: RatioCell;
984
+ readonly switched: {
985
+ readonly count: number;
986
+ /** count / non-pinned dispatch rows. */
987
+ readonly share: RatioCell;
988
+ /**
989
+ * Switches the engine ENFORCED on its own evidence: `enforce` rows with `switched`, floor lifts (`lift:floor`) excluded
990
+ * (QA-2.2-7). `count` also holds the would-switches of `shadow`/`advise` rows (the DF3 number); `failed` and `verified` only
991
+ * concern these (QA-2.2-8), because only an enforced switch can fail because of the switch.
992
+ */
993
+ readonly enforced: number;
994
+ /** Enforced switches whose attempt ended in a `fail` verdict or a false refusal (D17 input). */
995
+ readonly failed: number;
996
+ /** Enforced switches whose outcome is known (a pass/fail verdict or a refusal exists): the denominator that makes `failed` readable. */
997
+ readonly verified: number;
998
+ };
999
+ /** One entry per unit present in the window, sorted by unit name. */
1000
+ readonly savings: readonly SavingsRow[];
1001
+ readonly variantSteps: {
1002
+ readonly taken: number;
1003
+ /** pass / (pass + fail) over windowed verdict rows of `variant` attempts. */
1004
+ readonly passRate: RatioCell;
1005
+ };
1006
+ /** Fixed order: LADDER_STEP_KINDS. `renderMarkdown` leaves the `dispatch` row out (QA-2.3-7); the data keeps it. */
1007
+ readonly resumeVsFresh: readonly ResumeFreshRow[];
1008
+ /**
1009
+ * The orchestrator's own resumes (2.2: a `subagent` call with `task_id`/`sessionID` that reused a child), over the routed dispatch rows.
1010
+ * Not ladder decisions, so they are reported on their own line and never in the D11 resume-vs-fresh table (QA-2.3-7, 2.4).
1011
+ */
1012
+ readonly orchestratorResumes: { readonly resumed: number; readonly total: number };
1013
+ /**
1014
+ * The evidence gate (A27) over the routed dispatch rows of the window: how many were kept because the cheapest option had no
1015
+ * evidence yet (`kept:evidence`), and which keys that cheapest-but-unproven option was (`trace.argmin`), most frequent first.
1016
+ */
1017
+ readonly gate: {
1018
+ readonly keptEvidence: number;
1019
+ readonly argmin: ReadonlyArray<{ readonly key: OutcomeKey; readonly count: number }>;
1020
+ };
1021
+ /**
1022
+ * A34 (QA-G-B8), D9 never-down audit over the routed dispatch rows (fresh and resumed) of the window: `below` = rows with
1023
+ * `facts.risk == high` and `detection.effective == none` whose `capability.dispatched < capability.pick` (expected 0); `recorded` =
1024
+ * such high-risk `d=none` rows that carry both ranks. Rows without `detection`/`capability` (older rows, or a reader that drops the
1025
+ * fields) are not counted in either.
1026
+ */
1027
+ readonly neverDown: { readonly below: number; readonly recorded: number };
1028
+ }
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
+
1082
+ /** What the CLI reads from a directory (a Persister satisfies it). */
1083
+ export type StatsSource = Pick<Persister, "dir" | "load" | "readRows">;
1084
+
1085
+ export interface StatsCliIO {
1086
+ /** `resolveOutcomesDir(null, ...)`, used when `--dir` is absent. */
1087
+ readonly defaultDir: string;
1088
+ open(dir: string): StatsSource;
1089
+ stdout(text: string): void;
1090
+ stderr(text: string): void;
1091
+ }
1092
+
1093
+ export const STATS_EXIT = Object.freeze({ ok: 0, corrupt: 1, usage: 2 } as const);