opencode-model-router 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +35 -3
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +4 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +118 -31
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +484 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/index.ts +486 -38
  13. package/src/router/build-info.ts +151 -0
  14. package/src/router/config.ts +1365 -19
  15. package/src/router/protocol.ts +47 -0
  16. package/src/router/sessions.ts +441 -9
  17. package/src/routing/advisor/findings.ts +706 -0
  18. package/src/routing/advisor/index.ts +606 -0
  19. package/src/routing/classify/backends/host.ts +163 -0
  20. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  21. package/src/routing/classify/backends/shared.ts +741 -0
  22. package/src/routing/classify/backends/typesafe.ts +315 -0
  23. package/src/routing/classify/fences.ts +96 -0
  24. package/src/routing/classify/index.ts +576 -0
  25. package/src/routing/classify/route-line.ts +298 -0
  26. package/src/routing/classify/rules.ts +607 -0
  27. package/src/routing/classify/scrub.ts +214 -0
  28. package/src/routing/classify/state.ts +148 -0
  29. package/src/routing/classify/text.ts +20 -0
  30. package/src/routing/classify/types.ts +1280 -0
  31. package/src/routing/commands/annotate-plan.ts +652 -0
  32. package/src/routing/commands/stats.ts +131 -0
  33. package/src/routing/commands/v1-roles.ts +64 -0
  34. package/src/routing/engine/index.ts +32 -0
  35. package/src/routing/engine/kernel.ts +597 -0
  36. package/src/routing/engine/ladders.ts +561 -0
  37. package/src/routing/engine/plan.ts +404 -0
  38. package/src/routing/engine/protocol-line.ts +133 -0
  39. package/src/routing/engine/simulate.ts +167 -0
  40. package/src/routing/engine/types.ts +270 -0
  41. package/src/routing/file-lock.ts +53 -0
  42. package/src/routing/outcomes/beta.ts +141 -0
  43. package/src/routing/outcomes/cost.ts +313 -0
  44. package/src/routing/outcomes/index.ts +172 -0
  45. package/src/routing/outcomes/ingest.ts +812 -0
  46. package/src/routing/outcomes/persist.ts +1058 -0
  47. package/src/routing/outcomes/stats.ts +602 -0
  48. package/src/routing/outcomes/store.ts +653 -0
  49. package/src/routing/outcomes/types.ts +954 -0
  50. package/src/routing/wire/dispatch.ts +799 -0
  51. package/src/routing/wire/hint.ts +208 -0
  52. package/src/routing/wire/host-info.ts +256 -0
  53. package/src/routing/wire/runtime.ts +259 -0
  54. package/src/v2.ts +15 -1
@@ -0,0 +1,602 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Routing statistics (1.3.3, D18): pure `summarize`, deterministic `renderMarkdown`, argument parsing
3
+ // and the CLI driver behind `npm run routing:stats` and `/router stats` (2.4).
4
+ //
5
+ // Design: docs/qa/cost-aware-routing/phase-1.3.md "Design (1.3.1)" §7.
6
+ // No I/O of its own: `runStatsCli` gets every read and write through `StatsCliIO`. Runnable under Node
7
+ // type stripping (type-only imports use `import type`).
8
+ // ---------------------------------------------------------------------------
9
+
10
+ import type {
11
+ ClassStatsRow,
12
+ CostUnit,
13
+ DecisionRow,
14
+ KeyStatsRow,
15
+ LogRow,
16
+ OutcomeKey,
17
+ OutcomeStoreView,
18
+ RatioCell,
19
+ RefusalRow,
20
+ ResumeFreshRow,
21
+ SavingsRow,
22
+ StatsCliIO,
23
+ StatsTable,
24
+ StatsWindow,
25
+ VerdictRow,
26
+ } from "./types";
27
+ import { DECISIONS_MAX_GENERATIONS, FLOOR_LIFT_REASON, LADDER_STEP_KINDS, STATS_EXIT } from "./types";
28
+ import { createOutcomeStore } from "./store";
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // summarize
32
+ // ---------------------------------------------------------------------------
33
+
34
+ function ratio(num: number, den: number): RatioCell {
35
+ return { num, den, rate: den === 0 ? null : num / den };
36
+ }
37
+
38
+ function compareCodeUnits(a: string, b: string): number {
39
+ return a < b ? -1 : a > b ? 1 : 0;
40
+ }
41
+
42
+ function finiteOrNull(x: number | null): number | null {
43
+ return x !== null && Number.isFinite(x) ? x : null;
44
+ }
45
+
46
+ function isoOrNull(ms: number | null): string | null {
47
+ return ms === null ? null : new Date(ms).toISOString();
48
+ }
49
+
50
+ /** QA-2.2-7: a row the 2.2 adapter lifted to `floorTier` (policy, not an engine decision on evidence). */
51
+ function isFloorLift(row: DecisionRow): boolean {
52
+ return row.reason.startsWith(FLOOR_LIFT_REASON);
53
+ }
54
+
55
+ /** QA-INT-2: a first attempt the delegate runner's recorder wrote (its decision ids start with `ladder-`; it has no `best`). */
56
+ function isDelegateAttempt(row: DecisionRow): boolean {
57
+ return row.decisionID.startsWith("ladder-");
58
+ }
59
+
60
+ /**
61
+ * The key a decision row actually dispatched to: `best` when `enforce` switched, else `chosen`. A `switched` row of `shadow`
62
+ * or `advise` is a would-switch (2.2): nothing was dispatched to `best`, so it must not count as a dispatch there.
63
+ */
64
+ function dispatchedKey(row: DecisionRow): OutcomeKey {
65
+ return row.mode === "enforce" && row.switched && row.best !== null ? row.best.key : row.chosen.key;
66
+ }
67
+
68
+ interface KeyAcc {
69
+ dispatches: number;
70
+ attempts: number;
71
+ pass: number;
72
+ fail: number;
73
+ unverifiable: number;
74
+ falseRefusals: number;
75
+ }
76
+
77
+ /**
78
+ * Aggregate the decision log (and, for the cost column, the store) over `since ≤ ts < until`.
79
+ * `since` is inclusive and `until` exclusive so consecutive periods never double-count. Counts and
80
+ * rates come only from the windowed rows; the `switched.failed` join looks at all rows, because the
81
+ * verdict of a switched dispatch may land after `until`. Every rate is a {@link RatioCell}: an empty
82
+ * denominator is `null`, never NaN.
83
+ */
84
+ export function summarize(store: OutcomeStoreView | null, rows: readonly LogRow[], window: StatsWindow): StatsTable {
85
+ // An append may reach disk before reporting failure; retrying that batch must not inflate rates.
86
+ // Decisions keep their first row. Signals dedupe per outcome, before windowing and joins:
87
+ // a later decisive verdict must still replace an earlier unverifiable verdict (R2-9).
88
+ const seen = new Set<string>();
89
+ rows = rows.filter((row) => {
90
+ const id = JSON.stringify(row.kind === "decision"
91
+ ? [row.kind, row.decisionID]
92
+ : [row.kind, row.decisionID, row.attemptID, row.kind === "verdict" ? row.verdict : row.overrides ?? null]);
93
+ if (seen.has(id)) return false;
94
+ seen.add(id);
95
+ return true;
96
+ });
97
+ const since = finiteOrNull(window.since);
98
+ const until = finiteOrNull(window.until);
99
+ const inWindow = (row: LogRow): boolean => {
100
+ const t = Date.parse(row.ts);
101
+ return Number.isFinite(t) && (since === null || t >= since) && (until === null || t < until);
102
+ };
103
+
104
+ const decisions: DecisionRow[] = [];
105
+ const verdicts: VerdictRow[] = [];
106
+ const refusals: RefusalRow[] = [];
107
+ for (const row of rows) {
108
+ if (!inWindow(row)) continue;
109
+ if (row.kind === "decision") decisions.push(row);
110
+ else if (row.kind === "verdict") verdicts.push(row);
111
+ else refusals.push(row);
112
+ }
113
+ const dispatchRows = decisions.filter((r) => r.step === "dispatch");
114
+ // QA-2.4-R2-3 / A30: a dispatch that resumes an existing child (`task_id`/`sessionID`) is never switched by the engine, so it says nothing
115
+ // about routing: every routing metric below (class and key dispatch counts, agreement, switched, savings, the evidence gate) is over the
116
+ // FRESH dispatches only. Resumes are reported on their own line (`orchestratorResumes`).
117
+ const freshRows = dispatchRows.filter((r) => !r.resume);
118
+ const nonPinned = freshRows.filter((r) => !r.pinned);
119
+
120
+ // By class.
121
+ const classCounts = new Map<string, number>();
122
+ for (const r of freshRows) classCounts.set(r.facts.class, (classCounts.get(r.facts.class) ?? 0) + 1);
123
+ const byClass: ClassStatsRow[] = [...classCounts.keys()]
124
+ .sort(compareCodeUnits)
125
+ .map((cls) => ({ class: cls, dispatches: classCounts.get(cls) ?? 0 }));
126
+
127
+ // By key.
128
+ const accs = new Map<OutcomeKey, KeyAcc>();
129
+ const slot = (key: OutcomeKey): KeyAcc => {
130
+ let acc = accs.get(key);
131
+ if (acc === undefined) {
132
+ acc = { dispatches: 0, attempts: 0, pass: 0, fail: 0, unverifiable: 0, falseRefusals: 0 };
133
+ accs.set(key, acc);
134
+ }
135
+ return acc;
136
+ };
137
+ for (const r of decisions) {
138
+ const acc = slot(dispatchedKey(r));
139
+ acc.attempts += 1;
140
+ if (r.step === "dispatch" && !r.resume) acc.dispatches += 1;
141
+ }
142
+ // A refusal belongs to this window's refusal rate only when its decision row is in the window too
143
+ // (QA-1.3-13); otherwise `falseRefusals / attempts` could pass 100 %. Refusals without a decision id stay.
144
+ const windowDecisionIDs = new Set(decisions.map((r) => r.decisionID));
145
+ // QA-2.1-3 / R2-2: a refusal that records `overrides: "pass"` turned a `pass` of the same attempt into a failure,
146
+ // exactly as the store does (pass → fail, `falseRefusals` + 1). The conversion set comes from every row handed in,
147
+ // not only the window: the pass row may sit in an earlier window or in a rotated log. A converted attempt's pass is
148
+ // never counted as a pass; its failure is counted once, with the refusal, whichever window each row is in. Only the
149
+ // explicit marker counts: a refusal without it (another attempt, or after a fail) is a refusal and nothing else.
150
+ const converted = new Set<string>();
151
+ for (const row of rows) if (row.kind === "refusal" && row.overrides === "pass") converted.add(row.attemptID);
152
+ const decisiveAttempts = new Set(verdicts.filter((v) => v.verdict !== "unverifiable").map((v) => v.attemptID));
153
+ const effectiveVerdicts: Array<Pick<VerdictRow, "key" | "verdict" | "step" | "attemptID">> = [];
154
+ const unverifiableSeen = new Set<string>();
155
+ for (const v of verdicts) {
156
+ if (v.verdict === "pass" && converted.has(v.attemptID)) continue;
157
+ if (v.verdict === "unverifiable") {
158
+ // R2-9: a later pass/fail row for the attempt replaces an earlier unverifiable one; one unverifiable per attempt.
159
+ if (decisiveAttempts.has(v.attemptID) || unverifiableSeen.has(v.attemptID)) continue;
160
+ unverifiableSeen.add(v.attemptID);
161
+ }
162
+ effectiveVerdicts.push(v);
163
+ }
164
+ const countedRefusals: RefusalRow[] = [];
165
+ const failedByRefusal = new Set<string>();
166
+ for (const r of refusals) {
167
+ if (r.decisionID !== null && !windowDecisionIDs.has(r.decisionID)) continue;
168
+ countedRefusals.push(r);
169
+ slot(r.key).falseRefusals += 1;
170
+ if (r.overrides === "pass" && !failedByRefusal.has(r.attemptID)) {
171
+ failedByRefusal.add(r.attemptID);
172
+ effectiveVerdicts.push({ key: r.key, verdict: "fail", step: r.step, attemptID: r.attemptID });
173
+ }
174
+ }
175
+ for (const v of effectiveVerdicts) slot(v.key)[v.verdict] += 1;
176
+ const byKey: KeyStatsRow[] = [...accs.keys()].sort(compareCodeUnits).map((key) => {
177
+ const acc = accs.get(key) ?? { dispatches: 0, attempts: 0, pass: 0, fail: 0, unverifiable: 0, falseRefusals: 0 };
178
+ const measured = store === null ? null : store.cost(key).measuredUSD;
179
+ return {
180
+ key,
181
+ dispatches: acc.dispatches,
182
+ attempts: acc.attempts,
183
+ pass: acc.pass,
184
+ fail: acc.fail,
185
+ unverifiable: acc.unverifiable,
186
+ passRate: ratio(acc.pass, acc.pass + acc.fail),
187
+ falseRefusals: acc.falseRefusals,
188
+ refusalRate: ratio(Math.min(acc.falseRefusals, acc.attempts), acc.attempts),
189
+ measuredUSD: measured !== null && measured.n > 0 ? { mean: measured.mean, n: measured.n } : null,
190
+ };
191
+ });
192
+
193
+ // Agreement: best == chosen over non-pinned dispatches that have a best.
194
+ // QA-INT-2 / QA-2.2-R2-3: the rows the kernel decided: a `best` exists and the dispatch is not a floor lift (policy, whose `best` is the
195
+ // lifted tier, not an argmin). Delegate first attempts (the runner's recorder rows, `best: null`) and lifts are counted on their own lines.
196
+ const routedRows = nonPinned.filter((r) => r.best !== null && !isFloorLift(r));
197
+ const agreement = ratio(routedRows.filter((r) => r.best !== null && r.best.key === r.chosen.key).length, routedRows.length);
198
+
199
+ // Switched, and how many of those ended in a fail verdict or a false refusal (any window).
200
+ const failedDecisionIDs = new Set<string>();
201
+ const decidedDecisionIDs = new Set<string>(); // a pass/fail verdict or a refusal exists: the outcome is known
202
+ for (const row of rows) {
203
+ if (row.kind === "verdict" && row.decisionID !== null) {
204
+ if (row.verdict === "fail") failedDecisionIDs.add(row.decisionID);
205
+ if (row.verdict !== "unverifiable") decidedDecisionIDs.add(row.decisionID);
206
+ } else if (row.kind === "refusal" && row.decisionID !== null) {
207
+ failedDecisionIDs.add(row.decisionID);
208
+ decidedDecisionIDs.add(row.decisionID);
209
+ }
210
+ }
211
+ const switchedRows = routedRows.filter((r) => r.switched);
212
+ // QA-2.2-7/8: D17 asks whether a dispatch the engine moved ON ITS OWN EVIDENCE failed. A shadow/advise row is a would-switch (nothing
213
+ // moved) and a floor lift is policy, so neither can be a failed switch.
214
+ const enforcedSwitches = switchedRows.filter((r) => r.mode === "enforce");
215
+
216
+ // Savings: Σ C(chosen) − C(best) per unit, never summed across units. Summed in ascending order so
217
+ // the total does not depend on the row order.
218
+ const terms = new Map<CostUnit, number[]>();
219
+ for (const r of routedRows) {
220
+ if (r.best === null) continue;
221
+ const chosenCost = r.costs[r.chosen.key];
222
+ const bestCost = r.costs[r.best.key];
223
+ if (typeof chosenCost !== "number" || typeof bestCost !== "number") continue;
224
+ if (!Number.isFinite(chosenCost) || !Number.isFinite(bestCost)) continue;
225
+ const list = terms.get(r.unit) ?? [];
226
+ list.push(chosenCost - bestCost);
227
+ terms.set(r.unit, list);
228
+ }
229
+ const savings: SavingsRow[] = [...terms.keys()].sort(compareCodeUnits).map((unit) => {
230
+ const list = [...(terms.get(unit) ?? [])].sort((a, b) => a - b);
231
+ return { unit, total: list.reduce((sum, x) => sum + x, 0), rows: list.length };
232
+ });
233
+
234
+ // Variant steps.
235
+ const variantVerdicts = effectiveVerdicts.filter((v) => v.step === "variant");
236
+ const variantPass = variantVerdicts.filter((v) => v.verdict === "pass").length;
237
+ // R2-3: a refusal that was an attempt's first terminal signal is a variant failure in the store (`variantFail`), though it has
238
+ // no verdict row; one after a verdict, or a conversion (already a synthetic fail above), adds nothing.
239
+ const decidedAttempts = new Set(effectiveVerdicts.filter((v) => v.verdict !== "unverifiable").map((v) => v.attemptID));
240
+ let variantRefusalFails = 0;
241
+ for (const r of countedRefusals) {
242
+ if (r.step !== "variant" || decidedAttempts.has(r.attemptID)) continue;
243
+ decidedAttempts.add(r.attemptID);
244
+ variantRefusalFails += 1;
245
+ }
246
+ const variantFail = variantVerdicts.filter((v) => v.verdict === "fail").length + variantRefusalFails;
247
+
248
+ const resumeVsFresh: ResumeFreshRow[] = LADDER_STEP_KINDS.map((step) => {
249
+ const ofStep = decisions.filter((r) => r.step === step);
250
+ const resume = ofStep.filter((r) => r.resume).length;
251
+ return { step, resume, fresh: ofStep.length - resume };
252
+ });
253
+
254
+ // 2.4: the orchestrator's own resumes (2.2 `task_id`/`sessionID`) and the A27 evidence gate, over the routed dispatch rows.
255
+ const routedDispatches = dispatchRows.filter((r) => !isDelegateAttempt(r)); // fresh and resumed: the resume line's denominator
256
+ const routedFresh = routedDispatches.filter((r) => !r.resume);
257
+ const argminCounts = new Map<OutcomeKey, number>();
258
+ for (const r of routedFresh) {
259
+ const key = r.trace?.argmin?.key;
260
+ if (key !== undefined) argminCounts.set(key, (argminCounts.get(key) ?? 0) + 1);
261
+ }
262
+ const argmin = [...argminCounts.entries()]
263
+ .sort((a, b) => b[1] - a[1] || compareCodeUnits(a[0], b[0]))
264
+ .map(([key, count]) => ({ key, count }));
265
+
266
+ // A34 (QA-G-B8): D9 never-down audit. High-risk rows decided without detection that record both capability ranks; `below` = those that
267
+ // ran below the pick's capability rank. Rows written before A34 (no `detection`/`capability`) are tolerated and left out.
268
+ const isRank = (x: unknown): x is number => typeof x === "number" && Number.isFinite(x);
269
+ const audited: Array<{ readonly pick: number; readonly dispatched: number }> = [];
270
+ for (const r of routedDispatches) {
271
+ const capability = r.capability;
272
+ if (r.facts.risk !== "high" || r.detection?.effective !== "none" || capability === undefined) continue;
273
+ if (isRank(capability.pick) && isRank(capability.dispatched)) audited.push({ pick: capability.pick, dispatched: capability.dispatched });
274
+ }
275
+ const neverDownBelow = audited.filter((ranks) => ranks.dispatched < ranks.pick).length;
276
+
277
+ return {
278
+ version: 1,
279
+ window: { since: isoOrNull(since), until: isoOrNull(until) },
280
+ dispatches: dispatchRows.length,
281
+ routed: dispatchRows.filter((r) => !isDelegateAttempt(r)).length,
282
+ delegateFirstAttempts: dispatchRows.filter(isDelegateAttempt).length,
283
+ floorLifts: dispatchRows.filter(isFloorLift).length,
284
+ pinned: dispatchRows.filter((r) => r.pinned).length,
285
+ byClass,
286
+ byKey,
287
+ agreement,
288
+ switched: {
289
+ count: switchedRows.length,
290
+ share: ratio(switchedRows.length, routedRows.length),
291
+ enforced: enforcedSwitches.length,
292
+ failed: enforcedSwitches.filter((r) => failedDecisionIDs.has(r.decisionID)).length,
293
+ verified: enforcedSwitches.filter((r) => decidedDecisionIDs.has(r.decisionID)).length,
294
+ },
295
+ savings,
296
+ variantSteps: {
297
+ taken: decisions.filter((r) => r.step === "variant").length,
298
+ passRate: ratio(variantPass, variantPass + variantFail),
299
+ },
300
+ resumeVsFresh,
301
+ orchestratorResumes: { resumed: routedDispatches.filter((r) => r.resume).length, total: routedDispatches.length },
302
+ gate: { keptEvidence: routedFresh.filter((r) => r.reason.startsWith("kept:evidence")).length, argmin },
303
+ neverDown: { below: neverDownBelow, recorded: audited.length },
304
+ };
305
+ }
306
+
307
+ // ---------------------------------------------------------------------------
308
+ // renderMarkdown
309
+ // ---------------------------------------------------------------------------
310
+
311
+ /** D17 / DF5: apply to the enforce-period summary; any failed enforced switch returns to advise. */
312
+ export function d17Mode(summary: Pick<StatsTable, "switched">): "enforce" | "advise" | "n/a (0 enforced switches)" {
313
+ if (summary.switched.enforced === 0) return "n/a (0 enforced switches)";
314
+ return summary.switched.failed === 0 ? "enforce" : "advise";
315
+ }
316
+
317
+ /** `toFixed` without `-0.00`. */
318
+ function fix(x: number, digits: number): string {
319
+ return (Math.abs(x) < 0.5 * 10 ** -digits ? 0 : x).toFixed(digits);
320
+ }
321
+
322
+ function fmtRatio(cell: RatioCell): string {
323
+ return cell.den === 0 ? "n/a" : `${cell.num}/${cell.den} (${((100 * cell.num) / cell.den).toFixed(1)}%)`;
324
+ }
325
+
326
+ function fmtPercent(cell: RatioCell): string {
327
+ return cell.rate === null ? "n/a" : `${(100 * cell.rate).toFixed(1)}%`;
328
+ }
329
+
330
+ function fmtUSD(x: number): string {
331
+ return `$${fix(x, 4)}`;
332
+ }
333
+
334
+ function fmtRatioAmount(x: number): string {
335
+ return fix(x, 2);
336
+ }
337
+
338
+ /** Keys contain `|`; a cell must neither break the table nor span lines. */
339
+ function cell(text: string): string {
340
+ return text.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
341
+ }
342
+
343
+ /**
344
+ * Markdown report: `\n` only, blocks separated by exactly one blank line, exactly one trailing `\n`.
345
+ * Deterministic: the same table always renders the same bytes.
346
+ */
347
+ export function renderMarkdown(table: StatsTable): string {
348
+ const metrics = [
349
+ "| Metric | Value |",
350
+ "|---|---|",
351
+ `| Dispatches | ${table.dispatches} |`,
352
+ `| Routed dispatches | ${table.routed} |`,
353
+ `| Delegate first attempts | ${table.delegateFirstAttempts} |`,
354
+ `| Floor lifts | ${table.floorLifts} |`,
355
+ `| Pinned | ${table.pinned} |`,
356
+ `| Agreement (best == chosen, non-pinned) | ${fmtRatio(table.agreement)} |`,
357
+ `| Switched | ${table.switched.count} of ${table.switched.share.den} non-pinned routed (${fmtPercent(table.switched.share)}); enforced ${table.switched.enforced}; failed ${table.switched.failed} (verified ${table.switched.verified} of ${table.switched.enforced} enforced) |`,
358
+ `| D17 mode (use the DF4→DF5 enforce-period window) | ${d17Mode(table)} |`,
359
+ ...(table.savings.length === 0
360
+ ? ["| Estimated savings | n/a |"]
361
+ : table.savings.map(
362
+ (s) =>
363
+ `| Estimated savings (${s.unit}) | ${s.unit === "usd" ? fmtUSD(s.total) : fmtRatioAmount(s.total)} over ${s.rows} rows |`,
364
+ )),
365
+ `| Variant steps | ${table.variantSteps.taken} taken; pass ${fmtRatio(table.variantSteps.passRate)} |`,
366
+ // 2.4: not ladder decisions, so they are not rows of the D11 table below (QA-2.3-7).
367
+ `| Orchestrator resumes (task_id / sessionID; not a ladder step, never switched, outside every routing metric) | ${table.orchestratorResumes.resumed} of ${table.orchestratorResumes.total} routed dispatches |`,
368
+ `| Kept for lack of evidence (A27, fresh dispatches) | ${table.gate.keptEvidence} of ${table.orchestratorResumes.total - table.orchestratorResumes.resumed} fresh routed dispatches |`,
369
+ // A34 (QA-G-B8): the never-down audit. `n/a` when no row of the window records detection and both capability ranks.
370
+ `| High-risk d=none rows that ran below the pick's capability rank (D9 never-down, A34; expected 0) | ${
371
+ table.neverDown.recorded === 0 ? "n/a (no row records detection and capability)" : `${table.neverDown.below} of ${table.neverDown.recorded} recorded`
372
+ } |`,
373
+ ];
374
+
375
+ const classTable =
376
+ table.byClass.length === 0
377
+ ? "_none_"
378
+ : ["| Class | Dispatches |", "|---|---|", ...table.byClass.map((r) => `| ${cell(r.class)} | ${r.dispatches} |`)].join("\n");
379
+
380
+ const keyTable =
381
+ table.byKey.length === 0
382
+ ? "_none_"
383
+ : [
384
+ "| Key | Dispatches | Attempts | Pass | Fail | Unverifiable | Pass rate | False refusals | Refusal rate | USD/attempt (lifetime) |",
385
+ "|---|---|---|---|---|---|---|---|---|---|",
386
+ ...table.byKey.map(
387
+ (r) =>
388
+ `| ${cell(r.key)} | ${r.dispatches} | ${r.attempts} | ${r.pass} | ${r.fail} | ${r.unverifiable} | ${fmtRatio(r.passRate)} | ${r.falseRefusals} | ${fmtRatio(r.refusalRate)} | ${
389
+ r.measuredUSD === null ? "n/a" : `${fmtUSD(r.measuredUSD.mean)} (n=${r.measuredUSD.n})`
390
+ } |`,
391
+ ),
392
+ ].join("\n");
393
+
394
+ // QA-2.3-7: the rendered table is the ladder's. `dispatch` counts first dispatches (always fresh for `delegate`) and the
395
+ // `sessionID`/`task_id` resumes of dispatched subagents, neither of which is a D11 ladder decision, so its row is left out
396
+ // here; `resumeVsFresh` itself (and `--json`) keeps it, so those numbers stay countable.
397
+ const resumeTable = [
398
+ "| Step | Resume | Fresh |",
399
+ "|---|---|---|",
400
+ ...table.resumeVsFresh.filter((r) => r.step !== "dispatch").map((r) => `| ${r.step} | ${r.resume} | ${r.fresh} |`),
401
+ ].join("\n");
402
+
403
+ // A27 / DF3: the cheapest option the evidence filter held back (`trace.argmin`), i.e. where the gate stops the engine.
404
+ const argminTable =
405
+ table.gate.argmin.length === 0
406
+ ? "_none_"
407
+ : ["| Cheapest key held back | Rows |", "|---|---|", ...table.gate.argmin.map((r) => `| ${cell(r.key)} | ${r.count} |`)].join("\n");
408
+
409
+ const blocks = [
410
+ "## Routing stats",
411
+ `Window: ${table.window.since ?? "start"} → ${table.window.until ?? "open"}`,
412
+ metrics.join("\n"),
413
+ "### By class",
414
+ classTable,
415
+ "### By key",
416
+ keyTable,
417
+ "### Gated by evidence (trace.argmin)",
418
+ argminTable,
419
+ "### Resume vs fresh",
420
+ resumeTable,
421
+ // QA-2.1-10: rows are only recorded under a trusted class, so the rates below the metrics are not over every dispatch.
422
+ "_Verdict and false-refusal rates cover trusted classes only: dispatches whose class confidence reached `routing.minClassConfidence` and whose class is not `unknown`. Other dispatches have a decision row but no verdict or refusal rows, so Dispatches can exceed Pass + Fail + Unverifiable by design._",
423
+ ];
424
+ return blocks.join("\n\n") + "\n";
425
+ }
426
+
427
+ // ---------------------------------------------------------------------------
428
+ // Arguments and CLI
429
+ // ---------------------------------------------------------------------------
430
+
431
+ export interface StatsArgs {
432
+ readonly since: number | null;
433
+ readonly until: number | null;
434
+ readonly json: boolean;
435
+ readonly dir: string | null;
436
+ readonly help: boolean;
437
+ }
438
+
439
+ export type ParseStatsResult =
440
+ | { readonly ok: true; readonly args: StatsArgs }
441
+ | { readonly ok: false; readonly error: string };
442
+
443
+ export const USAGE = [
444
+ "Usage: node scripts/routing-stats.ts [--since <ISO>] [--until <ISO>] [--json] [--dir <path>]",
445
+ " or: npm run routing:stats -- [--since <ISO>] [--until <ISO>] [--json] [--dir <path>]",
446
+ ` (PowerShell swallows a bare "--": write npm run routing:stats '--' --since <ISO>)`,
447
+ " --since <ISO> include rows with ts >= since (YYYY-MM-DD, or date-time with Z or an offset)",
448
+ " --until <ISO> include rows with ts < until",
449
+ " --json print the StatsTable as JSON",
450
+ " --dir <path> outcome directory, resolved like routing.outcomes.path: ~ is the home directory and a",
451
+ " relative path is taken under <os tmpdir>/opencode-model-router-trajectory",
452
+ " (default: <os tmpdir>/opencode-model-router-trajectory)",
453
+ "",
454
+ ].join("\n");
455
+
456
+ const ISO_RE = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,3})?)?(Z|[+-](\d{2}):(\d{2})))?$/;
457
+
458
+ function daysInMonth(year: number, month: number): number {
459
+ return new Date(Date.UTC(year, month, 0)).getUTCDate();
460
+ }
461
+
462
+ /** Epoch ms of an ISO date or zoned date-time, or an error text. A zone-less date-time is refused (it would be machine-dependent). */
463
+ function parseInstant(flag: string, value: string): { readonly ms: number } | { readonly error: string } {
464
+ const m = ISO_RE.exec(value);
465
+ if (m === null) {
466
+ return {
467
+ error: `invalid ${flag} value "${value}": expected YYYY-MM-DD or a date-time with Z or an offset (e.g. 2026-10-06T12:00:00Z)`,
468
+ };
469
+ }
470
+ const year = Number(m[1]);
471
+ const month = Number(m[2]);
472
+ const day = Number(m[3]);
473
+ const hour = m[4] === undefined ? 0 : Number(m[4]);
474
+ const minute = m[5] === undefined ? 0 : Number(m[5]);
475
+ const second = m[6] === undefined ? 0 : Number(m[6]);
476
+ const offsetHour = m[8] === undefined ? 0 : Number(m[8]);
477
+ const offsetMinute = m[9] === undefined ? 0 : Number(m[9]);
478
+ const calendarOk =
479
+ month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month) && hour <= 23 && minute <= 59 && second <= 59 && offsetHour <= 23 && offsetMinute <= 59;
480
+ const ms = calendarOk ? Date.parse(value) : Number.NaN;
481
+ if (!Number.isFinite(ms)) return { error: `invalid ${flag} value "${value}": not a real date` };
482
+ return { ms };
483
+ }
484
+
485
+ /** `--since <v>`/`--since=<v>` (also `--until`, `--dir`), `--json`, `--help`/`-h`. Repeats, unknown arguments and an empty window are errors. */
486
+ export function parseStatsArgs(argv: readonly string[]): ParseStatsResult {
487
+ let since: number | null = null;
488
+ let until: number | null = null;
489
+ let json = false;
490
+ let dir: string | null = null;
491
+ let help = false;
492
+ const seen = new Set<string>();
493
+
494
+ for (let i = 0; i < argv.length; i++) {
495
+ const arg = argv[i] as string;
496
+ const eq = arg.startsWith("--") ? arg.indexOf("=") : -1;
497
+ const rawName = eq > 0 ? arg.slice(0, eq) : arg;
498
+ const inline = eq > 0 ? arg.slice(eq + 1) : null;
499
+ const name = rawName === "-h" ? "--help" : rawName;
500
+
501
+ if (name === "--json" || name === "--help") {
502
+ if (inline !== null) return { ok: false, error: `${name} does not take a value` };
503
+ if (seen.has(name)) return { ok: false, error: `${name} given more than once` };
504
+ seen.add(name);
505
+ if (name === "--json") json = true;
506
+ else help = true;
507
+ continue;
508
+ }
509
+ if (name !== "--since" && name !== "--until" && name !== "--dir") return { ok: false, error: `unknown argument: ${arg}` };
510
+ if (seen.has(name)) return { ok: false, error: `${name} given more than once` };
511
+ seen.add(name);
512
+
513
+ let value: string | null = inline;
514
+ if (value === null) {
515
+ const next = argv[i + 1];
516
+ if (next !== undefined && !next.startsWith("--")) {
517
+ value = next;
518
+ i += 1;
519
+ }
520
+ }
521
+ if (value === null || value === "") return { ok: false, error: `${name} requires a value` };
522
+
523
+ if (name === "--dir") {
524
+ dir = value;
525
+ continue;
526
+ }
527
+ const parsed = parseInstant(name, value);
528
+ if ("error" in parsed) return { ok: false, error: parsed.error };
529
+ if (name === "--since") since = parsed.ms;
530
+ else until = parsed.ms;
531
+ }
532
+
533
+ if (since !== null && until !== null && since >= until) {
534
+ return { ok: false, error: "--since must be earlier than --until" };
535
+ }
536
+ return { ok: true, args: { since, until, json, dir, help } };
537
+ }
538
+
539
+ function messageOf(error: unknown): string {
540
+ return error instanceof Error ? error.message : String(error);
541
+ }
542
+
543
+ /**
544
+ * `routing:stats` driver. Read-only: loads without quarantine, cleanup or mkdir. Never throws:
545
+ * a usage error exits 2, a corrupt or too-new store exits 1 with a clear message, an unexpected error
546
+ * writes `routing-stats: <message>` and exits 1. A missing store is an empty table with exit 0.
547
+ */
548
+ export async function runStatsCli(argv: readonly string[], io: StatsCliIO): Promise<number> {
549
+ try {
550
+ const parsed = parseStatsArgs(argv);
551
+ if (!parsed.ok) {
552
+ io.stderr(`routing-stats: ${parsed.error}\n${USAGE}`);
553
+ return STATS_EXIT.usage;
554
+ }
555
+ const { args } = parsed;
556
+ if (args.help) {
557
+ io.stdout(USAGE);
558
+ return STATS_EXIT.ok;
559
+ }
560
+
561
+ const source = io.open(args.dir ?? io.defaultDir);
562
+ const loaded = await source.load({ quarantine: false });
563
+ if (loaded.status === "corrupt" || loaded.status === "unsupported-version") {
564
+ io.stderr(`routing-stats: corrupted outcome store: ${loaded.message ?? loaded.status}\n`);
565
+ return STATS_EXIT.corrupt;
566
+ }
567
+ if (loaded.dropped > 0) io.stderr(`routing-stats: warning: ${loaded.message ?? `${loaded.dropped} invalid store entries dropped`}\n`);
568
+
569
+ const store = createOutcomeStore();
570
+ if (loaded.status === "ok") store.fromSnapshot(loaded.snapshot);
571
+ const read = await source.readRows();
572
+ if (loaded.status === "missing" && read.files.length === 0) {
573
+ // Not an error (a fresh install has nothing yet), but a typo in --dir looks exactly like this (QA-1.3-5).
574
+ io.stderr(`routing-stats: no outcome data in ${source.dir}\n`);
575
+ }
576
+ if (read.skipped > 0) io.stderr(`routing-stats: skipped ${read.skipped} unreadable decision-log line(s)\n`);
577
+ if (
578
+ read.generations >= DECISIONS_MAX_GENERATIONS &&
579
+ read.oldestTs !== null &&
580
+ (args.since === null || args.since < Date.parse(read.oldestTs))
581
+ ) {
582
+ // Rotation prunes only beyond DECISIONS_MAX_GENERATIONS rotated files, so fewer than that means nothing has
583
+ // been dropped yet (QA-1.3-19). At the limit, history before the oldest retained row may be gone (QA-1.3-10).
584
+ io.stderr(
585
+ `routing-stats: warning: the decision log has rotated; its oldest retained row is ${read.oldestTs}, so ${
586
+ args.since === null ? "an unbounded" : "this"
587
+ } window may be incomplete\n`,
588
+ );
589
+ }
590
+
591
+ const table = summarize(store, read.rows, { since: args.since, until: args.until });
592
+ io.stdout(args.json ? JSON.stringify(table, null, 2) + "\n" : renderMarkdown(table));
593
+ return STATS_EXIT.ok;
594
+ } catch (error) {
595
+ try {
596
+ io.stderr(`routing-stats: ${messageOf(error)}\n`);
597
+ } catch {
598
+ return STATS_EXIT.corrupt;
599
+ }
600
+ return STATS_EXIT.corrupt;
601
+ }
602
+ }