opencode-model-router 2.7.0 → 2.9.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 (111) hide show
  1. package/CHANGELOG.md +583 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/approvals.ts +354 -0
  5. package/src/commands/output.ts +34 -1
  6. package/src/compat/background.ts +2439 -0
  7. package/src/compat/child-session.ts +6 -0
  8. package/src/compat/turn-state.ts +215 -0
  9. package/src/compat/v2-client.ts +136 -17
  10. package/src/compat/v2-hooks.ts +2853 -109
  11. package/src/compat/v2-observations.ts +328 -0
  12. package/src/executor/capacity.ts +362 -0
  13. package/src/executor/child-guards.ts +40 -0
  14. package/src/executor/command.ts +265 -0
  15. package/src/executor/compile/edges.ts +809 -0
  16. package/src/executor/compile/estimate.ts +158 -0
  17. package/src/executor/compile/footprint.ts +829 -0
  18. package/src/executor/compile/index.ts +1080 -0
  19. package/src/executor/compile/parse.ts +1492 -0
  20. package/src/executor/compile/residue.ts +706 -0
  21. package/src/executor/compile/validate.ts +280 -0
  22. package/src/executor/create.ts +672 -0
  23. package/src/executor/expand.ts +551 -0
  24. package/src/executor/git.ts +1214 -0
  25. package/src/executor/host-preamble.ts +17 -0
  26. package/src/executor/instructions.ts +35 -0
  27. package/src/executor/integrate/bisect.ts +73 -0
  28. package/src/executor/integrate/checks.ts +1086 -0
  29. package/src/executor/integrate/land.ts +177 -0
  30. package/src/executor/integrate/phase-suite.ts +407 -0
  31. package/src/executor/integrate/queue.ts +3083 -0
  32. package/src/executor/integrate/run-resolver.ts +19 -0
  33. package/src/executor/launch.ts +652 -0
  34. package/src/executor/ledger.ts +2208 -0
  35. package/src/executor/observations.ts +212 -0
  36. package/src/executor/paths.ts +159 -0
  37. package/src/executor/platform.ts +39 -0
  38. package/src/executor/process-identity.ts +19 -0
  39. package/src/executor/qa-loop.ts +470 -0
  40. package/src/executor/recovery.ts +403 -0
  41. package/src/executor/runtime.ts +6233 -0
  42. package/src/executor/schedule.ts +246 -0
  43. package/src/executor/slots/env.ts +145 -0
  44. package/src/executor/slots/pool.ts +1564 -0
  45. package/src/executor/slots/provision.ts +853 -0
  46. package/src/executor/tool.ts +534 -0
  47. package/src/executor/types.ts +2064 -0
  48. package/src/executor/unattended.ts +488 -0
  49. package/src/guard/store.ts +3 -1
  50. package/src/index.ts +1789 -288
  51. package/src/router/config.ts +823 -26
  52. package/src/router/dispatch-header.ts +95 -2
  53. package/src/router/git-tools.ts +266 -19
  54. package/src/router/leases.ts +1469 -0
  55. package/src/router/logger.ts +44 -32
  56. package/src/router/protocol.ts +44 -10
  57. package/src/router/role-agents.ts +334 -20
  58. package/src/router/roles-config.ts +93 -1
  59. package/src/router/roles.ts +1 -1
  60. package/src/router/run-tools.ts +56 -4
  61. package/src/router/sessions.ts +11 -0
  62. package/src/router/tool-paths.ts +308 -0
  63. package/src/router/work-roots.ts +86 -0
  64. package/src/routing/advisor/findings.ts +25 -5
  65. package/src/routing/classify/index.ts +7 -1
  66. package/src/routing/classify/route-line.ts +96 -5
  67. package/src/routing/classify/rules.ts +11 -0
  68. package/src/routing/classify/types.ts +26 -0
  69. package/src/routing/commands/stats.ts +2 -2
  70. package/src/routing/outcomes/durations.ts +225 -0
  71. package/src/routing/outcomes/index.ts +59 -2
  72. package/src/routing/outcomes/persist.ts +409 -0
  73. package/src/routing/outcomes/signals.ts +17 -0
  74. package/src/routing/outcomes/stats.ts +170 -11
  75. package/src/routing/outcomes/timings.ts +836 -0
  76. package/src/routing/outcomes/types.ts +98 -0
  77. package/src/routing/roles/admission.ts +1028 -0
  78. package/src/routing/roles/approvals.ts +957 -0
  79. package/src/routing/roles/binding.ts +116 -13
  80. package/src/routing/roles/check-placement.ts +112 -0
  81. package/src/routing/roles/git-root.ts +500 -0
  82. package/src/routing/roles/orphans.ts +68 -0
  83. package/src/routing/roles/policy.ts +30 -3
  84. package/src/routing/roles/read-set.ts +325 -0
  85. package/src/routing/roles/work-root.ts +12 -2
  86. package/src/routing/wire/dispatch.ts +697 -30
  87. package/src/routing/wire/hint.ts +56 -8
  88. package/src/routing/wire/working-set.ts +58 -0
  89. package/src/util/linear-trim.ts +32 -0
  90. package/src/v2.ts +94 -49
  91. package/src/verify/batch.ts +7 -2
  92. package/src/verify/branch.ts +141 -0
  93. package/src/verify/canonical-path.ts +35 -0
  94. package/src/verify/deterministic.ts +268 -17
  95. package/src/verify/dispatch.ts +348 -37
  96. package/src/verify/dod.ts +46 -0
  97. package/src/verify/edges.ts +817 -0
  98. package/src/verify/exec.ts +52 -9
  99. package/src/verify/gate.ts +349 -16
  100. package/src/verify/git-top.ts +43 -0
  101. package/src/verify/head.ts +107 -0
  102. package/src/verify/pending.ts +1846 -18
  103. package/src/verify/perimeter.ts +1186 -0
  104. package/src/verify/pin.ts +109 -0
  105. package/src/verify/plan-task.ts +729 -0
  106. package/src/verify/reference.ts +297 -8
  107. package/src/verify/risk.ts +16 -3
  108. package/src/verify/runner.ts +706 -32
  109. package/src/verify/tree.ts +372 -16
  110. package/src/verify/types.ts +66 -2
  111. package/src/verify/wiring.ts +1594 -46
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Plugin } from "@opencode-ai/plugin";
2
+ import { completionIdentity, observeV2 } from "./compat/v2-observations";
2
3
  import type { RouterPluginInput } from "./compat/child-session";
3
4
  import { DEPTH_BANNER, ResumeRejectedError, TASK_VERIFICATION } from "./compat/child-session";
4
5
 
@@ -23,13 +24,13 @@ import {
23
24
  } from "./router/config";
24
25
  import type { RouterConfig, TierConfig, Preset, ModeConfig, EffortLevel } from "./router/config";
25
26
  import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
26
- import { gitTools } from "./router/git-tools";
27
+ import { gitTools, nearestCheckout, type GitRootResolver } from "./router/git-tools";
27
28
  import { isReadOnlyTier, legacyReadOnlyTools, mergePermissions, readOnlyPermissions } from "./router/read-only";
28
29
  import { buildPluginAgentDefinition, mergeHostAgentEntry, pluginAgentMarker } from "./router/plugin-agents";
29
30
  import { filterSensitiveGrep } from "./router/sensitive-paths";
30
31
  import { selectTierPrompt, TOOL_AUTHORITY_CLAUSE } from "./router/prompts";
31
32
  import { stripDelegateInstructions } from "./router/instructions";
32
- import { buildDispatchHeader, DISPATCH_HEADER_PREFIX, DISPATCH_HEADER_SEPARATOR, routeLineRoot } from "./router/dispatch-header";
33
+ import { buildDispatchHeader, DISPATCH_HEADER_PREFIX, DISPATCH_HEADER_SEPARATOR, routeLineRoot, stripDispatchHeader } from "./router/dispatch-header";
33
34
  import { detectFalseRefusal, parseTaskResult as parseRefusalTaskResult } from "./router/false-refusal";
34
35
  import {
35
36
  buildTiersOutput,
@@ -72,12 +73,14 @@ import { routerRunTool, type RunRecord } from "./router/run-tools";
72
73
  import type { WorkRootAnswer } from "./router/git-tools";
73
74
  import { GUARD_CUMULATIVE_MULTIPLIER, roleGuardProfile, type GuardProfile } from "./router/guard-profile";
74
75
  import { currentBinding } from "./routing/roles/binding";
76
+ import { readRoleOrphans } from "./routing/roles/orphans";
75
77
  import { authorityTool, requestedAuthority } from "./routing/roles/authority";
76
78
  import {
77
- CARRIED_NO_PROCESS_REASON, roleAttemptVerification, roleEscalationAfterFail, roleMaxActions, routedRoleOf, strippedRouteRoot,
79
+ CARRIED_NO_PROCESS_REASON, lapsedApprovalReason, pruneLapsedApprovals, roleAttemptVerification, roleEscalationAfterFail, roleMaxActions,
80
+ routedRoleOf, strippedRouteRoot,
78
81
  } from "./routing/wire/dispatch";
79
82
  import { roleTierOrder } from "./routing/engine/ladders";
80
- import { detectRedispatch, returnSignal, runSignal, parseReturnPrefix, type DispatchText } from "./routing/outcomes/signals";
83
+ import { acceptanceScriptsOf, detectRedispatch, returnSignal, runSignal, parseReturnPrefix, type DispatchText } from "./routing/outcomes/signals";
81
84
  import type { IngestSettings } from "./routing/outcomes/ingest";
82
85
  import { captureBudget } from "./guard/enforce";
83
86
  import { budgetClaimObserved, isIncompleteVerdict } from "./verify/checker";
@@ -88,14 +91,25 @@ import { createCatalogPricing, createIngest, ingestSettings } from "./routing/ou
88
91
  import type { Ingest } from "./routing/outcomes/ingest";
89
92
  import { isAnnotationRow, verdictGraderOf, verdictOf, type LogRow } from "./routing/outcomes/types";
90
93
  import { createPersister, nodePersistDeps, summarizeRoles } from "./routing/outcomes";
94
+ import { countUnknownBindings } from "./routing/outcomes/stats";
91
95
  import { roleAgentSteps } from "./router/role-agents";
92
96
  import type { HostBudgetObservation } from "./compat/v2-hooks";
97
+ import { ROUTER_TURN_STATE_ATTACH, TURN_STATE_ROOT, type TurnStateRegistry } from "./compat/turn-state";
98
+ import { ADOPTION_REFUSED, ROUTER_FINISH_ATTACH, type AdoptedRecords, type AdoptionRefused, type FinishApi, type FinishAttach, type FinishInput, type FinishResult, type HeldSink, type InflightJournal, type LeaseGuard, type PersistedRecord, type RestoredDispatch, type RoutedRoleSnapshot } from "./compat/background";
99
+ import type { DispatchDelta } from "./verify/dispatch";
100
+ import { configAsWritten, configuredV2OnlyKeys, setConfigNoticeHost } from "./router/config";
101
+
102
+ /** Phase 2.1: the v2-only config keys already announced as ignored on a v1 host (once per key per process). */
103
+ const warnedV2OnlyKeys = new Set<string>();
93
104
  import { checkpointLine, formatStatsReply, runStatsCommand } from "./routing/commands/stats";
94
- import { buildAnnotateDirectives } from "./routing/commands/annotate-plan";
105
+ import { agentInfosForPlan, buildAnnotateDirectives } from "./routing/commands/annotate-plan";
106
+ import { annotateSteps } from "./routing/engine/plan";
107
+ import { classifyMany as classifyPlanSteps } from "./routing/classify";
95
108
  import { applyV1Roles, hasExplicitV1Roles, v1AgentInfos } from "./routing/commands/v1-roles";
96
109
  import type { HostAgentInfo } from "./routing/engine/types";
97
110
  import { createEngineRuntime } from "./routing/wire/runtime";
98
111
  import type { EngineRuntime } from "./routing/wire/runtime";
112
+ import { forgetWorkingSet, workingSetOf } from "./routing/wire/working-set";
99
113
  import {
100
114
  advisorSettings,
101
115
  catalogFromProviders,
@@ -121,19 +135,24 @@ import {
121
135
  lastStepContext,
122
136
  } from "./router/sessions";
123
137
  import type { Cap, SubagentState } from "./router/sessions";
138
+ import { EXECUTOR_READ_CAP_LINE, type ExecutorChildGuardPort } from "./executor/types";
139
+ import { executorChildRound, publishExecutorChildRound } from "./executor/child-guards";
124
140
  import { createTrajectoryStore } from "./telemetry/trajectory";
125
141
  import { createGuardStore } from "./guard/store";
126
142
  import { createIdleTtlSweeper } from "./router/idle-sweep";
127
143
  import { guardBeforeCall, guardAfterCall, guardRefusedCall, formatScorecard } from "./guard/enforce";
128
- import { mkdirSync, writeFileSync, existsSync } from "node:fs";
129
- import { tmpdir } from "node:os";
144
+ import { mkdirSync, writeFileSync, existsSync, realpathSync, statSync } from "node:fs";
145
+ import { homedir, tmpdir } from "node:os";
130
146
  import { join, isAbsolute } from "node:path";
131
147
  import { access, readFile as fsReadFile } from "node:fs/promises";
132
148
  import { tool } from "@opencode-ai/plugin";
133
149
  import { scrubText } from "./guard/scrub";
134
150
  import { accept, unverifiableGateResult } from "./verify/gate";
135
- import { applyDispatchCaveats, createVerificationWiring, dispatchDirectiveText, extractAssistantText, parseRouterVerifyArgs, type DispatchStart } from "./verify/wiring";
136
- import { appendRouterFooter, buildLateNoticeBlock, buildPendingListBlock } from "./verify/pending";
151
+ import { applyDispatchCaveats, createVerificationWiring, resolvePendingTtlMs, dispatchDirectiveText, extractAssistantText, parseRouterVerifyArgs, type DispatchStart, type HandleReport } from "./verify/wiring";
152
+ import { waitTreeFreeExcept } from "./verify/wiring";
153
+ import { createLeaseSelfExemptions, createPlanTaskVerifier, planTaskGit, planTreeKey } from "./verify/plan-task";
154
+ import { locationOutsideWorkRoots } from "./router/work-roots";
155
+ import { CLAIM_REFRESH_MS, HEAD_LOST_REASON, PENDING_INSTANCES_DIRNAME, PERIMETER_LOST_REASON, type DispatchHeadState, claimPendingSession, createInstanceClaimToken, createPendingFileJournal, foldDormantRecords, refreshPendingClaims, releasePendingClaim, resolvePendingJournalDir, processedKeyOf, appendRouterFooter, buildLateNoticeBlock, buildPendingListBlock, unattributedRisk, type DormantSession, type LateNotice, type PendingEntry, type SettledVerification } from "./verify/pending";
137
156
  import { createDeadline } from "./verify/deterministic";
138
157
  import {
139
158
  DEFAULT_DELEGATE_PROMPT_TIMEOUT_MS,
@@ -150,7 +169,14 @@ import {
150
169
  buildForcingNote,
151
170
  buildAcceptedSuffix,
152
171
  } from "./verify/dispatch";
153
- import { requestedVerificationCwd, requestedVerificationCwdSource, verificationScope, type VerificationScope } from "./routing/roles/work-root";
172
+ import { canonicalAuthorityPath, captureRootOf, insideWorkRoot, requestedVerificationCwd, requestedVerificationCwdSource, verificationScope, type VerificationScope } from "./routing/roles/work-root";
173
+ import { resolveCheckPlacements } from "./routing/roles/check-placement";
174
+ // Static, not `await import`: dynamic imports made a bundle split src/router/config.ts into a chunk where its tiers.json
175
+ // lookup fails (the e2e child bundle). Each module below is used only inside functions.
176
+ import { createAdmission, type AdmissionConfig, type AdmissionService } from "./routing/roles/admission";
177
+ import * as gitRoot from "./routing/roles/git-root";
178
+ import * as approvalsCommands from "./commands/approvals";
179
+ import { createRepoProbe, displaySafe, readSetEligible, readSetPredicate } from "./routing/roles/read-set";
154
180
  import { newLadderState, recordAttempt, nextAction, advance, buildEscalatePolicy, formatLadderScorecard, startCostRatio } from "./escalate/ladder";
155
181
  import { createCatalogLookup, planFirstAttempt, planNextAttempt } from "./escalate/resume";
156
182
  import type { AttemptPlan, CatalogLookup } from "./escalate/resume";
@@ -159,6 +185,10 @@ import type { AttemptRecorder, DelegationFacts } from "./escalate/attempt-record
159
185
  import { createDepthTracker, DEPTH_LOOKUP_RETRY_MS } from "./router/depth";
160
186
  import { createDepthGuard } from "./router/depth-guard";
161
187
  import { applyEffortOverride, createEffortOverrideStore } from "./escalate/effort-override";
188
+ import { createExecutorAccess, lateRuntime, type ExecutorAccess, type CreateExecutorOptions } from "./executor/create";
189
+ import { executorPlatformSupported, warnExecutorPlatformOnce } from "./executor/platform";
190
+ import { createRouterPlanTool } from "./executor/tool";
191
+ import { createPlanCommand, parsePlanCommand } from "./executor/command";
162
192
 
163
193
  // ---------------------------------------------------------------------------
164
194
  // Re-exports — type-only re-exports for IDE/test consumers.
@@ -183,6 +213,16 @@ function describeError(error: unknown): string {
183
213
  }
184
214
  }
185
215
 
216
+ /**
217
+ * Cross-repo P2b.7 (OD1=B, v2 only): a tier dispatch honours no per-check `cwd=`. The first check of the DoD that sets one (0-based
218
+ * index) is the refusal the gate reports (`why: "tier"`, nothing runs); undefined when none does. `scope=` alone is ignored.
219
+ */
220
+ function tierCheckCwdRefusal(dod: Parameters<typeof resolveCheckPlacements>[0]): NonNullable<Parameters<typeof accept>[0]["refusedCheck"]> | undefined {
221
+ const index = dod.checks.findIndex((check) => check.cwd !== undefined);
222
+ const check = index < 0 ? undefined : dod.checks[index];
223
+ return check?.cwd === undefined ? undefined : { index, kind: check.kind, text: check.cwd, why: "tier" };
224
+ }
225
+
186
226
  /**
187
227
  * #84 P2.2 (advisor `tierDispatches`): dispatch rows WITHOUT a role at or after `since` — non-annotation `dispatch` decision rows,
188
228
  * the first row per decision id (as `summarizeRoles` keeps them), whose row names no role and whose chosen key is not a role's.
@@ -247,7 +287,7 @@ function saveEnforcementMode(mode: "off" | "advisory" | "enforced"): void {
247
287
  * `/router` dispatch. Decides and persists here; rendering lives in
248
288
  * src/commands/output.ts.
249
289
  */
250
- function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string, roles?: Iterable<RoleSpec>): string {
290
+ function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string, roles?: Iterable<RoleSpec>, approvals = false, plan = false): string {
251
291
  const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
252
292
  const sub = (tokens[0] ?? "").toLowerCase();
253
293
 
@@ -280,10 +320,14 @@ function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string,
280
320
  resolveEnforcementMode({ config: cfg, env: process.env }).mode,
281
321
  // `/router stats` is listed only for a config that has a `routing` block: without one `/router` is what it was (QA-2.4-3).
282
322
  // #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 }) },
323
+ // Cross-repo P4.7: `/router approve|repos|revoke`, only where they run (SD-P4-10); otherwise the help is what it was.
324
+ { stats: cfg.routing !== undefined, ...(roles === undefined ? {} : { roles }), ...(approvals ? { approvals: true } : {}), ...(plan ? { plan: true } : {}) },
284
325
  );
285
326
  }
286
327
 
328
+ /** Cross-repo P4.7: the `/router` subcommands of `commands/approvals.ts` (checked before that module is used). */
329
+ const APPROVAL_SUBCOMMANDS: ReadonlySet<string> = new Set(["approve", "repos", "revoke"]);
330
+
287
331
  /** `/budget` dispatch. Persists the switch, then renders. */
288
332
  function buildBudgetOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
289
333
  const modes = cfg.modes;
@@ -354,6 +398,71 @@ const V1_HOST_BUILTIN_AGENTS: Record<string, { mode: string }> = {
354
398
  const SESSION_ROOT_MEMO_MAX = 500;
355
399
  const SESSION_LOOKUP_RETRY_MS = DEPTH_LOOKUP_RETRY_MS;
356
400
 
401
+ /** Phase 1.2 (v2 only): bounds of the late-notice buffer behind the `late` turn-state provider. */
402
+ const LATE_BUFFER_PER_SESSION = 50;
403
+ const LATE_BUFFER_SESSIONS = 100;
404
+
405
+ /**
406
+ * Late notices retained per session until `router_verify` answers their handle, so a request that fails after the
407
+ * transform read them does not lose them (the v1 path delivers them once). First-seen order; a repeated handle replaces
408
+ * its notice in place; the oldest notice and the least recently used session go at the bounds.
409
+ */
410
+ interface LateBuffer {
411
+ add(sessionID: string, notices: readonly LateNotice[]): void;
412
+ list(sessionID: string): LateNotice[];
413
+ release(sessionID: string, handles: readonly string[]): void;
414
+ /** Marks the session as most recently used (a render read its notices). */
415
+ touch(sessionID: string): void;
416
+ /** Drops the session's buffer (`session.deleted`). */
417
+ forget(sessionID: string): void;
418
+ }
419
+
420
+ function createLateBuffer(): LateBuffer {
421
+ const sessions = new Map<string, Map<string, LateNotice>>();
422
+ return {
423
+ add(sessionID, notices) {
424
+ if (notices.length === 0) return;
425
+ const buffer = sessions.get(sessionID) ?? new Map<string, LateNotice>();
426
+ sessions.delete(sessionID);
427
+ sessions.set(sessionID, buffer);
428
+ for (const notice of notices) buffer.set(notice.handle, notice);
429
+ while (buffer.size > LATE_BUFFER_PER_SESSION) buffer.delete(buffer.keys().next().value!);
430
+ while (sessions.size > LATE_BUFFER_SESSIONS) sessions.delete(sessions.keys().next().value!);
431
+ },
432
+ list(sessionID) {
433
+ return [...(sessions.get(sessionID)?.values() ?? [])];
434
+ },
435
+ release(sessionID, handles) {
436
+ const buffer = sessions.get(sessionID);
437
+ if (buffer === undefined) return;
438
+ for (const handle of handles) buffer.delete(handle);
439
+ if (buffer.size === 0) sessions.delete(sessionID);
440
+ },
441
+ touch(sessionID) {
442
+ const buffer = sessions.get(sessionID);
443
+ if (buffer === undefined) return;
444
+ sessions.delete(sessionID);
445
+ sessions.set(sessionID, buffer);
446
+ },
447
+ forget(sessionID) {
448
+ sessions.delete(sessionID);
449
+ },
450
+ };
451
+ }
452
+
453
+ /**
454
+ * The handles a router_verify report answers: a verdict, an unknown input, an expired handle. A run that outlived the call
455
+ * ("elsewhere") and a held background result ("held", QA-2.1-9: its own gate posts the verdict) have no verdict yet.
456
+ */
457
+ function answeredHandles(items: readonly HandleReport[]): string[] {
458
+ const handles: string[] = [];
459
+ for (const item of items) {
460
+ if (item.kind === "verdict" || item.kind === "expired") handles.push(item.handle);
461
+ else if (item.kind === "unknown") handles.push(item.input);
462
+ }
463
+ return handles;
464
+ }
465
+
357
466
  const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
358
467
  // Project directory this plugin instance serves. Hosts that run several
359
468
  // projects in one process (OpenCode v2) may also move process.cwd() away from
@@ -507,6 +616,34 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
507
616
  // every role branch below is skipped there and both stay byte-identical (§2.7, I1, I8).
508
617
  // -------------------------------------------------------------------------
509
618
  const isV2Host = ctx.routerHost === "v2";
619
+ // Phase 5.1 D1: the runtime is resolved at each call, after the adapter's synchronous executor factory runs.
620
+ const executorInput = isV2Host ? ctx as RouterPluginInput & {
621
+ routerExecutor?: ExecutorAccess;
622
+ routerOnPlanAnnotate?: (port: NonNullable<CreateExecutorOptions["annotate"]>) => void;
623
+ } : undefined;
624
+ // G-16: the plan executor is Windows-only; elsewhere no executor access exists, so router_plan and /plan are not built.
625
+ const executorPlatform = isV2Host && executorPlatformSupported();
626
+ const absentExecutor = executorPlatform ? createExecutorAccess() : undefined;
627
+ const executorAccess: ExecutorAccess | undefined = absentExecutor === undefined ? undefined : {
628
+ runtime: () => (executorInput?.routerExecutor ?? absentExecutor).runtime(),
629
+ unavailable: () => (executorInput?.routerExecutor ?? absentExecutor).unavailable(),
630
+ set: (runtime) => (executorInput?.routerExecutor ?? absentExecutor).set(runtime),
631
+ clear: (reason) => (executorInput?.routerExecutor ?? absentExecutor).clear(reason),
632
+ };
633
+ const executorRuntime = executorAccess === undefined ? undefined : lateRuntime(executorAccess);
634
+ /**
635
+ * Cross-repo P2e.6 (OD-P2e-2): a dispatch runs the full scope when the host is OpenCode v2 and the effective testScope is
636
+ * "full"; the deferred finish then never treats an empty change set as nothing to run. Always false on v1. Never throws (an
637
+ * unreadable verify block is not full).
638
+ */
639
+ const fullScopeOf = (cfg: Parameters<typeof resolveVerifyBudget>[0]): boolean => {
640
+ if (!isV2Host) return false;
641
+ try {
642
+ return resolveVerifyBudget(cfg).testScope === "full";
643
+ } catch {
644
+ return false;
645
+ }
646
+ };
510
647
  /**
511
648
  * 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
649
  * start and its role agents only then (the v2 adapter logs "restart OpenCode" when the config switches to roles at runtime).
@@ -568,7 +705,160 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
568
705
  const answer = resolveWorkRoot(sessionID);
569
706
  if (!answer.role) return answer;
570
707
  const grant = currentBinding(sessionID, { maxOf: roleMaxOf })?.grant;
571
- return grant !== undefined && grant.actions.has(action) ? answer : { role: true, root: null };
708
+ if (grant === undefined || !grant.actions.has(action)) return { role: true, root: null };
709
+ // Phase 4 QA (m2): a binding backed by an approval holds only while the approval applies (store read, no git). The tools
710
+ // report a resolver's throw as their error, nothing runs.
711
+ const approval = grant.location?.approval;
712
+ if (approval !== undefined && answer.root !== null) {
713
+ const lapsed = lapsedApprovalReason(approval, resolveRolesRouting(cfg, "v2").repoApprovalDays);
714
+ if (lapsed !== undefined) throw new Error(`refused: ${lapsed}`);
715
+ }
716
+ // Cross-repo (P1.5): a binding that carries its repository makes it the repository `router_git_*` expects.
717
+ const repository = grant.location?.repository;
718
+ return repository !== undefined && answer.root !== null ? { ...answer, repository } : answer;
719
+ };
720
+ /**
721
+ * Cross-repo (P1.9, v2 only): the provenance line of a role's `read`, `glob` or `grep` whose target (the file, or the search root)
722
+ * canonicalises outside the session's work root but inside its read set (`routing/roles/read-set.ts`: the orchestrator's working
723
+ * set and the repositories below `routing.repoParents`). Undefined for a non-role session, an unbound or rootless one, a target in
724
+ * the work root, a target outside the read set, and whenever cross-repo is not in use (no parents and no working set: I9).
725
+ */
726
+ const repoProbe = createRepoProbe();
727
+ /** The read set R (P1.5) of the role dispatches of `orchestrator`: its working set plus `routing.repoParents`. Undefined when R adds nothing. */
728
+ const readSetMemberOf = (orchestrator: string | undefined): ReturnType<typeof readSetPredicate> => {
729
+ const routing = resolveRolesRouting(cfg, "v2");
730
+ const workingSet = orchestrator === undefined ? [] : workingSetOf(orchestrator);
731
+ return readSetPredicate({ parents: routing.repoParents, depth: routing.repoDepth, exclude: routing.repoExclude }, workingSet, repoProbe);
732
+ };
733
+ /**
734
+ * Cross-repo P2a.3 (v2 only): R as a yes/no test on a canonical absolute path, for the role dispatch `routed` (its orchestrator's
735
+ * working set). Undefined when no R applies.
736
+ */
737
+ const roleReadSetFor = (routed: { readonly parentSessionID: string }): ((absPath: string) => boolean) | undefined => {
738
+ if (ctx.routerHost !== "v2") return undefined;
739
+ const member = readSetMemberOf(routed.parentSessionID === "" ? undefined : routed.parentSessionID);
740
+ return member === undefined ? undefined : (absPath) => member(absPath) !== undefined;
741
+ };
742
+ /** F11: the orchestrator that dispatched role session `sid`: its dispatch record, else the session's parent (as the v2 adapter's readSetOf). */
743
+ const orchestratorOf = async (sid: string): Promise<string | undefined> => {
744
+ const recorded = lookupDispatch(sid)?.parentSessionID ?? undefined;
745
+ if (recorded !== undefined && recorded !== "") return recorded;
746
+ const res = await ctx.client.session.get({ path: { id: sid } });
747
+ const parentID = res?.data?.parentID;
748
+ return typeof parentID === "string" && parentID !== "" ? parentID : undefined;
749
+ };
750
+ /**
751
+ * Cross-repo P4.7 (SD-P4-10, S1): whether `/router approve|repos|revoke` run for the session `sessionID`. All of: the v2 host,
752
+ * roles mode (`rolesNow()` non-empty), `routing.repoParents` non-empty, and a top-level session typed in by the human: not a
753
+ * role session, not a known child (a dispatch record), and the host reports it without a parent. A failed lookup refuses.
754
+ */
755
+ const approvalsCommandsAvailable = async (sessionID: unknown): Promise<boolean> => {
756
+ if (ctx.routerHost !== "v2" || rolesNow().size === 0) return false;
757
+ if (resolveRolesRouting(cfg, "v2").repoParents.length === 0) return false;
758
+ if (typeof sessionID !== "string" || sessionID === "") return false;
759
+ if (roleOfSession(sessionID) !== undefined || lookupDispatch(sessionID) !== undefined) return false;
760
+ try {
761
+ const res = await ctx.client.session.get({ path: { id: sessionID } });
762
+ const data = res?.data;
763
+ if (data === undefined || data === null || typeof data !== "object") return false;
764
+ const parentID: unknown = Reflect.get(data, "parentID");
765
+ return !(typeof parentID === "string" && parentID !== "");
766
+ } catch {
767
+ return false;
768
+ }
769
+ };
770
+ /**
771
+ * Cross-repo 3b.4 (F10): one admission per resolved `{ repoParents, repoDepth, repoExclude }` for `router_git` `root` (it caches its
772
+ * git results for 5 s). Created on first use.
773
+ */
774
+ type GitRootAdmission = Pick<AdmissionService, "admit" | "find">;
775
+ let gitRootAdmissionMemo: { readonly key: string; readonly service: GitRootAdmission } | undefined;
776
+ const gitRootAdmissionFor = async (config: AdmissionConfig): Promise<GitRootAdmission> => {
777
+ const key = JSON.stringify([config.parents, config.depth, config.exclude, config.approvalDays ?? null]);
778
+ if (gitRootAdmissionMemo !== undefined && gitRootAdmissionMemo.key === key) return gitRootAdmissionMemo.service;
779
+ const service = createAdmission(config);
780
+ gitRootAdmissionMemo = { key, service };
781
+ return service;
782
+ };
783
+ /**
784
+ * Cross-repo 3b.4 (OpenCode v2, roles mode, `routing.repoParents` at start; SD-3b-1): the `root` resolver of `router_git_*`. Step 1
785
+ * here, no filesystem call and no spawn: a role session (D21), an exact binding with a work root and `router_git` in the grant (I9,
786
+ * F12), a local read action in the grant (SD-3b-5), parents still configured. Steps 2–10: `routing/roles/git-root.ts`.
787
+ */
788
+ const resolveGitRootFor: GitRootResolver = async (value, { sessionID, signal, deadlineAt }) => {
789
+ if (roleOfSession(sessionID) === undefined) return { ok: false, reason: gitRoot.GIT_ROOT_ROLE_ONLY };
790
+ const binding = currentBinding(sessionID, { maxOf: roleMaxOf });
791
+ const grant = binding?.kind === "exact" ? binding.grant : undefined;
792
+ const workRoot = grant?.workRoot;
793
+ if (grant === undefined || workRoot === null || workRoot === undefined || workRoot === "" || !grant.actions.has("router_git")) {
794
+ return { ok: false, reason: gitRoot.GIT_ROOT_NO_WORK_ROOT };
795
+ }
796
+ if (!grant.actions.has("read") && !grant.actions.has("glob") && !grant.actions.has("grep")) {
797
+ return { ok: false, reason: gitRoot.gitRootNeedsRead([...grant.actions].sort()) };
798
+ }
799
+ const routing = resolveRolesRouting(cfg, "v2");
800
+ if (routing.repoParents.length === 0) return { ok: false, reason: gitRoot.GIT_ROOT_NO_PARENTS };
801
+ // Phase 4 QA (m2): a binding backed by an approval that no longer applies (revoked, expired) inspects nothing (store read, no git).
802
+ const approval = grant.location?.approval;
803
+ const lapsed = approval === undefined ? undefined : lapsedApprovalReason(approval, routing.repoApprovalDays);
804
+ if (lapsed !== undefined) return { ok: false, reason: lapsed };
805
+ // QA round 1 (Phase 3 lot 1, F5): the session lookup is bounded by the call's deadline and signal (SD-3b-8).
806
+ const asked = await gitRoot.gitRootBounded(() => orchestratorOf(sessionID), { ...(signal === undefined ? {} : { signal }), deadlineAt });
807
+ if ("stop" in asked && asked.stop !== "failed") return { ok: false, reason: gitRoot.gitRootStopReason(value, asked.stop) };
808
+ // A failed lookup: no working set, R narrows to the parents (fail closed).
809
+ const orchestrator = "value" in asked ? asked.value : undefined;
810
+ // Phase 4 QA (M1): as for a dispatch (`crossRepoOf`), an entry whose approval lapsed is dropped before it can admit by rule 2;
811
+ // the drop reaches every working set, so the read set below shrinks with it.
812
+ const workingSet = (orchestrator === undefined ? [] : pruneLapsedApprovals(workingSetOf(orchestrator), routing.repoApprovalDays))
813
+ .map((location) => location.worktree);
814
+ const member = readSetMemberOf(orchestrator);
815
+ const admissionConfig = {
816
+ parents: routing.repoParents,
817
+ depth: routing.repoDepth,
818
+ exclude: routing.repoExclude,
819
+ approvalDays: routing.repoApprovalDays,
820
+ };
821
+ const known = [ctx.directory, ...(grant.location?.repository === undefined ? [] : [grant.location.repository]), ...workingSet];
822
+ return gitRoot.resolveGitRoot(value, { workRoot, parents: routing.repoParents, workingSet }, {
823
+ realpath: (path) => realpathSync.native(path),
824
+ isDirectory: (path) => statSync(path).isDirectory(),
825
+ nearestCheckout,
826
+ inReadSet: (path) => member !== undefined && member(path) !== undefined,
827
+ // Created on first use only: a text refusal never creates an admission.
828
+ admission: {
829
+ // Phase 4 QA (M1): the session repository is named, whatever order `known` reaches admission in.
830
+ admit: async (root, knownRepositories) => (await gitRootAdmissionFor(admissionConfig)).admit(root, knownRepositories, ctx.directory),
831
+ // QA round 1 (Phase 3 lot 1, F4): the resolver's `eligible` (the text gate and R) reaches the lookup.
832
+ find: async (name, opts) => (await gitRootAdmissionFor(admissionConfig)).find(name, opts),
833
+ },
834
+ known,
835
+ platform: process.platform,
836
+ ...(signal === undefined ? {} : { signal }),
837
+ deadlineAt,
838
+ });
839
+ };
840
+ const readProvenanceLine = async (input: any): Promise<string | undefined> => {
841
+ const sid: unknown = input?.sessionID;
842
+ if (ctx.routerHost !== "v2" || typeof sid !== "string" || !["read", "glob", "grep"].includes(input?.tool)) return undefined;
843
+ if (roleOfSession(sid) === undefined) return undefined;
844
+ const binding = currentBinding(sid, { maxOf: roleMaxOf });
845
+ const workRoot = binding?.kind === "exact" ? binding.grant.workRoot : null;
846
+ if (workRoot === null || workRoot === undefined) return undefined;
847
+ const args: Record<string, unknown> = input?.args && typeof input.args === "object" ? input.args : {};
848
+ const named = input.tool === "read" ? [args.filePath, args.path, args.file_path] : [args.path];
849
+ const target = named.find((value): value is string => typeof value === "string" && value !== "");
850
+ // No path (the session directory) or a relative one: the decision (v2-hooks `roleAuthorityDecision`) never lets it reach the
851
+ // read set (QA-1 F1) — it ran inside the work root or was refused — so there is no line. A fully qualified path canonicalises
852
+ // the same whatever the base, as in the decision; `.git` and below never reach R (F7).
853
+ if (target === undefined) return undefined;
854
+ const canonical = canonicalAuthorityPath(target, workRoot);
855
+ if (canonical === undefined || insideWorkRoot(canonical, workRoot) || !readSetEligible(target, canonical)) return undefined;
856
+ // The orchestrator that dispatched this role: its dispatch record, else the session's parent (as the v2 adapter's readSetOf).
857
+ const orchestrator = await orchestratorOf(sid);
858
+ const member = readSetMemberOf(orchestrator)?.(canonical);
859
+ if (member === undefined) return undefined;
860
+ // QA-1 F2: the name, branch and path come from the filesystem: display-safe.
861
+ return `[router: read from ${displaySafe(member.name)} (${displaySafe(member.branch ?? "detached")}) at ${displaySafe(member.repository)} — read-only in this dispatch]`;
572
862
  };
573
863
  /** 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
864
  interface RoutedGuardInput { readonly agent: string; readonly tier: string; readonly routeBudget: number | null }
@@ -608,6 +898,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
608
898
  * its registered fallback model, P-1) and the bound dispatch budget.
609
899
  */
610
900
  const roleGuardProfileOf = (sessionID: unknown, agent: unknown): GuardProfile | undefined => {
901
+ if (typeof sessionID === "string") consumeExecutorChildRound(sessionID);
611
902
  const spec = roleSpecOf(agent) ?? roleOfSession(sessionID);
612
903
  if (spec === undefined || typeof sessionID !== "string") return undefined;
613
904
  const routed = routedGuardOf(sessionID);
@@ -616,8 +907,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
616
907
  profile = roleGuardProfile(spec, routed.tier, routed.routeBudget);
617
908
  } else {
618
909
  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);
910
+ const binding = currentBinding(sessionID, { maxOf: roleMaxOf });
911
+ const tier = binding?.plan !== undefined && binding.tier !== undefined ? binding.tier
912
+ : record?.agent === spec.agent && typeof record.tier === "string" && record.tier !== "" ? record.tier : spec.tierRange.floor;
913
+ profile = roleGuardProfile(spec, tier, binding?.budget ?? null);
621
914
  }
622
915
  // 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
916
  // (a later round with a smaller budget never shrinks it below what earlier rounds were allowed).
@@ -681,6 +974,31 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
681
974
  resolveRouting(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger); // v1 + engine != static: log the notice once, at startup (QA-1.1-8)
682
975
  // #84 P2.1 (handoff 1): v1 + any roles key: the "roles delegation requires OpenCode v2" notice, once, at startup.
683
976
  resolveRolesRouting(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger);
977
+ // QA-4.1-9: on v1 the executor validation issues are not logged; the notice below names the keys.
978
+ setConfigNoticeHost(isV2Host ? "v2" : "v1");
979
+ if (!isV2Host) {
980
+ // Phase 2.1: the background and lease keys exist on v2 only; a v1 host does nothing with them. QA-2.1-12 (AGENTS.md: at most
981
+ // one notice per process for a v2-only feature): one notice names every configured key, and no later instance logs another.
982
+ // QA-4.1-9: the keys as written (the merged layers), so a value validation dropped is still named.
983
+ const keys = [...configuredV2OnlyKeys(configAsWritten(cfg))];
984
+ if (keys.length > 0 && warnedV2OnlyKeys.size === 0) {
985
+ for (const key of keys) warnedV2OnlyKeys.add(key);
986
+ // QA-2.1-32: the notice names the features actually configured (leases alone are not "background dispatch").
987
+ // QA-4.1-19: a block that is not an object is named whole (`routing.executor`).
988
+ const names = (block: string): boolean => keys.some((key) => key === `routing.${block}` || key.startsWith(`routing.${block}.`));
989
+ const background = names("background");
990
+ const leases = names("leases");
991
+ const executor = names("executor");
992
+ const orphans = names("orphans");
993
+ const features = [background ? "background dispatch" : "", leases ? "leases" : "", executor ? "the plan executor" : "", orphans ? "orphan cleanup" : ""].filter((f) => f !== "");
994
+ const subject = features.length === 0
995
+ ? "background dispatch requires"
996
+ : features.length === 1
997
+ ? `${features[0]} ${leases && !background && !executor && !orphans ? "require" : "requires"}`
998
+ : `${features.slice(0, -1).join(", ")} and ${features[features.length - 1]} require`;
999
+ logger.warn(`[router] ${subject} OpenCode v2; ignored: ${keys.join(", ")}`);
1000
+ }
1001
+ }
684
1002
  const depthTracker = createDepthTracker({
685
1003
  async getParent(id) {
686
1004
  if (sessionRootMemo.get(id) === true) return null;
@@ -704,6 +1022,36 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
704
1022
  }).mode,
705
1023
  logger: routerWarn,
706
1024
  });
1025
+ // State-changing executor actions require depth 0, even for an exactly bound plan child.
1026
+ const planRootCallerAllowed = async (sessionID: unknown): Promise<boolean> => {
1027
+ if (!isV2Host || typeof sessionID !== "string" || sessionID === "") return false;
1028
+ try {
1029
+ return await depthTracker.depthOf(sessionID) === 0;
1030
+ } catch {
1031
+ return false;
1032
+ }
1033
+ };
1034
+ const planReadCallerAllowed = (sessionID: unknown, planId: unknown): boolean => {
1035
+ if (!isV2Host || typeof sessionID !== "string" || sessionID === "" || typeof planId !== "string") return false;
1036
+ try {
1037
+ const binding = currentBinding(sessionID, { maxOf: roleMaxOf });
1038
+ return binding?.kind === "exact" && binding.plan !== undefined && binding.plan.planId === planId.trim();
1039
+ } catch {
1040
+ return false;
1041
+ }
1042
+ };
1043
+ // Only this allowlist is read-only; new or unknown actions remain root-only. `/plan inbox` parses as status.
1044
+ const planActionCallerAllowed = async (sessionID: unknown, action: unknown, planId: unknown): Promise<boolean> =>
1045
+ await planRootCallerAllowed(sessionID) ||
1046
+ ((action === "status" || action === "ready" || action === "export") && planReadCallerAllowed(sessionID, planId));
1047
+ const planCallerRefusal = "refused: plan actions require a root orchestrator session; bound plan children may only read their own plan.";
1048
+ const routerPlan = executorRuntime === undefined ? undefined : createRouterPlanTool(executorRuntime, {
1049
+ approve: () => resolveRouting(loadConfig(projectDir), "v2").executor.approve,
1050
+ });
1051
+ const planCommand = executorRuntime === undefined ? undefined : createPlanCommand(executorRuntime);
1052
+ const planCommandMarker = Symbol.for("opencode-model-router.plan-command");
1053
+ let userPlanCommandDefined = false;
1054
+ let warnedPlanCommandConflict = false;
707
1055
  const effortOverrides = createEffortOverrideStore({ logger: routerWarn });
708
1056
  let warnedGraderParams = false;
709
1057
  const depthBanners = new Map<string, string>();
@@ -735,26 +1083,240 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
735
1083
  }
736
1084
  };
737
1085
 
1086
+ // Phase 2.1 (v2 only): pending.jsonl in the durable per-user state directory, never the temp directory (QA-2.1-8).
1087
+ // On v1 there is no journal, no held state and no restore.
1088
+ const pendingDir = isV2Host
1089
+ ? resolvePendingJournalDir({ homedir: homedir(), platform: process.platform, xdgStateHome: process.env.XDG_STATE_HOME })
1090
+ : undefined;
1091
+ /**
1092
+ * QA-2.1-27: the journal compacts and reloads with the resolved `enforcement.verify.pendingTtlMs`, the TTL the pending
1093
+ * registry restores with (a longer configured TTL must not lose entries at the second restart).
1094
+ */
1095
+ const pendingJournalTtlMs = resolvePendingTtlMs(cfg);
1096
+ const pendingFile = pendingDir === undefined
1097
+ ? undefined
1098
+ : createPendingFileJournal(join(pendingDir, "pending.jsonl"), {
1099
+ ttlMs: pendingJournalTtlMs,
1100
+ // QA-2.1-22: a failed start-up compaction is told once (the journal stays as it was).
1101
+ warn: (message) => logger.warn(`[router] ${message}`),
1102
+ });
1103
+ /** Section 11.3: the exclusive per-session claim files of the journal's sessions (v2 only). */
1104
+ const pendingClaimsDir = pendingDir === undefined ? undefined : join(pendingDir, "pending.claims");
1105
+ /** DF-1-10: the beat files of the live plugin instances, which every module copy loaded into one host process can read. */
1106
+ const pendingBeatsDir = pendingDir === undefined ? undefined : join(pendingDir, PENDING_INSTANCES_DIRNAME);
1107
+ /** QA-2.1-33: the v2 adapter's live attempts and holds (`FinishApi.setAdapterSnapshot`); none before it attaches. */
1108
+ let adapterSnapshot: (() => readonly PersistedRecord[]) | undefined;
1109
+ /**
1110
+ * QA-2.1-16/-33: every record a later restore needs from this instance: the live pending entries, the sessions not
1111
+ * adopted yet, and the adapter's live attempts and holds. Registered on the journal (next to `dormantSessions`, once that
1112
+ * state exists), so a `recreate` by any instance of this process on the same path writes this instance's records too.
1113
+ */
1114
+ function journalSnapshot(): PersistedRecord[] {
1115
+ const dormant: PersistedRecord[] = [];
1116
+ for (const session of dormantSessions.values()) dormant.push(...session.holds, ...session.inflight);
1117
+ return [...pending.persistedRecords(), ...dormant, ...(adapterSnapshot?.() ?? [])];
1118
+ }
1119
+ /** QA-2.1-13: the sessions whose claim this process took at adoption; re-stamped while held, released on delete and dispose. */
1120
+ const claimedSessions = new Set<string>();
1121
+ let claimRefreshTimer: ReturnType<typeof setInterval> | undefined;
1122
+ function stopClaimRefresh(): void {
1123
+ if (claimRefreshTimer === undefined) return;
1124
+ clearInterval(claimRefreshTimer);
1125
+ claimRefreshTimer = undefined;
1126
+ }
1127
+ /**
1128
+ * QA-2.1-13/-34: a live owner re-stamps its claims every CLAIM_REFRESH_MS (unref'd timer, stopped when it holds no claim
1129
+ * and on dispose), well within CLAIM_STALE_MS, so they never read as a reused pid's; a crashed owner's claims go stale
1130
+ * within minutes, even when its pid is reused.
1131
+ */
1132
+ function trackPendingClaim(sessionID: string): void {
1133
+ claimedSessions.add(sessionID);
1134
+ if (claimRefreshTimer !== undefined || pendingClaimsDir === undefined) return;
1135
+ const claimsDir = pendingClaimsDir;
1136
+ claimRefreshTimer = setInterval(() => {
1137
+ refreshPendingClaims(claimsDir, claimedSessions, { pid: process.pid, now: Date.now(), ...(instanceClaim === undefined ? {} : { token: instanceClaim.token }) });
1138
+ // DF-1-10: the instance beat stays fresh while this instance holds a claim (a sibling module copy checks it).
1139
+ instanceClaim?.beat();
1140
+ }, CLAIM_REFRESH_MS);
1141
+ claimRefreshTimer.unref?.();
1142
+ }
1143
+ function releasePendingClaimOf(sessionID: string): void {
1144
+ if (!claimedSessions.delete(sessionID) || pendingClaimsDir === undefined) return;
1145
+ releasePendingClaim(pendingClaimsDir, sessionID, instanceClaim?.token);
1146
+ if (claimedSessions.size === 0) stopClaimRefresh();
1147
+ }
1148
+ function releaseAllPendingClaims(): void {
1149
+ stopClaimRefresh();
1150
+ if (pendingClaimsDir !== undefined) for (const sessionID of claimedSessions) releasePendingClaim(pendingClaimsDir, sessionID, instanceClaim?.token);
1151
+ claimedSessions.clear();
1152
+ // QA-2.1-19: from now on another instance of this process may take this instance's (remaining) claims.
1153
+ instanceClaim?.release();
1154
+ }
1155
+ /**
1156
+ * QA-2.1-19 (v2 only): this instance's claim token. Its claims are refused to every other live instance (of this
1157
+ * process: the token; of another process: the pid) until it disposes. DF-1-10: its beat file in `pending.instances`
1158
+ * makes the token visible to instances of this process that run another copy of the plugin modules.
1159
+ */
1160
+ const instanceClaim = pendingClaimsDir === undefined ? undefined : createInstanceClaimToken(pendingBeatsDir);
1161
+ /**
1162
+ * QA-2.1-19: takes the claim of `sessionID` for this instance (pid + token), once. The live owner claims at its first
1163
+ * `inflight`/`hold` write; `adopt` claims before handing dormant records over. False when another live instance holds
1164
+ * it (or the claim file cannot be written).
1165
+ */
1166
+ function claimSessionOnce(sessionID: string): boolean {
1167
+ if (claimedSessions.has(sessionID)) return true;
1168
+ if (pendingClaimsDir === undefined || instanceClaim === undefined) return false;
1169
+ try {
1170
+ const pidAliveNow = (pid: number): boolean => {
1171
+ try {
1172
+ process.kill(pid, 0);
1173
+ return true;
1174
+ } catch (error) {
1175
+ return (error as NodeJS.ErrnoException).code === "EPERM";
1176
+ }
1177
+ };
1178
+ // DF-1-10: the beat is fresh before the claim lands, so a sibling copy of the module never reads it as orphaned.
1179
+ if (claimRefreshTimer === undefined) instanceClaim.beat();
1180
+ if (!claimPendingSession(pendingClaimsDir, sessionID, {
1181
+ pid: process.pid, now: Date.now(), isAlive: pidAliveNow, token: instanceClaim.token,
1182
+ ...(pendingBeatsDir === undefined ? {} : { beatsDir: pendingBeatsDir }),
1183
+ })) return false;
1184
+ } catch (error) {
1185
+ logger.warn("[router] the pending session claim could not be taken", { sessionID, error: describeError(error) });
1186
+ return false;
1187
+ }
1188
+ trackPendingClaim(sessionID);
1189
+ return true;
1190
+ }
1191
+ /** Late-bound: the lease guard exists only once the v2 adapter attaches (FinishAttach `leaseGate`); the wiring reads it per use. */
1192
+ let leaseGateRef: Pick<LeaseGuard, "waitTreeFree"> | undefined;
1193
+ /** Phase 5.1 D11 (v2 only): the plan-task gates' own holders, exempt from the lease wait in their own slot tree. */
1194
+ const planTaskLeaseExemptions = createLeaseSelfExemptions((root) => planTreeKey(root));
738
1195
  const {
739
1196
  graderSessions, dispatchGrader, buildGateDeps, disposeChildSession,
740
- prepareVerification, startReferenceGc,
1197
+ prepareVerification, startReferenceGc, beginVerificationBounded,
741
1198
  sweepVerification, disposeVerification,
742
- startDispatch, takeDispatch, isDeferred: wiringIsDeferred, finishDeferred, applyLineage, pending,
1199
+ startDispatch, takeDispatch, isDeferred: wiringIsDeferred, directivesFor, finishDeferred, applyLineage, pending,
743
1200
  verifyHandles,
744
1201
  // 2.4.5: undefined unless `background: true` at plugin start (pending.ts R14).
745
1202
  background,
746
1203
  } = createVerificationWiring({
747
1204
  client: ctx.client,
1205
+ observations: isV2Host ? ctx.routerObservations : undefined,
748
1206
  childRunner: ctx.routerChildRunner,
749
1207
  onChildSessionCreated: (sid, creator) => depthTracker.recordPluginChild(sid, creator),
750
1208
  directory: ctx.directory,
751
1209
  getConfig: () => cfg,
752
1210
  logger,
1211
+ ...(pendingFile === undefined ? {} : {
1212
+ pending: { persist: pendingFile, onVerdict: (entry: PendingEntry, result: SettledVerification) => postHeldVerdict(entry, result) },
1213
+ pendingRestore: pendingFile.load(),
1214
+ // v2 only. Delegating: the guard arrives with the adapter's attach; until then (or without `leases: enforce`) nothing waits.
1215
+ leaseGate: {
1216
+ waitTreeFree: async (tree, owner, deadlineMs, signal) => {
1217
+ if (leaseGateRef === undefined) return { waitedMs: 0, holders: [], fileCount: 0 };
1218
+ // Phase 5.1 D11: a plan-task gate does not wait for its own task's holders in its own slot tree.
1219
+ const exempt = planTaskLeaseExemptions.exemptFor(tree);
1220
+ if (exempt.size === 0) return leaseGateRef.waitTreeFree(tree, owner, deadlineMs, signal);
1221
+ const gate = leaseGateRef;
1222
+ let fileCount = 0;
1223
+ const probe: Pick<LeaseGuard, "waitTreeFree"> = {
1224
+ waitTreeFree: async (...args) => { const r = await gate.waitTreeFree(...args); fileCount = r.fileCount; return r; },
1225
+ };
1226
+ const wait = await waitTreeFreeExcept(probe, tree, owner, exempt, deadlineMs, signal);
1227
+ return { waitedMs: wait.waitedMs, holders: wait.holders, fileCount: wait.holders.length === 0 ? 0 : fileCount };
1228
+ },
1229
+ },
1230
+ }),
753
1231
  });
754
1232
  // 2.1.5b: sweep reference dirs a crashed instance left behind. Fire-and-forget; never throws.
755
1233
  // QA-2.1-11: deferred (unref'd timer), so plugin start never holds the project directory with a
756
1234
  // git child; dispose cancels it.
757
- const stopReferenceGc = startReferenceGc();
1235
+ // DF-1-1 (v2 only): with `routing.workRoots` configured and non-empty, a location outside every entry is not the plan's:
1236
+ // the start-up reference GC is skipped (it would run git in, and write to, that repository). Unset or empty: unchanged.
1237
+ const outsideWorkRoots = isV2Host && locationOutsideWorkRoots(ctx.directory, cfg.routing?.workRoots);
1238
+ if (outsideWorkRoots) logger.info?.(`[router] ${ctx.directory} is outside routing.workRoots: the start-up reference GC is skipped`);
1239
+ const stopReferenceGc = outsideWorkRoots ? (): void => undefined : startReferenceGc();
1240
+ // Phase 5.1 D8 (v2 only): plan tasks are verified by this instance's dispatch verification engine; v2.ts hands the verifier to
1241
+ // the adapter's executor seam. Nothing is built or handed over on v1.
1242
+ if (isV2Host) {
1243
+ const planTaskVerifier = createPlanTaskVerifier({
1244
+ changedFileStore,
1245
+ beginVerificationBounded,
1246
+ prepareVerification,
1247
+ buildGateDeps,
1248
+ captureBudget: (childSessionID, capReached) => captureBudget(childSessionID, capReached),
1249
+ readCapReached: (childSessionID) => sessionStore.readCapReached(childSessionID),
1250
+ onVerdict: (childSessionID, verdict) => ingest?.onVerdict(childSessionID, verdictOf(verdict), verdictGraderOf(verdict)),
1251
+ abortSession: async (sessionID) => { await ctx.client.session.abort({ path: { id: sessionID } }); },
1252
+ getConfig: () => cfg,
1253
+ git: planTaskGit(),
1254
+ exemptions: planTaskLeaseExemptions,
1255
+ log: (message, detail) => logger.warn(`[verify] ${message}`, detail === undefined ? undefined : { error: describeError(detail) }),
1256
+ });
1257
+ (ctx as RouterPluginInput & { routerOnSlotVerifier?: (verifier: typeof planTaskVerifier) => void }).routerOnSlotVerifier?.(planTaskVerifier);
1258
+ }
1259
+
1260
+ // Phase 1.2 (v2 only): the turn-state registry the adapter injects. Without it (v1, or a v2 host that injects none) nothing
1261
+ // below is registered or buffered, and the system transform keeps pushing the pending list and the late notices.
1262
+ // The registry arrives through the ROUTER_TURN_STATE_ATTACH hook the v2 adapter calls (the only channel); the hook
1263
+ // returns whether the registry was accepted.
1264
+ let turnState: TurnStateRegistry | undefined;
1265
+ const lateBuffer: LateBuffer | undefined = isV2Host ? createLateBuffer() : undefined;
1266
+ const unregisterTurnStateProviders: Array<() => void> = [];
1267
+ let warnedSecondRegistry = false;
1268
+ const attachTurnState = (registry: TurnStateRegistry): boolean => {
1269
+ if (turnState !== undefined) {
1270
+ if (turnState !== registry && !warnedSecondRegistry) {
1271
+ warnedSecondRegistry = true;
1272
+ logger.warn("[router] turn state: a second registry was ignored");
1273
+ }
1274
+ return turnState === registry;
1275
+ }
1276
+ turnState = registry;
1277
+ if (lateBuffer === undefined) return true;
1278
+ try {
1279
+ // Late notices of background runs that did not pass: buffered before the block is built (a builder throw loses
1280
+ // nothing) and kept until router_verify answers their handle.
1281
+ unregisterTurnStateProviders.push(turnState.registerTurnStateProvider({
1282
+ name: "late",
1283
+ order: 10,
1284
+ render(sid) {
1285
+ if (background === undefined) return undefined;
1286
+ lateBuffer.add(sid, background.takeNotices(sid));
1287
+ lateBuffer.touch(sid);
1288
+ return buildLateNoticeBlock(lateBuffer.list(sid));
1289
+ },
1290
+ active(sid) {
1291
+ return lateBuffer.list(sid).length > 0;
1292
+ },
1293
+ }));
1294
+ // This orchestrator's still-unverified delegations (the same arguments the v1 transform passes).
1295
+ unregisterTurnStateProviders.push(turnState.registerTurnStateProvider({
1296
+ name: "pending",
1297
+ order: 20,
1298
+ render(sid) {
1299
+ return buildPendingListBlock(pending.listPending(sid, { verifying: background !== undefined }));
1300
+ },
1301
+ active(sid) {
1302
+ return pending.listPending(sid, { verifying: background !== undefined }).length > 0;
1303
+ },
1304
+ }));
1305
+ } catch (error) {
1306
+ logger.warn("[router] turn state: late/pending providers not registered", { error: scrubText(String(error)) });
1307
+ // Nothing stays half registered: the system transform keeps delivering through the system array.
1308
+ for (const unregister of unregisterTurnStateProviders.splice(0)) {
1309
+ try {
1310
+ unregister();
1311
+ } catch (unregisterError) {
1312
+ logger.warn("[router] turn state: unregistering a provider failed", { error: scrubText(String(unregisterError)) });
1313
+ }
1314
+ }
1315
+ turnState = undefined;
1316
+ return false;
1317
+ }
1318
+ return true;
1319
+ };
758
1320
 
759
1321
  // Best-effort, secret-free delegate scorecard dump (counts only).
760
1322
  const dumpDelegateScorecard = (
@@ -780,7 +1342,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
780
1342
  // #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
1343
  (ctx as RouterPluginInput & { routerOnBypassState?: (read: () => boolean) => void }).routerOnBypassState?.(() => bypassed);
782
1344
  /** 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));
1345
+ const roleBudgetSnapshot = (childSessionID: string) => {
1346
+ consumeExecutorChildRound(childSessionID);
1347
+ return captureBudget(childSessionID, sessionStore.readCapReached(childSessionID));
1348
+ };
784
1349
  (ctx as RouterPluginInput & { routerOnBudgetSnapshot?: (read: typeof roleBudgetSnapshot) => void }).routerOnBudgetSnapshot?.(roleBudgetSnapshot);
785
1350
  /**
786
1351
  * 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
@@ -845,21 +1410,30 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
845
1410
  const ADVISOR_ROLE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
846
1411
  /**
847
1412
  * #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.
1413
+ * statistics, unknown-binding counts and tier dispatch count over {@link ADVISOR_ROLE_WINDOW_MS}, plus process-lifetime orphan
1414
+ * counters. The v2 adapter uses this same gatherer. Tiers mode and v1 read nothing (`{ host }` only); a read failure leaves
1415
+ * the windowed statistics out but keeps the process counters.
850
1416
  */
851
1417
  const advisorExtras = async (): Promise<AdvisorExtras> => {
852
1418
  const host = isV2Host ? "v2" as const : "v1" as const;
853
1419
  if (rolesNow().size === 0) return { host };
1420
+ const orphanCounters = readRoleOrphans().counters;
854
1421
  const live = ingestSettings(cfg, "v2");
855
- if (live === null) return { host }; // engine static: no decision log
1422
+ if (live === null) return { host, orphanCounters }; // engine static: no decision log
856
1423
  try {
857
1424
  const read = await createPersister(live.outcomesDir, nodePersistDeps({ warn: () => undefined })).readRows();
858
1425
  const since = Date.now() - ADVISOR_ROLE_WINDOW_MS;
859
- return { host, roleStats: summarizeRoles(null, read.rows, { since, until: null }), tierDispatches: tierDispatchCount(read.rows, since) };
1426
+ const window = { since, until: null };
1427
+ return {
1428
+ host,
1429
+ roleStats: summarizeRoles(null, read.rows, window),
1430
+ tierDispatches: tierDispatchCount(read.rows, since),
1431
+ unknownBindings: countUnknownBindings(read.rows, window),
1432
+ orphanCounters,
1433
+ };
860
1434
  } catch (error) {
861
1435
  logger.warn("[router] cost doctor: the role statistics are unavailable", { error: describeError(error) });
862
- return { host };
1436
+ return { host, orphanCounters };
863
1437
  }
864
1438
  };
865
1439
  const gatherAdvisorInputs = async (
@@ -902,6 +1476,28 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
902
1476
  });
903
1477
  return annotateRuntime;
904
1478
  };
1479
+ if (isV2Host) {
1480
+ executorInput?.routerOnPlanAnnotate?.(async (steps) => {
1481
+ const current = loadConfig(projectDir);
1482
+ const runtime = annotatePlanRuntime();
1483
+ const prepared = await runtime?.prepare(current);
1484
+ const routing = prepared?.routing ?? resolveRouting(current, "v2");
1485
+ const classifyDeps = prepared && runtime ? runtime.classifyDeps(prepared) : {
1486
+ cfg: current, settings: { ...routing.classifier, backend: "rules" as const },
1487
+ minClassConfidence: routing.minClassConfidence, backend: null, logger,
1488
+ };
1489
+ let agents: HostAgentInfo[] | null = null;
1490
+ if (prepared && ctx.routerAgents !== undefined) {
1491
+ try { agents = agentInfosForPlan(await ctx.routerAgents()); }
1492
+ catch (error) { logger.warn("[router] executor: the agent list is unavailable; tiers are annotated without it", { error: describeError(error) }); }
1493
+ }
1494
+ return annotateSteps(steps, {
1495
+ cfg: current, routing, agents, store: prepared?.store ?? null, logger,
1496
+ ...(prepared ? { pricing: (model) => prepared.catalog.pricing(model), session: prepared.session } : {}),
1497
+ classifyMany: (inputs) => classifyPlanSteps(inputs, { ...classifyDeps, routeLinePositions: "any" }),
1498
+ });
1499
+ });
1500
+ }
905
1501
  // v1 only (A28): the host's agent list for the text-only roles line, read through `client.app.agents()` and never fetched unless
906
1502
  // `routing.roles` is set explicitly. It is refreshed IN THE BACKGROUND (QA-2.4-13): a turn never waits for it. The first turn after start
907
1503
  // has no list yet and gets the baseline prompt; later turns use the last list, stale while the next one is fetched (every minute). A
@@ -1103,7 +1699,23 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1103
1699
  // v1 the set is exactly the previous one (router_run and router_request_authority are not registered; router_git_* keep their
1104
1700
  // directory resolution). Switching to roles mode registers them on the next start.
1105
1701
  const rolesAtStart = rolesNow().size > 0;
1702
+ // G-16: on v2 off Windows, one notice per process, only for a config that asks for the executor (roles mode at start with
1703
+ // enforced leases and verification not disabled: the prerequisites v2.ts's executor discovery checks).
1704
+ if (isV2Host && !executorPlatform && rolesAtStart && resolveRouting(cfg, "v2").leases.mode === "enforce"
1705
+ && cfg.enforcement?.verify?.require !== "never") warnExecutorPlatformOnce(logger);
1106
1706
  const dynamicRolesAtStart = [...rolesNow().values()].some((spec) => spec.authority.mode === "dynamic");
1707
+ /**
1708
+ * Cross-repo 3b.4 (SD-3b-1): `router_git_*` declare `root` only on v2, in roles mode, with `routing.repoParents` non-empty at start
1709
+ * (the tool map is fixed at start). Everywhere else, v1 included, schema and description stay byte-identical; no notice.
1710
+ */
1711
+ const crossRepoAtStart = ((): boolean => {
1712
+ if (!isV2Host || !rolesAtStart) return false;
1713
+ try {
1714
+ return resolveRolesRouting(cfg, "v2").repoParents.length > 0;
1715
+ } catch {
1716
+ return false;
1717
+ }
1718
+ })();
1107
1719
  /** `router_request_authority` dependencies (P1.6): the role by child session; only the parent of `dispatchOf` is read. */
1108
1720
  const authorityDeps = {
1109
1721
  roleOf: (child: string) => roleOfSession(child),
@@ -1116,28 +1728,24 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1116
1728
  },
1117
1729
  bindingOf: (child: string) => currentBinding(child, { maxOf: roleMaxOf }),
1118
1730
  };
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
- };
1731
+ /** The acceptance commands of a role dispatch as `routing.run` names (handoff 13); see `acceptanceScriptsOf`. */
1732
+ const acceptanceScripts = (prompt: unknown, description: unknown): string[] =>
1733
+ acceptanceScriptsOf(
1734
+ buildDelegationDoD({
1735
+ prompt: typeof prompt === "string" ? prompt : undefined,
1736
+ description: typeof description === "string" ? description : undefined,
1737
+ }),
1738
+ );
1133
1739
  /**
1134
1740
  * 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
1741
  * `CAP:none` is no cap, as for tier dispatches); `null` when it names none (then the child gets no read-only cap).
1136
1742
  */
1137
1743
  const roleDispatchCap = (prompt: unknown): Cap | null => {
1138
1744
  if (typeof prompt !== "string") return null;
1139
- const parsed = parseCapDirective(prompt);
1140
- return parsed === "none" && !/\breason:/i.test(prompt) ? null : parsed;
1745
+ // P2g.3 (OD6): the orchestrator's own text — a router role header (a work root such as `.../CAP:9`) is never read as the cap.
1746
+ const text = stripDispatchHeader(prompt);
1747
+ const parsed = parseCapDirective(text);
1748
+ return parsed === "none" && !/\breason:/i.test(text) ? null : parsed;
1141
1749
  };
1142
1750
  /** Caps of fresh role dispatches, by the parent's call, until the child binds (bounded, oldest out). */
1143
1751
  const pendingRoleCaps = new Map<string, { agent: string; cap: Cap }>();
@@ -1155,6 +1763,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1155
1763
  };
1156
1764
  /** A fresh role child's first call: its exact binding names the dispatch's call, whose cap is registered once. */
1157
1765
  const applyPendingRoleCap = (child: string): void => {
1766
+ consumeExecutorChildRound(child);
1158
1767
  if (pendingRoleCaps.size === 0) return;
1159
1768
  const binding = currentBinding(child, { maxOf: roleMaxOf });
1160
1769
  const callID = binding?.kind === "exact" ? binding.candidates[0] : undefined;
@@ -1163,6 +1772,48 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1163
1772
  pendingRoleCaps.delete(callID);
1164
1773
  registerRoleCap(child, pending.agent, pending.cap);
1165
1774
  };
1775
+ /**
1776
+ * QA-PDF21-2-11: an executor budget resume (a launch with `req.resume`) opens a new guard round and a new read-cap round for
1777
+ * its child, exactly as a routed resume does (`noteRoleDispatch`): the per-dispatch budget and the read counter restart, the
1778
+ * cumulative ceiling stays. A cap the launch prompt names replaces the child's previous one.
1779
+ */
1780
+ const beginExecutorResumeRound = (child: string, agent: string, prompt: string): void => {
1781
+ publishExecutorChildRound(child, agent, executorLineCap(prompt), true);
1782
+ consumeExecutorChildRound(child);
1783
+ };
1784
+ /**
1785
+ * QA-PDF21-2-20: the read cap of a plan child's launch prompt is the executor's own cap line ONLY (`EXECUTOR_READ_CAP_LINE`,
1786
+ * right after the "PLAN CONTEXT" line, DF-2-9), parsed by `parseCapDirective`. A prompt without it (a non-editing task, a
1787
+ * resume) names no cap: plan text — even a `CAP` token split across lines, which the line-bound neutralization misses — never
1788
+ * sets one.
1789
+ */
1790
+ const executorLineCap = (prompt: string): Cap | null =>
1791
+ prompt.startsWith(`PLAN CONTEXT\n${EXECUTOR_READ_CAP_LINE}\n`) ? parseCapDirective(EXECUTOR_READ_CAP_LINE) : null;
1792
+ /**
1793
+ * QA-PDF21-2-20: a plan child the executor just bound gets the read cap of its launch prompt's cap line, through the state a
1794
+ * routed role dispatch uses (`registerRoleCap`). A plan child has no parent `task` call, so `applyPendingRoleCap` never
1795
+ * reaches it, and its role agent is no tier, so `registerFromChatMessage` does not either.
1796
+ */
1797
+ const applyExecutorChildCap = (child: string, agent: string, prompt: string): void => {
1798
+ publishExecutorChildRound(child, agent, executorLineCap(prompt), false);
1799
+ consumeExecutorChildRound(child);
1800
+ };
1801
+ const executorRoundsSeen = new Map<string, number>();
1802
+ const consumeExecutorChildRound = (child: string): void => {
1803
+ if (!isV2Host) return;
1804
+ const published = executorChildRound(child);
1805
+ if (published === undefined || executorRoundsSeen.get(child) === published.round) return;
1806
+ setBounded(executorRoundsSeen, child, published.round);
1807
+ rememberRoleSession(child, published.agent);
1808
+ sessionStore.markChildSession(child);
1809
+ guardStore.beginDispatch(child);
1810
+ if (!sessionStore.resumeRoleSession(child, published.cap) && published.cap !== null) registerRoleCap(child, published.agent, published.cap);
1811
+ };
1812
+ // QA-PDF21-2-11/-20: the v2 adapter's executor bookkeeping reaches the guard store and the read-cap state through these.
1813
+ (ctx as RouterPluginInput & { routerOnExecutorChildGuard?: (port: ExecutorChildGuardPort) => void }).routerOnExecutorChildGuard?.({
1814
+ beginResumeRound: beginExecutorResumeRound,
1815
+ applyCap: applyExecutorChildCap,
1816
+ });
1166
1817
  /**
1167
1818
  * #84 P3.3 DF2-F1: where the `task` call `callID` is verified. A routed role dispatch (`routedRoleOf`, kept until the adapter's
1168
1819
  * `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
@@ -1170,10 +1821,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1170
1821
  * 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
1822
  * outside it is refused by the gate. Every other dispatch: the explicit cwd, as before (I1).
1172
1823
  */
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*$/, "");
1824
+ const verificationScopeOf = (callID: unknown, args: Record<string, unknown> | undefined, dod: { cwd?: string }, restoredWorkRoot?: string): VerificationScope =>
1825
+ verificationScope(requestedVerificationCwd(args?.cwd, dod.cwd), (typeof callID === "string" ? routedRoleFor(callID)?.verifyRoot : undefined) ?? restoredWorkRoot);
1826
+ /** The prompt as the orchestrator wrote it: without the router's role dispatch header (P2g.3, OD6) and its nonce line (handoff 18). */
1827
+ const withoutNonceLine = (prompt: string): string => stripDispatchHeader(prompt).replace(/\r?\n?OMR_NONCE=[A-Za-z0-9_-]+\s*$/, "");
1177
1828
  /**
1178
1829
  * 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
1830
  * budget and `budgetExhausted` are per round), and the re-dispatch signal (P1.4, handoff 16) compares the dispatch with the
@@ -1286,30 +1937,48 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1286
1937
  roleBudgetPeaks.delete(sessionID);
1287
1938
  for (const [callID, sent] of roleDispatchTexts) if (sent.parentSessionID === sessionID) roleDispatchTexts.delete(callID);
1288
1939
  };
1289
- return {
1940
+ const routerHooks: Awaited<ReturnType<Plugin>> = {
1290
1941
  // Warnings post to /log fire-and-forget, which loses the message when the
1291
1942
  // process is about to exit — `opencode run` and `opencode debug` are short
1292
1943
  // enough for that to be the normal case. Verified against opencode 1.18.16
1293
1944
  // that dispose is both called and awaited, so flushing here is enough.
1294
1945
  dispose: async () => {
1295
1946
  stopReferenceGc();
1947
+ // Phase 1.2: the turn-state providers of this instance leave the (adapter-owned) registry.
1948
+ for (const unregister of unregisterTurnStateProviders.splice(0)) unregister();
1949
+ // QA-2.1-21 (v2 only): the held gates this instance started (and their verdict posts) end before the pending registry
1950
+ // and the verification wiring go; bounded, a gate still running then ends through the disposals below.
1951
+ await waitHeldGates(HELD_GATES_DISPOSE_BOUND_MS);
1296
1952
  // Stop new advisor work and finish state/claim writes and lock removal before teardown.
1297
1953
  await advisorNotifier?.dispose();
1298
1954
  // 2.4.5: abort a background run and drop its queue and notices before the registry goes.
1299
1955
  background?.dispose();
1300
1956
  // 2.4.2b: evict every pending delegation; in-flight router_verify runs resolve (pending.ts R5).
1301
1957
  pending.dispose();
1958
+ // QA-2.1-13 (v2 only): stop re-stamping and give back every session claim this process took at adoption.
1959
+ releaseAllPendingClaims();
1302
1960
  // 2.2.3: settle batched testsPass requests and kill running batches (never rejects).
1303
1961
  await disposeVerification();
1304
1962
  // 2.1.3: flush and release the outcome bundle held by this instance (never rejects).
1305
1963
  await ingest?.dispose();
1306
1964
  await annotateRuntime?.dispose();
1307
1965
  await attemptRecorder?.dispose();
1966
+ // QA-2.1-22 (v2 only): after the last append of this instance; the last journal of the path removes this process's writer mark.
1967
+ await pendingFile?.dispose();
1308
1968
  await logger.flush();
1309
1969
  },
1310
1970
  tool: {
1971
+ ...(rolesAtStart && routerPlan !== undefined ? { router_plan: {
1972
+ ...routerPlan,
1973
+ execute: async (args, context) => await planActionCallerAllowed(context?.sessionID, args?.action, args?.planId)
1974
+ ? routerPlan.execute(args, context)
1975
+ : `[router_plan] ${planCallerRefusal}`,
1976
+ } } : {}),
1311
1977
  // 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 } : {}) } : {}),
1978
+ ...gitTools(rolesAtStart ? {
1979
+ resolveWorkRoot: resolveWorkRootFor("router_git"), ...(ctx.directory ? { dispatchRepository: ctx.directory } : {}),
1980
+ ...(crossRepoAtStart ? { resolveRoot: resolveGitRootFor } : {}),
1981
+ } : {}),
1313
1982
  // #84 P2.1 (handoffs 11, 13): roles mode only. `router_run` runs in the bound work root; each run feeds the `run` signal.
1314
1983
  ...(rolesAtStart ? {
1315
1984
  router_run: routerRunTool({
@@ -1399,6 +2068,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1399
2068
  acceptance: args.acceptance,
1400
2069
  });
1401
2070
  const effectiveCwd = typeof args.cwd === "string" && args.cwd.trim() ? args.cwd : dod.cwd;
2071
+ // Cross-repo P2b.7 (OD1=B, v2 only): `delegate` is a tier dispatch; a per-check `cwd=` is unverifiable there. On v1 nothing changes.
2072
+ const tierRefusal = ctx.routerHost === "v2" ? tierCheckCwdRefusal(dod) : undefined;
1402
2073
 
1403
2074
  // Phase 2.3 (D10/D11): on v2 with `variantSteps: auto` (A15: only with a `routing` block) and a catalog,
1404
2075
  // the ladder is session-aware: variant steps on the same model first, resume of the child session
@@ -1618,7 +2289,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1618
2289
  // 2.4.2c, section 1.5-16: a deferred delegation runs no gate and no ladder. A producer
1619
2290
  // that failed outright produced nothing to verify later; it keeps today's
1620
2291
  // failed-attempt path, which runs no verification process either.
1621
- const finish = dispatchStart !== undefined && producerError === null && isDeferred(dod, dispatchStart.directives) &&
2292
+ const finish = dispatchStart !== undefined && producerError === null && tierRefusal === undefined && isDeferred(dod, dispatchStart.directives) &&
1622
2293
  await isProvenRootCaller(toolCtx?.sessionID)
1623
2294
  ? await finishDeferred(changedFileStore, {
1624
2295
  dispatchID: baselineID,
@@ -1631,6 +2302,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1631
2302
  dispatchedAt: dispatchStart.dispatchedAt,
1632
2303
  // Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule): router_verify judges the budget at return.
1633
2304
  budget: captureBudget(producerSid, sessionStore.readCapReached(producerSid)),
2305
+ // Cross-repo P2e.6 (OD-P2e-2): the full scope on v2; a delegate dispatch has no per-check placements.
2306
+ ...(fullScopeOf(activeCfg) ? { fullScope: true } : {}),
1634
2307
  })
1635
2308
  : undefined;
1636
2309
  // QA-2.4-4 / QA-2.4-10: a finish that did not defer falls through to the required gate
@@ -1653,6 +2326,9 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1653
2326
  await disposeChildSession(producerSid);
1654
2327
  return { sessionID: producerSid, text: producerText, deferredFooter: finish.footer };
1655
2328
  }
2329
+ // B2: the finish saw the tree switch branch; the gate's own read below may not (it can fail), so the finish's
2330
+ // reason is carried into the artefact.
2331
+ const deferredSwitch = finish !== undefined && !finish.deferred && finish.reason === "branch-switched" ? finish.detail : undefined;
1656
2332
  // Once a delegation is gated, every later attempt of its ladder is gated too.
1657
2333
  if (finish !== undefined && dispatchStart !== undefined) {
1658
2334
  dispatchStart = { ...dispatchStart, directives: { ...dispatchStart.directives, mode: "required" } };
@@ -1668,7 +2344,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1668
2344
  const gateDeadline = createDeadline(gateBudgetMs);
1669
2345
  let verification;
1670
2346
  try {
1671
- verification = await prepareVerification(changedFileStore, baselineID, producerSid, effectiveCwd, gateDeadline);
2347
+ // Cross-repo P3a (D23 as amended, QA C1): the dispatch's own start, the `since` of W's ignored-module listing.
2348
+ verification = await prepareVerification(changedFileStore, baselineID, producerSid, effectiveCwd, gateDeadline, dispatchStart?.dispatchedAt, undefined, isV2Host ? toolCtx?.sessionID : undefined);
1672
2349
  } catch (error) {
1673
2350
  gateDeadline.dispose();
1674
2351
  throw error;
@@ -1676,6 +2353,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1676
2353
  const artefact = {
1677
2354
  changedFiles: verification.changedFiles,
1678
2355
  changeBaseline: verification.changeBaseline,
2356
+ ...(verification.snapshot?.root !== undefined ? { changeRoot: verification.snapshot.root } : {}),
2357
+ ...((verification.branchSwitch ?? deferredSwitch) !== undefined ? { branchSwitch: verification.branchSwitch ?? deferredSwitch } : {}),
2358
+ ...(verification.unattributedWriters !== undefined && verification.unattributedWriters.length > 0
2359
+ ? { unattributedWriters: verification.unattributedWriters } : {}),
2360
+ ...(verification.perimeter !== undefined ? { perimeter: verification.perimeter } : {}),
1679
2361
  finalReturnText: producerText,
1680
2362
  declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
1681
2363
  producerSessionID: producerSid,
@@ -1706,6 +2388,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1706
2388
  trivial: false,
1707
2389
  mode: "modeA",
1708
2390
  ...(effectiveCwd ? { cwd: effectiveCwd } : {}),
2391
+ ...(tierRefusal !== undefined ? { refusedCheck: tierRefusal } : {}),
1709
2392
  },
1710
2393
  artefact,
1711
2394
  gateDeps,
@@ -1934,6 +2617,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1934
2617
  // R6: handles are scoped by the calling session; without one, every handle is unknown.
1935
2618
  const sessionID = typeof toolCtx?.sessionID === "string" ? toolCtx.sessionID : "";
1936
2619
  const report = await verifyHandles(sessionID, target, toolCtx?.abort !== undefined ? { signal: toolCtx.abort } : {});
2620
+ // Phase 1.2 (v2 only): the late notices this report answers stop being retained for the turn-state tail.
2621
+ lateBuffer?.release(sessionID, answeredHandles(report.items));
1937
2622
  return report.text;
1938
2623
  } catch (error) {
1939
2624
  logger.warn("[verify] router_verify failed", { error: scrubText(String(error)) });
@@ -2120,6 +2805,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2120
2805
  // non-subagent sessions or when enforcement is off (GA-1 preserved).
2121
2806
  // -----------------------------------------------------------------------
2122
2807
  "tool.execute.before": async (input: any, output: any) => {
2808
+ if (typeof input?.sessionID === "string") consumeExecutorChildRound(input.sessionID);
2809
+ rememberTaskArgs(input, output); // phase 2.1 (v2 only; a no-op on v1)
2123
2810
  // #84 P2.1: a role child's own call names its role agent (the v2 adapter passes the calling agent). Remembered even while
2124
2811
  // bypassed (the work-root resolver and the authority tool are authority, not routing), and marked a child session: role
2125
2812
  // agents are subagents, so the guard engages from their first call. Never on v1 / in tiers mode (no role table).
@@ -2161,9 +2848,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2161
2848
  // 2.4.2b: the directives come from the orchestrator's own prompt, read here before the
2162
2849
  // dispatch header or any repair touches it, and are kept for the after hook. The capture
2163
2850
  // 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).
2851
+ // DF2-F1 / I2 (P2.3): a role dispatch's capture is taken in its work root W (never in a refused cwd or a check
2852
+ // subdirectory); a tier dispatch has no workRoot, so this is its explicit cwd, as before.
2165
2853
  await startDispatch(changedFileStore, `task:${input.sessionID}:${input.callID}`,
2166
- verificationScopeOf(input.callID, output?.args, dod).cwd,
2854
+ captureRootOf(verificationScopeOf(input.callID, output?.args, dod)),
2167
2855
  dod,
2168
2856
  dispatchDirectiveText(prompt, description),
2169
2857
  true);
@@ -2224,8 +2912,15 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2224
2912
  // Handoff 30, R7 (I1/I8 exemption: T1.5.3a, the header names `root=`): on v2 shadow/advise/enforce the engine stripped the
2225
2913
  // route line already; its `root=` comes from the router. No root → the header is byte-identical to before.
2226
2914
  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;
2915
+ // Cross-repo (P1.7, v2 only): the orchestrator's working set and the read parents (a tier call has no routed role,
2916
+ // hence no location). All empty unless cross-repo is in use, so the header is then byte-identical to before.
2917
+ const crossRepo = ctx.routerHost === "v2" ? resolveRolesRouting(cfg, "v2") : undefined;
2918
+ const workingSet = ctx.routerHost === "v2" && typeof input.sessionID === "string" ? workingSetOf(input.sessionID) : [];
2919
+ const prompt = buildDispatchHeader({
2920
+ tier, cap, projectDirectory: ctx.directory, root,
2921
+ ...(workingSet.length === 0 ? {} : { workingSet }),
2922
+ ...(crossRepo === undefined || crossRepo.repoParents.length === 0 ? {} : { readParents: crossRepo.repoParents }),
2923
+ }) + DISPATCH_HEADER_SEPARATOR + args.prompt;
2229
2924
  args.prompt = prompt;
2230
2925
  if (process.env.MODEL_ROUTER_DISPATCH_DEBUG === "1" && !dispatchDebugLogged) {
2231
2926
  dispatchDebugLogged = true;
@@ -2251,7 +2946,13 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2251
2946
  }
2252
2947
  }
2253
2948
  const sid = input?.sessionID;
2949
+ // F1: the unattributed-writer tally is also kept before the call runs: a call that ends in error never reaches the
2950
+ // after-hook's record(). Reached only by calls the router did not refuse (a refusal throws below, before this runs).
2951
+ const noteWriter = (): void => {
2952
+ if (typeof sid === "string" && typeof input?.tool === "string") changedFileStore.noteWriter(sid, input.tool);
2953
+ };
2254
2954
  if (!sid || !sessionStore.isSubagent(sid) || typeof input?.tool !== "string") {
2955
+ noteWriter();
2255
2956
  return;
2256
2957
  }
2257
2958
  // Start-of-call refresh: the idle TTL must cover the tool's runtime, not
@@ -2274,6 +2975,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2274
2975
  ...(profile === undefined ? {} : { profile }),
2275
2976
  });
2276
2977
  } catch {
2978
+ noteWriter(); // the call proceeds
2277
2979
  return; // never break a real session on a guard-internal error
2278
2980
  }
2279
2981
  if (res.block) {
@@ -2285,6 +2987,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2285
2987
  });
2286
2988
  throw new Error(res.message);
2287
2989
  }
2990
+ noteWriter();
2288
2991
  },
2289
2992
 
2290
2993
  // -----------------------------------------------------------------------
@@ -2295,6 +2998,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2295
2998
  // treats them as ground truth rather than advisory system noise.
2296
2999
  // -----------------------------------------------------------------------
2297
3000
  "tool.execute.after": async (input: any, output: any) => {
3001
+ if (typeof input?.sessionID === "string") consumeExecutorChildRound(input.sessionID);
2298
3002
  if (input?.tool === "grep" && typeof output.output === "string") {
2299
3003
  const tier = input.agent ?? pluginAgentSessions.get(input.sessionID) ?? sessionStore.getTier(input.sessionID);
2300
3004
  const definition = tier && getActiveTiers(cfg)[tier];
@@ -2386,224 +3090,22 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2386
3090
  }
2387
3091
  }
2388
3092
 
3093
+ // Cross-repo (P1.9): a role's read from outside its work root says where it came from. Last, after every router banner.
3094
+ try {
3095
+ const provenance = await readProvenanceLine(input);
3096
+ if (provenance !== undefined && typeof output?.output === "string") {
3097
+ output.output = `${output.output}${output.output.endsWith("\n") ? "" : "\n"}${provenance}`;
3098
+ }
3099
+ } catch {
3100
+ // best-effort: a provenance line must never break a tool result
3101
+ }
3102
+
2389
3103
  // Option (i): verify-dispatch around the built-in `task` tool (advisory-grade —
2390
3104
  // we observe the finished task result and append a forcing note if it is not
2391
3105
  // accepted; we cannot retry a task call that already finished).
2392
- if (typeof input?.tool === "string") {
2393
- let mode = "off";
2394
- try {
2395
- mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
2396
- } catch {
2397
- // fall through with mode "off"
2398
- }
2399
- const requireMode = cfg.enforcement?.verify?.require;
2400
- if (shouldVerifyTask(input.tool, mode, requireMode)) {
2401
- try {
2402
- // pending.ts R11: the producer's changes landed by now.
2403
- const returnedAt = Date.now();
2404
- const { finalReturnText, childSessionID } = parseTaskResult(unbannered ? { ...output, output: unbannered.output } : output);
2405
- const producerTier =
2406
- typeof input?.args?.subagent_type === "string"
2407
- ? input.args.subagent_type
2408
- : "";
2409
- const dod = buildDelegationDoD({
2410
- prompt: input?.args?.prompt,
2411
- description: input?.args?.description,
2412
- });
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;
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;
2423
- const orchestratorSessionID = typeof input.sessionID === "string" ? input.sessionID : "";
2424
- const taskPrompt = typeof input?.args?.prompt === "string" ? input.args.prompt : undefined;
2425
- const taskDescription = typeof input?.args?.description === "string" ? input.args.description : undefined;
2426
- // 2.4.2b: the mode the orchestrator chose at dispatch (never the subagent's text).
2427
- const start = takeDispatch(dispatchID, dispatchDirectiveText(taskPrompt, taskDescription));
2428
- const trivial = childSessionID
2429
- ? sessionStore.isTrivial(childSessionID)
2430
- : false;
2431
- // QA-2.4-10: `trivial` as the gate sees it below; a dispatch the gate would skip is not
2432
- // deferred (isDeferred). QA-2.4-2: only a proven root orchestrator defers.
2433
- if (!scope.outside && !carriedRole && isDeferred(dod, start.directives, trivial) && await isProvenRootCaller(orchestratorSessionID)) {
2434
- // Section 1.5-16: no gate, no test process; the result goes back now with the
2435
- // footer, which is appended last and never says accepted or verified.
2436
- const finish = await finishDeferred(changedFileStore, {
2437
- dispatchID,
2438
- orchestratorSessionID,
2439
- producerSessionID: childSessionID ?? "",
2440
- producerTier,
2441
- description: taskDescription?.trim() ? taskDescription : (taskPrompt ?? ""),
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 } : {}),
2445
- dod,
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),
2449
- });
2450
- if (finish.deferred) {
2451
- output.output = appendRouterFooter(typeof output.output === "string" ? output.output : "", finish.footer);
2452
- // The dispatch record is cleared by finishDeferred once its capture settled.
2453
- if (childSessionID) changedFileStore.clear(childSessionID);
2454
- return;
2455
- }
2456
- // QA-2.4-4 / QA-2.4-10: not deferred after all; today's required gate runs below.
2457
- }
2458
- // Same bound as the delegate gate: one deadline per invocation,
2459
- // a withTimeout ceiling, and abort-on-reject so a hung check or
2460
- // grader cannot hold the after-hook (and its process tree) open.
2461
- // The deadline exists before prepareVerification (T2 P0,
2462
- // QA-2.1-4), so preparation counts against gateBudgetMs.
2463
- const { gateBudgetMs } = resolveVerifyBudget(cfg);
2464
- const gateDeadline = createDeadline(gateBudgetMs);
2465
- let verification;
2466
- try {
2467
- verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", effectiveCwd, gateDeadline);
2468
- } catch (error) {
2469
- gateDeadline.dispose();
2470
- throw error;
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;
2477
- const artefact = {
2478
- changedFiles: verification.changedFiles,
2479
- changeBaseline: verification.changeBaseline,
2480
- finalReturnText,
2481
- declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
2482
- producerSessionID: childSessionID ?? "",
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),
2488
- };
2489
-
2490
- // Read-only / research delegation: an auto-inferred, criteria-only DoD on a
2491
- // native Task() that changed no files is exploration, not implementation.
2492
- // There is nothing concrete to verify, so skip rather than grade the
2493
- // findings against the task's own summary, which otherwise appends false
2494
- // "not accepted" notes to legitimate read-only research delegations.
2495
- // Explicit [acceptance] blocks (source != "inferred") and inferred
2496
- // deterministic checks (dod.kind === "deterministic") still verify normally.
2497
- if (
2498
- dod.source === "inferred" &&
2499
- dod.kind === "checker" &&
2500
- artefact.changedFiles.length === 0
2501
- ) {
2502
- gateDeadline.dispose();
2503
- if (childSessionID) changedFileStore.clear(childSessionID);
2504
- changedFileStore.clear(dispatchID);
2505
- return;
2506
- }
2507
-
2508
- const gateGraderSessions = new Set<string>();
2509
- const completedFailures: string[] = [];
2510
- // Keep the native grader unparented on the backend; only depth tracking uses its caller.
2511
- const gateDeps = buildGateDeps(undefined, gateGraderSessions, verification, gateDeadline, false, orchestratorSessionID || null);
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;
2515
- let res;
2516
- try {
2517
- res = await withTimeout(
2518
- accept(
2519
- {
2520
- dod,
2521
- trivial,
2522
- mode: "modeA",
2523
- // Native task has no cwd argument; the acceptance block can supply it.
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 } : {}),
2529
- },
2530
- artefact,
2531
- gateDeps,
2532
- ),
2533
- // What preparation left of the gate budget (QA-2.1-4).
2534
- gateDeadline.remaining(),
2535
- "verification gate",
2536
- );
2537
- } catch (error) {
2538
- gateDeadline.abort(
2539
- error instanceof RouterTimeoutError ? "verification gate timed out" : "verification gate failed",
2540
- );
2541
- if (error instanceof RouterTimeoutError) {
2542
- for (const gsid of gateGraderSessions) {
2543
- try {
2544
- await ctx.client.session.abort({ path: { id: gsid } });
2545
- } catch {
2546
- // best-effort: the gate result stands either way
2547
- }
2548
- }
2549
- }
2550
- res = unverifiableGateResult(
2551
- error instanceof RouterTimeoutError
2552
- ? `verification gate timed out after ${gateBudgetMs}ms`
2553
- : `verification unavailable: ${scrubText(String(error))}`,
2554
- dod.source,
2555
- cfg.enforcement?.verify?.strictUnverifiable,
2556
- completedFailures,
2557
- );
2558
- } finally {
2559
- gateDeadline.dispose();
2560
- }
2561
- // pending.ts R11: a proven-introduced rejection is recorded for this session; a pass
2562
- // on ids an earlier rejection introduced becomes unverifiable (never a new pass/fail).
2563
- res = applyLineage(res, {
2564
- orchestratorSessionID,
2565
- root: verification.snapshot?.root,
2566
- dispatchID,
2567
- dispatchedAt: start.dispatchedAt,
2568
- returnedAt,
2569
- strictUnverifiable: cfg.enforcement?.verify?.strictUnverifiable,
2570
- });
2571
- // QA-3.1-2 / QA-3.1-3: concurrent delegations in this tree; a tool that discarded the baseline.
2572
- res = applyDispatchCaveats(res, verification);
2573
- // M6 (2.1.3): a real verdict of a registered child dispatch feeds the outcome store (v2, engine != static).
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));
2576
- if (!res.accepted && !res.verdict.skipped) {
2577
- const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
2578
- const li = ladder.indexOf(producerTier);
2579
- const nextTier = res.verdict.outcome !== "unverifiable" && li >= 0 && li < ladder.length - 1 ? ladder[li + 1] : null;
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);
2590
- output.output =
2591
- typeof output.output === "string"
2592
- ? output.output + "\n\n" + note
2593
- : note;
2594
- }
2595
- // QA-3.1-18: a clean pass also gets a line (`[router ✓ verified: …]`); a skipped
2596
- // check stays silent unless it carries caveats or notes.
2597
- if (res.accepted && (!res.verdict.skipped || res.verdict.caveats?.length || res.verdict.notes?.length)) {
2598
- output.output += buildAcceptedSuffix(res.verdict.method, res.verdict.outcome, res.verdict.caveats, res.verdict.notes);
2599
- }
2600
- if (childSessionID) changedFileStore.clear(childSessionID);
2601
- changedFileStore.clear(dispatchID);
2602
- } catch {
2603
- // fail-closed: a verification error must NEVER throw out of the after-hook
2604
- }
2605
- }
2606
- }
3106
+ await finishDispatch(input, output, unbannered);
3107
+ // QA-SYNC1-14: a foreground finish settled here; a background call's arguments stay for its finish (child end).
3108
+ if (input?.tool === "task" && typeof input.callID === "string" && !backgroundCalls.has(input.callID)) forgetTaskArgs(input.callID);
2607
3109
  },
2608
3110
 
2609
3111
  // -----------------------------------------------------------------------
@@ -2651,11 +3153,18 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2651
3153
  if (key.startsWith(`${id}:`)) depthBanners.delete(key);
2652
3154
  }
2653
3155
  warnedNoCallID.delete(id);
3156
+ lateBuffer?.forget(id);
2654
3157
  forgetRoleSession(id); // #84 P2.1 (the binding and authority registries are evicted by the v2 adapter)
3158
+ forgetWorkingSet(id); // cross-repo P1.4: the orchestrator's bound repository locations
2655
3159
  // 2.4.2b: a deleted orchestrator's handles, tombstones and lineage records go with it.
2656
3160
  // 2.4.5: so do its background requests and late notices; its run in flight is aborted.
2657
3161
  background?.forgetSession(id);
2658
3162
  pending.forgetSession(id);
3163
+ // QA-2.1-13 (v2 only): its held texts go, and its adoption claim is given back.
3164
+ forgetHeldTexts(id);
3165
+ // QA-SYNC1-14: its calls' arguments and routed-role copies go too.
3166
+ forgetSessionTaskArgs(id);
3167
+ releasePendingClaimOf(id);
2659
3168
  }
2660
3169
  } catch {
2661
3170
  // best-effort: cleanup must never crash a real session
@@ -2889,6 +3398,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2889
3398
 
2890
3399
  // Register commands
2891
3400
  opencodeConfig.command ??= {};
3401
+ // Remember the host command the hook sees; our v2 registration is marked so reloads are not conflicts.
3402
+ userPlanCommandDefined = opencodeConfig.command.plan !== undefined && opencodeConfig.command.plan?.[planCommandMarker] !== true;
2892
3403
  opencodeConfig.command["tiers"] = {
2893
3404
  template: "",
2894
3405
  description: "Show model delegation tiers and rules",
@@ -2956,6 +3467,16 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2956
3467
  description:
2957
3468
  "Model-router controls (e.g., /router enforce off|advisory|enforced, /router overrides, /router models)",
2958
3469
  };
3470
+ if (rolesAtStart && planCommand !== undefined) {
3471
+ if (userPlanCommandDefined) {
3472
+ if (!warnedPlanCommandConflict) {
3473
+ warnedPlanCommandConflict = true;
3474
+ logger.warn("[router] /plan command conflict: preserving the user-defined /plan; router_plan remains available");
3475
+ }
3476
+ } else {
3477
+ opencodeConfig.command.plan = { template: "$ARGUMENTS", description: planCommand.description, [planCommandMarker]: true };
3478
+ }
3479
+ }
2959
3480
  },
2960
3481
 
2961
3482
  // -----------------------------------------------------------------------
@@ -3027,7 +3548,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
3027
3548
  try { enfOn = resolveEnforcementMode({ config: cfg, env: process.env }).mode !== "off"; } catch {}
3028
3549
  // #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.
3029
3550
  const rolesPrompt = isV2Host ? assembleRolesSystemPrompt(cfg, rolesNow(), orchestratorModel, enfOn) : "";
3030
- let systemPrompt = rolesPrompt !== "" ? rolesPrompt : assembleSystemPrompt(cfg, orchestratorModel, enfOn);
3551
+ let systemPrompt = rolesPrompt !== "" ? rolesPrompt : assembleSystemPrompt(cfg, orchestratorModel, enfOn, isV2Host ? "v2" : "v1");
3031
3552
  // A28 (D1): on v1 only, and only with an explicit `routing.roles`, the `R:` line lists those agents as destinations (prose; no model
3032
3553
  // override). Anything else leaves `systemPrompt` the very string it is: the v1 protocol stays byte-identical.
3033
3554
  // Any failure leaves the baseline prompt (QA-2.4-13): the line is an extra, never a reason to lose the protocol.
@@ -3047,27 +3568,34 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
3047
3568
  // a system part that changes would cost the orchestrator its prompt cache (QA-2.4-9).
3048
3569
  advisorNotifier?.poll();
3049
3570
 
3050
- // 2.4.4, section 1.5-20: this orchestrator's still-unverified delegations (at most 5 shown,
3051
- // newest first), as one short block. Nothing is pushed when the list is empty, so the prompt
3052
- // does not grow for sessions that never defer. Orchestrator path only: every child returned
3053
- // above. With background mode on, an entry the queue is verifying right now is still
3054
- // unverified to the orchestrator, so it stays listed until its run settles.
3055
- try {
3056
- // QA-2.4-3: plus background verdicts that did not pass, until router_verify replays them.
3057
- const open = pending.listPending(sessionID, { verifying: background !== undefined });
3058
- const block = buildPendingListBlock(open);
3059
- if (block !== undefined) output.system.push(block);
3060
- } catch (error) {
3061
- logger.warn("[verify] pending list not injected", { error: scrubText(String(error)) });
3062
- }
3063
- // 2.4.5, section 1.5-19 (`background: true` only): late notices of background runs that did
3064
- // not pass, each delivered once (takeNotices marks them delivered).
3065
- if (background !== undefined) {
3571
+ if (turnState !== undefined) {
3572
+ // Phase 1.2 (v2 only): the pending list, the late notices and the route hint are rendered into the turn-state tail
3573
+ // by the context hook, never into the system array (which stays byte-identical between requests). This point is
3574
+ // reached for root sessions only (every child returned above): the flag tells the hook to build the tail.
3575
+ output[TURN_STATE_ROOT] = true;
3576
+ } else {
3577
+ // 2.4.4, section 1.5-20: this orchestrator's still-unverified delegations (at most 5 shown,
3578
+ // newest first), as one short block. Nothing is pushed when the list is empty, so the prompt
3579
+ // does not grow for sessions that never defer. Orchestrator path only: every child returned
3580
+ // above. With background mode on, an entry the queue is verifying right now is still
3581
+ // unverified to the orchestrator, so it stays listed until its run settles.
3066
3582
  try {
3067
- const late = buildLateNoticeBlock(background.takeNotices(sessionID));
3068
- if (late !== undefined) output.system.push(late);
3583
+ // QA-2.4-3: plus background verdicts that did not pass, until router_verify replays them.
3584
+ const open = pending.listPending(sessionID, { verifying: background !== undefined });
3585
+ const block = buildPendingListBlock(open);
3586
+ if (block !== undefined) output.system.push(block);
3069
3587
  } catch (error) {
3070
- logger.warn("[verify] late notices not injected", { error: scrubText(String(error)) });
3588
+ logger.warn("[verify] pending list not injected", { error: scrubText(String(error)) });
3589
+ }
3590
+ // 2.4.5, section 1.5-19 (`background: true` only): late notices of background runs that did
3591
+ // not pass, each delivered once (takeNotices marks them delivered).
3592
+ if (background !== undefined) {
3593
+ try {
3594
+ const late = buildLateNoticeBlock(background.takeNotices(sessionID));
3595
+ if (late !== undefined) output.system.push(late);
3596
+ } catch (error) {
3597
+ logger.warn("[verify] late notices not injected", { error: scrubText(String(error)) });
3598
+ }
3071
3599
  }
3072
3600
  }
3073
3601
  },
@@ -3076,6 +3604,31 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
3076
3604
  // Handle /tiers, /preset, and /budget commands
3077
3605
  // -----------------------------------------------------------------------
3078
3606
  "command.execute.before": async (input: any, output: any) => {
3607
+ if (input.command === "plan") {
3608
+ if (!isV2Host) {
3609
+ // Best-effort on v1 (the command is deliberately unregistered); share the configured-key notice's process guard.
3610
+ if (!userPlanCommandDefined && warnedV2OnlyKeys.size === 0) {
3611
+ warnedV2OnlyKeys.add("routing.executor");
3612
+ logger.warn("[router] the plan executor requires OpenCode v2; ignored: /plan");
3613
+ }
3614
+ return; // No model-visible part on v1.
3615
+ }
3616
+ if (!rolesAtStart || userPlanCommandDefined) return; // Leave unregistered or user-defined /plan commands alone.
3617
+ if (planCommand !== undefined) {
3618
+ const args: string = input.arguments ?? "";
3619
+ const parsed = parsePlanCommand(args);
3620
+ const allowed = parsed.kind !== "call" || await planActionCallerAllowed(
3621
+ input.sessionID, parsed.call.action, "planId" in parsed.call ? parsed.call.planId : undefined,
3622
+ );
3623
+ const text = !allowed
3624
+ ? `[router_plan] ${planCallerRefusal}`
3625
+ : executorAccess?.runtime() === null
3626
+ ? `[router_plan] ${executorAccess.unavailable()}`
3627
+ : planCommand.execute(args);
3628
+ output.parts.push({ type: "text" as const, text });
3629
+ }
3630
+ return;
3631
+ }
3079
3632
  if (input.command === "tiers") {
3080
3633
  try {
3081
3634
  cfg = loadConfig(projectDir);
@@ -3190,6 +3743,25 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
3190
3743
  const parts = args.split(/\s+/).filter(Boolean);
3191
3744
  const sub = (parts[0] ?? "").toLowerCase();
3192
3745
  let text: string;
3746
+ // Cross-repo P4.7 (SD-P4-10): `approve`, `repos`, `revoke` only on v2, in roles mode, with `routing.repoParents`, typed in a
3747
+ // top-level session; otherwise they fall through to the help below, unchanged (S5). Nothing runs in tiers mode or on v1.
3748
+ // The help lists them only where they run; `approvalsCommandsAvailable` returns before any session lookup unless v2 + roles
3749
+ // + parents hold.
3750
+ const approvalsAvailable = await approvalsCommandsAvailable(input.sessionID);
3751
+ const approvalsCmd = approvalsAvailable && APPROVAL_SUBCOMMANDS.has(sub) ? approvalsCommands : undefined;
3752
+ if (approvalsCmd !== undefined && approvalsCmd.isRouterApprovalSubcommand(sub)) {
3753
+ const routing = resolveRolesRouting(cfg, "v2");
3754
+ const result = await approvalsCmd.runRouterApprovals(sub, args.slice((parts[0] ?? "").length), {
3755
+ parents: routing.repoParents,
3756
+ exclude: routing.repoExclude,
3757
+ days: routing.repoApprovalDays,
3758
+ repoDepth: routing.repoDepth,
3759
+ });
3760
+ output.parts.push({ type: "text" as const, text: result.text });
3761
+ // SD-P4-11: the v2 command adapter reloads the role agents before it sends this text on.
3762
+ if (result.change !== undefined) approvalsCmd.markApprovalsChanged(output.parts, result.change);
3763
+ return;
3764
+ }
3193
3765
  if (sub === "models") {
3194
3766
  const catalog = await fetchCatalog();
3195
3767
  const orphans = catalog ? findOrphanedStrongPatterns(cfg, catalog) : [];
@@ -3204,7 +3776,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
3204
3776
  }
3205
3777
  } else {
3206
3778
  // #84 P2.2: `/router` lists the roles in roles mode on v2 (`rolesNow()` is empty in tiers mode and on v1).
3207
- text = buildRouterOutput(cfg, args, projectDir, rolesNow().size > 0 ? rolesNow().values() : undefined);
3779
+ // Match registration at start and v2.ts's executor discovery prerequisites; never advertise an unregistered command.
3780
+ const planAvailable = rolesAtStart && planCommand !== undefined && !userPlanCommandDefined && resolveRolesRouting(cfg, "v2").delegation === "roles"
3781
+ && resolveRouting(cfg, "v2").leases.mode === "enforce" && cfg.enforcement?.verify?.require !== "never"
3782
+ && !locationOutsideWorkRoots(ctx.directory, cfg.routing?.workRoots);
3783
+ text = buildRouterOutput(cfg, args, projectDir, rolesNow().size > 0 ? rolesNow().values() : undefined, approvalsAvailable, planAvailable);
3208
3784
  // On the bare status view, surface stale or missing models inline.
3209
3785
  if (sub === "") {
3210
3786
  text += "\n" + routerStatusLines(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger, projectDir).join("\n");
@@ -3237,6 +3813,931 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
3237
3813
  }
3238
3814
  },
3239
3815
  };
3816
+ /**
3817
+ * What the verification of a finished `task` call ended in (phase 2.1.4.a). The foreground hook ignores it.
3818
+ */
3819
+ type FinishOutcome =
3820
+ | { kind: "none" }
3821
+ | { kind: "deferred"; handle: string }
3822
+ // QA-DF1-16: `gate` is the gate's own verdict (method, outcome, reasons, caveats, notes); a held entry settles with it,
3823
+ // QA-DF1-29: with its pass/outcome set from `verdict` (the tag the gate's decision gives; see heldSettlementOf).
3824
+ | { kind: "required"; verdict: "PASS" | "FAIL" | "UNVERIFIABLE"; detail: string; gate: HeldSettlement }
3825
+ // QA-2.1-1: the gate was not run on purpose (a read-only delegation) or failed; neither is a verdict.
3826
+ | { kind: "skipped"; reason: string }
3827
+ | { kind: "error"; reason: string };
3828
+
3829
+ /**
3830
+ * Phase 2.1.4.a: the verification of a finished `task` call, extracted unchanged from the legacy
3831
+ * `tool.execute.after`. It rewrites `output.output` (footer, forcing note, accepted suffix) exactly as before;
3832
+ * the hook calls it in the foreground, and the v2 finish API (below) calls it for background completions.
3833
+ */
3834
+ async function finishDispatch(
3835
+ input: any,
3836
+ output: any,
3837
+ unbannered: { output: unknown } | undefined,
3838
+ // QA-SYNC1-2: `workRoot`, the journaled work root of a dispatch restored after a restart (its routed-role record is gone).
3839
+ // QA-SYNC1-3: `unattributedWriters`, those a restored held entry journaled (the live tally is gone after a restart).
3840
+ extra?: {
3841
+ delta?: DispatchDelta; dod?: ReturnType<typeof buildDelegationDoD>; graderParentSessionID?: string; workRoot?: string;
3842
+ unattributedWriters?: readonly string[];
3843
+ /** QA-SYNC1-3: the journaled dispatch-time head of a restored held entry; the branch check compares it as before. */
3844
+ restoredHead?: DispatchHeadState;
3845
+ /**
3846
+ * QA-SYNC1-3: never deferred. A restored held entry was held because its verification was required at dispatch (only a
3847
+ * required verification is held); it settles in place, never re-classified under the restarted process into a deferral.
3848
+ */
3849
+ noDefer?: true;
3850
+ },
3851
+ ): Promise<FinishOutcome> {
3852
+ let outcome: FinishOutcome = { kind: "none" };
3853
+ if (typeof input?.tool === "string") {
3854
+ let mode = "off";
3855
+ try {
3856
+ mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
3857
+ } catch {
3858
+ // fall through with mode "off"
3859
+ }
3860
+ const requireMode = cfg.enforcement?.verify?.require;
3861
+ if (shouldVerifyTask(input.tool, mode, requireMode)) {
3862
+ try {
3863
+ // pending.ts R11: the producer's changes landed by now.
3864
+ const returnedAt = Date.now();
3865
+ const { finalReturnText, childSessionID } = parseTaskResult(unbannered ? { ...output, output: unbannered.output } : output);
3866
+ const producerTier =
3867
+ typeof input?.args?.subagent_type === "string"
3868
+ ? input.args.subagent_type
3869
+ : "";
3870
+ // QA-2.1-17 (v2 only): a gate re-run after a restart verifies the DoD its restored pending entry persisted.
3871
+ const dod = extra?.dod ?? buildDelegationDoD({
3872
+ prompt: input?.args?.prompt,
3873
+ description: input?.args?.description,
3874
+ });
3875
+ // DF2-F1: a role dispatch is verified in its verification root (capture, change set, checks, deferral); a requested
3876
+ // cwd outside that root is refused by the gate below, never deferred to run there later.
3877
+ const scope = verificationScopeOf(input.callID, input?.args, dod, extra?.workRoot);
3878
+ const cwdSource = requestedVerificationCwdSource(input?.args?.cwd, dod.cwd);
3879
+ const effectiveCwd = scope.cwd;
3880
+ const dispatchID = `task:${input.sessionID}:${input.callID}`;
3881
+ // #84 QA-G-B-2-1: a routed role dispatch keeps its child's verification lineage; a resume that CARRIES the acceptance of an
3882
+ // earlier attempt is gated at once (never deferred) on the child's cumulative change set (roleAttemptVerification).
3883
+ // QA-SYNC1-1: a background finish runs after the adapter forgot its record; the copy taken with the call's arguments stands in.
3884
+ const routedRole = typeof input.callID === "string" ? routedRoleFor(input.callID) : undefined;
3885
+ const carriedRole = routedRole?.carried === true && childSessionID !== null && routedRole.resumeID === childSessionID;
3886
+ // Cross-repo P2a.3 (v2 only): where each check of a routed role dispatch runs. Tier dispatches resolve nothing.
3887
+ // P2e.6: valid per-check `cwd=`/`scope=` keys may be deferred (the placements travel with the handle, and router_verify
3888
+ // runs each check where it was placed); only a refusal is verified at once, below.
3889
+ const placement = routedRole === undefined ? undefined : resolveCheckPlacements(dod, scope, { inReadSet: roleReadSetFor(routedRole) });
3890
+ // P2b.7 (OD1=B, v2 only): a tier dispatch with a per-check `cwd=` is unverifiable (the gate refuses it); it is never deferred.
3891
+ const tierRefusal = routedRole === undefined && ctx.routerHost === "v2" ? tierCheckCwdRefusal(dod) : undefined;
3892
+ // P2e.6: a refused placement or the OD1 tier refusal is certain now: verified at once, never deferred.
3893
+ const placementRefused = tierRefusal !== undefined || placement?.refused !== undefined;
3894
+ const orchestratorSessionID = typeof input.sessionID === "string" ? input.sessionID : "";
3895
+ const taskPrompt = typeof input?.args?.prompt === "string" ? input.args.prompt : undefined;
3896
+ const taskDescription = typeof input?.args?.description === "string" ? input.args.description : undefined;
3897
+ // 2.4.2b: the mode the orchestrator chose at dispatch (never the subagent's text).
3898
+ const start = takeDispatch(dispatchID, dispatchDirectiveText(taskPrompt, taskDescription));
3899
+ const trivial = childSessionID
3900
+ ? sessionStore.isTrivial(childSessionID)
3901
+ : false;
3902
+ // QA-2.4-10: `trivial` as the gate sees it below; a dispatch the gate would skip is not
3903
+ // deferred (isDeferred). QA-2.4-2: only a proven root orchestrator defers.
3904
+ // B2: the reason a deferred finish refused for a branch switch, carried into the artefact below.
3905
+ let deferredSwitch: string | undefined;
3906
+ if (extra?.noDefer !== true && !scope.outside && !carriedRole && !placementRefused && isDeferred(dod, start.directives, trivial) && await isProvenRootCaller(orchestratorSessionID)) {
3907
+ // Section 1.5-16: no gate, no test process; the result goes back now with the
3908
+ // footer, which is appended last and never says accepted or verified.
3909
+ const finish = await finishDeferred(changedFileStore, {
3910
+ dispatchID,
3911
+ orchestratorSessionID,
3912
+ producerSessionID: childSessionID ?? "",
3913
+ producerTier,
3914
+ description: taskDescription?.trim() ? taskDescription : (taskPrompt ?? ""),
3915
+ cwd: effectiveCwd,
3916
+ // I2 (P2.3): the change observation stays in W; the registration's cwd above is the check base (F5).
3917
+ ...(scope.workRoot !== undefined ? { captureRoot: captureRootOf(scope) } : {}),
3918
+ // #84 P3.3 DF2-F1 (fix-1 review nit): router_verify's gate re-checks containment in the role's work root.
3919
+ ...(scope.workRoot !== undefined ? { workRoot: scope.workRoot } : {}),
3920
+ dod,
3921
+ dispatchedAt: start.dispatchedAt,
3922
+ // Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule): router_verify judges the budget at return.
3923
+ budget: captureBudget(childSessionID ?? "", childSessionID ? sessionStore.readCapReached(childSessionID) : undefined),
3924
+ // Cross-repo P2e.6: the checks' placements (registered with the handle), and the full scope on v2 (OD-P2e-2).
3925
+ ...(placement?.placements !== undefined ? { placements: placement.placements } : {}),
3926
+ ...(fullScopeOf(cfg) ? { fullScope: true } : {}),
3927
+ // Phase 2.1.4.b: the change set frozen at child end (background completions only).
3928
+ ...(extra?.delta !== undefined ? { delta: extra.delta } : {}),
3929
+ });
3930
+ if (finish.deferred) {
3931
+ output.output = appendRouterFooter(typeof output.output === "string" ? output.output : "", finish.footer);
3932
+ // The dispatch record is cleared by finishDeferred once its capture settled.
3933
+ if (childSessionID) changedFileStore.clear(childSessionID);
3934
+ outcome = { kind: "deferred", handle: finish.handle };
3935
+ return outcome;
3936
+ }
3937
+ if (finish.reason === "branch-switched") deferredSwitch = finish.detail;
3938
+ // QA-2.4-4 / QA-2.4-10: not deferred after all; today's required gate runs below.
3939
+ }
3940
+ // Same bound as the delegate gate: one deadline per invocation,
3941
+ // a withTimeout ceiling, and abort-on-reject so a hung check or
3942
+ // grader cannot hold the after-hook (and its process tree) open.
3943
+ // The deadline exists before prepareVerification (T2 P0,
3944
+ // QA-2.1-4), so preparation counts against gateBudgetMs.
3945
+ const { gateBudgetMs } = resolveVerifyBudget(cfg);
3946
+ const gateDeadline = createDeadline(gateBudgetMs);
3947
+ let verification;
3948
+ try {
3949
+ // Cross-repo P3a (D23 as amended, QA C1): the dispatch's start (takeDispatch), the `since` of W's ignored-module
3950
+ // listing. A start that was never remembered reads as now (the return), which lists nothing older: never stale inputs.
3951
+ verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", captureRootOf(scope), gateDeadline, start.dispatchedAt, extra?.restoredHead, isV2Host ? orchestratorSessionID : undefined);
3952
+ } catch (error) {
3953
+ gateDeadline.dispose();
3954
+ throw error;
3955
+ }
3956
+ // QA2 F4: a switch the deferred finish saw (and this gate's own read missed) is part of this attempt before the role
3957
+ // lineage records it; its change set may hold the other branch's commits, so it is unavailable.
3958
+ if (deferredSwitch !== undefined && verification.branchSwitch === undefined) {
3959
+ verification = { ...verification, branchSwitch: deferredSwitch, changeBaseline: "unavailable" as const };
3960
+ }
3961
+ // QA-SYNC1-3: a restored held entry's journaled unattributed writers count as the lineage's own.
3962
+ const restoredWriters = extra?.unattributedWriters;
3963
+ if (restoredWriters !== undefined && restoredWriters.length > 0) {
3964
+ verification = { ...verification, unattributedWriters: [...new Set([...(verification.unattributedWriters ?? []), ...restoredWriters])].sort() };
3965
+ }
3966
+ // #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
3967
+ // changed since the attempt that introduced the carried block, against that attempt's reference.
3968
+ if (routedRole !== undefined && childSessionID) verification = roleAttemptVerification(childSessionID, verification, { carried: carriedRole });
3969
+ // #84 P2.1: a role agent follows the return contract (handoff 26; roles mode only).
3970
+ const roleProducer = roleSpecOf(producerTier) !== undefined;
3971
+ const artefact = {
3972
+ changedFiles: verification.changedFiles,
3973
+ changeBaseline: verification.changeBaseline,
3974
+ ...(verification.snapshot?.root !== undefined ? { changeRoot: verification.snapshot.root } : {}),
3975
+ ...((verification.branchSwitch ?? deferredSwitch) !== undefined ? { branchSwitch: verification.branchSwitch ?? deferredSwitch } : {}),
3976
+ ...(verification.unattributedWriters !== undefined && verification.unattributedWriters.length > 0
3977
+ ? { unattributedWriters: verification.unattributedWriters } : {}),
3978
+ ...(verification.perimeter !== undefined ? { perimeter: verification.perimeter } : {}),
3979
+ finalReturnText,
3980
+ declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
3981
+ producerSessionID: childSessionID ?? "",
3982
+ producerTier,
3983
+ ...(roleProducer ? { returnContract: true } : {}),
3984
+ // Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule; every mode): the guard's budget state when the task
3985
+ // returned, not when the gate runs. Without a stop it judges like the live read it replaces.
3986
+ budget: captureBudget(childSessionID ?? "", childSessionID ? sessionStore.readCapReached(childSessionID) : undefined),
3987
+ };
3988
+
3989
+ // Read-only / research delegation: an auto-inferred, criteria-only DoD on a
3990
+ // native Task() that changed no files is exploration, not implementation.
3991
+ // There is nothing concrete to verify, so skip rather than grade the
3992
+ // findings against the task's own summary, which otherwise appends false
3993
+ // "not accepted" notes to legitimate read-only research delegations.
3994
+ // Explicit [acceptance] blocks (source != "inferred") and inferred
3995
+ // deterministic checks (dod.kind === "deterministic") still verify normally.
3996
+ if (
3997
+ dod.source === "inferred" &&
3998
+ dod.kind === "checker" &&
3999
+ artefact.changedFiles.length === 0
4000
+ ) {
4001
+ gateDeadline.dispose();
4002
+ if (childSessionID) changedFileStore.clear(childSessionID);
4003
+ changedFileStore.clear(dispatchID);
4004
+ outcome = { kind: "skipped", reason: "read-only delegation: no files changed and no explicit acceptance to verify" };
4005
+ return outcome;
4006
+ }
4007
+
4008
+ const gateGraderSessions = new Set<string>();
4009
+ const completedFailures: string[] = [];
4010
+ // Keep the native grader unparented on the backend; only depth tracking uses its caller. DF-1-3 (v2 finish API only,
4011
+ // absent on the v1 after-hook): a background completion names the parent whose retained context launches the grader.
4012
+ const gateDeps = buildGateDeps(extra?.graderParentSessionID, gateGraderSessions, verification, gateDeadline, false, orchestratorSessionID || null);
4013
+ gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
4014
+ // #84 QA-G-B-2-1: a carried acceptance never passes on a testsPass/lintClean that ran no process.
4015
+ if (carriedRole) gateDeps.deterministic.noAffectedUnverifiable = CARRIED_NO_PROCESS_REASON;
4016
+ let res;
4017
+ try {
4018
+ res = await withTimeout(
4019
+ accept(
4020
+ {
4021
+ dod,
4022
+ trivial,
4023
+ mode: "modeA",
4024
+ // Native task has no cwd argument; the acceptance block can supply it.
4025
+ ...(scope.requested ? { cwd: scope.requested } : {}),
4026
+ ...(scope.workRoot !== undefined ? { workRoot: scope.workRoot } : {}),
4027
+ ...(scope.refused !== undefined ? { refusedCwd: scope.refused } : {}),
4028
+ // Fix-1 review nit: a refusal names where the cwd came from (the call's `cwd`, else the block's `cwd:`).
4029
+ ...(scope.workRoot !== undefined && cwdSource !== undefined ? { cwdSource } : {}),
4030
+ // Cross-repo P2b.5 (v2 only): where each check of a routed role dispatch runs, or the check the router refused.
4031
+ ...(placement?.placements !== undefined ? { checkPlacements: placement.placements } : {}),
4032
+ ...(placement?.refused !== undefined ? { refusedCheck: placement.refused } : tierRefusal !== undefined ? { refusedCheck: tierRefusal } : {}),
4033
+ },
4034
+ artefact,
4035
+ gateDeps,
4036
+ ),
4037
+ // What preparation left of the gate budget (QA-2.1-4).
4038
+ gateDeadline.remaining(),
4039
+ "verification gate",
4040
+ );
4041
+ } catch (error) {
4042
+ gateDeadline.abort(
4043
+ error instanceof RouterTimeoutError ? "verification gate timed out" : "verification gate failed",
4044
+ );
4045
+ if (error instanceof RouterTimeoutError) {
4046
+ for (const gsid of gateGraderSessions) {
4047
+ try {
4048
+ await ctx.client.session.abort({ path: { id: gsid } });
4049
+ } catch {
4050
+ // best-effort: the gate result stands either way
4051
+ }
4052
+ }
4053
+ }
4054
+ res = unverifiableGateResult(
4055
+ error instanceof RouterTimeoutError
4056
+ ? `verification gate timed out after ${gateBudgetMs}ms`
4057
+ : `verification unavailable: ${scrubText(String(error))}`,
4058
+ dod.source,
4059
+ cfg.enforcement?.verify?.strictUnverifiable,
4060
+ completedFailures,
4061
+ );
4062
+ } finally {
4063
+ gateDeadline.dispose();
4064
+ }
4065
+ // pending.ts R11: a proven-introduced rejection is recorded for this session; a pass
4066
+ // on ids an earlier rejection introduced becomes unverifiable (never a new pass/fail).
4067
+ res = applyLineage(res, {
4068
+ orchestratorSessionID,
4069
+ root: verification.snapshot?.root,
4070
+ dispatchID,
4071
+ dispatchedAt: start.dispatchedAt,
4072
+ returnedAt,
4073
+ strictUnverifiable: cfg.enforcement?.verify?.strictUnverifiable,
4074
+ });
4075
+ // QA-3.1-2 / QA-3.1-3: concurrent delegations in this tree; a tool that discarded the baseline.
4076
+ res = applyDispatchCaveats(res, verification);
4077
+ // M6 (2.1.3): a real verdict of a registered child dispatch feeds the outcome store (v2, engine != static).
4078
+ // #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.
4079
+ if (childSessionID && !res.verdict.skipped) ingest?.onVerdict(childSessionID, verdictOf(res.verdict), verdictGraderOf(res.verdict));
4080
+ // A gated child must not stay on medium when its return gate cannot verify it, even if accepted with a caveat.
4081
+ // Strict children and incomplete returns keep their existing behaviour and text.
4082
+ if (isV2Host && routedRole?.gated === true && childSessionID && !res.verdict.skipped &&
4083
+ res.verdict.outcome === "unverifiable" && !isIncompleteVerdict(res.verdict)) {
4084
+ roleEscalationAfterFail(cfg, childSessionID, orchestratorSessionID);
4085
+ }
4086
+ if (!res.accepted && !res.verdict.skipped) {
4087
+ const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
4088
+ const li = ladder.indexOf(producerTier);
4089
+ const nextTier = res.verdict.outcome !== "unverifiable" && li >= 0 && li < ladder.length - 1 ? ladder[li + 1] : null;
4090
+ // Handoff 25, R7 (I1/I8 exemption: the I7 budget-incomplete rule): absent when false, so the note is unchanged.
4091
+ const incomplete = isIncompleteVerdict(res.verdict);
4092
+ let note = scrubText(buildForcingNote(res.verdict.reasons, { producerTier, nextTier, ...(incomplete ? { incomplete: true } : {}) }));
4093
+ // P-8 (handoff 39): a role agent is resumed on a higher tier of its range, never re-run on a tier agent.
4094
+ // QA-P21-1-4: only after a FAIL (an unverifiable result keeps the generic line: there is nothing to escalate on).
4095
+ // QA-P21-2-2: the hint promises the raise, and records it for this parent's next resume of the child.
4096
+ const roleHint = roleProducer && !incomplete && res.verdict.outcome === "fail" && childSessionID
4097
+ ? roleEscalationAfterFail(cfg, childSessionID, orchestratorSessionID) : null;
4098
+ const genericNext = "NEXT: address the above and re-run the delegation; do not treat the prior result as complete.";
4099
+ if (roleHint !== null && note.endsWith(genericNext)) note = note.slice(0, note.length - genericNext.length) + scrubText(roleHint);
4100
+ output.output =
4101
+ typeof output.output === "string"
4102
+ ? output.output + "\n\n" + note
4103
+ : note;
4104
+ }
4105
+ // QA-3.1-18: a clean pass also gets a line (`[router ✓ verified: …]`); a skipped
4106
+ // check stays silent unless it carries caveats or notes.
4107
+ if (res.accepted && (!res.verdict.skipped || res.verdict.caveats?.length || res.verdict.notes?.length)) {
4108
+ output.output += buildAcceptedSuffix(res.verdict.method, res.verdict.outcome, res.verdict.caveats, res.verdict.notes);
4109
+ }
4110
+ if (childSessionID) changedFileStore.clear(childSessionID);
4111
+ changedFileStore.clear(dispatchID);
4112
+ outcome = {
4113
+ kind: "required",
4114
+ // DF-1-3: the tag follows the outcome; an accepted unverifiable result (gate.ts, not strictUnverifiable) is UNVERIFIABLE.
4115
+ verdict: res.verdict.outcome === "unverifiable" ? "UNVERIFIABLE" : res.accepted ? "PASS" : "FAIL",
4116
+ detail: res.verdict.reasons.join("; "),
4117
+ // QA-DF1-16: the gate's real verdict, so router_verify on a held handle reports what the posted text says.
4118
+ gate: { verdict: res.verdict, retryable: false },
4119
+ };
4120
+ } catch (error) {
4121
+ // fail-closed: a verification error must NEVER throw out of the after-hook. QA-2.1-1: it is logged and reported as an
4122
+ // `error` outcome, so a held dispatch posts UNVERIFIABLE with this reason instead of a PASS.
4123
+ logger.warn("[router] verification failed in the after-hook", { tool: input?.tool, error: describeError(error) });
4124
+ outcome = { kind: "error", reason: `verification unavailable: ${scrubText(String(error))}` };
4125
+ }
4126
+ }
4127
+ }
4128
+ return outcome;
4129
+ }
4130
+
4131
+ /**
4132
+ * Phase 2.1.4.a (v2 only): the `task` arguments of a call in flight, kept for FinishApi.verificationFor / finish. QA-SYNC1-14:
4133
+ * forgotten when the call's finish settles (foreground, held, deferred or immediate) and with its parent session.
4134
+ */
4135
+ /**
4136
+ * QA-SYNC1-14 (test seam): `routerTaskArgsBounds` overrides the two bounds below (positive integers, `hard` ≥ `max`); anything
4137
+ * else keeps the production defaults.
4138
+ */
4139
+ const taskArgsBounds = (ctx as RouterPluginInput & { routerTaskArgsBounds?: { max?: number; hard?: number } }).routerTaskArgsBounds;
4140
+ const boundOr = (value: number | undefined, fallback: number): number =>
4141
+ typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
4142
+ const MAX_TASK_ARGS = boundOr(taskArgsBounds?.max, 1000);
4143
+ /** QA-SYNC1-14: the bound past which even a call with a background record is evicted (= MAX_HOLDS_GLOBAL, background.ts). */
4144
+ const MAX_TASK_ARGS_HARD = Math.max(MAX_TASK_ARGS, boundOr(taskArgsBounds?.hard, 10_000));
4145
+ const taskArgsByCall = new Map<string, Record<string, unknown>>();
4146
+ /** QA-2.1-7: the parent session of a call in flight (same keys and bound), so captureDelta finds the dispatch record. */
4147
+ const taskParentByCall = new Map<string, string>();
4148
+ /**
4149
+ * QA-SYNC1-1/-2: the routed-role record of a call in flight (same keys and bound), copied when its arguments are remembered.
4150
+ * The adapter forgets its own record once a background acknowledgement returns; the finish (child end) still needs it.
4151
+ */
4152
+ const routedRoleByCall = new Map<string, RoutedRoleSnapshot>();
4153
+ /**
4154
+ * QA-SYNC1-1: the routed-role record of `callID`: the dispatch module's while it keeps it, else the copy kept until the finish.
4155
+ * QA-SYNC1-13: after a restart, the snapshot a restored held entry journaled (finishRestored puts it in `routedRoleByCall`).
4156
+ */
4157
+ function routedRoleFor(callID: string): RoutedRoleSnapshot | undefined {
4158
+ return routedRoleOf(callID) ?? routedRoleByCall.get(callID);
4159
+ }
4160
+ /**
4161
+ * QA-SYNC1-6: finishDispatch verifies this dispatch at once, never deferred: a cwd outside the role's verification root, a refused
4162
+ * check placement, or (v2) a tier dispatch's per-check `cwd=` (OD1=B). The same rules as there; a failed read counts as at once.
4163
+ * QA-SYNC1-12: a carried resume too (finishDispatch never defers it; its resumeID is known at dispatch).
4164
+ */
4165
+ function verifiedAtOnce(callID: string, args: Record<string, unknown>, dod: ReturnType<typeof buildDelegationDoD>): boolean {
4166
+ try {
4167
+ const routed = routedRoleFor(callID);
4168
+ if (routed === undefined) return ctx.routerHost === "v2" && tierCheckCwdRefusal(dod) !== undefined;
4169
+ if (routed.carried === true) return true;
4170
+ const scope = verificationScopeOf(callID, args, dod);
4171
+ if (scope.outside) return true;
4172
+ return resolveCheckPlacements(dod, scope, { inReadSet: roleReadSetFor(routed) }).refused !== undefined;
4173
+ } catch (error) {
4174
+ logger.warn("[router] the check placements of a dispatch could not be read", { callID, error: describeError(error) });
4175
+ return true;
4176
+ }
4177
+ }
4178
+ function rememberTaskArgs(input: any, output: any): void {
4179
+ if (!isV2Host || input?.tool !== "task" || typeof input.callID !== "string") return;
4180
+ const args = output?.args;
4181
+ if (typeof args !== "object" || args === null) return;
4182
+ taskArgsByCall.set(input.callID, { ...(args as Record<string, unknown>) });
4183
+ if (typeof input.sessionID === "string") taskParentByCall.set(input.callID, input.sessionID);
4184
+ // QA-SYNC1-1: route() ran before this hook (v2 adapter), so the routed-role record is current here.
4185
+ const routed = routedRoleOf(input.callID);
4186
+ if (routed === undefined) routedRoleByCall.delete(input.callID);
4187
+ else routedRoleByCall.set(input.callID, routed);
4188
+ // QA-SYNC1-14: oldest first, but never a call that still has a held or in-flight background record (its finish needs the
4189
+ // arguments and the routed copy), nor the call just remembered; those are bounded by the background bounds instead.
4190
+ while (taskArgsByCall.size > MAX_TASK_ARGS) {
4191
+ let oldest: string | undefined;
4192
+ for (const key of taskArgsByCall.keys()) {
4193
+ if (key !== input.callID && !backgroundCalls.has(key)) { oldest = key; break; }
4194
+ }
4195
+ // A hard ceiling still holds (= MAX_HOLDS_GLOBAL): past it the oldest background call goes too, as before.
4196
+ if (oldest === undefined && taskArgsByCall.size > MAX_TASK_ARGS_HARD) {
4197
+ for (const key of taskArgsByCall.keys()) {
4198
+ if (key !== input.callID) { oldest = key; break; }
4199
+ }
4200
+ if (oldest !== undefined) backgroundCalls.delete(oldest);
4201
+ }
4202
+ if (oldest === undefined) break;
4203
+ taskArgsByCall.delete(oldest);
4204
+ taskParentByCall.delete(oldest);
4205
+ routedRoleByCall.delete(oldest);
4206
+ }
4207
+ }
4208
+ /**
4209
+ * QA-SYNC1-14: the calls with a held or in-flight background record (the adapter reserved a held slot for them, or read their
4210
+ * dispatch to journal an acknowledged background attempt); the FIFO bound above skips them. Forgotten with the call's arguments.
4211
+ */
4212
+ const backgroundCalls = new Set<string>();
4213
+ function forgetTaskArgs(callID: string): void {
4214
+ taskArgsByCall.delete(callID);
4215
+ taskParentByCall.delete(callID);
4216
+ routedRoleByCall.delete(callID);
4217
+ backgroundCalls.delete(callID);
4218
+ }
4219
+ /** QA-SYNC1-14: a deleted session's calls are never finished; their arguments and routed copies go with it. */
4220
+ function forgetSessionTaskArgs(sessionID: string): void {
4221
+ for (const [callID, parent] of [...taskParentByCall]) if (parent === sessionID) forgetTaskArgs(callID);
4222
+ }
4223
+
4224
+ // ---- Phase 2.1.4.a (v2 only): the finish API ------------------------------------------------------
4225
+ /**
4226
+ * The foreground-equivalent text of a held dispatch, kept from the end of its gate until onVerdict posts it. QA-2.1-13:
4227
+ * bounded (oldest first; an evicted hold posts the generic verdict line) and forgotten with its parent session.
4228
+ * QA-DF1-16: `post` is the tag and reason the held gate posts with its text (its settled verdict keeps every reason).
4229
+ */
4230
+ type HeldPost = { readonly verdict: "PASS" | "FAIL" | "UNVERIFIABLE"; readonly reason?: string };
4231
+ const heldTexts = new Map<string, { readonly sessionID: string; readonly text: string; readonly post?: HeldPost }>();
4232
+ /** = MAX_HOLDS_GLOBAL (background.ts): there are never more live holds than this. */
4233
+ const MAX_HELD_TEXTS = 10_000;
4234
+ function rememberHeldText(handle: string, sessionID: string, text: string, post?: HeldPost): void {
4235
+ heldTexts.delete(handle);
4236
+ heldTexts.set(handle, { sessionID, text, ...(post === undefined ? {} : { post }) });
4237
+ while (heldTexts.size > MAX_HELD_TEXTS) {
4238
+ const oldest = heldTexts.keys().next();
4239
+ if (oldest.done === true) break;
4240
+ heldTexts.delete(oldest.value);
4241
+ }
4242
+ }
4243
+ function forgetHeldTexts(sessionID: string): void {
4244
+ for (const [handle, held] of heldTexts) if (held.sessionID === sessionID) heldTexts.delete(handle);
4245
+ }
4246
+ let heldSink: HeldSink | undefined;
4247
+ /**
4248
+ * QA-2.1-21: the held gates `finish` starts without awaiting them, each with its verdict post. `finishApi.idle` (the
4249
+ * adapter's settled seam) and `dispose` (bounded) wait for them.
4250
+ */
4251
+ const heldGates = new Set<Promise<void>>();
4252
+ /** QA-2.1-21: how long `dispose` waits for running held gates before the registry and the wiring go. */
4253
+ const HELD_GATES_DISPOSE_BOUND_MS = 5_000;
4254
+ function trackHeldGate(gate: Promise<unknown>): void {
4255
+ const tracked = gate.then(
4256
+ () => undefined,
4257
+ (error: unknown) => logger.warn("[router] held gate failed", { error: describeError(error) }),
4258
+ );
4259
+ heldGates.add(tracked);
4260
+ void tracked.finally(() => heldGates.delete(tracked));
4261
+ }
4262
+ /** Resolves once no held gate runs (a gate started meanwhile is waited for too). Never rejects. */
4263
+ async function heldGatesIdle(): Promise<void> {
4264
+ while (heldGates.size > 0) await Promise.allSettled([...heldGates]);
4265
+ }
4266
+ async function waitHeldGates(boundMs: number): Promise<void> {
4267
+ if (heldGates.size === 0) return;
4268
+ let timer: ReturnType<typeof setTimeout> | undefined;
4269
+ try {
4270
+ await Promise.race([heldGatesIdle(), new Promise<void>((resolve) => { timer = setTimeout(resolve, boundMs); })]);
4271
+ } finally {
4272
+ if (timer !== undefined) clearTimeout(timer);
4273
+ }
4274
+ }
4275
+
4276
+ /** pending.onVerdict: a held entry's verdict goes to the parent through the HeldSink (v2 adapter). */
4277
+ function postHeldVerdict(entry: PendingEntry, result: SettledVerification): void {
4278
+ // QA-2.1-31: settled by `settleHeldDirect` after the adapter posted the verdict itself.
4279
+ if (directlySettled.has(entry.handle)) return;
4280
+ if (entry.hold === undefined || heldSink === undefined) return;
4281
+ // QA-DF1-16: a held gate's text posts with the tag and reason it was written for (unchanged by its full settled verdict).
4282
+ const held = heldTexts.get(entry.handle);
4283
+ const verdict = held?.post?.verdict ?? heldVerdictKind(result.verdict.outcome, result.verdict.pass);
4284
+ const reason = held?.post !== undefined ? held.post.reason : result.verdict.reasons[0];
4285
+ const text = held?.text ?? `[router] ${entry.handle}: verification ended ${verdict}${reason !== undefined ? ` — ${scrubText(reason)}` : ""}`;
4286
+ heldTexts.delete(entry.handle);
4287
+ heldSink.verdict(entry.handle, { verdict, text, ...(reason !== undefined ? { reason } : {}) }).catch((error: unknown) => {
4288
+ logger.warn("[router] held verdict not posted", { handle: entry.handle, error: describeError(error) });
4289
+ });
4290
+ }
4291
+
4292
+ function heldVerdictKind(outcome: string | undefined, pass: boolean): "PASS" | "FAIL" | "UNVERIFIABLE" {
4293
+ if (outcome === "unverifiable") return "UNVERIFIABLE";
4294
+ return pass ? "PASS" : "FAIL";
4295
+ }
4296
+
4297
+ /**
4298
+ * QA-2.1-1: the verdict a held dispatch posts for what its gate ended in. Only a `required` outcome carries a gate verdict;
4299
+ * every other outcome is UNVERIFIABLE with its reason, and `line` is the router line appended to the posted text.
4300
+ */
4301
+ function heldOutcomeOf(outcome: FinishOutcome): { verdict: "PASS" | "FAIL" | "UNVERIFIABLE"; reasons: string[]; line?: string } {
4302
+ if (outcome.kind === "required") return { verdict: outcome.verdict, reasons: outcome.detail !== "" ? [outcome.detail] : [] };
4303
+ const reason =
4304
+ outcome.kind === "skipped" ? `not verified: ${outcome.reason}`
4305
+ : outcome.kind === "error" ? outcome.reason
4306
+ : outcome.kind === "deferred" ? `not verified: deferred to router_verify as ${outcome.handle}`
4307
+ : "not verified: verification is not required for this dispatch";
4308
+ const scrubbed = scrubText(reason);
4309
+ return { verdict: "UNVERIFIABLE", reasons: [scrubbed], line: `[router] UNVERIFIABLE — ${scrubbed}` };
4310
+ }
4311
+
4312
+ /** The `task` result the host would have handed the hook: the child's id and its final text. */
4313
+ function taskOutputText(childSessionID: string, text: string): string {
4314
+ return `task_id: ${childSessionID} (for resuming to continue this task if needed)\n\n<task_result>\n${text}\n</task_result>`;
4315
+ }
4316
+
4317
+ // ONE journal (memo §11): the same `pending.jsonl` the pending store and the held results append to. Absent on v1 (accepts and forgets).
4318
+ const processedKeys = new Set<string>();
4319
+ let dormantSessions = new Map<string, DormantSession>();
4320
+ // QA-2.1-33: registered only now that `pending` and `dormantSessions` exist: another instance's recreate may call it at any time.
4321
+ pendingFile?.setSnapshotProvider(journalSnapshot);
4322
+ const sharedJournal: InflightJournal = {
4323
+ async append(record, opts) {
4324
+ if (record.kind === "processed") {
4325
+ const key = processedKeyOf(record);
4326
+ if (key !== undefined) processedKeys.add(key);
4327
+ }
4328
+ if (pendingFile === undefined) return;
4329
+ // QA-2.1-19: the live owner claims the parent session (pid + instance token) at its first `inflight`/`hold` write, so
4330
+ // no other instance or process adopts it (and posts or wakes for a child that is still running here).
4331
+ if (record.kind === "inflight" || record.kind === "hold") {
4332
+ const parent = typeof record.parentSessionID === "string" ? record.parentSessionID : typeof record.parent === "string" ? record.parent : undefined;
4333
+ if (parent !== undefined && !claimSessionOnce(parent)) {
4334
+ logger.warn("[router] background: another live instance holds the claim of this session", { sessionID: parent });
4335
+ }
4336
+ }
4337
+ // `inflight` and `hold` records are fsync'd (memo §11.2); the rest only when the caller asks.
4338
+ const fsync = opts?.fsync === true || record.kind === "inflight" || record.kind === "hold";
4339
+ // QA-2.1-23: a vanished journal (or state directory) fails the append; it is never recreated behind the reload's back
4340
+ // (QA-2.1-16: `recreateJournal` rewrites it from the in-memory state).
4341
+ await pendingFile.append(record, fsync ? { fsync: true } : undefined);
4342
+ },
4343
+ hasProcessed: (key) => processedKeys.has(key),
4344
+ };
4345
+ /** QA-2.1-17: an UNVERIFIABLE line for a finish after a restart that has nothing to verify with. */
4346
+ const RESTART_DATA_LOST = "verification data lost in restart";
4347
+ /** QA-SYNC1-3: how long a held registration waits for the dispatch-time head read (started at dispatch, normally settled). */
4348
+ const HELD_HEAD_READ_MS = 2_000;
4349
+ /** QA-2.1-31: handles whose restored pending entry the adapter settled after posting the verdict itself (no second post). */
4350
+ const directlySettled = new Set<string>();
4351
+ type HeldClaim = Extract<ReturnType<typeof pending.markVerifying>, { kind: "claimed" }>;
4352
+ type HeldSettlement = Parameters<HeldClaim["settle"]>[0];
4353
+ type HeldScratch = { output: string; title: string; metadata: Record<string, unknown> };
4354
+ /**
4355
+ * QA-DF1-16: what a held entry settles with: a gate verdict as the gate reached it (method, reasons, caveats, notes), anything
4356
+ * else as `heldVerification`. QA-DF1-29: its `pass`/`outcome` are those of the posted tag (the gate's decision, `accepted`, which
4357
+ * a trivial skip or `strictUnverifiable` sets apart from the raw verdict), so every reader that re-derives a tag from them
4358
+ * (router_verify through `gateResult`, the restart re-post and the onVerdict fallback through `heldVerdictKind`) reads the
4359
+ * posted one. Done here, once, not by each reader: a reader cannot re-derive a trivial skip's acceptance (gate.ts accepts it
4360
+ * outside `gateResult`), and `strictUnverifiable` read after a restart need not be the value the gate decided under.
4361
+ */
4362
+ function heldSettlementOf(outcome: FinishOutcome, held: { verdict: "PASS" | "FAIL" | "UNVERIFIABLE"; reasons: string[] }): HeldSettlement {
4363
+ if (outcome.kind !== "required") return heldVerification(held.verdict, held.reasons);
4364
+ const tag = outcome.verdict;
4365
+ return {
4366
+ ...outcome.gate,
4367
+ verdict: { ...outcome.gate.verdict, pass: tag === "PASS", outcome: tag === "PASS" ? "pass" : tag === "FAIL" ? "fail" : "unverifiable" },
4368
+ };
4369
+ }
4370
+ /**
4371
+ * A deterministic, non-retryable result for a held entry whose outcome is not a gate verdict (QA-DF1-16): the held gate's
4372
+ * none/deferred/skipped/error outcomes (verification not required, a read-only skip, a deferral, a gate failure), a restart
4373
+ * that lost the verification data (`finishRestored`), and a verdict the adapter posted itself (`settleHeldDirect`: only its
4374
+ * tag and reason cross the finish API). A gate verdict settles with the gate's own verdict (see `heldSettlementOf`).
4375
+ */
4376
+ function heldVerification(verdict: "PASS" | "FAIL" | "UNVERIFIABLE", reasons: string[]): HeldSettlement {
4377
+ return {
4378
+ verdict: {
4379
+ pass: verdict === "PASS",
4380
+ outcome: verdict === "PASS" ? "pass" : verdict === "FAIL" ? "fail" : "unverifiable",
4381
+ method: "deterministic",
4382
+ reasons,
4383
+ caveats: [],
4384
+ },
4385
+ retryable: false,
4386
+ };
4387
+ }
4388
+ /** QA-2.1-17: the `task` arguments a journaled dispatch stands in for after a restart. */
4389
+ function restoredTaskArgs(restored: RestoredDispatch): Record<string, unknown> {
4390
+ return {
4391
+ ...(restored.prompt === undefined ? {} : { prompt: restored.prompt }),
4392
+ ...(restored.description === undefined ? {} : { description: restored.description }),
4393
+ ...(restored.subagentType === undefined ? {} : { subagent_type: restored.subagentType }),
4394
+ ...(restored.cwd === undefined || restored.cwd === ctx.directory ? {} : { cwd: restored.cwd }),
4395
+ };
4396
+ }
4397
+ /** The verification mode of a dispatch's arguments under the current config (as `verificationFor`). */
4398
+ function verificationModeOfArgs(args: Record<string, unknown>): "none" | "required" | "deferred" {
4399
+ const prompt = typeof args.prompt === "string" ? args.prompt : undefined;
4400
+ const description = typeof args.description === "string" ? args.description : undefined;
4401
+ let mode = "off";
4402
+ try {
4403
+ mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
4404
+ } catch (error) {
4405
+ logger.warn("[router] the enforcement mode could not be read; verification off", { error: describeError(error) });
4406
+ }
4407
+ if (!shouldVerifyTask("task", mode, cfg.enforcement?.verify?.require)) return "none";
4408
+ const dod = buildDelegationDoD({ prompt, description });
4409
+ return isDeferred(dod, directivesFor(dispatchDirectiveText(prompt, description)), false) ? "deferred" : "required";
4410
+ }
4411
+ /** A held verdict posted straight through the sink (no claimable pending entry carries the hold). Never rejects. */
4412
+ function postHeldDirect(handle: string, verdict: "PASS" | "FAIL" | "UNVERIFIABLE", text: string, reason: string | undefined): Promise<void> {
4413
+ if (heldSink === undefined) return Promise.resolve();
4414
+ heldTexts.delete(handle);
4415
+ return heldSink.verdict(handle, { verdict, text, ...(reason !== undefined ? { reason } : {}) }).catch((error: unknown) => {
4416
+ logger.warn("[router] held verdict not posted", { handle, error: describeError(error) });
4417
+ });
4418
+ }
4419
+ /**
4420
+ * The held gate: the same required gate the foreground path runs. `finish` does not await it; QA-2.1-21: it is tracked
4421
+ * (with its verdict post) for `idle` and `dispose`. Its verdict is posted through pending.onVerdict, or straight through
4422
+ * the sink when no claimable entry carries the hold. `preClaim`: the entry is already claimed (a restored hold).
4423
+ */
4424
+ function runHeldGate(
4425
+ fin: FinishInput,
4426
+ handle: string,
4427
+ callInput: { tool: string; sessionID: string; callID: string; args: Record<string, unknown> },
4428
+ scratch: HeldScratch,
4429
+ extra: {
4430
+ delta?: DispatchDelta; dod?: ReturnType<typeof buildDelegationDoD>; workRoot?: string; unattributedWriters?: readonly string[];
4431
+ restoredHead?: DispatchHeadState; noDefer?: true;
4432
+ } | undefined,
4433
+ preClaim: HeldClaim | undefined,
4434
+ ): void {
4435
+ const settleHeld = (outcome: FinishOutcome): Promise<void> | undefined => {
4436
+ // QA-SYNC1-14: the held finish settled; its call's arguments and routed-role copy are no longer needed.
4437
+ forgetTaskArgs(fin.callID);
4438
+ const claim = preClaim ?? pending.markVerifying(fin.parentSessionID, handle);
4439
+ // QA-2.1-1: only a gate verdict is a verdict; none/deferred/skipped/error post UNVERIFIABLE with their reason.
4440
+ const held = heldOutcomeOf(outcome);
4441
+ const text = held.line === undefined ? scratch.output : `${scratch.output.trimEnd()}\n\n${held.line}`;
4442
+ const reason = held.reasons[0];
4443
+ if (claim.kind !== "claimed") return postHeldDirect(handle, held.verdict, text, reason);
4444
+ rememberHeldText(handle, fin.parentSessionID, text, { verdict: held.verdict, ...(reason !== undefined ? { reason } : {}) });
4445
+ // QA-DF1-16: a gate verdict settles as the gate reached it (method, outcome, reasons, caveats, notes).
4446
+ observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-settle", source: "held-gate", handle,
4447
+ parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
4448
+ claim.settle(heldSettlementOf(outcome, held));
4449
+ // onVerdict posts only for an entry that carries its hold.
4450
+ return claim.entry.hold === undefined ? postHeldDirect(handle, held.verdict, text, reason) : undefined;
4451
+ };
4452
+ // DF-1-3: the held gate's grader launches from the orchestrator's retained context too (C14 launcher A).
4453
+ observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-enqueue", source: "held-gate", handle,
4454
+ parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
4455
+ trackHeldGate(finishDispatch(callInput, scratch, undefined, { ...extra, graderParentSessionID: fin.parentSessionID }).then(settleHeld, (error: unknown) => {
4456
+ logger.warn("[router] held verification failed", { handle, error: describeError(error) });
4457
+ return settleHeld({ kind: "error", reason: `verification unavailable: ${scrubText(String(error))}` });
4458
+ }));
4459
+ }
4460
+ /**
4461
+ * QA-2.1-17: a finish after a restart. A verdict reached before it (the restored entry's `state` record) is posted again,
4462
+ * never recomputed; a restored held entry re-runs the gate on its persisted DoD and changed files; anything else that
4463
+ * needs verification ends UNVERIFIABLE "verification data lost in restart" (the live change set and reference are gone).
4464
+ * Undefined: no verification applies, the plain path finishes it.
4465
+ */
4466
+ function finishRestored(fin: FinishInput, args: Record<string, unknown>, scratch: HeldScratch): FinishResult | undefined {
4467
+ const lostLine = `[router] UNVERIFIABLE — ${RESTART_DATA_LOST}`;
4468
+ const lost = (): FinishResult => ({
4469
+ outputText: `${fin.outputText}\n\n${lostLine}`, suffix: `\n\n${lostLine}`,
4470
+ verification: { kind: "required", verdict: "UNVERIFIABLE" }, metadata: {},
4471
+ });
4472
+ const handle = fin.heldHandle;
4473
+ if (handle === undefined) return verificationModeOfArgs(args) === "none" ? undefined : lost();
4474
+ const heldResult: FinishResult = { outputText: fin.outputText, suffix: "", verification: { kind: "held", handle }, metadata: {} };
4475
+ const claim = pending.markVerifying(fin.parentSessionID, handle);
4476
+ if (claim.kind === "settled") {
4477
+ const verdict = heldVerdictKind(claim.result.verdict.outcome, claim.result.verdict.pass);
4478
+ const reason = claim.result.verdict.reasons[0];
4479
+ const line = `[router] ${verdict}${reason === undefined ? "" : ` — ${scrubText(reason)}`}`;
4480
+ trackHeldGate(postHeldDirect(handle, verdict, `${scratch.output.trimEnd()}\n\n${line}`, reason));
4481
+ return heldResult;
4482
+ }
4483
+ if (claim.kind === "joined") {
4484
+ // A router_verify run of this entry is under way; its settle posts the verdict through onVerdict.
4485
+ trackHeldGate(claim.run);
4486
+ return heldResult;
4487
+ }
4488
+ // No restored entry: the child ended after the restart, so its change set was never persisted.
4489
+ if (claim.kind !== "claimed") return lost();
4490
+ const entry = claim.entry;
4491
+ const prompt = typeof args.prompt === "string" ? args.prompt : undefined;
4492
+ const description = typeof args.description === "string" ? args.description : undefined;
4493
+ const dod = entry.dod ?? (prompt === undefined ? undefined : buildDelegationDoD({ prompt, description }));
4494
+ const settleLost = (reason: string): FinishResult => {
4495
+ const text = `${scratch.output.trimEnd()}\n\n[router] UNVERIFIABLE — ${reason}`;
4496
+ rememberHeldText(handle, fin.parentSessionID, text);
4497
+ observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-settle", source: "held-lost", handle,
4498
+ parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
4499
+ claim.settle(heldVerification("UNVERIFIABLE", [reason]));
4500
+ if (entry.hold === undefined) trackHeldGate(postHeldDirect(handle, "UNVERIFIABLE", text, reason));
4501
+ return heldResult;
4502
+ };
4503
+ if (dod === undefined || entry.changedFiles === "unavailable") return settleLost(RESTART_DATA_LOST);
4504
+ // QA-SYNC1-3: the perimeter (I4) and the dispatch-time head the gate checked before the restart are not journaled, so a
4505
+ // re-run gate would PASS with fewer checks: an entry that had a perimeter, or whose head cannot be confirmed, is UNVERIFIABLE.
4506
+ if (entry.perimeterLost === true) return settleLost(PERIMETER_LOST_REASON);
4507
+ if (entry.headLost === true) return settleLost(HEAD_LOST_REASON);
4508
+ changedFileStore.seed(fin.childSessionID, entry.changedFiles.map((file) => ({ path: file.path, status: file.status ?? "modified" })));
4509
+ const gateArgs = typeof args.cwd === "string" || entry.cwd === ctx.directory ? args : { ...args, cwd: entry.cwd };
4510
+ // QA-SYNC1-2: the journaled work root stands in for the routed-role record the restart lost.
4511
+ const workRoot = fin.restored?.workRoot;
4512
+ // QA-SYNC1-13: so does the journaled routed-role snapshot (routedRoleFor reads it until the held finish settles): the gate
4513
+ // places the checks in the role's root and applies the carried-resume and lineage rules, never the tier `cwd=` refusal.
4514
+ const routedSnapshot = fin.restored?.routed;
4515
+ if (routedSnapshot !== undefined && routedRoleFor(fin.callID) === undefined) routedRoleByCall.set(fin.callID, routedSnapshot);
4516
+ const writers = entry.unattributedWriters;
4517
+ const restoredHead = entry.dispatchHead;
4518
+ runHeldGate(fin, handle, { tool: "task", sessionID: fin.parentSessionID, callID: fin.callID, args: gateArgs }, scratch, {
4519
+ dod, ...(workRoot === undefined ? {} : { workRoot }), ...(writers === undefined ? {} : { unattributedWriters: writers }),
4520
+ ...(restoredHead === undefined ? {} : { restoredHead }),
4521
+ // QA-SYNC1-3: a held entry settles in place: without a dispatch record a re-deferral would register an unattributed
4522
+ // change set (risk high) and post "deferred" instead of the held verdict, which no live held gate does.
4523
+ noDefer: true,
4524
+ }, claim);
4525
+ return heldResult;
4526
+ }
4527
+ const finishApi: FinishApi = {
4528
+ journal: sharedJournal,
4529
+ // QA-2.1-7: the change-set store keys a dispatch by `task:<parent>:<callID>` (finishDispatch), never by the bare call id.
4530
+ // The background path passes the key (it knows the parent); the foreground path maps the parent through `taskParentByCall`.
4531
+ captureDelta: async (callID, childSessionID, dispatchID) => {
4532
+ if (dispatchID !== undefined) return changedFileStore.captureDelta(callID, childSessionID, dispatchID);
4533
+ const parent = taskParentByCall.get(callID);
4534
+ return changedFileStore.captureDelta(callID, childSessionID, parent === undefined ? undefined : `task:${parent}:${callID}`);
4535
+ },
4536
+ async reload() {
4537
+ if (pendingFile === undefined) return;
4538
+ const folded = foldDormantRecords(await pendingFile.load(), { now: Date.now(), ttlMs: pendingJournalTtlMs });
4539
+ dormantSessions = folded.sessions;
4540
+ for (const key of folded.processed) processedKeys.add(key);
4541
+ },
4542
+ adopt(sessionID): AdoptedRecords | AdoptionRefused | undefined {
4543
+ const session = dormantSessions.get(sessionID);
4544
+ if (session === undefined || pendingClaimsDir === undefined) return undefined;
4545
+ // QA-2.1-19: a session another live instance (pid, token) claimed is not adopted, and its dormant records stay: they
4546
+ // are that instance's running dispatches, or they wait for a later adoption once its claim is gone.
4547
+ // QA-2.1-34: told apart from "nothing to adopt", so the adapter tries again at a later sighting.
4548
+ if (!claimSessionOnce(sessionID)) return ADOPTION_REFUSED;
4549
+ dormantSessions.delete(sessionID);
4550
+ return { holds: session.holds, inflight: session.inflight };
4551
+ },
4552
+ verificationFor(callID) {
4553
+ const args = taskArgsByCall.get(callID);
4554
+ if (args === undefined) return undefined;
4555
+ const prompt = typeof args.prompt === "string" ? args.prompt : undefined;
4556
+ const description = typeof args.description === "string" ? args.description : undefined;
4557
+ const dod = buildDelegationDoD({ prompt, description });
4558
+ const acceptance = {
4559
+ testsPass: dod.checks.some(c => c.kind === "testsPass"),
4560
+ buildPasses: dod.checks.some(c => c.kind === "buildPasses"),
4561
+ };
4562
+ let mode = "off";
4563
+ try {
4564
+ mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
4565
+ } catch {
4566
+ mode = "off";
4567
+ }
4568
+ if (!shouldVerifyTask("task", mode, cfg.enforcement?.verify?.require)) return { mode: "none", acceptance };
4569
+ // QA-SYNC1-6: a dispatch finishDispatch verifies at once (a refused placement or cwd, the tier per-check `cwd=` refusal)
4570
+ // is never classified deferred, so it is held like any other required verification.
4571
+ if (verifiedAtOnce(callID, args, dod)) return { mode: "required", acceptance };
4572
+ const directives = directivesFor(dispatchDirectiveText(prompt, description));
4573
+ return { mode: isDeferred(dod, directives, false) ? "deferred" : "required", acceptance };
4574
+ },
4575
+ canHold(parentSessionID) {
4576
+ return pending.hasSlot(parentSessionID);
4577
+ },
4578
+ reserveHeld(parentSessionID, callID) {
4579
+ // QA-SYNC1-14: a held call keeps its arguments and routed copy until its finish settles.
4580
+ if (taskArgsByCall.has(callID)) backgroundCalls.add(callID);
4581
+ return pending.reserveHandle(parentSessionID);
4582
+ },
4583
+ // QA-2.1-14: a held dispatch that ends without a registered entry (failed, interrupted, ack failed) frees its slot at once.
4584
+ releaseHeld(handle) {
4585
+ pending.releaseHandle(handle);
4586
+ },
4587
+ async recreateJournal(records) {
4588
+ if (pendingFile === undefined) return;
4589
+ // QA-2.1-16: every record a later restore needs: the live pending entries, the sessions not adopted yet, and the
4590
+ // adapter's live attempts and holds. `recreate` resets the vanished state once the file is back.
4591
+ // QA-2.1-33: `recreate` adds the snapshot of every other instance of this process on the same journal
4592
+ // (`journalSnapshot`, registered below), so their records survive this instance's rewrite.
4593
+ await pendingFile.recreate([...journalSnapshot(), ...records]);
4594
+ },
4595
+ setAdapterSnapshot(provider) {
4596
+ adapterSnapshot = provider;
4597
+ },
4598
+ idle: () => heldGatesIdle(),
4599
+ settleHeldDirect(parentSessionID, handle, v) {
4600
+ const claim = pending.markVerifying(parentSessionID, handle);
4601
+ if (claim.kind !== "claimed") return;
4602
+ // QA-2.1-31: the verdict already reached the parent; settling must not post it a second time (onVerdict is synchronous).
4603
+ directlySettled.add(handle);
4604
+ try {
4605
+ observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-settle", source: "held-direct", handle,
4606
+ ...completionIdentity(parentSessionID, claim.entry.dispatchID, claim.entry.producerSessionID) }));
4607
+ claim.settle(heldVerification(v.verdict, v.reason === undefined ? [] : [scrubText(v.reason)]));
4608
+ } finally {
4609
+ directlySettled.delete(handle);
4610
+ }
4611
+ },
4612
+ dispatchOf(callID) {
4613
+ const args = taskArgsByCall.get(callID);
4614
+ if (args === undefined) return undefined;
4615
+ // QA-SYNC1-14: the adapter reads the dispatch of an acknowledged background attempt; it keeps its arguments until its finish.
4616
+ backgroundCalls.add(callID);
4617
+ const text = (value: unknown): string | undefined => (typeof value === "string" ? value : undefined);
4618
+ const prompt = text(args.prompt);
4619
+ const description = text(args.description);
4620
+ const subagentType = text(args.subagent_type);
4621
+ let workRoot: string | undefined;
4622
+ try {
4623
+ workRoot = verificationScopeOf(callID, args, buildDelegationDoD({ prompt, description })).workRoot;
4624
+ } catch (error) {
4625
+ logger.warn("[router] the work root of a dispatch could not be read", { callID, error: describeError(error) });
4626
+ }
4627
+ // QA-SYNC1-13: the routed-role facts the gate reads, journaled so a restored held gate verifies it as a role dispatch.
4628
+ const routedRole = routedRoleFor(callID);
4629
+ const routed: RoutedRoleSnapshot | undefined = routedRole === undefined ? undefined : {
4630
+ verifyRoot: routedRole.verifyRoot, parentSessionID: routedRole.parentSessionID, resumeID: routedRole.resumeID,
4631
+ ...(routedRole.carried === true ? { carried: true as const } : {}),
4632
+ ...(routedRole.gated === true ? { gated: true as const } : {}),
4633
+ };
4634
+ return {
4635
+ ...(prompt === undefined ? {} : { prompt }),
4636
+ ...(description === undefined ? {} : { description }),
4637
+ ...(subagentType === undefined ? {} : { subagentType }),
4638
+ cwd: text(args.cwd) ?? ctx.directory,
4639
+ ...(workRoot === undefined ? {} : { workRoot }),
4640
+ ...(routed === undefined ? {} : { routed }),
4641
+ };
4642
+ },
4643
+ async finish(fin: FinishInput): Promise<FinishResult> {
4644
+ // QA-2.1-17: after a restart the in-memory call arguments are gone; the journaled dispatch stands in for them.
4645
+ const args: Record<string, unknown> = taskArgsByCall.get(fin.callID) ?? (fin.restored === undefined ? {} : restoredTaskArgs(fin.restored));
4646
+ const callInput = { tool: "task", sessionID: fin.parentSessionID, callID: fin.callID, args };
4647
+ const delta = fin.delta as DispatchDelta | undefined;
4648
+ const scratch = { output: taskOutputText(fin.childSessionID, fin.outputText), title: "", metadata: { sessionId: fin.childSessionID } as Record<string, unknown> };
4649
+ const base = scratch.output.trimEnd();
4650
+ const suffixOf = (): string => (scratch.output.startsWith(base) ? scratch.output.slice(base.length) : "");
4651
+ if (fin.status !== "succeeded") {
4652
+ // QA-2.1-5: a failed, interrupted or unknown child produced no result to verify; the gate never runs on it. The
4653
+ // change-set records of the dispatch are dropped here, as finishDispatch would have.
4654
+ changedFileStore.clear(`task:${fin.parentSessionID}:${fin.callID}`);
4655
+ changedFileStore.clear(fin.childSessionID);
4656
+ forgetTaskArgs(fin.callID);
4657
+ return { outputText: fin.outputText, suffix: "", verification: { kind: "none" }, metadata: {} };
4658
+ }
4659
+ if (fin.restored !== undefined) {
4660
+ const restored = finishRestored(fin, args, scratch);
4661
+ if (restored !== undefined) return restored;
4662
+ }
4663
+ if (fin.heldHandle !== undefined) {
4664
+ const handle = fin.heldHandle;
4665
+ const dod = buildDelegationDoD({
4666
+ prompt: typeof args.prompt === "string" ? args.prompt : undefined,
4667
+ description: typeof args.description === "string" ? args.description : undefined,
4668
+ });
4669
+ // QA-SYNC1-3: what the held gate checks that a restart loses (the perimeter, the dispatch-time head) is journaled as a
4670
+ // fact, and the unattributed writers as they are, so a restored entry is never re-gated with fewer checks.
4671
+ const dispatchKey = `task:${fin.parentSessionID}:${fin.callID}`;
4672
+ const writers = changedFileStore.unattributedWritersOf(dispatchKey, fin.childSessionID);
4673
+ const headRead = changedFileStore.baselineHead(dispatchKey);
4674
+ const startHead = headRead === undefined ? undefined
4675
+ : await withTimeout(headRead, HELD_HEAD_READ_MS, "dispatch head").catch(() => undefined);
4676
+ // The head the gate compares the tree with (as prepareVerification: the head read, else the dispatch snapshot's head and
4677
+ // branch) is journaled as plain data, so the gate re-run after a restart runs the same branch check. A head reader whose
4678
+ // read gave nothing (the gate fails closed on it too) is journaled as the fact alone (`hadHead`, restored as headLost).
4679
+ const baseline = changedFileStore.baselineSnapshot(dispatchKey);
4680
+ const dispatchHead: DispatchHeadState | undefined = startHead !== undefined && startHead !== "none"
4681
+ ? { root: startHead.root, head: startHead.head, branch: startHead.branch, ...(startHead.reflog !== undefined ? { reflog: startHead.reflog } : {}) }
4682
+ : startHead === undefined && baseline !== undefined && baseline.branch !== undefined && typeof baseline.head === "string" && baseline.head !== ""
4683
+ ? { root: baseline.root ?? baseline.cwd, head: baseline.head, branch: baseline.branch }
4684
+ : undefined;
4685
+ const heldHead = dispatchHead === undefined && startHead === undefined && headRead !== undefined;
4686
+ observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "deferred-register", source: "held-register", handle,
4687
+ parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
4688
+ const reg = pending.register({
4689
+ orchestratorSessionID: fin.parentSessionID,
4690
+ dispatchID: fin.callID,
4691
+ producerSessionID: fin.childSessionID,
4692
+ producerTier: typeof args.subagent_type === "string" ? args.subagent_type : "",
4693
+ description: typeof args.description === "string" ? args.description : "",
4694
+ cwd: typeof args.cwd === "string" ? args.cwd : ctx.directory,
4695
+ root: undefined,
4696
+ dispatchedAt: fin.endedAt,
4697
+ dod,
4698
+ reference: Promise.resolve({ kind: "none", reason: "held dispatch: the required gate captures its own reference" }),
4699
+ changedFiles: delta === undefined || delta.files === "unavailable" ? "unavailable" : delta.files.map(f => ({ path: f.path, status: f.status })),
4700
+ risk: unattributedRisk(),
4701
+ handle,
4702
+ hold: { childSessionID: fin.childSessionID, callID: fin.callID },
4703
+ ...(writers.length > 0 ? { unattributedWriters: writers } : {}),
4704
+ ...(changedFileStore.perimeterOf(dispatchKey) !== undefined ? { heldPerimeter: true as const } : {}),
4705
+ ...(heldHead ? { heldHead: true as const } : {}),
4706
+ ...(dispatchHead !== undefined ? { dispatchHead } : {}),
4707
+ });
4708
+ if (!reg.ok) logger.warn("[router] held dispatch not registered", { code: reg.code, detail: reg.detail });
4709
+ runHeldGate(fin, handle, callInput, scratch, delta === undefined ? undefined : { delta }, undefined);
4710
+ return { outputText: fin.outputText, suffix: "", verification: { kind: "held", handle }, metadata: {} };
4711
+ }
4712
+ // DF-1-3: a background completion has no tool context of the orchestrator; its grader launches from the retained context of
4713
+ // the parent (C14 launcher A), never from whatever context is current (a role child's denies `subagent`).
4714
+ const restoredWorkRoot = taskArgsByCall.has(fin.callID) ? undefined : fin.restored?.workRoot;
4715
+ const outcome = await finishDispatch(callInput, scratch, undefined, {
4716
+ ...(delta === undefined ? {} : { delta }), graderParentSessionID: fin.parentSessionID,
4717
+ ...(restoredWorkRoot === undefined ? {} : { workRoot: restoredWorkRoot }),
4718
+ });
4719
+ const suffix = suffixOf();
4720
+ const verification: FinishResult["verification"] =
4721
+ outcome.kind === "deferred" ? { kind: "deferred", handle: outcome.handle }
4722
+ : outcome.kind === "required" ? { kind: "required", verdict: outcome.verdict }
4723
+ : { kind: "none" };
4724
+ forgetTaskArgs(fin.callID);
4725
+ return { outputText: fin.outputText + suffix, suffix, verification, metadata: {} };
4726
+ },
4727
+ };
4728
+ const attachFinish: FinishAttach = ({ held, leaseGate }) => {
4729
+ heldSink = held;
4730
+ leaseGateRef = leaseGate;
4731
+ return finishApi;
4732
+ };
4733
+
4734
+ if (isV2Host) {
4735
+ // Phase 1.2 (v2 only): non-enumerable, so spreading or enumerating the hooks never sees it.
4736
+ Object.defineProperty(routerHooks, ROUTER_TURN_STATE_ATTACH, { value: attachTurnState, enumerable: false });
4737
+ // Phase 2.1.4.a (v2 only): the finish API the v2 adapter attaches to; absent on v1.
4738
+ Object.defineProperty(routerHooks, ROUTER_FINISH_ATTACH, { value: attachFinish, enumerable: false });
4739
+ }
4740
+ return routerHooks;
3240
4741
  };
3241
4742
 
3242
4743
  export default ModelRouterPlugin;