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.
- package/CHANGELOG.md +214 -0
- package/README.md +90 -12
- package/package.json +4 -1
- package/src/commands/output.ts +24 -1
- package/src/compat/child-session.ts +43 -0
- package/src/compat/v2-client.ts +107 -7
- package/src/compat/v2-hooks.ts +1435 -44
- package/src/escalate/attempt-recorder.ts +263 -0
- package/src/escalate/ladder.ts +496 -10
- package/src/escalate/resume.ts +208 -0
- package/src/escalate/variants.ts +391 -0
- package/src/guard/enforce.ts +186 -22
- package/src/guard/guards.ts +132 -6
- package/src/guard/store.ts +5 -0
- package/src/index.ts +1193 -56
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1611 -19
- package/src/router/dispatch-header.ts +46 -4
- package/src/router/git-tools.ts +1152 -0
- package/src/router/guard-profile.ts +100 -0
- package/src/router/plugin-agents.ts +433 -0
- package/src/router/prompts.ts +26 -1
- package/src/router/protocol.ts +180 -0
- package/src/router/read-only.ts +149 -0
- package/src/router/role-agents.ts +409 -0
- package/src/router/roles-config.ts +429 -0
- package/src/router/roles.ts +600 -0
- package/src/router/run-tools.ts +913 -0
- package/src/router/sensitive-paths.ts +101 -0
- package/src/router/sessions.ts +533 -9
- package/src/router/subagents.ts +28 -1
- package/src/routing/advisor/findings.ts +898 -0
- package/src/routing/advisor/index.ts +614 -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 +594 -0
- package/src/routing/classify/route-line.ts +362 -0
- package/src/routing/classify/rules.ts +667 -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 +1310 -0
- package/src/routing/commands/annotate-plan.ts +652 -0
- package/src/routing/commands/stats.ts +134 -0
- package/src/routing/commands/v1-roles.ts +64 -0
- package/src/routing/engine/index.ts +32 -0
- package/src/routing/engine/kernel.ts +760 -0
- package/src/routing/engine/ladders.ts +802 -0
- package/src/routing/engine/plan.ts +404 -0
- package/src/routing/engine/protocol-line.ts +150 -0
- package/src/routing/engine/roles-taxonomy.ts +52 -0
- package/src/routing/engine/simulate.ts +167 -0
- package/src/routing/engine/types.ts +368 -0
- package/src/routing/file-lock.ts +53 -0
- package/src/routing/outcomes/beta.ts +147 -0
- package/src/routing/outcomes/cost.ts +313 -0
- package/src/routing/outcomes/index.ts +215 -0
- package/src/routing/outcomes/ingest.ts +960 -0
- package/src/routing/outcomes/persist.ts +1080 -0
- package/src/routing/outcomes/signals.ts +650 -0
- package/src/routing/outcomes/stats.ts +873 -0
- package/src/routing/outcomes/store.ts +673 -0
- package/src/routing/outcomes/types.ts +1093 -0
- package/src/routing/roles/authority.ts +495 -0
- package/src/routing/roles/binding.ts +543 -0
- package/src/routing/roles/policy.ts +416 -0
- package/src/routing/roles/work-root.ts +132 -0
- package/src/routing/wire/dispatch.ts +2088 -0
- package/src/routing/wire/hint.ts +222 -0
- package/src/routing/wire/host-info.ts +256 -0
- package/src/routing/wire/runtime.ts +348 -0
- package/src/v2.ts +40 -1
- package/src/verify/checker.ts +249 -7
- package/src/verify/deterministic.ts +10 -1
- package/src/verify/dispatch.ts +63 -6
- package/src/verify/dod.ts +127 -10
- package/src/verify/gate.ts +75 -7
- package/src/verify/types.ts +12 -0
- package/src/verify/wiring.ts +55 -10
- package/tiers.json +13 -5
|
@@ -0,0 +1,673 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Outcome store (M3): per-key Beta evidence (D4), per-attempt cost accounting (D6), snapshot/restore.
|
|
3
|
+
//
|
|
4
|
+
// Design: docs/qa/cost-aware-routing/phase-1.3.md "Design (1.3.1)" §4.
|
|
5
|
+
// Pure core: no I/O. The clock is injected (`Date.now` is only the default). Single writer per process
|
|
6
|
+
// (A3) is enforced by index.ts; this module is a plain in-memory object.
|
|
7
|
+
// ---------------------------------------------------------------------------
|
|
8
|
+
|
|
9
|
+
import type {
|
|
10
|
+
AttemptSignal,
|
|
11
|
+
BetaPrior,
|
|
12
|
+
BetaState,
|
|
13
|
+
CostStats,
|
|
14
|
+
MeanStat,
|
|
15
|
+
OpenAttempt,
|
|
16
|
+
OutcomeCounts,
|
|
17
|
+
OutcomeEntrySnapshot,
|
|
18
|
+
OutcomeKey,
|
|
19
|
+
OutcomeSnapshot,
|
|
20
|
+
OutcomeStore,
|
|
21
|
+
OutcomeStoreOptions,
|
|
22
|
+
OutcomeTuning,
|
|
23
|
+
SnapshotLoadReport,
|
|
24
|
+
StepSample,
|
|
25
|
+
TokenMeans,
|
|
26
|
+
Verdict,
|
|
27
|
+
} from "./types";
|
|
28
|
+
import { OUTCOMES_SCHEMA_ID, OUTCOMES_SCHEMA_VERSION, parseKey, safeNow } from "./types";
|
|
29
|
+
import { DAY_MS, MIN_TINY, SAME_RANK_PRIOR, capEvidence, decayFactor, decayTo, mergeBeta, observe, posteriorOf, sanitizeTuning } from "./beta";
|
|
30
|
+
import {
|
|
31
|
+
addTokens,
|
|
32
|
+
cleanTokenSample,
|
|
33
|
+
emptyCostStats,
|
|
34
|
+
emptyTokenSample,
|
|
35
|
+
foldAttempt,
|
|
36
|
+
mergeCostStats,
|
|
37
|
+
stepUSD,
|
|
38
|
+
} from "./cost";
|
|
39
|
+
|
|
40
|
+
const DEFAULT_MAX_OPEN_ATTEMPTS = 256;
|
|
41
|
+
const DEFAULT_MAX_SCORED_ATTEMPTS = 4096;
|
|
42
|
+
const DEFAULT_MAX_IDLE_MS = 30 * 60_000;
|
|
43
|
+
|
|
44
|
+
/** Internal mutable entry. Every field is replaced (never mutated in place), so values handed out stay stable. */
|
|
45
|
+
interface Entry {
|
|
46
|
+
readonly cls: string;
|
|
47
|
+
beta: BetaState;
|
|
48
|
+
counts: OutcomeCounts;
|
|
49
|
+
cost: CostStats;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const ZERO_COUNTS: OutcomeCounts = Object.freeze({
|
|
53
|
+
pass: 0,
|
|
54
|
+
fail: 0,
|
|
55
|
+
falseRefusals: 0,
|
|
56
|
+
variantPass: 0,
|
|
57
|
+
variantFail: 0,
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
function deepFreeze<T extends object>(value: T): T {
|
|
61
|
+
for (const child of Object.values(value)) {
|
|
62
|
+
if (typeof child === "object" && child !== null && !Object.isFrozen(child)) deepFreeze(child);
|
|
63
|
+
}
|
|
64
|
+
return Object.freeze(value);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const EMPTY_COST: CostStats = deepFreeze(emptyCostStats());
|
|
68
|
+
|
|
69
|
+
function compareCodeUnits(a: string, b: string): number {
|
|
70
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** LRU on a Map: refresh = delete + set; evict from the front. */
|
|
74
|
+
function remember<V>(map: Map<string, V>, id: string, value: V, max: number): void {
|
|
75
|
+
map.delete(id);
|
|
76
|
+
map.set(id, value);
|
|
77
|
+
while (map.size > max) {
|
|
78
|
+
const oldest = map.keys().next();
|
|
79
|
+
if (oldest.done === true) break;
|
|
80
|
+
map.delete(oldest.value);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** What scored an attempt (QA-1.3-6): enough to convert a pass into a failure when a false refusal follows it. */
|
|
85
|
+
interface ScoredInfo {
|
|
86
|
+
readonly key: OutcomeKey;
|
|
87
|
+
readonly kind: "pass" | "fail" | "refusal";
|
|
88
|
+
/** Instant of the Beta observation. */
|
|
89
|
+
readonly at: number;
|
|
90
|
+
/** The scoring signal was a `variant` step. */
|
|
91
|
+
readonly variant: boolean;
|
|
92
|
+
/** QA-P33F2-1-1: the Beta weight the observation carried (1, or 0.5 for an independent grader); absent = 1. */
|
|
93
|
+
readonly weight?: number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ---------------------------------------------------------------------------
|
|
97
|
+
// Snapshot validation (shared by fromSnapshot and parseSnapshot)
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
|
|
100
|
+
type Rec = Record<string, unknown>;
|
|
101
|
+
|
|
102
|
+
function isRec(x: unknown): x is Rec {
|
|
103
|
+
return typeof x === "object" && x !== null && !Array.isArray(x);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function isFiniteNum(x: unknown): x is number {
|
|
107
|
+
return typeof x === "number" && Number.isFinite(x);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function isNonNegFinite(x: unknown): x is number {
|
|
111
|
+
return isFiniteNum(x) && x >= 0;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function isCount(x: unknown): x is number {
|
|
115
|
+
return typeof x === "number" && Number.isInteger(x) && x >= 0;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function readMean(x: unknown): MeanStat | null {
|
|
119
|
+
if (!isRec(x) || !isNonNegFinite(x.mean) || !isCount(x.n)) return null;
|
|
120
|
+
return { mean: x.mean, n: x.n };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function readTokenMeans(x: unknown): TokenMeans | null {
|
|
124
|
+
if (!isRec(x) || !isCount(x.n)) return null;
|
|
125
|
+
const { input, output, reasoning, cacheRead, cacheWrite } = x;
|
|
126
|
+
if (!isNonNegFinite(input) || !isNonNegFinite(output) || !isNonNegFinite(reasoning)) return null;
|
|
127
|
+
if (!isNonNegFinite(cacheRead) || !isNonNegFinite(cacheWrite)) return null;
|
|
128
|
+
return { n: x.n, input, output, reasoning, cacheRead, cacheWrite };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function readCounts(x: unknown): OutcomeCounts | null {
|
|
132
|
+
if (!isRec(x)) return null;
|
|
133
|
+
const { pass, fail, falseRefusals, variantPass, variantFail } = x;
|
|
134
|
+
if (!isCount(pass) || !isCount(fail) || !isCount(falseRefusals) || !isCount(variantPass) || !isCount(variantFail)) {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
return { pass, fail, falseRefusals, variantPass, variantFail };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function readCost(x: unknown): CostStats | null {
|
|
141
|
+
if (!isRec(x) || !isCount(x.unpricedAttempts)) return null;
|
|
142
|
+
const measuredUSD = readMean(x.measuredUSD);
|
|
143
|
+
const tokens = readTokenMeans(x.tokens);
|
|
144
|
+
const steps = readMean(x.steps);
|
|
145
|
+
const finalMessageTokens = readMean(x.finalMessageTokens);
|
|
146
|
+
if (!measuredUSD || !tokens || !steps || !finalMessageTokens) return null;
|
|
147
|
+
return { measuredUSD, unpricedAttempts: x.unpricedAttempts, tokens, steps, finalMessageTokens };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Validate one persisted entry and return a deep copy of plain numbers, or null when invalid. */
|
|
151
|
+
function readEntry(key: string, value: unknown): Entry | null {
|
|
152
|
+
const parts = parseKey(key);
|
|
153
|
+
if (parts === null || !isRec(value)) return null;
|
|
154
|
+
const b = value.beta;
|
|
155
|
+
if (!isRec(b) || !isNonNegFinite(b.alpha) || !isNonNegFinite(b.beta) || !isFiniteNum(b.updatedAt)) return null;
|
|
156
|
+
const counts = readCounts(value.counts);
|
|
157
|
+
const cost = readCost(value.cost);
|
|
158
|
+
if (!counts || !cost) return null;
|
|
159
|
+
return { cls: parts.cls, beta: { alpha: b.alpha, beta: b.beta, updatedAt: b.updatedAt }, counts, cost };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function entrySnapshot(entry: Entry): OutcomeEntrySnapshot {
|
|
163
|
+
return {
|
|
164
|
+
beta: { alpha: entry.beta.alpha, beta: entry.beta.beta, updatedAt: entry.beta.updatedAt },
|
|
165
|
+
counts: { ...entry.counts },
|
|
166
|
+
cost: {
|
|
167
|
+
measuredUSD: { ...entry.cost.measuredUSD },
|
|
168
|
+
unpricedAttempts: entry.cost.unpricedAttempts,
|
|
169
|
+
tokens: { ...entry.cost.tokens },
|
|
170
|
+
steps: { ...entry.cost.steps },
|
|
171
|
+
finalMessageTokens: { ...entry.cost.finalMessageTokens },
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function addCounts(a: OutcomeCounts, b: OutcomeCounts): OutcomeCounts {
|
|
177
|
+
return {
|
|
178
|
+
pass: a.pass + b.pass,
|
|
179
|
+
fail: a.fail + b.fail,
|
|
180
|
+
falseRefusals: a.falseRefusals + b.falseRefusals,
|
|
181
|
+
variantPass: a.variantPass + b.variantPass,
|
|
182
|
+
variantFail: a.variantFail + b.variantFail,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ---------------------------------------------------------------------------
|
|
187
|
+
// Foreign-writer merge (QA-1.3-4, 16, 17): live + (disk − baseline), per entry
|
|
188
|
+
// ---------------------------------------------------------------------------
|
|
189
|
+
|
|
190
|
+
/** `live + disk − base` of a running mean in ONE step (QA-1.3-17); only the result is clamped, never the parts. */
|
|
191
|
+
function mergeMean(live: MeanStat, disk: MeanStat, base: MeanStat): MeanStat {
|
|
192
|
+
const n = live.n + disk.n - base.n;
|
|
193
|
+
if (n <= 0) return { mean: 0, n: 0 };
|
|
194
|
+
return { mean: Math.max(0, (live.mean * live.n + disk.mean * disk.n - base.mean * base.n) / n), n };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function mergeTokens(live: TokenMeans, disk: TokenMeans, base: TokenMeans): TokenMeans {
|
|
198
|
+
const n = live.n + disk.n - base.n;
|
|
199
|
+
if (n <= 0) return { n: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0 };
|
|
200
|
+
const part = (l: number, d: number, b: number): number => Math.max(0, (l * live.n + d * disk.n - b * base.n) / n);
|
|
201
|
+
return {
|
|
202
|
+
n,
|
|
203
|
+
input: part(live.input, disk.input, base.input),
|
|
204
|
+
output: part(live.output, disk.output, base.output),
|
|
205
|
+
reasoning: part(live.reasoning, disk.reasoning, base.reasoning),
|
|
206
|
+
cacheRead: part(live.cacheRead, disk.cacheRead, base.cacheRead),
|
|
207
|
+
cacheWrite: part(live.cacheWrite, disk.cacheWrite, base.cacheWrite),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const NO_BETA: BetaState = Object.freeze({ alpha: 0, beta: 0, updatedAt: 0 });
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* `live + (disk − base)` for an entry whose disk copy descends from the baseline: what another writer added
|
|
215
|
+
* since this process last synced, added on top of everything this process holds now. Each quantity is combined
|
|
216
|
+
* in one step, so nothing is clamped before the arithmetic is done (QA-1.3-17): counters and attempt-weighted
|
|
217
|
+
* means come out exact while no mean has passed the effective-sample cap, and stay consistent past it (a mean
|
|
218
|
+
* that is an EWMA is combined by the same n-weighted rule as every other merge). The Beta evidence is combined
|
|
219
|
+
* at a common instant and floored at 0.
|
|
220
|
+
*/
|
|
221
|
+
function mergeDescendant(live: Entry | undefined, disk: Entry, base: Entry, now: number, tuning: OutcomeTuning): Entry {
|
|
222
|
+
const l = live?.beta ?? NO_BETA;
|
|
223
|
+
const newest = Math.max(l.updatedAt, disk.beta.updatedAt, base.beta.updatedAt);
|
|
224
|
+
// A clock more than a day behind every stamp is a correction (QA-1.3-7): express the sum at `now`.
|
|
225
|
+
const at = newest - now > DAY_MS ? now : Math.max(newest, now);
|
|
226
|
+
const dl = live === undefined ? { alpha: 0, beta: 0, updatedAt: at } : decayTo(l, at, tuning);
|
|
227
|
+
const dd = decayTo(disk.beta, at, tuning);
|
|
228
|
+
const db = decayTo(base.beta, at, tuning);
|
|
229
|
+
let alpha = Math.max(0, dl.alpha + dd.alpha - db.alpha);
|
|
230
|
+
let beta = Math.max(0, dl.beta + dd.beta - db.beta);
|
|
231
|
+
if (alpha + beta < MIN_TINY) {
|
|
232
|
+
alpha = 0;
|
|
233
|
+
beta = 0;
|
|
234
|
+
}
|
|
235
|
+
const lc = live?.counts ?? ZERO_COUNTS;
|
|
236
|
+
const dc = disk.counts;
|
|
237
|
+
const bc = base.counts;
|
|
238
|
+
const lk = live?.cost ?? EMPTY_COST;
|
|
239
|
+
return {
|
|
240
|
+
cls: disk.cls,
|
|
241
|
+
beta: capEvidence({ alpha, beta, updatedAt: at }, tuning.maxEffectiveSamples),
|
|
242
|
+
counts: {
|
|
243
|
+
pass: Math.max(0, lc.pass + dc.pass - bc.pass),
|
|
244
|
+
fail: Math.max(0, lc.fail + dc.fail - bc.fail),
|
|
245
|
+
falseRefusals: Math.max(0, lc.falseRefusals + dc.falseRefusals - bc.falseRefusals),
|
|
246
|
+
variantPass: Math.max(0, lc.variantPass + dc.variantPass - bc.variantPass),
|
|
247
|
+
variantFail: Math.max(0, lc.variantFail + dc.variantFail - bc.variantFail),
|
|
248
|
+
},
|
|
249
|
+
cost: {
|
|
250
|
+
measuredUSD: mergeMean(lk.measuredUSD, disk.cost.measuredUSD, base.cost.measuredUSD),
|
|
251
|
+
unpricedAttempts: Math.max(0, lk.unpricedAttempts + disk.cost.unpricedAttempts - base.cost.unpricedAttempts),
|
|
252
|
+
tokens: mergeTokens(lk.tokens, disk.cost.tokens, base.cost.tokens),
|
|
253
|
+
steps: mergeMean(lk.steps, disk.cost.steps, base.cost.steps),
|
|
254
|
+
finalMessageTokens: mergeMean(lk.finalMessageTokens, disk.cost.finalMessageTokens, base.cost.finalMessageTokens),
|
|
255
|
+
},
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* QA-1.3-16: can `disk` be a later state of the lineage that `base` belongs to? Every counter and every
|
|
260
|
+
* sample count only ever grows, so one that is *lower* on disk means the file was reset or replaced (deleted
|
|
261
|
+
* and started again by a fresh process, restored from a backup, ...). Subtracting the baseline from such an
|
|
262
|
+
* entry would swallow the new writer's records, so it is taken whole instead.
|
|
263
|
+
*/
|
|
264
|
+
function descendsFrom(disk: Entry, base: Entry): boolean {
|
|
265
|
+
const d = disk.counts;
|
|
266
|
+
const b = base.counts;
|
|
267
|
+
return (
|
|
268
|
+
d.pass >= b.pass &&
|
|
269
|
+
d.fail >= b.fail &&
|
|
270
|
+
d.falseRefusals >= b.falseRefusals &&
|
|
271
|
+
d.variantPass >= b.variantPass &&
|
|
272
|
+
d.variantFail >= b.variantFail &&
|
|
273
|
+
disk.cost.unpricedAttempts >= base.cost.unpricedAttempts &&
|
|
274
|
+
disk.cost.measuredUSD.n >= base.cost.measuredUSD.n &&
|
|
275
|
+
disk.cost.tokens.n >= base.cost.tokens.n &&
|
|
276
|
+
disk.cost.steps.n >= base.cost.steps.n &&
|
|
277
|
+
disk.cost.finalMessageTokens.n >= base.cost.finalMessageTokens.n
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Did the other writer add anything (given that `disk` descends from `base`)? Counters and sample counts only grow. */
|
|
282
|
+
function grewSince(disk: Entry, base: Entry): boolean {
|
|
283
|
+
const d = disk.counts;
|
|
284
|
+
const b = base.counts;
|
|
285
|
+
return (
|
|
286
|
+
d.pass !== b.pass ||
|
|
287
|
+
d.fail !== b.fail ||
|
|
288
|
+
d.falseRefusals !== b.falseRefusals ||
|
|
289
|
+
d.variantPass !== b.variantPass ||
|
|
290
|
+
d.variantFail !== b.variantFail ||
|
|
291
|
+
disk.cost.unpricedAttempts !== base.cost.unpricedAttempts ||
|
|
292
|
+
disk.cost.measuredUSD.n !== base.cost.measuredUSD.n ||
|
|
293
|
+
disk.cost.tokens.n !== base.cost.tokens.n ||
|
|
294
|
+
disk.cost.steps.n !== base.cost.steps.n ||
|
|
295
|
+
disk.cost.finalMessageTokens.n !== base.cost.finalMessageTokens.n
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
export type ParseSnapshotResult =
|
|
299
|
+
| { readonly ok: true; readonly snapshot: OutcomeSnapshot; readonly dropped: number }
|
|
300
|
+
| { readonly ok: false; readonly reason: "unsupported-version" | "corrupt"; readonly message: string };
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Validate a parsed `outcomes.json` envelope. A newer `version`, another schema, a non-object or a
|
|
304
|
+
* non-integer `version` is `unsupported-version` (never quarantined or overwritten by this plugin);
|
|
305
|
+
* `version < 1` or a missing `entries` object on our schema is `corrupt`. Invalid entries are dropped
|
|
306
|
+
* and counted; the valid ones come back with keys in sorted order.
|
|
307
|
+
*/
|
|
308
|
+
export function parseSnapshot(json: unknown): ParseSnapshotResult {
|
|
309
|
+
// QA-1.3-11: valid JSON that is not a version-1 outcome store is somebody else's file (or a newer
|
|
310
|
+
// format): report it as `unsupported-version` so it is never quarantined or overwritten.
|
|
311
|
+
if (!isRec(json)) {
|
|
312
|
+
return { ok: false, reason: "unsupported-version", message: "not an outcome store: the top-level JSON value is not an object" };
|
|
313
|
+
}
|
|
314
|
+
if (json.schema !== OUTCOMES_SCHEMA_ID) {
|
|
315
|
+
return { ok: false, reason: "unsupported-version", message: `not an outcome store: unexpected schema ${JSON.stringify(json.schema)}` };
|
|
316
|
+
}
|
|
317
|
+
const version = json.version;
|
|
318
|
+
if (typeof version !== "number" || !Number.isInteger(version)) {
|
|
319
|
+
return { ok: false, reason: "unsupported-version", message: `unrecognized outcome store version ${JSON.stringify(version)}` };
|
|
320
|
+
}
|
|
321
|
+
if (version > OUTCOMES_SCHEMA_VERSION) {
|
|
322
|
+
return {
|
|
323
|
+
ok: false,
|
|
324
|
+
reason: "unsupported-version",
|
|
325
|
+
message: `unsupported outcome store version ${version} (this plugin reads version ${OUTCOMES_SCHEMA_VERSION})`,
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
if (version < 1) return { ok: false, reason: "corrupt", message: `invalid version ${version}` };
|
|
329
|
+
if (!isRec(json.entries)) return { ok: false, reason: "corrupt", message: "missing entries object" };
|
|
330
|
+
|
|
331
|
+
const valid: Array<readonly [string, OutcomeEntrySnapshot]> = [];
|
|
332
|
+
let dropped = 0;
|
|
333
|
+
for (const [key, value] of Object.entries(json.entries)) {
|
|
334
|
+
const entry = readEntry(key, value);
|
|
335
|
+
if (entry === null) dropped += 1;
|
|
336
|
+
else valid.push([key, entrySnapshot(entry)]);
|
|
337
|
+
}
|
|
338
|
+
valid.sort((a, b) => compareCodeUnits(a[0], b[0]));
|
|
339
|
+
const entries: Record<string, OutcomeEntrySnapshot> = {};
|
|
340
|
+
for (const [key, snap] of valid) entries[key] = snap;
|
|
341
|
+
return { ok: true, snapshot: { version: OUTCOMES_SCHEMA_VERSION, entries }, dropped };
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// ---------------------------------------------------------------------------
|
|
345
|
+
// Store
|
|
346
|
+
// ---------------------------------------------------------------------------
|
|
347
|
+
|
|
348
|
+
export function createOutcomeStore(options: OutcomeStoreOptions = {}): OutcomeStore {
|
|
349
|
+
const now = options.now ?? Date.now;
|
|
350
|
+
/** One reading of the clock; a non-finite reading falls back to Date.now() (QA-1.3-7). */
|
|
351
|
+
const clockNow = (): number => safeNow(now);
|
|
352
|
+
const maxOpen = Math.max(1, Math.floor(options.maxOpenAttempts ?? DEFAULT_MAX_OPEN_ATTEMPTS));
|
|
353
|
+
const maxScored = Math.max(1, Math.floor(options.maxScoredAttempts ?? DEFAULT_MAX_SCORED_ATTEMPTS));
|
|
354
|
+
let tuning: OutcomeTuning = sanitizeTuning(options);
|
|
355
|
+
let revision = 0;
|
|
356
|
+
|
|
357
|
+
const entries = new Map<OutcomeKey, Entry>();
|
|
358
|
+
const open = new Map<string, OpenAttempt>();
|
|
359
|
+
const scored = new Map<string, ScoredInfo>();
|
|
360
|
+
const closed = new Map<string, true>();
|
|
361
|
+
|
|
362
|
+
/** Existing entry, or a new one for a well-formed key (`cls` is cached from `parseKey`); null for a malformed key. */
|
|
363
|
+
function entryFor(key: OutcomeKey): Entry | null {
|
|
364
|
+
const existing = entries.get(key);
|
|
365
|
+
if (existing) return existing;
|
|
366
|
+
const parts = parseKey(key);
|
|
367
|
+
if (parts === null) return null;
|
|
368
|
+
const created: Entry = {
|
|
369
|
+
cls: parts.cls,
|
|
370
|
+
beta: { alpha: 0, beta: 0, updatedAt: clockNow() },
|
|
371
|
+
counts: ZERO_COUNTS,
|
|
372
|
+
cost: EMPTY_COST,
|
|
373
|
+
};
|
|
374
|
+
entries.set(key, created);
|
|
375
|
+
return created;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function fold(attempt: OpenAttempt): void {
|
|
379
|
+
const entry = entryFor(attempt.key);
|
|
380
|
+
if (entry === null) return;
|
|
381
|
+
entry.cost = foldAttempt(entry.cost, attempt, tuning.maxEffectiveSamples);
|
|
382
|
+
revision += 1;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** Add one validated persisted entry to the live state (new key: taken as is). */
|
|
386
|
+
function absorb(key: OutcomeKey, incoming: Entry, t: number): void {
|
|
387
|
+
// QA-1.3-7: evidence stamped after "now" (a clock that was ahead when it was written) is re-stamped.
|
|
388
|
+
if (incoming.beta.updatedAt > t) incoming.beta = { alpha: incoming.beta.alpha, beta: incoming.beta.beta, updatedAt: t };
|
|
389
|
+
const live = entries.get(key);
|
|
390
|
+
if (live === undefined) {
|
|
391
|
+
entries.set(key, incoming);
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
live.beta = mergeBeta(live.beta, incoming.beta, t, tuning);
|
|
395
|
+
live.counts = addCounts(live.counts, incoming.counts);
|
|
396
|
+
live.cost = mergeCostStats(live.cost, incoming.cost);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function markClosed(attemptID: string): void {
|
|
400
|
+
remember(closed, attemptID, true, maxScored);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function closeInternal(attemptID: string, rememberClosed: boolean): void {
|
|
404
|
+
const attempt = open.get(attemptID);
|
|
405
|
+
if (attempt === undefined) return;
|
|
406
|
+
open.delete(attemptID);
|
|
407
|
+
fold(attempt);
|
|
408
|
+
if (rememberClosed) markClosed(attemptID);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const store: OutcomeStore = {
|
|
412
|
+
get revision(): number {
|
|
413
|
+
return revision;
|
|
414
|
+
},
|
|
415
|
+
|
|
416
|
+
configure(next: Partial<OutcomeTuning>): void {
|
|
417
|
+
tuning = sanitizeTuning({
|
|
418
|
+
halfLifeDays: next.halfLifeDays ?? tuning.halfLifeDays,
|
|
419
|
+
maxEffectiveSamples: next.maxEffectiveSamples ?? tuning.maxEffectiveSamples,
|
|
420
|
+
});
|
|
421
|
+
},
|
|
422
|
+
|
|
423
|
+
recordVerdict(key: OutcomeKey, verdict: Verdict, signal: AttemptSignal, weight = 1): boolean {
|
|
424
|
+
if (verdict !== "pass" && verdict !== "fail") return false;
|
|
425
|
+
// QA-P33F2-1-1: a weighted observation (an independent grader's 0.5) never weighs more than one, nor nothing.
|
|
426
|
+
if (!(Number.isFinite(weight) && weight > 0 && weight <= 1)) return false;
|
|
427
|
+
const previous = scored.get(signal.attemptID);
|
|
428
|
+
if (previous !== undefined) {
|
|
429
|
+
remember(scored, signal.attemptID, previous, maxScored);
|
|
430
|
+
return false;
|
|
431
|
+
}
|
|
432
|
+
const entry = entryFor(key);
|
|
433
|
+
if (entry === null) return false;
|
|
434
|
+
const pass = verdict === "pass";
|
|
435
|
+
const variant = signal.step === "variant";
|
|
436
|
+
const t = clockNow();
|
|
437
|
+
entry.beta = observe(entry.beta, pass, t, tuning, weight);
|
|
438
|
+
const c = entry.counts;
|
|
439
|
+
entry.counts = {
|
|
440
|
+
pass: c.pass + (pass ? 1 : 0),
|
|
441
|
+
fail: c.fail + (pass ? 0 : 1),
|
|
442
|
+
falseRefusals: c.falseRefusals,
|
|
443
|
+
variantPass: c.variantPass + (variant && pass ? 1 : 0),
|
|
444
|
+
variantFail: c.variantFail + (variant && !pass ? 1 : 0),
|
|
445
|
+
};
|
|
446
|
+
remember(scored, signal.attemptID, { key, kind: pass ? "pass" : "fail", at: t, variant, ...(weight === 1 ? {} : { weight }) }, maxScored);
|
|
447
|
+
revision += 1;
|
|
448
|
+
return true;
|
|
449
|
+
},
|
|
450
|
+
|
|
451
|
+
recordFalseRefusal(key: OutcomeKey, signal: AttemptSignal): boolean {
|
|
452
|
+
const entry = entryFor(key);
|
|
453
|
+
if (entry === null) return false;
|
|
454
|
+
const previous = scored.get(signal.attemptID);
|
|
455
|
+
const c = entry.counts;
|
|
456
|
+
const t = clockNow();
|
|
457
|
+
revision += 1; // the lifetime counter below always changes
|
|
458
|
+
if (previous === undefined) {
|
|
459
|
+
// First terminal signal of the attempt: a failure.
|
|
460
|
+
const variant = signal.step === "variant";
|
|
461
|
+
entry.counts = { ...c, falseRefusals: c.falseRefusals + 1, variantFail: c.variantFail + (variant ? 1 : 0) };
|
|
462
|
+
entry.beta = observe(entry.beta, false, t, tuning);
|
|
463
|
+
remember(scored, signal.attemptID, { key, kind: "refusal", at: t, variant }, maxScored);
|
|
464
|
+
return true;
|
|
465
|
+
}
|
|
466
|
+
if (previous.kind === "pass" && previous.key === key) {
|
|
467
|
+
// QA-1.3-6: the pass was wrong. Observe the failure, take the pass's decayed contribution back out
|
|
468
|
+
// of alpha (floored at 0; an approximation once the cap has rescaled the evidence) and move the
|
|
469
|
+
// counters pass → fail.
|
|
470
|
+
const decayed = decayTo(entry.beta, t, tuning);
|
|
471
|
+
// QA-P33F2-1-1: a weighted pass (an independent grader's 0.5) gives back only what it added.
|
|
472
|
+
const contribution = decayFactor(t - previous.at, tuning.halfLifeDays) * (previous.weight ?? 1);
|
|
473
|
+
entry.beta = capEvidence(
|
|
474
|
+
{ alpha: Math.max(0, decayed.alpha - contribution), beta: decayed.beta + 1, updatedAt: decayed.updatedAt },
|
|
475
|
+
tuning.maxEffectiveSamples,
|
|
476
|
+
);
|
|
477
|
+
const v = previous.variant ? 1 : 0;
|
|
478
|
+
entry.counts = {
|
|
479
|
+
pass: Math.max(0, c.pass - 1),
|
|
480
|
+
fail: c.fail + 1,
|
|
481
|
+
falseRefusals: c.falseRefusals + 1,
|
|
482
|
+
variantPass: Math.max(0, c.variantPass - v),
|
|
483
|
+
variantFail: c.variantFail + v,
|
|
484
|
+
};
|
|
485
|
+
remember(scored, signal.attemptID, { key, kind: "refusal", at: t, variant: previous.variant }, maxScored);
|
|
486
|
+
return true;
|
|
487
|
+
}
|
|
488
|
+
const weight = previous.weight ?? 1;
|
|
489
|
+
if (previous.kind === "fail" && previous.key === key && weight < 1) {
|
|
490
|
+
// QA-P33F2-2 N-a: a weighted failure (an independent grader's 0.5) is topped up to a full failure, as a refusal after
|
|
491
|
+
// a weighted pass ends at one: beta gains 1 − weight × decay, so the attempt weighs one failure now. The fail is already
|
|
492
|
+
// counted; only the lifetime refusal counter moves. Recorded as the refusal, so a repeat tops up nothing.
|
|
493
|
+
const decayed = decayTo(entry.beta, t, tuning);
|
|
494
|
+
const topUp = Math.max(0, 1 - weight * decayFactor(t - previous.at, tuning.halfLifeDays));
|
|
495
|
+
entry.beta = capEvidence(
|
|
496
|
+
{ alpha: decayed.alpha, beta: decayed.beta + topUp, updatedAt: decayed.updatedAt },
|
|
497
|
+
tuning.maxEffectiveSamples,
|
|
498
|
+
);
|
|
499
|
+
entry.counts = { ...c, falseRefusals: c.falseRefusals + 1 };
|
|
500
|
+
remember(scored, signal.attemptID, { key, kind: "refusal", at: t, variant: previous.variant }, maxScored);
|
|
501
|
+
return true;
|
|
502
|
+
}
|
|
503
|
+
// Already a full failure (fail verdict or an earlier refusal): lifetime counter only.
|
|
504
|
+
entry.counts = { ...c, falseRefusals: c.falseRefusals + 1 };
|
|
505
|
+
remember(scored, signal.attemptID, previous, maxScored);
|
|
506
|
+
return false;
|
|
507
|
+
},
|
|
508
|
+
|
|
509
|
+
recordStep(key: OutcomeKey, step: StepSample): void {
|
|
510
|
+
if (closed.has(step.attemptID)) return;
|
|
511
|
+
let acc = open.get(step.attemptID);
|
|
512
|
+
if (acc !== undefined && acc.key !== key) {
|
|
513
|
+
// One attempt id is expected to map to one key. If it does not, fold what was gathered for the
|
|
514
|
+
// old key and start a fresh accumulator for this one (it must not stay in `closed`).
|
|
515
|
+
closeInternal(step.attemptID, false);
|
|
516
|
+
acc = undefined;
|
|
517
|
+
}
|
|
518
|
+
const usd = stepUSD(step.cost, step.pricing);
|
|
519
|
+
const t = clockNow();
|
|
520
|
+
const base: OpenAttempt = acc ?? {
|
|
521
|
+
key,
|
|
522
|
+
attemptID: step.attemptID,
|
|
523
|
+
steps: 0,
|
|
524
|
+
usd: 0,
|
|
525
|
+
usdKnown: true,
|
|
526
|
+
tokens: emptyTokenSample(),
|
|
527
|
+
finalOutput: null,
|
|
528
|
+
lastStepAt: t,
|
|
529
|
+
};
|
|
530
|
+
const tokens = cleanTokenSample(step.tokens);
|
|
531
|
+
const next: OpenAttempt = {
|
|
532
|
+
key: base.key,
|
|
533
|
+
attemptID: base.attemptID,
|
|
534
|
+
steps: base.steps + 1,
|
|
535
|
+
usd: base.usd + (usd ?? 0),
|
|
536
|
+
usdKnown: base.usdKnown && usd !== null,
|
|
537
|
+
tokens: addTokens(base.tokens, tokens),
|
|
538
|
+
finalOutput: step.final ? tokens.output : base.finalOutput,
|
|
539
|
+
lastStepAt: t,
|
|
540
|
+
};
|
|
541
|
+
open.delete(step.attemptID);
|
|
542
|
+
if (step.final) {
|
|
543
|
+
fold(next);
|
|
544
|
+
markClosed(step.attemptID);
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
open.set(step.attemptID, next);
|
|
548
|
+
if (open.size > maxOpen) {
|
|
549
|
+
const oldest = open.keys().next();
|
|
550
|
+
if (oldest.done !== true) closeInternal(oldest.value, true);
|
|
551
|
+
}
|
|
552
|
+
},
|
|
553
|
+
|
|
554
|
+
closeAttempt(attemptID: string): void {
|
|
555
|
+
closeInternal(attemptID, true);
|
|
556
|
+
},
|
|
557
|
+
|
|
558
|
+
sweepAttempts(maxIdleMs: number = DEFAULT_MAX_IDLE_MS): number {
|
|
559
|
+
const t = clockNow();
|
|
560
|
+
const idle: string[] = [];
|
|
561
|
+
for (const [id, attempt] of open) {
|
|
562
|
+
const age = t - attempt.lastStepAt;
|
|
563
|
+
if (Number.isFinite(age) && age >= maxIdleMs) idle.push(id);
|
|
564
|
+
}
|
|
565
|
+
for (const id of idle) closeInternal(id, true);
|
|
566
|
+
return idle.length;
|
|
567
|
+
},
|
|
568
|
+
|
|
569
|
+
posterior(key: OutcomeKey, prior: BetaPrior = SAME_RANK_PRIOR) {
|
|
570
|
+
const t = clockNow();
|
|
571
|
+
const entry = entries.get(key);
|
|
572
|
+
if (entry !== undefined && entry.beta.updatedAt > t + DAY_MS) {
|
|
573
|
+
// QA-1.3-7: the evidence is stamped more than a day after "now" (a clock that was ahead when it was
|
|
574
|
+
// written, since corrected). Re-stamp it *in the store*: a pure read would leave it frozen until the
|
|
575
|
+
// wall clock catches up. The counts are untouched, so nothing inflates; the change is persisted state.
|
|
576
|
+
entry.beta = { alpha: entry.beta.alpha, beta: entry.beta.beta, updatedAt: t };
|
|
577
|
+
revision += 1;
|
|
578
|
+
}
|
|
579
|
+
return posteriorOf(entry?.beta, prior, t, tuning);
|
|
580
|
+
},
|
|
581
|
+
|
|
582
|
+
cost(key: OutcomeKey): CostStats {
|
|
583
|
+
return entries.get(key)?.cost ?? EMPTY_COST;
|
|
584
|
+
},
|
|
585
|
+
|
|
586
|
+
classTokenProfile(cls: string): TokenMeans | null {
|
|
587
|
+
let n = 0;
|
|
588
|
+
let input = 0;
|
|
589
|
+
let output = 0;
|
|
590
|
+
let reasoning = 0;
|
|
591
|
+
let cacheRead = 0;
|
|
592
|
+
let cacheWrite = 0;
|
|
593
|
+
for (const entry of entries.values()) {
|
|
594
|
+
const t = entry.cost.tokens;
|
|
595
|
+
if (entry.cls !== cls || t.n === 0) continue;
|
|
596
|
+
n += t.n;
|
|
597
|
+
input += t.input * t.n;
|
|
598
|
+
output += t.output * t.n;
|
|
599
|
+
reasoning += t.reasoning * t.n;
|
|
600
|
+
cacheRead += t.cacheRead * t.n;
|
|
601
|
+
cacheWrite += t.cacheWrite * t.n;
|
|
602
|
+
}
|
|
603
|
+
if (n === 0) return null;
|
|
604
|
+
return {
|
|
605
|
+
n,
|
|
606
|
+
input: input / n,
|
|
607
|
+
output: output / n,
|
|
608
|
+
reasoning: reasoning / n,
|
|
609
|
+
cacheRead: cacheRead / n,
|
|
610
|
+
cacheWrite: cacheWrite / n,
|
|
611
|
+
};
|
|
612
|
+
},
|
|
613
|
+
|
|
614
|
+
keys(): OutcomeKey[] {
|
|
615
|
+
return [...entries.keys()].sort(compareCodeUnits);
|
|
616
|
+
},
|
|
617
|
+
|
|
618
|
+
snapshot(): OutcomeSnapshot {
|
|
619
|
+
const out: Record<string, OutcomeEntrySnapshot> = {};
|
|
620
|
+
for (const key of store.keys()) {
|
|
621
|
+
const entry = entries.get(key);
|
|
622
|
+
if (entry) out[key] = entrySnapshot(entry);
|
|
623
|
+
}
|
|
624
|
+
return { version: OUTCOMES_SCHEMA_VERSION, entries: out };
|
|
625
|
+
},
|
|
626
|
+
|
|
627
|
+
fromSnapshot(snapshot: OutcomeSnapshot, opts?: { readonly mode?: "replace" | "merge" }): SnapshotLoadReport {
|
|
628
|
+
const mode = opts?.mode ?? "replace";
|
|
629
|
+
const source: Record<string, unknown> = isRec(snapshot?.entries) ? snapshot.entries : {};
|
|
630
|
+
const accepted = new Map<OutcomeKey, Entry>();
|
|
631
|
+
let dropped = 0;
|
|
632
|
+
for (const [key, value] of Object.entries(source)) {
|
|
633
|
+
const entry = readEntry(key, value);
|
|
634
|
+
if (entry === null) dropped += 1;
|
|
635
|
+
else accepted.set(key as OutcomeKey, entry);
|
|
636
|
+
}
|
|
637
|
+
const hadEntries = entries.size > 0;
|
|
638
|
+
if (mode === "replace") entries.clear();
|
|
639
|
+
const t = clockNow();
|
|
640
|
+
for (const [key, disk] of accepted) absorb(key, disk, t);
|
|
641
|
+
if (accepted.size > 0 || (mode === "replace" && hadEntries)) revision += 1;
|
|
642
|
+
return { accepted: accepted.size, dropped };
|
|
643
|
+
},
|
|
644
|
+
|
|
645
|
+
mergeForeign(disk: OutcomeSnapshot, baseline: OutcomeSnapshot): SnapshotLoadReport {
|
|
646
|
+
const diskEntries: Record<string, unknown> = isRec(disk?.entries) ? disk.entries : {};
|
|
647
|
+
const baseEntries: Record<string, unknown> = isRec(baseline?.entries) ? baseline.entries : {};
|
|
648
|
+
const t = clockNow();
|
|
649
|
+
let accepted = 0;
|
|
650
|
+
let dropped = 0;
|
|
651
|
+
for (const [key, value] of Object.entries(diskEntries)) {
|
|
652
|
+
const current = readEntry(key, value);
|
|
653
|
+
if (current === null) {
|
|
654
|
+
dropped += 1;
|
|
655
|
+
continue;
|
|
656
|
+
}
|
|
657
|
+
const base = key in baseEntries ? readEntry(key, baseEntries[key]) : null;
|
|
658
|
+
if (base === null || !descendsFrom(current, base)) {
|
|
659
|
+
absorb(key as OutcomeKey, current, t); // new key, or a new lineage (QA-1.3-16): taken whole
|
|
660
|
+
} else if (grewSince(current, base)) {
|
|
661
|
+
entries.set(key as OutcomeKey, mergeDescendant(entries.get(key as OutcomeKey), current, base, t, tuning));
|
|
662
|
+
} else {
|
|
663
|
+
continue; // the other writer added nothing to this key
|
|
664
|
+
}
|
|
665
|
+
accepted += 1;
|
|
666
|
+
}
|
|
667
|
+
if (accepted > 0) revision += 1;
|
|
668
|
+
return { accepted, dropped };
|
|
669
|
+
},
|
|
670
|
+
};
|
|
671
|
+
|
|
672
|
+
return store;
|
|
673
|
+
}
|