opencode-model-router 2.3.0 → 2.5.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 (68) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +86 -11
  3. package/package.json +6 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1374 -24
  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/tui/effort-channel.ts +220 -0
  54. package/src/tui/effort-rpc.ts +60 -0
  55. package/src/tui/host-types.ts +154 -0
  56. package/src/tui/opentui-solid.d.ts +16 -0
  57. package/src/tui/plugin.ts +1007 -0
  58. package/src/tui/status-model.ts +561 -0
  59. package/src/v2.ts +26 -1
  60. package/src/verify/checker.ts +249 -7
  61. package/src/verify/deterministic.ts +10 -1
  62. package/src/verify/dispatch.ts +63 -6
  63. package/src/verify/dod.ts +127 -10
  64. package/src/verify/gate.ts +75 -7
  65. package/src/verify/types.ts +12 -0
  66. package/src/verify/wiring.ts +55 -10
  67. package/tiers.json +13 -5
  68. package/tui.ts +4 -0
package/src/index.ts CHANGED
@@ -15,15 +15,21 @@ import {
15
15
  resolveVerifyBudget,
16
16
  resolveDepthLimit,
17
17
  resolveRouting,
18
+ resolveRolesRouting,
18
19
  resolveVariantSteps,
19
20
  routerStatusLines,
20
21
  warnConfigIssues,
22
+ resolveActiveTiers,
21
23
  } from "./router/config";
22
24
  import type { RouterConfig, TierConfig, Preset, ModeConfig, EffortLevel } from "./router/config";
23
25
  import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
26
+ import { gitTools } from "./router/git-tools";
27
+ import { isReadOnlyTier, legacyReadOnlyTools, mergePermissions, readOnlyPermissions } from "./router/read-only";
28
+ import { buildPluginAgentDefinition, mergeHostAgentEntry, pluginAgentMarker } from "./router/plugin-agents";
29
+ import { filterSensitiveGrep } from "./router/sensitive-paths";
24
30
  import { selectTierPrompt, TOOL_AUTHORITY_CLAUSE } from "./router/prompts";
25
31
  import { stripDelegateInstructions } from "./router/instructions";
26
- import { buildDispatchHeader } from "./router/dispatch-header";
32
+ import { buildDispatchHeader, DISPATCH_HEADER_PREFIX, DISPATCH_HEADER_SEPARATOR, routeLineRoot } from "./router/dispatch-header";
27
33
  import { detectFalseRefusal, parseTaskResult as parseRefusalTaskResult } from "./router/false-refusal";
28
34
  import {
29
35
  buildTiersOutput,
@@ -44,6 +50,8 @@ import {
44
50
  } from "./commands/output";
45
51
  import {
46
52
  resolveSubagentOverrides,
53
+ DEFER_MISSING_SUBAGENT_NOTICE,
54
+ HOST_SEED_AGENTS,
47
55
  mergeSubagentOverride,
48
56
  } from "./router/subagents";
49
57
  import { fingerprintToolCall } from "./guard/fingerprint";
@@ -56,13 +64,32 @@ import {
56
64
  CLAUDE_ORCHESTRATOR_PREFIX,
57
65
  CLAUDE_ANTI_NARRATION,
58
66
  assembleSystemPrompt,
67
+ assembleRolesSystemPrompt,
59
68
  DELEGATE_TOOL_DESCRIPTION,
60
69
  } from "./router/protocol";
70
+ import { resolveRoles, type RoleSpec } from "./router/roles";
71
+ import { routerRunTool, type RunRecord } from "./router/run-tools";
72
+ import type { WorkRootAnswer } from "./router/git-tools";
73
+ import { GUARD_CUMULATIVE_MULTIPLIER, roleGuardProfile, type GuardProfile } from "./router/guard-profile";
74
+ import { currentBinding } from "./routing/roles/binding";
75
+ import { authorityTool, requestedAuthority } from "./routing/roles/authority";
76
+ import {
77
+ CARRIED_NO_PROCESS_REASON, roleAttemptVerification, roleEscalationAfterFail, roleMaxActions, routedRoleOf, strippedRouteRoot,
78
+ } from "./routing/wire/dispatch";
79
+ import { roleTierOrder } from "./routing/engine/ladders";
80
+ import { detectRedispatch, returnSignal, runSignal, parseReturnPrefix, type DispatchText } from "./routing/outcomes/signals";
81
+ import type { IngestSettings } from "./routing/outcomes/ingest";
82
+ import { captureBudget } from "./guard/enforce";
83
+ import { budgetClaimObserved, isIncompleteVerdict } from "./verify/checker";
84
+ import { lookupDispatch } from "./router/sessions";
61
85
  import { resolveEnforcementMode } from "./router/enforcement";
62
86
  import { createPluginLogger } from "./router/logger";
63
87
  import { createCatalogPricing, createIngest, ingestSettings } from "./routing/outcomes/ingest";
64
88
  import type { Ingest } from "./routing/outcomes/ingest";
65
- import { verdictOf } from "./routing/outcomes/types";
89
+ import { isAnnotationRow, verdictGraderOf, verdictOf, type LogRow } from "./routing/outcomes/types";
90
+ import { createPersister, nodePersistDeps, summarizeRoles } from "./routing/outcomes";
91
+ import { roleAgentSteps } from "./router/role-agents";
92
+ import type { HostBudgetObservation } from "./compat/v2-hooks";
66
93
  import { checkpointLine, formatStatsReply, runStatsCommand } from "./routing/commands/stats";
67
94
  import { buildAnnotateDirectives } from "./routing/commands/annotate-plan";
68
95
  import { applyV1Roles, hasExplicitV1Roles, v1AgentInfos } from "./routing/commands/v1-roles";
@@ -77,7 +104,7 @@ import {
77
104
  hostConfigFromAgents,
78
105
  runAdvisor,
79
106
  } from "./routing/advisor";
80
- import type { AdvisorCatalogModel, HostConfigView } from "./routing/advisor";
107
+ import type { AdvisorCatalogModel, AdvisorExtras, HostConfigView } from "./routing/advisor";
81
108
  import {
82
109
  findOrphanedStrongPatterns,
83
110
  normalizeCatalog,
@@ -97,7 +124,7 @@ import type { Cap, SubagentState } from "./router/sessions";
97
124
  import { createTrajectoryStore } from "./telemetry/trajectory";
98
125
  import { createGuardStore } from "./guard/store";
99
126
  import { createIdleTtlSweeper } from "./router/idle-sweep";
100
- import { guardBeforeCall, guardAfterCall, formatScorecard } from "./guard/enforce";
127
+ import { guardBeforeCall, guardAfterCall, guardRefusedCall, formatScorecard } from "./guard/enforce";
101
128
  import { mkdirSync, writeFileSync, existsSync } from "node:fs";
102
129
  import { tmpdir } from "node:os";
103
130
  import { join, isAbsolute } from "node:path";
@@ -123,6 +150,7 @@ import {
123
150
  buildForcingNote,
124
151
  buildAcceptedSuffix,
125
152
  } from "./verify/dispatch";
153
+ import { requestedVerificationCwd, requestedVerificationCwdSource, verificationScope, type VerificationScope } from "./routing/roles/work-root";
126
154
  import { newLadderState, recordAttempt, nextAction, advance, buildEscalatePolicy, formatLadderScorecard, startCostRatio } from "./escalate/ladder";
127
155
  import { createCatalogLookup, planFirstAttempt, planNextAttempt } from "./escalate/resume";
128
156
  import type { AttemptPlan, CatalogLookup } from "./escalate/resume";
@@ -155,6 +183,34 @@ function describeError(error: unknown): string {
155
183
  }
156
184
  }
157
185
 
186
+ /**
187
+ * #84 P2.2 (advisor `tierDispatches`): dispatch rows WITHOUT a role at or after `since` — non-annotation `dispatch` decision rows,
188
+ * the first row per decision id (as `summarizeRoles` keeps them), whose row names no role and whose chosen key is not a role's.
189
+ */
190
+ function tierDispatchCount(rows: readonly LogRow[], since: number): number {
191
+ const seen = new Set<string>();
192
+ let count = 0;
193
+ for (const row of rows) {
194
+ if (row.kind !== "decision" || isAnnotationRow(row) || row.step !== "dispatch" || seen.has(row.decisionID)) continue;
195
+ seen.add(row.decisionID);
196
+ const t = Date.parse(row.ts);
197
+ if (!Number.isFinite(t) || t < since) continue;
198
+ if (typeof row.role === "string" || row.chosen?.origin === "role") continue;
199
+ count += 1;
200
+ }
201
+ return count;
202
+ }
203
+
204
+ /**
205
+ * #84 P2.1 (handoffs 22, 23): one budget observation from the guard's and the host's. A stop seen by either is a stop; without a
206
+ * host observer (v1, or a host that does not hand one) the guard's alone; otherwise anything unobserved leaves it unobserved.
207
+ */
208
+ function foldBudgetObservation(guard: HostBudgetObservation, host: HostBudgetObservation | undefined): HostBudgetObservation {
209
+ if (guard === true || host === true) return true;
210
+ if (host === undefined) return guard;
211
+ return guard === "unobserved" || host === "unobserved" ? "unobserved" : false;
212
+ }
213
+
158
214
  function saveActivePreset(presetName: string, projectDir?: string): void {
159
215
  const cfg = loadConfig(projectDir);
160
216
  const resolved = resolvePresetName(cfg, presetName);
@@ -191,7 +247,7 @@ function saveEnforcementMode(mode: "off" | "advisory" | "enforced"): void {
191
247
  * `/router` dispatch. Decides and persists here; rendering lives in
192
248
  * src/commands/output.ts.
193
249
  */
194
- function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
250
+ function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string, roles?: Iterable<RoleSpec>): string {
195
251
  const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
196
252
  const sub = (tokens[0] ?? "").toLowerCase();
197
253
 
@@ -223,7 +279,8 @@ function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string)
223
279
  return buildRouterHelp(
224
280
  resolveEnforcementMode({ config: cfg, env: process.env }).mode,
225
281
  // `/router stats` is listed only for a config that has a `routing` block: without one `/router` is what it was (QA-2.4-3).
226
- { stats: cfg.routing !== undefined },
282
+ // #84 P2.2: the role lines, only when the caller hands roles (roles mode on v2); otherwise the help is what it was.
283
+ { stats: cfg.routing !== undefined, ...(roles === undefined ? {} : { roles }) },
227
284
  );
228
285
  }
229
286
 
@@ -280,6 +337,20 @@ function warnSessionLookupFailedOnce(): void {
280
337
  );
281
338
  }
282
339
 
340
+ /**
341
+ * Agents the v1 host defines itself (opencode v1.18.34 agent.ts). They are absent from the `opencodeConfig.agent`
342
+ * record the config hook receives, so `subagentTiers` needs them listed to avoid a false `missing` skip (QA-81-4).
343
+ */
344
+ const V1_HOST_BUILTIN_AGENTS: Record<string, { mode: string }> = {
345
+ general: { mode: "subagent" },
346
+ explore: { mode: "subagent" },
347
+ build: { mode: "primary" },
348
+ plan: { mode: "primary" },
349
+ title: { mode: "primary" },
350
+ summary: { mode: "primary" },
351
+ compaction: { mode: "primary" },
352
+ };
353
+
283
354
  const SESSION_ROOT_MEMO_MAX = 500;
284
355
  const SESSION_LOOKUP_RETRY_MS = DEPTH_LOOKUP_RETRY_MS;
285
356
 
@@ -293,6 +364,20 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
293
364
 
294
365
  // Per-plugin-instance session store: owns subagentSessionIDs and subagentCapState.
295
366
  const sessionStore = createSessionStore();
367
+ /** v1 sessionID -> plugin agent name, from chat.message (tool.execute.after has no `agent` on v1). */
368
+ const pluginAgentSessions = new Map<string, string>();
369
+ /** Records a plugin-agent session, bounded like the session-root memo (oldest entry evicted first). */
370
+ const rememberPluginAgentSession = (sessionID: string, agent: string): void => {
371
+ pluginAgentSessions.delete(sessionID);
372
+ pluginAgentSessions.set(sessionID, agent);
373
+ while (pluginAgentSessions.size > SESSION_ROOT_MEMO_MAX) {
374
+ const oldest = pluginAgentSessions.keys().next().value;
375
+ if (oldest === undefined) break;
376
+ pluginAgentSessions.delete(oldest);
377
+ }
378
+ };
379
+ /** Plugin agents the v1 config hook built on its previous run -> the host entry it merged (QA-81-8). */
380
+ let builtPluginAgents = new Map<string, Record<string, unknown> | undefined>();
296
381
  let systemDebugLogged = false;
297
382
  let dispatchDebugLogged = false;
298
383
 
@@ -416,13 +501,170 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
416
501
  // has no /log endpoint. See src/router/logger.ts.
417
502
  const logger = createPluginLogger(ctx.client);
418
503
  const routerWarn = { warn: (message: string) => logger.warn(message) };
504
+
505
+ // -------------------------------------------------------------------------
506
+ // #84 P2.1 (T2.1.3): the role runtime of roles mode on OpenCode v2. `rolesNow()` is empty on v1 and in tiers mode, so
507
+ // every role branch below is skipped there and both stay byte-identical (§2.7, I1, I8).
508
+ // -------------------------------------------------------------------------
509
+ const isV2Host = ctx.routerHost === "v2";
510
+ /**
511
+ * QA-P21-1-8 (plan R8): the role runtime exists only when the plugin STARTED in roles mode — its role tools are registered at
512
+ * start and its role agents only then (the v2 adapter logs "restart OpenCode" when the config switches to roles at runtime).
513
+ */
514
+ const startedInRoles = isV2Host && cfg.routing?.delegation === "roles";
515
+ /** QA-P21-2-4: the v2 adapter's "this role agent is registered" check (absent on v1 and before the adapter is set up). */
516
+ const roleLiveOf = (ctx as RouterPluginInput & { routerRoleLive?: (agent: string) => boolean | undefined }).routerRoleLive;
517
+ const NO_ROLES: ReadonlyMap<string, RoleSpec> = new Map();
518
+ const roleTables = new WeakMap<RouterConfig, ReadonlyMap<string, RoleSpec>>();
519
+ /** The role agents of the current config, cached per config object (hot reload builds a new one). */
520
+ const rolesNow = (): ReadonlyMap<string, RoleSpec> => {
521
+ if (!startedInRoles) return NO_ROLES;
522
+ const current = cfg;
523
+ let roles = roleTables.get(current);
524
+ if (roles === undefined) {
525
+ try {
526
+ roles = resolveRoles(current, "v2");
527
+ } catch (error) {
528
+ roles = NO_ROLES;
529
+ logger.warn("[router] roles: the role table could not be resolved; no role runtime for this config", { error: describeError(error) });
530
+ }
531
+ roleTables.set(current, roles);
532
+ }
533
+ // QA-P21-2-4: a role whose agent registration failed is not live (the v2 adapter's check; undefined = not known yet).
534
+ const live = roleLiveOf === undefined ? [...roles] : [...roles].filter(([name]) => roleLiveOf(name) !== false);
535
+ return live.length === roles.size ? roles : new Map(live);
536
+ };
537
+ const roleSpecOf = (agent: unknown): RoleSpec | undefined => (typeof agent === "string" ? rolesNow().get(agent) : undefined);
538
+ /** `maxOf` of every `currentBinding` call (handoff 33). */
539
+ const roleMaxOf = (agent: string) => roleMaxActions(rolesNow().get(agent));
540
+ /** Role child sessions → their role agent: from the tool hooks' calling agent and `session.created` (bounded, oldest out). */
541
+ const roleSessions = new Map<string, string>();
542
+ const ROLE_STATE_MAX = 1000;
543
+ const rememberRoleSession = (sessionID: unknown, agent: unknown): boolean => {
544
+ if (typeof sessionID !== "string" || sessionID === "" || typeof agent !== "string" || roleSpecOf(agent) === undefined) return false;
545
+ roleSessions.delete(sessionID);
546
+ roleSessions.set(sessionID, agent);
547
+ while (roleSessions.size > ROLE_STATE_MAX) roleSessions.delete(roleSessions.keys().next().value!);
548
+ return true;
549
+ };
550
+ /** The role of a session: what its tool hooks named, else what the dispatch registry recorded for it. */
551
+ const roleOfSession = (sessionID: unknown): RoleSpec | undefined => typeof sessionID !== "string" || sessionID === ""
552
+ ? undefined : roleSpecOf(roleSessions.get(sessionID) ?? lookupDispatch(sessionID)?.agent);
553
+ /**
554
+ * Handoff 11 (P-10, P-18): the ONE work-root resolver of `router_run` and `router_git_*`, from the child's binding (bound by the
555
+ * adapter's `execute.before` before any tool of the child runs). Not a role session → `{ role: false }` (git keeps today's
556
+ * directory; `router_run` refuses); a role session without a binding or a work root → `{ role: true, root: null }` (I9).
557
+ */
558
+ const resolveWorkRoot = (sessionID: string): WorkRootAnswer => {
559
+ if (roleOfSession(sessionID) === undefined) return { role: false };
560
+ return { role: true, root: currentBinding(sessionID, { maxOf: roleMaxOf })?.grant.workRoot ?? null };
561
+ };
562
+ /**
563
+ * #84 P2.3 (P-12, S11, I3): no `evaluate` fires for a plugin tool, so each tool's own resolver also refuses a role session whose
564
+ * dispatch grant lacks the tool's action (`router_run`: exec; `router_git_*`: local): the answer is then "no bound work root"
565
+ * and the tool refuses (I9). The context hook's catalog filter is the primary control; this one holds when a call gets through.
566
+ */
567
+ const resolveWorkRootFor = (action: "router_run" | "router_git") => (sessionID: string): WorkRootAnswer => {
568
+ const answer = resolveWorkRoot(sessionID);
569
+ if (!answer.role) return answer;
570
+ const grant = currentBinding(sessionID, { maxOf: roleMaxOf })?.grant;
571
+ return grant !== undefined && grant.actions.has(action) ? answer : { role: true, root: null };
572
+ };
573
+ /** What a routed role dispatch decided for its child's guard (QA-G-A3-3): the dispatched tier and the route line's `budget=`. */
574
+ interface RoutedGuardInput { readonly agent: string; readonly tier: string; readonly routeBudget: number | null }
575
+ /**
576
+ * QA-G-B-5 / QA-G-A3-3: each routed role dispatch this instance noted, by the parent's call — when it was dispatched (the
577
+ * attempt's start, for the `run` signal) and its routed guard input. Bounded, oldest out.
578
+ */
579
+ const roleAttempts = new Map<string, RoutedGuardInput & { readonly at: number }>();
580
+ /** QA-G-A3-3: the routed guard input of each role child — its latest routed dispatch or resume (a resume replaces it). */
581
+ const roleChildGuards = new Map<string, RoutedGuardInput>();
582
+ /** QA-G-A3-2-2: the largest round budget each role child's guard profile had (its cumulative limit follows it). */
583
+ const roleBudgetPeaks = new Map<string, number>();
584
+ const setBounded = <T>(map: Map<string, T>, key: string, value: T): void => {
585
+ map.delete(key);
586
+ map.set(key, value);
587
+ while (map.size > ROLE_STATE_MAX) map.delete(map.keys().next().value!);
588
+ };
589
+ /**
590
+ * QA-G-A3-3: the routed guard input of a role child. A resume set it in `noteRoleDispatch`; a fresh child takes its dispatch's
591
+ * once it is bound EXACTLY (its binding names the parent's call). Undefined when no routed decision is known for it.
592
+ */
593
+ const routedGuardOf = (sessionID: string): RoutedGuardInput | undefined => {
594
+ const known = roleChildGuards.get(sessionID);
595
+ if (known !== undefined) return known;
596
+ const binding = currentBinding(sessionID, { maxOf: roleMaxOf });
597
+ const callID = binding?.kind === "exact" ? binding.candidates[0] : undefined;
598
+ const attempt = callID === undefined ? undefined : roleAttempts.get(callID);
599
+ if (attempt === undefined) return undefined;
600
+ const routed: RoutedGuardInput = { agent: attempt.agent, tier: attempt.tier, routeBudget: attempt.routeBudget };
601
+ setBounded(roleChildGuards, sessionID, routed);
602
+ return routed;
603
+ };
604
+ /**
605
+ * Handoff 27: the guard profile of a role child — the role's budget for the tier it runs on, raised by the dispatch's `budget=`.
606
+ * QA-G-A3-3: both come from the ROUTED decision of the child's current dispatch (a resume's own tier and `budget=`); only a child
607
+ * without one (a delegate's unbound child, another instance's) falls back to the dispatch registry's tier (else the role's floor,
608
+ * its registered fallback model, P-1) and the bound dispatch budget.
609
+ */
610
+ const roleGuardProfileOf = (sessionID: unknown, agent: unknown): GuardProfile | undefined => {
611
+ const spec = roleSpecOf(agent) ?? roleOfSession(sessionID);
612
+ if (spec === undefined || typeof sessionID !== "string") return undefined;
613
+ const routed = routedGuardOf(sessionID);
614
+ let profile: GuardProfile;
615
+ if (routed !== undefined && routed.agent === spec.agent) {
616
+ profile = roleGuardProfile(spec, routed.tier, routed.routeBudget);
617
+ } else {
618
+ const record = lookupDispatch(sessionID);
619
+ const tier = record?.agent === spec.agent && typeof record.tier === "string" && record.tier !== "" ? record.tier : spec.tierRange.floor;
620
+ profile = roleGuardProfile(spec, tier, currentBinding(sessionID, { maxOf: roleMaxOf })?.budget ?? null);
621
+ }
622
+ // QA-G-A3-2-2 (§2.6): the cumulative limit spans the child's rounds, so it follows the LARGEST round budget the child had
623
+ // (a later round with a smaller budget never shrinks it below what earlier rounds were allowed).
624
+ const peak = Math.max(roleBudgetPeaks.get(sessionID) ?? 0, profile.budget);
625
+ if (roleBudgetPeaks.get(sessionID) !== peak) setBounded(roleBudgetPeaks, sessionID, peak);
626
+ return { ...profile, cumulative: Math.max(profile.cumulative, peak * GUARD_CUMULATIVE_MULTIPLIER) };
627
+ };
628
+ /** Handoff 13 (P1.4 `run` signal): router-observed runs and edit times of role children, bounded per child and overall. */
629
+ const roleRuns = new Map<string, RunRecord[]>();
630
+ const roleEdits = new Map<string, number[]>();
631
+ /** QA-P21-1-7: role children that made a tool call while the router was bypassed (their edits were not recorded). */
632
+ const roleBypassedCalls = new Set<string>();
633
+ const noteBypassedRoleCall = (sessionID: unknown): void => {
634
+ if (typeof sessionID !== "string" || roleOfSession(sessionID) === undefined) return;
635
+ roleBypassedCalls.add(sessionID);
636
+ while (roleBypassedCalls.size > ROLE_STATE_MAX) roleBypassedCalls.delete(roleBypassedCalls.values().next().value!);
637
+ };
638
+ const pushBounded = <T>(map: Map<string, T[]>, key: string, value: T): void => {
639
+ const list = map.get(key) ?? [];
640
+ map.delete(key);
641
+ list.push(value);
642
+ while (list.length > 64) list.shift();
643
+ map.set(key, list);
644
+ while (map.size > ROLE_STATE_MAX) map.delete(map.keys().next().value!);
645
+ };
646
+ const ROLE_EDIT_TOOLS: ReadonlySet<string> = new Set(["edit", "write", "patch", "multiedit", "apply_patch"]);
647
+ /** Handoffs 16-18: the parent's role dispatches (by call), for the re-dispatch signal; bounded, oldest out. */
648
+ const roleDispatchTexts = new Map<string, DispatchText>();
649
+ /** IngestSettings.roleAgentIds from `resolveRoles` (handoff 21): the same object per base settings, so ingestion keeps its caches. */
650
+ const roleIngestSettings = new WeakMap<IngestSettings, IngestSettings>();
651
+ const withRoleAgents = (settings: IngestSettings | null): IngestSettings | null => {
652
+ const roles = rolesNow();
653
+ if (settings === null || roles.size === 0) return settings;
654
+ let extended = roleIngestSettings.get(settings);
655
+ if (extended === undefined) {
656
+ extended = Object.freeze({ ...settings, roleAgentIds: new Set(roles.keys()) });
657
+ roleIngestSettings.set(settings, extended);
658
+ }
659
+ return extended;
660
+ };
419
661
  // M6 (2.1.3, QA-2.1-7): the one telemetry ingest of this plugin instance. v2 only (D1); every call is a no-op unless
420
662
  // routing.engine != static. Verdicts and false refusals come from the hooks below; the v2 adapter receives this same
421
663
  // instance through `routerOnIngest` and feeds it the step and session events, so there is a single settings source.
422
664
  const ingestAbort = new AbortController();
423
665
  const ingest: Ingest | undefined = ctx.routerHost === "v2" ? (() => {
424
666
  const core = createIngest({
425
- settings: () => ingestSettings(cfg, "v2"),
667
+ settings: () => withRoleAgents(ingestSettings(cfg, "v2")),
426
668
  logger,
427
669
  ...(ctx.routerCatalog
428
670
  ? { pricing: createCatalogPricing(ctx.routerCatalog, { logger, cacheKey: ctx.directory, signal: ingestAbort.signal }) }
@@ -437,6 +679,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
437
679
  ? createAttemptRecorder({ host: "v2", config: () => cfg, logger })
438
680
  : undefined;
439
681
  resolveRouting(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger); // v1 + engine != static: log the notice once, at startup (QA-1.1-8)
682
+ // #84 P2.1 (handoff 1): v1 + any roles key: the "roles delegation requires OpenCode v2" notice, once, at startup.
683
+ resolveRolesRouting(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger);
440
684
  const depthTracker = createDepthTracker({
441
685
  async getParent(id) {
442
686
  if (sessionRootMemo.get(id) === true) return null;
@@ -533,6 +777,46 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
533
777
  // subagent tracking, cap enforcement, and narration detection for the
534
778
  // current plugin lifetime (i.e., until OpenCode is restarted).
535
779
  let bypassed = false;
780
+ // #84 P2.1: the v2 adapter's role path reads the bypass state (the router gate does not run while bypassed, S10/P-9).
781
+ (ctx as RouterPluginInput & { routerOnBypassState?: (read: () => boolean) => void }).routerOnBypassState?.(() => bypassed);
782
+ /** QA-P21-1-3: the budget snapshot of a role child as the signals AND the adapter's budget notice read it (guard + read cap). */
783
+ const roleBudgetSnapshot = (childSessionID: string) => captureBudget(childSessionID, sessionStore.readCapReached(childSessionID));
784
+ (ctx as RouterPluginInput & { routerOnBudgetSnapshot?: (read: typeof roleBudgetSnapshot) => void }).routerOnBudgetSnapshot?.(roleBudgetSnapshot);
785
+ /**
786
+ * QA-G-A3-2 (§2.9 E6, R7 REFUSAL_CAP): a role child's call refused where the guard's before-hook never sees it — the v2
787
+ * adapter's role-authority check (thrown in its `execute.before`, before this plugin's hook) and host permission denials (its
788
+ * `execute.after` with a permission error) — counted on the child's guard state like the guard's own refusals, so `denied_cap`
789
+ * stops a child that keeps retrying refused actions. Returns the guard's text for the refusal (its stop, or the advisory
790
+ * banner), or undefined. Role children only; nothing while bypassed or when enforcement is off. Never throws.
791
+ */
792
+ const recordRoleRefusal = (sessionID: string, agent: string | undefined, tool: string, args: unknown): string | undefined => {
793
+ try {
794
+ if (bypassed) return undefined;
795
+ // A child whose first calls are all refused never reached the before-hook that marks it: as there, from its own agent.
796
+ if (rememberRoleSession(sessionID, agent)) sessionStore.markChildSession(sessionID);
797
+ if (roleOfSession(sessionID) === undefined || !sessionStore.isSubagent(sessionID)) return undefined;
798
+ const profile = roleGuardProfileOf(sessionID, agent);
799
+ return guardRefusedCall({
800
+ cfg,
801
+ tier: sessionStore.getTier(sessionID),
802
+ trivial: sessionStore.isTrivial(sessionID),
803
+ cap: sessionStore.getCap(sessionID),
804
+ sessionID,
805
+ tool,
806
+ toolArgs: args,
807
+ store: guardStore,
808
+ env: process.env,
809
+ ...(profile === undefined ? {} : { profile }),
810
+ });
811
+ } catch {
812
+ return undefined; // never break a real session on a guard-internal error
813
+ }
814
+ };
815
+ (ctx as RouterPluginInput & { routerOnRefusal?: (record: typeof recordRoleRefusal) => void }).routerOnRefusal?.(recordRoleRefusal);
816
+ /** #84 P2.1 (handoff 22): the v2 adapter's host-side budget observation of a role child (step limit, context overflow). */
817
+ const hostBudgetOf = (ctx as RouterPluginInput & {
818
+ routerHostBudget?: (childSessionID: string, stepLimit: number | null) => HostBudgetObservation | undefined;
819
+ }).routerHostBudget;
536
820
 
537
821
  warnConfigIssues(cfg, logger);
538
822
 
@@ -557,9 +841,30 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
557
841
  // The catalog comes from `config.providers()` (the call `/router` already makes for the model check, enriched with cost and capabilities
558
842
  // by the v2 adapter), so the doctor does not ask the host for the model list a second time (QA-2.4-3). `prefetched` is that call's result
559
843
  // when the caller already has it.
844
+ /** #84 P2.2: the window of the decision log the roles checks of the cost doctor read. */
845
+ const ADVISOR_ROLE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
846
+ /**
847
+ * #84 P2.2: the extras of the cost doctor's roles checks — the host and, in roles mode with a live engine, the role × tier
848
+ * statistics and the tier dispatch count of the decision log over {@link ADVISOR_ROLE_WINDOW_MS}. Tiers mode and v1 read nothing
849
+ * (`{ host }` only, which no tier check reads); a read failure leaves the statistics out, so those checks stay silent.
850
+ */
851
+ const advisorExtras = async (): Promise<AdvisorExtras> => {
852
+ const host = isV2Host ? "v2" as const : "v1" as const;
853
+ if (rolesNow().size === 0) return { host };
854
+ const live = ingestSettings(cfg, "v2");
855
+ if (live === null) return { host }; // engine static: no decision log
856
+ try {
857
+ const read = await createPersister(live.outcomesDir, nodePersistDeps({ warn: () => undefined })).readRows();
858
+ const since = Date.now() - ADVISOR_ROLE_WINDOW_MS;
859
+ return { host, roleStats: summarizeRoles(null, read.rows, { since, until: null }), tierDispatches: tierDispatchCount(read.rows, since) };
860
+ } catch (error) {
861
+ logger.warn("[router] cost doctor: the role statistics are unavailable", { error: describeError(error) });
862
+ return { host };
863
+ }
864
+ };
560
865
  const gatherAdvisorInputs = async (
561
866
  prefetched?: { raw: unknown } | null,
562
- ): Promise<{ host: HostConfigView | null; catalog: AdvisorCatalogModel[] | null }> => {
867
+ ): Promise<{ host: HostConfigView | null; catalog: AdvisorCatalogModel[] | null; extras: AdvisorExtras }> => {
563
868
  const attempt = async <T>(label: string, call: (() => Promise<T>) | undefined): Promise<T | null> => {
564
869
  if (call === undefined) return null;
565
870
  try {
@@ -569,13 +874,15 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
569
874
  return null;
570
875
  }
571
876
  };
572
- const [agents, providers] = await Promise.all([
877
+ const [agents, providers, extras] = await Promise.all([
573
878
  attempt("host agent list", ctx.routerAgents),
574
879
  prefetched !== undefined ? Promise.resolve(prefetched) : attempt("model catalog", fetchCatalogRaw),
880
+ advisorExtras(),
575
881
  ]);
576
882
  return {
577
883
  host: agents === null ? null : hostConfigFromAgents(agents, lastPrimary),
578
884
  catalog: providers === null ? null : catalogFromProviders(providers.raw),
885
+ extras,
579
886
  };
580
887
  };
581
888
  const advisorNotifier = ctx.routerHost === "v2"
@@ -640,8 +947,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
640
947
  const buildCostDoctorLines = async (prefetched?: { raw: unknown } | null): Promise<string[]> => {
641
948
  const routing = resolveRouting(cfg, "v2");
642
949
  if (!routing.advisor.enabled) return ["Cost doctor: disabled (routing.advisor.enabled is false)."];
643
- const { host, catalog } = await gatherAdvisorInputs(prefetched);
644
- const lines = formatFindings(runAdvisor(cfg, host, catalog, logger), {
950
+ const { host, catalog, extras } = await gatherAdvisorInputs(prefetched);
951
+ const lines = formatFindings(runAdvisor(cfg, host, catalog, logger, extras), {
645
952
  hostKnown: host !== null,
646
953
  catalogKnown: catalog !== null && catalog.length > 0,
647
954
  primaryKnown: lastPrimary !== null,
@@ -701,6 +1008,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
701
1008
  } catch (error) {
702
1009
  logger.warn("[verify] router_verify not registered: the enforcement mode could not be resolved", { error: scrubText(String(error)) });
703
1010
  }
1011
+ // QA-P21-2 nit 3: the role path's deferral check follows it (nothing is deferred without router_verify).
1012
+ (ctx as RouterPluginInput & { routerOnVerifyEnabled?: (read: () => boolean) => void }).routerOnVerifyEnabled?.(() => routerVerifyEnabled);
704
1013
  /**
705
1014
  * 2.4.2 + 2.4.3b: a delegation defers only when `router_verify` exists to verify it later. A
706
1015
  * footer never names a tool this instance did not register; without it the delegation keeps the
@@ -789,6 +1098,194 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
789
1098
  runnerCatalogLoad = load;
790
1099
  return load;
791
1100
  };
1101
+
1102
+ // #84 P2.1 (T2.1.3): the tools of roles mode. The tool map is fixed at plugin start (like `router_verify`): in tiers mode and on
1103
+ // v1 the set is exactly the previous one (router_run and router_request_authority are not registered; router_git_* keep their
1104
+ // directory resolution). Switching to roles mode registers them on the next start.
1105
+ const rolesAtStart = rolesNow().size > 0;
1106
+ const dynamicRolesAtStart = [...rolesNow().values()].some((spec) => spec.authority.mode === "dynamic");
1107
+ /** `router_request_authority` dependencies (P1.6): the role by child session; only the parent of `dispatchOf` is read. */
1108
+ const authorityDeps = {
1109
+ roleOf: (child: string) => roleOfSession(child),
1110
+ roles: () => rolesNow(),
1111
+ dispatchOf: (child: string) => {
1112
+ const parent = lookupDispatch(child)?.parentSessionID;
1113
+ // QA-P21-1-13: `callID: ""` = not attached yet. authority.ts reads only the parent (to drop the request with it);
1114
+ // `markAnnotated` attaches the request to the parent's call in the adapter's execute.after.
1115
+ return typeof parent === "string" && parent !== "" ? { parentSessionID: parent, callID: "" } : undefined;
1116
+ },
1117
+ bindingOf: (child: string) => currentBinding(child, { maxOf: roleMaxOf }),
1118
+ };
1119
+ /** Exact npm forms of a deterministic check's command → the `routing.run` script it names (`npm test`, `npm run <name>`). */
1120
+ const NPM_SCRIPT_RE = /^npm(?:\.cmd)?\s+(?:(test|t)|run(?:-script)?\s+([A-Za-z0-9_][A-Za-z0-9_.:@+-]*))$/;
1121
+ /** The acceptance commands of a role dispatch as `routing.run` names (handoff 13): only exact npm script forms count. */
1122
+ const acceptanceScripts = (prompt: unknown, description: unknown): string[] => {
1123
+ const dod = buildDelegationDoD({
1124
+ prompt: typeof prompt === "string" ? prompt : undefined,
1125
+ description: typeof description === "string" ? description : undefined,
1126
+ });
1127
+ if (dod.kind !== "deterministic") return [];
1128
+ return dod.checks.flatMap((check) => {
1129
+ const match = typeof check.command === "string" ? NPM_SCRIPT_RE.exec(check.command.trim()) : null;
1130
+ return match === null ? [] : [match[1] !== undefined ? "test" : (match[2] as string)];
1131
+ });
1132
+ };
1133
+ /**
1134
+ * QA-P21-2-3: the read-only cap a role dispatch asks for itself — `CAP:N`, or `CAP:none` with a `reason:` line (an unjustified
1135
+ * `CAP:none` is no cap, as for tier dispatches); `null` when it names none (then the child gets no read-only cap).
1136
+ */
1137
+ const roleDispatchCap = (prompt: unknown): Cap | null => {
1138
+ if (typeof prompt !== "string") return null;
1139
+ const parsed = parseCapDirective(prompt);
1140
+ return parsed === "none" && !/\breason:/i.test(prompt) ? null : parsed;
1141
+ };
1142
+ /** Caps of fresh role dispatches, by the parent's call, until the child binds (bounded, oldest out). */
1143
+ const pendingRoleCaps = new Map<string, { agent: string; cap: Cap }>();
1144
+ const rememberPendingRoleCap = (callID: string, agent: string, cap: Cap): void => {
1145
+ pendingRoleCaps.delete(callID);
1146
+ pendingRoleCaps.set(callID, { agent, cap });
1147
+ while (pendingRoleCaps.size > ROLE_STATE_MAX) pendingRoleCaps.delete(pendingRoleCaps.keys().next().value!);
1148
+ };
1149
+ /**
1150
+ * The role child's read-only counter with the dispatch's cap, independent of `subagentTiers` (the session store's producer
1151
+ * registration: no trivial downgrade). The cap is keyed by the role agent's name, which is never a tier.
1152
+ */
1153
+ const registerRoleCap = (child: string, agent: string, cap: Cap): void => {
1154
+ sessionStore.registerProducerSession(child, agent, { ...cfg, tierCaps: { ...(cfg.tierCaps ?? {}), [agent]: cap } } as RouterConfig);
1155
+ };
1156
+ /** A fresh role child's first call: its exact binding names the dispatch's call, whose cap is registered once. */
1157
+ const applyPendingRoleCap = (child: string): void => {
1158
+ if (pendingRoleCaps.size === 0) return;
1159
+ const binding = currentBinding(child, { maxOf: roleMaxOf });
1160
+ const callID = binding?.kind === "exact" ? binding.candidates[0] : undefined;
1161
+ const pending = callID === undefined ? undefined : pendingRoleCaps.get(callID);
1162
+ if (callID === undefined || pending === undefined) return;
1163
+ pendingRoleCaps.delete(callID);
1164
+ registerRoleCap(child, pending.agent, pending.cap);
1165
+ };
1166
+ /**
1167
+ * #84 P3.3 DF2-F1: where the `task` call `callID` is verified. A routed role dispatch (`routedRoleOf`, kept until the adapter's
1168
+ * `execute.after` is done) in its `verifyRoot` — the grant's work root (a resume keeps the child's bound root, QA-P33F1-1-1), else
1169
+ * its canonical session directory (QA-P33F1-1-3); the requested cwd (`requestedVerificationCwd`: the call's `cwd`, else the
1170
+ * block's `cwd:`, the order the dispatch-time detection uses, nit 3) still wins inside it, by P2.3's rule (QA-P33F1-1-2); one
1171
+ * outside it is refused by the gate. Every other dispatch: the explicit cwd, as before (I1).
1172
+ */
1173
+ const verificationScopeOf = (callID: unknown, args: Record<string, unknown> | undefined, dod: { cwd?: string }): VerificationScope =>
1174
+ verificationScope(requestedVerificationCwd(args?.cwd, dod.cwd), typeof callID === "string" ? routedRoleOf(callID)?.verifyRoot : undefined);
1175
+ /** The prompt as the orchestrator wrote it: without the router's nonce line (handoff 18; role dispatches carry no header). */
1176
+ const withoutNonceLine = (prompt: string): string => prompt.replace(/\r?\n?OMR_NONCE=[A-Za-z0-9_-]+\s*$/, "");
1177
+ /**
1178
+ * The parent's `task` call of a routed role dispatch (before it runs): a resume opens a new guard round for the child (its
1179
+ * budget and `budgetExhausted` are per round), and the re-dispatch signal (P1.4, handoff 16) compares the dispatch with the
1180
+ * parent's earlier role dispatches: a failure lands on the previous attempt, addressed by its decision id.
1181
+ */
1182
+ const noteRoleDispatch = (callID: string, parentSessionID: string, args: Record<string, unknown>): void => {
1183
+ const routed = routedRoleOf(callID);
1184
+ if (routed === undefined || routed.parentSessionID !== parentSessionID) return;
1185
+ // QA-G-B-5: the attempt starts now. QA-G-A3-3: the routed tier and `budget=` guard its child — a resume's at once (its new
1186
+ // guard round takes them), a fresh child's once it binds to this call.
1187
+ const guard: RoutedGuardInput = { agent: routed.agent, tier: routed.tier, routeBudget: routed.routeBudget };
1188
+ setBounded(roleAttempts, callID, { ...guard, at: Date.now() });
1189
+ if (routed.resumeID !== null) {
1190
+ // QA-G-A3-2-2 (§2.6): a resume that names no `budget=` keeps the child's previous routed `budget=` (raise-only, applied to
1191
+ // the resume's own tier); one that names a `budget=` takes its own.
1192
+ const previous = routedGuardOf(routed.resumeID);
1193
+ const inherited = routed.routeBudget ?? (previous?.agent === routed.agent ? previous.routeBudget : null);
1194
+ setBounded(roleChildGuards, routed.resumeID, { ...guard, routeBudget: inherited });
1195
+ guardStore.beginDispatch(routed.resumeID);
1196
+ }
1197
+ // QA-P21-2-3: the dispatch's own read-only cap. A resume names its child: registered now; a fresh child when it binds.
1198
+ // QA-P21-3-1: every routed resume starts a new round of the child's read counter (the previous cap kept unless it names one),
1199
+ // so a "continue and finish" resume after a CAP stop does not inherit the exhausted counter.
1200
+ const cap = roleDispatchCap(args.prompt);
1201
+ if (routed.resumeID !== null) {
1202
+ if (!sessionStore.resumeRoleSession(routed.resumeID, cap) && cap !== null) registerRoleCap(routed.resumeID, routed.agent, cap);
1203
+ } else if (cap !== null) {
1204
+ rememberPendingRoleCap(callID, routed.agent, cap);
1205
+ }
1206
+ if (routed.decisionID === null) return; // engine static: no rows
1207
+ const current: DispatchText = {
1208
+ decisionID: routed.decisionID,
1209
+ parentSessionID,
1210
+ childSessionID: routed.resumeID,
1211
+ class: routed.class,
1212
+ role: routed.agent,
1213
+ prompt: withoutNonceLine(typeof args.prompt === "string" ? args.prompt : ""),
1214
+ tier: routed.tier,
1215
+ at: Date.now(),
1216
+ resume: routed.resumeID !== null,
1217
+ };
1218
+ const match = detectRedispatch(current, [...roleDispatchTexts.values()], roleTierOrder(cfg));
1219
+ if (match !== null && match.previous.childSessionID !== null) {
1220
+ ingest?.onSignal?.(match.previous.childSessionID, match.observation, { expectDecisionID: match.previous.decisionID });
1221
+ }
1222
+ roleDispatchTexts.delete(callID);
1223
+ roleDispatchTexts.set(callID, current);
1224
+ while (roleDispatchTexts.size > 200) roleDispatchTexts.delete(roleDispatchTexts.keys().next().value!);
1225
+ };
1226
+ /**
1227
+ * The parent's `task` call of a role child returned (P1.4, handoffs 15-17, 23): the return signal with the REAL guard state
1228
+ * (budget: the guard's enforced stop, or a `NEED MORE: budget` return the guard backs — QA-G-A3-1; `unobserved` when the guard
1229
+ * never tracked the child; authority: the child's recorded request for this call), the router-observed run signal of THIS
1230
+ * attempt (QA-G-B-5), and the dispatch text's end state for later re-dispatch checks.
1231
+ * Verdict rows stay with `onVerdict`.
1232
+ */
1233
+ const observeRoleReturn = (callID: string, args: Record<string, unknown>, output: unknown): void => {
1234
+ const { finalReturnText, childSessionID } = parseTaskResult(output);
1235
+ const spec = childSessionID ? roleOfSession(childSessionID) ?? roleSpecOf(args.subagent_type) : undefined;
1236
+ if (!childSessionID || spec === undefined) return;
1237
+ rememberRoleSession(childSessionID, spec.agent);
1238
+ // QA-P21-1-3: the snapshot includes the read-only CAP state. QA-P21-3-1: a reached read cap is a budget stop only when the
1239
+ // child says so (`NEED MORE`, as the gate's claim check): a `DONE` or an unrelated `ESCALATE` at the cap is not one.
1240
+ const snapshot = roleBudgetSnapshot(childSessionID);
1241
+ const capStop = snapshot.readCapReached === true && parseReturnPrefix(finalReturnText)?.prefix === "need-more";
1242
+ // QA-G-A3-1 (I7): advisory mode (the default) never enforces a stop; a `NEED MORE: budget` return of a tracked child whose
1243
+ // budget or refusals are used up is a budget stop all the same — the gate's rule for honouring the claim (claimHonoured).
1244
+ const claimStop = budgetClaimObserved(finalReturnText, snapshot);
1245
+ // Handoff 22: the guard's stop folded with the host's own (step limit, context overflow), as the v2 adapter observed them.
1246
+ const budgetObserved = foldBudgetObservation(
1247
+ capStop || claimStop ? true : snapshot.tracked ? snapshot.stopped : "unobserved",
1248
+ hostBudgetOf?.(childSessionID, roleAgentSteps(spec)),
1249
+ );
1250
+ const request = requestedAuthority(childSessionID);
1251
+ const authorityObserved = request !== undefined && (!request.annotated || request.callID === callID);
1252
+ const signal = returnSignal({ text: finalReturnText, budgetExhausted: budgetObserved, authorityRequested: authorityObserved });
1253
+ if (signal !== null) ingest?.onSignal?.(childSessionID, signal);
1254
+ const run = runSignal({
1255
+ childSessionID,
1256
+ runs: roleRuns.get(childSessionID) ?? [],
1257
+ // QA-P21-1-7: a child that made any tool call while the router was bypassed has unrecorded edits.
1258
+ editsObserved: !roleBypassedCalls.has(childSessionID),
1259
+ edits: roleEdits.get(childSessionID) ?? [],
1260
+ acceptance: acceptanceScripts(args.prompt, args.description),
1261
+ // QA-G-B-5: only this attempt's runs count (an earlier attempt's run of the same child is that attempt's evidence). An
1262
+ // attempt this instance did not note has no known start: NaN, so it gets no run signal (I6: never unscoped evidence).
1263
+ since: roleAttempts.get(callID)?.at ?? Number.NaN,
1264
+ });
1265
+ if (run !== null) ingest?.onSignal?.(childSessionID, run);
1266
+ const sent = roleDispatchTexts.get(callID);
1267
+ if (sent !== undefined) {
1268
+ roleDispatchTexts.set(callID, {
1269
+ ...sent,
1270
+ childSessionID: sent.childSessionID ?? childSessionID,
1271
+ endedAt: Date.now(),
1272
+ returnPrefix: parseReturnPrefix(finalReturnText)?.prefix ?? null,
1273
+ returned: signal?.kind === "budget" || signal?.kind === "authority" ? signal.kind : null,
1274
+ budgetExhausted: budgetObserved,
1275
+ authorityRequested: authorityObserved,
1276
+ });
1277
+ }
1278
+ };
1279
+ /** Forget a deleted session's role state (as a child, and as the parent of role dispatches). */
1280
+ const forgetRoleSession = (sessionID: string): void => {
1281
+ roleSessions.delete(sessionID);
1282
+ roleRuns.delete(sessionID);
1283
+ roleEdits.delete(sessionID);
1284
+ roleBypassedCalls.delete(sessionID);
1285
+ roleChildGuards.delete(sessionID);
1286
+ roleBudgetPeaks.delete(sessionID);
1287
+ for (const [callID, sent] of roleDispatchTexts) if (sent.parentSessionID === sessionID) roleDispatchTexts.delete(callID);
1288
+ };
792
1289
  return {
793
1290
  // Warnings post to /log fire-and-forget, which loses the message when the
794
1291
  // process is about to exit — `opencode run` and `opencode debug` are short
@@ -811,6 +1308,18 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
811
1308
  await logger.flush();
812
1309
  },
813
1310
  tool: {
1311
+ // QA-G-A2-2: a role session's work root must belong to the repository its dispatch listed the worktrees in (this directory's).
1312
+ ...gitTools(rolesAtStart ? { resolveWorkRoot: resolveWorkRootFor("router_git"), ...(ctx.directory ? { dispatchRepository: ctx.directory } : {}) } : {}),
1313
+ // #84 P2.1 (handoffs 11, 13): roles mode only. `router_run` runs in the bound work root; each run feeds the `run` signal.
1314
+ ...(rolesAtStart ? {
1315
+ router_run: routerRunTool({
1316
+ config: () => resolveRolesRouting(cfg, "v2").run,
1317
+ resolveWorkRoot: resolveWorkRootFor("router_run"),
1318
+ recordRun: (run) => pushBounded(roleRuns, run.sessionID, run),
1319
+ }),
1320
+ } : {}),
1321
+ // #84 P2.1: the authority ladder (P1.6) for dynamic roles (`general`).
1322
+ ...(rolesAtStart && dynamicRolesAtStart ? { router_request_authority: authorityTool(authorityDeps) } : {}),
814
1323
  ...(enableDelegateTool ? { delegate: tool({
815
1324
  description: DELEGATE_TOOL_DESCRIPTION,
816
1325
  args: {
@@ -1120,6 +1629,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1120
1629
  cwd: effectiveCwd,
1121
1630
  dod,
1122
1631
  dispatchedAt: dispatchStart.dispatchedAt,
1632
+ // Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule): router_verify judges the budget at return.
1633
+ budget: captureBudget(producerSid, sessionStore.readCapReached(producerSid)),
1123
1634
  })
1124
1635
  : undefined;
1125
1636
  // QA-2.4-4 / QA-2.4-10: a finish that did not defer falls through to the required gate
@@ -1332,12 +1843,18 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1332
1843
  // R2-2: a failed/timed-out producer may never deliver host confirmation. The ladder's
1333
1844
  // verdict still needs its decision row; the same callback is idempotent after host progress/result.
1334
1845
  attempt.confirmProducer?.();
1335
- ingest?.onVerdict(producerSid, verdictOf(gateRes.verdict));
1846
+ // #84 P3.3 fix 2 (plan §2.6, I6): a grader's verdict is a grader signal of a role dispatch, never a deterministic one.
1847
+ ingest?.onVerdict(producerSid, verdictOf(gateRes.verdict), verdictGraderOf(gateRes.verdict));
1336
1848
  }
1337
1849
 
1338
1850
  const action = nextAction(
1339
1851
  state,
1340
- { pass: gateRes.accepted, outcome: gateRes.verdict.outcome, reasons: gateRes.verdict.reasons },
1852
+ {
1853
+ pass: gateRes.accepted, outcome: gateRes.verdict.outcome, reasons: gateRes.verdict.reasons,
1854
+ // Handoff 25, R7 (I1/I8 exemption: §2.9 E8, the I7 budget-incomplete rule): the structured incomplete flag; absent
1855
+ // when false, so the action is unchanged.
1856
+ ...(isIncompleteVerdict(gateRes.verdict) ? { incomplete: true } : {}),
1857
+ },
1341
1858
  policy,
1342
1859
  sessionAware ? { dispatchPromptChars: args.task.length } : undefined,
1343
1860
  );
@@ -1358,7 +1875,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1358
1875
  false,
1359
1876
  gateRes.verdict.method,
1360
1877
  );
1361
- const note = scrubText(buildForcingNote(gateRes.verdict.reasons));
1878
+ // Handoff 25, R7 (I1/I8 exemption: the I7 budget-incomplete rule): no flag when false, so the note is unchanged.
1879
+ const note = scrubText(buildForcingNote(gateRes.verdict.reasons, isIncompleteVerdict(gateRes.verdict) ? { incomplete: true } : undefined));
1362
1880
  return withDepthBanner(
1363
1881
  `[router status: unmet] The delegated result was not accepted after ` +
1364
1882
  `${state.totalAttempts} attempt(s) across ${state.escalations} escalation(s) ` +
@@ -1477,6 +1995,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1477
1995
  },
1478
1996
 
1479
1997
  "chat.message": async (input: any, output: any) => {
1998
+ // Recorded even while bypassed: the grep redaction in `tool.execute.after` runs regardless of bypass (QA-81-R2-2).
1999
+ if (typeof input?.sessionID === "string" && typeof input?.agent === "string" && Object.hasOwn(cfg.agents ?? {}, input.agent)) {
2000
+ rememberPluginAgentSession(input.sessionID, input.agent);
2001
+ }
1480
2002
  if (bypassed) return;
1481
2003
  // 2.4.3 (QA-2.4-R2-1): the cost doctor's notice is NEVER part of the user's message (the prompt text stays byte for byte what the user
1482
2004
  // typed). It is a synthetic transcript entry, through the same host call the adapter uses for the config-reload and narration notices
@@ -1506,6 +2028,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1506
2028
  }
1507
2029
  const tierNames = Object.keys(getActiveTiers(cfg));
1508
2030
  const sid = input?.sessionID;
2031
+ // v1 `tool.execute.after` carries no agent: plugin-agent sessions are recorded at the top of this hook (QA-81-2).
1509
2032
  try {
1510
2033
  const registration = sessionStore.registerFromChatMessage(
1511
2034
  input,
@@ -1597,7 +2120,17 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1597
2120
  // non-subagent sessions or when enforcement is off (GA-1 preserved).
1598
2121
  // -----------------------------------------------------------------------
1599
2122
  "tool.execute.before": async (input: any, output: any) => {
1600
- if (bypassed) return;
2123
+ // #84 P2.1: a role child's own call names its role agent (the v2 adapter passes the calling agent). Remembered even while
2124
+ // bypassed (the work-root resolver and the authority tool are authority, not routing), and marked a child session: role
2125
+ // agents are subagents, so the guard engages from their first call. Never on v1 / in tiers mode (no role table).
2126
+ if (rememberRoleSession(input?.sessionID, input?.agent)) {
2127
+ sessionStore.markChildSession(input.sessionID);
2128
+ applyPendingRoleCap(input.sessionID); // QA-P21-2-3
2129
+ }
2130
+ if (bypassed) {
2131
+ noteBypassedRoleCall(input?.sessionID); // QA-P21-1-7
2132
+ return;
2133
+ }
1601
2134
  if (input?.tool === "task") {
1602
2135
  const depth = await depthGuard.checkDispatch(input.sessionID);
1603
2136
  if (depth.block) {
@@ -1625,12 +2158,12 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1625
2158
  const prompt = typeof output?.args?.prompt === "string" ? output.args.prompt : undefined;
1626
2159
  const description = typeof output?.args?.description === "string" ? output.args.description : undefined;
1627
2160
  const dod = buildDelegationDoD({ prompt, description });
1628
- const effectiveCwd = typeof output?.args?.cwd === "string" && output.args.cwd.trim() ? output.args.cwd : dod.cwd;
1629
2161
  // 2.4.2b: the directives come from the orchestrator's own prompt, read here before the
1630
2162
  // dispatch header or any repair touches it, and are kept for the after hook. The capture
1631
2163
  // is awaited for at most VERIFY_WAIT (section 1.5-14) and continues in the background.
2164
+ // DF2-F1: a role dispatch's capture is taken in its verification root (never in a refused cwd).
1632
2165
  await startDispatch(changedFileStore, `task:${input.sessionID}:${input.callID}`,
1633
- effectiveCwd,
2166
+ verificationScopeOf(input.callID, output?.args, dod).cwd,
1634
2167
  dod,
1635
2168
  dispatchDirectiveText(prompt, description),
1636
2169
  true);
@@ -1680,7 +2213,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1680
2213
  typeof tier === "string" &&
1681
2214
  Object.prototype.hasOwnProperty.call(getActiveTiers(cfg), tier) &&
1682
2215
  typeof args.prompt === "string" &&
1683
- !args.prompt.startsWith("[router] You are @")
2216
+ !args.prompt.startsWith(DISPATCH_HEADER_PREFIX)
1684
2217
  ) {
1685
2218
  // Resolve from the original dispatch, using the registration rules.
1686
2219
  const parsed = parseCapDirective(args.prompt);
@@ -1688,8 +2221,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1688
2221
  parsed === "none" && !/\breason:/i.test(args.prompt) ? null : parsed;
1689
2222
  const baseline = cfg.tierCaps?.[tier] ?? DEFAULT_TIER_CAPS[tier] ?? 5;
1690
2223
  const cap = override ?? baseline;
1691
- const prompt = buildDispatchHeader({ tier, cap, projectDirectory: ctx.directory }) +
1692
- "\n\n---\n\n" + args.prompt;
2224
+ // Handoff 30, R7 (I1/I8 exemption: T1.5.3a, the header names `root=`): on v2 shadow/advise/enforce the engine stripped the
2225
+ // route line already; its `root=` comes from the router. No root → the header is byte-identical to before.
2226
+ const root = routeLineRoot(args.prompt) ?? (typeof input.callID === "string" ? strippedRouteRoot(input.callID) : undefined);
2227
+ const prompt = buildDispatchHeader({ tier, cap, projectDirectory: ctx.directory, root }) +
2228
+ DISPATCH_HEADER_SEPARATOR + args.prompt;
1693
2229
  args.prompt = prompt;
1694
2230
  if (process.env.MODEL_ROUTER_DISPATCH_DEBUG === "1" && !dispatchDebugLogged) {
1695
2231
  dispatchDebugLogged = true;
@@ -1705,6 +2241,15 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1705
2241
  } catch {
1706
2242
  // Best-effort: malformed args or debug I/O must never break a dispatch.
1707
2243
  }
2244
+ // #84 P2.1: a routed role dispatch of this session (roles mode on v2 only): resume round, re-dispatch signal.
2245
+ if (input?.tool === "task" && typeof input.callID === "string" && typeof input.sessionID === "string"
2246
+ && output?.args && typeof output.args === "object") {
2247
+ try {
2248
+ noteRoleDispatch(input.callID, input.sessionID, output.args as Record<string, unknown>);
2249
+ } catch (error) {
2250
+ logger.warn("[router] roles: the role dispatch could not be noted", { error: describeError(error) });
2251
+ }
2252
+ }
1708
2253
  const sid = input?.sessionID;
1709
2254
  if (!sid || !sessionStore.isSubagent(sid) || typeof input?.tool !== "string") {
1710
2255
  return;
@@ -1714,15 +2259,19 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1714
2259
  sessionStore.touchIfTracked(sid);
1715
2260
  let res;
1716
2261
  try {
2262
+ // Handoff 27: a role child is guarded with its role profile (reader/producer, role budget); tier agents get none.
2263
+ const profile = roleGuardProfileOf(sid, input?.agent);
1717
2264
  res = guardBeforeCall({
1718
2265
  cfg,
1719
2266
  tier: sessionStore.getTier(sid),
1720
2267
  trivial: sessionStore.isTrivial(sid),
2268
+ cap: sessionStore.getCap(sid),
1721
2269
  sessionID: sid,
1722
2270
  tool: input.tool,
1723
2271
  toolArgs: output?.args,
1724
2272
  store: guardStore,
1725
2273
  env: process.env,
2274
+ ...(profile === undefined ? {} : { profile }),
1726
2275
  });
1727
2276
  } catch {
1728
2277
  return; // never break a real session on a guard-internal error
@@ -1746,9 +2295,32 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1746
2295
  // treats them as ground truth rather than advisory system noise.
1747
2296
  // -----------------------------------------------------------------------
1748
2297
  "tool.execute.after": async (input: any, output: any) => {
1749
- if (bypassed) return;
2298
+ if (input?.tool === "grep" && typeof output.output === "string") {
2299
+ const tier = input.agent ?? pluginAgentSessions.get(input.sessionID) ?? sessionStore.getTier(input.sessionID);
2300
+ const definition = tier && getActiveTiers(cfg)[tier];
2301
+ // Every plugin agent is redacted (a denied grep produces no output anyway), readOnly or explicit-permission.
2302
+ const isPlugin = typeof tier === "string" && Object.hasOwn(cfg.agents ?? {}, tier);
2303
+ if ((definition && isReadOnlyTier(tier, definition)) || isPlugin) output.output = filterSensitiveGrep(output.output);
2304
+ }
2305
+ if (bypassed) {
2306
+ noteBypassedRoleCall(input?.sessionID); // QA-P21-1-7
2307
+ return;
2308
+ }
1750
2309
  sessionStore.recordToolCall(input, output);
1751
2310
 
2311
+ // #84 P2.1 (handoffs 13, 15-17, 23): role children only (roles mode on v2). Edit times feed the `run` signal; the parent's
2312
+ // `task` return feeds the return/run signals, read BEFORE any router note is put in front of the child's text.
2313
+ try {
2314
+ if (typeof input?.sessionID === "string" && ROLE_EDIT_TOOLS.has(input?.tool) && roleOfSession(input.sessionID) !== undefined) {
2315
+ pushBounded(roleEdits, input.sessionID, Date.now());
2316
+ }
2317
+ if (input?.tool === "task" && typeof input.callID === "string" && rolesNow().size > 0) {
2318
+ observeRoleReturn(input.callID, input?.args && typeof input.args === "object" ? input.args : {}, output);
2319
+ }
2320
+ } catch (error) {
2321
+ logger.warn("[router] roles: the role return could not be observed", { error: describeError(error) });
2322
+ }
2323
+
1752
2324
  // Best-effort false-refusal observation alongside the existing guard path.
1753
2325
  // Keep scorecards unchanged; counts live in the TTL-managed trajectory.
1754
2326
  try {
@@ -1798,6 +2370,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1798
2370
  readOnly: READ_ONLY_TOOLS.has(input.tool),
1799
2371
  });
1800
2372
  try {
2373
+ const profile = roleGuardProfileOf(sid, input?.agent); // handoff 27, as in the before-hook
1801
2374
  guardAfterCall({
1802
2375
  cfg,
1803
2376
  tier: sessionStore.getTier(sid),
@@ -1806,6 +2379,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1806
2379
  toolArgs: input?.args,
1807
2380
  output,
1808
2381
  store: guardStore,
2382
+ ...(profile === undefined ? {} : { profile }),
1809
2383
  });
1810
2384
  } catch {
1811
2385
  // best-effort: enforcement must never crash a real session
@@ -1836,8 +2410,16 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1836
2410
  prompt: input?.args?.prompt,
1837
2411
  description: input?.args?.description,
1838
2412
  });
1839
- const effectiveCwd = typeof input?.args?.cwd === "string" && input.args.cwd.trim() ? input.args.cwd : dod.cwd;
2413
+ // DF2-F1: a role dispatch is verified in its verification root (capture, change set, checks, deferral); a requested
2414
+ // cwd outside that root is refused by the gate below, never deferred to run there later.
2415
+ const scope = verificationScopeOf(input.callID, input?.args, dod);
2416
+ const cwdSource = requestedVerificationCwdSource(input?.args?.cwd, dod.cwd);
2417
+ const effectiveCwd = scope.cwd;
1840
2418
  const dispatchID = `task:${input.sessionID}:${input.callID}`;
2419
+ // #84 QA-G-B-2-1: a routed role dispatch keeps its child's verification lineage; a resume that CARRIES the acceptance of an
2420
+ // earlier attempt is gated at once (never deferred) on the child's cumulative change set (roleAttemptVerification).
2421
+ const routedRole = typeof input.callID === "string" ? routedRoleOf(input.callID) : undefined;
2422
+ const carriedRole = routedRole?.carried === true && childSessionID !== null && routedRole.resumeID === childSessionID;
1841
2423
  const orchestratorSessionID = typeof input.sessionID === "string" ? input.sessionID : "";
1842
2424
  const taskPrompt = typeof input?.args?.prompt === "string" ? input.args.prompt : undefined;
1843
2425
  const taskDescription = typeof input?.args?.description === "string" ? input.args.description : undefined;
@@ -1848,7 +2430,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1848
2430
  : false;
1849
2431
  // QA-2.4-10: `trivial` as the gate sees it below; a dispatch the gate would skip is not
1850
2432
  // deferred (isDeferred). QA-2.4-2: only a proven root orchestrator defers.
1851
- if (isDeferred(dod, start.directives, trivial) && await isProvenRootCaller(orchestratorSessionID)) {
2433
+ if (!scope.outside && !carriedRole && isDeferred(dod, start.directives, trivial) && await isProvenRootCaller(orchestratorSessionID)) {
1852
2434
  // Section 1.5-16: no gate, no test process; the result goes back now with the
1853
2435
  // footer, which is appended last and never says accepted or verified.
1854
2436
  const finish = await finishDeferred(changedFileStore, {
@@ -1858,8 +2440,12 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1858
2440
  producerTier,
1859
2441
  description: taskDescription?.trim() ? taskDescription : (taskPrompt ?? ""),
1860
2442
  cwd: effectiveCwd,
2443
+ // #84 P3.3 DF2-F1 (fix-1 review nit): router_verify's gate re-checks containment in the role's work root.
2444
+ ...(scope.workRoot !== undefined ? { workRoot: scope.workRoot } : {}),
1861
2445
  dod,
1862
2446
  dispatchedAt: start.dispatchedAt,
2447
+ // Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule): router_verify judges the budget at return.
2448
+ budget: captureBudget(childSessionID ?? "", childSessionID ? sessionStore.readCapReached(childSessionID) : undefined),
1863
2449
  });
1864
2450
  if (finish.deferred) {
1865
2451
  output.output = appendRouterFooter(typeof output.output === "string" ? output.output : "", finish.footer);
@@ -1883,6 +2469,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1883
2469
  gateDeadline.dispose();
1884
2470
  throw error;
1885
2471
  }
2472
+ // #84 QA-G-B-2-1: the role child's lineage — this attempt starts it (its own block) or is judged on everything the child
2473
+ // changed since the attempt that introduced the carried block, against that attempt's reference.
2474
+ if (routedRole !== undefined && childSessionID) verification = roleAttemptVerification(childSessionID, verification, { carried: carriedRole });
2475
+ // #84 P2.1: a role agent follows the return contract (handoff 26; roles mode only).
2476
+ const roleProducer = roleSpecOf(producerTier) !== undefined;
1886
2477
  const artefact = {
1887
2478
  changedFiles: verification.changedFiles,
1888
2479
  changeBaseline: verification.changeBaseline,
@@ -1890,6 +2481,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1890
2481
  declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
1891
2482
  producerSessionID: childSessionID ?? "",
1892
2483
  producerTier,
2484
+ ...(roleProducer ? { returnContract: true } : {}),
2485
+ // Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule; every mode): the guard's budget state when the task
2486
+ // returned, not when the gate runs. Without a stop it judges like the live read it replaces.
2487
+ budget: captureBudget(childSessionID ?? "", childSessionID ? sessionStore.readCapReached(childSessionID) : undefined),
1893
2488
  };
1894
2489
 
1895
2490
  // Read-only / research delegation: an auto-inferred, criteria-only DoD on a
@@ -1915,6 +2510,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1915
2510
  // Keep the native grader unparented on the backend; only depth tracking uses its caller.
1916
2511
  const gateDeps = buildGateDeps(undefined, gateGraderSessions, verification, gateDeadline, false, orchestratorSessionID || null);
1917
2512
  gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
2513
+ // #84 QA-G-B-2-1: a carried acceptance never passes on a testsPass/lintClean that ran no process.
2514
+ if (carriedRole) gateDeps.deterministic.noAffectedUnverifiable = CARRIED_NO_PROCESS_REASON;
1918
2515
  let res;
1919
2516
  try {
1920
2517
  res = await withTimeout(
@@ -1924,7 +2521,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1924
2521
  trivial,
1925
2522
  mode: "modeA",
1926
2523
  // Native task has no cwd argument; the acceptance block can supply it.
1927
- ...(effectiveCwd ? { cwd: effectiveCwd } : {}),
2524
+ ...(scope.requested ? { cwd: scope.requested } : {}),
2525
+ ...(scope.workRoot !== undefined ? { workRoot: scope.workRoot } : {}),
2526
+ ...(scope.refused !== undefined ? { refusedCwd: scope.refused } : {}),
2527
+ // Fix-1 review nit: a refusal names where the cwd came from (the call's `cwd`, else the block's `cwd:`).
2528
+ ...(scope.workRoot !== undefined && cwdSource !== undefined ? { cwdSource } : {}),
1928
2529
  },
1929
2530
  artefact,
1930
2531
  gateDeps,
@@ -1970,12 +2571,22 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1970
2571
  // QA-3.1-2 / QA-3.1-3: concurrent delegations in this tree; a tool that discarded the baseline.
1971
2572
  res = applyDispatchCaveats(res, verification);
1972
2573
  // M6 (2.1.3): a real verdict of a registered child dispatch feeds the outcome store (v2, engine != static).
1973
- if (childSessionID && !res.verdict.skipped) ingest?.onVerdict(childSessionID, verdictOf(res.verdict));
2574
+ // #84 P3.3 fix 2 (plan §2.6, I6): a grader's verdict is a grader signal of a role dispatch, never a deterministic one.
2575
+ if (childSessionID && !res.verdict.skipped) ingest?.onVerdict(childSessionID, verdictOf(res.verdict), verdictGraderOf(res.verdict));
1974
2576
  if (!res.accepted && !res.verdict.skipped) {
1975
2577
  const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
1976
2578
  const li = ladder.indexOf(producerTier);
1977
2579
  const nextTier = res.verdict.outcome !== "unverifiable" && li >= 0 && li < ladder.length - 1 ? ladder[li + 1] : null;
1978
- const note = scrubText(buildForcingNote(res.verdict.reasons, { producerTier, nextTier }));
2580
+ // Handoff 25, R7 (I1/I8 exemption: the I7 budget-incomplete rule): absent when false, so the note is unchanged.
2581
+ const incomplete = isIncompleteVerdict(res.verdict);
2582
+ let note = scrubText(buildForcingNote(res.verdict.reasons, { producerTier, nextTier, ...(incomplete ? { incomplete: true } : {}) }));
2583
+ // P-8 (handoff 39): a role agent is resumed on a higher tier of its range, never re-run on a tier agent.
2584
+ // QA-P21-1-4: only after a FAIL (an unverifiable result keeps the generic line: there is nothing to escalate on).
2585
+ // QA-P21-2-2: the hint promises the raise, and records it for this parent's next resume of the child.
2586
+ const roleHint = roleProducer && !incomplete && res.verdict.outcome === "fail" && childSessionID
2587
+ ? roleEscalationAfterFail(cfg, childSessionID, orchestratorSessionID) : null;
2588
+ const genericNext = "NEXT: address the above and re-run the delegation; do not treat the prior result as complete.";
2589
+ if (roleHint !== null && note.endsWith(genericNext)) note = note.slice(0, note.length - genericNext.length) + scrubText(roleHint);
1979
2590
  output.output =
1980
2591
  typeof output.output === "string"
1981
2592
  ? output.output + "\n\n" + note
@@ -2032,6 +2643,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2032
2643
  if (typeof id === "string") {
2033
2644
  sessionRootMemo.delete(id);
2034
2645
  sessionLookupFailedAt.delete(id);
2646
+ pluginAgentSessions.delete(id);
2035
2647
  sessionStore.unregister(id);
2036
2648
  effortOverrides.clear(id);
2037
2649
  depthTracker.forget(id);
@@ -2039,6 +2651,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2039
2651
  if (key.startsWith(`${id}:`)) depthBanners.delete(key);
2040
2652
  }
2041
2653
  warnedNoCallID.delete(id);
2654
+ forgetRoleSession(id); // #84 P2.1 (the binding and authority registries are evicted by the v2 adapter)
2042
2655
  // 2.4.2b: a deleted orchestrator's handles, tombstones and lineage records go with it.
2043
2656
  // 2.4.5: so do its background requests and late notices; its run in flight is aborted.
2044
2657
  background?.forgetSession(id);
@@ -2075,6 +2688,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2075
2688
  ) {
2076
2689
  try {
2077
2690
  sessionStore.markChildSession(info.id);
2691
+ rememberRoleSession(info.id, info.agent); // #84 P2.1: a role child is known before its first tool call (v2 carries the agent)
2078
2692
  } catch {
2079
2693
  // best-effort: classification must never crash a real session
2080
2694
  }
@@ -2162,6 +2776,17 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2162
2776
  prompt: finalPrompt,
2163
2777
  color: tier.color,
2164
2778
  };
2779
+ if (isReadOnlyTier(name, tier)) {
2780
+ const permission = mergePermissions(readOnlyPermissions(Boolean(opencodeConfig.mcp?.context7)
2781
+ && opencodeConfig.mcp.context7.enabled !== false), opencodeConfig.agent[name]?.permission);
2782
+ agentDef.permission = permission;
2783
+ agentDef.tools = { ...legacyReadOnlyTools(permission), ...opencodeConfig.agent[name]?.tools };
2784
+ } else if (name === "fast" || tier.readOnly === false) {
2785
+ // Opt-out removes OUR policy, not restrictions the user supplied.
2786
+ for (const key of ["permission", "tools"]) {
2787
+ if (opencodeConfig.agent[name]?.[key] !== undefined) agentDef[key] = opencodeConfig.agent[name][key];
2788
+ }
2789
+ }
2165
2790
 
2166
2791
  // Apply variant (thinking/reasoning mode)
2167
2792
  if (tier.variant) {
@@ -2188,10 +2813,71 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2188
2813
  // preset's models. Opt-in: with no map, nothing here runs and the agent
2189
2814
  // record is left exactly as opencode built it. Runs after tier
2190
2815
  // registration so the tier-name collision guard sees the real tiers.
2816
+ // Plugin agents (#81): subagents defined by the router `agents` block.
2817
+ // Model/variant/steps always follow the ACTIVE preset's tier, so this
2818
+ // re-run on /preset rebuilds them. An opencode.json `agent.<name>` entry
2819
+ // wins for the fields it sets (its permission rules go after ours).
2820
+ const context7 = Boolean(opencodeConfig.mcp?.context7) && opencodeConfig.mcp.context7.enabled !== false;
2821
+ const builtNow = new Map<string, Record<string, unknown> | undefined>();
2822
+ const pluginTiers = resolveActiveTiers(cfg);
2823
+ for (const [name, entry] of Object.entries(cfg.agents ?? {})) {
2824
+ const tier = pluginTiers[entry.tier];
2825
+ if (!tier) continue;
2826
+ const existing = opencodeConfig.agent[name];
2827
+ const seed = (opencodeConfig as Record<symbol, unknown>)[HOST_SEED_AGENTS];
2828
+ const fromHostSeed = seed instanceof Set && seed.has(name);
2829
+ if (fromHostSeed && existing?.mode !== undefined && existing.mode !== "subagent") {
2830
+ warnAgentOptionsEffortOnce(`plugin-agent-host-mode:${name}`, `agent ${name} collides with a host built-in agent whose mode is '${String(existing.mode)}'; the router \`agents\` entry is skipped`, logger);
2831
+ continue;
2832
+ }
2833
+ // A definition this hook built on a previous run is not a user entry.
2834
+ const previous = pluginAgentMarker(existing);
2835
+ const hostEntry: Record<string, unknown> | undefined = previous
2836
+ ? previous.hostEntry
2837
+ : existing !== undefined && typeof existing === "object" && existing !== null && !Array.isArray(existing)
2838
+ ? existing as Record<string, unknown>
2839
+ : undefined;
2840
+ let definition = buildPluginAgentDefinition(entry, tier, { context7, host: "v1" });
2841
+ if (hostEntry !== undefined) {
2842
+ definition = mergeHostAgentEntry(definition, hostEntry);
2843
+ warnAgentOptionsEffortOnce(
2844
+ `plugin-agent-host-entry:${name}`,
2845
+ `agent ${name} is defined both in the router \`agents\` block and in ${fromHostSeed ? "a host built-in agent" : "opencode.json"}; ${fromHostSeed ? "the host definition" : "opencode.json"} wins for the fields it sets`,
2846
+ logger,
2847
+ );
2848
+ }
2849
+ opencodeConfig.agent[name] = definition;
2850
+ builtNow.set(name, hostEntry);
2851
+ }
2852
+ // QA-81-8 invariant: after this loop every plugin agent in `opencodeConfig.agent` was built THIS run, or is the host entry
2853
+ // the router replaced (restored), or is absent. Anything built on a previous run and not rebuilt now (removed or invalid) must not linger.
2854
+ // Detection is the symbol marker OR the closure set, so a cloned config (marker lost) is covered too.
2855
+ for (const name of Object.keys(opencodeConfig.agent)) {
2856
+ if (builtNow.has(name)) continue;
2857
+ const marker = pluginAgentMarker(opencodeConfig.agent[name]);
2858
+ if (marker === undefined && !builtPluginAgents.has(name)) continue;
2859
+ const restore = marker ? marker.hostEntry : builtPluginAgents.get(name);
2860
+ if (restore !== undefined) opencodeConfig.agent[name] = restore;
2861
+ else delete opencodeConfig.agent[name];
2862
+ }
2863
+ builtPluginAgents = builtNow;
2864
+
2191
2865
  const subagentOverrides = resolveSubagentOverrides({
2192
2866
  subagentTiers: cfg.subagentTiers,
2193
2867
  tiers: activeTiers,
2194
- existingAgents: opencodeConfig.agent,
2868
+ // The built-in list is the v1 host's; on v2 the setup seed already carries the real host agents.
2869
+ existingAgents: ctx.routerHost === "v2" ? opencodeConfig.agent : { ...V1_HOST_BUILTIN_AGENTS, ...opencodeConfig.agent },
2870
+ pluginAgents: cfg.agents,
2871
+ onSkip: (agentName, reason) =>
2872
+ reason === "missing" && opencodeConfig[DEFER_MISSING_SUBAGENT_NOTICE] === true
2873
+ ? undefined
2874
+ : warnAgentOptionsEffortOnce(
2875
+ `subagent-tiers:${reason}:${agentName}`,
2876
+ reason === "missing"
2877
+ ? `subagentTiers: '${agentName}' is not defined in opencode.json or the router \`agents\` block; skipped (the router never creates it)`
2878
+ : `subagentTiers: '${agentName}' is defined by the router \`agents\` block, whose tier wins; entry skipped`,
2879
+ logger,
2880
+ ),
2195
2881
  });
2196
2882
  for (const [agentName, override] of Object.entries(subagentOverrides)) {
2197
2883
  opencodeConfig.agent[agentName] = mergeSubagentOverride(
@@ -2338,7 +3024,9 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2338
3024
 
2339
3025
  let enfOn = false;
2340
3026
  try { enfOn = resolveEnforcementMode({ config: cfg, env: process.env }).mode !== "off"; } catch {}
2341
- let systemPrompt = assembleSystemPrompt(cfg, orchestratorModel, enfOn);
3027
+ // #84 P2.1 (T2.1.3): v2 roles mode carries the roles protocol (P2.2); "" (v1, tiers mode, no enabled role) keeps today's prompt.
3028
+ const rolesPrompt = isV2Host ? assembleRolesSystemPrompt(cfg, rolesNow(), orchestratorModel, enfOn) : "";
3029
+ let systemPrompt = rolesPrompt !== "" ? rolesPrompt : assembleSystemPrompt(cfg, orchestratorModel, enfOn);
2342
3030
  // A28 (D1): on v1 only, and only with an explicit `routing.roles`, the `R:` line lists those agents as destinations (prose; no model
2343
3031
  // override). Anything else leaves `systemPrompt` the very string it is: the v1 protocol stays byte-identical.
2344
3032
  // Any failure leaves the baseline prompt (QA-2.4-13): the line is an extra, never a reason to lose the protocol.
@@ -2514,7 +3202,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2514
3202
  text = `routing-stats: ${describeError(error)}`;
2515
3203
  }
2516
3204
  } else {
2517
- text = buildRouterOutput(cfg, args, projectDir);
3205
+ // #84 P2.2: `/router` lists the roles in roles mode on v2 (`rolesNow()` is empty in tiers mode and on v1).
3206
+ text = buildRouterOutput(cfg, args, projectDir, rolesNow().size > 0 ? rolesNow().values() : undefined);
2518
3207
  // On the bare status view, surface stale or missing models inline.
2519
3208
  if (sub === "") {
2520
3209
  text += "\n" + routerStatusLines(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger, projectDir).join("\n");