opencode-model-router 2.2.0 → 2.3.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 (54) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +35 -3
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +4 -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 +118 -31
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +484 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/index.ts +486 -38
  13. package/src/router/build-info.ts +151 -0
  14. package/src/router/config.ts +1365 -19
  15. package/src/router/protocol.ts +47 -0
  16. package/src/router/sessions.ts +441 -9
  17. package/src/routing/advisor/findings.ts +706 -0
  18. package/src/routing/advisor/index.ts +606 -0
  19. package/src/routing/classify/backends/host.ts +163 -0
  20. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  21. package/src/routing/classify/backends/shared.ts +741 -0
  22. package/src/routing/classify/backends/typesafe.ts +315 -0
  23. package/src/routing/classify/fences.ts +96 -0
  24. package/src/routing/classify/index.ts +576 -0
  25. package/src/routing/classify/route-line.ts +298 -0
  26. package/src/routing/classify/rules.ts +607 -0
  27. package/src/routing/classify/scrub.ts +214 -0
  28. package/src/routing/classify/state.ts +148 -0
  29. package/src/routing/classify/text.ts +20 -0
  30. package/src/routing/classify/types.ts +1280 -0
  31. package/src/routing/commands/annotate-plan.ts +652 -0
  32. package/src/routing/commands/stats.ts +131 -0
  33. package/src/routing/commands/v1-roles.ts +64 -0
  34. package/src/routing/engine/index.ts +32 -0
  35. package/src/routing/engine/kernel.ts +597 -0
  36. package/src/routing/engine/ladders.ts +561 -0
  37. package/src/routing/engine/plan.ts +404 -0
  38. package/src/routing/engine/protocol-line.ts +133 -0
  39. package/src/routing/engine/simulate.ts +167 -0
  40. package/src/routing/engine/types.ts +270 -0
  41. package/src/routing/file-lock.ts +53 -0
  42. package/src/routing/outcomes/beta.ts +141 -0
  43. package/src/routing/outcomes/cost.ts +313 -0
  44. package/src/routing/outcomes/index.ts +172 -0
  45. package/src/routing/outcomes/ingest.ts +812 -0
  46. package/src/routing/outcomes/persist.ts +1058 -0
  47. package/src/routing/outcomes/stats.ts +602 -0
  48. package/src/routing/outcomes/store.ts +653 -0
  49. package/src/routing/outcomes/types.ts +954 -0
  50. package/src/routing/wire/dispatch.ts +799 -0
  51. package/src/routing/wire/hint.ts +208 -0
  52. package/src/routing/wire/host-info.ts +256 -0
  53. package/src/routing/wire/runtime.ts +259 -0
  54. package/src/v2.ts +15 -1
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Runner simulation (A25, QA-1.4-2) — the attempts the 1.5 escalation runner makes after a rung fails.
3
+ *
4
+ * D8 prices a candidate as "attempt it; if it fails and the failure is detected, the cascade continues". The
5
+ * cascade of a router rung is not a fixed chain: it is whatever `nextAction` decides from the attempt count,
6
+ * the cumulative cost, the cost ceiling, `maxAttemptsPerTier`, variant steps and the covered-tier skips of
7
+ * the policy. This module replays exactly that loop (`newLadderState` → `recordAttempt` → `nextAction` →
8
+ * `advance`) with a failing verdict after every attempt and returns the rungs it ran, so the kernel never
9
+ * prices an escalation the runner would not perform (e.g. a tier covered by a rung already tried, or a tier
10
+ * beyond the cost ceiling).
11
+ *
12
+ * Costs are in `costRatio` units, as the runner charges them (`action.costRatio ?? tier.costRatio`), whatever
13
+ * unit the kernel later prices in. Pure: no I/O, no clock, no randomness, no module state.
14
+ */
15
+
16
+ import {
17
+ advance,
18
+ newLadderState,
19
+ nextAction,
20
+ recordAttempt,
21
+ startCostRatio,
22
+ type EscalatePolicy,
23
+ type LadderState,
24
+ type LadderVerdict,
25
+ } from "../../escalate/ladder";
26
+ import { DEFAULT_VARIANT } from "../../escalate/variants";
27
+
28
+ /** One rung the runner runs: a tier on `model#variant`, charged `costRatio`. */
29
+ export interface RunnerRung {
30
+ readonly tier: string;
31
+ readonly model: string;
32
+ /** `null` = the model's default variant. */
33
+ readonly variant: string | null;
34
+ readonly costRatio: number;
35
+ }
36
+
37
+ /** The base rung of a tier (its own `model`, `variant`, `costRatio`), or `undefined` for an unknown tier. */
38
+ export type TierBase = (tier: string) => RunnerRung | undefined;
39
+
40
+ /**
41
+ * Upper bound on simulated attempts. `maxTotalAttempts` ends every real path (default 4); the bound only
42
+ * protects against an absurd configured value.
43
+ */
44
+ export const MAX_SIMULATED_ATTEMPTS = 64;
45
+
46
+ const FAILED: LadderVerdict = { pass: false, outcome: "fail", reasons: [] };
47
+
48
+ function ownVariantInfo(policy: EscalatePolicy, tier: string) {
49
+ const perTier = policy.variants?.perTier;
50
+ return perTier !== undefined && Object.prototype.hasOwnProperty.call(perTier, tier) ? perTier[tier] : undefined;
51
+ }
52
+
53
+ /**
54
+ * Rungs the runner runs when it is started on `start` and every attempt fails with a detected failure, in
55
+ * order (the first is `start` itself, unless `floorTier` lifts the start tier: QA-1.4-17, the first attempt is
56
+ * then the floor tier's base). Ends when the runner gives up, when it would enter a tier the preset does not
57
+ * define, or after {@link MAX_SIMULATED_ATTEMPTS}.
58
+ *
59
+ * A start on a rung other than the tier's base is modelled as a delegation that already stepped there (its
60
+ * variant is recorded as tried, so the ladder never re-runs it).
61
+ */
62
+ export function simulateRunner(policy: EscalatePolicy, tierBase: TierBase, start: RunnerRung): RunnerRung[] {
63
+ let state = newLadderState(start.tier, policy);
64
+ let first: RunnerRung;
65
+ if (state.currentTier === start.tier) {
66
+ const info = ownVariantInfo(policy, start.tier);
67
+ const variant = start.variant ?? DEFAULT_VARIANT;
68
+ if (info !== undefined && !info.effortConfigured && variant !== info.base) {
69
+ state = advance(state, {
70
+ action: "retry",
71
+ tier: start.tier,
72
+ variantStep: true,
73
+ model: info.model,
74
+ variant,
75
+ rung: { model: info.model, variant },
76
+ });
77
+ }
78
+ first = start;
79
+ } else {
80
+ // floorTier lifts the start: the first attempt runs the floor tier's base, whatever rung was asked for.
81
+ const base = tierBase(state.currentTier);
82
+ if (base === undefined) return [];
83
+ first = { ...base, costRatio: startCostRatio(policy, state) ?? base.costRatio };
84
+ }
85
+ return walk(policy, tierBase, state, first);
86
+ }
87
+
88
+ /**
89
+ * QA-1.4-16: the rungs the runner runs AFTER a native agent has already made `seed.attempts` (its own-model
90
+ * rung and the owning tier's rungs) on tier `seed.tier`. The escalation out of a role chain continues the same
91
+ * delegation, so the attempts and the cost already spent count against `maxTotalAttempts` and the cost
92
+ * ceiling, the chain's tier has used its per-tier retries, and the models the chain ran are recorded as tried
93
+ * (a later tier on one of them is skipped like any covered tier). Returns the continuation only.
94
+ */
95
+ export function simulateAfter(
96
+ policy: EscalatePolicy,
97
+ tierBase: TierBase,
98
+ seed: { readonly tier: string; readonly attempts: readonly RunnerRung[] },
99
+ ): RunnerRung[] {
100
+ if (seed.attempts.length === 0) return [];
101
+ const spent = seed.attempts.reduce((sum, rung) => sum + rung.costRatio, 0);
102
+ let state = newLadderState(seed.tier, policy);
103
+ const info = ownVariantInfo(policy, seed.tier);
104
+ if (info !== undefined && !info.effortConfigured) {
105
+ // Record every rung the chain ran (raises `triedByModel`); `advance` of a variant step does exactly that.
106
+ for (const rung of seed.attempts) {
107
+ const variant = rung.variant ?? DEFAULT_VARIANT;
108
+ state = advance(state, {
109
+ action: "retry",
110
+ tier: seed.tier,
111
+ variantStep: true,
112
+ model: rung.model,
113
+ variant,
114
+ rung: { model: rung.model, variant },
115
+ });
116
+ }
117
+ const lastOwn = [...seed.attempts].reverse().find((rung) => rung.model === info.model);
118
+ state = { ...state, currentVariant: lastOwn === undefined ? null : (lastOwn.variant ?? DEFAULT_VARIANT) };
119
+ }
120
+ state = {
121
+ ...state,
122
+ currentTier: seed.tier,
123
+ // The chain was this tier's retries: only a variant step or an escalation is left.
124
+ attemptsThisTier: Math.max(policy.maxAttemptsPerTier, state.attemptsThisTier),
125
+ totalAttempts: seed.attempts.length,
126
+ cumulativeCost: spent,
127
+ firstAttemptCost: seed.attempts[0]!.costRatio,
128
+ };
129
+ return walk(policy, tierBase, state, null);
130
+ }
131
+
132
+ /**
133
+ * The shared loop: record the attempt just made (`current`; none for a seeded state), ask `nextAction` what
134
+ * the runner does after a detected failure, advance, and read the rung it lands on.
135
+ */
136
+ function walk(policy: EscalatePolicy, tierBase: TierBase, start: LadderState, first: RunnerRung | null): RunnerRung[] {
137
+ let state = start;
138
+ let current = first;
139
+ const rungs: RunnerRung[] = [];
140
+ for (let attempt = 0; attempt < MAX_SIMULATED_ATTEMPTS; attempt++) {
141
+ if (current !== null) {
142
+ rungs.push(current);
143
+ state = recordAttempt(state, current.costRatio);
144
+ }
145
+ const action = nextAction(state, FAILED, policy);
146
+ if (action.action !== "retry" && action.action !== "escalate") break;
147
+ state = advance(state, action);
148
+ const base = tierBase(state.currentTier);
149
+ if (base === undefined) break;
150
+ if (current !== null && action.action === "retry" && action.variantStep !== true && state.currentVariant === undefined) {
151
+ // No variant info in the policy: a plain retry re-runs the rung it just ran (the runner still charges
152
+ // the tier's own ratio, A17).
153
+ current = { ...current, costRatio: action.costRatio ?? base.costRatio };
154
+ continue;
155
+ }
156
+ const info = ownVariantInfo(policy, state.currentTier);
157
+ const variant = state.currentVariant ?? info?.base ?? base.variant ?? DEFAULT_VARIANT;
158
+ current = {
159
+ tier: state.currentTier,
160
+ model: info?.model ?? base.model,
161
+ variant: variant === DEFAULT_VARIANT ? null : variant,
162
+ // A17: the runner charges the action's rung ratio, else the tier's own.
163
+ costRatio: action.costRatio ?? base.costRatio,
164
+ };
165
+ }
166
+ return rungs;
167
+ }
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Decision kernel (M4) — shared types of `src/routing/engine/*`.
3
+ *
4
+ * Design: `docs/qa/cost-aware-routing/phase-1.4.md` → "Design (1.4.1)".
5
+ * Plan #74 §1.5 D5, D7, D8, D9 (amendment A16), D12, D13; amendments A1, A11.
6
+ *
7
+ * TYPES ONLY: every import is `import type`, so this module has no runtime
8
+ * dependency (the kernel stays pure and cheap to load). Producers:
9
+ * - `ladders.ts` (1.4.2) builds a {@link Ladder} per decision;
10
+ * - the caller (2.2 dispatch wiring, `protocol-line.ts`, `plan.ts`) assembles a
11
+ * {@link DecisionInput};
12
+ * - `kernel.ts` turns it into a {@link Decision}, which maps 1:1 onto the
13
+ * `DecisionRow` fields of the 1.3 decision log.
14
+ */
15
+
16
+ import type { ResolvedRouting } from "../../router/config";
17
+ import type { Detection, Need, TaskFacts } from "../classify/types";
18
+ import type {
19
+ AgentRef,
20
+ CostUnit,
21
+ ModelPricing,
22
+ OutcomeStore,
23
+ RouteChoice,
24
+ } from "../outcomes/types";
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // Candidates and ladders
28
+ // ---------------------------------------------------------------------------
29
+
30
+ /**
31
+ * Where a rung comes from (D12):
32
+ * - `tier` — a rung of a router tier's own ladder (`resolveCandidates`);
33
+ * - `role-own-model` — a `routing.roles` agent on the model the host configured for it;
34
+ * - `role-tier-rung` — a `routing.roles` agent on a rung of the tier that owns the class
35
+ * (applied at dispatch by a per-call `model` override).
36
+ */
37
+ export type CandidateSource = "tier" | "role-own-model" | "role-tier-rung";
38
+
39
+ /** One `(agent, model#variant)` the engine may dispatch, with what the kernel needs to price it. */
40
+ export interface Candidate {
41
+ /** `router` for a tier agent of the active preset, `host` for any other agent (outcome-key origin). */
42
+ readonly agent: AgentRef;
43
+ /** `provider/model`, never with a `#variant` suffix. */
44
+ readonly model: string;
45
+ /** Catalog variant id; `null` = the model's default (stored as `default`, A9). */
46
+ readonly variant: string | null;
47
+ /**
48
+ * Cost of one attempt in `costRatio` units (fast = 1), finite and > 0. Router rungs: the rung's own
49
+ * ratio from `resolveCandidates`. Role rungs: see `ladders.ts` (inherited, never invented).
50
+ */
51
+ readonly costRatio: number;
52
+ /**
53
+ * Capability rank on the escalation ladder: index of the router tier in the escalate ladder for
54
+ * router rungs; for role rungs the rank of the tier that owns the class (D7 "inherited rank").
55
+ */
56
+ readonly rank: number;
57
+ /** Router tier that owns the rung: the tier itself, or the class's owning tier for role rungs. */
58
+ readonly tier: string;
59
+ readonly source: CandidateSource;
60
+ /**
61
+ * Needs the agent's EVALUATED permissions grant (A11), supplied by the caller from host agent
62
+ * info — never inferred from the agent id. `null` = unknown: covers no need at all.
63
+ */
64
+ readonly grants: readonly Need[] | null;
65
+ /** Catalog `cost` of `model`; absent/empty/all-zero = unpriced (A1). */
66
+ readonly pricing?: ModelPricing;
67
+ }
68
+
69
+ /**
70
+ * The candidate graph of one decision. `next[k]` is the index of the rung the cascade of D8 moves to
71
+ * when candidate `k` fails and the failure is detected (`null` = terminal: give up at cost `U`). A candidate
72
+ * that has a simulated runner path in `paths` is priced through that path instead and its `next` is `null`
73
+ * (A25: the router rungs); role chains use `next`.
74
+ * `ladders.ts` guarantees the graph is acyclic; the kernel also treats any back edge, out-of-range or
75
+ * unusable successor as terminal, so no input can make it recurse forever.
76
+ */
77
+ export interface Ladder {
78
+ readonly candidates: readonly Candidate[];
79
+ /** Same length as `candidates`. */
80
+ readonly next: readonly (number | null)[];
81
+ /**
82
+ * Rank of the class's static tier (`CLASS_STATIC_TIER`) on the same scale as `Candidate.rank`;
83
+ * `null` when the class has none (`other`) or that tier is not on the ladder. D7 prior offsets are
84
+ * `rank − classRank`.
85
+ */
86
+ readonly classRank: number | null;
87
+ /** Candidates dropped while building the ladder (permissions, unknown agents, ...), for the log. */
88
+ readonly excluded: readonly ExcludedCandidate[];
89
+ /**
90
+ * Rungs the 1.5 runner reaches (variant steps, covered-tier entries) that the engine never dispatches on
91
+ * its own: priced exactly like candidates, never `best`. Indices `candidates.length + i` in {@link paths}.
92
+ */
93
+ readonly reachable?: readonly Candidate[];
94
+ /**
95
+ * A25: per candidate, the attempts the 1.5 runner makes when every attempt fails and the failure is
96
+ * detected, as indices into `[...candidates, ...reachable]` (first = the candidate itself): retries,
97
+ * variant steps, escalations, covered-tier skips, `maxTotalAttempts` and the cost ceiling are already
98
+ * applied by simulating `nextAction`/`advance`. The path ends in a give-up (cost `U`). `null`/absent =
99
+ * the candidate is priced through its `next` pointer instead (role chains, hand-built ladders).
100
+ */
101
+ readonly paths?: readonly (readonly number[] | null)[];
102
+ /**
103
+ * A34 (QA-G-B1): every rung of the active preset on the escalate ladder — modelled or not, its agent available or not — with
104
+ * its tier's rank: the table a dispatch's CAPABILITY rank is read from (`kernel.capabilityRank`). Absent on hand-built ladders:
105
+ * the router rungs of `candidates` and `reachable` stand in for it.
106
+ */
107
+ readonly presetRungs?: readonly PresetRung[];
108
+ }
109
+
110
+ /** A34: one rung of the active preset and the rank of its tier on the escalate ladder. */
111
+ export interface PresetRung {
112
+ /** `provider/model`, never with a `#variant` suffix. */
113
+ readonly model: string;
114
+ readonly variant: string | null;
115
+ readonly rank: number;
116
+ }
117
+
118
+ export type ExclusionReason =
119
+ /** The agent's evaluated permissions do not cover `TaskFacts.needs` (A11, D12). */
120
+ | "needs"
121
+ /** Not in the host agent list, `mode: primary`, `hidden`, not permitted for the parent, or reserved (D12). */
122
+ | "agent-unavailable"
123
+ /** The class has no static tier on the escalate ladder, so a role agent has no inherited rank (D7). */
124
+ | "no-owning-tier"
125
+ /** Same `(agent, model, variant)` as an earlier rung, or a role naming a router tier agent. */
126
+ | "duplicate"
127
+ /** A25: an other-model rung of a tier's `candidates`; the 1.5 runner never runs it (escalation territory). */
128
+ | "not-modelled";
129
+
130
+ /**
131
+ * What the caller knows about one host agent: `ctx.agent.list()` on v2 (router tier agents
132
+ * included), the config agent map plus the native agents on v1. Supplied, never inferred (A11).
133
+ */
134
+ export interface HostAgentInfo {
135
+ readonly id: string;
136
+ /** `provider/model[#variant]` configured for the agent; absent/null = it runs on the parent's model. */
137
+ readonly model?: string | null;
138
+ /** Host agent mode; `primary` agents are never candidates (D12). */
139
+ readonly mode: string;
140
+ readonly hidden: boolean;
141
+ /** The parent session may dispatch it (host permission check). */
142
+ readonly permitted: boolean;
143
+ /** Needs its EVALUATED permissions grant (A11), e.g. via `ladders.grantsFromTools`. */
144
+ readonly grants: readonly Need[];
145
+ }
146
+
147
+ export interface ExcludedCandidate {
148
+ readonly agent: AgentRef;
149
+ readonly model: string;
150
+ readonly variant: string | null;
151
+ readonly why: ExclusionReason;
152
+ }
153
+
154
+ // ---------------------------------------------------------------------------
155
+ // Kernel input
156
+ // ---------------------------------------------------------------------------
157
+
158
+ /** What the kernel reads from the 1.3 outcome store. */
159
+ export type EngineStoreView = Pick<OutcomeStore, "posterior" | "cost" | "classTokenProfile">;
160
+
161
+ /** The slice of the resolved `routing` block the kernel uses (D8, D9). */
162
+ export type KernelRouting = Pick<ResolvedRouting, "profile" | "margin" | "minClassConfidence" | "detection">;
163
+
164
+ /**
165
+ * The orchestrator's pick, fully resolved by the caller: the agent it named and the model#variant
166
+ * that agent runs on (the tier's rung for a router tier, the configured model for a host agent).
167
+ */
168
+ export interface ChosenDispatch {
169
+ readonly agent: AgentRef;
170
+ /** `provider/model` (a `#variant` suffix is accepted and split off when `variant` is null). */
171
+ readonly model: string;
172
+ readonly variant: string | null;
173
+ }
174
+
175
+ /** Orchestrator pricing for the D8 `tax` term (USD unit only). */
176
+ export interface OrchestratorCost {
177
+ readonly pricing: ModelPricing;
178
+ /** Current orchestrator context size in tokens (selects the A10 price entry). */
179
+ readonly contextTokens: number;
180
+ }
181
+
182
+ export interface DecisionInput {
183
+ /** Classifier output (M2). `confidence` gates switching (D9) and store reads (1.2 → 1.4 handoff). */
184
+ readonly facts: TaskFacts;
185
+ readonly chosen: ChosenDispatch;
186
+ readonly ladder: Ladder;
187
+ /** Verification depth of the dispatch (its `[acceptance]` checks or a plan `d=`); `d = routing.detection[detection]`. */
188
+ readonly detection: Detection;
189
+ /** `[route pin]` (D13): never switched; `best` still computed. */
190
+ readonly pin: boolean;
191
+ readonly routing: KernelRouting;
192
+ /** `null` = no outcome data (static/degenerate case): priors and `costRatio` only. */
193
+ readonly store: EngineStoreView | null;
194
+ /** Rank of `enforcement.escalate.floorTier`; candidates below it are never `best` (D9). */
195
+ readonly floorRank?: number | null;
196
+ /** Needed only for a measured `tax` in USD; absent → `tax = 0`. */
197
+ readonly orchestrator?: OrchestratorCost | null;
198
+ /** D8 `remainingTurnsEstimate`; default 4. */
199
+ readonly remainingTurns?: number;
200
+ }
201
+
202
+ // ---------------------------------------------------------------------------
203
+ // Kernel output
204
+ // ---------------------------------------------------------------------------
205
+
206
+ /** Why a candidate (other than the orchestrator's pick) could not be `best`. */
207
+ export type IneligibleReason =
208
+ /** Permissions do not cover `needs` (A11). */
209
+ | "needs"
210
+ /** Below `floorTier` (D9). */
211
+ | "floor"
212
+ /**
213
+ * `risk == high` and `d == none`: never down (D9, A34): a rank below the pick's CAPABILITY rank, or the pick's own model on a
214
+ * lower-effort variant at the same rank.
215
+ */
216
+ | "never-down"
217
+ /** Non-finite or non-positive attempt cost. */
218
+ | "invalid-cost"
219
+ /** A27: not ranked above the pick and fewer than 5 recorded outcomes for its key: it cannot be `best`. */
220
+ | "evidence";
221
+
222
+ export type DecisionReasonCode =
223
+ | "switched"
224
+ | "kept:no-candidates"
225
+ | "kept:pinned"
226
+ | "kept:chosen-not-candidate"
227
+ | "kept:best-is-chosen"
228
+ | "kept:class-confidence"
229
+ | "kept:margin"
230
+ /** A24: a down switch whose `best` has fewer than 5 recorded outcomes. */
231
+ | "kept:evidence"
232
+ | "kept:invalid-config";
233
+
234
+ export interface Decision {
235
+ /** The orchestrator's pick (as dispatched unless `switched`). */
236
+ readonly chosen: RouteChoice;
237
+ /** Argmin of `C(k)` over the pick and the eligible candidates; `null` when nothing could be priced. */
238
+ readonly best: RouteChoice | null;
239
+ /** The engine would replace `chosen` with `best` (D9 as amended by A16); never with `pinned`. */
240
+ readonly switched: boolean;
241
+ readonly pinned: boolean;
242
+ /**
243
+ * Trust in `best` ∈ [0, 1]: `facts.confidence × n / (n + 5)` with `n` the effective evidence of
244
+ * `best`'s posterior (0 with priors only). Reported, never a gate.
245
+ */
246
+ readonly confidence: number;
247
+ readonly reasonCode: DecisionReasonCode;
248
+ /** Human-readable reason, with the compared costs. */
249
+ readonly reason: string;
250
+ /**
251
+ * A27: the argmin BEFORE the evidence filter (the cheapest candidate that passes the permission, floor and never-down
252
+ * filters, whether or not it has evidence); `null` when nothing could be priced. It differs from `best` exactly when the
253
+ * evidence gate removed a cheaper candidate: the statistics log it in the row's trace.
254
+ */
255
+ readonly argmin: RouteChoice | null;
256
+ /** `C(k)` per candidate key, finite numbers only, in `unit`. */
257
+ readonly costs: Readonly<Record<string, number>>;
258
+ /** D5: every cost of this decision is in this unit. */
259
+ readonly unit: CostUnit;
260
+ /** Candidates that could not be `best`, by key. */
261
+ readonly ineligible: Readonly<Record<string, IneligibleReason>>;
262
+ /** `best`'s candidate (its `agent`/`model`/`variant` are what an `enforce` swap writes); `null` with `best`. */
263
+ readonly target: Candidate | null;
264
+ /**
265
+ * A34 (QA-G-B1): the pick's CAPABILITY rank — the highest rank of a preset rung on the pick's model (`kernel.capabilityRank`),
266
+ * never below its candidate rank. Never-down and the A24/A27 "strictly higher rank" test compare against it; candidate ranks
267
+ * stay capped at the class's owning tier (A25). `null` when the pick is not a candidate.
268
+ */
269
+ readonly pickRank: number | null;
270
+ }
@@ -0,0 +1,53 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { PersistFs, OutcomeLogger } from "./outcomes/types";
3
+
4
+ export const LOCK_STALE_MS = 30_000;
5
+ export type LockResult<T> = { status: "ran"; value: T } | { status: "busy" };
6
+
7
+ /** Exclusive create, bounded attempts, mtime-based stale recovery; never waits on the hot path.
8
+ * A process suspended longer than staleMs can lose its lease: this is a best-effort local-file lock.
9
+ * Lock errors propagate: callers choose whether an unlocked fallback is safe.
10
+ */
11
+ export async function withLock<T>(
12
+ fs: PersistFs, dir: string, lockPath: string, now: () => number,
13
+ logger: OutcomeLogger, run: () => Promise<T>, staleMs = LOCK_STALE_MS,
14
+ ): Promise<LockResult<T>> {
15
+ await fs.mkdirp(dir);
16
+ let acquired = false;
17
+ for (let attempt = 0; attempt < 3; attempt++) {
18
+ if (await fs.createExclusive(lockPath, String(now()))) {
19
+ acquired = true;
20
+ break;
21
+ }
22
+ const held = await fs.stat(lockPath);
23
+ if (held === null) continue;
24
+ if (now() - held.mtimeMs < staleMs) return { status: "busy" };
25
+ const grave = `${lockPath}.stale-${randomUUID()}`;
26
+ try {
27
+ await fs.rename(lockPath, grave);
28
+ } catch (error) {
29
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") continue;
30
+ throw error;
31
+ }
32
+ const moved = await fs.stat(grave);
33
+ if (moved !== null && now() - moved.mtimeMs < staleMs) {
34
+ try {
35
+ await fs.rename(grave, lockPath);
36
+ } catch (error) {
37
+ logger.warn("[router] could not put back a live file lock", { error: String(error) });
38
+ }
39
+ return { status: "busy" };
40
+ }
41
+ try { await fs.unlink(grave); } catch (error) {
42
+ logger.warn("[router] could not remove stale file lock", { error: String(error) });
43
+ }
44
+ }
45
+ if (!acquired) return { status: "busy" };
46
+ try {
47
+ return { status: "ran", value: await run() };
48
+ } finally {
49
+ try { await fs.unlink(lockPath); } catch (error) {
50
+ logger.warn("[router] could not remove file lock", { error: String(error) });
51
+ }
52
+ }
53
+ }
@@ -0,0 +1,141 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Beta posteriors (M3): D4 observations, D7 rank priors, time decay, effective-sample cap.
3
+ //
4
+ // Design: docs/qa/cost-aware-routing/phase-1.3.md "Design (1.3.1)" §2.
5
+ // Pure module: no I/O, no clock of its own (every function takes `now`). Must stay runnable under
6
+ // Node type stripping (type-only imports use `import type`).
7
+ //
8
+ // Stored state is *evidence only* (prior excluded) expressed at `updatedAt`. The D7 prior is added on
9
+ // read, so changing a rank never rewrites evidence and old evidence decays toward the prior.
10
+ // ---------------------------------------------------------------------------
11
+
12
+ import type { BetaPrior, BetaState, OutcomeTuning, Posterior } from "./types";
13
+ import { DEFAULT_OUTCOME_TUNING } from "./types";
14
+
15
+ /** `alpha + beta` of every D7 prior. */
16
+ export const PRIOR_STRENGTH = 5;
17
+ /** Evidence totals below this are flushed to 0 so subnormals never reach storage. */
18
+ export const MIN_TINY = 1e-12;
19
+ export const DAY_MS = 86_400_000;
20
+
21
+ const MAX_PRIOR_OFFSET_CENTI = 95;
22
+ const MIN_PRIOR_OFFSET_CENTI = 30;
23
+
24
+ /**
25
+ * D7: prior for a candidate whose capability rank differs from the static tier of the class by `offset`
26
+ * (`rank(candidate) − rank(static tier)`). Means: ≤ −2 → 0.30 (floor), −1 → 0.55, 0 → 0.80, +1 → 0.85,
27
+ * +2 → 0.90, ≥ +3 → 0.95 (cap). Integer hundredths keep every value exact in binary.
28
+ */
29
+ export function priorForRankOffset(offset: number): BetaPrior {
30
+ const o = Number.isFinite(offset) ? Math.round(offset) : 0;
31
+ const centi =
32
+ o >= 0
33
+ ? Math.min(MAX_PRIOR_OFFSET_CENTI, 80 + 5 * o)
34
+ : Math.max(MIN_PRIOR_OFFSET_CENTI, 80 + 25 * o);
35
+ const alpha = centi / 20;
36
+ return { alpha, beta: PRIOR_STRENGTH - alpha };
37
+ }
38
+
39
+ /** Same-rank prior, `Beta(4, 1)` (mean 0.80). */
40
+ export const SAME_RANK_PRIOR: BetaPrior = Object.freeze(priorForRankOffset(0));
41
+
42
+ function clamp(x: number, lo: number, hi: number): number {
43
+ return Math.min(hi, Math.max(lo, x));
44
+ }
45
+
46
+ /** Defensive normalisation of `routing.outcomes` tuning (1.1 validates the same ranges). */
47
+ export function sanitizeTuning(tuning: Partial<OutcomeTuning> | null | undefined): OutcomeTuning {
48
+ const half = tuning?.halfLifeDays;
49
+ const cap = tuning?.maxEffectiveSamples;
50
+ return {
51
+ halfLifeDays: typeof half === "number" && Number.isFinite(half) ? clamp(half, 1, 365) : DEFAULT_OUTCOME_TUNING.halfLifeDays,
52
+ maxEffectiveSamples:
53
+ typeof cap === "number" && Number.isFinite(cap)
54
+ ? clamp(Math.round(cap), 5, 1000)
55
+ : DEFAULT_OUTCOME_TUNING.maxEffectiveSamples,
56
+ };
57
+ }
58
+
59
+ /**
60
+ * `2 ** (−dt / (halfLifeDays · DAY_MS))` ∈ [0, 1]. A negative, NaN or non-finite `dt` counts as 0, so a
61
+ * clock going backwards gives factor 1 and counts never inflate.
62
+ */
63
+ export function decayFactor(dtMs: number, halfLifeDays: number): number {
64
+ const dt = Number.isFinite(dtMs) && dtMs > 0 ? dtMs : 0;
65
+ const half = Number.isFinite(halfLifeDays) && halfLifeDays > 0 ? halfLifeDays : DEFAULT_OUTCOME_TUNING.halfLifeDays;
66
+ return 2 ** (-dt / (half * DAY_MS));
67
+ }
68
+
69
+ /**
70
+ * Express `state` at `now`. Pure and multiplicative (materialising at t1 then t2 equals materialising at
71
+ * t2 directly). `updatedAt` never moves backwards by less than a day (clock jitter); further back it is
72
+ * re-stamped at `now` with the counts untouched (QA-1.3-7). A NaN `now` means "no time passed".
73
+ */
74
+ export function decayTo(state: BetaState, now: number, tuning: OutcomeTuning): BetaState {
75
+ const t = Number.isFinite(now) ? now : state.updatedAt;
76
+ // QA-1.3-7: more than a day behind the stored instant is a clock correction, not jitter: re-stamp the
77
+ // evidence at `t` (counts untouched, so nothing inflates) instead of leaving it frozen in the "future".
78
+ if (t < state.updatedAt - DAY_MS) return { alpha: state.alpha, beta: state.beta, updatedAt: t };
79
+ const f = decayFactor(t - state.updatedAt, tuning.halfLifeDays);
80
+ let alpha = state.alpha * f;
81
+ let beta = state.beta * f;
82
+ if (alpha + beta < MIN_TINY) {
83
+ alpha = 0;
84
+ beta = 0;
85
+ }
86
+ return { alpha, beta, updatedAt: Math.max(state.updatedAt, t) };
87
+ }
88
+
89
+ /** Scale the evidence down to `maxEffectiveSamples` total, preserving the evidence mean (≤ 1e-15). */
90
+ export function capEvidence(state: BetaState, maxEffectiveSamples: number): BetaState {
91
+ const n = state.alpha + state.beta;
92
+ if (!(n > maxEffectiveSamples)) return state;
93
+ const scale = maxEffectiveSamples / n;
94
+ return { alpha: state.alpha * scale, beta: state.beta * scale, updatedAt: state.updatedAt };
95
+ }
96
+
97
+ /** D4: one observation. Decays the stored evidence to `now`, adds +1 to alpha (success) or beta, then caps. */
98
+ export function observe(state: BetaState | undefined, success: boolean, now: number, tuning: OutcomeTuning): BetaState {
99
+ const at = Number.isFinite(now) ? now : (state?.updatedAt ?? 0);
100
+ const base = decayTo(state ?? { alpha: 0, beta: 0, updatedAt: at }, at, tuning);
101
+ const next: BetaState = success
102
+ ? { alpha: base.alpha + 1, beta: base.beta, updatedAt: base.updatedAt }
103
+ : { alpha: base.alpha, beta: base.beta + 1, updatedAt: base.updatedAt };
104
+ return capEvidence(next, tuning.maxEffectiveSamples);
105
+ }
106
+
107
+ function usablePrior(prior: BetaPrior): BetaPrior {
108
+ const ok = Number.isFinite(prior.alpha) && Number.isFinite(prior.beta) && prior.alpha > 0 && prior.beta > 0;
109
+ return ok ? prior : SAME_RANK_PRIOR;
110
+ }
111
+
112
+ /**
113
+ * Posterior at read time: prior + evidence decayed to `now` and capped. A read only: it never writes
114
+ * back, so reads cannot drift the stored state. Unknown evidence → exactly the prior.
115
+ */
116
+ export function posteriorOf(
117
+ state: BetaState | undefined,
118
+ prior: BetaPrior,
119
+ now: number,
120
+ tuning: OutcomeTuning,
121
+ ): Posterior {
122
+ const p = usablePrior(prior);
123
+ const e = state ? capEvidence(decayTo(state, now, tuning), tuning.maxEffectiveSamples) : { alpha: 0, beta: 0 };
124
+ const alpha = p.alpha + e.alpha;
125
+ const beta = p.beta + e.beta;
126
+ return { alpha, beta, mean: alpha / (alpha + beta), n: e.alpha + e.beta, prior: p };
127
+ }
128
+
129
+ /**
130
+ * Add two evidence states (loading a disk snapshot into a live store). Both are decayed to a common
131
+ * instant `max(a.updatedAt, b.updatedAt, now)` (forward only), summed, and capped.
132
+ */
133
+ export function mergeBeta(a: BetaState, b: BetaState, now: number, tuning: OutcomeTuning): BetaState {
134
+ const newest = Math.max(a.updatedAt, b.updatedAt);
135
+ // A clock more than a day behind both states is a correction (QA-1.3-7): express the sum at `now`.
136
+ const t = !Number.isFinite(now) ? newest : newest - now > DAY_MS ? now : Math.max(newest, now);
137
+ const da = decayTo(a, t, tuning);
138
+ const db = decayTo(b, t, tuning);
139
+ const sum: BetaState = { alpha: da.alpha + db.alpha, beta: da.beta + db.beta, updatedAt: t };
140
+ return capEvidence(sum, tuning.maxEffectiveSamples);
141
+ }