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.
Files changed (83) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +90 -12
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +24 -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 +1435 -44
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +496 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/guard/enforce.ts +186 -22
  13. package/src/guard/guards.ts +132 -6
  14. package/src/guard/store.ts +5 -0
  15. package/src/index.ts +1193 -56
  16. package/src/router/build-info.ts +151 -0
  17. package/src/router/config.ts +1611 -19
  18. package/src/router/dispatch-header.ts +46 -4
  19. package/src/router/git-tools.ts +1152 -0
  20. package/src/router/guard-profile.ts +100 -0
  21. package/src/router/plugin-agents.ts +433 -0
  22. package/src/router/prompts.ts +26 -1
  23. package/src/router/protocol.ts +180 -0
  24. package/src/router/read-only.ts +149 -0
  25. package/src/router/role-agents.ts +409 -0
  26. package/src/router/roles-config.ts +429 -0
  27. package/src/router/roles.ts +600 -0
  28. package/src/router/run-tools.ts +913 -0
  29. package/src/router/sensitive-paths.ts +101 -0
  30. package/src/router/sessions.ts +533 -9
  31. package/src/router/subagents.ts +28 -1
  32. package/src/routing/advisor/findings.ts +898 -0
  33. package/src/routing/advisor/index.ts +614 -0
  34. package/src/routing/classify/backends/host.ts +163 -0
  35. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  36. package/src/routing/classify/backends/shared.ts +741 -0
  37. package/src/routing/classify/backends/typesafe.ts +315 -0
  38. package/src/routing/classify/fences.ts +96 -0
  39. package/src/routing/classify/index.ts +594 -0
  40. package/src/routing/classify/route-line.ts +362 -0
  41. package/src/routing/classify/rules.ts +667 -0
  42. package/src/routing/classify/scrub.ts +214 -0
  43. package/src/routing/classify/state.ts +148 -0
  44. package/src/routing/classify/text.ts +20 -0
  45. package/src/routing/classify/types.ts +1310 -0
  46. package/src/routing/commands/annotate-plan.ts +652 -0
  47. package/src/routing/commands/stats.ts +134 -0
  48. package/src/routing/commands/v1-roles.ts +64 -0
  49. package/src/routing/engine/index.ts +32 -0
  50. package/src/routing/engine/kernel.ts +760 -0
  51. package/src/routing/engine/ladders.ts +802 -0
  52. package/src/routing/engine/plan.ts +404 -0
  53. package/src/routing/engine/protocol-line.ts +150 -0
  54. package/src/routing/engine/roles-taxonomy.ts +52 -0
  55. package/src/routing/engine/simulate.ts +167 -0
  56. package/src/routing/engine/types.ts +368 -0
  57. package/src/routing/file-lock.ts +53 -0
  58. package/src/routing/outcomes/beta.ts +147 -0
  59. package/src/routing/outcomes/cost.ts +313 -0
  60. package/src/routing/outcomes/index.ts +215 -0
  61. package/src/routing/outcomes/ingest.ts +960 -0
  62. package/src/routing/outcomes/persist.ts +1080 -0
  63. package/src/routing/outcomes/signals.ts +650 -0
  64. package/src/routing/outcomes/stats.ts +873 -0
  65. package/src/routing/outcomes/store.ts +673 -0
  66. package/src/routing/outcomes/types.ts +1093 -0
  67. package/src/routing/roles/authority.ts +495 -0
  68. package/src/routing/roles/binding.ts +543 -0
  69. package/src/routing/roles/policy.ts +416 -0
  70. package/src/routing/roles/work-root.ts +132 -0
  71. package/src/routing/wire/dispatch.ts +2088 -0
  72. package/src/routing/wire/hint.ts +222 -0
  73. package/src/routing/wire/host-info.ts +256 -0
  74. package/src/routing/wire/runtime.ts +348 -0
  75. package/src/v2.ts +40 -1
  76. package/src/verify/checker.ts +249 -7
  77. package/src/verify/deterministic.ts +10 -1
  78. package/src/verify/dispatch.ts +63 -6
  79. package/src/verify/dod.ts +127 -10
  80. package/src/verify/gate.ts +75 -7
  81. package/src/verify/types.ts +12 -0
  82. package/src/verify/wiring.ts +55 -10
  83. package/tiers.json +13 -5
@@ -0,0 +1,960 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Telemetry ingestion (M6, plan 2.1.2) — child-session outcomes and costs → outcome store.
3
+ //
4
+ // Signals handled (OpenCode v2 only, D1):
5
+ // - `session.step.ended` of a registered child → `store.recordStep` (cost and tokens, D6/A1)
6
+ // - a verifier verdict → `store.recordVerdict` + a `VerdictRow`
7
+ // - a false-refusal observation → `store.recordFalseRefusal` + a `RefusalRow`
8
+ // - a session that went away → open attempts folded, registry entries forgotten
9
+ //
10
+ // Rules (docs/qa/cost-aware-routing/phase-1.2.md, phase-1.3.md "to 2.1"):
11
+ // - Nothing happens unless `routing.engine !== "static"` (§1.2: no new files in static mode). The
12
+ // outcomes bundle is acquired lazily, on the first signal that is actually recorded.
13
+ // - Only children registered with `rememberDispatch` are recorded (`src/router/sessions.ts`).
14
+ // - Never record under a class whose `facts.confidence < routing.minClassConfidence`, and never under
15
+ // a backend label: the registry only ever holds `facts.class` (A19, QA-1.2-27). Such a dispatch has
16
+ // no store call and no verdict/refusal row.
17
+ // - The same `session.step.ended` (same event id) reaches every live location's plugin instance (S3b,
18
+ // A3): a module-scope LRU of event ids counts it once. The registry, the dedupe state and the store
19
+ // bundle (`acquireOutcomes`) are all process-wide; there is one writer per process.
20
+ // - Never on a dispatch's hot path: handlers only update memory and enqueue rows; the flusher writes
21
+ // (D15: on session idle/deleted and at most every 30 s, coalesced).
22
+ // - Errors are logged and swallowed (§0.10.10); a handler never throws into a session or the event loop.
23
+ // ---------------------------------------------------------------------------
24
+
25
+ import { homedir, tmpdir } from "node:os";
26
+ import type { RouterConfig, RouterHost } from "../../router/config";
27
+ import { resolveCandidates, resolveRouting } from "../../router/config";
28
+ import { getActiveTiers } from "../../router/protocol";
29
+ import {
30
+ forgetDispatch,
31
+ forgetDispatchesOf,
32
+ lookupDispatch,
33
+ noteExecutionEnded,
34
+ noteStepContext,
35
+ sweepDispatches,
36
+ touchDispatch,
37
+ } from "../../router/sessions";
38
+ import { stepContextTokens } from "../../escalate/variants";
39
+ import type { DispatchRecord } from "../../router/sessions";
40
+ import type { AcquireOutcomesOptions } from "./index";
41
+ import { acquireOutcomes } from "./index";
42
+ import { pricingState, tokenSampleFromEvent } from "./cost";
43
+ import { resolveOutcomesDir } from "./persist";
44
+ import { roleTierOrder } from "../engine/ladders";
45
+ import type { SignalObservation, TierRung } from "./signals";
46
+ import { SIGNAL_MASS_CAPS, graderSignal, isSignalObservation, signalRow, tierOfModel, verdictSignal } from "./signals";
47
+ import type {
48
+ AgentOrigin,
49
+ AttemptSignal,
50
+ Clock,
51
+ LoggedRoutingMode,
52
+ ModelPricing,
53
+ OutcomeKey,
54
+ OutcomeLogger,
55
+ OutcomesBundle,
56
+ OutcomeTuning,
57
+ RefusalRow,
58
+ OutcomeStore,
59
+ StepEndedTokens,
60
+ StepSample,
61
+ Verdict,
62
+ VerdictGrader,
63
+ VerdictRow,
64
+ } from "./types";
65
+ import { LOG_ROW_VERSION, classifyAgentOrigin, makeKey, normalizeVariant, safeNow, splitModelRef } from "./types";
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // Settings
69
+ // ---------------------------------------------------------------------------
70
+
71
+ /** What ingestion needs from the resolved config. `null` from {@link ingestSettings} = ingestion is off. */
72
+ export interface IngestSettings {
73
+ /** Never `static`: a static engine has no settings at all. */
74
+ readonly engine: LoggedRoutingMode;
75
+ readonly minClassConfidence: number;
76
+ /** Resolved outcomes directory (`routing.outcomes.path`, else the scorecard directory). */
77
+ readonly outcomesDir: string;
78
+ readonly tuning: OutcomeTuning;
79
+ /** Ids of the active preset's router tier agents (origin `router`); every other agent is `host`. */
80
+ readonly routerAgentIds: ReadonlySet<string>;
81
+ /**
82
+ * P1.4: agent names of the resolved role agents (origin `role`, key `class|role:<agent>|…`). Absent or empty in tiers
83
+ * mode and on v1, so keys stay `router`/`host` there. Filled by P2.1 from `resolveRoles`.
84
+ */
85
+ readonly roleAgentIds?: ReadonlySet<string>;
86
+ /**
87
+ * #84 P3.3 fix 2: the tier order of role dispatches (`roleTierOrder`, cheapest first) and its rungs, which rank a grader
88
+ * against the producer (plan §2.6: grader tier ≥ producer tier). Absent or empty: no grader is ever independent.
89
+ */
90
+ readonly tierOrder?: readonly string[];
91
+ readonly tierRungs?: readonly TierRung[];
92
+ }
93
+
94
+ /** The role tier order of `cfg` and its rungs (empty without a config). */
95
+ function tierLadderOf(cfg: RouterConfig | undefined): { readonly tierOrder: readonly string[]; readonly tierRungs: readonly TierRung[] } {
96
+ if (cfg === undefined) return { tierOrder: [], tierRungs: [] };
97
+ const tierOrder = Object.freeze([...roleTierOrder(cfg)]);
98
+ const tierRungs = Object.freeze(tierOrder.flatMap((tier) =>
99
+ resolveCandidates(tier, cfg).map((rung): TierRung => Object.freeze({ tier, model: rung.model, variant: rung.variant ?? null }))));
100
+ return { tierOrder, tierRungs };
101
+ }
102
+
103
+ const settingsCache = new WeakMap<RouterConfig, IngestSettings | null>();
104
+
105
+ /**
106
+ * Ingestion settings for `cfg` on `host`, or `null` when ingestion must do nothing: any host but v2 (D1) and
107
+ * `routing.engine === "static"` (§1.2). Cached per config object (hot reload builds a new object).
108
+ */
109
+ export function ingestSettings(cfg: RouterConfig | undefined, host: RouterHost): IngestSettings | null {
110
+ if (host !== "v2") return null;
111
+ const cached = cfg === undefined ? undefined : settingsCache.get(cfg);
112
+ if (cached !== undefined) return cached;
113
+ const routing = resolveRouting(cfg, host);
114
+ let settings: IngestSettings | null = null;
115
+ const engine = routing.engine;
116
+ if (engine !== "static") {
117
+ settings = Object.freeze({
118
+ engine,
119
+ minClassConfidence: routing.minClassConfidence,
120
+ outcomesDir: resolveOutcomesDir(routing.outcomes.path, { tmpdir: tmpdir(), homedir: homedir() }),
121
+ tuning: Object.freeze({
122
+ halfLifeDays: routing.outcomes.halfLifeDays,
123
+ maxEffectiveSamples: routing.outcomes.maxEffectiveSamples,
124
+ }),
125
+ routerAgentIds: new Set(cfg === undefined ? [] : Object.keys(getActiveTiers(cfg))),
126
+ ...tierLadderOf(cfg),
127
+ });
128
+ }
129
+ if (cfg !== undefined) settingsCache.set(cfg, settings);
130
+ return settings;
131
+ }
132
+
133
+ // ---------------------------------------------------------------------------
134
+ // Catalog pricing (A1/A10): supplied from the catalog lookup the v2 adapter already uses (`ctx.model.list`)
135
+ // ---------------------------------------------------------------------------
136
+
137
+ /** The part of a host catalog model that pricing needs (`Model.Info` is assignable). */
138
+ export interface CatalogModel {
139
+ readonly providerID: string;
140
+ readonly id: string;
141
+ readonly cost?: unknown;
142
+ }
143
+
144
+ export type PricingLookup = (provider: string, model: string) => Promise<ModelPricing>;
145
+
146
+ export interface CatalogPricingOptions {
147
+ readonly now?: Clock;
148
+ readonly logger?: OutcomeLogger;
149
+ /** How long a loaded catalog is fresh (default 60 s); after that it is served stale while it reloads in the background. */
150
+ readonly ttlMs?: number;
151
+ /** After a failed or timed-out load, wait this long before trying again (default 15 s). */
152
+ readonly retryMs?: number;
153
+ /** The longest a lookup waits for the very first load of a catalog (default 2 s); then it answers `unpriced` (QA-2.1-5). */
154
+ readonly loadTimeoutMs?: number;
155
+ /** Shutdown: lookups waiting for a load return at once. The shared load itself is not cancelled. */
156
+ readonly signal?: AbortSignal;
157
+ /**
158
+ * Share the table, the in-flight load and the back-off with every lookup created with the same key, in the whole
159
+ * process (QA-2.1-2): the location directory. The first creator's `list` serves them all. Without a key the lookup
160
+ * has a private cache.
161
+ */
162
+ readonly cacheKey?: string;
163
+ }
164
+
165
+ interface CatalogLoad {
166
+ readonly promise: Promise<void>;
167
+ readonly startedAt: number;
168
+ /** A lookup stopped waiting for it (timeout). It stays pending: no other load starts while it does (QA-2.1-R2-4). */
169
+ abandoned: boolean;
170
+ }
171
+
172
+ interface CatalogState {
173
+ table: Map<string, ModelPricing>;
174
+ loadedAt: number | null;
175
+ failedAt: number | null;
176
+ loading: CatalogLoad | null;
177
+ /** A lookup has timed out once: none waits again, however many loads follow, until one has succeeded (QA-2.1-R2-4). */
178
+ timedOut: boolean;
179
+ }
180
+
181
+ const sharedCatalogs = new Map<string, CatalogState>();
182
+
183
+ /** Test-only: forget every shared catalog cache. */
184
+ export function resetCatalogPricing(): void {
185
+ sharedCatalogs.clear();
186
+ }
187
+
188
+ function asPricing(value: unknown): ModelPricing {
189
+ return typeof value === "object" && value !== null ? (value as ModelPricing) : undefined;
190
+ }
191
+
192
+ /**
193
+ * Cached `provider/model → catalog cost` lookup over `list`. A model that is absent, a failed or slow first load, or
194
+ * a lookup that was aborted gives `undefined`, which {@link pricingState} reads as `unpriced` (A1): a `0` cost is then
195
+ * stored as unknown and only a positive host-reported cost is kept.
196
+ *
197
+ * It never blocks the serial event loop for long (QA-2.1-5): once a table has loaded it is served immediately, stale
198
+ * after the TTL while it reloads in the background; only the first lookup of a cold catalog waits, for at most
199
+ * `loadTimeoutMs` and never past `signal`. After one timeout nobody waits again until a load has succeeded, and a load
200
+ * that timed out stays pending: no second `list()` starts behind it (QA-2.1-R2-4). A failed load backs off for
201
+ * `retryMs`. Never rejects.
202
+ */
203
+ export function createCatalogPricing(
204
+ list: () => Promise<readonly CatalogModel[]>,
205
+ options: CatalogPricingOptions = {},
206
+ ): PricingLookup {
207
+ const now = options.now ?? Date.now;
208
+ const ttlMs = options.ttlMs ?? 60_000;
209
+ const retryMs = options.retryMs ?? 15_000;
210
+ const loadTimeoutMs = options.loadTimeoutMs ?? 2_000;
211
+ const { signal, logger } = options;
212
+ let state: CatalogState | undefined = options.cacheKey === undefined ? undefined : sharedCatalogs.get(options.cacheKey);
213
+ if (state === undefined) {
214
+ state = { table: new Map(), loadedAt: null, failedAt: null, loading: null, timedOut: false };
215
+ if (options.cacheKey !== undefined) sharedCatalogs.set(options.cacheKey, state);
216
+ }
217
+ const shared = state;
218
+
219
+ const startLoad = (t: number): CatalogLoad => {
220
+ const run = async (): Promise<void> => {
221
+ try {
222
+ const models = await list();
223
+ const next = new Map<string, ModelPricing>();
224
+ for (const model of models) next.set(`${model.providerID}/${model.id}`, asPricing(model.cost));
225
+ shared.table = next;
226
+ shared.loadedAt = safeNow(now);
227
+ shared.failedAt = null;
228
+ shared.timedOut = false;
229
+ } catch (error) {
230
+ shared.failedAt = safeNow(now);
231
+ logger?.warn("[router] outcome ingestion: model catalog unavailable; step costs treated as unpriced", {
232
+ error: describe(error),
233
+ });
234
+ }
235
+ };
236
+ const load: CatalogLoad = {
237
+ startedAt: t,
238
+ abandoned: false,
239
+ promise: run().finally(() => {
240
+ if (shared.loading === load) shared.loading = null;
241
+ }),
242
+ };
243
+ shared.loading = load;
244
+ return load;
245
+ };
246
+
247
+ /** Wait for `load`, but not longer than `loadTimeoutMs` and not past an abort. */
248
+ const waitFor = (load: CatalogLoad): Promise<"done" | "timeout" | "aborted"> => {
249
+ if (signal?.aborted === true) return Promise.resolve("aborted");
250
+ return new Promise<"done" | "timeout" | "aborted">((resolve) => {
251
+ const onAbort = (): void => finish("aborted");
252
+ const timer = setTimeout(() => finish("timeout"), loadTimeoutMs);
253
+ timer.unref();
254
+ const finish = (outcome: "done" | "timeout" | "aborted"): void => {
255
+ clearTimeout(timer);
256
+ signal?.removeEventListener("abort", onAbort);
257
+ resolve(outcome);
258
+ };
259
+ signal?.addEventListener("abort", onAbort, { once: true });
260
+ void load.promise.then(() => finish("done"));
261
+ });
262
+ };
263
+
264
+ return async (provider, model) => {
265
+ const t = safeNow(now);
266
+ const fresh = shared.loadedAt !== null && t - shared.loadedAt < ttlMs;
267
+ if (!fresh) {
268
+ const backingOff = shared.failedAt !== null && t - shared.failedAt < retryMs;
269
+ let load = shared.loading;
270
+ if (load === null && !backingOff) load = startLoad(t);
271
+ if (shared.loadedAt === null && load !== null && !load.abandoned && !shared.timedOut) {
272
+ const outcome = await waitFor(load);
273
+ if (outcome === "timeout" && shared.loadedAt === null) {
274
+ load.abandoned = true;
275
+ shared.timedOut = true;
276
+ shared.failedAt = safeNow(now);
277
+ logger?.warn("[router] outcome ingestion: model catalog is slow; step costs treated as unpriced", { loadTimeoutMs });
278
+ }
279
+ }
280
+ }
281
+ return shared.table.get(`${provider}/${model}`);
282
+ };
283
+ }
284
+ // ---------------------------------------------------------------------------
285
+ // Module-scope state (A3: shared by every plugin instance of the process)
286
+ // ---------------------------------------------------------------------------
287
+
288
+ /** Event ids remembered for the duplicate-delivery dedupe (LRU). */
289
+ export const SEEN_EVENT_CAP = 4096;
290
+ /** Signals (verdict/refusal rows) remembered so a repeated signal enqueues one row. */
291
+ const SIGNAL_CAP = 4096;
292
+ /** Children whose last attempt id is tracked (so a superseded attempt can be folded). */
293
+ const LAST_ATTEMPT_CAP = 2000;
294
+ /** Final steps held back until their attempt ends (QA-2.1-6). */
295
+ const HELD_FINAL_CAP = 2000;
296
+ /** A held final step whose attempt never reported its end is folded after this idle time (the store's own default). */
297
+ const HELD_FINAL_IDLE_MS = 30 * 60_000;
298
+ /** Model references already reported as unkeyable (model unresolved), one warning each. */
299
+ const WARNED_CAP = 500;
300
+
301
+ const seenEvents = new Map<string, true>();
302
+ const signalled = new Set<string>();
303
+ /** What scored each attempt in the store (`pass`, `fail` or `refusal`), so a refusal knows whether it converts a pass. */
304
+ const scored = new Map<string, "pass" | "fail" | "refusal">();
305
+ /** `${outcomesDir}|${child}` → the attempt the child's latest step belongs to (a store in another directory is another recording). */
306
+ const lastAttemptByChild = new Map<string, LastAttempt>();
307
+ const warnedUnkeyed = new Set<string>();
308
+
309
+ interface LastAttempt {
310
+ readonly dir: string;
311
+ readonly attempt: string;
312
+ }
313
+
314
+ interface HeldFinal {
315
+ readonly dir: string;
316
+ readonly attempt: string;
317
+ readonly key: OutcomeKey;
318
+ /** Already marked `final`: recorded as such when the attempt ends. */
319
+ readonly sample: StepSample;
320
+ readonly at: number;
321
+ }
322
+ /**
323
+ * QA-2.1-6: a step that finished with anything but `tool-calls` only sets the attempt's `finalOutput`; the attempt
324
+ * stays open (a `length` or `error` finish may be followed by more steps) and is folded when its execution ends. The
325
+ * step is held here, outside the store, until the next step of the attempt (then it was not the last), the end of the
326
+ * execution, the session's deletion, a sweep or a dispose.
327
+ */
328
+ const heldFinals = new Map<string, HeldFinal>();
329
+
330
+ function boundedSet<V>(map: Map<string, V>, key: string, value: V, cap: number): void {
331
+ map.delete(key);
332
+ map.set(key, value);
333
+ while (map.size > cap) {
334
+ const oldest = map.keys().next();
335
+ if (oldest.done === true) break;
336
+ map.delete(oldest.value);
337
+ }
338
+ }
339
+
340
+ function boundedAdd(set: Set<string>, value: string, cap: number): boolean {
341
+ if (set.has(value)) return false;
342
+ set.add(value);
343
+ while (set.size > cap) {
344
+ const oldest = set.values().next();
345
+ if (oldest.done === true) break;
346
+ set.delete(oldest.value);
347
+ }
348
+ return true;
349
+ }
350
+
351
+ /** True the first time an event id is seen. A repeat refreshes its recency (LRU). */
352
+ function firstDelivery(eventKey: string): boolean {
353
+ if (seenEvents.has(eventKey)) {
354
+ seenEvents.delete(eventKey);
355
+ seenEvents.set(eventKey, true);
356
+ return false;
357
+ }
358
+ seenEvents.set(eventKey, true);
359
+ while (seenEvents.size > SEEN_EVENT_CAP) {
360
+ const oldest = seenEvents.keys().next();
361
+ if (oldest.done === true) break;
362
+ seenEvents.delete(oldest.value);
363
+ }
364
+ return true;
365
+ }
366
+
367
+ const scopeKey = (dir: string, id: string): string => `${dir}|${id}`;
368
+
369
+ function rememberAttempt(dir: string, child: string, attemptId: string): string | undefined {
370
+ const mapKey = scopeKey(dir, child);
371
+ const previous = lastAttemptByChild.get(mapKey)?.attempt;
372
+ lastAttemptByChild.delete(mapKey);
373
+ lastAttemptByChild.set(mapKey, { dir, attempt: attemptId });
374
+ while (lastAttemptByChild.size > LAST_ATTEMPT_CAP) {
375
+ const oldest = lastAttemptByChild.keys().next();
376
+ if (oldest.done === true) break;
377
+ lastAttemptByChild.delete(oldest.value);
378
+ }
379
+ return previous;
380
+ }
381
+
382
+ /** Test-only: drop the module-scope dedupe and attempt state (the dispatch registry has its own reset). */
383
+ export function resetIngestState(): void {
384
+ resetCatalogPricing();
385
+ seenEvents.clear();
386
+ signalled.clear();
387
+ scored.clear();
388
+ lastAttemptByChild.clear();
389
+ warnedUnkeyed.clear();
390
+ heldFinals.clear();
391
+ }
392
+
393
+ // ---------------------------------------------------------------------------
394
+ // Ingest
395
+ // ---------------------------------------------------------------------------
396
+
397
+ /** A v2 event as delivered by `ctx.event.subscribe` (only what ingestion reads). */
398
+ export interface IngestEvent {
399
+ readonly id?: unknown;
400
+ readonly type: string;
401
+ readonly data?: unknown;
402
+ }
403
+
404
+ export interface IngestDeps {
405
+ /** Settings for the current call; `null` = ingestion off. Called per event, so it must be cheap (cache by config). */
406
+ readonly settings: () => IngestSettings | null;
407
+ readonly logger: OutcomeLogger;
408
+ /** Catalog pricing of `provider`/`model`; absent → every step is priced as `unpriced` (A1). Only step events use it. */
409
+ readonly pricing?: PricingLookup;
410
+ /** Clock for row timestamps (default `Date.now`). */
411
+ readonly now?: Clock;
412
+ /** Seam over `acquireOutcomes` (tests pass injected deps/scheduler through). */
413
+ readonly acquire?: (options: AcquireOutcomesOptions) => OutcomesBundle;
414
+ }
415
+
416
+ /** P1.4: options of {@link Ingest.onSignal}. */
417
+ export interface SignalOptions {
418
+ /**
419
+ * The decision id of the attempt the signal is about; the child's current registration must carry it, else nothing is
420
+ * written (a re-registered or evicted child). Required for `redispatch` (the previous attempt, `RedispatchMatch.previous`).
421
+ */
422
+ readonly expectDecisionID?: string;
423
+ }
424
+
425
+ export interface Ingest {
426
+ /**
427
+ * `session.step.ended` (and `session.step.failed`, when it carries a cost or tokens) of a registered child. Awaits
428
+ * only the cached catalog lookup, bounded by its load timeout. Never rejects.
429
+ */
430
+ onStepEnded(event: IngestEvent): Promise<void>;
431
+ /**
432
+ * The child's execution ended (succeeded, failed or interrupted): its open attempt is folded (QA-2.1-6) and its
433
+ * registration is marked ended for the delegate ladder (QA-2.3-2). `eventId` is the host event's id: a copy of the
434
+ * same event delivered again (to another plugin instance, perhaps after the child was registered again) is ignored
435
+ * (QA-2.3-R2-1). Without an id every delivery is applied.
436
+ */
437
+ onExecutionEnded(childSessionID: string, eventId?: unknown): void;
438
+ /**
439
+ * A verifier verdict for the child's current attempt. Never throws. `grader` (#84 P3.3 fix 2, `verdictGraderOf`; always passed,
440
+ * `undefined` = deterministic checks): the LLM grader that judged the verdict. Tier and host dispatches: the store and the
441
+ * verdict row take it either way, at full weight (unchanged, I1). A ROLE dispatch's grader verdict (plan §2.6, I6,
442
+ * QA-P33F2-1-1) moves the store at 0.5 with a verdict row and a `grader` signal row only when the grader is independent (tier
443
+ * ≥ the producer's and another model); otherwise nothing at all — no store change, no verdict row, no signal row.
444
+ */
445
+ onVerdict(childSessionID: string, outcome: Verdict, grader: VerdictGrader | undefined): void;
446
+ /** A false refusal (zero tool calls) observed for the child's current attempt. Never throws. */
447
+ onFalseRefusal(childSessionID: string): void;
448
+ /**
449
+ * P1.4: append a signal row (signals.ts) for the child's current attempt. Rows only: the Beta store, its decay and the
450
+ * verdict/refusal rows are untouched. `verdict` and `grader` are refused (`onVerdict` writes them when the store takes the
451
+ * verdict; QA-P33F2-1 N2);
452
+ * `redispatch` needs `expectDecisionID`. Gated like a verdict (registered, keyable, trusted class), except that the
453
+ * zero-mass kinds (`budget`, `authority`) are written under class `unknown` when the class is not trusted. The dispatch
454
+ * must have a decision id (the row annotates its decision row). One row per attempt and kind (C7: a repeat, even with
455
+ * another outcome, writes nothing). Returns whether a row was enqueued. Never throws. Optional only so that existing test
456
+ * doubles still satisfy `Ingest`; `createIngest` and {@link NOOP_INGEST} implement it.
457
+ */
458
+ onSignal?(childSessionID: string, observation: SignalObservation, options?: SignalOptions): boolean;
459
+ /** A session was deleted: the child's open attempt is folded and its registry entry dropped; children of the session too. */
460
+ onSessionGone(sessionID: string): void;
461
+ /** Idle/deleted flush point (D15): coalesced and throttled by the flusher, never awaited. No-op without recorded data. */
462
+ requestFlush(): void;
463
+ /** Opportunistic maintenance for the idle sweeper: expired dispatches, idle open attempts. */
464
+ sweep(): void;
465
+ /** Flush and release this instance's reference to the outcomes bundle. Never rejects. */
466
+ dispose(): Promise<void>;
467
+ }
468
+
469
+ /** Event types after which the router flushes (v2's equivalents of `session.idle`, plus the idle/deleted events). */
470
+ /** An ingest that does nothing (a v2 adapter started without the plugin's own). */
471
+ export const NOOP_INGEST: Ingest = Object.freeze({
472
+ onStepEnded: () => Promise.resolve(),
473
+ onExecutionEnded: () => undefined,
474
+ onVerdict: () => undefined,
475
+ onFalseRefusal: () => undefined,
476
+ onSignal: () => false,
477
+ onSessionGone: () => undefined,
478
+ requestFlush: () => undefined,
479
+ sweep: () => undefined,
480
+ dispose: () => Promise.resolve(),
481
+ });
482
+
483
+ /** The v2 events that end a session's execution (the adapter maps them to `session.idle`). */
484
+ export const EXECUTION_END_TYPES: ReadonlySet<string> = new Set([
485
+ "session.execution.succeeded",
486
+ "session.execution.failed",
487
+ "session.execution.interrupted",
488
+ ]);
489
+
490
+ export const FLUSH_EVENT_TYPES: ReadonlySet<string> = new Set([
491
+ "session.idle",
492
+ "session.deleted",
493
+ ...EXECUTION_END_TYPES,
494
+ ]);
495
+
496
+ function describe(error: unknown): string {
497
+ return error instanceof Error ? error.message : String(error);
498
+ }
499
+
500
+ function isRecord(value: unknown): value is Record<string, unknown> {
501
+ return typeof value === "object" && value !== null && !Array.isArray(value);
502
+ }
503
+
504
+ interface Target {
505
+ readonly record: DispatchRecord;
506
+ readonly settings: IngestSettings;
507
+ readonly key: OutcomeKey;
508
+ readonly origin: AgentOrigin;
509
+ /** `provider/model`. */
510
+ readonly model: string;
511
+ readonly variant: string;
512
+ }
513
+
514
+ export function createIngest(deps: IngestDeps): Ingest {
515
+ const now: Clock = deps.now ?? Date.now;
516
+ const acquire = deps.acquire ?? acquireOutcomes;
517
+ let held: { readonly dir: string; readonly bundle: OutcomesBundle; tuning: OutcomeTuning } | null = null;
518
+ let disposed = false;
519
+
520
+ const warn = (message: string, error: unknown, extra?: Record<string, unknown>): void => {
521
+ deps.logger.warn(`[router] outcome ingestion: ${message}`, { ...extra, error: describe(error) });
522
+ };
523
+
524
+ /** The bundle for `settings.outcomesDir`, acquired on first use; a changed directory re-acquires. */
525
+ const bundleFor = (settings: IngestSettings): OutcomesBundle | null => {
526
+ if (disposed) return null;
527
+ if (held !== null && held.dir === settings.outcomesDir) {
528
+ if (
529
+ held.tuning.halfLifeDays !== settings.tuning.halfLifeDays ||
530
+ held.tuning.maxEffectiveSamples !== settings.tuning.maxEffectiveSamples
531
+ ) {
532
+ held.bundle.store.configure(settings.tuning);
533
+ held.tuning = settings.tuning;
534
+ }
535
+ return held.bundle;
536
+ }
537
+ const previous = held;
538
+ if (previous !== null) settleOwned(); // while `held` still names the old directory
539
+ held = null;
540
+ if (previous !== null) {
541
+ void previous.bundle.release().catch((error: unknown) => warn("releasing the previous outcomes directory failed", error));
542
+ }
543
+ const bundle = acquire({ dir: settings.outcomesDir, tuning: settings.tuning, logger: deps.logger });
544
+ held = { dir: settings.outcomesDir, bundle, tuning: settings.tuning };
545
+ return bundle;
546
+ };
547
+
548
+ /** Registered, trusted and keyable? Otherwise nothing may be recorded for the child. */
549
+ const targetOf = (childSessionID: string, untrusted: "skip" | "unknown" = "skip"): Target | null => {
550
+ // Registry first: most `session.step.ended` events belong to sessions that are not registered children
551
+ // (the orchestrator's own), and the settings may cost a config fingerprint check.
552
+ const record = lookupDispatch(childSessionID);
553
+ if (record === undefined) return null;
554
+ // Registered where ingestion was off (QA-2.3-6): another instance's configuration decides, not this one's.
555
+ if (record.outcomes === false) return null;
556
+ const settings = deps.settings();
557
+ if (settings === null) return null;
558
+ const confidence = record.facts.confidence;
559
+ const rawClass = record.facts.class;
560
+ // Phase 1.2 handoff (QA-1.2-27): a class below the threshold is "unknown" for learning, not a class of
561
+ // its own. No fallback class, no store call, no row. P1.4 (`untrusted: "unknown"`): a zero-mass role signal
562
+ // (budget, authority) is still a row, keyed under class `unknown`; it never reaches the store.
563
+ const trusted =
564
+ typeof confidence === "number" && Number.isFinite(confidence) && confidence >= settings.minClassConfidence &&
565
+ typeof rawClass === "string" && rawClass !== "" && rawClass !== "unknown";
566
+ if (!trusted && untrusted === "skip") return null;
567
+ const cls = trusted ? rawClass : "unknown";
568
+ if (record.model === null) return unkeyable(`${record.agent}|`, childSessionID, "the dispatch registered no model");
569
+ const ref = splitModelRef(record.model);
570
+ if (ref === null) return unkeyable(`${record.agent}|${record.model}`, childSessionID, `model "${record.model}" is not provider/model`);
571
+ const variant = record.variant ?? ref.variant;
572
+ const origin: AgentOrigin = settings.roleAgentIds?.has(record.agent) === true ? "role" : classifyAgentOrigin(record.agent, settings.routerAgentIds);
573
+ const key = makeKey(cls, { origin, id: record.agent }, ref.provider, ref.model, variant);
574
+ return { record, settings, key, origin, model: `${ref.provider}/${ref.model}`, variant: normalizeVariant(variant) };
575
+ };
576
+
577
+ // One warning per model reference (QA-2.1-12), not per child: every child of an unresolved agent says the same.
578
+ const unkeyable = (reference: string, childSessionID: string, why: string): null => {
579
+ if (boundedAdd(warnedUnkeyed, reference, WARNED_CAP)) {
580
+ deps.logger.warn(`[router] outcome ingestion: child ${childSessionID} is not recorded: ${why}`);
581
+ }
582
+ return null;
583
+ };
584
+
585
+ const signalOf = (record: DispatchRecord): AttemptSignal => ({ attemptID: record.attemptId, step: record.step });
586
+
587
+ const rowBase = (record: DispatchRecord): { v: typeof LOG_ROW_VERSION; ts: string; sessionID: string } => ({
588
+ v: LOG_ROW_VERSION,
589
+ ts: new Date(safeNow(now)).toISOString(),
590
+ sessionID: record.parentSessionID ?? "",
591
+ });
592
+
593
+ /** Held final steps this instance created (`${dir}|${attempt}`), released with it. */
594
+ const ownedHeld = new Set<string>();
595
+
596
+ /** The outcomes directory this instance writes to right now, or null when ingestion is off. */
597
+ const currentDir = (): string | null => held?.dir ?? deps.settings()?.outcomesDir ?? null;
598
+
599
+ /** The shared store of `dir`, through this instance's bundle when it has one; null when ingestion is off for `dir`. */
600
+ const storeOf = (dir: string): OutcomeStore | null => {
601
+ if (held !== null) return held.dir === dir ? held.bundle.store : null;
602
+ const settings = deps.settings();
603
+ return settings === null || settings.outcomesDir !== dir ? null : (bundleFor(settings)?.store ?? null);
604
+ };
605
+
606
+ /** Record the held final step of an attempt: as its last step (`asFinal`, folds the attempt) or as a plain step. */
607
+ const settle = (dir: string, attemptId: string, asFinal: boolean): void => {
608
+ const heldKey = scopeKey(dir, attemptId);
609
+ const pending = heldFinals.get(heldKey);
610
+ if (pending === undefined) return;
611
+ // The held step is shared by every instance of the process (QA-2.1-R2-1): when this one cannot reach the store of
612
+ // `dir` (it is off, disposed or writes elsewhere) the step stays for the instance that can.
613
+ const store = storeOf(dir);
614
+ if (store === null) return;
615
+ heldFinals.delete(heldKey);
616
+ ownedHeld.delete(heldKey);
617
+ store.recordStep(pending.key, asFinal ? pending.sample : { ...pending.sample, final: false });
618
+ };
619
+
620
+ /** Fold an attempt that is over: its held final step first, then whatever is still open. */
621
+ const endAttempt = (dir: string, attemptId: string): void => {
622
+ settle(dir, attemptId, true);
623
+ storeOf(dir)?.closeAttempt(attemptId);
624
+ };
625
+
626
+ const closeLastAttempt = (childSessionID: string): void => {
627
+ const dir = currentDir();
628
+ if (dir === null) return;
629
+ const mapKey = scopeKey(dir, childSessionID);
630
+ const last = lastAttemptByChild.get(mapKey);
631
+ lastAttemptByChild.delete(mapKey);
632
+ if (last !== undefined) endAttempt(last.dir, last.attempt);
633
+ };
634
+
635
+ const settleOwned = (): void => {
636
+ for (const heldKey of [...ownedHeld]) {
637
+ const pending = heldFinals.get(heldKey);
638
+ if (pending === undefined) ownedHeld.delete(heldKey);
639
+ else settle(pending.dir, pending.attempt, true);
640
+ }
641
+ };
642
+
643
+ /** QA-2.1-11: ingestion went off (engine switched to static): finish what is pending and let the bundle go. */
644
+ const dropIfOff = (): boolean => {
645
+ if (held === null || deps.settings() !== null) return false;
646
+ settleOwned();
647
+ const current = held;
648
+ held = null;
649
+ void current.bundle.release().catch((error: unknown) => warn("releasing the outcomes bundle failed", error));
650
+ return true;
651
+ };
652
+ /**
653
+ * P1.4: enqueue one signal row for the target's attempt: one per attempt and kind (C7, the store's one-observation
654
+ * rule), process-wide per outcomes directory. Needs the dispatch's decision id: without it there is no decision row
655
+ * to annotate and a pre-P1.4 reader would count the row as a dispatch (QA-P14-1-11).
656
+ */
657
+ const appendSignal = (target: Target, childSessionID: string, observation: SignalObservation, bundle: OutcomesBundle): boolean => {
658
+ const { record, settings, key } = target;
659
+ if (record.decisionID === null) return false;
660
+ if (!boundedAdd(signalled, `signal|${settings.outcomesDir}|${record.attemptId}|${observation.kind}`, SIGNAL_CAP)) return false;
661
+ bundle.flusher.enqueue(
662
+ signalRow(
663
+ {
664
+ ts: new Date(safeNow(now)).toISOString(),
665
+ sessionID: record.parentSessionID ?? "",
666
+ decisionID: record.decisionID,
667
+ mode: settings.engine,
668
+ childSessionID,
669
+ facts: record.facts,
670
+ chosen: { key, agent: record.agent, origin: target.origin, model: target.model, variant: target.variant },
671
+ step: record.step,
672
+ attemptID: record.attemptId,
673
+ ...(target.origin === "role" ? { role: record.agent } : {}),
674
+ ...(record.tier === null ? {} : { tier: record.tier }),
675
+ },
676
+ observation,
677
+ ),
678
+ );
679
+ return true;
680
+ };
681
+
682
+ /**
683
+ * #84 P3.3 fix 2 (plan §2.6, I6): the signal of a grader's verdict on the target's attempt. The grader's tier is the LOWER of
684
+ * the tier of the model it ran on (`tierOfModel`: a variant that is not a preset rung, as the host's `#default`, matches by
685
+ * model) and the tier the checker asked for (on the order, with a known model) — either one alone when the other is unknown
686
+ * (QA-P33F2-1 N3: a grader never ranks above either); the producer's is the registered tier, else its model's. `graderSignal`
687
+ * decides: independent (tier ≥ producer's, another model) → 0.5; unknown or not → none.
688
+ */
689
+ const graderSignalOf = (target: Target, outcome: Verdict, grader: VerdictGrader): SignalObservation | null => {
690
+ const tiers = target.settings.tierOrder ?? [];
691
+ const rungs = target.settings.tierRungs ?? [];
692
+ const requested = grader.model !== null && grader.tier !== null && tiers.includes(grader.tier) ? grader.tier : null;
693
+ const byModel = tierOfModel(grader.model, rungs);
694
+ const graderTier = byModel !== null && requested !== null
695
+ ? (tiers.indexOf(byModel) <= tiers.indexOf(requested) ? byModel : requested)
696
+ : (byModel ?? requested);
697
+ const producerTier = target.record.tier ?? tierOfModel(`${target.model}#${target.variant}`, rungs);
698
+ return graderSignal({ outcome, graderTier, graderModel: grader.model, producerTier, producerModel: target.model }, tiers);
699
+ };
700
+
701
+ return {
702
+ async onStepEnded(event: IngestEvent): Promise<void> {
703
+ try {
704
+ const failed = event.type === "session.step.failed";
705
+ if ((event.type !== "session.step.ended" && !failed) || !isRecord(event.data)) return;
706
+ const data = event.data;
707
+ const sessionID = data.sessionID;
708
+ if (typeof sessionID !== "string") return;
709
+ // Phase 2.3 (D11): the delegate ladder decides resume vs fresh from the child's context size, in every engine
710
+ // mode, so this runs before the settings gate. It only updates the in-memory registry (nothing is written)
711
+ // and ignores children that are not registered.
712
+ if (!failed && lookupDispatch(sessionID) !== undefined) {
713
+ const context = stepContextTokens(isRecord(data.tokens) ? data.tokens : undefined);
714
+ if (context !== null) noteStepContext(sessionID, context, safeNow(now));
715
+ }
716
+ const first = targetOf(sessionID);
717
+ if (first === null) return;
718
+ const tokens = isRecord(data.tokens) ? (data.tokens as unknown as StepEndedTokens) : undefined;
719
+ // A failed step reports cost and tokens only when it got that far (QA-2.1-6): nothing measured, nothing to add.
720
+ if (failed && typeof data.cost !== "number" && tokens === undefined) return;
721
+ const eventKey =
722
+ typeof event.id === "string" && event.id !== ""
723
+ ? event.id
724
+ : `${sessionID}|${String(data.assistantMessageID)}|${String(data.cost)}|${tokens?.input}|${tokens?.output}`;
725
+ // Pricing first (cached, or bounded by the catalog's own load timeout): a slow lookup must not decide
726
+ // which instance owns the event (QA-2.1-2).
727
+ const ref = splitModelRef(first.record.model ?? "");
728
+ const pricing = ref === null || deps.pricing === undefined ? undefined : await deps.pricing(ref.provider, ref.model);
729
+ if (disposed) return;
730
+ // From here on everything is synchronous, so the check and the record of an event id cannot interleave
731
+ // with another instance. The registry and the settings may have changed during the await.
732
+ const target = targetOf(sessionID);
733
+ if (target === null) return;
734
+ const { record, settings, key } = target;
735
+ // The pricing above belongs to the registration read before the await. A child that was registered again
736
+ // meanwhile (a new attempt, perhaps another model) must not receive a step of the previous one
737
+ // (QA-2.1-R2-11).
738
+ if (record.attemptId !== first.record.attemptId) return;
739
+ // Dedupe only a step that is about to be recorded: an instance whose own settings are static must not
740
+ // consume the event another instance (another location, another config) will record. The directory is
741
+ // part of the key (QA-2.1-8): a store in another directory is a different recording.
742
+ if (!firstDelivery(`${settings.outcomesDir}|${eventKey}`)) return;
743
+ const bundle = bundleFor(settings);
744
+ if (bundle === null) return;
745
+ const dir = settings.outcomesDir;
746
+ const superseded = rememberAttempt(dir, sessionID, record.attemptId);
747
+ if (superseded !== undefined && superseded !== record.attemptId) endAttempt(dir, superseded);
748
+ const sample: StepSample = {
749
+ attemptID: record.attemptId,
750
+ cost: typeof data.cost === "number" ? data.cost : Number.NaN,
751
+ pricing: pricingState(pricing),
752
+ tokens: tokenSampleFromEvent(
753
+ tokens ?? { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
754
+ ),
755
+ final: false,
756
+ };
757
+ // A step after a held final one proves that one was not the last.
758
+ settle(dir, record.attemptId, false);
759
+ if (!failed && data.finish !== "tool-calls") {
760
+ const heldKey = scopeKey(dir, record.attemptId);
761
+ boundedSet(heldFinals, heldKey, { dir, attempt: record.attemptId, key, sample: { ...sample, final: true }, at: safeNow(now) }, HELD_FINAL_CAP);
762
+ ownedHeld.add(heldKey);
763
+ } else {
764
+ bundle.store.recordStep(key, sample);
765
+ }
766
+ touchDispatch(sessionID, safeNow(now));
767
+ } catch (error) {
768
+ warn("session.step.ended failed", error);
769
+ }
770
+ },
771
+ onExecutionEnded(childSessionID: string, eventId?: unknown): void {
772
+ try {
773
+ if (lookupDispatch(childSessionID) === undefined) return;
774
+ const id = typeof eventId === "string" && eventId !== "" ? eventId : undefined;
775
+ // Phase 2.3 (QA-2.3-2): every step event of this registration has been noted, whatever the engine mode; the
776
+ // delegate ladder reads the child's context only after this. The registry applies an end id once per process.
777
+ noteExecutionEnded(childSessionID, safeNow(now), id);
778
+ // The fold is per outcomes directory, like the step events' dedupe: an instance that cannot record (static, or
779
+ // another directory) must not consume the end another instance folds with. A stale copy delivered after the
780
+ // child was registered again would otherwise fold the NEW attempt early (QA-2.3-R2-1).
781
+ const dir = currentDir();
782
+ if (id !== undefined && dir !== null && !firstDelivery(`${dir}|end|${id}`)) return;
783
+ closeLastAttempt(childSessionID);
784
+ } catch (error) {
785
+ warn("execution end failed", error, { childSessionID });
786
+ }
787
+ },
788
+
789
+ onVerdict(childSessionID: string, outcome: Verdict, grader: VerdictGrader | undefined): void {
790
+ try {
791
+ const target = targetOf(childSessionID);
792
+ if (target === null) return;
793
+ const { record, settings, key } = target;
794
+ const bundle = bundleFor(settings);
795
+ if (bundle === null) return;
796
+ const attempt = record.attemptId;
797
+ // QA-P33F2-1-1 (plan §2.6, I6): a role dispatch's GRADER verdict counts only from an independent grader, and then at
798
+ // the grader's 0.5 — in the store that role routing reads (kernel) as in the rows. A grader that is not independent, or
799
+ // not known to be, moves nothing: no store observation, no verdict row, no signal row, and the attempt stays unscored
800
+ // (a later false refusal is then its first terminal signal, as in the store). Tier and host dispatches: unchanged (I1).
801
+ const graded = outcome !== "unverifiable" && target.origin === "role" && grader !== undefined
802
+ ? graderSignalOf(target, outcome, grader)
803
+ : undefined;
804
+ if (graded === null) {
805
+ touchDispatch(childSessionID, safeNow(now));
806
+ return;
807
+ }
808
+ // Rows follow the store (QA-2.1-3): a verdict that moves nothing (the attempt was scored already, by a
809
+ // verdict or a refusal) writes no row, or `routing:stats` would count outcomes the store never saw.
810
+ // `unverifiable` moves nothing by design; it is a row only while the attempt is still unscored.
811
+ if (outcome === "unverifiable") {
812
+ if (scored.has(attempt) || !boundedAdd(signalled, `unverifiable|${attempt}`, SIGNAL_CAP)) return;
813
+ } else {
814
+ const weight = graded === undefined ? undefined : graded.weight; // the grader's 0.5 (signals.ts SIGNAL_WEIGHTS.grader)
815
+ if (!bundle.store.recordVerdict(key, outcome, signalOf(record), weight)) return;
816
+ boundedSet(scored, attempt, outcome, SIGNAL_CAP);
817
+ }
818
+ const row: VerdictRow = {
819
+ ...rowBase(record),
820
+ kind: "verdict",
821
+ decisionID: record.decisionID,
822
+ childSessionID,
823
+ attemptID: attempt,
824
+ key,
825
+ verdict: outcome,
826
+ step: record.step,
827
+ };
828
+ bundle.flusher.enqueue(row);
829
+ // P1.4 (QA-P14-1-6): a role dispatch's verdict signal row follows the store: written only for a verdict it took.
830
+ // #84 P3.3 fix 2 (plan §2.6, I6): a grader's verdict is a `grader` signal (0.5, independent graders only), never `verdict`.
831
+ if (outcome !== "unverifiable" && target.origin === "role") {
832
+ const signal = graded ?? verdictSignal(outcome);
833
+ if (signal !== null) appendSignal(target, childSessionID, signal, bundle);
834
+ }
835
+ touchDispatch(childSessionID, safeNow(now));
836
+ } catch (error) {
837
+ warn("verdict failed", error, { childSessionID });
838
+ }
839
+ },
840
+
841
+ onFalseRefusal(childSessionID: string): void {
842
+ try {
843
+ const target = targetOf(childSessionID);
844
+ if (target === null) return;
845
+ const { record, settings, key } = target;
846
+ const attempt = record.attemptId;
847
+ // One refusal per attempt (QA-2.1-9): a repeat must not reach the store, whose lifetime counter would grow.
848
+ if (!boundedAdd(signalled, `refusal|${attempt}`, SIGNAL_CAP)) return;
849
+ const bundle = bundleFor(settings);
850
+ if (bundle === null) return;
851
+ const prior = scored.get(attempt);
852
+ // The store converts an earlier `pass` of the same attempt into a failure (C5, QA-1.3-6); the row says so,
853
+ // and `routing:stats` moves that pass to a fail the same way.
854
+ const changed = bundle.store.recordFalseRefusal(key, signalOf(record));
855
+ boundedSet(scored, attempt, "refusal", SIGNAL_CAP);
856
+ const row: RefusalRow = {
857
+ ...rowBase(record),
858
+ kind: "refusal",
859
+ decisionID: record.decisionID,
860
+ childSessionID,
861
+ attemptID: attempt,
862
+ key,
863
+ step: record.step,
864
+ ...(prior === "pass" && changed ? { overrides: "pass" as const } : {}),
865
+ };
866
+ bundle.flusher.enqueue(row);
867
+ touchDispatch(childSessionID, safeNow(now));
868
+ } catch (error) {
869
+ warn("false refusal failed", error, { childSessionID });
870
+ }
871
+ },
872
+
873
+ onSignal(childSessionID: string, observation: SignalObservation, options: SignalOptions = {}): boolean {
874
+ try {
875
+ if (!isSignalObservation(observation)) return false;
876
+ // QA-P14-1-6: verdict rows follow the store; only onVerdict writes them. QA-P33F2-1 N2: grader rows too.
877
+ if (observation.kind === "verdict" || observation.kind === "grader") return false;
878
+ // QA-P14-1-5: a re-dispatch failure belongs to one earlier attempt and must name it.
879
+ if (observation.kind === "redispatch" && options.expectDecisionID === undefined) return false;
880
+ const caps = SIGNAL_MASS_CAPS[observation.kind];
881
+ const target = targetOf(childSessionID, caps.positive === 0 && caps.negative === 0 ? "unknown" : "skip");
882
+ if (target === null) return false;
883
+ if (options.expectDecisionID !== undefined && target.record.decisionID !== options.expectDecisionID) return false;
884
+ const bundle = bundleFor(target.settings);
885
+ if (bundle === null) return false;
886
+ if (!appendSignal(target, childSessionID, observation, bundle)) return false;
887
+ touchDispatch(childSessionID, safeNow(now));
888
+ return true;
889
+ } catch (error) {
890
+ warn("signal failed", error, { childSessionID });
891
+ return false;
892
+ }
893
+ },
894
+ onSessionGone(sessionID: string): void {
895
+ try {
896
+ if (lookupDispatch(sessionID) !== undefined) {
897
+ closeLastAttempt(sessionID);
898
+ forgetDispatch(sessionID);
899
+ }
900
+ // The orchestrator went away: its children can no longer receive verdicts.
901
+ for (const child of forgetDispatchesOf(sessionID)) closeLastAttempt(child.childSessionID);
902
+ if (held !== null) void held.bundle.flusher.requestFlush();
903
+ } catch (error) {
904
+ warn("session cleanup failed", error, { sessionID });
905
+ }
906
+ },
907
+
908
+ requestFlush(): void {
909
+ try {
910
+ if (dropIfOff()) return;
911
+ if (held !== null) void held.bundle.flusher.requestFlush();
912
+ } catch (error) {
913
+ warn("flush request failed", error);
914
+ }
915
+ },
916
+
917
+ sweep(): void {
918
+ try {
919
+ dropIfOff();
920
+ const t = safeNow(now);
921
+ sweepDispatches(t);
922
+ // Only what belongs to this instance's own directory: another instance (or another directory) owns the rest
923
+ // (QA-2.1-R2-1).
924
+ const dir = currentDir();
925
+ if (dir !== null) {
926
+ // A child that was swept away can no longer end its attempt: fold it.
927
+ for (const [mapKey, last] of [...lastAttemptByChild]) {
928
+ if (last.dir !== dir) continue;
929
+ const child = mapKey.slice(last.dir.length + 1);
930
+ if (lookupDispatch(child) !== undefined) continue;
931
+ lastAttemptByChild.delete(mapKey);
932
+ endAttempt(last.dir, last.attempt);
933
+ }
934
+ for (const pending of [...heldFinals.values()]) {
935
+ if (pending.dir === dir && t - pending.at >= HELD_FINAL_IDLE_MS) settle(pending.dir, pending.attempt, true);
936
+ }
937
+ }
938
+ // Keys of held steps that someone else settled (QA-2.1-R2-8).
939
+ for (const heldKey of [...ownedHeld]) if (!heldFinals.has(heldKey)) ownedHeld.delete(heldKey);
940
+ held?.bundle.store.sweepAttempts();
941
+ } catch (error) {
942
+ warn("sweep failed", error);
943
+ }
944
+ },
945
+
946
+ async dispose(): Promise<void> {
947
+ if (disposed) return;
948
+ disposed = true;
949
+ settleOwned();
950
+ const current = held;
951
+ held = null;
952
+ if (current === null) return;
953
+ try {
954
+ await current.bundle.release();
955
+ } catch (error) {
956
+ warn("release failed", error);
957
+ }
958
+ },
959
+ };
960
+ }