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,650 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Outcome signals of role/tier assurance (plan §2.6, invariants I6 and I7) — pure functions.
3
+ //
4
+ // Every input is injected (the child's final assistant text, router-observed runs, edit timestamps, grader verdicts,
5
+ // earlier dispatches); the hook call sites belong to P2.1. Nothing here does I/O, reads a clock or touches the
6
+ // store. Runnable under Node type stripping, like every module of src/routing/outcomes/.
7
+ //
8
+ // Weights (§2.6): success — deterministic pass, or a router-observed acceptance run (exit 0) that started after the
9
+ // child's last edit: 1; an independent grader pass (grader tier ≥ producer tier AND another model): 0.5.
10
+ // Failure — deterministic fail: 1; independent grader fail: 0.5; an explicit `NEED MORE`/`ESCALATE` return without
11
+ // budget exhaustion or an authority request: 0.5; the same task dispatched again to a HIGHER tier within 30 min of the
12
+ // previous attempt: 0.5 on that attempt. `DONE` alone and a return without a contract prefix: no signal (I6, §2.9
13
+ // E8). Budget exhaustion and authority requests: recorded with no mass (I7). Self-report never moves evidence: the
14
+ // child's own `NEED MORE: budget` / `ESCALATE: authority` claim is not an exemption, only the guard's state is.
15
+ // ---------------------------------------------------------------------------
16
+
17
+ import type {
18
+ DecisionFacts,
19
+ DecisionRow,
20
+ LadderStepKind,
21
+ LoggedRoutingMode,
22
+ RouteChoice,
23
+ SignalKind,
24
+ Verdict,
25
+ } from "./types";
26
+ import { LOG_ROW_VERSION, SIGNAL_REASON, normalizeVariant, splitModelRef } from "./types";
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // Observations and weights
30
+ // ---------------------------------------------------------------------------
31
+
32
+ /** Direction of a signal: success, failure, or recorded without evidence mass. */
33
+ export type SignalOutcome = "pass" | "fail" | "none";
34
+
35
+ /** One signal about one attempt. `weight` is the magnitude (≥ 0); the direction is `outcome`. */
36
+ export interface SignalObservation {
37
+ readonly kind: SignalKind;
38
+ readonly outcome: SignalOutcome;
39
+ readonly weight: number;
40
+ }
41
+
42
+ /** §2.6 weights. */
43
+ export const SIGNAL_WEIGHTS = Object.freeze({
44
+ deterministic: 1,
45
+ run: 1,
46
+ grader: 0.5,
47
+ incomplete: 0.5,
48
+ redispatch: 0.5,
49
+ recorded: 0,
50
+ } as const);
51
+
52
+ /**
53
+ * The largest success and failure mass a row of each kind may carry. Readers clamp rows to it, so a malformed or
54
+ * forged row can neither create positive evidence from self-report (I6) nor a penalty for budget or authority (I7).
55
+ */
56
+ export const SIGNAL_MASS_CAPS: Readonly<Record<SignalKind, { readonly positive: number; readonly negative: number }>> = Object.freeze({
57
+ verdict: { positive: SIGNAL_WEIGHTS.deterministic, negative: SIGNAL_WEIGHTS.deterministic },
58
+ run: { positive: SIGNAL_WEIGHTS.run, negative: 0 },
59
+ grader: { positive: SIGNAL_WEIGHTS.grader, negative: SIGNAL_WEIGHTS.grader },
60
+ incomplete: { positive: 0, negative: SIGNAL_WEIGHTS.incomplete },
61
+ budget: { positive: 0, negative: 0 },
62
+ authority: { positive: 0, negative: 0 },
63
+ redispatch: { positive: 0, negative: SIGNAL_WEIGHTS.redispatch },
64
+ });
65
+
66
+ const KINDS: readonly string[] = Object.keys(SIGNAL_MASS_CAPS);
67
+
68
+ /** Structural check of an observation handed in by a caller (the ingest API validates before writing). */
69
+ export function isSignalObservation(x: unknown): x is SignalObservation {
70
+ if (typeof x !== "object" || x === null) return false;
71
+ const o = x as Record<string, unknown>;
72
+ return (
73
+ typeof o.kind === "string" &&
74
+ KINDS.includes(o.kind) &&
75
+ (o.outcome === "pass" || o.outcome === "fail" || o.outcome === "none") &&
76
+ typeof o.weight === "number" &&
77
+ Number.isFinite(o.weight) &&
78
+ o.weight >= 0
79
+ );
80
+ }
81
+
82
+ /** Signed mass as written to a row: + success, − failure, 0 recorded only. */
83
+ export function signedWeight(observation: SignalObservation): number {
84
+ if (observation.outcome === "none" || observation.weight === 0) return 0;
85
+ return observation.outcome === "pass" ? observation.weight : -observation.weight;
86
+ }
87
+
88
+ /** Success and failure mass of a signal of `kind` with signed weight `weight`, clamped to {@link SIGNAL_MASS_CAPS}. */
89
+ export function signalMass(kind: SignalKind, weight: number | undefined): { readonly positive: number; readonly negative: number } {
90
+ const caps = SIGNAL_MASS_CAPS[kind];
91
+ if (caps === undefined || weight === undefined || !Number.isFinite(weight) || weight === 0) return { positive: 0, negative: 0 };
92
+ return weight > 0
93
+ ? { positive: Math.min(weight, caps.positive), negative: 0 }
94
+ : { positive: 0, negative: Math.min(-weight, caps.negative) };
95
+ }
96
+
97
+ const observe = (kind: SignalKind, outcome: SignalOutcome, weight: number): SignalObservation => ({ kind, outcome, weight });
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Return contract of the child's final assistant text
101
+ // ---------------------------------------------------------------------------
102
+
103
+ export type ReturnPrefix = "done" | "need-more" | "escalate" | "none";
104
+
105
+ export interface ReturnContract {
106
+ readonly prefix: ReturnPrefix;
107
+ /** `NEED MORE: budget` / `ESCALATE: authority` (either prefix, either word). Informational: never an exemption. */
108
+ readonly claim: "budget" | "authority" | null;
109
+ }
110
+
111
+ /**
112
+ * The host's `task` tool output wraps the child's text: `task_id: … <task_result> … </task_result>`. Unwrapped only when
113
+ * the wrapper LEADS the text (after `task_id:` lines) and closes at its end: a `<task_result>` mentioned inside the body
114
+ * is the child's text (QA-P14-2-4).
115
+ */
116
+ const TASK_RESULT_RE = /^\s*(?:task_id\s*:[^\n]*\n\s*)*<task_result>([\s\S]*?)(?:<\/task_result>\s*$|$)/i;
117
+ const TASK_ID_RE = /^\s*task_id\s*:/i;
118
+ /** Leading decoration: markdown marks, list bullets, quotes, emoji, punctuation (anything but a letter or a digit). */
119
+ const LEAD_RE = /^[^\p{L}\p{N}]+/u;
120
+ const LIST_NUMBER_RE = /^\d+[.)]\s+/;
121
+ // Bounded runs ({0,16}): the child's text is uncontrolled, and an open-ended `[*_`\s]*` next to `(.*)` is polynomial (CodeQL js/polynomial-redos).
122
+ const PREFIX_RE = /^(DONE|NEED[\s_-]{0,8}MORE|ESCALATE)\b[*_`\s]{0,16}(?:[:.!\-\u2013\u2014]|$)[*_`\s]{0,16}(.*)$/i;
123
+ const CLAIM_RE = /^(budget|authority)\b/i;
124
+
125
+ /**
126
+ * The return contract of a child's final assistant text (the unwrapped `subagent` result: a `<task_result>` wrapper and
127
+ * leading `task_id:` lines are skipped): its first non-empty line, with leading markdown, list markers and emoji
128
+ * stripped. `null` when there is no text at all. A first line without a contract prefix is `none`.
129
+ */
130
+ export function parseReturnPrefix(text: string | null | undefined): ReturnContract | null {
131
+ if (typeof text !== "string") return null;
132
+ const wrapped = TASK_RESULT_RE.exec(text);
133
+ const body = wrapped === null ? text : (wrapped[1] as string);
134
+ const first = body.split(/\r?\n/).find((line) => line.trim() !== "" && !TASK_ID_RE.test(line));
135
+ if (first === undefined) return null;
136
+ const match = PREFIX_RE.exec(first.replace(LEAD_RE, "").replace(LIST_NUMBER_RE, ""));
137
+ if (match === null) return { prefix: "none", claim: null };
138
+ const word = (match[1] as string).toUpperCase();
139
+ const prefix: ReturnPrefix = word === "DONE" ? "done" : word === "ESCALATE" ? "escalate" : "need-more";
140
+ const claim = prefix === "done" ? null : CLAIM_RE.exec((match[2] as string).trim());
141
+ return { prefix, claim: claim === null ? null : ((claim[1] as string).toLowerCase() as "budget" | "authority") };
142
+ }
143
+
144
+ /** A guard state as P2.1 hands it in: observed true/false, or not observed at all. */
145
+ export type GuardObservation = boolean | "unobserved";
146
+
147
+ export interface ReturnSignalInput {
148
+ /** The child's final assistant text (see {@link parseReturnPrefix}). */
149
+ readonly text: string | null | undefined;
150
+ /**
151
+ * The child's budget was exhausted: the guard's call budget (P1.5), and equally a host step limit or a context overflow
152
+ * that ended the child (P2.1 folds those in). P2.1 must pass the real state.
153
+ */
154
+ readonly budgetExhausted: GuardObservation;
155
+ /** The child called `router_request_authority` (P1.6). P2.1 must pass the real state. */
156
+ readonly authorityRequested: GuardObservation;
157
+ }
158
+
159
+ /**
160
+ * Signal of the child's return:
161
+ * - an observed authority request → `authority`, an observed budget exhaustion → `budget` (no mass, I7), whatever the text;
162
+ * - `DONE`, no text, or no contract prefix (a progress note, §2.9 E8) → no signal (I6);
163
+ * - an explicit `NEED MORE`/`ESCALATE` with both guards observed false → `incomplete` (failure 0.5). The child's own
164
+ * budget/authority claim does not exempt it (self-report never moves evidence);
165
+ * - the same with either guard `unobserved` → no signal: it cannot be told apart from budget or authority (I7).
166
+ */
167
+ export function returnSignal(input: ReturnSignalInput): SignalObservation | null {
168
+ if (input.authorityRequested === true) return observe("authority", "none", SIGNAL_WEIGHTS.recorded);
169
+ if (input.budgetExhausted === true) return observe("budget", "none", SIGNAL_WEIGHTS.recorded);
170
+ const contract = parseReturnPrefix(input.text);
171
+ if (contract === null || contract.prefix === "done" || contract.prefix === "none") return null;
172
+ if (input.authorityRequested === "unobserved" || input.budgetExhausted === "unobserved") return null;
173
+ return observe("incomplete", "fail", SIGNAL_WEIGHTS.incomplete);
174
+ }
175
+
176
+ // ---------------------------------------------------------------------------
177
+ // Deterministic verdicts, graders and router-observed runs
178
+ // ---------------------------------------------------------------------------
179
+
180
+ /** A deterministic verifier verdict: pass/fail weight 1; `unverifiable` is no signal. */
181
+ export function verdictSignal(outcome: Verdict): SignalObservation | null {
182
+ if (outcome === "unverifiable") return null;
183
+ return observe("verdict", outcome, SIGNAL_WEIGHTS.deterministic);
184
+ }
185
+
186
+ /** Rank of `tier` in `tiers` (cheapest first, the escalate ladder's order); null when absent. */
187
+ export function tierRank(tier: string | null | undefined, tiers: readonly string[]): number | null {
188
+ if (typeof tier !== "string") return null;
189
+ const rank = tiers.indexOf(tier);
190
+ return rank < 0 ? null : rank;
191
+ }
192
+
193
+ interface ModelIds {
194
+ /** `provider/model` without `#variant`, lowercased. */
195
+ readonly full: string;
196
+ /**
197
+ * Last path segment, every run of non-alphanumerics folded to `-` (`anthropic.claude-sonnet-4-5-v1:0` →
198
+ * `anthropic-claude-sonnet-4-5-v1-0`, Vertex `claude-sonnet-4-5@20250929` → `claude-sonnet-4-5-20250929`).
199
+ */
200
+ readonly bare: string;
201
+ }
202
+
203
+ function modelIds(model: string | null | undefined): ModelIds | null {
204
+ if (typeof model !== "string") return null;
205
+ const hash = model.lastIndexOf("#");
206
+ const full = (hash >= 0 ? model.slice(0, hash) : model).trim().toLowerCase();
207
+ const bare = full.slice(full.lastIndexOf("/") + 1).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
208
+ return full === "" || bare === "" ? null : { full, bare };
209
+ }
210
+
211
+ /**
212
+ * Could the two ids name the same model? Same full id, same bare id across providers, or one bare id contained in the
213
+ * other on `-` boundaries (a vendor prefix, a date or version suffix, a size suffix): ambiguous counts as the same.
214
+ */
215
+ export function sameModel(a: string | null | undefined, b: string | null | undefined): boolean {
216
+ const x = modelIds(a);
217
+ const y = modelIds(b);
218
+ if (x === null || y === null) return true;
219
+ if (x.full === y.full || x.bare === y.bare) return true;
220
+ const bx = `-${x.bare}-`;
221
+ const by = `-${y.bare}-`;
222
+ return bx.includes(by) || by.includes(bx);
223
+ }
224
+
225
+ export interface GraderVerdictInput {
226
+ readonly outcome: Verdict;
227
+ readonly graderTier: string | null;
228
+ readonly graderModel: string | null;
229
+ readonly producerTier: string | null;
230
+ readonly producerModel: string | null;
231
+ }
232
+
233
+ /**
234
+ * An LLM grader's verdict counts (weight 0.5) only when the grader is independent: its tier is at least the producer's
235
+ * and it is certainly another model ({@link sameModel} false). Unknown tiers or models cannot prove it: no signal.
236
+ */
237
+ export function graderSignal(input: GraderVerdictInput, tiers: readonly string[]): SignalObservation | null {
238
+ if (input.outcome === "unverifiable") return null;
239
+ const graderRank = tierRank(input.graderTier, tiers);
240
+ const producerRank = tierRank(input.producerTier, tiers);
241
+ if (graderRank === null || producerRank === null || graderRank < producerRank) return null;
242
+ if (sameModel(input.graderModel, input.producerModel)) return null;
243
+ return observe("grader", input.outcome, SIGNAL_WEIGHTS.grader);
244
+ }
245
+
246
+ /** One rung of the active preset on the tier order: the tier it belongs to and its `provider/model` and variant (null = default). */
247
+ export interface TierRung {
248
+ readonly tier: string;
249
+ readonly model: string;
250
+ readonly variant: string | null;
251
+ }
252
+
253
+ /**
254
+ * #84 P3.3 fix 2: the tier of a model reference (`provider/model` or `provider/model#variant`) among `rungs` (cheapest tier
255
+ * first). An exact rung — same model and variant (absent ≡ `default`) — decides, the cheapest exact rung when there are several,
256
+ * even when the model also sits on a cheaper tier with another variant (`…#high` on `heavy` stays `heavy` although `…#low` is on
257
+ * `medium`). Only when the variant is no rung of the preset — as when the host reports the model's default variant
258
+ * (`anthropic/claude-opus-5-5#default`) of a tier that lists another one — the cheapest tier listing the model decides, so a
259
+ * reference that matches only by model never ranks higher than its cheapest tier. Models are compared case-insensitively. Null
260
+ * for an unknown or malformed reference. (The ingest's grader rank also caps this by the tier the checker asked for, QA-P33F2-1 N3.)
261
+ */
262
+ export function tierOfModel(model: string | null | undefined, rungs: readonly TierRung[]): string | null {
263
+ const parse = (text: unknown): { readonly id: string; readonly variant: string | null } | null => {
264
+ const ref = typeof text === "string" ? splitModelRef(text.trim()) : null;
265
+ return ref === null ? null : { id: `${ref.provider}/${ref.model}`.toLowerCase(), variant: ref.variant };
266
+ };
267
+ const wanted = parse(model);
268
+ if (wanted === null) return null;
269
+ const variant = normalizeVariant(wanted.variant);
270
+ const same: Array<{ readonly tier: string; readonly variant: string }> = [];
271
+ for (const rung of rungs) {
272
+ const own = parse(rung.model);
273
+ if (own !== null && own.id === wanted.id) same.push({ tier: rung.tier, variant: normalizeVariant(rung.variant ?? own.variant) });
274
+ }
275
+ return (same.find((rung) => rung.variant === variant) ?? same[0])?.tier ?? null;
276
+ }
277
+
278
+ /** One router-observed `router_run` (P1.3). `at` is the run's START (epoch ms). `exitCode` null = killed or timed out. */
279
+ export interface RunRecord {
280
+ readonly sessionID: string;
281
+ readonly script: string;
282
+ readonly exitCode: number | null;
283
+ readonly at: number;
284
+ }
285
+
286
+ export interface RunSignalInput {
287
+ readonly childSessionID: string;
288
+ readonly runs: readonly RunRecord[];
289
+ /** The child's edits were tracked for this attempt. `false` (not tracked) is not "no edits": no run signal. */
290
+ readonly editsObserved: boolean;
291
+ /** Epoch ms of the child's edits. One non-finite time makes the last edit unknown: no run signal. */
292
+ readonly edits: readonly number[];
293
+ /** The dispatch's acceptance commands (`routing.run` names). Empty → no run signal. */
294
+ readonly acceptance: readonly string[];
295
+ /**
296
+ * QA-G-B-5: epoch ms the attempt was dispatched (the parent's `task` call). Runs that started before it belong to an earlier
297
+ * attempt of the same child and never count for this one; edits before it are covered by any run of this attempt. Absent: no
298
+ * lower bound. A non-finite value makes the attempt's start unknown: no run signal.
299
+ */
300
+ readonly since?: number;
301
+ }
302
+
303
+ /**
304
+ * Success weight 1 when edits were tracked, EVERY acceptance command has a run by the child in this attempt (at or after
305
+ * `since`) that started strictly after its last edit, and the latest such run of each exited 0. A run that started before
306
+ * (or at) the last edit does not cover it. A failing run is no signal (the deterministic verdict owns failures).
307
+ */
308
+ export function runSignal(input: RunSignalInput): SignalObservation | null {
309
+ if (input.editsObserved !== true) return null;
310
+ const acceptance = [...new Set(input.acceptance)];
311
+ if (acceptance.length === 0) return null;
312
+ if (input.since !== undefined && !Number.isFinite(input.since)) return null;
313
+ const since = input.since ?? Number.NEGATIVE_INFINITY;
314
+ let lastEdit = Number.NEGATIVE_INFINITY;
315
+ for (const t of input.edits) {
316
+ if (!Number.isFinite(t)) return null;
317
+ if (t >= since && t > lastEdit) lastEdit = t;
318
+ }
319
+ for (const script of acceptance) {
320
+ let latest: RunRecord | null = null;
321
+ let latestFailed = false;
322
+ for (const run of input.runs) {
323
+ if (run.sessionID !== input.childSessionID || run.script !== script || !Number.isFinite(run.at) || run.at < since || run.at <= lastEdit) continue;
324
+ if (latest === null || run.at > latest.at) {
325
+ latest = run;
326
+ latestFailed = run.exitCode !== 0;
327
+ } else if (run.at === latest.at && run.exitCode !== 0) {
328
+ latestFailed = true; // simultaneous runs: any failure wins
329
+ }
330
+ }
331
+ if (latest === null || latestFailed) return null;
332
+ }
333
+ return observe("run", "pass", SIGNAL_WEIGHTS.run);
334
+ }
335
+
336
+ // ---------------------------------------------------------------------------
337
+ // Re-dispatch of the same task to a higher tier
338
+ // ---------------------------------------------------------------------------
339
+
340
+ /** Measured from the previous attempt's end when known, else from its start. */
341
+ export const REDISPATCH_WINDOW_MS = 30 * 60_000;
342
+ /** Dice coefficient over TASK words (and over identifier words, when any) at or above which two tasks are the same. */
343
+ export const REDISPATCH_SIMILARITY = 0.6;
344
+ /** Texts with fewer distinct words than this never match (too little to tell tasks apart). */
345
+ export const REDISPATCH_MIN_TOKENS = 3;
346
+ /** A line present in at least this many sibling dispatches (other tasks of the same parent) is boilerplate. */
347
+ export const SIBLING_SHARED_MIN = 2;
348
+ /** A sibling whose compared lines lie at least this much inside the compared pair is an earlier attempt of the same task. */
349
+ export const SAME_TASK_LINE_SHARE = 0.8;
350
+ /**
351
+ * Only the most recent earlier dispatches of the parent are considered (QA-P14-3-1). The window is 30 min, so a re-dispatch
352
+ * candidate older than the 100 most recent dispatches of one parent is unrealistic; the bound keeps the call synchronous-safe.
353
+ */
354
+ export const REDISPATCH_MAX_EARLIER = 100;
355
+
356
+ export interface DispatchText {
357
+ readonly decisionID: string;
358
+ readonly parentSessionID: string;
359
+ /** The attempt's child session; an attempt without one cannot be addressed and is never penalised. */
360
+ readonly childSessionID: string | null;
361
+ /** Task class (classifier facts). Must match; null (unknown) never matches. */
362
+ readonly class: string | null;
363
+ /** Role agent of the dispatch (roles mode). Must match (absent ≡ null). */
364
+ readonly role?: string | null;
365
+ /**
366
+ * The orchestrator's ORIGINAL prompt, before the router prepends its header (`[router] …`, dispatch-header.ts, the
367
+ * route line): the header is identical in every dispatch and, without ≥ 2 siblings to reveal it, would dominate.
368
+ */
369
+ readonly prompt: string;
370
+ readonly tier: string | null;
371
+ /** Epoch ms of the dispatch. */
372
+ readonly at: number;
373
+ /** Epoch ms the attempt ended (the parent's `subagent` call returned), when known. */
374
+ readonly endedAt?: number | null;
375
+ /** The dispatch resumed an existing child (`task_id`/`sessionID`, the authority ladder): never a re-dispatch. */
376
+ readonly resume?: boolean;
377
+ /** How the attempt ended, when known: an attempt that stopped on budget or authority is never penalised (I7). */
378
+ readonly returned?: SignalKind | null;
379
+ /** The attempt's return contract (`parseReturnPrefix(...).prefix`), when known. */
380
+ readonly returnPrefix?: ReturnPrefix | null;
381
+ /** Guard states of the attempt (as for {@link returnSignal}); absent ≡ `unobserved`. */
382
+ readonly budgetExhausted?: GuardObservation;
383
+ readonly authorityRequested?: GuardObservation;
384
+ }
385
+
386
+ /**
387
+ * May an earlier attempt take a re-dispatch failure (I7, QA-P14-2-3)? Never when it stopped on an observed budget
388
+ * exhaustion or authority request. Otherwise only when its stop is known not to be one: it returned finished (`DONE` or
389
+ * no contract prefix), or both guards were observed false. An unfinished or unknown return with an unobserved guard may
390
+ * have been a budget stop: no penalty.
391
+ */
392
+ function penalisable(previous: DispatchText): boolean {
393
+ if (previous.returned === "budget" || previous.returned === "authority") return false;
394
+ if (previous.budgetExhausted === true || previous.authorityRequested === true) return false;
395
+ if (previous.budgetExhausted === false && previous.authorityRequested === false) return true;
396
+ return previous.returnPrefix === "done" || previous.returnPrefix === "none";
397
+ }
398
+
399
+ export interface RedispatchMatch {
400
+ /** The earlier attempt the failure belongs to (address it by `decisionID`, ingest `expectDecisionID`). */
401
+ readonly previous: DispatchText;
402
+ readonly similarity: number;
403
+ readonly observation: SignalObservation;
404
+ }
405
+
406
+ export interface RedispatchOptions {
407
+ readonly windowMs?: number;
408
+ readonly threshold?: number;
409
+ }
410
+
411
+ // Bounded runs ({0,16}/{0,8}): the prompt is uncontrolled text, and the adjacent open-ended `\s*`/`[*_]*` runs were polynomial (CodeQL js/polynomial-redos).
412
+ const SECTION_RE =
413
+ /^[\s>#*_]{0,16}(?:\d{1,4}\s{0,8}[.)]\s{0,8})?[*_]{0,8}\s{0,8}(TASK|EXPECTED OUTCOME|REQUIRED TOOLS|TOOLS|MUST DO|MUST NOT DO|CONTEXT|ENVIRONMENT)(?:\s{0,8}\([^)\n]{0,256}\))?\s{0,8}[*_]{0,8}\s{0,8}:[*_]{0,8}(.*)$/;
414
+
415
+ interface PromptLines {
416
+ /** Normalized non-empty content lines with their section (a header's inline content belongs to its section). */
417
+ readonly lines: ReadonlyArray<{ readonly section: string | null; readonly text: string }>;
418
+ /** The prompt has a TASK header. */
419
+ readonly hasTask: boolean;
420
+ }
421
+
422
+ const normalizeLine = (line: string): string => line.trim().replace(/\s+/g, " ");
423
+
424
+ function promptLines(prompt: string): PromptLines {
425
+ let section: string | null = null;
426
+ let hasTask = false;
427
+ const lines: Array<{ section: string | null; text: string }> = [];
428
+ for (const raw of prompt.split(/\r?\n/)) {
429
+ const header = SECTION_RE.exec(raw);
430
+ let content = raw;
431
+ if (header !== null) {
432
+ section = header[1] as string;
433
+ if (section === "TASK") hasTask = true;
434
+ content = header[2] as string;
435
+ }
436
+ const text = normalizeLine(content);
437
+ if (text !== "") lines.push({ section, text });
438
+ }
439
+ return { lines, hasTask };
440
+ }
441
+
442
+ /** TASK section of a 7-section dispatch prompt (normalized lines), or null without a TASK header. */
443
+ export function taskSection(prompt: string): string | null {
444
+ const parsed = promptLines(prompt);
445
+ return parsed.hasTask ? parsed.lines.filter((l) => l.section === "TASK").map((l) => l.text).join("\n") : null;
446
+ }
447
+
448
+ /** Normalized lines shared with at least {@link SIBLING_SHARED_MIN} of `siblings` (boilerplate). */
449
+ export function sharedLines(siblings: readonly string[]): Set<string> {
450
+ const counts = new Map<string, number>();
451
+ for (const sibling of siblings) {
452
+ for (const text of new Set(promptLines(sibling).lines.map((l) => l.text))) counts.set(text, (counts.get(text) ?? 0) + 1);
453
+ }
454
+ return new Set([...counts].filter(([, n]) => n >= SIBLING_SHARED_MIN).map(([text]) => text));
455
+ }
456
+
457
+ const TOKEN_RE = /[\p{L}\p{N}_]+(?:[.\-][\p{L}\p{N}_]+)*/gu;
458
+
459
+ /** Lowercased words; dotted/hyphenated identifiers stay one word (`p1.4`, `signals.ts`); 1-char words only when numeric. */
460
+ function words(text: string): Set<string> {
461
+ const out = new Set<string>();
462
+ for (const match of text.toLowerCase().matchAll(TOKEN_RE)) {
463
+ const w = match[0];
464
+ if (w.length >= 2 || /^\p{N}$/u.test(w)) out.add(w);
465
+ }
466
+ return out;
467
+ }
468
+
469
+ function dice(a: ReadonlySet<string>, b: ReadonlySet<string>): number {
470
+ let shared = 0;
471
+ for (const w of a) if (b.has(w)) shared += 1;
472
+ return (2 * shared) / (a.size + b.size);
473
+ }
474
+
475
+ /** Overlap coefficient |a ∩ b| / min(|a|, |b|) of two non-empty sets. */
476
+ function overlap(a: ReadonlySet<string>, b: ReadonlySet<string>): number {
477
+ let shared = 0;
478
+ for (const w of a) if (b.has(w)) shared += 1;
479
+ return shared / Math.min(a.size, b.size);
480
+ }
481
+
482
+ /**
483
+ * Dice coefficient of the two texts' word sets, capped, when BOTH texts have identifier words (a digit or a dot: plan
484
+ * steps, versions, files), by the overlap coefficient of those: `P1.4` and `P1.5` are different tasks, while a retry that
485
+ * adds identifiers (`attempt 2`, `lexer.test.ts line 42`) still covers the original's (QA-P14-2-2). 0 when either text
486
+ * has fewer than {@link REDISPATCH_MIN_TOKENS} words.
487
+ */
488
+ export function taskSimilarity(a: string, b: string): number {
489
+ const wa = words(a);
490
+ const wb = words(b);
491
+ if (wa.size < REDISPATCH_MIN_TOKENS || wb.size < REDISPATCH_MIN_TOKENS) return 0;
492
+ const isIdentifier = (w: string): boolean => /[\p{N}.]/u.test(w);
493
+ const ia = new Set([...wa].filter(isIdentifier));
494
+ const ib = new Set([...wb].filter(isIdentifier));
495
+ const all = dice(wa, wb);
496
+ return ia.size === 0 || ib.size === 0 ? all : Math.min(all, overlap(ia, ib));
497
+ }
498
+
499
+ /**
500
+ * Has `current` dispatched again the task of an earlier attempt, to a higher tier, within the window? Candidates: the
501
+ * same parent, class and role, another addressable child, dispatched before `current` and (when known) ended before it,
502
+ * at most `windowMs` after the previous attempt's end (else its start). For each candidate, most recent first:
503
+ * 1. siblings = the parent's other dispatches, minus earlier attempts of the same task (their compared lines, without
504
+ * their own template lines found in ≥ 2 other dispatches, lie ≥ {@link SAME_TASK_LINE_SHARE} inside the pair's), so a
505
+ * third dispatch is not judged against its own history and a templated sibling still teaches the template;
506
+ * 2. lines shared with ≥ {@link SIBLING_SHARED_MIN} siblings are boilerplate and removed BEFORE comparing;
507
+ * 3. the TASK sections alone are compared (the whole remaining text when either prompt has no TASK header).
508
+ * The most recent earlier attempt of the same task decides: a lower tier gets a failure (0.5); the same or a higher
509
+ * tier, a resume, an unknown tier, or an attempt whose stop may have been budget or authority ({@link penalisable}) gets
510
+ * nothing. Residual: with fewer than two siblings a template cannot be learnt (pass the prompt without the router header).
511
+ * Only the {@link REDISPATCH_MAX_EARLIER} most recent dispatches of the parent are read; each prompt is parsed once.
512
+ */
513
+ export function detectRedispatch(
514
+ current: DispatchText,
515
+ earlier: readonly DispatchText[],
516
+ tiers: readonly string[],
517
+ options: RedispatchOptions = {},
518
+ ): RedispatchMatch | null {
519
+ if (current.resume === true || !Number.isFinite(current.at) || current.class === null) return null;
520
+ const windowMs = options.windowMs ?? REDISPATCH_WINDOW_MS;
521
+ const threshold = options.threshold ?? REDISPATCH_SIMILARITY;
522
+ let family = earlier.filter((d) => d.parentSessionID === current.parentSessionID && d.decisionID !== current.decisionID);
523
+ if (family.length > REDISPATCH_MAX_EARLIER) {
524
+ // QA-P14-3-1: only the most recent dispatches of the parent (stable: ties keep their input order).
525
+ const at = (d: DispatchText): number => (Number.isFinite(d.at) ? d.at : Number.NEGATIVE_INFINITY);
526
+ family = [...family].sort((x, y) => (at(x) > at(y) ? -1 : at(x) < at(y) ? 1 : 0)).slice(0, REDISPATCH_MAX_EARLIER);
527
+ }
528
+ const role = current.role ?? null;
529
+
530
+ // QA-P14-3-1: every prompt is parsed once per call, and one count map (line → dispatches of family ∪ current containing
531
+ // it) serves every leave-one-out count, so the cost is C × F × L, not C × F² parses.
532
+ const parsed = new Map<DispatchText, { readonly lines: PromptLines; readonly texts: ReadonlySet<string> }>();
533
+ const parse = (d: DispatchText): { readonly lines: PromptLines; readonly texts: ReadonlySet<string> } => {
534
+ let entry = parsed.get(d);
535
+ if (entry === undefined) {
536
+ const lines = promptLines(d.prompt);
537
+ entry = { lines, texts: new Set(lines.lines.map((l) => l.text)) };
538
+ parsed.set(d, entry);
539
+ }
540
+ return entry;
541
+ };
542
+ const counts = new Map<string, number>();
543
+ for (const d of [...family, current]) for (const t of parse(d).texts) counts.set(t, (counts.get(t) ?? 0) + 1);
544
+
545
+ const candidates = family
546
+ .filter((d) => {
547
+ if (d.childSessionID === null || d.childSessionID === current.childSessionID) return false;
548
+ if (d.class !== current.class || (d.role ?? null) !== role || !(current.at > d.at)) return false;
549
+ const ended = typeof d.endedAt === "number" && Number.isFinite(d.endedAt) ? d.endedAt : null;
550
+ if (ended !== null && current.at < ended) return false; // still running: a parallel dispatch, not a re-dispatch
551
+ return current.at - (ended ?? d.at) <= windowMs;
552
+ })
553
+ .sort((x, y) => y.at - x.at);
554
+
555
+ const currentLines = parse(current).lines;
556
+ for (const previous of candidates) {
557
+ const previousParsed = parse(previous);
558
+ const previousLines = previousParsed.lines;
559
+ const sectionMode = currentLines.hasTask && previousLines.hasTask;
560
+ const compared = (p: PromptLines): string[] => p.lines.filter((l) => !sectionMode || l.section === "TASK").map((l) => l.text);
561
+ const pair = new Set([...compared(currentLines), ...compared(previousLines)]);
562
+ // Leave-one-out (QA-P14-2-1): a sibling's own template lines (present in ≥ SIBLING_SHARED_MIN OTHER dispatches of the
563
+ // parent, `current` included, `previous` and the sibling itself excluded) do not count when judging whether the
564
+ // sibling is an earlier attempt of the same task; the raw share decides only when nothing else is left.
565
+ // count(t) − [sibling has t] (always 1: t is one of its lines) − [previous has t].
566
+ const othersWith = (t: string): number => (counts.get(t) ?? 0) - 1 - (previousParsed.texts.has(t) ? 1 : 0);
567
+ const siblings = family.filter((d) => {
568
+ if (d === previous) return false;
569
+ const own = compared(parse(d).lines);
570
+ if (own.length === 0) return false;
571
+ const specific = own.filter((t) => othersWith(t) < SIBLING_SHARED_MIN);
572
+ const judged = specific.length > 0 ? specific : own;
573
+ return judged.filter((t) => pair.has(t)).length / judged.length < SAME_TASK_LINE_SHARE;
574
+ });
575
+ // Lines shared with ≥ SIBLING_SHARED_MIN siblings (as `sharedLines`, from the parsed sets).
576
+ const siblingCounts = new Map<string, number>();
577
+ for (const d of siblings) for (const t of parse(d).texts) siblingCounts.set(t, (siblingCounts.get(t) ?? 0) + 1);
578
+ const text = (p: PromptLines): string => compared(p).filter((t) => (siblingCounts.get(t) ?? 0) < SIBLING_SHARED_MIN).join("\n");
579
+ const similarity = taskSimilarity(text(currentLines), text(previousLines));
580
+ if (similarity < threshold) continue;
581
+ // The most recent earlier attempt of the same task decides.
582
+ const from = tierRank(previous.tier, tiers);
583
+ const to = tierRank(current.tier, tiers);
584
+ if (from === null || to === null || to <= from) return null;
585
+ if (!penalisable(previous)) return null;
586
+ return { previous, similarity, observation: observe("redispatch", "fail", SIGNAL_WEIGHTS.redispatch) };
587
+ }
588
+ return null;
589
+ }
590
+
591
+ // ---------------------------------------------------------------------------
592
+ // Signal rows
593
+ // ---------------------------------------------------------------------------
594
+
595
+ export interface SignalRowInput {
596
+ /** ISO-8601 UTC. */
597
+ readonly ts: string;
598
+ /** Parent (orchestrator) session. */
599
+ readonly sessionID: string;
600
+ /** The annotated attempt's decision id (the row joins its dispatch row on it). */
601
+ readonly decisionID: string;
602
+ readonly mode: LoggedRoutingMode;
603
+ readonly childSessionID: string | null;
604
+ readonly facts: DecisionFacts;
605
+ /** The attempt's dispatched key. */
606
+ readonly chosen: RouteChoice;
607
+ readonly step: LadderStepKind;
608
+ /** The annotated attempt (ingest's dedupe identity; statistics dedupe on it too). */
609
+ readonly attemptID?: string;
610
+ readonly role?: string;
611
+ readonly tier?: string;
612
+ }
613
+
614
+ /** Reason of a signal row: `note:signal:<kind>:<outcome>`. */
615
+ export function signalReason(observation: SignalObservation): string {
616
+ return `${SIGNAL_REASON}${observation.kind}:${observation.outcome}`;
617
+ }
618
+
619
+ /**
620
+ * A signal row: a decision row that annotates the attempt (reason `note:signal:…`, `signal`, `signalWeight`). It is never
621
+ * a dispatch: `summarize` leaves it out, `summarizeRoles` counts it under the dispatch it joins. Readers before P1.4
622
+ * drop it only through the C7 decision-id dedupe (it shares its dispatch's id): downgrading is unsupported.
623
+ */
624
+ export function signalRow(input: SignalRowInput, observation: SignalObservation): DecisionRow {
625
+ return {
626
+ v: LOG_ROW_VERSION,
627
+ kind: "decision",
628
+ ts: input.ts,
629
+ sessionID: input.sessionID,
630
+ decisionID: input.decisionID,
631
+ mode: input.mode,
632
+ childSessionID: input.childSessionID,
633
+ facts: input.facts,
634
+ chosen: input.chosen,
635
+ best: null,
636
+ switched: false,
637
+ pinned: false,
638
+ unit: "ratio",
639
+ costs: {},
640
+ confidence: input.facts.confidence,
641
+ reason: signalReason(observation),
642
+ step: input.step,
643
+ resume: false,
644
+ ...(input.attemptID === undefined ? {} : { attemptID: input.attemptID }),
645
+ ...(input.role === undefined ? {} : { role: input.role }),
646
+ ...(input.tier === undefined ? {} : { tier: input.tier }),
647
+ signal: observation.kind,
648
+ signalWeight: signedWeight(observation),
649
+ };
650
+ }