opencode-model-router 2.3.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 (61) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/README.md +56 -10
  3. package/package.json +1 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1322 -18
  6. package/src/escalate/ladder.ts +12 -0
  7. package/src/guard/enforce.ts +186 -22
  8. package/src/guard/guards.ts +132 -6
  9. package/src/guard/store.ts +5 -0
  10. package/src/index.ts +718 -29
  11. package/src/router/config.ts +247 -1
  12. package/src/router/dispatch-header.ts +46 -4
  13. package/src/router/git-tools.ts +1152 -0
  14. package/src/router/guard-profile.ts +100 -0
  15. package/src/router/plugin-agents.ts +433 -0
  16. package/src/router/prompts.ts +26 -1
  17. package/src/router/protocol.ts +133 -0
  18. package/src/router/read-only.ts +149 -0
  19. package/src/router/role-agents.ts +409 -0
  20. package/src/router/roles-config.ts +429 -0
  21. package/src/router/roles.ts +600 -0
  22. package/src/router/run-tools.ts +913 -0
  23. package/src/router/sensitive-paths.ts +101 -0
  24. package/src/router/sessions.ts +92 -0
  25. package/src/router/subagents.ts +28 -1
  26. package/src/routing/advisor/findings.ts +193 -1
  27. package/src/routing/advisor/index.ts +13 -5
  28. package/src/routing/classify/index.ts +23 -5
  29. package/src/routing/classify/route-line.ts +67 -3
  30. package/src/routing/classify/rules.ts +80 -20
  31. package/src/routing/classify/types.ts +34 -4
  32. package/src/routing/commands/stats.ts +3 -0
  33. package/src/routing/engine/kernel.ts +163 -0
  34. package/src/routing/engine/ladders.ts +242 -1
  35. package/src/routing/engine/protocol-line.ts +17 -0
  36. package/src/routing/engine/roles-taxonomy.ts +52 -0
  37. package/src/routing/engine/types.ts +99 -1
  38. package/src/routing/outcomes/beta.ts +10 -4
  39. package/src/routing/outcomes/index.ts +44 -1
  40. package/src/routing/outcomes/ingest.ts +163 -15
  41. package/src/routing/outcomes/persist.ts +23 -1
  42. package/src/routing/outcomes/signals.ts +650 -0
  43. package/src/routing/outcomes/stats.ts +273 -2
  44. package/src/routing/outcomes/store.ts +25 -5
  45. package/src/routing/outcomes/types.ts +145 -6
  46. package/src/routing/roles/authority.ts +495 -0
  47. package/src/routing/roles/binding.ts +543 -0
  48. package/src/routing/roles/policy.ts +416 -0
  49. package/src/routing/roles/work-root.ts +132 -0
  50. package/src/routing/wire/dispatch.ts +1306 -17
  51. package/src/routing/wire/hint.ts +14 -0
  52. package/src/routing/wire/runtime.ts +117 -28
  53. package/src/v2.ts +26 -1
  54. package/src/verify/checker.ts +249 -7
  55. package/src/verify/deterministic.ts +10 -1
  56. package/src/verify/dispatch.ts +63 -6
  57. package/src/verify/dod.ts +127 -10
  58. package/src/verify/gate.ts +75 -7
  59. package/src/verify/types.ts +12 -0
  60. package/src/verify/wiring.ts +55 -10
  61. package/tiers.json +13 -5
@@ -45,15 +45,29 @@ import {
45
45
  buildLadder, candidateKey, capabilityRank, coversNeeds, decide, detectionOf, escalateLadder, floorRankOf, lowerEffortOnSameModel, resolveChosen,
46
46
  tierRankOf, weakerDetection,
47
47
  } from "../engine";
48
- import { routerTierIds } from "../engine/ladders";
49
- import type { ChosenDispatch, Decision, HostAgentInfo, Ladder } from "../engine/types";
50
- import { classify } from "../classify";
51
- import type { ClassifyResult, Detection, TaskFacts } from "../classify/types";
52
- import type { RouterConfig } from "../../router/config";
48
+ import { buildRoleLadder, roleTierOrder, routerTierIds } from "../engine/ladders";
49
+ import { decideRole } from "../engine/kernel";
50
+ import type { Candidate, ChosenDispatch, Decision, HostAgentInfo, Ladder, RoleLadder } from "../engine/types";
51
+ import { CLASS_IMPLIED_NEEDS, FACT_SOURCES, NEEDS, RISKS, SCOPES, TASK_CLASSES, classify, classifyNeedMatches } from "../classify";
52
+ import type { ClassifyResult, Detection, Need, RouteLine, TaskFacts } from "../classify/types";
53
+ import { resolveVerifyBudget, type RouterConfig } from "../../router/config";
54
+ import { resolveEnforcementMode } from "../../router/enforcement";
55
+ import { roleGuardProfile } from "../../router/guard-profile";
56
+ import { resolveRoles, type AuthorityAction, type RoleSpec } from "../../router/roles";
57
+ import { parseVerifyDirectives } from "../../verify/directives";
58
+ import { buildDelegationDoD } from "../../verify/dispatch";
59
+ import { requestedVerificationCwd, verificationScope } from "../roles/work-root";
60
+ import { effectiveDetection, effectiveFactsOf, grantFor, tierBounds, type DispatchGrant, type EffectiveDetection } from "../roles/policy";
61
+ import {
62
+ BINDING_NOTES, LOCAL_ACTIONS, currentBinding, evictCall, newDispatchNonce, noncePromptLine, nonceTitleSuffix, registerPending, type Binding,
63
+ } from "../roles/binding";
64
+ import { realpathSync } from "node:fs";
53
65
  import {
54
66
  consumeRunnerDispatch, consumeRunnerDispatchLoose, forgetDispatch, lookupDispatch, rememberDispatch, runnerDescription,
55
- type DetectionDepth, type DispatchInput, type DispatchRecord,
67
+ updateDispatchVerification, type CarriedVerification, type DetectionDepth, type DispatchInput, type DispatchRecord,
56
68
  } from "../../router/sessions";
69
+ import type { ChangedFile } from "../../verify/dispatch";
70
+ import type { ReferenceState } from "../../verify/types";
57
71
  import { randomBytes } from "node:crypto";
58
72
  import {
59
73
  FLOOR_LIFT_REASON,
@@ -62,6 +76,7 @@ import {
62
76
  RESUME_PINNED_REASON,
63
77
  RESUME_NAMED_NEEDS_REASON,
64
78
  RESUME_NAMED_NEVER_DOWN_REASON,
79
+ ANNOTATION_REASON,
65
80
  LOG_ROW_VERSION,
66
81
  classifyAgentOrigin,
67
82
  makeKey,
@@ -73,7 +88,7 @@ import {
73
88
  type RouteChoice,
74
89
  } from "../outcomes/types";
75
90
  import { agentModelRef, type AgentView } from "./host-info";
76
- import { sessionRulesOf, type EngineRuntime, type Prepared, type WireLogger } from "./runtime";
91
+ import { sessionRulesOf, type EngineRuntime, type Prepared, type RolePrepared, type WireLogger } from "./runtime";
77
92
 
78
93
  /** A fresh dispatch can be claimed by a `session.created` event for at most this long. */
79
94
  export const PENDING_TTL_MS = 120_000;
@@ -97,19 +112,110 @@ export interface RouteCall {
97
112
  readonly tierModel?: string | undefined;
98
113
  /** The router config the caller already loaded for this call. */
99
114
  readonly cfg?: RouterConfig | undefined;
115
+ /**
116
+ * #84 P2.1, role dispatches only: actions widened for this resume (`consumeAuthority(…).widened`, P1.6). They enter
117
+ * `grantFor(…, widened, …)`, so the authority floor is recomputed on them (handoff 36). Absent = none.
118
+ */
119
+ readonly widened?: readonly AuthorityAction[] | undefined;
100
120
  }
101
121
 
102
122
  export interface RouteOutcome {
103
123
  readonly mode: "static" | "shadow" | "advise" | "enforce";
104
- /** The prompt without its first-line `[route …]`; only when something was stripped. */
124
+ /** The prompt without its first-line `[route …]`; only when something was stripped. Role dispatch: also ends with the nonce line. */
105
125
  readonly prompt?: string;
106
126
  /** `enforce`: the agent to dispatch instead (never for a pinned dispatch). */
107
127
  readonly agent?: string;
108
- /** `enforce`: `provider/model[#variant]` to dispatch with. */
128
+ /** `enforce`: `provider/model[#variant]` to dispatch with. Role dispatch: ALWAYS set, in every engine mode (I2). */
109
129
  readonly model?: string;
110
130
  readonly decisionID?: string;
131
+ /**
132
+ * #84 P2.1, a fresh role dispatch: the description with the nonce title suffix at its END (`nonceTitleSuffix`). The adapter
133
+ * must apply it like `prompt` (P2.1-C: `args.description = routed.description`).
134
+ */
135
+ readonly description?: string;
136
+ /** #84 P2.1: what the role path decided (absent for every tier dispatch). */
137
+ readonly role?: RoleRouted;
138
+ }
139
+
140
+ /** #84 P2.1: one routed role dispatch, as the adapter (P2.1-C) needs it (header root, guard profile, escalation hint). */
141
+ export interface RoleRouted {
142
+ readonly callID: string;
143
+ readonly parentSessionID: string;
144
+ /** The role agent. */
145
+ readonly agent: string;
146
+ /** The tier the dispatched rung belongs to (role × tier statistics, guard profile, escalation hint). */
147
+ readonly tier: string;
148
+ /** `provider/model[#variant]` set as the call's `model`. */
149
+ readonly model: string;
150
+ /** `tierBounds(…)` of the dispatch. */
151
+ readonly window: { readonly floor: string; readonly ceiling: string; readonly pinned: string | null };
152
+ readonly grant: DispatchGrant;
153
+ /** The validated work root (canonical long form), or null (no `root=` match, or the session directory could not be resolved). */
154
+ readonly workRoot: string | null;
155
+ /**
156
+ * #84 P3.3 DF2-F1 (QA-P33F1-1-1, 1-3): where the router's gate verifies this dispatch — the grant's work root (a resume keeps the
157
+ * child's bound root, whatever its prompt's route line says), else the canonical session directory (no validated work root).
158
+ */
159
+ readonly verifyRoot: string;
160
+ /** The route line's `root=` as written, or null. */
161
+ readonly requestedRoot: string | null;
162
+ /** Work-root, grant and catalog notes (for the dispatch header / parent result). */
163
+ readonly notes: readonly string[];
164
+ readonly detection: EffectiveDetection;
165
+ /** The dispatch's total call budget (`roleGuardProfile(spec, tier, routeLine.budget).budget`). */
166
+ readonly budget: number;
167
+ /** The route line's `budget=`, or null (pass it to `roleGuardProfile`, handoff 27). */
168
+ readonly routeBudget: number | null;
169
+ /** The nonce registered for a fresh dispatch; null on a resume (no pending entry). */
170
+ readonly nonce: string | null;
171
+ /** The decision row's id; null when no row is written (`engine: static`). */
172
+ readonly decisionID: string | null;
173
+ /** The resumed child (`sessionID`/`task_id`), or null. */
174
+ readonly resumeID: string | null;
175
+ /** The next tier of the role's range above `tier` (escalation hint, P-8); null at the ceiling. */
176
+ readonly nextTier: string | null;
177
+ /** The effective task class of the dispatch (re-dispatch signal, handoff 17); null when unknown. */
178
+ readonly class: string | null;
179
+ /**
180
+ * QA-G-A1-2: a delegate's dispatch (`decideDelegateRoleDispatch`: unparsed, the floor rung of the local-only window). The adapter
181
+ * never consumes an authority request on it. Absent for every orchestrator dispatch.
182
+ */
183
+ readonly delegate?: true;
184
+ /**
185
+ * QA-G-B-2-1: a resume that CARRIES the acceptance of the dispatch it resumes (it names no `[acceptance]` block of its own). Its
186
+ * gate runs at once — never deferred — on the child's cumulative change set since the attempt that introduced the block
187
+ * ({@link roleAttemptVerification}), and a check that ran no process is unverifiable. Absent otherwise.
188
+ */
189
+ readonly carried?: true;
111
190
  }
112
191
 
192
+ /**
193
+ * #84 P2.1: a role dispatch the router refuses (malformed first route line, no candidate inside the tier window, the router could not
194
+ * route it). `route()` THROWS it — the one exception to "never throws" — so the adapter's `execute.before` fails the call with this
195
+ * message and the host never runs the child. It never falls back to a tier agent (QA-P12-1-5).
196
+ */
197
+ export class RoleDispatchRefusal extends Error {
198
+ readonly agent: string;
199
+ readonly reason: string;
200
+ constructor(agent: string, reason: string) {
201
+ super(`[router] role dispatch @${agent} refused: ${reason}`);
202
+ this.name = "RoleDispatchRefusal";
203
+ this.agent = agent;
204
+ this.reason = reason;
205
+ }
206
+ }
207
+
208
+ /** Exact refusal reasons of the role path (shared with the tests). */
209
+ export const ROLE_REFUSALS = {
210
+ malformed:
211
+ "the first line of the prompt starts like a route line but is not a valid one (unbalanced, too long, ...); fix it (`[route class=… root=<absolute path>]`) or remove it",
212
+ noPrompt: "the call carries no prompt",
213
+ noCandidate: (floor: string, ceiling: string, reasons: readonly string[]): string =>
214
+ `no model is available inside the tier window ${floor}..${ceiling} (${reasons.join(", ") || "window:no-candidates"}); the router never falls back to a tier agent — fix the preset, or dispatch a tier agent explicitly`,
215
+ failed: (detail: string): string => `the router could not route it (${detail}); retry, or dispatch a tier agent explicitly`,
216
+ session: (detail: string): string => `the dispatching session is unavailable (${detail}); retry`,
217
+ } as const;
218
+
113
219
  const UNTOUCHED: RouteOutcome = Object.freeze({ mode: "static" });
114
220
 
115
221
  /**
@@ -119,7 +225,10 @@ const UNTOUCHED: RouteOutcome = Object.freeze({ mode: "static" });
119
225
  const RUNNER_CHILD_TITLE = /^Router (?:.+ delegation|result verification)$/;
120
226
 
121
227
  export interface DispatchRouter {
122
- /** Decide one `subagent` call. Writes and registers nothing: `commit` writes its decision row and registers it. Never throws. */
228
+ /**
229
+ * Decide one `subagent` call. Writes and registers nothing: `commit` writes its decision row and registers it. Never throws, except
230
+ * {@link RoleDispatchRefusal} for a role dispatch the router refuses (#84 P2.1; tier dispatches never throw).
231
+ */
123
232
  route(call: RouteCall): Promise<RouteOutcome>;
124
233
  /**
125
234
  * The input the host is about to execute (`event.input` after the legacy hook ran): write the call's decision row, then register the
@@ -132,6 +241,12 @@ export interface DispatchRouter {
132
241
  onCallResult(callID: string, childSessionID: string | null): void;
133
242
  /** The call ended without a result, or its hook chain failed: forget it. */
134
243
  onCallFinished(callID: string): void;
244
+ /**
245
+ * QA-P21-1-11 (handoff 20): a role child bound to its dispatch (`bind`). The first time per child, an annotation row records the
246
+ * OBSERVED binding kind (reason `note:binding:<kind>`, `note:binding:unknown` for an unknown one) against its dispatch's decision
247
+ * row; nothing when the engine writes no rows or the dispatch is unknown. Never throws.
248
+ */
249
+ noteBinding(childSessionID: string, binding: Pick<Binding, "kind" | "decisionID">): void;
135
250
  /** Dispatches still waiting to be claimed (diagnostics, tests). */
136
251
  pendingCount(): number;
137
252
  /** Children registered by a wrong heuristic claim and not yet taken over by their own dispatch (diagnostics, tests). */
@@ -150,6 +265,29 @@ export interface DispatchRouterDeps {
150
265
  readonly directory: string;
151
266
  readonly logger: WireLogger;
152
267
  readonly now?: () => number;
268
+ /**
269
+ * #84 P2.1 (role dispatches only): stdout of `git worktree list --porcelain` run in `cwd` (the session directory). Default:
270
+ * {@link gitWorktreeList} (the hardened spawn, 5 s timeout). Injected by tests.
271
+ */
272
+ readonly listWorktrees?: (cwd: string) => Promise<string>;
273
+ /** #84 P2.1: canonical long form of an existing path (default `realpathSync.native`). Only called on an already matched root. */
274
+ readonly realpath?: (path: string) => string;
275
+ /** #84 P2.1: path rules of the work-root comparison (default `process.platform`). */
276
+ readonly platform?: NodeJS.Platform;
277
+ /** #84 P2.1: the router is bypassed for this session (`/bypass`, `src/index.ts`): the verification gate will not run (S10/P-9). */
278
+ readonly isBypassed?: (sessionID: string) => boolean;
279
+ /** #84 P2.1: environment of the enforcement-mode env gate (default `process.env`). */
280
+ readonly env?: Readonly<Record<string, string | undefined>>;
281
+ /**
282
+ * QA-P21-1-8: the role path is live (the plugin STARTED in roles mode, so its role agents and tools exist). `false` → every role
283
+ * agent takes the tier path, as in tiers mode. Default: live.
284
+ */
285
+ readonly rolesEnabled?: (agent: string) => boolean;
286
+ /**
287
+ * QA-P21-2 nit 3: `router_verify` is registered (index.ts `routerVerifyEnabled`); `false` → nothing is deferred, so a deferred
288
+ * directive does not weaken the detection. Absent: treated as registered.
289
+ */
290
+ readonly routerVerifyEnabled?: () => boolean;
153
291
  }
154
292
 
155
293
  /** What `route()` decided, until `commit()` has the final input. */
@@ -164,7 +302,7 @@ interface Decided {
164
302
  * legacy hook rejects (`onCallFinished`) never writes it. Known limit: a call the HOST then fails (`onCallResult` with no child for a
165
303
  * fresh dispatch) keeps its row; no retraction row is written.
166
304
  */
167
- readonly row: DecisionRow;
305
+ readonly row: DecisionRow | null;
168
306
  /** Appends a row to the decision log (`Prepared.enqueue` of the call). */
169
307
  readonly enqueue: (row: DecisionRow) => void;
170
308
  /** A34 (QA-G-B8): the capability rank of what the host is handed (`row.capability.dispatched`); `null` = unknown. */
@@ -177,6 +315,20 @@ interface Decided {
177
315
  /** Resolve an agent the legacy hook switched to (the same resolution the engine used for the pick). */
178
316
  readonly resolve: (agent: string) => ChosenDispatch | null;
179
317
  readonly at: number;
318
+ /** #84 P2.1: a role dispatch (absent for every tier dispatch). */
319
+ readonly role?: RoleCommit;
320
+ }
321
+
322
+ /** What `commit()` needs of a role dispatch. */
323
+ interface RoleCommit {
324
+ /** The tier of the dispatched rung: the registry's `tier` (running tier on a resume, role × tier rows of ingestion). */
325
+ readonly tier: string;
326
+ /** `false` when the engine is static: no instance may score the attempt (`DispatchInput.outcomes`). */
327
+ readonly outcomes: boolean;
328
+ /** The pending binding entry to register (a fresh dispatch); null on a resume. */
329
+ readonly pending: { readonly nonce: string; readonly grant: DispatchGrant; readonly budget: number; readonly description: string; readonly decisionID: string | null } | null;
330
+ /** QA-G-B-1: the verification this dispatch carries to its resumes (its own, or the one it carried itself); null: none. */
331
+ readonly verification: CarriedVerification | null;
180
332
  }
181
333
 
182
334
  /** A committed dispatch, kept until its call ends. */
@@ -193,6 +345,10 @@ interface Entry {
193
345
  /** `waiting`: no child yet; `claimed`: a `session.created` was matched to it; `resumed`: registered at commit. */
194
346
  state: "waiting" | "claimed" | "resumed";
195
347
  claimedChild?: string;
348
+ /** #84 P2.1: a binding entry was registered for this call (`registerPending`); a rejected call evicts it. */
349
+ rolePending?: true;
350
+ /** QA-P21-1-11: a role dispatch's decision row and its log, for the binding annotation row (absent: no rows). */
351
+ roleRow?: { readonly row: DecisionRow; readonly enqueue: (row: DecisionRow) => void };
196
352
  }
197
353
 
198
354
  /**
@@ -208,9 +364,672 @@ function claimCall(key: string): boolean {
208
364
  return true;
209
365
  }
210
366
 
367
+ /** Bound on children with pending subagent-result annotations (oldest dropped first). */
368
+ export const MAX_ANNOTATED_CHILDREN = 256;
369
+ /** Bound on annotations kept per child (oldest dropped first). */
370
+ export const MAX_ANNOTATIONS_PER_CHILD = 8;
371
+
372
+ export interface SubagentAnnotation {
373
+ readonly kind: "budget" | "authority";
374
+ readonly text: string;
375
+ }
376
+
377
+ /** Process-wide: annotations for the parent's `subagent` result, keyed by child session. */
378
+ const subagentAnnotations = new Map<string, SubagentAnnotation[]>();
379
+
380
+ /**
381
+ * Seam: record an annotation to be appended to the parent's `subagent` result of `childSessionID`.
382
+ * Bounded; consumed once by {@link takeSubagentAnnotations}.
383
+ */
384
+ export function annotateSubagentResult(kind: "budget" | "authority", childSessionID: string, text: string): void {
385
+ const list = subagentAnnotations.get(childSessionID) ?? [];
386
+ subagentAnnotations.delete(childSessionID);
387
+ list.push({ kind, text });
388
+ while (list.length > MAX_ANNOTATIONS_PER_CHILD) list.shift();
389
+ subagentAnnotations.set(childSessionID, list);
390
+ while (subagentAnnotations.size > MAX_ANNOTATED_CHILDREN) subagentAnnotations.delete(subagentAnnotations.keys().next().value as string);
391
+ }
392
+
393
+ /** The annotations recorded for `childSessionID`, in order; they are removed (a second call returns none). */
394
+ export function takeSubagentAnnotations(childSessionID: string): readonly SubagentAnnotation[] {
395
+ const list = subagentAnnotations.get(childSessionID);
396
+ if (list === undefined) return [];
397
+ subagentAnnotations.delete(childSessionID);
398
+ return list;
399
+ }
400
+
401
+ // ---------------------------------------------------------------------------
402
+ // #84 P2.1 (T2.1.2): role dispatch path — exported API for the adapter (P2.1-C)
403
+ // ---------------------------------------------------------------------------
404
+
405
+ /** Bound on routed role dispatches kept for the adapter (oldest dropped first). */
406
+ export const MAX_ROUTED_ROLES = 1000;
407
+
408
+ /** Process-wide: the routed role dispatch of each call id, for the legacy hook (header) and `execute.after` (hint). */
409
+ const routedRoles = new Map<string, RoleRouted>();
410
+
411
+ function rememberRoutedRole(routed: RoleRouted): void {
412
+ routedRoles.delete(routed.callID);
413
+ routedRoles.set(routed.callID, routed);
414
+ while (routedRoles.size > MAX_ROUTED_ROLES) routedRoles.delete(routedRoles.keys().next().value as string);
415
+ }
416
+
417
+ /** The role dispatch `route()` decided for `callID` (kept until {@link forgetRoutedRole}, a rejected call, or the LRU bound). */
418
+ export function routedRoleOf(callID: string): RoleRouted | undefined {
419
+ return routedRoles.get(callID);
420
+ }
421
+
422
+ /**
423
+ * Handoff 30: the routed decision's work root for `buildDispatchHeader` (canonical long form). `undefined` = not a routed role
424
+ * dispatch (tier dispatches: the tier path does not resolve roots); `null` = a role dispatch without a validated work root.
425
+ */
426
+ export function routedWorkRoot(callID: string): string | null | undefined {
427
+ const routed = routedRoles.get(callID);
428
+ return routed === undefined ? undefined : routed.workRoot;
429
+ }
430
+
431
+ /** Drop what `route()` kept for `callID` (the adapter calls it once `execute.after` is done with it). */
432
+ export function forgetRoutedRole(callID: string): void {
433
+ routedRoles.delete(callID);
434
+ strippedRoots.delete(callID);
435
+ }
436
+
437
+ /**
438
+ * Handoff 30 (tier dispatches, v2 shadow/advise/enforce): the `root=` of the first-line route line `route()` stripped from the
439
+ * prompt, so the legacy hook's dispatch header can still name it (T1.5.3a). Process-wide, bounded like {@link routedRoles}.
440
+ */
441
+ const strippedRoots = new Map<string, string>();
442
+
443
+ function rememberStrippedRoot(callID: string, root: string): void {
444
+ strippedRoots.delete(callID);
445
+ strippedRoots.set(callID, root);
446
+ while (strippedRoots.size > MAX_ROUTED_ROLES) strippedRoots.delete(strippedRoots.keys().next().value as string);
447
+ }
448
+
449
+ /** The route line's `root=` of a tier dispatch whose route line `route()` stripped; undefined otherwise. */
450
+ export function strippedRouteRoot(callID: string): string | undefined {
451
+ return strippedRoots.get(callID);
452
+ }
453
+
454
+ /** A role's max authority (allow − deny, never `execute`): the `maxOf` of `bind` / `currentBinding` (handoff 33). */
455
+ export function roleMaxActions(spec: RoleSpec | undefined): readonly AuthorityAction[] | undefined {
456
+ if (spec === undefined) return undefined;
457
+ return spec.authority.allow.filter((action) => action !== "execute" && !spec.authority.deny.includes(action));
458
+ }
459
+
460
+ /**
461
+ * Text form of a path for the work-root comparison, WITHOUT touching the filesystem: separators unified (win32: `/` → `\`),
462
+ * repeated separators and `.` segments dropped, the trailing separator dropped (a drive or POSIX root keeps it), case folded on win32.
463
+ */
464
+ export function normalizeRootText(path: string, platform: NodeJS.Platform = process.platform): string {
465
+ const win = platform === "win32";
466
+ const sep = win ? "\\" : "/";
467
+ let text = path.trim();
468
+ if (win) text = text.replace(/\//g, "\\");
469
+ const absolute = text.startsWith(sep);
470
+ const parts = text.split(sep).filter((part) => part !== "" && part !== ".");
471
+ let out = (absolute ? sep : "") + parts.join(sep);
472
+ if (win && /^[A-Za-z]:$/.test(out)) out += sep; // `D:\` stays a root
473
+ if (out === "") out = absolute ? sep : "";
474
+ return win ? out.toLowerCase() : out;
475
+ }
476
+
477
+ /**
478
+ * The worktree paths of `git worktree list --porcelain` output (the `worktree <path>` line of each entry), as git prints them, in
479
+ * git's order (the main worktree first). QA-P23-A4: an entry git marks `prunable` (its directory is gone or no longer points
480
+ * back) is dropped — it is not a work root any more, even if a plain directory now sits at its path.
481
+ */
482
+ export function parseWorktreeList(porcelain: string): string[] {
483
+ const out: string[] = [];
484
+ let current: string | undefined;
485
+ let prunable = false;
486
+ const flush = (): void => {
487
+ if (current !== undefined && !prunable) out.push(current);
488
+ current = undefined;
489
+ prunable = false;
490
+ };
491
+ for (const raw of porcelain.split("\n")) {
492
+ const line = raw.replace(/\r$/, "");
493
+ if (line.startsWith("worktree ")) {
494
+ flush();
495
+ if (line.length > "worktree ".length) current = line.slice("worktree ".length);
496
+ } else if (line === "prunable" || line.startsWith("prunable ")) {
497
+ prunable = true;
498
+ }
499
+ }
500
+ flush();
501
+ return out;
502
+ }
503
+
504
+ export interface WorkRootResolution {
505
+ /** Canonical long form (`realpathSync.native`) of the validated root; null = no validated work root. */
506
+ readonly workRoot: string | null;
507
+ /** The route line's `root=` as written, or null. */
508
+ readonly requested: string | null;
509
+ /** Why there is no work root (for the grant notes and the dispatch header); null when resolved. */
510
+ readonly note: string | null;
511
+ }
512
+
513
+ export interface WorkRootDeps {
514
+ readonly listWorktrees: (cwd: string) => Promise<string>;
515
+ readonly realpath: (path: string) => string;
516
+ readonly platform: NodeJS.Platform;
517
+ }
518
+
519
+ /**
520
+ * `git worktree list --porcelain` in `cwd` (stdout); rejects on any failure. QA-G-A2-3: the hardened spawn of `listWorktrees`
521
+ * (role-agents.ts) — the absolute git executable selected outside the work-root guards of `cwd` (`workRootGuards`), the
522
+ * `hardeningArgs()` flags, `gitEnvironment()` (no inherited GIT_*, no system/global config), no shell — bounded to 5 s and 1 MiB.
523
+ * QA-G-A2-2-1: the user's system/global `safe.directory` values are passed back as `-c safe.directory=…` pairs (as `inspectGit`
524
+ * does), so a repository trusted that way is still listed instead of failing with "dubious ownership".
525
+ */
526
+ export async function gitWorktreeList(cwd: string): Promise<string> {
527
+ // Loaded lazily: the hardened git helpers are only needed when a worktree list actually runs.
528
+ const { gitEnvironment, gitExecutable, hardeningArgs, inheritedSafeDirectoryArgs, spawnBounded, workRootGuards } = await import("../../router/git-tools");
529
+ const started = performance.now();
530
+ const executable = gitExecutable(workRootGuards(cwd));
531
+ const trusted = await inheritedSafeDirectoryArgs(executable, 5_000);
532
+ const result = await spawnBounded(executable, [...hardeningArgs(), ...trusted, "worktree", "list", "--porcelain"], cwd, {
533
+ env: gitEnvironment(), timeoutMs: Math.max(1, 5_000 - (performance.now() - started)), maxBytes: 1 << 20,
534
+ });
535
+ if (result.code !== 0 || result.truncated) {
536
+ throw new Error(`git worktree list failed (exit ${String(result.code)}${result.truncated ? ", output truncated" : ""}): ${result.stderr.toString("utf8").trim()}`);
537
+ }
538
+ return result.output.toString("utf8");
539
+ }
540
+
541
+ /**
542
+ * The work root of a role dispatch (plan §2.2, handoff 8). `root` comes ONLY from `ClassifyResult.trace.routeLine.root` (never a
543
+ * re-parse of the prompt).
544
+ * - no `root=` → the session directory (canonical long form);
545
+ * - `root=` → its normalised TEXT is compared with the session directory and with every worktree of `git worktree list --porcelain`
546
+ * (run in the session directory) BEFORE any filesystem call on it; a match → the canonical long form of the matched entry;
547
+ * - anything else (no match, git unavailable, an entry that does not resolve) → `workRoot: null` with a note.
548
+ * Never throws.
549
+ */
550
+ export async function resolveRoleWorkRoot(
551
+ input: { readonly root: string | null; readonly sessionDirectory: string },
552
+ deps: WorkRootDeps,
553
+ ): Promise<WorkRootResolution> {
554
+ const canonical = (path: string): string | null => {
555
+ try {
556
+ const resolved = deps.realpath(path);
557
+ return typeof resolved === "string" && resolved !== "" ? resolved : null;
558
+ } catch {
559
+ return null;
560
+ }
561
+ };
562
+ if (input.root === null) {
563
+ const dir = canonical(input.sessionDirectory);
564
+ return dir === null
565
+ ? { workRoot: null, requested: null, note: `the session directory ${input.sessionDirectory} could not be resolved: no work root` }
566
+ : { workRoot: dir, requested: null, note: null };
567
+ }
568
+ const want = normalizeRootText(input.root, deps.platform);
569
+ let match: string | undefined = normalizeRootText(input.sessionDirectory, deps.platform) === want ? input.sessionDirectory : undefined;
570
+ if (match === undefined) {
571
+ let listed: string[] = [];
572
+ try {
573
+ listed = parseWorktreeList(await deps.listWorktrees(input.sessionDirectory));
574
+ } catch {
575
+ listed = [];
576
+ }
577
+ match = listed.find((path) => normalizeRootText(path, deps.platform) === want);
578
+ }
579
+ const none = `root=${input.root} is neither the session directory nor a worktree listed by \`git worktree list --porcelain\`: no work root`;
580
+ if (match === undefined) return { workRoot: null, requested: input.root, note: none };
581
+ const resolved = canonical(match);
582
+ return resolved === null
583
+ ? { workRoot: null, requested: input.root, note: `root=${input.root} does not resolve on disk: no work root` }
584
+ : { workRoot: resolved, requested: input.root, note: null };
585
+ }
586
+
587
+ /**
588
+ * S10/P-9 (agent-agnostic): the router's own verification gate will run deterministic checks for this dispatch — the call is a
589
+ * `task`/`subagent` (always, here), `enforcement.mode ≠ off` (env gate included), `verify.require ≠ never` (the condition of
590
+ * `verify/dispatch.shouldVerifyTask`), the router is not bypassed, and the prompt's `[acceptance]` block carries a machine check.
591
+ */
592
+ export function roleRouterGate(input: {
593
+ readonly cfg: RouterConfig;
594
+ readonly bypassed: boolean;
595
+ /** `detectionOf(prompt)`: the depth of the prompt's own `[acceptance]` block. */
596
+ readonly acceptance: Detection;
597
+ readonly env?: Readonly<Record<string, string | undefined>>;
598
+ /**
599
+ * QA-P21-1-2: the dispatch's verification is DEFERRED (`roleGateDeferred`): the gate does not run at the return, so the
600
+ * detection is never `deterministic` on its account. Absent = not deferred.
601
+ */
602
+ readonly deferred?: boolean;
603
+ /**
604
+ * #84 P3.3 DF2-F1: the gate cannot run the checks in the dispatch's work root ({@link roleGateOutsideWorkRoot}), so the
605
+ * detection is never `deterministic` on its account. Absent = it can.
606
+ */
607
+ readonly outsideWorkRoot?: boolean;
608
+ }): boolean {
609
+ if (input.deferred === true || input.acceptance !== "deterministic") return false;
610
+ return roleVerificationRuns(input);
611
+ }
612
+
613
+ /**
614
+ * #84 QA-G-B-7: the router's gate verifies this role dispatch at all — `enforcement.mode ≠ off` (env gate included), the router is
615
+ * not bypassed (`/bypass`), `verify.require ≠ never`, and the requested cwd is not outside the root the gate verifies in
616
+ * (`outsideWorkRoot`). When it does not, nothing checks the work: the dispatch's detection is `none` (`effectiveDetection`'s
617
+ * `verifies`), whatever its claim or `[acceptance]` block says. Fails toward "does not run" on any error.
618
+ */
619
+ export function roleVerificationRuns(input: {
620
+ readonly cfg: RouterConfig;
621
+ readonly bypassed: boolean;
622
+ readonly env?: Readonly<Record<string, string | undefined>>;
623
+ readonly outsideWorkRoot?: boolean;
624
+ }): boolean {
625
+ if (input.bypassed || input.outsideWorkRoot === true) return false;
626
+ let mode = "off";
627
+ try {
628
+ mode = resolveEnforcementMode({ config: input.cfg, env: { ...(input.env ?? process.env) } }).mode;
629
+ } catch {
630
+ mode = "off";
631
+ }
632
+ if (mode === "off") return false;
633
+ return (input.cfg.enforcement?.verify?.require ?? "whenDoDPresent") !== "never";
634
+ }
635
+
636
+ /**
637
+ * QA-P21-1-2: the dispatch's verification would be deferred, exactly as the native path decides it (index.ts `isDeferred` →
638
+ * verify/wiring.ts `isDeferred`): its `VERIFY:` directives resolve to `deferred` (the configured `defaultVerify` when the text has
639
+ * none; the text is `dispatchDirectiveText(prompt, description)`) AND its DoD carries a `testsPass` check. A deferred dispatch
640
+ * returns without the gate (`router_verify` runs it later), so the router's gate cannot back a `deterministic` detection.
641
+ * Fails toward "deferred" on any error (a weaker detection, never a stronger one). QA-P21-2 nit 3: nothing is deferred when
642
+ * `router_verify` is not registered (`verifyEnabled: false`, index.ts `routerVerifyEnabled`): the gate then runs at the return.
643
+ */
644
+ export function roleGateDeferred(cfg: RouterConfig, prompt: string, description: string, opts: { readonly verifyEnabled?: boolean } = {}): boolean {
645
+ if (opts.verifyEnabled === false) return false;
646
+ try {
647
+ const text = prompt.trim() !== "" ? prompt : description; // verify/wiring.ts dispatchDirectiveText
648
+ const budget = resolveVerifyBudget(cfg);
649
+ const directives = parseVerifyDirectives(text, {
650
+ defaultVerify: budget.defaultVerify, captureWaitMs: budget.captureWaitMs, baselineTimeoutMs: budget.baselineTimeoutMs,
651
+ });
652
+ if (directives.mode !== "deferred") return false;
653
+ return buildDelegationDoD({ prompt, description }).checks.some((check) => check.kind === "testsPass");
654
+ } catch {
655
+ return true;
656
+ }
657
+ }
658
+
659
+ /**
660
+ * #84 P3.3 DF2-F1: the router's gate verifies a role dispatch in its work root (index.ts `verificationScopeOf` → gate
661
+ * `Delegation.workRoot`). It cannot when the dispatch has no validated work root (`workRoot: null`), or when the requested cwd —
662
+ * the call's `cwd` argument, else the `[acceptance]` block's `cwd:` (`requestedVerificationCwd`, the after-hook's order, nit 3) —
663
+ * lies outside that root by P2.3's rule (`verificationScope`; the gate refuses it: unverifiable). Then the router's gate cannot
664
+ * back a `deterministic` detection. `workRoot` is the GRANT's root (QA-P33F1-1-1: a resume keeps the child's bound root). Fails
665
+ * toward "outside" on any error (a weaker detection, never a stronger one).
666
+ *
667
+ * What the decision row records is decided HERE, at dispatch: a gate that later reports the delegation unverifiable for a reason
668
+ * only the return shows (every change outside the work root, a timeout, a verifier error) does not rewrite the row — its verdict
669
+ * carries the caveat (`[router ⚠ UNVERIFIED …]`) and is never accepted as verified.
670
+ */
671
+ export function roleGateOutsideWorkRoot(workRoot: string | null, prompt: string, description: string, argsCwd?: unknown): boolean {
672
+ if (workRoot === null) return true;
673
+ try {
674
+ return verificationScope(requestedVerificationCwd(argsCwd, buildDelegationDoD({ prompt, description }).cwd), workRoot).outside;
675
+ } catch {
676
+ return true;
677
+ }
678
+ }
679
+
680
+ /** QA-P33F1-1-1 / 1-3: where the gate verifies a role dispatch — the grant's work root, else the canonical session directory. */
681
+ function verifyRootOf(grant: DispatchGrant, sessionDirectory: string, realpath: (path: string) => string): string {
682
+ if (grant.workRoot !== null) return grant.workRoot;
683
+ try {
684
+ const real = realpath(sessionDirectory);
685
+ return typeof real === "string" && real !== "" ? real : sessionDirectory;
686
+ } catch {
687
+ return sessionDirectory;
688
+ }
689
+ }
690
+
691
+ /** The tier above `current` on `order`, up to the role's `ceiling`; null at (or above) the ceiling or when either is not on the order. */
692
+ export function nextRoleTier(order: readonly string[], ceiling: string, current: string | null): string | null {
693
+ if (current === null) return null;
694
+ const at = order.indexOf(current);
695
+ const top = order.indexOf(ceiling);
696
+ if (at < 0 || top < 0 || at >= top) return null;
697
+ return order[at + 1] ?? null;
698
+ }
699
+
700
+ /**
701
+ * P-8 (handoff 39), QA-P21-2-2: the role-aware escalation hint after a verification FAIL — resume the SAME child with the findings;
702
+ * the router itself raises it to the next tier of the role's range ({@link roleEscalationAfterFail} records the raise, the next
703
+ * resume applies it). The orchestrator sets neither `model` nor a `tier=` pin, and never names a tier agent. Pure.
704
+ */
705
+ export function roleEscalationHint(input: {
706
+ readonly agent: string;
707
+ readonly childSessionID: string | null;
708
+ readonly currentTier: string | null;
709
+ readonly nextTier: string | null;
710
+ }): string {
711
+ const task = input.childSessionID === null ? "the same sessionID" : `the same sessionID ("${input.childSessionID}")`;
712
+ if (input.nextTier === null) {
713
+ const top = input.currentTier === null ? "" : ` (it already runs on its highest tier, ${input.currentTier})`;
714
+ return `NEXT: resume ${task} with @${input.agent} and the findings${top}; set neither \`model\` nor \`tier=\`; do not start a new task and do not treat the prior result as complete.`;
715
+ }
716
+ const from = input.currentTier === null ? "" : ` from ${input.currentTier}`;
717
+ return `NEXT: resume ${task} with @${input.agent} and the findings; the router raises it to ${input.nextTier}${from}; set neither \`model\` nor \`tier=\`; do not start a new task.`;
718
+ }
719
+
720
+ /** The child's role, running tier and next tier of its role range, from the dispatch registry; null when it is not a role child. */
721
+ function escalationOf(cfg: RouterConfig, childSessionID: string): { agent: string; current: string | null; next: string | null } | null {
722
+ const record = lookupDispatch(childSessionID);
723
+ if (record === undefined) return null;
724
+ const spec = resolveRoles(cfg, "v2").get(record.agent);
725
+ if (spec === undefined) return null;
726
+ const current = record.tier ?? null;
727
+ return { agent: record.agent, current, next: nextRoleTier(roleTierOrder(cfg), spec.tierRange.ceiling, current) };
728
+ }
729
+
730
+ /**
731
+ * {@link roleEscalationHint} for a child the router registered: its role and running tier from the dispatch registry, the next
732
+ * tier from the role's range on `roleTierOrder(cfg)`. `null` when the child is not a role dispatch of roles mode. Records nothing.
733
+ */
734
+ export function roleEscalationHintFor(cfg: RouterConfig, childSessionID: string): string | null {
735
+ const e = escalationOf(cfg, childSessionID);
736
+ return e === null ? null : roleEscalationHint({ agent: e.agent, childSessionID, currentTier: e.current, nextTier: e.next });
737
+ }
738
+
739
+ /** QA-P21-2-2: pending raises, child → the parent that may consume it and the tier (bounded, oldest out; 30 min TTL). */
740
+ export const MAX_RESUME_RAISES = 1000;
741
+ export const RESUME_RAISE_TTL_MS = 30 * 60 * 1000;
742
+ const resumeRaises = new Map<string, { readonly parentSessionID: string; readonly tier: string; readonly at: number }>();
743
+
744
+ /**
745
+ * QA-P21-2-2 ("the router raises the tier"): the hint emitted after a verification FAIL of a role child, AND the raise it promises:
746
+ * the next tier of the role's range is recorded for the child, consumed once by `parentSessionID`'s next resume of that child,
747
+ * which applies it as a raise-only floor. Nothing is recorded at the ceiling. `null` when the child is not a role child.
748
+ */
749
+ export function roleEscalationAfterFail(cfg: RouterConfig, childSessionID: string, parentSessionID: string): string | null {
750
+ const e = escalationOf(cfg, childSessionID);
751
+ if (e === null) return null;
752
+ if (e.next !== null && parentSessionID !== "") {
753
+ resumeRaises.delete(childSessionID);
754
+ resumeRaises.set(childSessionID, { parentSessionID, tier: e.next, at: Date.now() });
755
+ while (resumeRaises.size > MAX_RESUME_RAISES) resumeRaises.delete(resumeRaises.keys().next().value as string);
756
+ }
757
+ return roleEscalationHint({ agent: e.agent, childSessionID, currentTier: e.current, nextTier: e.next });
758
+ }
759
+
760
+ /** The raise recorded for this parent's resume of the child (not consumed), or null. */
761
+ export function pendingResumeRaise(childSessionID: string, parentSessionID: string): string | null {
762
+ const raise = resumeRaises.get(childSessionID);
763
+ if (raise === undefined) return null;
764
+ if (Date.now() - raise.at >= RESUME_RAISE_TTL_MS) {
765
+ resumeRaises.delete(childSessionID);
766
+ return null;
767
+ }
768
+ return raise.parentSessionID === parentSessionID ? raise.tier : null;
769
+ }
770
+
771
+ /** `prompt` with `line` as its LAST line (every byte of `prompt` kept). */
772
+ function withLastLine(prompt: string, line: string): string {
773
+ if (prompt === "") return line;
774
+ return prompt.endsWith("\n") ? `${prompt}${line}` : `${prompt}\n${line}`;
775
+ }
776
+
777
+ /** The catalog's variant ids of `model`; `null` when the catalog does not know the model (then nothing is dropped). */
778
+ function catalogVariantIds(catalog: RolePrepared["catalog"], model: string): string[] | null {
779
+ let entry: ReturnType<RolePrepared["catalog"]["entry"]>;
780
+ try {
781
+ entry = catalog.entry(model);
782
+ } catch {
783
+ return null;
784
+ }
785
+ if (entry === undefined) return null;
786
+ const variants = Array.isArray(entry.variants) ? entry.variants : [];
787
+ return variants.flatMap((v) => (v !== null && v !== undefined && typeof v.id === "string" ? [v.id] : []));
788
+ }
789
+
790
+ /**
791
+ * An explicit caller `model` on a role dispatch: kept when it is a rung of the window (inside the bounds); above the ceiling →
792
+ * clamped to the ceiling's rung (the pin rule of `tierBounds`); anything else (below the floor, unknown) → lifted to the floor's
793
+ * rung. On a resume it never moves below what the kernel decided (the running rung).
794
+ */
795
+ function placeCallerModel(
796
+ ladder: RoleLadder,
797
+ ref: string,
798
+ decided: Candidate,
799
+ resumed: boolean,
800
+ ): { readonly candidate: Candidate; readonly code: string } {
801
+ const parts = splitModelRef(ref);
802
+ const model = parts === null ? ref : `${parts.provider}/${parts.model}`;
803
+ const variant = parts === null ? null : parts.variant;
804
+ const cands = ladder.candidates;
805
+ const inside = cands.find((c) => c.model === model && (variant === null || normalizeVariant(c.variant) === normalizeVariant(variant)));
806
+ if (inside !== undefined) {
807
+ if (resumed && inside.rank < decided.rank) return { candidate: decided, code: "kept:caller-model:resume" };
808
+ return { candidate: inside, code: "kept:caller-model" };
809
+ }
810
+ const firsts = ladder.tiers.flatMap((t) => (t.first === null ? [] : [t.first]));
811
+ const floor = cands[firsts[0] ?? 0] ?? decided;
812
+ const ceiling = cands[firsts[firsts.length - 1] ?? 0] ?? decided;
813
+ const rank = capabilityRank(ladder, { model, variant }, null);
814
+ const placed = rank !== null && ladder.ceilingRank !== null && rank > ladder.ceilingRank
815
+ ? { candidate: ceiling, code: "clamp:caller-model:ceiling" }
816
+ : { candidate: floor, code: "lift:caller-model:floor" };
817
+ return resumed && placed.candidate.rank < decided.rank ? { candidate: decided, code: "kept:caller-model:resume" } : placed;
818
+ }
819
+
820
+ /** QA-P21-2-2: the note of a resume raised after a verification FAIL (`raise:verification-fail:<tier>`). */
821
+ export const RESUME_RAISE_NOTE = "raise:verification-fail:";
822
+ /** QA-G-B-1: the note of a resume that carries the `[acceptance]` block of the dispatch it resumes (appended to its prompt). */
823
+ export const CARRIED_ACCEPTANCE_NOTE = "acceptance carried from the resumed dispatch";
824
+
825
+ /** The higher of two tiers on `order` (unknown or null ones ignored); null when neither is on it. */
826
+ function higherTier(order: readonly string[], a: string | null, b: string | null): string | null {
827
+ const ia = a === null ? -1 : order.indexOf(a);
828
+ const ib = b === null ? -1 : order.indexOf(b);
829
+ if (ia < 0 && ib < 0) return a ?? b; // let tierBounds report an unknown floorTier as before
830
+ return ia >= ib ? a : b;
831
+ }
832
+
833
+ /**
834
+ * QA-P21-2-1: the grant of a resume of an EXACTLY bound child: what the child holds (its bound grant) plus the actions widened for
835
+ * this resume. Only adds; `router_run` and `edit` stay withheld from a child bound without a work root (I9, QA-G-B-2). The work root
836
+ * is the bound one — QA-G-B N-b: a child bound without one keeps none, whatever root the resume's own route line names (the child
837
+ * cannot touch it: binding.ts holds its enforced grant), so the verification root, the outside-root check and the classification
838
+ * never use it.
839
+ */
840
+ function resumedGrant(boundGrant: DispatchGrant, widened: readonly AuthorityAction[]): DispatchGrant {
841
+ const root = boundGrant.workRoot;
842
+ const actions = new Set<AuthorityAction>([...boundGrant.actions, ...widened]);
843
+ if (boundGrant.workRoot === null) {
844
+ // QA-G-B-2 (R7 null-root contract, I3): a child bound without a validated work root gets no run and no write, whatever root the
845
+ // resume's own route line names — as binding.ts `widen` (the enforced grant) refuses them.
846
+ actions.delete("router_run");
847
+ actions.delete("edit");
848
+ }
849
+ return { actions, notes: [...boundGrant.notes], workRoot: root };
850
+ }
851
+
852
+ /** verify/dod.ts `OPEN_TAG_RE` / `CLOSE_TAG_RE`: the lines that open and close an `[acceptance]` block. */
853
+ const ACCEPTANCE_OPEN_LINE = /^\s*\[(acceptance|dod)\]\s*$/i;
854
+ const ACCEPTANCE_CLOSE_LINE = /^\s*\[\/(acceptance|dod)\]\s*$/i;
855
+ /** A whole-line `VERIFY:` / `VERIFY_WAIT:` directive (verify/directives.ts). */
856
+ const VERIFY_DIRECTIVE_LINE = /^\s*VERIFY(?:_WAIT)?\s*:/i;
857
+
858
+ /**
859
+ * #84 QA-G-B-1: what a role dispatch's verification is built from — its first `[acceptance]` block, found as verify/dod.ts
860
+ * `parseAcceptanceBlock` finds it (verbatim lines; null without a closed block), and its whole-line `VERIFY:` / `VERIFY_WAIT:`
861
+ * directives outside that block.
862
+ */
863
+ export function verificationParts(prompt: string): { readonly block: string | null; readonly directives: readonly string[] } {
864
+ const lines = prompt.split(/\r?\n/);
865
+ const open = lines.findIndex((line) => ACCEPTANCE_OPEN_LINE.test(line));
866
+ const close = open < 0 ? -1 : lines.findIndex((line, i) => i > open && ACCEPTANCE_CLOSE_LINE.test(line));
867
+ const inBlock = (i: number): boolean => close >= 0 && i >= open && i <= close;
868
+ return {
869
+ block: close < 0 ? null : lines.slice(open, close + 1).join("\n"),
870
+ directives: lines.flatMap((line, i) => (!inBlock(i) && VERIFY_DIRECTIVE_LINE.test(line) ? [line.trim()] : [])),
871
+ };
872
+ }
873
+
874
+ /** QA-G-B-2-1: the block has a check judged on the change set (testsPass, lintClean). Fails toward "it has". */
875
+ function carriedChecksChangeSet(block: string): boolean {
876
+ try {
877
+ return buildDelegationDoD({ prompt: block }).checks.some((check) => check.kind === "testsPass" || check.kind === "lintClean");
878
+ } catch {
879
+ return true;
880
+ }
881
+ }
882
+
883
+ /** QA-G-B-2-1: the reason a carried acceptance's testsPass/lintClean that ran no process is unverifiable (DeterministicDeps). */
884
+ export const CARRIED_NO_PROCESS_REASON =
885
+ "a carried acceptance re-checked no earlier change of the child: a check that runs no process verifies nothing here";
886
+ /** QA-G-B-2-1: the reference of a carried acceptance whose introducing attempt was never gated (no failure can be excused). */
887
+ export const CARRIED_NO_REFERENCE: ReferenceState = Object.freeze({
888
+ kind: "none" as const, reason: "the attempt that introduced this carried acceptance was not verified at its return",
889
+ });
890
+ /** Bound on the files a carried baseline keeps; beyond it the cumulative change set is "unavailable" (fails safe). */
891
+ export const MAX_CARRIED_CHANGES = 2000;
892
+
893
+ /** What a gate prepares for one attempt (`PreparedVerification` of verify/wiring.ts, structurally). */
894
+ export interface RoleAttemptChanges {
895
+ readonly changedFiles: ChangedFile[];
896
+ readonly changeBaseline: "available" | "unavailable";
897
+ readonly reference: ReferenceState;
898
+ }
899
+
900
+ /** The union of two change sets, keyed by path (separators unified, case folded on win32); `newer` wins. */
901
+ function unionChanges(older: readonly ChangedFile[] | "unavailable", newer: readonly ChangedFile[] | "unavailable"): ChangedFile[] | "unavailable" {
902
+ if (older === "unavailable" || newer === "unavailable") return "unavailable";
903
+ const key = (path: string): string => (process.platform === "win32" ? path.replace(/\//g, "\\").toLowerCase() : path);
904
+ const all = new Map<string, ChangedFile>();
905
+ for (const file of [...older, ...newer]) all.set(key(file.path), { ...file });
906
+ return all.size > MAX_CARRIED_CHANGES ? "unavailable" : [...all.values()];
907
+ }
908
+
909
+ /**
910
+ * #84 QA-G-B-2-1: the change set and reference a role child's gate judges this attempt on, and the bookkeeping of its carried
911
+ * verification (the dispatch registry's `CarriedVerification.baseline`). Called by the after-hook once the attempt's own change
912
+ * set is prepared:
913
+ * - an attempt under its OWN block (a fresh dispatch, or a resume naming a new block) starts the lineage: its reference and change
914
+ * set become the baseline; it is judged on them, as before;
915
+ * - a CARRIED attempt (`carried`: the resume re-checks the block of an earlier attempt) is judged on the union of every change the
916
+ * child made since the attempt that introduced the block (and that attempt's reference: what it broke is never pre-existing);
917
+ * without such a baseline (that attempt was never gated) the change set is unavailable and no failure can be excused.
918
+ * Not a role child with an acceptance on record: `prepared` unchanged, nothing recorded.
919
+ */
920
+ export function roleAttemptVerification<T extends RoleAttemptChanges>(childSessionID: string, prepared: T, opts: { readonly carried: boolean }): T {
921
+ const verification = lookupDispatch(childSessionID)?.verification;
922
+ if (verification === undefined) return prepared;
923
+ const own: readonly ChangedFile[] | "unavailable" = prepared.changeBaseline === "available" ? prepared.changedFiles : "unavailable";
924
+ if (!opts.carried) {
925
+ updateDispatchVerification(childSessionID, { ...verification, baseline: { reference: prepared.reference, changed: own } });
926
+ return prepared;
927
+ }
928
+ const baseline = verification.baseline;
929
+ if (baseline === undefined) return { ...prepared, changeBaseline: "unavailable", reference: CARRIED_NO_REFERENCE };
930
+ const changed = unionChanges(baseline.changed, own);
931
+ updateDispatchVerification(childSessionID, { ...verification, baseline: { reference: baseline.reference, changed } });
932
+ return {
933
+ ...prepared,
934
+ changedFiles: changed === "unavailable" ? prepared.changedFiles : changed,
935
+ changeBaseline: changed === "unavailable" ? "unavailable" : "available",
936
+ reference: baseline.reference,
937
+ };
938
+ }
939
+
940
+ /**
941
+ * #84 QA-G-B-1 (I2, §2.3): the task facts a role RESUME is decided with. A resume prompt ("continue", "address the findings") is not
942
+ * the task: the class, confidence, source and needs come from the dispatch it resumes (the registry's record; its needs widened by
943
+ * the resume's own), and risk/scope are the max of that record and the resume's effective facts (its classification and route line,
944
+ * raise-only). Without a record the resume's own facts. Values outside the classifier's vocabularies fall back to the resume's.
945
+ */
946
+ function resumeFactsOf(original: DispatchRecord["facts"] | undefined, current: TaskFacts): TaskFacts {
947
+ if (original === undefined) return current;
948
+ const member = <T extends string>(values: readonly T[], value: unknown): value is T => typeof value === "string" && (values as readonly string[]).includes(value);
949
+ const higher = <T extends string>(order: readonly T[], a: unknown, b: T): T => (member(order, a) && order.indexOf(a) > order.indexOf(b) ? a : b);
950
+ const needs = Array.isArray(original.needs) ? original.needs : [];
951
+ return {
952
+ class: member(TASK_CLASSES, original.class) ? original.class : current.class,
953
+ risk: higher(RISKS, original.risk, current.risk),
954
+ scope: higher(SCOPES, original.scope, current.scope),
955
+ needs: NEEDS.filter((need) => needs.includes(need) || current.needs.includes(need)),
956
+ confidence: typeof original.confidence === "number" && Number.isFinite(original.confidence) ? original.confidence : current.confidence,
957
+ source: member(FACT_SOURCES, original.source) ? original.source : current.source,
958
+ };
959
+ }
960
+
961
+ /**
962
+ * #84 QA-G-B-3 (2), a dynamic role's needs (fixed roles, and a dispatch without a route line, unchanged):
963
+ * - the route line names `needs=` → that list plus the route class's implied needs (`network` ⇒ `shell`) are authoritative;
964
+ * - the route line names only `class=` → the needs the text itself names (`textNeeds`, never a class's implied ones) plus the
965
+ * route class's implied needs: the class the route line replaced takes its implied needs with it (DF-2: "a new file" made the
966
+ * rules class `implement`, whose `edit` outlived `class=other`).
967
+ * The result is intersected with `facts.needs`, which already holds the route line's needs (`applyRouteLine` merges them
968
+ * first, with the route class's implied needs): so a `needs=` list REPLACES the needs the text implies — a listed need the text
969
+ * never names is kept (QA-G-C-2-1), the text's other needs are dropped. Only the role max bounds the grant (`grantFor`).
970
+ */
971
+ function roleNeedsOf(facts: TaskFacts, line: RouteLine | null, spec: RoleSpec, textNeeds: ReadonlySet<Need>): TaskFacts {
972
+ if (spec.authority.mode === "fixed" || line === null || (line.needs === undefined && line.class === undefined)) return facts;
973
+ const keep = new Set<Need>([...(line.needs ?? textNeeds), ...CLASS_IMPLIED_NEEDS[facts.class]]);
974
+ if (keep.has("network")) keep.add("shell");
975
+ const needs = NEEDS.filter((need) => keep.has(need) && facts.needs.includes(need));
976
+ return needs.length === facts.needs.length ? facts : { ...facts, needs };
977
+ }
978
+
979
+ /** QA-P21-1-1: the note of a delegate's role dispatch (unparsed, floor rung of the unknown-binding window). */
980
+ export const DELEGATE_DISPATCH_NOTE =
981
+ "delegate dispatch: the prompt is not routed (a delegate never pins or steers); the floor rung of the role's local-only window is dispatched";
982
+ /** QA-P21-1-5: the reason code of a route-line pin that wins over an explicit caller `model`. */
983
+ export const PIN_OVER_CALLER_REASON = "pin:over-caller-model";
984
+ /** QA-P21-1-6: no window rung present in the host catalog at or above the floor (the role dispatch is refused). */
985
+ export const VARIANT_NO_CANDIDATE_REASON = "variant:no-catalog-candidate";
986
+
987
+ /**
988
+ * QA-P21-1-6: what is dispatched for the picked rung given the host catalog. Its variant exists (or the catalog does not know the
989
+ * model) → the rung as is. Otherwise the bare model, at its OWN capability rank (`capabilityRank(ladder, { model, variant: null })`),
990
+ * when that rank reaches the window floor; else the next window rung present in the catalog at or above the floor; `null` when
991
+ * there is none (the caller refuses).
992
+ */
993
+ function placeInCatalog(
994
+ ladder: RoleLadder,
995
+ picked: Candidate,
996
+ catalog: RolePrepared["catalog"],
997
+ ): { readonly candidate: Candidate; readonly variant: string | null; readonly dropped: string | null } | null {
998
+ const variantOf = (c: Pick<Candidate, "variant">): string | null => (normalizeVariant(c.variant) === "default" ? null : normalizeVariant(c.variant));
999
+ const present = (c: Candidate): boolean => {
1000
+ const v = variantOf(c);
1001
+ if (v === null) return true;
1002
+ const ids = catalogVariantIds(catalog, c.model);
1003
+ return ids === null || ids.includes(v);
1004
+ };
1005
+ if (present(picked)) return { candidate: picked, variant: variantOf(picked), dropped: null };
1006
+ const wanted = variantOf(picked);
1007
+ const floorRank = ladder.floorRank;
1008
+ const bareRank = capabilityRank(ladder, { model: picked.model, variant: null }, null);
1009
+ if (bareRank !== null && (floorRank === null || bareRank >= floorRank)) {
1010
+ return {
1011
+ candidate: { ...picked, variant: null, rank: bareRank },
1012
+ variant: null,
1013
+ dropped: `variant ${wanted} of ${picked.model} is not in the host catalog: dispatched on the tier model without a variant (capability rank ${bareRank})`,
1014
+ };
1015
+ }
1016
+ const at = ladder.candidates.indexOf(picked);
1017
+ const next = ladder.candidates.slice(at < 0 ? 0 : at + 1).find((c) => present(c) && (floorRank === null || c.rank >= floorRank));
1018
+ if (next === undefined) return null;
1019
+ return {
1020
+ candidate: next,
1021
+ variant: variantOf(next),
1022
+ dropped: `variant ${wanted} of ${picked.model} is not in the host catalog and the bare model ranks below the window floor: dispatched on ${refOf(next.model, variantOf(next))}`,
1023
+ };
1024
+ }
1025
+
211
1026
  /** Test-only: forget which calls were handled. */
212
1027
  export function resetDispatchRouting(): void {
213
1028
  handledCalls.clear();
1029
+ subagentAnnotations.clear();
1030
+ routedRoles.clear();
1031
+ strippedRoots.clear();
1032
+ resumeRaises.clear();
214
1033
  }
215
1034
 
216
1035
  function isRecord(value: unknown): value is Record<string, unknown> {
@@ -357,6 +1176,8 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
357
1176
  * result of the dispatch that really started them takes them over.
358
1177
  */
359
1178
  const misclaimed = new Map<string, string>();
1179
+ /** QA-P21-1-11: role children whose observed binding has been recorded (once per child; bounded). */
1180
+ const notedBindings = new Set<string>();
360
1181
  let sequence = 0;
361
1182
 
362
1183
  const trim = <T>(map: Map<string, T>, limit: number): void => {
@@ -387,6 +1208,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
387
1208
  facts: before.facts, agent: before.agent, model: before.model, variant: before.variant, tier: before.tier, acceptance: before.acceptance,
388
1209
  parentSessionID: before.parentSessionID, attemptId: before.attemptId, decisionID: before.decisionID, step: before.step,
389
1210
  outcomes: before.outcomes, picked: before.picked, keepExecution: true,
1211
+ ...(before.verification === undefined ? {} : { verification: before.verification }),
390
1212
  });
391
1213
  };
392
1214
 
@@ -479,6 +1301,8 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
479
1301
  const pin = result.pin;
480
1302
  // `classify` removes only the first-line route line and returns every other byte unchanged (probe, QA-2.2-5).
481
1303
  const stripped = result.stripped !== prompt ? result.stripped : undefined;
1304
+ const strippedRoot = stripped === undefined ? undefined : result.trace.routeLine?.root;
1305
+ if (typeof strippedRoot === "string" && strippedRoot !== "") rememberStrippedRoot(call.callID, strippedRoot);
482
1306
  const callModel = str(args.model) ?? call.tierModel ?? null;
483
1307
  const resumeID = str(args.sessionID);
484
1308
  const decisionID = `${call.sessionID}:${safeNow(now)}:${instanceNonce}:${++sequence}`;
@@ -633,6 +1457,389 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
633
1457
  return outcome;
634
1458
  };
635
1459
 
1460
+ // -------------------------------------------------------------------------
1461
+ // #84 P2.1 (T2.1.2): the role path. Tier dispatches never reach it (I1).
1462
+ // -------------------------------------------------------------------------
1463
+
1464
+ const workRootDeps: WorkRootDeps = {
1465
+ listWorktrees: deps.listWorktrees ?? gitWorktreeList,
1466
+ realpath: deps.realpath ?? ((path: string) => realpathSync.native(path)),
1467
+ platform: deps.platform ?? process.platform,
1468
+ };
1469
+
1470
+ /**
1471
+ * The rung a resumed child runs on: the dispatch registry's record (its `tier` is the role tier the router registered), else the
1472
+ * child session's own model; unknown → a model off every ladder, which the kernel lifts to the window ceiling (never below).
1473
+ */
1474
+ const runningRungOf = async (resumeID: string): Promise<{ tier: string | null; model: string; variant: string | null }> => {
1475
+ const record = lookupDispatch(resumeID);
1476
+ if (record !== undefined && record.model !== null) return { tier: record.tier ?? null, model: record.model, variant: record.variant ?? null };
1477
+ try {
1478
+ const ref = readSession(await deps.getSession(resumeID)).model;
1479
+ const parts = ref === null ? null : splitModelRef(ref);
1480
+ if (parts !== null) return { tier: null, model: `${parts.provider}/${parts.model}`, variant: parts.variant };
1481
+ } catch {
1482
+ // unknown: fail closed below
1483
+ }
1484
+ return { tier: null, model: "unknown/unknown", variant: null };
1485
+ };
1486
+
1487
+ /** `null`: not a role dispatch (tiers mode, a tier or host agent). A role agent whose preparation fails is refused. */
1488
+ const prepareRole = async (agent: string, cfg: RouterConfig | undefined): Promise<RolePrepared | null> => {
1489
+ const prepareRoles = deps.runtime.prepareRoles;
1490
+ if (prepareRoles === undefined) return null;
1491
+ // QA-P21-1-8 / QA-P21-2-4: not started in roles mode, or this role agent was not registered: the tier path, as today.
1492
+ if (deps.rolesEnabled !== undefined && !deps.rolesEnabled(agent)) return null;
1493
+
1494
+ try {
1495
+ return await prepareRoles.call(deps.runtime, agent, cfg);
1496
+ } catch (error) {
1497
+ // `prepareRoles` throws only once it knows `agent` is a role agent (fail closed).
1498
+ throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.failed(describeError(error)));
1499
+ }
1500
+ };
1501
+
1502
+ const decideRoleDispatch = async (call: RouteCall, rp: RolePrepared, session: SessionView): Promise<RouteOutcome> => {
1503
+ const { args } = call;
1504
+ const agent = rp.spec.agent;
1505
+ const prompt = typeof args.prompt === "string" ? args.prompt : null;
1506
+ if (prompt === null) throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.noPrompt);
1507
+ const description = typeof args.description === "string" ? args.description : "";
1508
+ const sessionDirectory = session.directory ?? deps.directory;
1509
+ const resumeID = str(args.sessionID);
1510
+ const resumed = resumeID !== null;
1511
+
1512
+ // 1. the route line, from a rules-only pass (never the backend); a malformed first route line refuses the dispatch (handoff 4).
1513
+ const lined = await classify({ description, prompt, cwd: sessionDirectory }, { ...rp.classifyDeps, backend: null });
1514
+ if (lined.trace.routeLines.malformed === true) throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.malformed);
1515
+
1516
+ // 2. work root: `root=` from the trace only, text-compared with `git worktree list --porcelain` before any filesystem call.
1517
+ const root = await resolveRoleWorkRoot({ root: lined.trace.routeLine?.root ?? null, sessionDirectory }, workRootDeps);
1518
+ const bound = resumeID === null ? undefined : currentBinding(resumeID, { maxOf: (name) => roleMaxActions(rp.roles.get(name)) });
1519
+
1520
+ // 3. classify in the dispatch's own root (QA-G-B-3 (1)): an absolute path inside it is no `external_dir`. A resume of an exactly
1521
+ // bound child is classified in its bound root (QA-P33F1-1-1); without a `root=` (the work root is the session directory) or a
1522
+ // validated one, in the session directory as the host names it.
1523
+ const requestedRoot = root.requested !== null ? root.workRoot : null;
1524
+ const classifyCwd = (bound?.kind === "exact" ? bound.grant.workRoot : null) ?? requestedRoot ?? sessionDirectory;
1525
+ const result = await classify({ description, prompt, cwd: classifyCwd }, rp.classifyDeps);
1526
+ if (result.trace.routeLines.malformed === true) throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.malformed);
1527
+ const routeLine = result.trace.routeLine;
1528
+ // QA-G-B-3 (2): a dynamic role's route line decides its needs (narrow-only). QA-G-B-1: a resume is decided on the facts of the
1529
+ // dispatch it resumes (class, confidence, needs; risk/scope the max with its own, raise-only).
1530
+ const matches = classifyNeedMatches({ description, prompt, cwd: classifyCwd }, rp.classifyDeps);
1531
+ const original = resumeID === null ? undefined : lookupDispatch(resumeID);
1532
+ const ownFacts = effectiveFactsOf({ facts: roleNeedsOf(result.facts, routeLine, rp.spec, new Set(matches.map((m) => m.need))), trace: result.trace });
1533
+ const taskFacts = resumeFactsOf(original?.facts, ownFacts);
1534
+ const classified: ClassifyResult = { ...result, facts: taskFacts };
1535
+ // QA-G-B-3 (3): why each need could be there (before any narrowing), for the decision row's trace.
1536
+ const needTerms = [
1537
+ ...matches.map((m) => `${m.need}:${m.term}`),
1538
+ ...(routeLine?.needs ?? []).map((need) => `${need}:route-line`),
1539
+ // the implied needs of the rules' class and of the final class (the route line's, or the backend's)
1540
+ ...[...new Set([result.trace.rules.class, result.facts.class])].flatMap((cls) => CLASS_IMPLIED_NEEDS[cls].map((need) => `${need}:class=${cls}`)),
1541
+ ...(original === undefined ? [] : original.facts.needs.map((need) => `${need}:resumed-dispatch`)),
1542
+ ];
1543
+
1544
+ // 4. grant (widened actions of a resume recompute the floor, handoff 36). QA-P21-2-1: a resume of an EXACTLY bound child keeps
1545
+ // what that child holds (its bound grant) plus the widened actions — the resume prompt alone ("continue") would lose them.
1546
+ const grant: DispatchGrant = bound?.kind === "exact" ? resumedGrant(bound.grant, call.widened ?? [])
1547
+ : grantFor(rp.spec, taskFacts, call.widened ?? [], root.workRoot, routeLine);
1548
+
1549
+ // 5. effective detection (S10/P-9, A34; handoff 5): never `result.detection` as is. QA-G-B-1: a resume that names no
1550
+ // `[acceptance]` block of its own carries the one of the dispatch it resumes (and its `VERIFY:` lines, when it names none), so
1551
+ // the floor and the router's gate see the same acceptance as that dispatch — the block is appended to the resume's prompt.
1552
+ const own = verificationParts(prompt);
1553
+ const carried = resumed && own.block === null ? original?.verification ?? null : null;
1554
+ const carriedText = carried === null ? null : [...(own.directives.length === 0 ? carried.directives : []), carried.block].join("\n");
1555
+ const verifyPrompt = carriedText === null ? prompt : withLastLine(prompt, carriedText);
1556
+ // QA-G-B N-a: the `d=` claim travels with the block it was made for (a resume's own route line names its own).
1557
+ const claim = result.detection ?? (carried === null ? null : carried.claim ?? null);
1558
+ const verification: CarriedVerification | null = own.block !== null
1559
+ ? { block: own.block, directives: own.directives, ...(result.detection == null ? {} : { claim: result.detection }) }
1560
+ : carried === null ? null : {
1561
+ block: carried.block, directives: own.directives.length > 0 ? own.directives : carried.directives,
1562
+ ...(claim === null ? {} : { claim }),
1563
+ // QA-G-B-2-1: the same lineage — judged against the baseline of the attempt that introduced the block.
1564
+ ...(carried.baseline === undefined ? {} : { baseline: carried.baseline }),
1565
+ };
1566
+ const acceptance = detectionOf(verifyPrompt);
1567
+ const bypassed = deps.isBypassed?.(call.sessionID) === true;
1568
+ const env = deps.env === undefined ? {} : { env: deps.env };
1569
+ const verifyRoot = verifyRootOf(grant, sessionDirectory, workRootDeps.realpath);
1570
+ const routerGate = roleRouterGate({
1571
+ cfg: rp.cfg, bypassed, acceptance, ...env,
1572
+ // QA-P21-1-2, QA-P21-2 nit 3. QA-G-B-2-1: a carried acceptance is never deferred (its gate runs at the return); its change-set
1573
+ // checks (testsPass, lintClean) can cover the child's earlier attempts only once the attempt that introduced the block was
1574
+ // gated with a known change set (its baseline) — until then the gate cannot back `deterministic`.
1575
+ deferred: carried === null
1576
+ ? roleGateDeferred(rp.cfg, verifyPrompt, description, { verifyEnabled: deps.routerVerifyEnabled?.() !== false })
1577
+ : (carried.baseline === undefined || carried.baseline.changed === "unavailable") && carriedChecksChangeSet(carried.block),
1578
+ outsideWorkRoot: roleGateOutsideWorkRoot(grant.workRoot, verifyPrompt, description, args.cwd), // DF2-F1, QA-P33F1-1-1, nit 3
1579
+ });
1580
+ // QA-G-B-7: the gate verifies nothing at all (enforcement off, /bypass, `require: never`, a cwd outside the root it verifies in)
1581
+ // → detection `none`.
1582
+ const verifies = roleVerificationRuns({
1583
+ cfg: rp.cfg, bypassed, ...env, outsideWorkRoot: roleGateOutsideWorkRoot(verifyRoot, verifyPrompt, description, args.cwd),
1584
+ });
1585
+ const detection = effectiveDetection({ routerGate, claim, acceptance, verifies });
1586
+
1587
+ // 6. bounds on the one role tier order (handoff 9); a resume passes the child's running tier. QA-P21-2-2: the raise recorded
1588
+ // after a verification FAIL of this child (for this parent) is a raise-only floor, like `floorTier`; consumed on success.
1589
+ const running = resumeID === null ? null : await runningRungOf(resumeID);
1590
+ const tiers = roleTierOrder(rp.cfg, rp.session);
1591
+ const raised = resumeID === null ? null : pendingResumeRaise(resumeID, call.sessionID);
1592
+ const floorTier = higherTier(tiers, rp.cfg.enforcement?.escalate?.floorTier ?? null, raised);
1593
+ const bounds = tierBounds(rp.spec, grant, classified, detection, {
1594
+ floorTier,
1595
+ runningTier: running?.tier ?? null,
1596
+ pinTier: routeLine?.tier ?? null,
1597
+ tiers,
1598
+ });
1599
+
1600
+ // 7. kernel (handoff 10: kernel.ts / ladders.ts); `dispatch === null` refuses, never a fallback (handoff 6).
1601
+ const ladder = buildRoleLadder({
1602
+ cfg: rp.cfg, facts: taskFacts, role: agent, window: bounds, pricing: (model) => rp.catalog.pricing(model), logger: deps.logger, session: rp.session,
1603
+ });
1604
+ const decisionID = `${call.sessionID}:${safeNow(now)}:${instanceNonce}:${++sequence}`;
1605
+ const rd = decideRole({
1606
+ classified, ladder, detection, engine: rp.engine, routing: rp.routing, store: rp.store,
1607
+ resume: running === null ? null : { model: running.model, variant: running.variant },
1608
+ exploration: { rate: rp.exploration, decisionID },
1609
+ });
1610
+ if (rd.dispatch === null) throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.noCandidate(bounds.floor, bounds.ceiling, rd.reasons));
1611
+
1612
+ // 8. an explicit caller `model` is kept only inside the bounds, and never over a route-line pin (QA-P21-1-5: the pinned rung,
1613
+ // raised to the running rung on a resume, wins); then the host catalog decides whether the variant exists.
1614
+ const notes: string[] = [...(root.note === null ? [] : [root.note]), ...grant.notes];
1615
+ if (carried !== null) notes.push(CARRIED_ACCEPTANCE_NOTE);
1616
+ // #84 P2.3 (T2.3.3): the row of a resume records the authority it widens (the actions new to this child's grant).
1617
+ const widenedNow = (call.widened ?? []).filter((action) => grant.actions.has(action) && bound?.grant.actions.has(action) !== true);
1618
+ if (widenedNow.length > 0) notes.push(BINDING_NOTES.widened(widenedNow));
1619
+ if (raised !== null) notes.push(`${RESUME_RAISE_NOTE}${raised}`);
1620
+ const callerRef = str(args.model);
1621
+ const placed = callerRef === null
1622
+ ? null
1623
+ : bounds.pinned !== null
1624
+ ? { candidate: rd.dispatch, code: PIN_OVER_CALLER_REASON }
1625
+ : placeCallerModel(ladder, callerRef, rd.dispatch, resumed);
1626
+ const picked: Candidate = placed === null ? rd.dispatch : placed.candidate;
1627
+ // QA-G-B nit N1: an explicit caller `model` that wins over an exploration draw makes the dispatch no exploration (a route-line
1628
+ // pin over the caller keeps the kernel's pick, so its draw stands).
1629
+ const explored = rd.explore && (placed === null || placed.code === PIN_OVER_CALLER_REASON);
1630
+ const variantPlace = placeInCatalog(ladder, picked, rp.catalog);
1631
+ if (variantPlace === null) {
1632
+ throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.noCandidate(bounds.floor, bounds.ceiling, [...rd.reasons, VARIANT_NO_CANDIDATE_REASON]));
1633
+ }
1634
+ const { candidate: dispatch, variant: finalVariant, dropped } = variantPlace;
1635
+ if (dropped !== null) notes.push(dropped);
1636
+ const model = refOf(dispatch.model, finalVariant);
1637
+ const tier = dispatch.tier;
1638
+
1639
+ // 9. binding markers (a fresh dispatch only; handoff 31): nonce at the END of the description, nonce line LAST in the prompt.
1640
+ // QA-G-B-1: a resume's carried verification is appended instead (it has no nonce).
1641
+ const nonce = resumed ? null : newDispatchNonce();
1642
+ const outPrompt = nonce !== null ? withLastLine(result.stripped, noncePromptLine(nonce))
1643
+ : carriedText === null ? result.stripped : withLastLine(result.stripped, carriedText);
1644
+ const outDescription = nonce === null ? null : `${description}${nonceTitleSuffix(nonce)}`;
1645
+ const routeBudget = routeLine?.budget ?? null;
1646
+ const budget = roleGuardProfile(rp.spec, tier, routeBudget).budget;
1647
+
1648
+ // 10. the decision row with the role extension (no row when the engine is static).
1649
+ const decision = rd.decision;
1650
+ const facts = taskFacts;
1651
+ const cls = facts.class;
1652
+ const ran: ChosenDispatch = { agent: { origin: "role", id: agent }, model: dispatch.model, variant: finalVariant };
1653
+ let row: DecisionRow | null = null;
1654
+ const mode = rp.engine;
1655
+ if (mode !== "static" && rp.enqueue !== null) {
1656
+ // QA-P21-1-6: switched/chosen follow the kernel's decision; a variant the catalog lacks only changes what is dispatched.
1657
+ const applied = mode === "enforce" && rd.switched && placed === null;
1658
+ const wouldSwitch = mode !== "enforce" && !resumed && decision.switched && placed === null;
1659
+ const argmin = decision.argmin !== null && decision.argmin.key !== decision.best?.key ? decision.argmin : null;
1660
+ const head = resumed
1661
+ ? `${RESUME_REASON}: a role dispatch that resumes a child is never switched or explored (A30); engine decision: ${reasonText(decision)}`
1662
+ : explored
1663
+ ? `explore: exploration draw (propensity ${rd.propensity}); engine decision: ${reasonText(decision)}`
1664
+ : placed !== null
1665
+ ? `${placed.code}: the call named model ${callerRef}; engine decision: ${reasonText(decision)}`
1666
+ : reasonText(decision);
1667
+ const extra = [...rd.reasons, ...notes];
1668
+ // QA-P21-1-11: a fresh dispatch has no binding yet (its child binds later; `noteBinding` writes the observed kind then).
1669
+ // A resume records the child's current binding.
1670
+ const binding = resumed ? currentBinding(resumeID, { maxOf: (name) => roleMaxActions(rp.roles.get(name)) })?.kind : undefined;
1671
+ row = {
1672
+ v: LOG_ROW_VERSION,
1673
+ ts: new Date(safeNow(now)).toISOString(),
1674
+ sessionID: call.sessionID,
1675
+ kind: "decision",
1676
+ decisionID,
1677
+ mode,
1678
+ childSessionID: resumeID,
1679
+ facts: factsOf(facts),
1680
+ chosen: applied && rd.base !== null ? choiceOf(cls, rd.base) : choiceOf(cls, ran),
1681
+ best: decision.best,
1682
+ switched: applied || wouldSwitch,
1683
+ pinned: decision.pinned,
1684
+ unit: decision.unit,
1685
+ costs: { ...decision.costs },
1686
+ confidence: decision.confidence,
1687
+ reason: `${head}; role @${agent} on ${tier} in ${bounds.floor}..${bounds.ceiling}${extra.length > 0 ? ` [${extra.join("; ")}]` : ""}`,
1688
+ step: "dispatch",
1689
+ resume: resumed,
1690
+ trace: { ...traceOf(result, argmin), needTerms }, // QA-G-B-3 (3)
1691
+ detection: {
1692
+ effective: detection,
1693
+ ...(result.detection !== undefined && result.detection !== null && result.detection !== detection ? { claimed: result.detection } : {}),
1694
+ },
1695
+ capability: { pick: rd.base?.rank ?? null, dispatched: dispatch.rank },
1696
+ role: agent,
1697
+ tier,
1698
+ grant: [...grant.actions].sort(),
1699
+ boundsReasons: [...bounds.reasons],
1700
+ explore: explored,
1701
+ propensity: rd.propensity,
1702
+ ...(binding === undefined ? {} : { binding }),
1703
+ };
1704
+ }
1705
+ const logged = row === null ? null : decisionID;
1706
+
1707
+ const routed: RoleRouted = {
1708
+ callID: call.callID,
1709
+ parentSessionID: call.sessionID,
1710
+ agent,
1711
+ tier,
1712
+ model,
1713
+ window: { floor: bounds.floor, ceiling: bounds.ceiling, pinned: bounds.pinned },
1714
+ grant,
1715
+ workRoot: root.workRoot,
1716
+ verifyRoot,
1717
+ requestedRoot: root.requested,
1718
+ notes,
1719
+ detection,
1720
+ budget,
1721
+ routeBudget,
1722
+ nonce,
1723
+ decisionID: logged,
1724
+ resumeID,
1725
+ nextTier: nextRoleTier(tiers, rp.spec.tierRange.ceiling, tier),
1726
+ class: cls,
1727
+ ...(carried !== null ? { carried: true as const } : {}), // QA-G-B-2-1
1728
+ };
1729
+ rememberRoutedRole(routed);
1730
+ if (raised !== null && resumeID !== null) resumeRaises.delete(resumeID); // QA-P21-2-2: consumed once, by a routed resume
1731
+
1732
+ decided.set(call.callID, {
1733
+ parentSessionID: call.sessionID,
1734
+ decisionID,
1735
+ facts: factsOf(facts),
1736
+ acceptance: depthOf(detection),
1737
+ description: outDescription ?? (description !== "" ? description : null),
1738
+ row,
1739
+ enqueue: rp.enqueue ?? (() => {}),
1740
+ capabilityOf: (r) => (r.agent === agent && sameModelVariant(r, ran) ? dispatch.rank : null),
1741
+ final: { agent, model: dispatch.model, variant: finalVariant },
1742
+ routerIds: routerTierIds(rp.cfg),
1743
+ resolve: (target) => resolveChosen({ cfg: rp.cfg, agents: null, agent: target, parentModel: session.model }),
1744
+ picked: agent,
1745
+ at: now(),
1746
+ role: {
1747
+ tier,
1748
+ outcomes: mode !== "static",
1749
+ pending: nonce === null ? null : { nonce, grant, budget, description: outDescription ?? description, decisionID: logged },
1750
+ verification,
1751
+ },
1752
+ });
1753
+ trim(decided, MAX_PENDING);
1754
+ return {
1755
+ mode,
1756
+ ...(outPrompt !== prompt ? { prompt: outPrompt } : {}),
1757
+ model,
1758
+ ...(logged === null ? {} : { decisionID: logged }),
1759
+ ...(outDescription === null ? {} : { description: outDescription }),
1760
+ role: routed,
1761
+ };
1762
+ };
1763
+
1764
+ /**
1765
+ * QA-P21-1-1: a role dispatch made by a session that has a parent (a delegate). Its prompt is never parsed (no route line, pin
1766
+ * or steering) and nothing is registered for it (no nonce, no pending entry, no row: its child binds `unknown`), but it never
1767
+ * runs on a model of its own choosing (I2): any caller `model` is replaced by the FLOOR rung of the window computed on the
1768
+ * unknown-binding grant (role max ∩ local, I9) — on a resume never below the child's running tier — and, as a routed role
1769
+ * dispatch, it is forced to the foreground (P-5).
1770
+ */
1771
+ const decideDelegateRoleDispatch = (call: RouteCall, rp: RolePrepared, session: SessionView): RouteOutcome => {
1772
+ const agent = rp.spec.agent;
1773
+ const max = new Set<AuthorityAction>(roleMaxActions(rp.spec) ?? []);
1774
+ const grant: DispatchGrant = { actions: new Set(LOCAL_ACTIONS.filter((a) => max.has(a))), notes: [DELEGATE_DISPATCH_NOTE], workRoot: null };
1775
+ const facts: TaskFacts = { class: "other", risk: "low", scope: "single", needs: [], confidence: 0, source: "rules" };
1776
+ const detection = effectiveDetection({ routerGate: false, claim: null, acceptance: null });
1777
+ const tiers = roleTierOrder(rp.cfg, rp.session);
1778
+ const resumeID = str(call.args.sessionID);
1779
+ const runningTier = resumeID === null ? null : lookupDispatch(resumeID)?.tier ?? null;
1780
+ const bounds = tierBounds(rp.spec, grant, { facts, trace: { rules: facts, routeLine: null } }, detection, {
1781
+ floorTier: rp.cfg.enforcement?.escalate?.floorTier ?? null, runningTier, pinTier: null, tiers,
1782
+ });
1783
+ const ladder = buildRoleLadder({
1784
+ cfg: rp.cfg, facts, role: agent, window: { floor: bounds.floor, ceiling: bounds.ceiling, pinned: null },
1785
+ pricing: (model) => rp.catalog.pricing(model), logger: deps.logger, session: rp.session,
1786
+ });
1787
+ const first = ladder.tiers.find((t) => t.tier === bounds.floor)?.first ?? ladder.tiers.find((t) => t.first !== null)?.first ?? null;
1788
+ const rung = first === null ? undefined : ladder.candidates[first];
1789
+ const placed = rung === undefined ? null : placeInCatalog(ladder, rung, rp.catalog);
1790
+ if (placed === null) {
1791
+ throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.noCandidate(bounds.floor, bounds.ceiling, rung === undefined ? ["window:no-candidates"] : [VARIANT_NO_CANDIDATE_REASON]));
1792
+ }
1793
+ const tier = placed.candidate.tier;
1794
+ const model = refOf(placed.candidate.model, placed.variant);
1795
+ const routed: RoleRouted = {
1796
+ callID: call.callID,
1797
+ parentSessionID: call.sessionID,
1798
+ agent,
1799
+ tier,
1800
+ model,
1801
+ window: { floor: bounds.floor, ceiling: bounds.ceiling, pinned: null },
1802
+ grant,
1803
+ workRoot: null,
1804
+ verifyRoot: verifyRootOf(grant, session.directory ?? deps.directory, workRootDeps.realpath),
1805
+ requestedRoot: null,
1806
+ notes: [DELEGATE_DISPATCH_NOTE, ...(placed.dropped === null ? [] : [placed.dropped])],
1807
+ detection,
1808
+ budget: roleGuardProfile(rp.spec, tier, null).budget,
1809
+ routeBudget: null,
1810
+ nonce: null,
1811
+ decisionID: null,
1812
+ resumeID,
1813
+ nextTier: nextRoleTier(tiers, rp.spec.tierRange.ceiling, tier),
1814
+ class: null,
1815
+ delegate: true, // QA-G-A1-2: the adapter never consumes an authority request on this path
1816
+ };
1817
+ rememberRoutedRole(routed);
1818
+ return { mode: rp.engine, model, role: routed };
1819
+ };
1820
+
1821
+ /** A role dispatch, from `route()`: claimed like a tier call (A3); only the orchestrator's own dispatch is routed. */
1822
+ const routeRoleCall = async (call: RouteCall, callKey: string, rp: RolePrepared): Promise<RouteOutcome> => {
1823
+ const agent = rp.spec.agent;
1824
+ if (handledCalls.has(callKey)) return UNTOUCHED; // A3: another instance already acted on this call
1825
+ let session: SessionView;
1826
+ try {
1827
+ session = readSession(await deps.getSession(call.sessionID));
1828
+ } catch (error) {
1829
+ throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.session(describeError(error)));
1830
+ }
1831
+ if (!claimCall(callKey)) return UNTOUCHED;
1832
+ try {
1833
+ // QA-P21-1-1: a delegate's dispatch is never parsed (it must not pin or steer), but it runs on the router's floor rung of
1834
+ // the unknown-binding window, in the foreground — never on a model the delegate names (I2).
1835
+ if (session.parentID !== null) return decideDelegateRoleDispatch(call, rp, session);
1836
+ return await decideRoleDispatch(call, rp, session);
1837
+ } catch (error) {
1838
+ if (error instanceof RoleDispatchRefusal) throw error;
1839
+ throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.failed(describeError(error)));
1840
+ }
1841
+ };
1842
+
636
1843
  return {
637
1844
  async route(call): Promise<RouteOutcome> {
638
1845
  try {
@@ -652,6 +1859,9 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
652
1859
  }
653
1860
  }
654
1861
  if (agent === null || agent === deps.graderAgent) return UNTOUCHED;
1862
+ // #84 P2.1: a role agent of roles mode (v2) takes the role path in EVERY engine mode; tiers mode gets `null` before any host call.
1863
+ const role = await prepareRole(agent, call.cfg);
1864
+ if (role !== null) return await routeRoleCall(call, callKey, role);
655
1865
  const prepared = await deps.runtime.prepare(call.cfg);
656
1866
  if (prepared === null) return UNTOUCHED; // static: nothing touched
657
1867
  if (handledCalls.has(callKey)) return UNTOUCHED; // A3 (QA-2.2-12): another instance already acted on this call
@@ -670,6 +1880,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
670
1880
  const view = await deps.runtime.agents(session.agent ?? call.agent, session.rules);
671
1881
  return await decideAndRecord(call, prepared, session, view);
672
1882
  } catch (error) {
1883
+ if (error instanceof RoleDispatchRefusal) throw error; // #84 P2.1: the host must refuse the role dispatch
673
1884
  deps.logger.warn("[router] routing: the engine failed; the dispatch proceeds as the orchestrator chose", { error: describeError(error) });
674
1885
  return UNTOUCHED;
675
1886
  }
@@ -684,37 +1895,67 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
684
1895
  // The agent and model the host will run, after the legacy hook: they win over what the engine decided.
685
1896
  const ran = d.final === null ? null : ranOf(d, d.final, final);
686
1897
  // QA-G-A2: the hook chain let the call through, so the dispatch runs: its decision row is written now (never for a rejected call).
1898
+ let written: DecisionRow | null = null;
687
1899
  try {
688
1900
  // A34 (QA-G-B8): the capability of what really runs, after the legacy hook.
689
1901
  const dispatched = ran === null ? null : d.capabilityOf(ran);
690
- d.enqueue({ ...d.row, capability: { pick: d.row.capability?.pick ?? null, dispatched } });
1902
+ if (d.row !== null) {
1903
+ written = { ...d.row, capability: { pick: d.row.capability?.pick ?? null, dispatched } };
1904
+ d.enqueue(written);
1905
+ }
691
1906
  } catch (error) {
692
1907
  deps.logger.warn("[router] routing: the decision row could not be queued", { error: describeError(error) });
693
1908
  }
1909
+ // #84 P2.1: a fresh role dispatch registers its pending binding entry from the input the host will execute (handoff 31).
1910
+ const rolePending = d.role !== undefined && d.role.pending !== null && str(final.sessionID) === null;
1911
+ if (rolePending && d.role !== undefined && d.role.pending !== null) {
1912
+ try {
1913
+ registerPending({
1914
+ parentSessionID: d.parentSessionID,
1915
+ callID,
1916
+ agent: str(final.agent) ?? d.picked,
1917
+ description: str(final.description) ?? d.role.pending.description,
1918
+ nonce: d.role.pending.nonce,
1919
+ grant: d.role.pending.grant,
1920
+ budget: d.role.pending.budget,
1921
+ decisionID: d.role.pending.decisionID,
1922
+ registeredAt: Date.now(), // the binding registry's own clock
1923
+ });
1924
+ } catch (error) {
1925
+ deps.logger.warn("[router] routing: the role dispatch could not be registered for binding", { error: describeError(error) });
1926
+ }
1927
+ }
694
1928
  if (ran === null) return; // nothing to record a step against
695
1929
  const { agent, model, variant } = ran;
1930
+ const resumeID = str(final.sessionID);
1931
+ // QA-2.2-R2-1: remember what the registry held for a resumed child, in case the host then rejects the resume.
1932
+ const previous = resumeID === null ? undefined : lookupDispatch(resumeID);
1933
+ // QA-G-B-1: a role resume never overwrites the class the child was dispatched under, so an attempt raised after a FAIL is
1934
+ // recorded (and scored) under the original class.
1935
+ const facts = d.role !== undefined && previous !== undefined ? { ...d.facts, class: previous.facts.class } : d.facts;
696
1936
  const dispatched: DispatchInput = {
697
- facts: d.facts,
1937
+ facts,
698
1938
  agent,
699
1939
  model,
700
1940
  variant,
701
- tier: classifyAgentOrigin(agent, d.routerIds) === "router" ? agent : null,
1941
+ tier: d.role !== undefined && agent === d.picked ? d.role.tier : classifyAgentOrigin(agent, d.routerIds) === "router" ? agent : null,
702
1942
  acceptance: d.acceptance,
703
1943
  parentSessionID: d.parentSessionID,
704
1944
  decisionID: d.decisionID,
705
1945
  step: "dispatch",
706
1946
  picked: d.picked,
1947
+ ...(d.role !== undefined && !d.role.outcomes ? { outcomes: false } : {}),
1948
+ ...(d.role?.verification == null ? {} : { verification: d.role.verification }),
707
1949
  };
708
1950
  const t = now();
709
1951
  sweep(t);
710
- const resumeID = str(final.sessionID);
711
- // QA-2.2-R2-1: remember what the registry held for a resumed child, in case the host then rejects the resume.
712
- const previous = resumeID === null ? undefined : lookupDispatch(resumeID);
713
1952
  const entry: Entry = {
714
1953
  callID, parentSessionID: d.parentSessionID, agent, description: d.description, input: dispatched, at: t,
715
1954
  state: resumeID === null ? "waiting" : "resumed",
716
1955
  ...(resumeID === null ? {} : { resumeID }),
717
1956
  ...(previous === undefined ? {} : { previous }),
1957
+ ...(rolePending ? { rolePending: true as const } : {}),
1958
+ ...(d.role !== undefined && written !== null ? { roleRow: { row: written, enqueue: d.enqueue } } : {}),
718
1959
  };
719
1960
  if (resumeID !== null) register(resumeID, dispatched);
720
1961
  entries.delete(callID);
@@ -782,6 +2023,54 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
782
2023
  const entry = entries.get(callID);
783
2024
  entries.delete(callID);
784
2025
  if (entry !== undefined) undoResume(entry);
2026
+ // #84 P2.1: a rejected role call leaves no pending binding entry and no routed record behind.
2027
+ routedRoles.delete(callID);
2028
+ strippedRoots.delete(callID);
2029
+ if (entry?.rolePending === true) {
2030
+ try {
2031
+ evictCall(entry.parentSessionID, callID);
2032
+ } catch (error) {
2033
+ deps.logger.warn("[router] routing: a rejected role dispatch could not be evicted from the binding registry", { error: describeError(error) });
2034
+ }
2035
+ }
2036
+ },
2037
+
2038
+ noteBinding(childSessionID, binding): void {
2039
+ try {
2040
+ if (notedBindings.has(childSessionID)) return;
2041
+ const decisionID = binding.decisionID ?? lookupDispatch(childSessionID)?.decisionID ?? null;
2042
+ const entry = [...entries.values()].find((e) => e.roleRow !== undefined
2043
+ && ((decisionID !== null && e.input.decisionID === decisionID) || e.claimedChild === childSessionID || e.resumeID === childSessionID));
2044
+ if (entry?.roleRow === undefined) return;
2045
+ notedBindings.add(childSessionID);
2046
+ while (notedBindings.size > MAX_HANDLED_CALLS) notedBindings.delete(notedBindings.values().next().value as string);
2047
+ const { row, enqueue } = entry.roleRow;
2048
+ enqueue({
2049
+ v: LOG_ROW_VERSION,
2050
+ kind: "decision",
2051
+ ts: new Date(safeNow(now)).toISOString(),
2052
+ sessionID: row.sessionID,
2053
+ decisionID: row.decisionID,
2054
+ mode: row.mode,
2055
+ childSessionID,
2056
+ facts: row.facts,
2057
+ chosen: row.chosen,
2058
+ best: null,
2059
+ switched: false,
2060
+ pinned: false,
2061
+ unit: row.unit,
2062
+ costs: {},
2063
+ confidence: row.confidence,
2064
+ reason: `${ANNOTATION_REASON}binding:${binding.kind}`,
2065
+ step: row.step,
2066
+ resume: row.resume,
2067
+ ...(row.role === undefined ? {} : { role: row.role }),
2068
+ ...(row.tier === undefined ? {} : { tier: row.tier }),
2069
+ binding: binding.kind,
2070
+ });
2071
+ } catch (error) {
2072
+ deps.logger.warn("[router] routing: the binding of a role child could not be recorded", { error: describeError(error) });
2073
+ }
785
2074
  },
786
2075
 
787
2076
  misclaimedCount: () => misclaimed.size,