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,873 @@
|
|
|
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
|
+
CostUnitRow,
|
|
14
|
+
DecisionRow,
|
|
15
|
+
KeyStatsRow,
|
|
16
|
+
LogRow,
|
|
17
|
+
MeanStat,
|
|
18
|
+
OutcomeKey,
|
|
19
|
+
OutcomeStoreView,
|
|
20
|
+
RatioCell,
|
|
21
|
+
RefusalRow,
|
|
22
|
+
ResumeFreshRow,
|
|
23
|
+
RoleStatsTable,
|
|
24
|
+
RoleTierStatsRow,
|
|
25
|
+
SavingsRow,
|
|
26
|
+
SignalKind,
|
|
27
|
+
SignalKindStats,
|
|
28
|
+
StatsCliIO,
|
|
29
|
+
StatsTable,
|
|
30
|
+
StatsWindow,
|
|
31
|
+
TokenMeans,
|
|
32
|
+
VerdictRow,
|
|
33
|
+
} from "./types";
|
|
34
|
+
import { DECISIONS_MAX_GENERATIONS, FLOOR_LIFT_REASON, LADDER_STEP_KINDS, SIGNAL_KINDS, STATS_EXIT, isAnnotationRow, parseKey } from "./types";
|
|
35
|
+
import { createOutcomeStore } from "./store";
|
|
36
|
+
import { signalMass } from "./signals";
|
|
37
|
+
|
|
38
|
+
// ---------------------------------------------------------------------------
|
|
39
|
+
// summarize
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
function ratio(num: number, den: number): RatioCell {
|
|
43
|
+
return { num, den, rate: den === 0 ? null : num / den };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function compareCodeUnits(a: string, b: string): number {
|
|
47
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function finiteOrNull(x: number | null): number | null {
|
|
51
|
+
return x !== null && Number.isFinite(x) ? x : null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function isoOrNull(ms: number | null): string | null {
|
|
55
|
+
return ms === null ? null : new Date(ms).toISOString();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** QA-2.2-7: a row the 2.2 adapter lifted to `floorTier` (policy, not an engine decision on evidence). */
|
|
59
|
+
function isFloorLift(row: DecisionRow): boolean {
|
|
60
|
+
return row.reason.startsWith(FLOOR_LIFT_REASON);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** QA-INT-2: a first attempt the delegate runner's recorder wrote (its decision ids start with `ladder-`; it has no `best`). */
|
|
64
|
+
function isDelegateAttempt(row: DecisionRow): boolean {
|
|
65
|
+
return row.decisionID.startsWith("ladder-");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The key a decision row actually dispatched to: `best` when `enforce` switched, else `chosen`. A `switched` row of `shadow`
|
|
70
|
+
* or `advise` is a would-switch (2.2): nothing was dispatched to `best`, so it must not count as a dispatch there.
|
|
71
|
+
*/
|
|
72
|
+
function dispatchedKey(row: DecisionRow): OutcomeKey {
|
|
73
|
+
return row.mode === "enforce" && row.switched && row.best !== null ? row.best.key : row.chosen.key;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
interface KeyAcc {
|
|
77
|
+
dispatches: number;
|
|
78
|
+
attempts: number;
|
|
79
|
+
pass: number;
|
|
80
|
+
fail: number;
|
|
81
|
+
unverifiable: number;
|
|
82
|
+
falseRefusals: number;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Aggregate the decision log (and, for the cost column, the store) over `since ≤ ts < until`.
|
|
87
|
+
* `since` is inclusive and `until` exclusive so consecutive periods never double-count. Counts and
|
|
88
|
+
* rates come only from the windowed rows; the `switched.failed` join looks at all rows, because the
|
|
89
|
+
* verdict of a switched dispatch may land after `until`. Every rate is a {@link RatioCell}: an empty
|
|
90
|
+
* denominator is `null`, never NaN.
|
|
91
|
+
*/
|
|
92
|
+
export function summarize(store: OutcomeStoreView | null, rows: readonly LogRow[], window: StatsWindow): StatsTable {
|
|
93
|
+
// An append may reach disk before reporting failure; retrying that batch must not inflate rates.
|
|
94
|
+
// Decisions keep their first row. Signals dedupe per outcome, before windowing and joins:
|
|
95
|
+
// a later decisive verdict must still replace an earlier unverifiable verdict (R2-9).
|
|
96
|
+
// P1.4: annotation rows (role signals, bindings) are not dispatches; they never reach the tier-mode numbers.
|
|
97
|
+
const seen = new Set<string>();
|
|
98
|
+
rows = rows.filter((row) => {
|
|
99
|
+
if (isAnnotationRow(row)) return false;
|
|
100
|
+
const id = JSON.stringify(row.kind === "decision"
|
|
101
|
+
? [row.kind, row.decisionID]
|
|
102
|
+
: [row.kind, row.decisionID, row.attemptID, row.kind === "verdict" ? row.verdict : row.overrides ?? null]);
|
|
103
|
+
if (seen.has(id)) return false;
|
|
104
|
+
seen.add(id);
|
|
105
|
+
return true;
|
|
106
|
+
});
|
|
107
|
+
const since = finiteOrNull(window.since);
|
|
108
|
+
const until = finiteOrNull(window.until);
|
|
109
|
+
const inWindow = (row: LogRow): boolean => {
|
|
110
|
+
const t = Date.parse(row.ts);
|
|
111
|
+
return Number.isFinite(t) && (since === null || t >= since) && (until === null || t < until);
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const decisions: DecisionRow[] = [];
|
|
115
|
+
const verdicts: VerdictRow[] = [];
|
|
116
|
+
const refusals: RefusalRow[] = [];
|
|
117
|
+
for (const row of rows) {
|
|
118
|
+
if (!inWindow(row)) continue;
|
|
119
|
+
if (row.kind === "decision") decisions.push(row);
|
|
120
|
+
else if (row.kind === "verdict") verdicts.push(row);
|
|
121
|
+
else refusals.push(row);
|
|
122
|
+
}
|
|
123
|
+
const dispatchRows = decisions.filter((r) => r.step === "dispatch");
|
|
124
|
+
// 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
|
|
125
|
+
// about routing: every routing metric below (class and key dispatch counts, agreement, switched, savings, the evidence gate) is over the
|
|
126
|
+
// FRESH dispatches only. Resumes are reported on their own line (`orchestratorResumes`).
|
|
127
|
+
const freshRows = dispatchRows.filter((r) => !r.resume);
|
|
128
|
+
const nonPinned = freshRows.filter((r) => !r.pinned);
|
|
129
|
+
|
|
130
|
+
// By class.
|
|
131
|
+
const classCounts = new Map<string, number>();
|
|
132
|
+
for (const r of freshRows) classCounts.set(r.facts.class, (classCounts.get(r.facts.class) ?? 0) + 1);
|
|
133
|
+
const byClass: ClassStatsRow[] = [...classCounts.keys()]
|
|
134
|
+
.sort(compareCodeUnits)
|
|
135
|
+
.map((cls) => ({ class: cls, dispatches: classCounts.get(cls) ?? 0 }));
|
|
136
|
+
|
|
137
|
+
// By key.
|
|
138
|
+
const accs = new Map<OutcomeKey, KeyAcc>();
|
|
139
|
+
const slot = (key: OutcomeKey): KeyAcc => {
|
|
140
|
+
let acc = accs.get(key);
|
|
141
|
+
if (acc === undefined) {
|
|
142
|
+
acc = { dispatches: 0, attempts: 0, pass: 0, fail: 0, unverifiable: 0, falseRefusals: 0 };
|
|
143
|
+
accs.set(key, acc);
|
|
144
|
+
}
|
|
145
|
+
return acc;
|
|
146
|
+
};
|
|
147
|
+
for (const r of decisions) {
|
|
148
|
+
const acc = slot(dispatchedKey(r));
|
|
149
|
+
acc.attempts += 1;
|
|
150
|
+
if (r.step === "dispatch" && !r.resume) acc.dispatches += 1;
|
|
151
|
+
}
|
|
152
|
+
// A refusal belongs to this window's refusal rate only when its decision row is in the window too
|
|
153
|
+
// (QA-1.3-13); otherwise `falseRefusals / attempts` could pass 100 %. Refusals without a decision id stay.
|
|
154
|
+
const windowDecisionIDs = new Set(decisions.map((r) => r.decisionID));
|
|
155
|
+
// QA-2.1-3 / R2-2: a refusal that records `overrides: "pass"` turned a `pass` of the same attempt into a failure,
|
|
156
|
+
// exactly as the store does (pass → fail, `falseRefusals` + 1). The conversion set comes from every row handed in,
|
|
157
|
+
// not only the window: the pass row may sit in an earlier window or in a rotated log. A converted attempt's pass is
|
|
158
|
+
// never counted as a pass; its failure is counted once, with the refusal, whichever window each row is in. Only the
|
|
159
|
+
// explicit marker counts: a refusal without it (another attempt, or after a fail) is a refusal and nothing else.
|
|
160
|
+
const converted = new Set<string>();
|
|
161
|
+
for (const row of rows) if (row.kind === "refusal" && row.overrides === "pass") converted.add(row.attemptID);
|
|
162
|
+
const decisiveAttempts = new Set(verdicts.filter((v) => v.verdict !== "unverifiable").map((v) => v.attemptID));
|
|
163
|
+
const effectiveVerdicts: Array<Pick<VerdictRow, "key" | "verdict" | "step" | "attemptID">> = [];
|
|
164
|
+
const unverifiableSeen = new Set<string>();
|
|
165
|
+
for (const v of verdicts) {
|
|
166
|
+
if (v.verdict === "pass" && converted.has(v.attemptID)) continue;
|
|
167
|
+
if (v.verdict === "unverifiable") {
|
|
168
|
+
// R2-9: a later pass/fail row for the attempt replaces an earlier unverifiable one; one unverifiable per attempt.
|
|
169
|
+
if (decisiveAttempts.has(v.attemptID) || unverifiableSeen.has(v.attemptID)) continue;
|
|
170
|
+
unverifiableSeen.add(v.attemptID);
|
|
171
|
+
}
|
|
172
|
+
effectiveVerdicts.push(v);
|
|
173
|
+
}
|
|
174
|
+
const countedRefusals: RefusalRow[] = [];
|
|
175
|
+
const failedByRefusal = new Set<string>();
|
|
176
|
+
for (const r of refusals) {
|
|
177
|
+
if (r.decisionID !== null && !windowDecisionIDs.has(r.decisionID)) continue;
|
|
178
|
+
countedRefusals.push(r);
|
|
179
|
+
slot(r.key).falseRefusals += 1;
|
|
180
|
+
if (r.overrides === "pass" && !failedByRefusal.has(r.attemptID)) {
|
|
181
|
+
failedByRefusal.add(r.attemptID);
|
|
182
|
+
effectiveVerdicts.push({ key: r.key, verdict: "fail", step: r.step, attemptID: r.attemptID });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
for (const v of effectiveVerdicts) slot(v.key)[v.verdict] += 1;
|
|
186
|
+
const byKey: KeyStatsRow[] = [...accs.keys()].sort(compareCodeUnits).map((key) => {
|
|
187
|
+
const acc = accs.get(key) ?? { dispatches: 0, attempts: 0, pass: 0, fail: 0, unverifiable: 0, falseRefusals: 0 };
|
|
188
|
+
const measured = store === null ? null : store.cost(key).measuredUSD;
|
|
189
|
+
return {
|
|
190
|
+
key,
|
|
191
|
+
dispatches: acc.dispatches,
|
|
192
|
+
attempts: acc.attempts,
|
|
193
|
+
pass: acc.pass,
|
|
194
|
+
fail: acc.fail,
|
|
195
|
+
unverifiable: acc.unverifiable,
|
|
196
|
+
passRate: ratio(acc.pass, acc.pass + acc.fail),
|
|
197
|
+
falseRefusals: acc.falseRefusals,
|
|
198
|
+
refusalRate: ratio(Math.min(acc.falseRefusals, acc.attempts), acc.attempts),
|
|
199
|
+
measuredUSD: measured !== null && measured.n > 0 ? { mean: measured.mean, n: measured.n } : null,
|
|
200
|
+
};
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
// Agreement: best == chosen over non-pinned dispatches that have a best.
|
|
204
|
+
// 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
|
|
205
|
+
// lifted tier, not an argmin). Delegate first attempts (the runner's recorder rows, `best: null`) and lifts are counted on their own lines.
|
|
206
|
+
const routedRows = nonPinned.filter((r) => r.best !== null && !isFloorLift(r));
|
|
207
|
+
const agreement = ratio(routedRows.filter((r) => r.best !== null && r.best.key === r.chosen.key).length, routedRows.length);
|
|
208
|
+
|
|
209
|
+
// Switched, and how many of those ended in a fail verdict or a false refusal (any window).
|
|
210
|
+
const failedDecisionIDs = new Set<string>();
|
|
211
|
+
const decidedDecisionIDs = new Set<string>(); // a pass/fail verdict or a refusal exists: the outcome is known
|
|
212
|
+
for (const row of rows) {
|
|
213
|
+
if (row.kind === "verdict" && row.decisionID !== null) {
|
|
214
|
+
if (row.verdict === "fail") failedDecisionIDs.add(row.decisionID);
|
|
215
|
+
if (row.verdict !== "unverifiable") decidedDecisionIDs.add(row.decisionID);
|
|
216
|
+
} else if (row.kind === "refusal" && row.decisionID !== null) {
|
|
217
|
+
failedDecisionIDs.add(row.decisionID);
|
|
218
|
+
decidedDecisionIDs.add(row.decisionID);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const switchedRows = routedRows.filter((r) => r.switched);
|
|
222
|
+
// 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
|
|
223
|
+
// moved) and a floor lift is policy, so neither can be a failed switch.
|
|
224
|
+
const enforcedSwitches = switchedRows.filter((r) => r.mode === "enforce");
|
|
225
|
+
|
|
226
|
+
// Savings: Σ C(chosen) − C(best) per unit, never summed across units. Summed in ascending order so
|
|
227
|
+
// the total does not depend on the row order.
|
|
228
|
+
const terms = new Map<CostUnit, number[]>();
|
|
229
|
+
for (const r of routedRows) {
|
|
230
|
+
if (r.best === null) continue;
|
|
231
|
+
const chosenCost = r.costs[r.chosen.key];
|
|
232
|
+
const bestCost = r.costs[r.best.key];
|
|
233
|
+
if (typeof chosenCost !== "number" || typeof bestCost !== "number") continue;
|
|
234
|
+
if (!Number.isFinite(chosenCost) || !Number.isFinite(bestCost)) continue;
|
|
235
|
+
const list = terms.get(r.unit) ?? [];
|
|
236
|
+
list.push(chosenCost - bestCost);
|
|
237
|
+
terms.set(r.unit, list);
|
|
238
|
+
}
|
|
239
|
+
const savings: SavingsRow[] = [...terms.keys()].sort(compareCodeUnits).map((unit) => {
|
|
240
|
+
const list = [...(terms.get(unit) ?? [])].sort((a, b) => a - b);
|
|
241
|
+
return { unit, total: list.reduce((sum, x) => sum + x, 0), rows: list.length };
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
// Variant steps.
|
|
245
|
+
const variantVerdicts = effectiveVerdicts.filter((v) => v.step === "variant");
|
|
246
|
+
const variantPass = variantVerdicts.filter((v) => v.verdict === "pass").length;
|
|
247
|
+
// R2-3: a refusal that was an attempt's first terminal signal is a variant failure in the store (`variantFail`), though it has
|
|
248
|
+
// no verdict row; one after a verdict, or a conversion (already a synthetic fail above), adds nothing.
|
|
249
|
+
const decidedAttempts = new Set(effectiveVerdicts.filter((v) => v.verdict !== "unverifiable").map((v) => v.attemptID));
|
|
250
|
+
let variantRefusalFails = 0;
|
|
251
|
+
for (const r of countedRefusals) {
|
|
252
|
+
if (r.step !== "variant" || decidedAttempts.has(r.attemptID)) continue;
|
|
253
|
+
decidedAttempts.add(r.attemptID);
|
|
254
|
+
variantRefusalFails += 1;
|
|
255
|
+
}
|
|
256
|
+
const variantFail = variantVerdicts.filter((v) => v.verdict === "fail").length + variantRefusalFails;
|
|
257
|
+
|
|
258
|
+
const resumeVsFresh: ResumeFreshRow[] = LADDER_STEP_KINDS.map((step) => {
|
|
259
|
+
const ofStep = decisions.filter((r) => r.step === step);
|
|
260
|
+
const resume = ofStep.filter((r) => r.resume).length;
|
|
261
|
+
return { step, resume, fresh: ofStep.length - resume };
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
// 2.4: the orchestrator's own resumes (2.2 `task_id`/`sessionID`) and the A27 evidence gate, over the routed dispatch rows.
|
|
265
|
+
const routedDispatches = dispatchRows.filter((r) => !isDelegateAttempt(r)); // fresh and resumed: the resume line's denominator
|
|
266
|
+
const routedFresh = routedDispatches.filter((r) => !r.resume);
|
|
267
|
+
const argminCounts = new Map<OutcomeKey, number>();
|
|
268
|
+
for (const r of routedFresh) {
|
|
269
|
+
const key = r.trace?.argmin?.key;
|
|
270
|
+
if (key !== undefined) argminCounts.set(key, (argminCounts.get(key) ?? 0) + 1);
|
|
271
|
+
}
|
|
272
|
+
const argmin = [...argminCounts.entries()]
|
|
273
|
+
.sort((a, b) => b[1] - a[1] || compareCodeUnits(a[0], b[0]))
|
|
274
|
+
.map(([key, count]) => ({ key, count }));
|
|
275
|
+
|
|
276
|
+
// A34 (QA-G-B8): D9 never-down audit. High-risk rows decided without detection that record both capability ranks; `below` = those that
|
|
277
|
+
// ran below the pick's capability rank. Rows written before A34 (no `detection`/`capability`) are tolerated and left out.
|
|
278
|
+
const isRank = (x: unknown): x is number => typeof x === "number" && Number.isFinite(x);
|
|
279
|
+
const audited: Array<{ readonly pick: number; readonly dispatched: number }> = [];
|
|
280
|
+
for (const r of routedDispatches) {
|
|
281
|
+
const capability = r.capability;
|
|
282
|
+
if (r.facts.risk !== "high" || r.detection?.effective !== "none" || capability === undefined) continue;
|
|
283
|
+
if (isRank(capability.pick) && isRank(capability.dispatched)) audited.push({ pick: capability.pick, dispatched: capability.dispatched });
|
|
284
|
+
}
|
|
285
|
+
const neverDownBelow = audited.filter((ranks) => ranks.dispatched < ranks.pick).length;
|
|
286
|
+
|
|
287
|
+
return {
|
|
288
|
+
version: 1,
|
|
289
|
+
window: { since: isoOrNull(since), until: isoOrNull(until) },
|
|
290
|
+
dispatches: dispatchRows.length,
|
|
291
|
+
routed: dispatchRows.filter((r) => !isDelegateAttempt(r)).length,
|
|
292
|
+
delegateFirstAttempts: dispatchRows.filter(isDelegateAttempt).length,
|
|
293
|
+
floorLifts: dispatchRows.filter(isFloorLift).length,
|
|
294
|
+
pinned: dispatchRows.filter((r) => r.pinned).length,
|
|
295
|
+
byClass,
|
|
296
|
+
byKey,
|
|
297
|
+
agreement,
|
|
298
|
+
switched: {
|
|
299
|
+
count: switchedRows.length,
|
|
300
|
+
share: ratio(switchedRows.length, routedRows.length),
|
|
301
|
+
enforced: enforcedSwitches.length,
|
|
302
|
+
failed: enforcedSwitches.filter((r) => failedDecisionIDs.has(r.decisionID)).length,
|
|
303
|
+
verified: enforcedSwitches.filter((r) => decidedDecisionIDs.has(r.decisionID)).length,
|
|
304
|
+
},
|
|
305
|
+
savings,
|
|
306
|
+
variantSteps: {
|
|
307
|
+
taken: decisions.filter((r) => r.step === "variant").length,
|
|
308
|
+
passRate: ratio(variantPass, variantPass + variantFail),
|
|
309
|
+
},
|
|
310
|
+
resumeVsFresh,
|
|
311
|
+
orchestratorResumes: { resumed: routedDispatches.filter((r) => r.resume).length, total: routedDispatches.length },
|
|
312
|
+
gate: { keptEvidence: routedFresh.filter((r) => r.reason.startsWith("kept:evidence")).length, argmin },
|
|
313
|
+
neverDown: { below: neverDownBelow, recorded: audited.length },
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// ---------------------------------------------------------------------------
|
|
318
|
+
// summarizeRoles (P1.4): role × tier statistics; computation only, rendering is P2.2
|
|
319
|
+
// ---------------------------------------------------------------------------
|
|
320
|
+
|
|
321
|
+
const UNKNOWN_TIER = "unknown";
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Role of a decision row: its `role`, else the agent of its dispatched key when that key has origin `role` (QA-P14-2-5:
|
|
325
|
+
* a role dispatch row written without `role` is still the role's; P2.1 should write `role` anyway).
|
|
326
|
+
*/
|
|
327
|
+
function roleOf(row: DecisionRow): string | undefined {
|
|
328
|
+
if (row.role !== undefined) return row.role;
|
|
329
|
+
const parts = parseKey(dispatchedKey(row));
|
|
330
|
+
return parts !== null && parts.agent.origin === "role" ? parts.agent.id : undefined;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
interface RoleTierAcc {
|
|
334
|
+
readonly role: string;
|
|
335
|
+
readonly tier: string;
|
|
336
|
+
dispatches: number;
|
|
337
|
+
explored: number;
|
|
338
|
+
unknownBindings: number;
|
|
339
|
+
readonly signals: Map<SignalKind, { pass: number; fail: number; none: number; positive: number; negative: number }>;
|
|
340
|
+
readonly keys: Set<OutcomeKey>;
|
|
341
|
+
readonly costs: Map<CostUnit, number[]>;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Ascending-order sum, so a total never depends on the row order. */
|
|
345
|
+
function stableSum(values: readonly number[]): number {
|
|
346
|
+
return [...values].sort((a, b) => a - b).reduce((sum, x) => sum + x, 0);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function pooledTokens(store: OutcomeStoreView, keys: ReadonlySet<OutcomeKey>): TokenMeans | null {
|
|
350
|
+
let n = 0;
|
|
351
|
+
const sums = { input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0 };
|
|
352
|
+
for (const key of [...keys].sort(compareCodeUnits)) {
|
|
353
|
+
const t = store.cost(key).tokens;
|
|
354
|
+
if (t.n <= 0) continue;
|
|
355
|
+
n += t.n;
|
|
356
|
+
sums.input += t.input * t.n;
|
|
357
|
+
sums.output += t.output * t.n;
|
|
358
|
+
sums.reasoning += t.reasoning * t.n;
|
|
359
|
+
sums.cacheRead += t.cacheRead * t.n;
|
|
360
|
+
sums.cacheWrite += t.cacheWrite * t.n;
|
|
361
|
+
}
|
|
362
|
+
if (n === 0) return null;
|
|
363
|
+
return {
|
|
364
|
+
n,
|
|
365
|
+
input: sums.input / n,
|
|
366
|
+
output: sums.output / n,
|
|
367
|
+
reasoning: sums.reasoning / n,
|
|
368
|
+
cacheRead: sums.cacheRead / n,
|
|
369
|
+
cacheWrite: sums.cacheWrite / n,
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function pooledUSD(store: OutcomeStoreView, keys: ReadonlySet<OutcomeKey>): MeanStat | null {
|
|
374
|
+
let n = 0;
|
|
375
|
+
let sum = 0;
|
|
376
|
+
for (const key of [...keys].sort(compareCodeUnits)) {
|
|
377
|
+
const m = store.cost(key).measuredUSD;
|
|
378
|
+
if (m.n <= 0) continue;
|
|
379
|
+
n += m.n;
|
|
380
|
+
sum += m.mean * m.n;
|
|
381
|
+
}
|
|
382
|
+
return n === 0 ? null : { mean: sum / n, n };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Role × tier statistics over `since ≤ ts < until`. Only rows of role dispatches count: a dispatch row is a non-annotation
|
|
387
|
+
* `dispatch` decision row with a role (`role`, else a role-origin dispatched key: {@link roleOf}); signal rows and unknown-binding rows are attributed to the role
|
|
388
|
+
* and tier of the dispatch row they join on `decisionID` (any window: the dispatch may precede the window), else to their
|
|
389
|
+
* own `role`/`tier`. Rows are deduplicated like `summarize` (C7): the first dispatch row per decision id, and identical
|
|
390
|
+
* annotation rows once. Signal masses are clamped per kind (`signalMass`): I6 and I7 hold whatever a row claims.
|
|
391
|
+
* Tokens and USD come from the store (lifetime per attempt, like `KeyStatsRow.measuredUSD`).
|
|
392
|
+
*/
|
|
393
|
+
export function summarizeRoles(store: OutcomeStoreView | null, rows: readonly LogRow[], window: StatsWindow): RoleStatsTable {
|
|
394
|
+
const since = finiteOrNull(window.since);
|
|
395
|
+
const until = finiteOrNull(window.until);
|
|
396
|
+
const inWindow = (row: LogRow): boolean => {
|
|
397
|
+
const t = Date.parse(row.ts);
|
|
398
|
+
return Number.isFinite(t) && (since === null || t >= since) && (until === null || t < until);
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
const dispatchByID = new Map<string, DecisionRow>();
|
|
402
|
+
const annotations: DecisionRow[] = [];
|
|
403
|
+
const seenNotes = new Set<string>();
|
|
404
|
+
// Residual QA-P14-1-6: a refusal that records `overrides: "pass"` turned the attempt's store pass into a failure (as
|
|
405
|
+
// `summarize` moves that pass to a fail). The attempt's `verdict:pass` signal then counts as a failure of 1, and its
|
|
406
|
+
// `grader:pass` signal (#84 P3.3 fix 2: grader verdicts follow the store too) as a failure of the grader's 0.5. Every row
|
|
407
|
+
// handed in, not only the window: the refusal may land in another window than the signal.
|
|
408
|
+
const converted = new Set<string>();
|
|
409
|
+
for (const row of rows) if (row.kind === "refusal" && row.overrides === "pass") converted.add(row.attemptID);
|
|
410
|
+
for (const row of rows) {
|
|
411
|
+
if (row.kind !== "decision") continue;
|
|
412
|
+
if (isAnnotationRow(row)) {
|
|
413
|
+
// Signals: one row per attempt and kind, first wins (ingest's own identity and the store's one-observation rule);
|
|
414
|
+
// `attemptID` when the row carries it, else the child session. Other annotations: per attempt and reason.
|
|
415
|
+
const attempt = row.attemptID ?? row.childSessionID;
|
|
416
|
+
const id = JSON.stringify(row.signal !== undefined
|
|
417
|
+
? ["signal", row.decisionID, attempt, row.signal]
|
|
418
|
+
: ["note", row.decisionID, attempt, row.reason, row.binding ?? null]);
|
|
419
|
+
if (seenNotes.has(id)) continue;
|
|
420
|
+
seenNotes.add(id);
|
|
421
|
+
annotations.push(row);
|
|
422
|
+
} else if (!dispatchByID.has(row.decisionID)) {
|
|
423
|
+
dispatchByID.set(row.decisionID, row);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const buckets = new Map<string, RoleTierAcc>();
|
|
428
|
+
const bucket = (role: string, tier: string): RoleTierAcc => {
|
|
429
|
+
const id = JSON.stringify([role, tier]);
|
|
430
|
+
let acc = buckets.get(id);
|
|
431
|
+
if (acc === undefined) {
|
|
432
|
+
acc = { role, tier, dispatches: 0, explored: 0, unknownBindings: 0, signals: new Map(), keys: new Set(), costs: new Map() };
|
|
433
|
+
buckets.set(id, acc);
|
|
434
|
+
}
|
|
435
|
+
return acc;
|
|
436
|
+
};
|
|
437
|
+
/**
|
|
438
|
+
* Role and tier of an annotation: when its dispatch row exists, that row's role AND tier only (a dispatch without a role
|
|
439
|
+
* is tier mode: unattributed); else the annotation's own. Null without a role.
|
|
440
|
+
*/
|
|
441
|
+
const placeOf = (row: DecisionRow): RoleTierAcc | null => {
|
|
442
|
+
const dispatch = dispatchByID.get(row.decisionID);
|
|
443
|
+
const source = dispatch ?? row;
|
|
444
|
+
const role = roleOf(source);
|
|
445
|
+
if (role === undefined) return null;
|
|
446
|
+
return bucket(role, source.tier ?? UNKNOWN_TIER);
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
const unknownBindingSeen = new Set<string>();
|
|
450
|
+
const noteUnknownBinding = (row: DecisionRow, acc: RoleTierAcc | null): boolean => {
|
|
451
|
+
if (row.binding !== "unknown") return false;
|
|
452
|
+
const id = JSON.stringify([row.decisionID, row.childSessionID]);
|
|
453
|
+
if (unknownBindingSeen.has(id)) return false;
|
|
454
|
+
unknownBindingSeen.add(id);
|
|
455
|
+
if (acc !== null) acc.unknownBindings += 1;
|
|
456
|
+
return acc === null;
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
let unattributedSignals = 0;
|
|
460
|
+
let unattributedBindings = 0;
|
|
461
|
+
for (const row of dispatchByID.values()) {
|
|
462
|
+
const role = roleOf(row);
|
|
463
|
+
if (!inWindow(row) || role === undefined) continue;
|
|
464
|
+
const acc = bucket(role, row.tier ?? UNKNOWN_TIER);
|
|
465
|
+
if (noteUnknownBinding(row, acc)) unattributedBindings += 1;
|
|
466
|
+
if (row.step !== "dispatch") continue;
|
|
467
|
+
acc.dispatches += 1;
|
|
468
|
+
if (row.explore === true) acc.explored += 1;
|
|
469
|
+
const key = dispatchedKey(row);
|
|
470
|
+
acc.keys.add(key);
|
|
471
|
+
const cost = row.costs[key];
|
|
472
|
+
if (typeof cost === "number" && Number.isFinite(cost)) {
|
|
473
|
+
const list = acc.costs.get(row.unit) ?? [];
|
|
474
|
+
list.push(cost);
|
|
475
|
+
acc.costs.set(row.unit, list);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
for (const row of annotations) {
|
|
479
|
+
if (!inWindow(row)) continue;
|
|
480
|
+
const acc = placeOf(row);
|
|
481
|
+
if (noteUnknownBinding(row, acc)) unattributedBindings += 1;
|
|
482
|
+
const kind = row.signal;
|
|
483
|
+
if (kind === undefined) continue;
|
|
484
|
+
if (acc === null) {
|
|
485
|
+
unattributedSignals += 1;
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
const cell = acc.signals.get(kind) ?? { pass: 0, fail: 0, none: 0, positive: 0, negative: 0 };
|
|
489
|
+
const overridden = (kind === "verdict" || kind === "grader") && row.attemptID !== undefined && converted.has(row.attemptID) && (row.signalWeight ?? 0) > 0;
|
|
490
|
+
const mass = signalMass(kind, overridden ? -1 : row.signalWeight);
|
|
491
|
+
if (mass.positive > 0) cell.pass += 1;
|
|
492
|
+
else if (mass.negative > 0) cell.fail += 1;
|
|
493
|
+
else cell.none += 1;
|
|
494
|
+
cell.positive += mass.positive;
|
|
495
|
+
cell.negative += mass.negative;
|
|
496
|
+
acc.signals.set(kind, cell);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
const byRoleTier: RoleTierStatsRow[] = [...buckets.values()]
|
|
500
|
+
.sort((a, b) => compareCodeUnits(a.role, b.role) || compareCodeUnits(a.tier, b.tier))
|
|
501
|
+
.map((acc) => {
|
|
502
|
+
const signals: SignalKindStats[] = SIGNAL_KINDS.map((kind) => ({
|
|
503
|
+
kind,
|
|
504
|
+
...(acc.signals.get(kind) ?? { pass: 0, fail: 0, none: 0, positive: 0, negative: 0 }),
|
|
505
|
+
}));
|
|
506
|
+
const costUnits: CostUnitRow[] = [...acc.costs.keys()].sort(compareCodeUnits).map((unit) => {
|
|
507
|
+
const list = acc.costs.get(unit) ?? [];
|
|
508
|
+
return { unit, total: stableSum(list), rows: list.length };
|
|
509
|
+
});
|
|
510
|
+
const count = (kind: SignalKind): number => {
|
|
511
|
+
const s = acc.signals.get(kind);
|
|
512
|
+
return s === undefined ? 0 : s.pass + s.fail + s.none;
|
|
513
|
+
};
|
|
514
|
+
return {
|
|
515
|
+
role: acc.role,
|
|
516
|
+
tier: acc.tier,
|
|
517
|
+
dispatches: acc.dispatches,
|
|
518
|
+
signals,
|
|
519
|
+
positiveMass: stableSum(signals.map((s) => s.positive)),
|
|
520
|
+
negativeMass: stableSum(signals.map((s) => s.negative)),
|
|
521
|
+
budgetExhaustions: count("budget"),
|
|
522
|
+
authorityRequests: count("authority"),
|
|
523
|
+
unknownBindings: acc.unknownBindings,
|
|
524
|
+
explored: acc.explored,
|
|
525
|
+
tokensPerDispatch: store === null ? null : pooledTokens(store, acc.keys),
|
|
526
|
+
measuredUSD: store === null ? null : pooledUSD(store, acc.keys),
|
|
527
|
+
costUnits,
|
|
528
|
+
};
|
|
529
|
+
});
|
|
530
|
+
|
|
531
|
+
return {
|
|
532
|
+
version: 1,
|
|
533
|
+
window: { since: isoOrNull(since), until: isoOrNull(until) },
|
|
534
|
+
byRoleTier,
|
|
535
|
+
unattributed: { signals: unattributedSignals, unknownBindings: unattributedBindings },
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// ---------------------------------------------------------------------------
|
|
540
|
+
// renderMarkdown
|
|
541
|
+
// ---------------------------------------------------------------------------
|
|
542
|
+
|
|
543
|
+
/** D17 / DF5: apply to the enforce-period summary; any failed enforced switch returns to advise. */
|
|
544
|
+
export function d17Mode(summary: Pick<StatsTable, "switched">): "enforce" | "advise" | "n/a (0 enforced switches)" {
|
|
545
|
+
if (summary.switched.enforced === 0) return "n/a (0 enforced switches)";
|
|
546
|
+
return summary.switched.failed === 0 ? "enforce" : "advise";
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** `toFixed` without `-0.00`. */
|
|
550
|
+
function fix(x: number, digits: number): string {
|
|
551
|
+
return (Math.abs(x) < 0.5 * 10 ** -digits ? 0 : x).toFixed(digits);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function fmtRatio(cell: RatioCell): string {
|
|
555
|
+
return cell.den === 0 ? "n/a" : `${cell.num}/${cell.den} (${((100 * cell.num) / cell.den).toFixed(1)}%)`;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function fmtPercent(cell: RatioCell): string {
|
|
559
|
+
return cell.rate === null ? "n/a" : `${(100 * cell.rate).toFixed(1)}%`;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function fmtUSD(x: number): string {
|
|
563
|
+
return `$${fix(x, 4)}`;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function fmtRatioAmount(x: number): string {
|
|
567
|
+
return fix(x, 2);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** Keys contain `|`; a cell must neither break the table nor span lines. */
|
|
571
|
+
function cell(text: string): string {
|
|
572
|
+
return text.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Markdown report: `\n` only, blocks separated by exactly one blank line, exactly one trailing `\n`.
|
|
577
|
+
* Deterministic: the same table always renders the same bytes.
|
|
578
|
+
*/
|
|
579
|
+
export function renderMarkdown(table: StatsTable): string {
|
|
580
|
+
const metrics = [
|
|
581
|
+
"| Metric | Value |",
|
|
582
|
+
"|---|---|",
|
|
583
|
+
`| Dispatches | ${table.dispatches} |`,
|
|
584
|
+
`| Routed dispatches | ${table.routed} |`,
|
|
585
|
+
`| Delegate first attempts | ${table.delegateFirstAttempts} |`,
|
|
586
|
+
`| Floor lifts | ${table.floorLifts} |`,
|
|
587
|
+
`| Pinned | ${table.pinned} |`,
|
|
588
|
+
`| Agreement (best == chosen, non-pinned) | ${fmtRatio(table.agreement)} |`,
|
|
589
|
+
`| 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) |`,
|
|
590
|
+
`| D17 mode (use the DF4→DF5 enforce-period window) | ${d17Mode(table)} |`,
|
|
591
|
+
...(table.savings.length === 0
|
|
592
|
+
? ["| Estimated savings | n/a |"]
|
|
593
|
+
: table.savings.map(
|
|
594
|
+
(s) =>
|
|
595
|
+
`| Estimated savings (${s.unit}) | ${s.unit === "usd" ? fmtUSD(s.total) : fmtRatioAmount(s.total)} over ${s.rows} rows |`,
|
|
596
|
+
)),
|
|
597
|
+
`| Variant steps | ${table.variantSteps.taken} taken; pass ${fmtRatio(table.variantSteps.passRate)} |`,
|
|
598
|
+
// 2.4: not ladder decisions, so they are not rows of the D11 table below (QA-2.3-7).
|
|
599
|
+
`| Orchestrator resumes (task_id / sessionID; not a ladder step, never switched, outside every routing metric) | ${table.orchestratorResumes.resumed} of ${table.orchestratorResumes.total} routed dispatches |`,
|
|
600
|
+
`| Kept for lack of evidence (A27, fresh dispatches) | ${table.gate.keptEvidence} of ${table.orchestratorResumes.total - table.orchestratorResumes.resumed} fresh routed dispatches |`,
|
|
601
|
+
// A34 (QA-G-B8): the never-down audit. `n/a` when no row of the window records detection and both capability ranks.
|
|
602
|
+
`| High-risk d=none rows that ran below the pick's capability rank (D9 never-down, A34; expected 0) | ${
|
|
603
|
+
table.neverDown.recorded === 0 ? "n/a (no row records detection and capability)" : `${table.neverDown.below} of ${table.neverDown.recorded} recorded`
|
|
604
|
+
} |`,
|
|
605
|
+
];
|
|
606
|
+
|
|
607
|
+
const classTable =
|
|
608
|
+
table.byClass.length === 0
|
|
609
|
+
? "_none_"
|
|
610
|
+
: ["| Class | Dispatches |", "|---|---|", ...table.byClass.map((r) => `| ${cell(r.class)} | ${r.dispatches} |`)].join("\n");
|
|
611
|
+
|
|
612
|
+
const keyTable =
|
|
613
|
+
table.byKey.length === 0
|
|
614
|
+
? "_none_"
|
|
615
|
+
: [
|
|
616
|
+
"| Key | Dispatches | Attempts | Pass | Fail | Unverifiable | Pass rate | False refusals | Refusal rate | USD/attempt (lifetime) |",
|
|
617
|
+
"|---|---|---|---|---|---|---|---|---|---|",
|
|
618
|
+
...table.byKey.map(
|
|
619
|
+
(r) =>
|
|
620
|
+
`| ${cell(r.key)} | ${r.dispatches} | ${r.attempts} | ${r.pass} | ${r.fail} | ${r.unverifiable} | ${fmtRatio(r.passRate)} | ${r.falseRefusals} | ${fmtRatio(r.refusalRate)} | ${
|
|
621
|
+
r.measuredUSD === null ? "n/a" : `${fmtUSD(r.measuredUSD.mean)} (n=${r.measuredUSD.n})`
|
|
622
|
+
} |`,
|
|
623
|
+
),
|
|
624
|
+
].join("\n");
|
|
625
|
+
|
|
626
|
+
// QA-2.3-7: the rendered table is the ladder's. `dispatch` counts first dispatches (always fresh for `delegate`) and the
|
|
627
|
+
// `sessionID`/`task_id` resumes of dispatched subagents, neither of which is a D11 ladder decision, so its row is left out
|
|
628
|
+
// here; `resumeVsFresh` itself (and `--json`) keeps it, so those numbers stay countable.
|
|
629
|
+
const resumeTable = [
|
|
630
|
+
"| Step | Resume | Fresh |",
|
|
631
|
+
"|---|---|---|",
|
|
632
|
+
...table.resumeVsFresh.filter((r) => r.step !== "dispatch").map((r) => `| ${r.step} | ${r.resume} | ${r.fresh} |`),
|
|
633
|
+
].join("\n");
|
|
634
|
+
|
|
635
|
+
// A27 / DF3: the cheapest option the evidence filter held back (`trace.argmin`), i.e. where the gate stops the engine.
|
|
636
|
+
const argminTable =
|
|
637
|
+
table.gate.argmin.length === 0
|
|
638
|
+
? "_none_"
|
|
639
|
+
: ["| Cheapest key held back | Rows |", "|---|---|", ...table.gate.argmin.map((r) => `| ${cell(r.key)} | ${r.count} |`)].join("\n");
|
|
640
|
+
|
|
641
|
+
const blocks = [
|
|
642
|
+
"## Routing stats",
|
|
643
|
+
`Window: ${table.window.since ?? "start"} → ${table.window.until ?? "open"}`,
|
|
644
|
+
metrics.join("\n"),
|
|
645
|
+
"### By class",
|
|
646
|
+
classTable,
|
|
647
|
+
"### By key",
|
|
648
|
+
keyTable,
|
|
649
|
+
"### Gated by evidence (trace.argmin)",
|
|
650
|
+
argminTable,
|
|
651
|
+
"### Resume vs fresh",
|
|
652
|
+
resumeTable,
|
|
653
|
+
// QA-2.1-10: rows are only recorded under a trusted class, so the rates below the metrics are not over every dispatch.
|
|
654
|
+
"_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._",
|
|
655
|
+
];
|
|
656
|
+
return blocks.join("\n\n") + "\n";
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* True when the log has role rows: a role dispatch bucket, or an unknown-binding row (only role dispatches are bound). Unattributed
|
|
661
|
+
* SIGNAL rows do not count: tier-origin verdict/run signals are written in every mode, so tier-only logs render exactly as before.
|
|
662
|
+
*/
|
|
663
|
+
export function hasRoleRows(table: RoleStatsTable): boolean {
|
|
664
|
+
return table.byRoleTier.length > 0 || table.unattributed.unknownBindings > 0;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/** P2.2: the role × tier section appended to the report when the log has role rows. Same determinism rules as {@link renderMarkdown}. */
|
|
668
|
+
export function renderRoleMarkdown(table: RoleStatsTable): string {
|
|
669
|
+
const rows =
|
|
670
|
+
table.byRoleTier.length === 0
|
|
671
|
+
? "_none_"
|
|
672
|
+
: [
|
|
673
|
+
"| Role | Tier | Dispatches | Pass | Fail | +mass | -mass | Budget exhaustions | Authority requests | Unknown bindings | Explored | Tokens/dispatch (in/out) | USD/attempt (lifetime) |",
|
|
674
|
+
"|---|---|---|---|---|---|---|---|---|---|---|---|---|",
|
|
675
|
+
...table.byRoleTier.map((r) => {
|
|
676
|
+
const pass = r.signals.reduce((sum, s) => sum + s.pass, 0);
|
|
677
|
+
const fail = r.signals.reduce((sum, s) => sum + s.fail, 0);
|
|
678
|
+
const tokens = r.tokensPerDispatch === null ? "n/a" : `${fix(r.tokensPerDispatch.input, 0)}/${fix(r.tokensPerDispatch.output, 0)} (n=${r.tokensPerDispatch.n})`;
|
|
679
|
+
const usd = r.measuredUSD === null ? "n/a" : `${fmtUSD(r.measuredUSD.mean)} (n=${r.measuredUSD.n})`;
|
|
680
|
+
return `| ${cell(r.role)} | ${cell(r.tier)} | ${r.dispatches} | ${pass} | ${fail} | ${fix(r.positiveMass, 2)} | ${fix(r.negativeMass, 2)} | ${r.budgetExhaustions} | ${r.authorityRequests} | ${r.unknownBindings} | ${r.explored} | ${tokens} | ${usd} |`;
|
|
681
|
+
}),
|
|
682
|
+
].join("\n");
|
|
683
|
+
const blocks = ["### By role × tier", rows];
|
|
684
|
+
if (table.unattributed.signals > 0 || table.unattributed.unknownBindings > 0) {
|
|
685
|
+
blocks.push(`_Not attributed to a role: ${table.unattributed.signals} signal row(s), ${table.unattributed.unknownBindings} unknown binding(s)._`);
|
|
686
|
+
}
|
|
687
|
+
return blocks.join("\n\n") + "\n";
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// ---------------------------------------------------------------------------
|
|
691
|
+
// Arguments and CLI
|
|
692
|
+
// ---------------------------------------------------------------------------
|
|
693
|
+
|
|
694
|
+
export interface StatsArgs {
|
|
695
|
+
readonly since: number | null;
|
|
696
|
+
readonly until: number | null;
|
|
697
|
+
readonly json: boolean;
|
|
698
|
+
readonly dir: string | null;
|
|
699
|
+
readonly help: boolean;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
export type ParseStatsResult =
|
|
703
|
+
| { readonly ok: true; readonly args: StatsArgs }
|
|
704
|
+
| { readonly ok: false; readonly error: string };
|
|
705
|
+
|
|
706
|
+
export const USAGE = [
|
|
707
|
+
"Usage: node scripts/routing-stats.ts [--since <ISO>] [--until <ISO>] [--json] [--dir <path>]",
|
|
708
|
+
" or: npm run routing:stats -- [--since <ISO>] [--until <ISO>] [--json] [--dir <path>]",
|
|
709
|
+
` (PowerShell swallows a bare "--": write npm run routing:stats '--' --since <ISO>)`,
|
|
710
|
+
" --since <ISO> include rows with ts >= since (YYYY-MM-DD, or date-time with Z or an offset)",
|
|
711
|
+
" --until <ISO> include rows with ts < until",
|
|
712
|
+
" --json print the StatsTable as JSON",
|
|
713
|
+
" --dir <path> outcome directory, resolved like routing.outcomes.path: ~ is the home directory and a",
|
|
714
|
+
" relative path is taken under <os tmpdir>/opencode-model-router-trajectory",
|
|
715
|
+
" (default: <os tmpdir>/opencode-model-router-trajectory)",
|
|
716
|
+
"",
|
|
717
|
+
].join("\n");
|
|
718
|
+
|
|
719
|
+
const ISO_RE = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,3})?)?(Z|[+-](\d{2}):(\d{2})))?$/;
|
|
720
|
+
|
|
721
|
+
function daysInMonth(year: number, month: number): number {
|
|
722
|
+
return new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/** 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). */
|
|
726
|
+
function parseInstant(flag: string, value: string): { readonly ms: number } | { readonly error: string } {
|
|
727
|
+
const m = ISO_RE.exec(value);
|
|
728
|
+
if (m === null) {
|
|
729
|
+
return {
|
|
730
|
+
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)`,
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
const year = Number(m[1]);
|
|
734
|
+
const month = Number(m[2]);
|
|
735
|
+
const day = Number(m[3]);
|
|
736
|
+
const hour = m[4] === undefined ? 0 : Number(m[4]);
|
|
737
|
+
const minute = m[5] === undefined ? 0 : Number(m[5]);
|
|
738
|
+
const second = m[6] === undefined ? 0 : Number(m[6]);
|
|
739
|
+
const offsetHour = m[8] === undefined ? 0 : Number(m[8]);
|
|
740
|
+
const offsetMinute = m[9] === undefined ? 0 : Number(m[9]);
|
|
741
|
+
const calendarOk =
|
|
742
|
+
month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month) && hour <= 23 && minute <= 59 && second <= 59 && offsetHour <= 23 && offsetMinute <= 59;
|
|
743
|
+
const ms = calendarOk ? Date.parse(value) : Number.NaN;
|
|
744
|
+
if (!Number.isFinite(ms)) return { error: `invalid ${flag} value "${value}": not a real date` };
|
|
745
|
+
return { ms };
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/** `--since <v>`/`--since=<v>` (also `--until`, `--dir`), `--json`, `--help`/`-h`. Repeats, unknown arguments and an empty window are errors. */
|
|
749
|
+
export function parseStatsArgs(argv: readonly string[]): ParseStatsResult {
|
|
750
|
+
let since: number | null = null;
|
|
751
|
+
let until: number | null = null;
|
|
752
|
+
let json = false;
|
|
753
|
+
let dir: string | null = null;
|
|
754
|
+
let help = false;
|
|
755
|
+
const seen = new Set<string>();
|
|
756
|
+
|
|
757
|
+
for (let i = 0; i < argv.length; i++) {
|
|
758
|
+
const arg = argv[i] as string;
|
|
759
|
+
const eq = arg.startsWith("--") ? arg.indexOf("=") : -1;
|
|
760
|
+
const rawName = eq > 0 ? arg.slice(0, eq) : arg;
|
|
761
|
+
const inline = eq > 0 ? arg.slice(eq + 1) : null;
|
|
762
|
+
const name = rawName === "-h" ? "--help" : rawName;
|
|
763
|
+
|
|
764
|
+
if (name === "--json" || name === "--help") {
|
|
765
|
+
if (inline !== null) return { ok: false, error: `${name} does not take a value` };
|
|
766
|
+
if (seen.has(name)) return { ok: false, error: `${name} given more than once` };
|
|
767
|
+
seen.add(name);
|
|
768
|
+
if (name === "--json") json = true;
|
|
769
|
+
else help = true;
|
|
770
|
+
continue;
|
|
771
|
+
}
|
|
772
|
+
if (name !== "--since" && name !== "--until" && name !== "--dir") return { ok: false, error: `unknown argument: ${arg}` };
|
|
773
|
+
if (seen.has(name)) return { ok: false, error: `${name} given more than once` };
|
|
774
|
+
seen.add(name);
|
|
775
|
+
|
|
776
|
+
let value: string | null = inline;
|
|
777
|
+
if (value === null) {
|
|
778
|
+
const next = argv[i + 1];
|
|
779
|
+
if (next !== undefined && !next.startsWith("--")) {
|
|
780
|
+
value = next;
|
|
781
|
+
i += 1;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
if (value === null || value === "") return { ok: false, error: `${name} requires a value` };
|
|
785
|
+
|
|
786
|
+
if (name === "--dir") {
|
|
787
|
+
dir = value;
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
const parsed = parseInstant(name, value);
|
|
791
|
+
if ("error" in parsed) return { ok: false, error: parsed.error };
|
|
792
|
+
if (name === "--since") since = parsed.ms;
|
|
793
|
+
else until = parsed.ms;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
if (since !== null && until !== null && since >= until) {
|
|
797
|
+
return { ok: false, error: "--since must be earlier than --until" };
|
|
798
|
+
}
|
|
799
|
+
return { ok: true, args: { since, until, json, dir, help } };
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
function messageOf(error: unknown): string {
|
|
803
|
+
return error instanceof Error ? error.message : String(error);
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* `routing:stats` driver. Read-only: loads without quarantine, cleanup or mkdir. Never throws:
|
|
808
|
+
* a usage error exits 2, a corrupt or too-new store exits 1 with a clear message, an unexpected error
|
|
809
|
+
* writes `routing-stats: <message>` and exits 1. A missing store is an empty table with exit 0.
|
|
810
|
+
*/
|
|
811
|
+
export async function runStatsCli(argv: readonly string[], io: StatsCliIO): Promise<number> {
|
|
812
|
+
try {
|
|
813
|
+
const parsed = parseStatsArgs(argv);
|
|
814
|
+
if (!parsed.ok) {
|
|
815
|
+
io.stderr(`routing-stats: ${parsed.error}\n${USAGE}`);
|
|
816
|
+
return STATS_EXIT.usage;
|
|
817
|
+
}
|
|
818
|
+
const { args } = parsed;
|
|
819
|
+
if (args.help) {
|
|
820
|
+
io.stdout(USAGE);
|
|
821
|
+
return STATS_EXIT.ok;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
const source = io.open(args.dir ?? io.defaultDir);
|
|
825
|
+
const loaded = await source.load({ quarantine: false });
|
|
826
|
+
if (loaded.status === "corrupt" || loaded.status === "unsupported-version") {
|
|
827
|
+
io.stderr(`routing-stats: corrupted outcome store: ${loaded.message ?? loaded.status}\n`);
|
|
828
|
+
return STATS_EXIT.corrupt;
|
|
829
|
+
}
|
|
830
|
+
if (loaded.dropped > 0) io.stderr(`routing-stats: warning: ${loaded.message ?? `${loaded.dropped} invalid store entries dropped`}\n`);
|
|
831
|
+
|
|
832
|
+
const store = createOutcomeStore();
|
|
833
|
+
if (loaded.status === "ok") store.fromSnapshot(loaded.snapshot);
|
|
834
|
+
const read = await source.readRows();
|
|
835
|
+
if (loaded.status === "missing" && read.files.length === 0) {
|
|
836
|
+
// Not an error (a fresh install has nothing yet), but a typo in --dir looks exactly like this (QA-1.3-5).
|
|
837
|
+
io.stderr(`routing-stats: no outcome data in ${source.dir}\n`);
|
|
838
|
+
}
|
|
839
|
+
if (read.skipped > 0) io.stderr(`routing-stats: skipped ${read.skipped} unreadable decision-log line(s)\n`);
|
|
840
|
+
if (
|
|
841
|
+
read.generations >= DECISIONS_MAX_GENERATIONS &&
|
|
842
|
+
read.oldestTs !== null &&
|
|
843
|
+
(args.since === null || args.since < Date.parse(read.oldestTs))
|
|
844
|
+
) {
|
|
845
|
+
// Rotation prunes only beyond DECISIONS_MAX_GENERATIONS rotated files, so fewer than that means nothing has
|
|
846
|
+
// been dropped yet (QA-1.3-19). At the limit, history before the oldest retained row may be gone (QA-1.3-10).
|
|
847
|
+
io.stderr(
|
|
848
|
+
`routing-stats: warning: the decision log has rotated; its oldest retained row is ${read.oldestTs}, so ${
|
|
849
|
+
args.since === null ? "an unbounded" : "this"
|
|
850
|
+
} window may be incomplete\n`,
|
|
851
|
+
);
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
const table = summarize(store, read.rows, { since: args.since, until: args.until });
|
|
855
|
+
const roles = summarizeRoles(store, read.rows, { since: args.since, until: args.until });
|
|
856
|
+
const withRoles = hasRoleRows(roles);
|
|
857
|
+
io.stdout(
|
|
858
|
+
args.json
|
|
859
|
+
? JSON.stringify(withRoles ? { ...table, roles } : table, null, 2) + "\n"
|
|
860
|
+
: withRoles
|
|
861
|
+
? `${renderMarkdown(table)}\n${renderRoleMarkdown(roles)}`
|
|
862
|
+
: renderMarkdown(table),
|
|
863
|
+
);
|
|
864
|
+
return STATS_EXIT.ok;
|
|
865
|
+
} catch (error) {
|
|
866
|
+
try {
|
|
867
|
+
io.stderr(`routing-stats: ${messageOf(error)}\n`);
|
|
868
|
+
} catch {
|
|
869
|
+
return STATS_EXIT.corrupt;
|
|
870
|
+
}
|
|
871
|
+
return STATS_EXIT.corrupt;
|
|
872
|
+
}
|
|
873
|
+
}
|