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