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,404 @@
1
+ /**
2
+ * Plan fan-out (M4) — annotate every step of a plan with `[tier:X]` and a `[route …]` line in one pass.
3
+ *
4
+ * Design: `docs/qa/cost-aware-routing/phase-1.4.md` → "Design (1.4.1)" §5. Plan #74 §0.10.12 and 2.4.4
5
+ * (`/annotate-plan`), D13 (`[route pin]`), A22 (a route line is recognised in trusted positions only).
6
+ *
7
+ * - ONE batched classification per call (`deps.classifyMany`, which chunks to `MAX_BATCH_ITEMS` itself).
8
+ * - A `[tier:X]` or `[route …]` already in a step (outside fenced code blocks, QA-1.4-9) is authoritative and
9
+ * is never re-emitted or duplicated, so annotating an annotated plan returns byte-identical text. The one
10
+ * edit made to an existing route line is appending ` pin` when the step must be pinned (`[tier:heavy]` or a
11
+ * QA step, QA-1.4-7), which is reported (`routeEdited`).
12
+ * - A QA step (QA-1.4-13: a leading `QA` word or `QA review|round|pass|…`) without a tier tag gets `heavy` if
13
+ * the preset has it, else the default tier, and is pinned (QA-1.4-8). The match is deliberately narrow: a
14
+ * false positive forces the heavy tier, a false negative only leaves the engine's normal choice.
15
+ * - Without a tier tag the engine picks the class's static tier and lets the kernel move it only on
16
+ * evidence (`MIN_EVIDENCE_TO_MOVE`, the same gate as the `R:` line): an empty store annotates exactly the
17
+ * static mapping.
18
+ * - The route line is placed right after the step's first task line, indented at most 3 columns (the
19
+ * parser ignores 4+), and `dispatchPrompt` always starts with it (A22).
20
+ *
21
+ * Pure apart from awaiting the injected `classifyMany`: no I/O, no clock, no randomness, no module state.
22
+ */
23
+
24
+ import type { ResolvedRouting, RouterConfig } from "../../router/config";
25
+ import { parseAcceptanceBlock } from "../../verify/dod";
26
+ import { fenceMask } from "../classify/fences";
27
+ import { parseRouteLine } from "../classify/route-line";
28
+ import {
29
+ CLASS_STATIC_TIER,
30
+ DETECTIONS,
31
+ NEEDS,
32
+ RISKS,
33
+ SCOPES,
34
+ TASK_CLASSES,
35
+ UNKNOWN_FACTS,
36
+ type ClassifyInput,
37
+ type ClassifyResult,
38
+ type Detection,
39
+ type TaskFacts,
40
+ } from "../classify/types";
41
+ import type { ModelPricing } from "../outcomes/types";
42
+ import { decide, hasMinEvidence } from "./kernel";
43
+ import { buildLadder, type LadderBuildInput, floorRankOf, resolveChosen, routerTierIds } from "./ladders";
44
+ import type { Decision, EngineStoreView, HostAgentInfo } from "./types";
45
+
46
+ export interface PlanStep {
47
+ readonly id: string;
48
+ /** First line = the step's task line. */
49
+ readonly text: string;
50
+ }
51
+
52
+ export interface AnnotateDeps {
53
+ readonly cfg: RouterConfig;
54
+ readonly routing: ResolvedRouting;
55
+ readonly agents: readonly HostAgentInfo[] | null;
56
+ readonly store: EngineStoreView | null;
57
+ readonly pricing?: (model: string) => ModelPricing;
58
+ /** Forwarded to `buildLadder`: the runner policy's session input (A25), the parent model, the pricing logger. */
59
+ readonly session?: LadderBuildInput["session"];
60
+ readonly parentModel?: string | null;
61
+ readonly logger?: LadderBuildInput["logger"];
62
+ /** 1.2 `classifyMany` bound to its deps with `routeLinePositions: "any"` (tooling); called exactly once. */
63
+ readonly classifyMany: (inputs: readonly ClassifyInput[]) => Promise<ClassifyResult[]>;
64
+ }
65
+
66
+ export interface AnnotatedStep {
67
+ readonly id: string;
68
+ readonly tier: string;
69
+ readonly tierSource: "existing" | "engine";
70
+ readonly routeLine: string;
71
+ readonly routeSource: "existing" | "engine";
72
+ /** An existing route line was minimally edited to add ` pin` (a `[tier:heavy]` or QA step, QA-1.4-7). */
73
+ readonly routeEdited: boolean;
74
+ readonly facts: TaskFacts;
75
+ readonly detection: Detection;
76
+ readonly pin: boolean;
77
+ readonly decision: Decision | null;
78
+ /** Annotated step text. */
79
+ readonly text: string;
80
+ /** `text` differs from the step the caller passed in. */
81
+ readonly changed: boolean;
82
+ /** Route line FIRST (A22), then the annotated step text without route lines; joined with the step's own line ending. */
83
+ readonly dispatchPrompt: string;
84
+ }
85
+
86
+ // ---------------------------------------------------------------------------
87
+ // Pure helpers
88
+ // ---------------------------------------------------------------------------
89
+
90
+ const TIER_TAG_RE = /\[tier:([A-Za-z0-9_-]+)\]/;
91
+ /**
92
+ * QA-1.4-13 / QA-1.4-18: a QA step
93
+ * - starts with the word `QA` (after list, heading or emphasis markers: `QA the release`, `- QA: verify`,
94
+ * `## QA round 2`), or
95
+ * - names a QA activity (`QA review`, `QA round`, `QA pass`, `QA sign-off`, `QA gate`, `QA cycle`, `QA phase`), or
96
+ * - puts a verb or an adjective in front of it (`Run QA on phase 3`, `Perform the QA`, `Do QA for …`,
97
+ * `Final QA`, `Adversarial QA`, `Senior QA review`), or
98
+ * - has `QA` followed by `on` / `of` / `for`, a colon, or the end of the line (`Phase 3 QA on the build`).
99
+ * Case-sensitive for `QA`. The word never continues into a finding or ticket id (`QA-1.4-3`, `QA2`) or a longer
100
+ * word (`QAT`). `Write the QA notes`, `Update the QA docs` and `Fix QA-1.4-3 finding` are routine work: a false
101
+ * positive forces the heavy tier, a false negative only leaves the engine's normal choice.
102
+ */
103
+ const QA_WORD = "QA(?![A-Za-z0-9_]|-[A-Za-z0-9])";
104
+ const QA_LEADING_RE = new RegExp(`^(?:[-*+>#]+\\s*|\\d+[.)]\\s+|\\*\\*|__|\\s)*${QA_WORD}`);
105
+ const QA_PHRASE_RE = /\bQA[ -](?:review|round|pass|sign-?off|gate|cycle|phase)\b/;
106
+ const QA_VERB_RE = new RegExp(`\\b(?:[Rr]un|[Pp]erform|[Dd]o|[Ff]inal|[Aa]dversarial|[Ss]enior)(?:\\s+(?:the|a|an))?\\s+${QA_WORD}`);
107
+ const QA_CONTEXT_RE = new RegExp(`\\b${QA_WORD}(?:\\s+(?:on|of|for)\\b|\\s*:|\\s*$)`);
108
+ const LINE_SPLIT_RE = /(\r\n|\n|\r)/;
109
+ const DESCRIPTION_MAX_CHARS = 200;
110
+
111
+ function isMember<T extends string>(values: readonly T[], value: unknown): value is T {
112
+ return typeof value === "string" && (values as readonly string[]).includes(value);
113
+ }
114
+
115
+ /**
116
+ * QA-1.4-20: a `[tier:X]` inside an inline code span is documentation, not a tag. A span opens with a run of
117
+ * backticks and closes with a run of the SAME length (CommonMark); an unclosed run is plain text.
118
+ */
119
+ const INLINE_CODE_RE = /(?<!`)(`+)(?!`)[\s\S]*?(?<!`)\1(?!`)/g;
120
+
121
+ function withoutInlineCode(line: string): string {
122
+ return line.includes("`") ? line.replace(INLINE_CODE_RE, " ") : line;
123
+ }
124
+
125
+ function isQaLine(line: string): boolean {
126
+ return QA_LEADING_RE.test(line) || QA_PHRASE_RE.test(line) || QA_VERB_RE.test(line) || QA_CONTEXT_RE.test(line);
127
+ }
128
+
129
+ /**
130
+ * Verification depth of a step (`d = routing.detection[detection]`): the verifier's own `[acceptance]`
131
+ * parser decides. Any machine check → `deterministic`; only `criteria:` (an LLM grader is scheduled) →
132
+ * `grader`; otherwise `none`.
133
+ */
134
+ export function detectionOf(stepText: string): Detection {
135
+ const dod = parseAcceptanceBlock(typeof stepText === "string" ? stepText : "");
136
+ if (dod === null) return "none";
137
+ if (dod.checks.length > 0) return "deterministic";
138
+ if (dod.criteria.length > 0) return "grader";
139
+ return "none";
140
+ }
141
+
142
+ /** Strength order of the detection vocabulary: `none` < `grader` < `deterministic`. */
143
+ const DETECTION_STRENGTH: Readonly<Record<Detection, number>> = Object.freeze({ none: 0, grader: 1, deterministic: 2 });
144
+
145
+ /**
146
+ * A34 (QA-G-B2): the detection a dispatch is decided with — the WEAKER of the route line's `d=` claim and what the prompt's own
147
+ * `[acceptance]` block makes the verifier run (`detectionOf`). A route line is written by the orchestrator (an LLM); detection is
148
+ * the one field of it that can weaken a safety rule (D9 never-down holds only for `d == none`), so a claim never raises it above
149
+ * what the verifier will really check. No claim (`null`/`undefined`): the prompt alone decides.
150
+ */
151
+ export function weakerDetection(claimed: Detection | null | undefined, observed: Detection): Detection {
152
+ if (claimed === null || claimed === undefined || !isMember(DETECTIONS, claimed)) return observed;
153
+ return DETECTION_STRENGTH[claimed] < DETECTION_STRENGTH[observed] ? claimed : observed;
154
+ }
155
+
156
+ /**
157
+ * `[route class=<c> risk=<r> scope=<s>[ needs=<a,b>] d=<d>[ pin]]` — fixed field order, `needs` omitted
158
+ * when empty, values from the 1.2 vocabularies only (anything else would be ignored by the parser).
159
+ */
160
+ export function formatRouteLine(facts: TaskFacts, detection: Detection, pin: boolean): string {
161
+ const cls = isMember(TASK_CLASSES, facts.class) ? facts.class : "other";
162
+ const risk = isMember(RISKS, facts.risk) ? facts.risk : "medium";
163
+ const scope = isMember(SCOPES, facts.scope) ? facts.scope : "single";
164
+ const needs = NEEDS.filter((need) => Array.isArray(facts.needs) && facts.needs.includes(need));
165
+ const d = isMember(DETECTIONS, detection) ? detection : "none";
166
+ const parts = [`class=${cls}`, `risk=${risk}`, `scope=${scope}`];
167
+ if (needs.length > 0) parts.push(`needs=${needs.join(",")}`);
168
+ parts.push(`d=${d}`);
169
+ if (pin) parts.push("pin");
170
+ return `[route ${parts.join(" ")}]`;
171
+ }
172
+
173
+ const PIN_FIELD_RE = /(\s)pin(?:\s*=\s*[^\s\]]*)?(?=[\s\]])/i;
174
+
175
+ /**
176
+ * The minimal edit that pins an existing route line: an explicit `pin=false`-style field becomes `pin`, a
177
+ * line without the field gets ` pin` before its closing bracket. Everything else (indentation, fields,
178
+ * trailing whitespace) is kept byte for byte. A line that already pins is returned as is.
179
+ */
180
+ function withPin(line: string): string {
181
+ if (PIN_FIELD_RE.test(line)) return line.replace(PIN_FIELD_RE, (_whole, space: string) => `${space}pin`);
182
+ return line.replace(/\s*\](\s*)$/, (_whole, tail: string) => ` pin]${tail}`);
183
+ }
184
+
185
+ /** One step's text, split into lines with the structure the annotation needs (QA-1.4-9). */
186
+ interface Scan {
187
+ /** Line contents, without terminators. */
188
+ readonly lines: string[];
189
+ /** `terminators[i]` follows `lines[i]`; one fewer than `lines`. */
190
+ readonly terminators: string[];
191
+ /** The step's own line ending (its first terminator, else `\n`). */
192
+ readonly eol: string;
193
+ /** Indices of the recognised route lines: outside fenced code blocks, plain, unindented, unquoted. */
194
+ readonly routeAt: readonly number[];
195
+ /** The task line: first non-empty line that is unfenced (so no fence marker either) and not a route line; -1 = none. */
196
+ readonly taskAt: number;
197
+ /** The first `[tier:X]` tag outside fenced blocks. */
198
+ readonly tierTag: string | null;
199
+ }
200
+
201
+ function scanStep(text: string): Scan {
202
+ const parts = text.split(LINE_SPLIT_RE);
203
+ const lines: string[] = [];
204
+ const terminators: string[] = [];
205
+ parts.forEach((part, index) => {
206
+ if (index % 2 === 0) lines.push(part);
207
+ else terminators.push(part);
208
+ });
209
+ const fenced = fenceMask(lines);
210
+ const routeAt: number[] = [];
211
+ let taskAt = -1;
212
+ let tierTag: string | null = null;
213
+ lines.forEach((line, index) => {
214
+ if (fenced[index] === true) return;
215
+ if (parseRouteLine(line, { positions: "any" }).count > 0) {
216
+ routeAt.push(index);
217
+ return;
218
+ }
219
+ if (taskAt < 0 && line.trim() !== "") taskAt = index;
220
+ if (tierTag === null) tierTag = TIER_TAG_RE.exec(withoutInlineCode(line))?.[1] ?? null;
221
+ });
222
+ return { lines, terminators, eol: terminators[0] ?? "\n", routeAt, taskAt, tierTag };
223
+ }
224
+
225
+ /** What `placeAnnotations` changes in a step. */
226
+ interface Edits {
227
+ /** ` [tier:X]` appended to the task line. */
228
+ readonly tag: string | null;
229
+ /** A new route line inserted right after the task line. */
230
+ readonly insertRoute: string | null;
231
+ /** The first existing route line replaced by this (a minimal edit of it). */
232
+ readonly replaceRoute: string | null;
233
+ }
234
+
235
+ function placeAnnotations(scan: Scan, edits: Edits): string {
236
+ const lines = [...scan.lines];
237
+ const terminators = [...scan.terminators];
238
+ if (edits.replaceRoute !== null && scan.routeAt[0] !== undefined) lines[scan.routeAt[0]] = edits.replaceRoute;
239
+ const at = scan.taskAt;
240
+ if (at >= 0) {
241
+ if (edits.tag !== null) lines[at] = `${lines[at]!.trimEnd()} ${edits.tag}`;
242
+ if (edits.insertRoute !== null) {
243
+ // Leading SPACES only, at most 3: the route-line parser ignores 4+ columns and counts a tab as 4.
244
+ const indent = (/^ */.exec(lines[at]!)?.[0] ?? "").slice(0, 3);
245
+ lines.splice(at + 1, 0, `${indent}${edits.insertRoute}`);
246
+ terminators.splice(at, 0, terminators[at] ?? scan.eol);
247
+ }
248
+ }
249
+ return lines.map((line, index) => line + (terminators[index] ?? "")).join("");
250
+ }
251
+
252
+ /** What the classifier itself returns when it fails (`UNKNOWN_FACTS`, confidence 0 ⇒ never switches). */
253
+ function unknownResult(text: string): ClassifyResult {
254
+ return {
255
+ facts: UNKNOWN_FACTS,
256
+ pin: false,
257
+ detection: null,
258
+ stripped: text,
259
+ trace: {
260
+ rules: UNKNOWN_FACTS,
261
+ routeLine: null,
262
+ routeLines: { count: 0, conflict: false, edgeOnly: true },
263
+ backend: null,
264
+ },
265
+ };
266
+ }
267
+
268
+ // ---------------------------------------------------------------------------
269
+ // annotateSteps
270
+ // ---------------------------------------------------------------------------
271
+
272
+ /**
273
+ * The annotated steps, in order, plus how many of them THIS annotation pinned (A26, QA-1.4-19): steps given an
274
+ * engine route line that carries `pin`, or an existing route line edited to add it. A step that was already
275
+ * pinned, or whose text did not change, is not counted, so annotating an annotated plan reports 0.
276
+ * `pinnedCount` is a non-enumerable property: the result still compares and iterates as a plain array.
277
+ */
278
+ export type AnnotatedPlan = AnnotatedStep[] & { readonly pinnedCount: number };
279
+
280
+ function withPinnedCount(steps: AnnotatedStep[]): AnnotatedPlan {
281
+ const pinnedCount = steps.filter((a) => a.pin && a.changed && (a.routeEdited || a.routeSource === "engine")).length;
282
+ const plan: AnnotatedPlan = Object.assign([...steps], { pinnedCount });
283
+ Object.defineProperty(plan, "pinnedCount", { enumerable: false });
284
+ return plan;
285
+ }
286
+
287
+ /**
288
+ * Annotate a plan's steps in one pass. Never throws for well-typed input: a classifier failure leaves the
289
+ * steps with `UNKNOWN_FACTS` (confidence 0, so the engine keeps the static tier and never switches).
290
+ * `steps` must already be split by the caller (2.4 owns plan parsing); fenced code blocks inside a step are
291
+ * respected (nothing inside a fence is a tag, a route line or a task line).
292
+ */
293
+ export async function annotateSteps(steps: readonly PlanStep[], deps: AnnotateDeps): Promise<AnnotatedPlan> {
294
+ if (steps.length === 0) return withPinnedCount([]);
295
+ const { cfg, routing, agents, store } = deps;
296
+
297
+ // --- one batched classification ---------------------------------------------------------------
298
+ const scans = steps.map((step) => scanStep(step.text));
299
+ const inputs: ClassifyInput[] = steps.map((step, index) => {
300
+ const scan = scans[index]!;
301
+ const description = (scan.taskAt < 0 ? "" : scan.lines[scan.taskAt]!).trim().slice(0, DESCRIPTION_MAX_CHARS);
302
+ return { description, prompt: step.text };
303
+ });
304
+ let results: readonly ClassifyResult[];
305
+ try {
306
+ results = await deps.classifyMany(inputs);
307
+ } catch {
308
+ results = steps.map((step) => unknownResult(step.text));
309
+ }
310
+
311
+ const floorRank = floorRankOf(cfg);
312
+ const tierIds = routerTierIds(cfg);
313
+ const annotated: AnnotatedStep[] = [];
314
+ steps.forEach((step, index) => {
315
+ const result = results[index] ?? unknownResult(step.text);
316
+ const facts = result.facts;
317
+ const scan = scans[index]!;
318
+ const taskLine = scan.taskAt < 0 ? "" : scan.lines[scan.taskAt]!;
319
+
320
+ // Existing tags are authoritative and kept verbatim.
321
+ const existingTier = scan.tierTag;
322
+ const existingRoute = scan.routeAt[0] === undefined ? null : scan.lines[scan.routeAt[0]]!;
323
+ const parsed = parseRouteLine(step.text, { positions: "any" });
324
+ const routePins = result.pin === true || parsed.line?.pin === true;
325
+
326
+ const detection = weakerDetection(result.detection, detectionOf(step.text));
327
+ // A `[tier:heavy]` step and a QA step are pinned (D13): the engine never moves them.
328
+ const qaStep = isQaLine(taskLine);
329
+ const decisionPin = routePins || existingTier === "heavy" || qaStep;
330
+
331
+ // The orchestrator's pick: the plan's tag; else heavy for a QA step; else the class's static tier. A tier
332
+ // the active preset lacks falls back to the config's default tier (never tag a ghost tier).
333
+ const mapped = CLASS_STATIC_TIER[facts.class] ?? cfg.defaultTier;
334
+ const staticTier = tierIds.includes(mapped) || !tierIds.includes(cfg.defaultTier) ? mapped : cfg.defaultTier;
335
+ const qaTier = tierIds.includes("heavy") ? "heavy" : cfg.defaultTier;
336
+ const pickedTier = existingTier ?? (qaStep ? qaTier : staticTier);
337
+ const chosen = resolveChosen({ cfg, agents, agent: pickedTier });
338
+ const decision = chosen === null
339
+ ? null
340
+ : decide({
341
+ facts,
342
+ chosen,
343
+ ladder: buildLadder({
344
+ cfg,
345
+ routing,
346
+ facts,
347
+ agents,
348
+ ...(deps.pricing === undefined ? {} : { pricing: deps.pricing }),
349
+ ...(deps.session === undefined ? {} : { session: deps.session }),
350
+ ...(deps.parentModel === undefined ? {} : { parentModel: deps.parentModel }),
351
+ ...(deps.logger === undefined ? {} : { logger: deps.logger }),
352
+ }),
353
+ detection,
354
+ pin: decisionPin,
355
+ routing,
356
+ store,
357
+ floorRank,
358
+ });
359
+
360
+ let tier = pickedTier;
361
+ if (
362
+ existingTier === null &&
363
+ !qaStep &&
364
+ store !== null &&
365
+ decision !== null &&
366
+ decision.switched &&
367
+ decision.best !== null &&
368
+ decision.target !== null &&
369
+ hasMinEvidence(store.posterior(decision.best.key).n)
370
+ ) {
371
+ tier = decision.target.tier;
372
+ }
373
+
374
+ // A step that ends up tagged `[tier:heavy]` is pinned, because that is how the next pass and the dispatch
375
+ // read the tag: annotating the annotated plan must change nothing (QA-1.4-9). The decision above was made
376
+ // before the tier was final, so an engine-chosen heavy could still have moved on evidence.
377
+ const pin = decisionPin || tier === "heavy";
378
+ // The route line: an existing one stays (plus ` pin` when the step must be pinned and it is not).
379
+ const editedRoute = existingRoute !== null && pin && !routePins ? withPin(existingRoute) : null;
380
+ const routeLine = (editedRoute ?? existingRoute ?? formatRouteLine(facts, detection, pin)).trim();
381
+ const text = placeAnnotations(scan, {
382
+ tag: existingTier === null ? `[tier:${tier}]` : null,
383
+ insertRoute: existingRoute === null ? routeLine : null,
384
+ replaceRoute: editedRoute,
385
+ });
386
+ const withoutRoute = parseRouteLine(text, { positions: "any" }).stripped;
387
+ annotated.push({
388
+ id: step.id,
389
+ tier,
390
+ tierSource: existingTier === null ? "engine" : "existing",
391
+ routeLine,
392
+ routeSource: existingRoute === null ? "engine" : "existing",
393
+ routeEdited: editedRoute !== null,
394
+ facts,
395
+ detection,
396
+ pin,
397
+ decision,
398
+ text,
399
+ changed: text !== step.text,
400
+ dispatchPrompt: `${routeLine}${scan.eol}${withoutRoute}`,
401
+ });
402
+ });
403
+ return withPinnedCount(annotated);
404
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * The generated `R:` taxonomy line (M4) — `buildTaskTaxonomy` plus an optional `by class:` suffix.
3
+ *
4
+ * Design: `docs/qa/cost-aware-routing/phase-1.4.md` → "Design (1.4.1)" §4. Plan #74 D2 (the degenerate
5
+ * case is byte-identical to today's line), D1 (v1 is a text-only opt-in), D12, amendment A11.
6
+ *
7
+ * - The base is `buildTaskTaxonomy(cfg)` itself, never re-implemented: with no evidence and no configured
8
+ * roles the output equals it byte for byte, by construction.
9
+ * - v1 (`host === "v1"`): only an explicitly configured `routing.roles` produces segments, listing the
10
+ * available agents per class. The outcome store is never read on v1.
11
+ * - v2: with a store, a class moves to another agent only when the kernel says `switched` AND `best` has at
12
+ * least {@link MIN_EVIDENCE_TO_MOVE} effective evidence. Priors alone can move a class in the kernel
13
+ * (e.g. `margin: 0`), so the evidence gate is what keeps the line static until data exists.
14
+ *
15
+ * v2 roles mode (plan #84 T2.2.1): with a non-empty role table the line maps class → role agent
16
+ * ({@link generateRolesTaxonomy}); tiers mode and v1 never pass one, so their line is unchanged.
17
+ *
18
+ * Pure: no I/O, no clock, no randomness, no module state.
19
+ */
20
+
21
+ import type { ResolvedRouting, RouterConfig, RouterHost } from "../../router/config";
22
+ import { buildTaskTaxonomy } from "../../router/protocol";
23
+ import type { RoleSpec } from "../../router/roles";
24
+ import {
25
+ CLASS_BASE_RISK,
26
+ CLASS_IMPLIED_NEEDS,
27
+ CLASS_STATIC_TIER,
28
+ TASK_CLASSES,
29
+ type TaskFacts,
30
+ } from "../classify/types";
31
+ import type { ModelPricing } from "../outcomes/types";
32
+ import { MIN_EVIDENCE_TO_SWITCH_DOWN, decide, hasMinEvidence } from "./kernel";
33
+ import { buildLadder, type LadderBuildInput, floorRankOf, resolveChosen, roleAgentExclusion, routerTierIds, tierRankOf } from "./ladders";
34
+ import type { EngineStoreView, HostAgentInfo } from "./types";
35
+ import { generateRolesTaxonomy } from "./roles-taxonomy";
36
+
37
+ /** `best` must carry evidence at least as strong as the prior before a class line moves (= `PRIOR_STRENGTH`). */
38
+ export const MIN_EVIDENCE_TO_MOVE: number = MIN_EVIDENCE_TO_SWITCH_DOWN;
39
+
40
+ export interface TaxonomyInput {
41
+ readonly cfg: RouterConfig;
42
+ readonly routing: ResolvedRouting;
43
+ readonly host: RouterHost;
44
+ readonly store: EngineStoreView | null;
45
+ readonly agents: readonly HostAgentInfo[] | null;
46
+ readonly pricing?: (model: string) => ModelPricing;
47
+ /** Forwarded to `buildLadder`: the runner policy's session input (A25), the parent model, the pricing logger. */
48
+ readonly session?: LadderBuildInput["session"];
49
+ readonly parentModel?: string | null;
50
+ readonly logger?: LadderBuildInput["logger"];
51
+ /**
52
+ * v2 roles mode (T2.2.1): the enabled role agents (`resolveRoles`). A non-empty table makes the line the
53
+ * class → role map of {@link generateRolesTaxonomy}; absent or empty, the tier line below is unchanged.
54
+ */
55
+ readonly roles?: ReadonlyMap<string, RoleSpec>;
56
+ }
57
+
58
+ /** The class → role line lives in a leaf module (QA-P22-1-11); re-exported here as part of the `R:` line API. */
59
+ export { CLASS_ROLE_KIND, generateRolesTaxonomy } from "./roles-taxonomy";
60
+
61
+ function ownRoleList(roles: Readonly<Record<string, readonly string[]>>, cls: string): readonly string[] {
62
+ const list = Object.hasOwn(roles, cls) ? roles[cls] : undefined;
63
+ return Array.isArray(list) ? [...new Set(list)] : [];
64
+ }
65
+
66
+ /** v1 text-only roles: the available agents of each configured class (no needs check, nothing classified). */
67
+ function v1Segments(input: TaxonomyInput): string[] {
68
+ const { cfg, routing, agents } = input;
69
+ if (routing.applied.rolesSource !== "configured" || agents === null) return [];
70
+ const routerIds = routerTierIds(cfg);
71
+ const segments: string[] = [];
72
+ for (const cls of TASK_CLASSES) {
73
+ const destinations = ownRoleList(routing.roles, cls).filter(
74
+ (id) => roleAgentExclusion(id, agents.find((agent) => agent.id === id), routerIds) === null,
75
+ );
76
+ if (destinations.length > 0) segments.push(`${cls}→${destinations.map((id) => `@${id}`).join("/")}`);
77
+ }
78
+ return segments;
79
+ }
80
+
81
+ /** v2: classes whose evidence-backed argmin is another agent than the static tier's. */
82
+ function v2Segments(input: TaxonomyInput, store: EngineStoreView): string[] {
83
+ const { cfg, routing, agents } = input;
84
+ const floorRank = floorRankOf(cfg);
85
+ const segments: string[] = [];
86
+ for (const cls of TASK_CLASSES) {
87
+ const staticTier = CLASS_STATIC_TIER[cls];
88
+ if (staticTier === null || tierRankOf(cfg, staticTier) === null) continue;
89
+ const facts: TaskFacts = {
90
+ class: cls,
91
+ risk: CLASS_BASE_RISK[cls],
92
+ scope: "single",
93
+ needs: CLASS_IMPLIED_NEEDS[cls],
94
+ confidence: 1,
95
+ source: "rules",
96
+ };
97
+ const chosen = resolveChosen({ cfg, agents, agent: staticTier });
98
+ if (chosen === null) continue;
99
+ const ladder = buildLadder({
100
+ cfg,
101
+ routing,
102
+ facts,
103
+ agents,
104
+ ...(input.pricing === undefined ? {} : { pricing: input.pricing }),
105
+ ...(input.session === undefined ? {} : { session: input.session }),
106
+ ...(input.parentModel === undefined ? {} : { parentModel: input.parentModel }),
107
+ ...(input.logger === undefined ? {} : { logger: input.logger }),
108
+ });
109
+ const decision = decide({ facts, chosen, ladder, detection: "none", pin: false, routing, store, floorRank });
110
+ if (!decision.switched || decision.best === null || decision.target === null) continue;
111
+ if (decision.best.agent === staticTier) continue; // a variant change inside the same tier never changes the line
112
+ if (!hasMinEvidence(store.posterior(decision.best.key).n)) continue;
113
+ segments.push(`${cls}→@${decision.best.agent}`);
114
+ }
115
+ return segments;
116
+ }
117
+
118
+ /**
119
+ * The `R:` line the protocol should carry: `buildTaskTaxonomy(cfg)` unchanged unless a class has somewhere
120
+ * better to go, then `<base> | by class: c→@agent …` (`R: by class: …` when the base is empty or the bare
121
+ * `R:` header). Classes are listed in `TASK_CLASSES` order, so the text depends on the inputs and never on
122
+ * key order.
123
+ *
124
+ * Engine gate (QA-1.4-5, D1): on v2 the line only changes when the resolved engine is `advise` or `enforce`;
125
+ * `static` and `shadow` never touch the protocol text. On v1 the engine is always `static`; the text-only
126
+ * opt-in is an explicitly configured `routing.roles` (D1), which is what the v1 branch reads.
127
+ *
128
+ * Handoff to 2.2 (QA-1.4-11): (1) substitute with a FUNCTION replacer, `protocol.replace(base, () => line)`:
129
+ * the line carries agent ids, and a string replacement would expand `$&`, `$1` or `$$` inside them;
130
+ * (2) when `buildTaskTaxonomy(cfg)` is empty the protocol has no `R:` line to replace: insert the generated
131
+ * line (`R: by class: …`) where the taxonomy would go, and only when it is non-empty.
132
+ */
133
+ export function generateTaxonomy(input: TaxonomyInput): string {
134
+ if (input.host === "v2" && input.roles !== undefined) {
135
+ const roleLine = generateRolesTaxonomy(input.roles);
136
+ if (roleLine !== "") return roleLine; // roles mode: class → role, never a tier
137
+ }
138
+ const base = buildTaskTaxonomy(input.cfg);
139
+ let segments: string[];
140
+ if (input.host === "v1") {
141
+ segments = v1Segments(input);
142
+ } else if (input.routing.engine !== "advise" && input.routing.engine !== "enforce") {
143
+ return base; // static or shadow: the shipped text, byte for byte
144
+ } else {
145
+ segments = input.store === null ? [] : v2Segments(input, input.store);
146
+ }
147
+ if (segments.length === 0) return base;
148
+ const suffix = `by class: ${segments.join(" ")}`;
149
+ return base === "" || base === "R:" ? `R: ${suffix}` : `${base} | ${suffix}`;
150
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The roles-mode `R:` line (plan #84 T2.2.1): task class → role agent.
3
+ *
4
+ * A leaf module (QA-P22-1-11): it imports only `TASK_CLASSES` and types, so `src/router/protocol.ts` can build the
5
+ * roles protocol without importing the routing engine (`protocol-line.ts` imports `protocol.ts`, which would make a
6
+ * cycle). `protocol-line.ts` re-exports both names.
7
+ *
8
+ * Pure: no I/O, no clock, no randomness, no module state.
9
+ */
10
+
11
+ import type { RoleKind, RoleSpec } from "../../router/roles";
12
+ import { TASK_CLASSES, type TaskClass } from "../classify/types";
13
+
14
+ /**
15
+ * The role kind that does each task class in roles mode (plan §2.2). `runner` and `researcher` have no class of
16
+ * their own: the orchestrator picks them by intent (running checks, web research) from the role menu.
17
+ */
18
+ export const CLASS_ROLE_KIND: Readonly<Record<TaskClass, RoleKind>> = Object.freeze({
19
+ search: "explore",
20
+ recon: "explore",
21
+ mechanical: "implement",
22
+ implement: "implement",
23
+ debug: "implement",
24
+ design: "design",
25
+ review: "review",
26
+ other: "general",
27
+ });
28
+
29
+ /**
30
+ * The roles-mode `R:` line: each class → the enabled role agent of {@link CLASS_ROLE_KIND}, else `general`, else
31
+ * the class is left out. Classes sharing an agent are grouped (`search/recon→explorer`), in `TASK_CLASSES` order;
32
+ * of two enabled agents of one kind the first by name wins. Depends on the table only (no tiers, no models, no
33
+ * evidence), so the text is stable for the whole session. "" when no class has an agent.
34
+ */
35
+ export function generateRolesTaxonomy(roles: ReadonlyMap<string, RoleSpec>): string {
36
+ const byKind = new Map<RoleKind, string>();
37
+ for (const spec of roles.values()) {
38
+ if (spec.enabled !== true) continue;
39
+ const held = byKind.get(spec.kind);
40
+ if (held === undefined || spec.agent < held) byKind.set(spec.kind, spec.agent);
41
+ }
42
+ const groups = new Map<string, TaskClass[]>();
43
+ for (const cls of TASK_CLASSES) {
44
+ const agent = byKind.get(CLASS_ROLE_KIND[cls]) ?? byKind.get("general");
45
+ if (agent === undefined) continue;
46
+ const classes = groups.get(agent);
47
+ if (classes === undefined) groups.set(agent, [cls]);
48
+ else classes.push(cls);
49
+ }
50
+ if (groups.size === 0) return "";
51
+ return `R: ${[...groups].map(([agent, classes]) => `${classes.join("/")}→${agent}`).join(" ")}`;
52
+ }