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
@@ -8,13 +8,17 @@ import type { V2Runtime } from "./v2-client";
8
8
  import { V2_GRADER_AGENT } from "./v2-client";
9
9
  import { DEPTH_BANNER, TASK_VERIFICATION } from "./child-session";
10
10
  import { realpathSync, statSync } from "node:fs";
11
- import { isAbsolute, join, posix, resolve, win32 } from "node:path";
12
- import { loadConfig } from "../router/config";
11
+ import { basename, isAbsolute, join, posix, resolve, win32 } from "node:path";
12
+ import { loadConfig, resolveRolesRouting } from "../router/config";
13
13
  import { getActiveTiers } from "../router/protocol";
14
14
  import { DEFER_MISSING_SUBAGENT_NOTICE, HOST_SEED_AGENTS, resolveSubagentOverrides } from "../router/subagents";
15
15
  import { warnAgentOptionsEffortOnce } from "../router/agent-options";
16
16
  import { pluginAgentMarker } from "../router/plugin-agents";
17
17
  import { registerRoleAgents, roleAgentAlias, roleAgentOf, roleAgentSteps } from "../router/role-agents";
18
+ import { readApprovals, type RepoApproval } from "../routing/roles/approvals";
19
+ // Static, not `await import`: a dynamic import made a bundle split src/router/config.ts into a chunk where its tiers.json
20
+ // lookup fails.
21
+ import { approvalReloadLine, approvalsChangedOf } from "../commands/approvals";
18
22
  import { stripDelegateInstructions } from "../router/instructions";
19
23
  import { createPluginLogger } from "../router/logger";
20
24
  import { budgetClaimObserved, GRADER_SYSTEM } from "../verify/checker";
@@ -23,14 +27,19 @@ import type { Ingest } from "../routing/outcomes/ingest";
23
27
  import { createEngineRuntime } from "../routing/wire/runtime";
24
28
  import {
25
29
  annotateSubagentResult, childSessionOf, createDispatchRouter, forgetRoutedRole, gitWorktreeList, normalizeRootText, parseWorktreeList,
26
- roleMaxActions, routedRoleOf, takeSubagentAnnotations,
30
+ ROLE_REFUSALS, RoleDispatchRefusal, roleMaxActions, routedRoleOf, takeSubagentAnnotations,
27
31
  } from "../routing/wire/dispatch";
28
32
  import type { RouterConfig } from "../router/config";
29
33
  import { resolveRoles, type AuthorityAction, type RoleSpec } from "../router/roles";
30
34
  import {
31
- BINDING_NOTES, bind, currentBinding, evict as evictBinding, evictCall, type Binding, type SessionLookup,
35
+ BINDING_NOTES, bind, bindPlanChild, currentBinding, evict as evictBinding, evictCall, type Binding, type SessionLookup,
32
36
  } from "../routing/roles/binding";
37
+ import { recordRoleOrphan, takeRoleBindingLookupNotice } from "../routing/roles/orphans";
33
38
  import type { DispatchGrant } from "../routing/roles/policy";
39
+ import { forgetWorkingSet, workingSetOf } from "../routing/wire/working-set";
40
+ import {
41
+ createRepoProbe, displaySafe, gitMetadataSegment, readSetEligible, readSetPredicate, type InReadSet,
42
+ } from "../routing/roles/read-set";
34
43
  import {
35
44
  AUTHORITY_TEXT, AUTHORITY_TOOL_NAME, consumeAuthority, discardAuthority, evictAuthority, markAnnotated, previewAuthority, quoteChildText,
36
45
  requestedAuthority, type AuthorityDeps,
@@ -40,10 +49,165 @@ import { ROUTER_BUDGET_NOTE_PREFIX } from "../router/prompts";
40
49
  import { parseReturnPrefix } from "../routing/outcomes/signals";
41
50
  import { lookupDispatch } from "../router/sessions";
42
51
  import { createSystemAugmenter } from "../routing/wire/hint";
52
+ import { createTurnStateRegistry, placeTurnState, ROUTER_TURN_STATE_ATTACH, TURN_STATE_ROOT, type TurnStateRegistry } from "./turn-state";
53
+ // 3.1.7 W6: the `plan` provider after the background ones (completed 30, held 40, in-flight 50), before the route hint (90).
54
+ import { PLAN_PROVIDER_NAME, PLAN_PROVIDER_ORDER } from "./turn-state";
55
+ import { createExecutorInstructionsProvider, EXECUTOR_INSTRUCTIONS_ORDER } from "../executor/instructions";
43
56
  import { CONTEXT7_DOC_TOOLS, evaluatePermission, permissionMatches, permissionRules, publishReadOnlyPermissions } from "../router/read-only";
44
57
  import { filterSensitiveGrep, isSensitivePath } from "../router/sensitive-paths";
45
58
  import { canonicalAuthorityPath, insideWorkRoot } from "../routing/roles/work-root";
46
59
  import { appliedEffort, appliedThinkingBudget, createEffortStore, registerEffortChannel } from "../tui/effort-channel";
60
+ import {
61
+ acquireLeaseRegistry, ADOPTION_RETRY_MS, attemptLabel, COMPLETION_SETTLE_MS, createCompletionProcessor, createHeldResults, createInFlightRegistry,
62
+ isExecutorOwned,
63
+ createLeaseGuard, decideBackground, isAdoptionRefused, PENDING_GUARANTEES_TEXT, PROVIDER_ORDER, renderCompleted, renderHeld, renderInFlight,
64
+ restoredDispatchOf, ROUTER_FINISH_ATTACH,
65
+ } from "./background";
66
+ import { acquireTimingRecorder, classifyCapacity } from "../routing/outcomes/timings";
67
+ import type { TimingRecorderHolder } from "../routing/outcomes/timings";
68
+ import { createSideLogs, durationSeamsFor, nodePersistDeps, resolveOutcomesDir } from "../routing/outcomes/persist";
69
+ import { homedir, tmpdir } from "node:os";
70
+ import { installGitSearchFilter, nearestRepository, repositoryIdentity } from "../router/git-tools";
71
+ import { readFileSync } from "node:fs";
72
+ import { fileURLToPath } from "node:url";
73
+ import { resolveRouting } from "../router/config";
74
+
75
+ /** 2.1.5.f: the plugin-root notice is logged once per process. */
76
+ let pluginRootLogged = false;
77
+ import { createDurationModel, DURATION_MIN_SAMPLES } from "../routing/outcomes/durations";
78
+ import type { DurationModel } from "../routing/outcomes/durations";
79
+ import type {
80
+ Attempt, CompletionProcessor, FinishApi, FinishAttach, HeldResults, InFlightRegistry, InflightJournal, LeaseGuard, PersistedRecord,
81
+ RestoredDispatch, RestoredHold, RestoredHolds,
82
+ } from "./background";
83
+ import { PENDING_JOURNAL_VANISHED, pendingRecordIdentity } from "../verify/pending";
84
+ import type { ExecutorRuntimeHandle, LeaseRegistryPort, PlanTaskVerifier } from "../executor/runtime";
85
+ import type { LeaseRegistry } from "../router/leases";
86
+ import type {
87
+ ChildEnd, ChildRunner, DispatchBookkeeping, ExecutorChildGuardPort, HostError, HostSessionContext, HostSessionEvent, HostSessions, IsoTime, LaunchRequest, MetricPayload, PlanId, RouteResolver,
88
+ TaskLauncher,
89
+ } from "../executor/types";
90
+ import type { PlanRoleBindings } from "../executor/launch";
91
+ import { LAUNCH_HEADER_PATTERN, parseLaunchHeader, type LaunchHeaderFields } from "../executor/types";
92
+ import { withoutHostPreamble } from "../executor/host-preamble";
93
+ import { processToken } from "../executor/process-identity";
94
+ import { executorPlatformSupported } from "../executor/platform";
95
+ export { processToken } from "../executor/process-identity";
96
+ import { grantFor } from "../routing/roles/policy";
97
+ import { NEEDS, UNKNOWN_FACTS, type Need } from "../routing/classify/types";
98
+ import { observeV2, timingWriteObserver, type V2Observations } from "./v2-observations";
99
+
100
+ /** §7 grammar (`formatLaunchPrompt`): every launcher prompt starts with this line. */
101
+ const PLAN_CONTEXT_PREFIX = "PLAN CONTEXT\n";
102
+ const LIVE_STATES: ReadonlySet<Attempt["state"]> = new Set<Attempt["state"]>(["acknowledged", "child-ended", "processing"]);
103
+ /** Bound host lookups for one Code Mode resume check. */
104
+ const MAX_ORPHAN_RESUME_TARGETS = 4;
105
+
106
+ /**
107
+ * The status of an executor launch's `runner` trigger. QA-3.1 nit 4: the child's observed end (`execution.*`) decides;
108
+ * QA-3.1-24: else the launch's settled end kind the launcher passes (its runner result can settle before the child's
109
+ * `execution.succeeded` is seen); else the registry's outcome. A child that settled with none of them (lost, cancelled, a
110
+ * runner error) did not succeed: interrupted.
111
+ */
112
+ export function executorRunnerStatus(
113
+ observed: "succeeded" | "failed" | "interrupted" | undefined,
114
+ settled: ChildEnd["kind"] | undefined,
115
+ registry: string | undefined,
116
+ ): "succeeded" | "failed" | "interrupted" {
117
+ if (observed !== undefined) return observed;
118
+ if (settled === "completed") return "succeeded";
119
+ if (settled === "failed" || settled === "capacity") return "failed";
120
+ if (settled === "interrupted") return "interrupted";
121
+ return registry === "succeeded" || registry === "failed" || registry === "interrupted" ? registry : "interrupted";
122
+ }
123
+
124
+ /**
125
+ * QA-4.2-27: the kind of one entry of a child's host history, with the one precedence every reader of that history uses. The
126
+ * host's context entries are discriminated by `type` ("user" | "assistant" | "synthetic"); model-facing messages use `role`:
127
+ * `type: "synthetic"` first, then assistant (either field), then user (either field); anything else (a tool turn) is `other`.
128
+ */
129
+ export function historyEntryKind(message: unknown): "synthetic" | "assistant" | "user" | "other" {
130
+ if (message === null || typeof message !== "object") return "other";
131
+ const m = message as Record<string, unknown>;
132
+ if (m.type === "synthetic") return "synthetic";
133
+ if (m.type === "assistant" || m.role === "assistant") return "assistant";
134
+ if (m.type === "user" || m.role === "user") return "user";
135
+ return "other";
136
+ }
137
+
138
+ /** QA-4.2-27: what a child's own history says about its end (`childHistoryEnd`). */
139
+ export type ChildHistoryEnd =
140
+ /** No entry but synthetic ones. */
141
+ | { kind: "none" }
142
+ /** QA-DF1-21: a user or tool turn last, or a step without its end (cut mid-stream or mid-tool-call): it may still run. */
143
+ | { kind: "open" }
144
+ /** The newest step ended; `text` is its text, absent when the step has none. */
145
+ | { kind: "ended"; outcome: "succeeded" | "failed" | "interrupted"; text: string | undefined };
146
+
147
+ /**
148
+ * QA-4.2-27: the ONE end rule over a child's own history (QA-2.1-6, QA-2.1-18, QA-DF1-21), shared by the background recovery
149
+ * (`childEndState`) and the executor's `HostSessions.context` (`executorHostContext`). Synthetic entries are skipped; the newest
150
+ * other entry decides. An assistant entry with an error failed (interrupted, for an abort, interrupt or cancel); one with a
151
+ * completion marker (`assistantStepCompleted`: a finish reason other than `tool-calls`, or a completed time, and no open tool
152
+ * part) succeeded, with or without text. Anything else is not an end.
153
+ */
154
+ export function childHistoryEnd(history: unknown): ChildHistoryEnd {
155
+ const entries: readonly unknown[] = Array.isArray(history) ? history : [];
156
+ for (let index = entries.length - 1; index >= 0; index--) {
157
+ const message = entries[index];
158
+ const kind = historyEntryKind(message);
159
+ if (kind === "synthetic") continue;
160
+ if (kind !== "assistant") return { kind: "open" };
161
+ const m = message as { error?: unknown; info?: { error?: unknown } };
162
+ const text = messageText(message);
163
+ const error = m.error ?? m.info?.error;
164
+ if (error !== undefined && error !== null && error !== false) {
165
+ const described = typeof error === "string" ? error : JSON.stringify(error) ?? "";
166
+ return { kind: "ended", outcome: /abort|interrupt|cancel/i.test(described) ? "interrupted" : "failed", text };
167
+ }
168
+ // QA-2.1-18: text alone is not an end: a child cut mid-step has partial text.
169
+ if (!assistantStepCompleted(message)) return { kind: "open" };
170
+ return { kind: "ended", outcome: "succeeded", text };
171
+ }
172
+ return { kind: "none" };
173
+ }
174
+
175
+ /** An open tool can leave processes behind after its launcher dies; only completed/error states prove it closed. */
176
+ export function historyToolInFlight(history: unknown): boolean {
177
+ const entries: readonly unknown[] = Array.isArray(history) ? history : [];
178
+ const toolOpen = (part: unknown): boolean => {
179
+ if (part === null || typeof part !== "object" || (part as Record<string, unknown>).type !== "tool") return false;
180
+ const state = (part as Record<string, unknown>).state;
181
+ const status = state !== null && typeof state === "object" ? (state as Record<string, unknown>).status : state ?? (part as Record<string, unknown>).status;
182
+ return status !== "completed" && status !== "error";
183
+ };
184
+ return entries.some((entry) => {
185
+ if (toolOpen(entry)) return true;
186
+ if (entry === null || typeof entry !== "object") return false;
187
+ const m = entry as Record<string, unknown>;
188
+ return [m.content, m.parts].some((parts) => Array.isArray(parts) && parts.some(toolOpen));
189
+ });
190
+ }
191
+
192
+ /**
193
+ * QA-4.2-2: the executor's `HostSessions.context` over the host's history (amendment to memo R1 rule 5). User and assistant
194
+ * entries (`historyEntryKind`) keep their role and text; every other entry (synthetic, tool turns) is a non-terminal `assistant`
195
+ * entry without text, never `idle`. One explicit terminal entry `{ role: "idle", text: null, outcome }` is appended ONLY when
196
+ * the history shows the child ended (`childHistoryEnd`), with that end's real outcome. QA-4.2-27: a completed step without text
197
+ * is an end (succeeded), as the live launcher treats it; the runtime then reads an empty result.
198
+ */
199
+ export function executorHostContext(history: unknown): HostSessionContext {
200
+ const entries: readonly unknown[] = Array.isArray(history) ? history : [];
201
+ const messages: HostSessionContext["messages"] = entries.map((m) => {
202
+ const kind = historyEntryKind(m);
203
+ if (kind === "user") return { role: "user" as const, text: messageText(m) ?? null, outcome: null };
204
+ if (kind === "assistant") return { role: "assistant" as const, text: messageText(m) ?? null, outcome: null };
205
+ return { role: "assistant" as const, text: null, outcome: null };
206
+ });
207
+ const end = childHistoryEnd(entries);
208
+ if (end.kind === "ended") messages.push({ role: "idle", text: null, outcome: end.outcome });
209
+ return { messages, toolInFlight: historyToolInFlight(entries) };
210
+ }
47
211
 
48
212
  /** Translate the router's own v1 tool vocabulary at the v2 boundary. */
49
213
  export function v2Instructions(text: string): string {
@@ -76,14 +240,16 @@ function taskArgs(toolName: string, input: unknown): any {
76
240
  }
77
241
 
78
242
  /**
79
- * `foreground` (#84 P-5): a role dispatch is forced to the foreground whatever the verification settings, so the router can
80
- * annotate its result (budget, authority) in `execute.after`. A separate flag: it never marks the call as verifying.
243
+ * `background` (#84 P-5, Phase 2.1 D1): the `background` key the router sets on a `subagent` call, from `decideBackground`
244
+ * (`undefined` = no key). With `routing.background.mode: "off"` that is `verifying || roleRouted ? false : undefined`: a role
245
+ * dispatch or a verifying call is forced to the foreground, so the router can annotate its result (budget, authority) in
246
+ * `execute.after`. It never marks the call as verifying.
81
247
  */
82
- function nativeArgs(toolName: string, args: any, original: any, verifying: boolean, foreground = false): any {
248
+ function nativeArgs(toolName: string, args: any, original: any, background: boolean | undefined): any {
83
249
  if (!args || typeof args !== "object") return args;
84
250
  if (toolName === "subagent") {
85
251
  const { subagent_type, task_id, ...rest } = args;
86
- return { ...rest, agent: subagent_type, ...(task_id === undefined ? {} : { sessionID: task_id }), ...(verifying || foreground ? { background: false } : {}) };
252
+ return { ...rest, agent: subagent_type, ...(task_id === undefined ? {} : { sessionID: task_id }), ...(background === undefined ? {} : { background }) };
87
253
  }
88
254
  if (toolName === "shell") { const { cwd, ...rest } = args; return { ...rest, ...(cwd === undefined ? {} : { workdir: cwd }) }; }
89
255
  if (["read", "write", "edit"].includes(toolName)) {
@@ -120,6 +286,7 @@ function messageText(message: unknown): string | undefined {
120
286
  if (!message || typeof message !== "object") return undefined;
121
287
  const m = message as Record<string, unknown>;
122
288
  if (typeof m.text === "string") return m.text;
289
+ if (typeof m.content === "string") return m.content;
123
290
  const parts = Array.isArray(m.content) ? m.content : Array.isArray(m.parts) ? m.parts : undefined;
124
291
  if (parts === undefined) return undefined;
125
292
  const texts = parts.flatMap((part) => part && typeof part === "object" && (part as Record<string, unknown>).type === "text"
@@ -250,6 +417,13 @@ export function isPermissionRefusal(error: unknown): boolean {
250
417
  export const AUTHORITY_BINDING_UNKNOWN_DROP = `${AUTHORITY_TEXT.dropped.bindingUnknown}.`;
251
418
 
252
419
  /** QA-P21-1-8: logged once when `routing.delegation` becomes `roles` while OpenCode runs in tiers mode. */
420
+ /**
421
+ * Cross-repo P4.7 (SD-P4-11, spike T6): whether reloading the role agents after `/router approve` makes the host allow the
422
+ * approved directory at once. True: the adapter says "Role agents reloaded; dispatch again with root=<path>."; false: "Restart
423
+ * OpenCode to use it." (as after a failed reload).
424
+ */
425
+ export const APPROVAL_RELOAD_APPLIES: boolean = true;
426
+
253
427
  export const ROLES_RESTART_NOTICE =
254
428
  "roles mode (OpenCode v2 only): routing.delegation is now `roles`, but this OpenCode instance started in tiers mode; restart OpenCode to register the role agents and tools (tiers mode stays active until then)";
255
429
 
@@ -458,15 +632,6 @@ export function toolCallPaths(tool: string, args: unknown): string[] | undefined
458
632
  return paths.length > 0 ? paths : undefined;
459
633
  }
460
634
 
461
- /**
462
- * QA-G-A2-2: a path segment that names git's metadata entry `.git` — compared case-insensitively (win32, and stricter
463
- * elsewhere), with the trailing dots and spaces win32 drops and an NTFS `:stream` suffix removed (`.git.`, `.GIT`,
464
- * `.git::$INDEX_ALLOCATION` all name `.git` there).
465
- */
466
- function gitMetadataSegment(segment: string): boolean {
467
- return segment.replace(/:.*$/s, "").replace(/[. ]+$/, "").toLowerCase() === ".git";
468
- }
469
-
470
635
  /**
471
636
  * QA-G-A2-2: an edit of `path` (canonical `target`, inside `root`) would write `.git` or anything below it — the work root's own
472
637
  * repository pointer (a file in a linked worktree) or metadata (config, hooks, `commondir`), or a nested repository's. Such an
@@ -480,11 +645,27 @@ export function editsGitMetadata(path: string, target: string, root: string): bo
480
645
  return [path, below].some((text) => text.split(/[\\/]/).some(gitMetadataSegment));
481
646
  }
482
647
 
483
- /** The decision for one role-session action: allowed, or refused with the reason the child sees. */
484
- export type RoleAuthorityDecision = { readonly allow: true } | { readonly allow: false; readonly reason: string };
648
+ /**
649
+ * What allowed a path action (QA-1 F6): every path inside the work root W, some only in the read set R (P1.5), or some only as the
650
+ * session's own truncated output (QA-P23-2-A1) — the last one present wins (`own-output` over `read-set` over `work-root`).
651
+ */
652
+ export type RoleAuthorityAllowance = "work-root" | "read-set" | "own-output";
653
+
654
+ /**
655
+ * The decision for one role-session action: allowed (`via`: what allowed it, for an action with paths), or refused with the reason
656
+ * the child sees.
657
+ */
658
+ export type RoleAuthorityDecision =
659
+ | { readonly allow: true; readonly via?: RoleAuthorityAllowance }
660
+ | { readonly allow: false; readonly reason: string };
485
661
 
486
662
  const ALLOW: RoleAuthorityDecision = Object.freeze({ allow: true });
487
663
  const refuse = (reason: string): RoleAuthorityDecision => ({ allow: false, reason });
664
+ const ALLOWANCE_ORDER: readonly RoleAuthorityAllowance[] = ["work-root", "read-set", "own-output"];
665
+ /** The allowance of a decision over several paths: the widest one any path needed. */
666
+ const widerAllowance = (a: RoleAuthorityAllowance | undefined, b: RoleAuthorityAllowance): RoleAuthorityAllowance =>
667
+ a === undefined || ALLOWANCE_ORDER.indexOf(b) > ALLOWANCE_ORDER.indexOf(a) ? b : a;
668
+ const allowedVia = (via: RoleAuthorityAllowance | undefined): RoleAuthorityDecision => (via === undefined ? ALLOW : { allow: true, via });
488
669
 
489
670
  export interface RoleAuthorityInput {
490
671
  /** The host permission action (`event.action`) or the tool name (`execute.before`). */
@@ -508,6 +689,58 @@ export interface RoleAuthorityInput {
508
689
  * root. Never `edit`, `glob` or anything else.
509
690
  */
510
691
  readonly ownOutputs?: ReadonlySet<string>;
692
+ /**
693
+ * Cross-repo P1.5: the read set R beyond the work root (`routing/roles/read-set.ts`) — where a CANONICAL target lies when it is
694
+ * in R, undefined (or no predicate at all) when it is not. Used only for an exact binding with a work root (I9): `read`, `glob`
695
+ * and `grep` may reach R, `external_directory` too when the grant has a local read action; an edit never, it only names where
696
+ * the file lies.
697
+ */
698
+ readonly inReadSet?: (canonicalTarget: string) => { readonly repository: string; readonly name: string; readonly branch: string | null } | undefined;
699
+ /**
700
+ * QA-1 F1: the paths are the host's own resources (`evaluate`): a relative `read`/`edit` resource is the host's Location-relative
701
+ * form of a file the call's `execute.before` already checked as the call wrote it, so it may reach R. Without it (the call's own
702
+ * arguments, `execute.before`) a relative path never reaches R: it resolves against the session directory, which may itself be
703
+ * a repository of R, and the role would read another checkout's file silently.
704
+ */
705
+ readonly hostRelative?: boolean;
706
+ /**
707
+ * QA-1 F1: the one path is a `glob`/`grep` search root the call did not name (the session directory, or the host's `.`): it never
708
+ * reaches R, only W.
709
+ */
710
+ readonly implicitRoot?: boolean;
711
+ }
712
+
713
+ /**
714
+ * Cross-repo P1.5 (§5 refusal wording): where an edit outside the work root `root` lands — another worktree of the bound
715
+ * repository (and the same file's path in the work root), or a repository of R this dispatch may only read. Undefined when it is
716
+ * neither: the caller keeps the plain "outside this dispatch's work root" text.
717
+ */
718
+ function editElsewhereReason(
719
+ action: string, path: string, target: string, root: string, location: DispatchGrant["location"],
720
+ readSet: RoleAuthorityInput["inReadSet"], canonicalOf: (path: string) => string | undefined,
721
+ ): string | undefined {
722
+ // QA-1 F2: names, branches and paths from the filesystem (and the call's own path) are echoed display-safe.
723
+ const branch = (name: string | null): string => displaySafe(name ?? "(detached)");
724
+ const shown = displaySafe(path);
725
+ if (location !== undefined) {
726
+ let match: { dir: string; branch: string | null } | undefined;
727
+ for (const entry of location.worktrees) {
728
+ const dir = canonicalOf(entry.path);
729
+ if (dir === undefined || permissionMatches(dir, root) || !insideWorkRoot(target, dir)) continue;
730
+ if (match === undefined || dir.length > match.dir.length) match = { dir, branch: entry.branch };
731
+ }
732
+ if (match !== undefined) {
733
+ const rel = target.slice(match.dir.replace(/[\\/]+$/, "").length).replace(/^[\\/]+/, "");
734
+ return `${action}: ${shown} is in worktree ${displaySafe(match.dir)} (repository ${displaySafe(location.name)}, branch ${branch(match.branch)}); `
735
+ + `this dispatch edits only in ${displaySafe(root)} (branch ${branch(location.branch)}). The same file in your work root is `
736
+ + `${displaySafe(rel === "" ? root : join(root, rel))}.`;
737
+ }
738
+ }
739
+ const repo = readSet?.(target);
740
+ if (repo === undefined) return undefined;
741
+ const name = displaySafe(repo.name);
742
+ return `${action}: ${shown} is in repository ${name} (branch ${branch(repo.branch)}), which this dispatch may read but not edit. `
743
+ + `Finish the ${displaySafe(location?.name ?? basename(root))} part and return NEED MORE: naming the ${name} change; it needs a dispatch with repo=${name}.`;
511
744
  }
512
745
 
513
746
  /** The shape of a tool-output store file: `<data>/tool-output/tool_<id>` (`MANAGED_DIRECTORY`, `tool_${Identifier.ascending()}`). */
@@ -577,8 +810,11 @@ export function listedWorktreeRoot(
577
810
  * - `execute` (Code Mode) never (R6/P-6: its inner calls are never evaluated); `router_request_authority` for dynamic roles only.
578
811
  * - an action outside every role class → refused; a role action outside the dispatch grant → refused (an unknown binding's grant
579
812
  * is the role max ∩ local, binding.ts);
580
- * - `external_directory` (P-13): only an EXACT binding with a work root and a local action, every resource inside that root;
581
- * an unknown binding or a grant without a root → refused (I9);
813
+ * - `external_directory` (P-13): only an EXACT binding with a work root and a local action, every resource inside that root —
814
+ * or inside the read set R (cross-repo P1.5, `inReadSet`) when the grant has a local read action; an unknown binding or a grant
815
+ * without a root → refused (I9);
816
+ * - cross-repo P1.5: `read`/`glob`/`grep` may also reach R (exact binding with a work root only); an edit outside W stays refused,
817
+ * and its text names another worktree of the bound repository or a repository of R ({@link editElsewhereReason});
582
818
  * - path actions (`read`, `edit`, `glob`, `grep`): every path, canonical ({@link canonicalAuthorityPath}; case folded on win32),
583
819
  * inside the bound work root — the plugin's directory when the grant has none, except for `edit`, which a grant without a work
584
820
  * root never allows (QA-G-B-2); `read`/`edit` with no path refuse (QA-P23-A5);
@@ -595,6 +831,9 @@ export function roleAuthorityDecision(input: RoleAuthorityInput): RoleAuthorityD
595
831
  const canonical = input.canonical ?? ((path: string, base: string) => canonicalAuthorityPath(path, base));
596
832
  const cls = roleActionOf(action);
597
833
  if (cls === undefined) return refuse(`${action} is outside every role's authority`);
834
+ // Cross-repo P1.5: R beyond W only for an exact binding with a bound work root (I9: an unknown binding, or a grant without a
835
+ // root, never reaches outside its directory).
836
+ const readSet = binding.kind === "exact" && grant.workRoot !== null ? input.inReadSet : undefined;
598
837
  if (cls === "external_directory") {
599
838
  if (binding.kind !== "exact") return refuse("external_directory: this session is not bound to its dispatch (binding unknown, I9)");
600
839
  const root = grant.workRoot;
@@ -604,16 +843,30 @@ export function roleAuthorityDecision(input: RoleAuthorityInput): RoleAuthorityD
604
843
  if (input.paths.length === 0) return refuse("external_directory: no path to check");
605
844
  // QA-P23-2-A1: the directory of the session's own truncated output, for `read`/`grep` of exactly those files.
606
845
  const outputs = grant.actions.has("read") || grant.actions.has("grep") ? input.ownOutputs : undefined;
846
+ // P1.5: a directory of R only for a grant with a local READ action; `router_git` alone keeps W only.
847
+ const reads = grant.actions.has("read") || grant.actions.has("glob") || grant.actions.has("grep");
848
+ let via: RoleAuthorityAllowance | undefined;
607
849
  for (const resource of input.paths) {
608
850
  const dir = resource.replace(/[\\/]\*$/, "");
609
851
  const target = dir === "" ? undefined : canonical(dir, input.sessionDirectory);
610
- if (target !== undefined && root !== null && insideWorkRoot(target, root)) continue;
611
- if (target !== undefined && ownOutputDirectory(target, outputs)) continue;
852
+ if (target !== undefined && root !== null && insideWorkRoot(target, root)) {
853
+ via = widerAllowance(via, "work-root");
854
+ continue;
855
+ }
856
+ if (target !== undefined && ownOutputDirectory(target, outputs)) {
857
+ via = widerAllowance(via, "own-output");
858
+ continue;
859
+ }
860
+ // QA-1 F1/F7: the host's resources are canonical absolute; never `.git` or below in R.
861
+ if (target !== undefined && reads && readSetEligible(dir, target) && readSet?.(target) !== undefined) {
862
+ via = widerAllowance(via, "read-set");
863
+ continue;
864
+ }
612
865
  return refuse(root === null
613
866
  ? "external_directory: this dispatch has no work root (root=)"
614
867
  : `external_directory: ${resource} is outside this dispatch's work root ${root}`);
615
868
  }
616
- return ALLOW;
869
+ return allowedVia(via);
617
870
  }
618
871
  if (!grant.actions.has(cls)) return refuse(`${action} is not in this dispatch's grant (${[...grant.actions].join(", ") || "none"})`);
619
872
  if (cls === "read" || cls === "edit" || cls === "glob" || cls === "grep") {
@@ -626,17 +879,35 @@ export function roleAuthorityDecision(input: RoleAuthorityInput): RoleAuthorityD
626
879
  for (const pattern of input.patterns ?? []) {
627
880
  if (unsafeSearchPattern(pattern)) return refuse(`${action}: the pattern ${pattern} reaches outside its search root (use a relative pattern and \`path\`)`);
628
881
  }
882
+ // QA-1 F1: R only for a path the call wrote fully qualified (or the host's own Location-relative resource) and a search root
883
+ // the call named; a relative path or a search without a path that lands outside W keeps the refusal it had before P1.5.
884
+ const mayReachReadSet = (path: string, target: string): boolean =>
885
+ cls !== "edit" && input.implicitRoot !== true && readSetEligible(path, target, input.hostRelative === true);
886
+ let via: RoleAuthorityAllowance | undefined;
629
887
  for (const path of input.paths) {
630
888
  const target = canonical(path, input.sessionDirectory);
631
889
  if (target !== undefined && insideWorkRoot(target, root)) {
632
890
  if (cls === "edit" && editsGitMetadata(path, target, root)) {
633
891
  return refuse(`${action}: ${path} is repository metadata (\`.git\` or below it); a role never edits it`);
634
892
  }
893
+ via = widerAllowance(via, "work-root");
894
+ continue;
895
+ }
896
+ if (target !== undefined && (cls === "read" || cls === "grep") && ownOutput(target, input.ownOutputs)) { // QA-P23-2-A1
897
+ via = widerAllowance(via, "own-output");
898
+ continue;
899
+ }
900
+ if (target !== undefined && mayReachReadSet(path, target) && readSet?.(target) !== undefined) { // P1.5: read/glob/grep in R
901
+ via = widerAllowance(via, "read-set");
635
902
  continue;
636
903
  }
637
- if (target !== undefined && (cls === "read" || cls === "grep") && ownOutput(target, input.ownOutputs)) continue; // QA-P23-2-A1
904
+ const elsewhere = cls === "edit" && target !== undefined
905
+ ? editElsewhereReason(action, path, target, root, grant.location, readSet, (named) => canonical(named, input.sessionDirectory))
906
+ : undefined;
907
+ if (elsewhere !== undefined) return refuse(elsewhere);
638
908
  return refuse(`${action}: ${path} is outside this dispatch's work root ${root} (use an absolute path inside it)`);
639
909
  }
910
+ return allowedVia(via);
640
911
  }
641
912
  return ALLOW;
642
913
  }
@@ -672,10 +943,230 @@ export function normalizeAgentOptions(options: Readonly<Record<string, unknown>>
672
943
  }
673
944
 
674
945
  /** Register the existing router engine on the public OpenCode 2 domain APIs. */
946
+ /** One host completion element `<subagent sessionID="X" state="S">body</subagent>` in a message text (memo §4.4, C2). */
947
+ interface CompletionElement { child: string; state: "completed" | "error" | "cancelled"; body: string }
948
+ // Further attributes after `state` (the host may add some) are tolerated and kept.
949
+ const COMPLETION_ELEMENT = /<subagent sessionID="([^"]+)" state="([^"]+)"[^>]*>([\s\S]*?)(?:<\/subagent>|$)/g;
950
+
951
+ /** QA-2.1-8: the refusal of a resume while the pending journal is not reloaded (the session may be held). */
952
+ export function reloadFailedResumeText(child: string): string {
953
+ // QA-2.1-16: the retry is real: each refused call (and each later hook or event) starts another reload, or rebuilds a
954
+ // vanished journal, at most every PENDING_RELOAD_RETRY_MS.
955
+ return `[router] Refused: the router could not reload its pending journal, so session ${child} may be held for verification. Try the resume again shortly: each attempt makes the router retry the reload (at most every ${PENDING_RELOAD_RETRY_MS / 1000} s).`;
956
+ }
957
+
958
+ /** QA-2.1-20: a `sessionID` / `task_id` key given a string literal in Code Mode code (`sessionID: "x"`, `"task_id": 'x'`, `task_id = "x"`). */
959
+ const CODE_RESUME_TARGET = /\b(?:sessionID|task_id)["']?\s*[:=]\s*(["'`])([^"'`\r\n]+)\1/g;
960
+
961
+ /**
962
+ * QA-2.1-8 / QA-2.1-20: the sessions a tool call may resume: a `subagent` call's `sessionID` / `task_id`, and for Code Mode
963
+ * `execute` every string literal its code gives to those keys (the caller's own session excepted: it is not a resume). The
964
+ * reload-failed refusal reads the same calls `held.refusal` does (`subagent` args and `execute` code).
965
+ */
966
+ export function resumeTargetsOf(tool: string, args: unknown, caller: string): string[] {
967
+ if (args === null || typeof args !== "object") return [];
968
+ if (tool === "subagent") {
969
+ return ["sessionID", "task_id"].flatMap((key) => {
970
+ const target: unknown = Reflect.get(args, key);
971
+ return typeof target === "string" && target !== "" ? [target] : [];
972
+ });
973
+ }
974
+ if (tool !== "execute") return [];
975
+ const code: unknown = Reflect.get(args, "code");
976
+ if (typeof code !== "string") return [];
977
+ const targets = new Set<string>();
978
+ for (const match of code.matchAll(CODE_RESUME_TARGET)) {
979
+ const target = match[2];
980
+ if (target !== undefined && target !== "" && target !== caller) targets.add(target);
981
+ }
982
+ return [...targets];
983
+ }
984
+
985
+ /** QA-2.1-6: what a persisted dispatch's child history says about its end. */
986
+ /** `incomplete` (QA-DF1-21): the child's last step has no end (no step end, no execution end): it may still be running. */
987
+ type ChildEndState =
988
+ | { outcome: "succeeded" | "failed" | "interrupted"; text?: string }
989
+ | { outcome: "lost"; text?: undefined; incomplete?: boolean };
990
+
991
+ /**
992
+ * QA-2.1-18: whether an assistant entry of a child's history ended its step (top level or under `info`): a finish reason other
993
+ * than a tool-call continuation, or a completed time; and no tool part still `pending` or `running`. A step cut mid-stream has
994
+ * none of these, and a `tool-calls` finish means the child meant to go on: neither is an end, whatever text it already has.
995
+ */
996
+ function assistantStepCompleted(message: unknown): boolean {
997
+ if (message === null || typeof message !== "object") return false;
998
+ const m = message as Record<string, unknown>;
999
+ const info = m.info !== null && typeof m.info === "object" ? m.info as Record<string, unknown> : undefined;
1000
+ const parts: readonly unknown[] = Array.isArray(m.content) ? m.content : Array.isArray(m.parts) ? m.parts : [];
1001
+ const toolOpen = parts.some((part) => {
1002
+ if (part === null || typeof part !== "object" || (part as Record<string, unknown>).type !== "tool") return false;
1003
+ const state = (part as Record<string, unknown>).state;
1004
+ const status = state !== null && typeof state === "object" ? (state as Record<string, unknown>).status : state ?? (part as Record<string, unknown>).status;
1005
+ // The v2 tool state is `streaming` | `running` | `completed` | `error` (`pending` is the v1 name of the first).
1006
+ return status === "streaming" || status === "pending" || status === "running";
1007
+ });
1008
+ if (toolOpen) return false;
1009
+ const finish = m.finish ?? info?.finish;
1010
+ if (typeof finish === "string" && finish !== "") return finish !== "tool-calls" && finish !== "unknown";
1011
+ const time = m.time ?? info?.time;
1012
+ // `time.completed` is set once the step ended: epoch millis on the wire, a DateTime once decoded; either counts.
1013
+ const completed = time !== null && typeof time === "object" ? (time as Record<string, unknown>).completed : undefined;
1014
+ return completed !== undefined && completed !== null && completed !== "" && completed !== false;
1015
+ }
1016
+
1017
+ /**
1018
+ * QA-2.1-11: a failed session-directory lookup is not repeated for this long (the lease guard calls it per tool call).
1019
+ * QA-2.1-25: a failed directory means no lease check and no lease for that call, like a failed kind, so the window is as short.
1020
+ */
1021
+ export const SESSION_DIR_NEGATIVE_TTL_MS = 2_000;
1022
+ /**
1023
+ * QA-2.1-25: a failed session-kind lookup is not repeated for this long. Short on purpose: the failure answers `unknown` (root
1024
+ * semantics, no lease), so a write in that window is unguarded; the window only spares a burst of tool calls a failing host call each.
1025
+ */
1026
+ export const SESSION_KIND_NEGATIVE_TTL_MS = 2_000;
1027
+ /**
1028
+ * DF-1.1-4: the lease registry's `repoKeyOf` seam. Write keys are per checkout (`repo` = the work tree), so ordinary writers
1029
+ * of one repo-relative path in two linked worktrees of a repository never refuse each other. `shared` (the common git
1030
+ * directory every linked worktree has) keeps the leases of plan tasks (`until-integrated`) repository-wide: the tasks of a
1031
+ * plan are integrated into one branch.
1032
+ */
1033
+ export function leaseRepoKeyOf(dir: string): { repo: string; tree: string; shared: string } | undefined {
1034
+ const id = repositoryIdentity(dir);
1035
+ return id === undefined ? undefined : { repo: id.tree, tree: id.tree, shared: id.repo };
1036
+ }
1037
+ /**
1038
+ * QA-DF1-23 (DF-1-9): the background decision waits at most this long for the kind of an unrecorded parent; past it the parent
1039
+ * is no root (the dispatch stays foreground). Short: the dispatch's `execute.before` waits for it.
1040
+ */
1041
+ export const SESSION_KIND_DISPATCH_TIMEOUT_MS = 1_000;
1042
+ /** QA-2.1-11: session directories cached (oldest first out). */
1043
+ const MAX_SESSION_DIRS = 1000;
1044
+ /** QA-2.1-13: parent sessions remembered as adopted (oldest first out). */
1045
+ const MAX_ADOPTED_SESSIONS = 5000;
1046
+ /** DF-1-4: the children whose completion elements are remembered, and the elements kept per child. */
1047
+ const MAX_SEEN_COMPLETION_CHILDREN = 1000;
1048
+ const MAX_SEEN_COMPLETION_ELEMENTS = 64;
1049
+ /** QA-2.1-8: a failed pending-journal reload is tried again at most this often (fail closed meanwhile). */
1050
+ export const PENDING_RELOAD_RETRY_MS = 30_000;
1051
+ /** QA-2.1-8: `dispose` waits at most this long for the background work in flight (verdict posts, recoveries). */
1052
+ const BACKGROUND_DRAIN_MS = 5_000;
1053
+ /**
1054
+ * Non-enumerable slot on the cleanup function `registerV2Hooks` returns: `() => Promise<void>` that resolves once no background
1055
+ * work is in flight (verdict posts, recoveries, reloads, including work they start). Lets integration tests await what an
1056
+ * adoption or a gate started instead of polling for it; nothing in the plugin reads it.
1057
+ */
1058
+ export const V2_BACKGROUND_SETTLED: unique symbol = Symbol("opencode-model-router.v2.background-settled");
1059
+ // QA-2.1-26: a module-private `Symbol()` (not the global registry `Symbol.for`): only code importing this module reaches the seam.
1060
+
1061
+ /** The completion elements of a text part that STARTS with one (the host writes a completion as a whole message, C2). */
1062
+ function completionElementsOf(text: string): CompletionElement[] {
1063
+ if (!text.trimStart().startsWith("<subagent sessionID=\"")) return [];
1064
+ const found: CompletionElement[] = [];
1065
+ for (const m of text.matchAll(COMPLETION_ELEMENT)) {
1066
+ const state = m[2];
1067
+ if (state !== "completed" && state !== "error" && state !== "cancelled") continue;
1068
+ found.push({ child: m[1] ?? "", state, body: m[3] ?? "" });
1069
+ }
1070
+ return found;
1071
+ }
1072
+
1073
+ /**
1074
+ * QA-DF1-20: the identity of the message that holds a completion element, never its content: the host's message id when the
1075
+ * message carries one, else its position in the request's history (a session's history only grows between its requests).
1076
+ */
1077
+ function completionMessageKey(message: object, index: number): string {
1078
+ const id = "id" in message ? message.id : undefined;
1079
+ if (typeof id === "string" && id !== "") return `id:${id}`;
1080
+ return `at:${index}`;
1081
+ }
1082
+
1083
+ /** Applies `defang` to the body of every `<subagent …>` element of a text (a pure rewrite; the element tags stay). */
1084
+ function defangSubagentBodies(text: string, defang: (body: string) => string): string {
1085
+ if (!text.includes("<subagent sessionID=\"")) return text;
1086
+ return text.replace(COMPLETION_ELEMENT, (whole: string, _child: string, _state: string, body: string) => {
1087
+ const next = defang(body);
1088
+ if (next === body) return whole;
1089
+ const closed = whole.endsWith("</subagent>");
1090
+ const open = whole.slice(0, whole.length - body.length - (closed ? "</subagent>".length : 0));
1091
+ return `${open}${next}${closed ? "</subagent>" : ""}`;
1092
+ });
1093
+ }
1094
+
1095
+ /** Memo §12 (fail closed): replaces the body of every completion element whose child `isProcessed` rejects. Pure; the element tags stay. */
1096
+ function redactUnprocessedElements(text: string, isProcessed: (child: string) => boolean): string {
1097
+ if (!text.includes("<subagent sessionID=\"")) return text;
1098
+ return text.replace(COMPLETION_ELEMENT, (whole: string, child: string, _state: string, was: string) => {
1099
+ if (isProcessed(child)) return whole;
1100
+ const body = `[router] The result of session ${child} is withheld: the router could not restore its verification state.`;
1101
+ const closed = whole.endsWith("</subagent>");
1102
+ const open = whole.slice(0, whole.length - was.length - (closed ? "</subagent>".length : 0));
1103
+ return `${open}${body}${closed ? "</subagent>" : ""}`;
1104
+ });
1105
+ }
1106
+
1107
+ /** 3.1.7 W4: a v2 event error (`type`, `message`, an optional HTTP status) as the executor's `HostError`. */
1108
+ function toHostError(error: unknown): HostError {
1109
+ const record = typeof error === "object" && error !== null ? (error as Record<string, unknown>) : {};
1110
+ const type = typeof record.type === "string" ? record.type : typeof record.name === "string" ? record.name : "unknown";
1111
+ const message = typeof record.message === "string" ? record.message : typeof error === "string" ? error : "";
1112
+ const raw = record.status ?? record.statusCode;
1113
+ return { type, status: typeof raw === "number" && Number.isFinite(raw) ? raw : null, message };
1114
+ }
1115
+
1116
+ /**
1117
+ * Host adapters v2-hooks builds for the plan executor (3.1.7 W1, memo 3.1.1 §8). The executor factory composes the
1118
+ * launcher and the runtime over them; v2-hooks never constructs the runtime itself (its collaborators arrive later).
1119
+ */
1120
+ export interface V2ExecutorHost {
1121
+ /** `HostSessions` over `ctx.session` plus the one host-event emitter (M46). */
1122
+ hosts: HostSessions;
1123
+ /**
1124
+ * The routing kernel with the tier pin and the agent/model. null here: `dispatchRouter.route` is asynchronous and the port is
1125
+ * synchronous, so the factory supplies the resolver (open for 3.1.8 / 5.1).
1126
+ */
1127
+ routes: RouteResolver | null;
1128
+ /** `bindPlanChild` / binding.ts `evict`. */
1129
+ bindings: PlanRoleBindings;
1130
+ /** Decision row, dispatch start and the background in-flight registry; rows tagged `source: "executor"`. */
1131
+ bookkeeping: DispatchBookkeeping;
1132
+ /** The verification engine as a slot verifier; null when this host has none. */
1133
+ verifier: PlanTaskVerifier | null;
1134
+ /** The adapter's shared registry, including its release notification. */
1135
+ leases: { registry: LeaseRegistry; notifyReleased(): void } | null;
1136
+ durations: DurationModel | null;
1137
+ /** The Phase 1.3 lease registry; null when this host has none. */
1138
+ leaseRegistry: LeaseRegistryPort | null;
1139
+ /** The child runner the launcher drives (v2-client); null when the runtime passed to v2-hooks has none. */
1140
+ runner: ChildRunner | null;
1141
+ /** `childRunner.pin`: keeps the orchestrator's retained context alive while its plan runs. */
1142
+ pinOrchestrator(sessionID: string): () => void;
1143
+ /** `TaskLauncherDeps.onMetric`: forwards to `ExecutorRuntimeHandle.recordMetric` once the executor exists. */
1144
+ onLauncherMetric(planId: PlanId, m: MetricPayload): void;
1145
+ /** `TaskLauncherDeps.knownAgent`. */
1146
+ knownAgent(agent: string): boolean;
1147
+ /** Plugin lifetime (`TaskLauncherDeps.lifetime`); aborted on dispose. */
1148
+ lifetime: AbortSignal;
1149
+ /**
1150
+ * QA-5.1-26: hands the adapter an executor assembled after the factory returned (a claim handover). The adapter adopts it
1151
+ * through the path it adopts the factory's executor by (its providers and hooks, `start()`, the W7 dispose) and answers
1152
+ * true. False: not adopted (the adapter is disposing, or it already holds another executor); the caller disposes it.
1153
+ */
1154
+ onExecutor(built: V2Executor): boolean;
1155
+ }
1156
+
1157
+ /** The composed executor: the runtime plus the launcher it drives (W7 disposes both, runtime first). */
1158
+ export interface V2Executor {
1159
+ runtime: ExecutorRuntimeHandle;
1160
+ launcher: Pick<TaskLauncher, "dispose">;
1161
+ }
1162
+
1163
+ /** Builds the executor over the host adapters, or null when the executor is not enabled (M3: then nothing changes). */
1164
+ export type V2ExecutorFactory = (host: V2ExecutorHost) => V2Executor | null;
1165
+
675
1166
  export async function registerV2Hooks(
676
1167
  ctx: Context,
677
1168
  hooks: Hooks,
678
- runtime?: Pick<V2Runtime, "withToolContext" | "applyChildSystem"> & Partial<Pick<V2Runtime, "dispose" | "forgetSession">>,
1169
+ runtime?: Pick<V2Runtime, "withToolContext" | "applyChildSystem"> & Partial<Pick<V2Runtime, "dispose" | "forgetSession" | "childRunner">>,
679
1170
  /**
680
1171
  * `ingest`: the plugin instance's telemetry ingest (M6, QA-2.1-7); without one the adapter ingests nothing.
681
1172
  * `isBypassed`: the plugin's `/bypass` state (#84 P2.1: the role path's router-gate condition, S10/P-9).
@@ -684,6 +1175,7 @@ export async function registerV2Hooks(
684
1175
  * `hostSettleMs`: how long a role dispatch's result waits for the child's execution-end event (default 500 ms).
685
1176
  */
686
1177
  options: {
1178
+ observations?: V2Observations;
687
1179
  ingest?: Ingest; isBypassed?: () => boolean; hostBudget?: HostBudgetObserver; hostSettleMs?: number;
688
1180
  onHostBudget?: (observe: (childSessionID: string, stepLimit: number | null) => HostBudgetObservation) => void;
689
1181
  /**
@@ -702,12 +1194,28 @@ export async function registerV2Hooks(
702
1194
  listWorktrees?: (cwd: string) => Promise<string>;
703
1195
  /** Role-agent registration (roles mode): the repository's worktree roots for the `external_directory` allow rules. Default: `listWorktrees` (role-agents.ts, a real `git worktree list`). */
704
1196
  listRegistrationWorktrees?: (directory: string) => Promise<string[]>;
1197
+ /** Cross-repo Phase 4 (SD-P4-15): directory of the repository approvals store read at role registration. Default: `dirname(statePath())` (approvals.ts). */
1198
+ approvalsDir?: string;
705
1199
  /**
706
1200
  * QA-G-A3-2: the plugin's count of a role child's call refused outside its guard (index.ts `recordRoleRefusal`): the router's
707
1201
  * role-authority refusal here in `execute.before`, a host permission denial in `execute.after`. Returns the guard's text to
708
1202
  * add to the refusal (its denied_cap stop or advisory banner), or undefined. Absent: refusals are not counted.
709
1203
  */
710
1204
  recordRefusal?: (sessionID: string, agent: string | undefined, tool: string, args: unknown) => string | undefined;
1205
+ /**
1206
+ * Plan task 3.1.7: builds the plan executor over the host adapters (W1). Absent, or returning null: no executor, and nothing
1207
+ * changes (M3). The fail-closed check of plan children (M41) is on either way.
1208
+ */
1209
+ executor?: V2ExecutorFactory;
1210
+ /** W1: the Phase 1.3 lease registry the executor's leases go through; absent: the executor gets none. */
1211
+ leaseRegistry?: LeaseRegistryPort;
1212
+ /** W1: the verification engine as a slot verifier; absent: the executor gets none. */
1213
+ slotVerifier?: PlanTaskVerifier;
1214
+ /**
1215
+ * QA-PDF21-2-11/-20: the plugin's guard state of executor children (index.ts `routerOnExecutorChildGuard`): a resume's new
1216
+ * guard round and read-cap round, and a freshly bound child's read cap from its launch prompt's cap line. Absent: neither.
1217
+ */
1218
+ executorChildGuard?: ExecutorChildGuardPort;
711
1219
  } = {},
712
1220
  ): Promise<() => Promise<void>> {
713
1221
  // The old plugin surface uses separate mutable input/output bags. Keep those
@@ -741,6 +1249,27 @@ export async function registerV2Hooks(
741
1249
  // M6 (2.1.3): child-session outcomes and costs reach the outcome store through the plugin instance's ingest, which
742
1250
  // does nothing unless routing.engine != static (its settings are null otherwise: no bundle, no files).
743
1251
  const ingestLogger = createPluginLogger();
1252
+ // Phase 1.2: the turn-state registry of this adapter instance. The legacy plugin registers its late/pending providers on it
1253
+ // through the attach hook; the system augmenter registers the route hint; `buildContext` places the tail (root sessions only).
1254
+ const turnState = createTurnStateRegistry({ logger: ingestLogger, translate: v2Instructions });
1255
+ const attachTurnState = (hooks as unknown as Record<PropertyKey, unknown>)[ROUTER_TURN_STATE_ATTACH];
1256
+ /** The plugin accepted the registry (its attach function returned `true`): only then does the tail carry the route hint. */
1257
+ let turnStateAttached = false;
1258
+ if (typeof attachTurnState === "function") {
1259
+ try {
1260
+ turnStateAttached = (attachTurnState as (registry: TurnStateRegistry) => unknown)(turnState) === true;
1261
+ } catch (error) {
1262
+ ingestLogger.warn("[router] turn state: the plugin could not attach the registry", { error: String(error) });
1263
+ }
1264
+ }
1265
+ let turnStateWarned = false;
1266
+ const warnTurnStateOnce = (error: unknown): void => {
1267
+ if (turnStateWarned) return;
1268
+ turnStateWarned = true;
1269
+ ingestLogger.warn("[router] turn state: the tail was not placed; the request goes on without it", { error: String(error) });
1270
+ };
1271
+ type ContextMessage = NonNullable<SessionContext["messages"]>[number];
1272
+ const tailMessage = (text: string): ContextMessage => ({ role: "user", content: [{ type: "text", text }] });
744
1273
  const ingest: Ingest = options.ingest ?? NOOP_INGEST;
745
1274
  // An ingestion error is logged and the loop carries on: it must never cost the router an event.
746
1275
  const ingesting = async (what: string, run: () => void | Promise<void>): Promise<void> => {
@@ -750,6 +1279,230 @@ export async function registerV2Hooks(
750
1279
  if (!abort.signal.aborted) ingestLogger.warn(`[router] telemetry ingestion: ${what} failed`, { error: error instanceof Error ? error.message : String(error) });
751
1280
  }
752
1281
  };
1282
+ // ---------------------------------------------------------------------------------------------------------------
1283
+ // Plan task 3.1.7 (memo 3.1.1 §8): the plan executor's seams. `executor` stays null unless `options.executor` builds one
1284
+ // (M3: then nothing below changes behaviour); the fail-closed check of plan children (M41) is on either way. QA-5.1-26: it
1285
+ // is set only by `adopt`, for the factory's executor at start or one a claim handover assembles later (`host.onExecutor`).
1286
+ // ---------------------------------------------------------------------------------------------------------------
1287
+ let executor: V2Executor | null = null;
1288
+ /** W1: the plugin lifetime the launcher combines with each launch's own controller; aborted on dispose (W7). */
1289
+ const executorLifetime = new AbortController();
1290
+ /** M46: the one host-event path. v2-hooks only emits; the runtime and the launcher subscribe through `hosts.onEvent`. */
1291
+ const hostEventListeners = new Set<(e: HostSessionEvent) => void>();
1292
+ const emitHostEvent = (e: HostSessionEvent): void => {
1293
+ if (executor === null || hostEventListeners.size === 0) return;
1294
+ for (const listener of [...hostEventListeners]) {
1295
+ try {
1296
+ listener(e);
1297
+ } catch (error) {
1298
+ ingestLogger.warn("[router] executor: a host-event listener failed", { error: String(error) });
1299
+ }
1300
+ }
1301
+ };
1302
+ /**
1303
+ * W4 (M19), QA-3.1-8: the adapter is the single owner of the step key `<sessionID>:<k>`; it sets the key on every forwarded
1304
+ * retry/step event and on the retry-hook call (the runtime prefers `e.stepKey`). k counts `step.started` after a closed step;
1305
+ * `step.ended` closes the step, `step.failed` closes it only when no retry is pending (memo :163; the retry's own
1306
+ * `step.started` clears the pending mark), `execution.*` closes it and ends the session. So the retries of one step (C10:
1307
+ * `step.started`, `retry.scheduled`…, `step.ended`) carry one key. Only kept while an executor exists; an LRU map capped at
1308
+ * `EXECUTOR_STEPS_CAP` that evicts ended sessions first.
1309
+ */
1310
+ const EXECUTOR_STEPS_CAP = 1000;
1311
+ /** `early`: the step was opened by the retry hook before its `step.started` was processed (QA-3.1-21). */
1312
+ type ExecutorStep = { k: number; open: boolean; retryPending: boolean; ended: boolean; early: boolean };
1313
+ const executorSteps = new Map<string, ExecutorStep>();
1314
+ const touchExecutorStep = (sessionID: string): ExecutorStep => {
1315
+ const st = executorSteps.get(sessionID) ?? { k: 0, open: false, retryPending: false, ended: false, early: false };
1316
+ executorSteps.delete(sessionID); // LRU: the latest use goes last
1317
+ executorSteps.set(sessionID, st);
1318
+ while (executorSteps.size > EXECUTOR_STEPS_CAP) {
1319
+ let victim: string | undefined;
1320
+ for (const [id, s] of executorSteps) {
1321
+ if (s.ended && id !== sessionID) {
1322
+ victim = id;
1323
+ break;
1324
+ }
1325
+ }
1326
+ victim ??= executorSteps.keys().next().value!;
1327
+ executorSteps.delete(victim);
1328
+ }
1329
+ return st;
1330
+ };
1331
+ const noteExecutorStep = (
1332
+ sessionID: string, edge: "started" | "ended" | "failed" | "retry" | "retry-stop" | "execution",
1333
+ ): void => {
1334
+ if (executor === null) return;
1335
+ const st = touchExecutorStep(sessionID);
1336
+ if (edge === "started") {
1337
+ if (st.early) {
1338
+ // QA-3.1-21: the `step.started` of a step the retry hook already opened: a no-op (no second advance, the retry mark kept)
1339
+ st.early = false;
1340
+ return;
1341
+ }
1342
+ st.ended = false;
1343
+ st.retryPending = false;
1344
+ if (!st.open) {
1345
+ st.k += 1;
1346
+ st.open = true;
1347
+ }
1348
+ } else if (edge === "retry" || edge === "retry-stop") {
1349
+ // a scheduled retry, or a retry-hook call that let the host retry, is pending; a hook that stopped it leaves none
1350
+ st.retryPending = edge === "retry";
1351
+ } else if (edge === "failed") {
1352
+ st.early = false;
1353
+ if (!st.retryPending) st.open = false;
1354
+ } else {
1355
+ st.early = false;
1356
+ st.open = false;
1357
+ st.retryPending = false;
1358
+ if (edge === "execution") st.ended = true;
1359
+ }
1360
+ };
1361
+ /**
1362
+ * QA-3.1-21: the retry hook can run before the event loop processed the step's `session.step.started` (the loop can wait on an
1363
+ * ingest). A step that is not open is opened here, so the key the hook reads names this step; its `step.started`, processed
1364
+ * later, is then a no-op (`early`).
1365
+ */
1366
+ const openExecutorStepForHook = (sessionID: string): void => {
1367
+ if (executor === null || executorSteps.get(sessionID)?.open === true) return;
1368
+ noteExecutorStep(sessionID, "started");
1369
+ touchExecutorStep(sessionID).early = true;
1370
+ };
1371
+ const executorStepKey = (sessionID: string): string => `${sessionID}:${executorSteps.get(sessionID)?.k ?? 0}`;
1372
+ /**
1373
+ * 3.1.7 M41 (always on, memo §8): plan children are bound (`bindPlanChild`) before their first tool call. A child session whose
1374
+ * first user message is a launcher prompt (QA-3.1-9: it starts with "PLAN CONTEXT\n", at offset 0 or right after the host's one
1375
+ * exact preamble line (QA-3.1-16), and its launch header sits at the §7 grammar position, `planPromptHeader`) and that has no
1376
+ * plan binding, or one naming another plan task, joins
1377
+ * `refusedPlanChildren` and is refused every tool call (fail closed). The check runs in the context hook; a first tool call
1378
+ * that comes before it (a restart) runs it in `execute.before`. Every caller awaits the same in-flight check (QA-3.1-9 b).
1379
+ */
1380
+ const refusedPlanChildren = new Set<string>();
1381
+ /** Per session, the (in-flight or settled) check of its first user message (bounded). */
1382
+ const planChildChecks = new Map<string, Promise<void>>();
1383
+ const rememberPlanChildCheck = (sessionID: string, check: Promise<void>): void => {
1384
+ planChildChecks.set(sessionID, check);
1385
+ while (planChildChecks.size > 5000) planChildChecks.delete(planChildChecks.keys().next().value!);
1386
+ };
1387
+ /**
1388
+ * QA-3.1-9 (a): the launch header of a launcher prompt (`formatLaunchPrompt`), read by `parseLaunchHeader` at its grammar
1389
+ * position, or null. The shared context has no header-shaped line (the launcher refuses one), so the first header-shaped line
1390
+ * is the header and the text between the prefix and it is the shared context.
1391
+ */
1392
+ const planPromptHeader = (firstText: string): LaunchHeaderFields | null => {
1393
+ // QA-3.1-16: the grammar is checked at offset 0, or right after the host's one exact preamble line, never elsewhere
1394
+ const text = withoutHostPreamble(firstText);
1395
+ if (!text.startsWith(PLAN_CONTEXT_PREFIX)) return null;
1396
+ const m = LAUNCH_HEADER_PATTERN.exec(text);
1397
+ if (m === null || m.index - 2 < PLAN_CONTEXT_PREFIX.length) return null;
1398
+ return parseLaunchHeader(text, text.slice(PLAN_CONTEXT_PREFIX.length, m.index - 2));
1399
+ };
1400
+ /** M41: the session has a plan binding and the prompt's header names that plan task. */
1401
+ const planBindingMatches = (sessionID: string, header: LaunchHeaderFields): boolean => {
1402
+ const plan = currentBinding(sessionID, { maxOf: () => [] })?.plan;
1403
+ return plan !== undefined && header.planId === plan.planId && header.taskId === plan.taskId;
1404
+ };
1405
+ /** The verdict on one session's first user message text: a plan prompt in a non-root session without its binding is refused. */
1406
+ const planChildVerdict = async (sessionID: string, firstText: string): Promise<void> => {
1407
+ const header = planPromptHeader(firstText);
1408
+ if (header === null) return; // not a launcher prompt: never refused, the session kind is not even looked up
1409
+ let kind: Awaited<ReturnType<typeof sessionKindOf>>;
1410
+ try {
1411
+ kind = await sessionKindOf(sessionID);
1412
+ } catch {
1413
+ kind = "unknown"; // a plan prompt in a session of unknown kind: checked as a child (fail closed)
1414
+ }
1415
+ if (kind === "root") return;
1416
+ let matches: boolean;
1417
+ try {
1418
+ matches = planBindingMatches(sessionID, header);
1419
+ } catch {
1420
+ matches = false; // the binding could not be read: fail closed, with the refusal's own message
1421
+ }
1422
+ if (matches) return;
1423
+ refusedPlanChildren.add(sessionID);
1424
+ while (refusedPlanChildren.size > 5000) refusedPlanChildren.delete(refusedPlanChildren.values().next().value!);
1425
+ ingestLogger.warn("[router] executor: a plan child without its plan binding is refused every tool call", { sessionID });
1426
+ };
1427
+ const planChildGuard = {
1428
+ /** The check on the first user message text of a session; once per session, shared by every caller while in flight. */
1429
+ check(sessionID: string, firstText: string | undefined): Promise<void> {
1430
+ if (sessionID === "" || firstText === undefined) return Promise.resolve();
1431
+ const known = planChildChecks.get(sessionID);
1432
+ if (known !== undefined) return known;
1433
+ const check = planChildVerdict(sessionID, firstText);
1434
+ rememberPlanChildCheck(sessionID, check);
1435
+ return check;
1436
+ },
1437
+ /** `execute.before`: the fallback check (or the in-flight one), then the refusal. */
1438
+ async assertToolAllowed(sessionID: string): Promise<void> {
1439
+ if (sessionID !== "" && sessionKinds.get(sessionID) !== "root") {
1440
+ let check = planChildChecks.get(sessionID);
1441
+ if (check === undefined) {
1442
+ /** True when a verdict was reached; false when the first message could not be read. */
1443
+ const verdict = (async (): Promise<boolean> => {
1444
+ let firstText: string | undefined;
1445
+ try {
1446
+ firstText = firstMessageText(await ctx.session.context({ sessionID } as Parameters<typeof ctx.session.context>[0]));
1447
+ } catch {
1448
+ firstText = undefined;
1449
+ }
1450
+ if (firstText === undefined) return false;
1451
+ await planChildVerdict(sessionID, firstText);
1452
+ return true;
1453
+ })();
1454
+ const fallback: Promise<void> = verdict.then((checked) => {
1455
+ // not checked yet: the next call (or the context hook) tries again
1456
+ if (!checked && planChildChecks.get(sessionID) === fallback) planChildChecks.delete(sessionID);
1457
+ });
1458
+ check = fallback;
1459
+ rememberPlanChildCheck(sessionID, fallback);
1460
+ }
1461
+ await check;
1462
+ }
1463
+ if (refusedPlanChildren.has(sessionID)) {
1464
+ throw new Error(`[router] Refused for session ${sessionID}: its prompt carries a plan task header but the session has no matching plan binding (fail closed)`);
1465
+ }
1466
+ },
1467
+ };
1468
+ /**
1469
+ * W4/W6 (M34, M46): a v2 session event as the executor's `HostSessionEvent`, emitted on the one path (the orchestrator's
1470
+ * events included, so the runtime sees root idleness). `session.step.started` carries the provider (`model.providerID`).
1471
+ */
1472
+ const forwardHostEvent = (type: string, sessionID: string, data: Record<string, unknown>, created: unknown): void => {
1473
+ if (executor === null) return;
1474
+ const ms = created instanceof Date ? created.getTime() : typeof created === "number" && Number.isFinite(created) ? created : Date.now();
1475
+ const at: IsoTime = new Date(ms).toISOString();
1476
+ const text = (value: unknown): string => (typeof value === "string" ? value : "");
1477
+ const error = (): HostError => toHostError(data.error ?? data);
1478
+ // QA-3.1-8: every step/retry event carries the adapter's step key, read after the edge that opens a step and before the
1479
+ // edge that closes it.
1480
+ if (type === "session.step.started") {
1481
+ noteExecutorStep(sessionID, "started");
1482
+ const model = typeof data.model === "object" && data.model !== null ? (data.model as Record<string, unknown>) : {};
1483
+ emitHostEvent({
1484
+ type: "step.started", sessionID, providerID: text(model.providerID), modelID: text(model.id ?? model.modelID),
1485
+ stepKey: executorStepKey(sessionID), at,
1486
+ });
1487
+ } else if (type === "session.retry.scheduled") {
1488
+ noteExecutorStep(sessionID, "retry");
1489
+ emitHostEvent({ type: "retry", sessionID, stepKey: executorStepKey(sessionID), source: "scheduled", error: error(), at });
1490
+ } else if (type === "session.step.ended") {
1491
+ emitHostEvent({ type: "step.ended", sessionID, stepKey: executorStepKey(sessionID), at });
1492
+ noteExecutorStep(sessionID, "ended");
1493
+ } else if (type === "session.step.failed") {
1494
+ emitHostEvent({ type: "step.failed", sessionID, error: error(), stepKey: executorStepKey(sessionID), at });
1495
+ noteExecutorStep(sessionID, "failed");
1496
+ } else if (type === "session.execution.failed") {
1497
+ executorInFlight.noteEnd(sessionID, "failed");
1498
+ emitHostEvent({ type: "execution.failed", sessionID, error: error(), stepKey: executorStepKey(sessionID), at });
1499
+ noteExecutorStep(sessionID, "execution");
1500
+ } else if (type === "session.execution.succeeded" || type === "session.execution.interrupted") {
1501
+ executorInFlight.noteEnd(sessionID, type === "session.execution.succeeded" ? "succeeded" : "interrupted");
1502
+ emitHostEvent({ type: type === "session.execution.succeeded" ? "execution.completed" : "execution.interrupted", sessionID, at });
1503
+ noteExecutorStep(sessionID, "execution");
1504
+ }
1505
+ };
753
1506
  // M7 (2.2): dispatch routing and the protocol/hint adaptation share one runtime; it touches nothing (no host call, no
754
1507
  // store, no disk) while routing.engine is static, which is the default and what every config without a `routing` block is.
755
1508
  const sessionOf = (sessionID: string): Promise<unknown> => ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]);
@@ -801,13 +1554,25 @@ export async function registerV2Hooks(
801
1554
  return live.length === roles.size ? roles : new Map(live);
802
1555
  };
803
1556
  const maxOfRoles = (roles: ReadonlyMap<string, RoleSpec>) => (agent: string) => roleMaxActions(roles.get(agent));
1557
+ const warnBindingLookup = (message: string, child: string, error: unknown): void => {
1558
+ const extra = { child, error: String(error) };
1559
+ if (takeRoleBindingLookupNotice()) ingestLogger.warn(message, extra);
1560
+ else console.debug(message, extra);
1561
+ };
804
1562
  /** Handoff 32: what the binding reads of a child session (parent, agent, title, first message text). */
805
1563
  const bindingLookup: SessionLookup = async (id) => {
806
- const session = await ctx.session.get({ sessionID: id } as Parameters<typeof ctx.session.get>[0]) as unknown as Record<string, unknown>;
1564
+ let session: Record<string, unknown>;
1565
+ try {
1566
+ session = await ctx.session.get({ sessionID: id } as Parameters<typeof ctx.session.get>[0]) as unknown as Record<string, unknown>;
1567
+ } catch (error) {
1568
+ warnBindingLookup("[router] roles: a binding session could not be read", id, error);
1569
+ throw error; // bind treats this as lookupFailed, without caching it
1570
+ }
807
1571
  let firstText: string | undefined;
808
1572
  try {
809
1573
  firstText = firstMessageText(await ctx.session.context({ sessionID: id } as Parameters<typeof ctx.session.context>[0]));
810
- } catch {
1574
+ } catch (error) {
1575
+ warnBindingLookup("[router] roles: a child's first message could not be read", id, error);
811
1576
  firstText = undefined; // the title marker still binds
812
1577
  }
813
1578
  const text = (value: unknown): string | undefined => (typeof value === "string" && value !== "" ? value : undefined);
@@ -895,11 +1660,58 @@ export async function registerV2Hooks(
895
1660
  if (typeof recorded === "string" && registeredRole(recorded)) return recorded;
896
1661
  return currentBinding(sessionID, { maxOf: () => [] }) !== undefined ? "(bound role session)" : undefined;
897
1662
  };
898
- /** The directory the host resolves a session's relative paths against (its location), else the plugin's. */
899
- const sessionDirectoryOf = async (sessionID: string): Promise<string> => {
900
- const session = await ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]) as unknown as { location?: { directory?: unknown } };
901
- const directory = session?.location?.directory;
902
- return typeof directory === "string" && directory !== "" ? directory : ctx.location.directory;
1663
+ /**
1664
+ * The directory the host resolves a session's relative paths against (its location), else the plugin's; and the session's
1665
+ * parent (cross-repo P1.5: the orchestrator whose working set widens R). QA-2.1-11: cached per session (a session's location
1666
+ * and parent do not move), concurrent lookups share one host call, and a failed lookup is remembered for
1667
+ * SESSION_DIR_NEGATIVE_TTL_MS so a tool hook does not pay a failing `ctx.session.get` per call. Bounded; forgotten with the session.
1668
+ */
1669
+ type SessionInfo = { directory: string; parentID: string | undefined; agent?: string };
1670
+ const sessionDirs = new Map<string, { at: number; info: Promise<SessionInfo>; failed: boolean }>();
1671
+ const sessionInfoOf = (sessionID: string): Promise<SessionInfo> => {
1672
+ const cached = sessionDirs.get(sessionID);
1673
+ if (cached !== undefined && (!cached.failed || Date.now() - cached.at < SESSION_DIR_NEGATIVE_TTL_MS)) return cached.info;
1674
+ const entry: { at: number; failed: boolean; info: Promise<SessionInfo> } = {
1675
+ at: Date.now(), failed: false, info: Promise.resolve<SessionInfo>({ directory: ctx.location.directory, parentID: undefined }),
1676
+ };
1677
+ entry.info = (async () => {
1678
+ const session = await ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]) as unknown as {
1679
+ location?: { directory?: unknown }; parentID?: unknown; agent?: unknown;
1680
+ };
1681
+ const directory = session?.location?.directory;
1682
+ const parentID = session?.parentID;
1683
+ return {
1684
+ directory: typeof directory === "string" && directory !== "" ? directory : ctx.location.directory,
1685
+ parentID: typeof parentID === "string" && parentID !== "" ? parentID : undefined,
1686
+ agent: typeof session?.agent === "string" && session.agent !== "" ? session.agent : undefined,
1687
+ };
1688
+ })();
1689
+ entry.info.catch(() => {
1690
+ // Negative cache: the rejection itself reaches every caller of this entry until the TTL passes.
1691
+ entry.failed = true;
1692
+ entry.at = Date.now();
1693
+ });
1694
+ sessionDirs.delete(sessionID);
1695
+ sessionDirs.set(sessionID, entry);
1696
+ while (sessionDirs.size > MAX_SESSION_DIRS) sessionDirs.delete(sessionDirs.keys().next().value!);
1697
+ return entry.info;
1698
+ };
1699
+ /** The directory half of {@link sessionInfoOf} (the work-lease wiring's `sessionDir`). */
1700
+ const sessionDirectoryOf = (sessionID: string): Promise<string> => sessionInfoOf(sessionID).then((info) => info.directory);
1701
+ /**
1702
+ * Cross-repo P1.5: the read set R of a role session beyond its work root (`routing/roles/read-set.ts`) — the worktrees of its
1703
+ * orchestrator's working set (the session that dispatched it: its dispatch record, else the session's parent) and the
1704
+ * repositories below `routing.repoParents`. Only for an exact binding with a work root; undefined when R adds nothing (no
1705
+ * parents and no working set: I9). The probe (`.git` and `HEAD`, synchronous) is cached 5 s per directory.
1706
+ */
1707
+ const repoProbe = createRepoProbe();
1708
+ const readSetOf = (sessionID: string, binding: Pick<Binding, "kind" | "grant">, parentID: string | undefined): InReadSet | undefined => {
1709
+ if (binding.kind !== "exact" || binding.grant.workRoot === null) return undefined;
1710
+ const routing = resolveRolesRouting(loadConfig(ctx.location.directory), "v2");
1711
+ const recorded = lookupDispatch(sessionID)?.parentSessionID;
1712
+ const orchestrator = typeof recorded === "string" && recorded !== "" ? recorded : parentID;
1713
+ const workingSet = orchestrator === undefined ? [] : workingSetOf(orchestrator);
1714
+ return readSetPredicate({ parents: routing.repoParents, depth: routing.repoDepth, exclude: routing.repoExclude }, workingSet, repoProbe);
903
1715
  };
904
1716
  /**
905
1717
  * §2.2: a sibling work root is re-checked against a fresh `git worktree list --porcelain` when `external_directory` is
@@ -910,9 +1722,10 @@ export async function registerV2Hooks(
910
1722
  */
911
1723
  const listWorktreesOf = options.listWorktrees ?? gitWorktreeList;
912
1724
  const worktreeChecks = new Map<string, { at: number; listed: Promise<boolean> }>();
913
- const checkWorktree = async (root: string): Promise<boolean> => {
1725
+ /** Cross-repo P1.5: lists the repository of the binding's grant (`grant.location.repository`), else the plugin's directory. */
1726
+ const checkWorktree = async (root: string, repository: string): Promise<boolean> => {
914
1727
  try {
915
- return listedWorktreeRoot(await listWorktreesOf(ctx.location.directory), root);
1728
+ return listedWorktreeRoot(await listWorktreesOf(repository), root);
916
1729
  } catch {
917
1730
  return false;
918
1731
  }
@@ -940,14 +1753,15 @@ export async function registerV2Hooks(
940
1753
  while (ownOutputs.size > 1000) ownOutputs.delete(ownOutputs.keys().next().value!);
941
1754
  }
942
1755
  };
943
- const stillAWorktree = (root: string): Promise<boolean> => {
1756
+ const stillAWorktree = (root: string, repository: string): Promise<boolean> => {
944
1757
  const own = fallbackRoot();
945
1758
  if (own !== undefined && normalizeRootText(own) === normalizeRootText(root)) return Promise.resolve(true);
946
- const cached = worktreeChecks.get(root);
1759
+ const key = `${normalizeRootText(repository)}\u0000${root}`;
1760
+ const cached = worktreeChecks.get(key);
947
1761
  if (cached !== undefined && Date.now() - cached.at < 5_000) return cached.listed;
948
- const listed = checkWorktree(root);
949
- worktreeChecks.delete(root);
950
- worktreeChecks.set(root, { at: Date.now(), listed });
1762
+ const listed = checkWorktree(root, repository);
1763
+ worktreeChecks.delete(key);
1764
+ worktreeChecks.set(key, { at: Date.now(), listed });
951
1765
  while (worktreeChecks.size > 64) worktreeChecks.delete(worktreeChecks.keys().next().value!);
952
1766
  return listed;
953
1767
  };
@@ -967,27 +1781,41 @@ export async function registerV2Hooks(
967
1781
  const roleEvaluateRefusal = async (
968
1782
  event: { sessionID: unknown; action: string; resources: readonly string[]; metadata?: Record<string, unknown> | undefined },
969
1783
  agent: string,
970
- ): Promise<string | undefined> => {
1784
+ ): Promise<{ readonly refusal: string | undefined; readonly exact: boolean; readonly lift: boolean }> => {
971
1785
  const sessionID = String(event.sessionID);
972
1786
  const authority = await roleAuthorityOf(sessionID, agent);
973
- if (authority === undefined) return "the role table is unavailable (fail closed)";
1787
+ if (authority === undefined) return { refusal: "the role table is unavailable (fail closed)", exact: false, lift: false };
1788
+ const exact = authority.binding.kind === "exact";
974
1789
  const cls = roleActionOf(event.action);
975
1790
  const metadata = event.metadata !== null && typeof event.metadata === "object" ? event.metadata : undefined;
976
1791
  const search = cls === "glob" || cls === "grep";
1792
+ // QA-1 F1: a search the call named no root for (the host's `.`) never reaches R.
1793
+ const namedRoot = search && typeof metadata?.path === "string" && metadata.path !== "" ? metadata.path : undefined;
977
1794
  const paths = cls === "read" || cls === "edit" || cls === "external_directory" ? event.resources
978
- : search && metadata !== undefined ? [typeof metadata.path === "string" && metadata.path !== "" ? metadata.path : "."] : [];
1795
+ : search && metadata !== undefined ? [namedRoot ?? "."] : [];
979
1796
  const patterns = searchPatterns(cls, event.resources[0], metadata?.include);
1797
+ const info = paths.length > 0 ? await sessionInfoOf(sessionID) : undefined;
1798
+ const readSet = info === undefined ? undefined : readSetOf(sessionID, authority.binding, info.parentID);
980
1799
  const decision = roleAuthorityDecision({
981
1800
  action: event.action, paths, patterns, binding: authority.binding, dynamic: authority.spec.authority.mode === "dynamic",
982
- sessionDirectory: paths.length > 0 ? await sessionDirectoryOf(sessionID) : ctx.location.directory, fallbackRoot: fallbackRoot(),
983
- ownOutputs: ownOutputs.get(sessionID),
1801
+ sessionDirectory: info?.directory ?? ctx.location.directory, fallbackRoot: fallbackRoot(),
1802
+ ownOutputs: ownOutputs.get(sessionID), inReadSet: readSet,
1803
+ // QA-1 F1: a relative read/edit resource is the host's Location-relative form; execute.before checked the call as written.
1804
+ hostRelative: cls === "read" || cls === "edit",
1805
+ implicitRoot: search && namedRoot === undefined,
984
1806
  });
985
- if (!decision.allow) return decision.reason;
986
- const root = authority.binding.grant.workRoot;
987
- if (cls === "external_directory" && root !== null && !(await stillAWorktree(root))) {
988
- return `external_directory: the work root ${root} is no longer a worktree listed by \`git worktree list --porcelain\``;
1807
+ if (!decision.allow) return { refusal: decision.reason, exact, lift: false };
1808
+ const grant = authority.binding.grant;
1809
+ const root = grant.workRoot;
1810
+ if (cls === "external_directory" && root !== null && !(await stillAWorktree(root, grant.location?.repository ?? ctx.location.directory))) {
1811
+ return { refusal: `external_directory: the work root ${root} is no longer a worktree listed by \`git worktree list --porcelain\``, exact, lift: false };
989
1812
  }
990
- return undefined;
1813
+ // QA-1 F6 (D13, I18): the lift is for an exact binding's `external_directory` allowed by W or R only — never by the session's
1814
+ // own output directory — and only while cross-repo is in use (`routing.repoParents`, a working set, or a grant that carries its
1815
+ // repository's location); otherwise a host ask stays an ask (I9).
1816
+ const crossRepo = readSet !== undefined || grant.location !== undefined;
1817
+ const lift = exact && cls === "external_directory" && crossRepo && (decision.via === "work-root" || decision.via === "read-set");
1818
+ return { refusal: undefined, exact, lift };
991
1819
  };
992
1820
  /**
993
1821
  * T2.3.1 (P-12, S11): the `execute.before` side of EVERY tool call a role session makes — the tool's role action must be in the
@@ -997,35 +1825,51 @@ export async function registerV2Hooks(
997
1825
  * (`router_run`, `router_git_*`: no `evaluate`, S11) and for Code Mode `execute` (S8). A tool outside every role class —
998
1826
  * `subagent` included — is refused here too (QA-P23-A7), whatever the agent's max policy or the parent's grants say.
999
1827
  */
1000
- const roleToolRefusal = async (event: { sessionID: unknown; tool: string }, args: any, agent: string): Promise<string | undefined> => {
1828
+ const roleToolRefusal = async (event: { sessionID: unknown; tool: string; input?: unknown }, args: any, agent: string): Promise<string | undefined> => {
1001
1829
  const cls = roleActionOf(event.tool);
1002
1830
  if (cls === undefined && event.tool !== "execute" && event.tool !== AUTHORITY_TOOL_NAME) return `${event.tool} is outside every role's authority`;
1003
1831
  const sessionID = String(event.sessionID);
1004
1832
  const authority = await roleAuthorityOf(sessionID, agent);
1005
1833
  if (authority === undefined) return "the role table is unavailable (fail closed)";
1006
1834
  const record = args !== null && typeof args === "object" ? args as Record<string, unknown> : {};
1007
- const sessionDirectory = await sessionDirectoryOf(sessionID);
1835
+ const info = await sessionInfoOf(sessionID);
1836
+ const sessionDirectory = info.directory;
1008
1837
  let paths: string[] = [];
1838
+ let implicitRoot = false;
1009
1839
  if (cls === "read" || cls === "edit") {
1010
- const named = toolCallPaths(event.tool, record);
1011
- if (named === undefined) return `${event.tool}: no path to check (or a patch whose paths cannot be read)`;
1012
- paths = named;
1840
+ // QA-2: `scopedArgs` resolves a relative `filePath` against the session directory (and `taskArgs` maps `path` onto `filePath`),
1841
+ // so the call's RAW arguments are read too: a path written relative stays among the checked ones as written, and is never
1842
+ // eligible for R (`readSetEligible`) — only a path inside W passes. The resolved forms are checked next to them.
1843
+ const scoped = toolCallPaths(event.tool, record);
1844
+ const raw = toolCallPaths(event.tool, event.input);
1845
+ if (scoped === undefined && raw === undefined) return `${event.tool}: no path to check (or a patch whose paths cannot be read)`;
1846
+ paths = [...new Set([...(raw ?? []), ...(scoped ?? [])])];
1013
1847
  } else if (cls === "glob" || cls === "grep") {
1014
- paths = [typeof record.path === "string" && record.path !== "" ? record.path : sessionDirectory];
1848
+ const named = typeof record.path === "string" && record.path !== "" ? record.path : undefined;
1849
+ implicitRoot = named === undefined; // QA-1 F1: the session directory by default — W only, never R
1850
+ paths = [named ?? sessionDirectory];
1015
1851
  }
1016
1852
  const decision = roleAuthorityDecision({
1017
1853
  action: event.tool, paths, patterns: searchPatterns(cls, record.pattern, record.include), binding: authority.binding,
1018
1854
  dynamic: authority.spec.authority.mode === "dynamic", sessionDirectory, fallbackRoot: fallbackRoot(), ownOutputs: ownOutputs.get(sessionID),
1855
+ inReadSet: paths.length > 0 ? readSetOf(sessionID, authority.binding, info.parentID) : undefined, implicitRoot,
1019
1856
  });
1020
1857
  return decision.allow ? undefined : decision.reason;
1021
1858
  };
1022
1859
  /** P-3: role children whose catalog failure is already annotated for the parent's current call (cleared when it ends). */
1023
1860
  const catalogFailures = new Set<string>();
1024
- const systemAugmenter = createSystemAugmenter({ runtime: engine, getSession: sessionOf, logger: ingestLogger });
1861
+ // The augmenter keeps the hint in the tail only when the plugin accepted the registry; otherwise (stub or spread hooks, a failed
1862
+ // attach) nothing would render the tail's hint, so it takes the old system push.
1863
+ const systemAugmenter = createSystemAugmenter({
1864
+ runtime: engine, getSession: sessionOf, logger: ingestLogger, turnState: turnStateAttached ? turnState : undefined,
1865
+ });
1025
1866
  let eventTask: Promise<void> | undefined;
1026
1867
  let disposed = false;
1027
1868
  const within = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
1028
1869
  runtime ? runtime.withToolContext(context, operation) : operation();
1870
+ /** QA-PDF12-7: a context rebuilt from journaled data runs its operation but never becomes the parent's retained context. */
1871
+ const withinRebuilt = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
1872
+ runtime ? runtime.withToolContext(context, operation, { retain: false }) : operation();
1029
1873
  const scopedArgs = async (event: { tool: string; input: unknown; sessionID: any }): Promise<any> => {
1030
1874
  const args = taskArgs(event.tool, event.input);
1031
1875
  if (["read", "write", "edit"].includes(event.tool) && typeof args?.filePath === "string" && !isAbsolute(args.filePath)) {
@@ -1037,45 +1881,865 @@ export async function registerV2Hooks(
1037
1881
  const hookContext = (event: { sessionID: any; agent: any; messageID: any; id: any }): ToolContext => ({
1038
1882
  ...event, signal: abort.signal, progress: async () => {},
1039
1883
  });
1040
- const cleanup = async () => {
1041
- if (disposed) return;
1042
- disposed = true;
1043
- abort.abort();
1044
- await runtime?.dispose?.();
1045
- // Before the event task: disposing releases a step handler that waits for the model catalog (QA-2.1-5).
1046
- await ingest.dispose();
1047
- dispatchRouter.dispose(); // this location no longer owns its sessions
1048
- await engine.dispose();
1049
- await eventTask;
1050
- await Promise.allSettled(registrations.map((registration) => registration.dispose()));
1051
- await hooks.dispose?.();
1884
+ /** QA-PDF12-1: how long a rebuilt context waits for the parent session's current agent. */
1885
+ const CALLER_AGENT_LOOKUP_MS = 2_000;
1886
+ /**
1887
+ * QA-PDF12-1: the caller agent of a rebuilt context: the journaled one, else (a record journaled before DF-1.1-1) the parent
1888
+ * session's current agent, looked up within CALLER_AGENT_LOOKUP_MS; undefined when neither is known. Never throws.
1889
+ */
1890
+ /** Runs `work` (a host lookup) for at most CALLER_AGENT_LOOKUP_MS; undefined when it fails or is too slow. Never throws. */
1891
+ const boundedLookup = async (work: () => Promise<string | undefined>): Promise<string | undefined> => {
1892
+ let timer: ReturnType<typeof setTimeout> | undefined;
1893
+ try {
1894
+ const lookup = work().then((value) => value, () => undefined);
1895
+ const timeout = new Promise<undefined>((resolveTimeout) => {
1896
+ timer = setTimeout(() => resolveTimeout(undefined), CALLER_AGENT_LOOKUP_MS);
1897
+ if (typeof timer === "object" && typeof timer.unref === "function") timer.unref();
1898
+ });
1899
+ return await Promise.race([lookup, timeout]);
1900
+ } catch {
1901
+ return undefined;
1902
+ } finally {
1903
+ clearTimeout(timer);
1904
+ }
1052
1905
  };
1053
-
1906
+ /**
1907
+ * QA-PDF12-14: the parent lookups made while at least one restore pass runs are shared per parent, so N restored holds of one
1908
+ * parent cost one lookup each, not N. Dropped when the last running pass ends (a later pass looks again).
1909
+ */
1910
+ let restorePass: { passes: number; agents: Map<string, Promise<string | undefined>>; messages: Map<string, Promise<string | undefined>> } | undefined;
1911
+ const sharedPerParent = (kind: "agents" | "messages", parent: string, work: () => Promise<string | undefined>): Promise<string | undefined> => {
1912
+ const cache = restorePass?.[kind];
1913
+ if (cache === undefined) return boundedLookup(work);
1914
+ let pending = cache.get(parent);
1915
+ if (pending === undefined) {
1916
+ pending = boundedLookup(work);
1917
+ cache.set(parent, pending);
1918
+ }
1919
+ return pending;
1920
+ };
1921
+ const duringRestorePass = async <T>(pass: () => Promise<T>): Promise<T> => {
1922
+ restorePass ??= { passes: 0, agents: new Map(), messages: new Map() };
1923
+ restorePass.passes += 1;
1924
+ try {
1925
+ return await pass();
1926
+ } finally {
1927
+ if (restorePass !== undefined && (restorePass.passes -= 1) <= 0) restorePass = undefined;
1928
+ }
1929
+ };
1930
+ const callerAgentOf = (parentSessionID: string, journaled: string | undefined): Promise<string | undefined> => {
1931
+ if (journaled !== undefined && journaled !== "") return Promise.resolve(journaled);
1932
+ return sharedPerParent("agents", parentSessionID, async () => {
1933
+ const session: unknown = await ctx.session.get({ sessionID: parentSessionID } as Parameters<typeof ctx.session.get>[0]);
1934
+ const agent = (session as { agent?: unknown } | null | undefined)?.agent;
1935
+ return typeof agent === "string" && agent !== "" ? agent : undefined;
1936
+ });
1937
+ };
1938
+ /**
1939
+ * QA-PDF12-12: the message id of a rebuilt context: the journaled one, else (a record journaled before QA-PDF12-5) the id of
1940
+ * the parent's latest assistant message, read from its context within the same bound; undefined when that fails.
1941
+ */
1942
+ const callerMessageIDOf = (parentSessionID: string, journaled: string | undefined): Promise<string | undefined> => {
1943
+ if (journaled !== undefined && journaled !== "") return Promise.resolve(journaled);
1944
+ return sharedPerParent("messages", parentSessionID, async () => {
1945
+ const history: unknown = await ctx.session.context({ sessionID: parentSessionID } as Parameters<typeof ctx.session.context>[0]);
1946
+ const list: unknown = Array.isArray(history) ? history : Reflect.get(Object(history), "messages");
1947
+ if (!Array.isArray(list)) return undefined;
1948
+ for (let i = list.length - 1; i >= 0; i -= 1) {
1949
+ const message: unknown = list[i];
1950
+ if (message === null || typeof message !== "object") continue;
1951
+ const role: unknown = Reflect.get(message, "role") ?? Reflect.get(message, "type");
1952
+ const id: unknown = Reflect.get(message, "id");
1953
+ if (role === "assistant" && typeof id === "string" && id !== "") return id;
1954
+ }
1955
+ return undefined;
1956
+ });
1957
+ };
1958
+ /**
1959
+ * QA-PDF12-1/-5/-7/-9: runs `operation` (a background finish, a restored hold's gate) in the context of the dispatch's caller,
1960
+ * rebuilt from the data the dispatch journaled: its call, the message that made it and the caller agent (else the parent's
1961
+ * current one). The context is never retained as the parent's context.
1962
+ */
1963
+ const withinCaller = async <T>(
1964
+ caller: { parentSessionID: string; callID: string; callerAgent?: string; callerMessageID?: string },
1965
+ operation: () => Promise<T>,
1966
+ /** QA-PDF12-14: false when nothing in `operation` launches as the caller (a completion that did not succeed runs no grader). */
1967
+ lookup = true,
1968
+ ): Promise<T> => {
1969
+ const [agent, messageID] = lookup ? await Promise.all([
1970
+ callerAgentOf(caller.parentSessionID, caller.callerAgent),
1971
+ callerMessageIDOf(caller.parentSessionID, caller.callerMessageID),
1972
+ ]) : [caller.callerAgent, caller.callerMessageID];
1973
+ return withinRebuilt(hookContext({ sessionID: caller.parentSessionID, agent, messageID: messageID ?? "", id: caller.callID }), operation);
1974
+ };
1975
+ // ---------------------------------------------------------------------------------------------------------------------
1976
+ // Phase 2.1 startup (memo §4.1). Everything below is v2-only (this module is loaded by server.ts alone) and inert under
1977
+ // `routing.background.mode: "off"` + `routing.leases.mode: "off"` except the timing rows (telemetry, not visible to the user).
1978
+ // ---------------------------------------------------------------------------------------------------------------------
1979
+ const startRouting = resolveRouting(loadConfig(ctx.location.directory), "v2", ingestLogger);
1980
+ const outcomesDir = resolveOutcomesDir(startRouting.outcomes.path, { tmpdir: tmpdir(), homedir: homedir() });
1981
+ const nowMs = (): number => Date.now();
1982
+ /** Memo §4.1 step 3: the pending journal reload is awaited at most this long before the context hook registers (fail closed after, §12). */
1983
+ const PENDING_RELOAD_BOUND_MS = 5_000;
1984
+ /** Disposers run by `cleanup` (timers, shared registries, installed filters), in reverse order. */
1985
+ const bgDisposers: Array<() => void | Promise<void>> = [];
1986
+ /** 1.1: the timing recorder (whatever `routing.engine` is) and the duration model fed by its rows. */
1987
+ let timings: TimingRecorderHolder | undefined;
1988
+ let durations: DurationModel | undefined;
1054
1989
  try {
1055
- // Captured once: after our own transform, ctx.agent.list() returns
1056
- // router-modified agents, which would defeat the originals diff on refresh.
1057
- const agents = await ctx.agent.list();
1058
- const baseSeed: Record<string, LegacyAgent> = {};
1059
- for (const agent of agents.data) baseSeed[agent.id] = {
1060
- mode: agent.mode,
1061
- model: agent.model && `${agent.model.providerID}/${agent.model.id}`,
1062
- variant: agent.model?.variant,
1063
- };
1064
- let config: LegacyConfig = { agent: {}, command: {} };
1065
- registeredRole = (agent) => roleAgentOf(config.agent[agent]) === agent; // QA-P21-2-4
1066
- let originals = new Map<string, string>();
1067
- let agentOptions = new Map<string, Record<string, unknown>>();
1068
- const warnedPermissions = new Set<string>();
1069
- const warnPermissionOnce = (message: string) => {
1070
- if (warnedPermissions.has(message)) return;
1071
- warnedPermissions.add(message);
1072
- ingestLogger.warn(message);
1073
- };
1074
- const warnedRoles = new Set<string>();
1075
- const warnRoleOnce = (key: string, message: string) => {
1076
- if (warnedRoles.has(key)) return;
1077
- warnedRoles.add(key);
1078
- ingestLogger.warn(message);
1990
+ const model = createDurationModel(durationSeamsFor(createSideLogs(outcomesDir, nodePersistDeps(ingestLogger)), nowMs));
1991
+ durations = model;
1992
+ void model.load(); // not awaited: until it loads, estimates are the prior (never selects a dispatch)
1993
+ const holder = acquireTimingRecorder({
1994
+ dir: outcomesDir, now: nowMs, logger: ingestLogger,
1995
+ onTimingWrite: timingWriteObserver(options.observations),
1996
+ onRow: (row) => { if (row.kind === "dispatch-timing") model.observe(row); },
1997
+ });
1998
+ timings = holder;
1999
+ bgDisposers.push(() => holder.release());
2000
+ } catch (error) {
2001
+ ingestLogger.warn("[router] timing: the recorder could not start; dispatch timings are not recorded", { error: String(error) });
2002
+ }
2003
+ /** Session kinds seen so far (bounded): `root` has no parent. A failed lookup is never cached (root semantics, memo §14.1). */
2004
+ const sessionKinds = new Map<string, "root" | "child">();
2005
+ const noteSessionKind = (sessionID: string, kind: "root" | "child"): void => {
2006
+ sessionKinds.delete(sessionID);
2007
+ sessionKinds.set(sessionID, kind);
2008
+ while (sessionKinds.size > 1000) sessionKinds.delete(sessionKinds.keys().next().value!);
2009
+ };
2010
+ /**
2011
+ * QA-2.1-11: a failed kind lookup is remembered for SESSION_KIND_NEGATIVE_TTL_MS (bounded, like `sessionDirs`), so a tool hook
2012
+ * does not pay a failing host call per call, and it answers `unknown`: root semantics in the lease guard (memo §14.1), child
2013
+ * wording in what it says (a child misread as a root must not be told it is the orchestrator).
2014
+ * QA-2.1-25: `unknown` means no lease, so the window is short (not the 30 s of a session directory): a transient host failure
2015
+ * must not let a child write unleased for long; the next hook after the window asks the host again.
2016
+ */
2017
+ const failedKinds = new Map<string, number>();
2018
+ const sessionKindOf = async (sessionID: string): Promise<"root" | "child" | "unknown"> => {
2019
+ const known = sessionKinds.get(sessionID);
2020
+ if (known !== undefined) return known;
2021
+ const failedAt = failedKinds.get(sessionID);
2022
+ if (failedAt !== undefined && Date.now() - failedAt < SESSION_KIND_NEGATIVE_TTL_MS) return "unknown";
2023
+ try {
2024
+ const session = await sessionOf(sessionID) as { parentID?: unknown } | undefined;
2025
+ const kind = typeof session?.parentID === "string" && session.parentID !== "" ? "child" : "root";
2026
+ failedKinds.delete(sessionID);
2027
+ noteSessionKind(sessionID, kind);
2028
+ return kind;
2029
+ } catch (error) {
2030
+ failedKinds.delete(sessionID);
2031
+ failedKinds.set(sessionID, Date.now());
2032
+ while (failedKinds.size > MAX_SESSION_DIRS) failedKinds.delete(failedKinds.keys().next().value!);
2033
+ // QA-DF1-23: one lookup serves the leases and the background decision; the warning names what each does with the failure.
2034
+ ingestLogger.warn("[router] the session kind could not be read: leases use root semantics with child wording; a background decision stays foreground", {
2035
+ session: sessionID, error: String(error),
2036
+ });
2037
+ return "unknown";
2038
+ }
2039
+ };
2040
+ /**
2041
+ * QA-DF1-23 (DF-1-9): the background decision's lookup of an unrecorded parent, bounded by SESSION_KIND_DISPATCH_TIMEOUT_MS. A
2042
+ * slow host answers `unknown` (no root: the dispatch stays foreground) once the bound passes; the lookup itself goes on and
2043
+ * records the kind for the next dispatch.
2044
+ */
2045
+ const dispatchSessionKindOf = async (sessionID: string): Promise<"root" | "child" | "unknown"> => {
2046
+ let timer: ReturnType<typeof setTimeout> | undefined;
2047
+ const bound = new Promise<"unknown">((resolve) => {
2048
+ timer = setTimeout(() => resolve("unknown"), SESSION_KIND_DISPATCH_TIMEOUT_MS);
2049
+ timer.unref?.();
2050
+ });
2051
+ try {
2052
+ return await Promise.race([sessionKindOf(sessionID), bound]);
2053
+ } finally {
2054
+ if (timer !== undefined) clearTimeout(timer);
2055
+ }
2056
+ };
2057
+ /**
2058
+ * The kind of a session WITHOUT a host call (`session.created` and the `prompt` hook record it): an unknown session is a root,
2059
+ * as in the lease guard (memo §14.1). The dispatch path adds no host call of its own (a static session stays silent, §1.2),
2060
+ * with one exception: DF-1-9 / QA-DF1-23, never for the background decision — while background routing is active
2061
+ * (`bgActive()`), an unrecorded parent is resolved once with `dispatchSessionKindOf` (one `session.get`, bounded by
2062
+ * SESSION_KIND_DISPATCH_TIMEOUT_MS, cached once answered; `unknown` is no root).
2063
+ */
2064
+ const knownKindOf = (sessionID: string): "root" | "child" => sessionKinds.get(sessionID) ?? "root";
2065
+ /** The in-flight registry and held results exist whatever the mode; they hold nothing until a background dispatch is acknowledged. */
2066
+ const bgMode = startRouting.background.mode;
2067
+ const inflight: InFlightRegistry = createInFlightRegistry({
2068
+ now: nowMs, logger: ingestLogger,
2069
+ onClosed: (attempt, cause) => { void closeAttempt?.(attempt, cause); },
2070
+ });
2071
+ // QA-2.1-13: the process-wide call claims of this instance go with it (a reload must not inherit them).
2072
+ bgDisposers.push(() => inflight.dispose());
2073
+ /**
2074
+ * 3.1.7 W1/W5: the executor's in-flight entries (`owner: "executor"`), one call record per task attempt. The launcher calls
2075
+ * `decisionRow`, `recordDispatchStart`, `registerInFlight(.., null)`, then `registerInFlight(.., child)` once the child exists,
2076
+ * and `unregisterInFlight` when its launch completion settles (the only settle point): that submits the `runner` trigger (with
2077
+ * the child's own end status, `noteEnd`, else the launch's settled end kind the launcher passes, QA-3.1-24), so
2078
+ * the processor's D2 dedupe makes a later `execution.*` trigger a duplicate. Excluded from the ordinary completion and
2079
+ * verification path (background.ts `isExecutorOwned`). Keyed by task attempt (the bookkeeping port carries no plan id).
2080
+ */
2081
+ const executorLaunches = new Map<string, {
2082
+ req: LaunchRequest; callID: string; child: string | null; end?: "succeeded" | "failed" | "interrupted";
2083
+ }>();
2084
+ /** Timing-only identities of settled childless launches, for accepted late children; never reopen in-flight work. */
2085
+ const executorLateTimings = new Map<string, string>();
2086
+ const executorAttemptKey = (taskId: string, attempt: number): string => `${taskId}#${attempt}`;
2087
+ const executorInFlight = {
2088
+ /**
2089
+ * QA-3.1 nit 4: the child's own end (its `execution.*` event), carried into the `runner` trigger `unregister` submits.
2090
+ * The latest end wins; a child of no executor launch is ignored.
2091
+ */
2092
+ noteEnd(child: string, status: "succeeded" | "failed" | "interrupted"): void {
2093
+ for (const entry of executorLaunches.values()) {
2094
+ if (entry.child === child) entry.end = status;
2095
+ }
2096
+ },
2097
+ remember(req: LaunchRequest): void {
2098
+ const key = executorAttemptKey(req.taskId, req.attempt);
2099
+ executorLateTimings.delete(key);
2100
+ executorLaunches.delete(key);
2101
+ executorLaunches.set(key, { req, callID: `executor:${req.planId}:${req.taskId}#${req.attempt}:${req.nonce}`, child: null });
2102
+ while (executorLaunches.size > 1000) executorLaunches.delete(executorLaunches.keys().next().value!);
2103
+ },
2104
+ register(taskId: string, attempt: number, child: string | null): void {
2105
+ const key = executorAttemptKey(taskId, attempt);
2106
+ const entry = executorLaunches.get(key);
2107
+ if (entry === undefined) {
2108
+ if (child === null) return;
2109
+ const callID = executorLateTimings.get(key);
2110
+ if (callID === undefined) return;
2111
+ executorLateTimings.delete(key); // consume once, without deciding or acknowledging another in-flight record
2112
+ noteSessionKind(child, "child");
2113
+ timings?.bindChild(callID, child);
2114
+ return;
2115
+ }
2116
+ if (inflight.byCall(entry.callID) === undefined) {
2117
+ inflight.decide({
2118
+ callID: entry.callID, parentSessionID: entry.req.orchestratorSessionID, agent: entry.req.route.agent, role: entry.req.role,
2119
+ description: `plan ${entry.req.planId} task ${taskId}#${attempt}`, verifying: false, verificationMode: "none",
2120
+ decision: { background: true, hold: false, reason: "plan-task" }, at: nowMs(), owner: "executor",
2121
+ });
2122
+ }
2123
+ if (child !== null && entry.child === null) {
2124
+ entry.child = child;
2125
+ noteSessionKind(child, "child");
2126
+ // Retained launches bypass the subagent result hook that binds ordinary dispatch timings.
2127
+ timings?.bindChild(entry.callID, child);
2128
+ inflight.acknowledge(entry.callID, child, { userBackgrounded: false });
2129
+ }
2130
+ },
2131
+ unregister(taskId: string, attempt: number, settled?: ChildEnd["kind"]): void {
2132
+ const key = executorAttemptKey(taskId, attempt);
2133
+ const entry = executorLaunches.get(key);
2134
+ executorLaunches.delete(key);
2135
+ if (entry === undefined) return;
2136
+ if (entry.child === null) {
2137
+ executorLateTimings.set(key, entry.callID);
2138
+ while (executorLateTimings.size > 1000) executorLateTimings.delete(executorLateTimings.keys().next().value!);
2139
+ inflight.cancel(entry.callID);
2140
+ return;
2141
+ }
2142
+ // QA-3.1 nit 4, QA-3.1-24: the observed end, else the launch's settled end kind, else the registry's outcome
2143
+ const status = executorRunnerStatus(entry.end, settled, inflight.byChild(entry.child)?.outcome);
2144
+ const sink = executorProcessor;
2145
+ if (sink !== undefined) trackBackground(sink.process(entry.child, { kind: "runner", status, text: "", at: nowMs() }));
2146
+ else inflight.foreground(entry.callID, entry.child);
2147
+ },
2148
+ };
2149
+ /** W5: the completion processor once the hooks created it (it lives in the hook block below); undefined before and without one. */
2150
+ let executorProcessor: CompletionProcessor | undefined;
2151
+ let closeAttempt: ((attempt: Attempt, cause: string) => Promise<void>) | undefined;
2152
+ /**
2153
+ * ONE journal (memo §11): the plugin's `pending.jsonl` file journal, reached through the finish API once it is attached. The
2154
+ * in-memory set only answers `hasProcessed` before the attach (and when it fails: then nothing persists, fail-closed).
2155
+ */
2156
+ const processedKeys = new Set<string>();
2157
+ const journal: InflightJournal = {
2158
+ append: async (...args: Parameters<InflightJournal["append"]>): Promise<void> => {
2159
+ const record: PersistedRecord = args[0];
2160
+ if (record.kind === "processed") {
2161
+ // The processor writes `{callID, child}` (the attempt key is `child NUL callID`, memo §10).
2162
+ if (typeof record.key === "string") processedKeys.add(record.key);
2163
+ else if (typeof record.child === "string" && typeof record.callID === "string") processedKeys.add(`${record.child}\u0000${record.callID}`);
2164
+ }
2165
+ const shared = finishApi?.journal;
2166
+ if (shared === undefined) return;
2167
+ try {
2168
+ await shared.append(...args);
2169
+ } catch (error) {
2170
+ if (!(error instanceof Error && error.message === PENDING_JOURNAL_VANISHED)) throw error;
2171
+ // QA-2.1-8: a journal that vanished under this process fails closed exactly like a failed reload, until QA-2.1-16
2172
+ // rewrites it from the in-memory state; then this append is tried once more.
2173
+ noteVanished();
2174
+ if (!(await recreateJournal())) throw error;
2175
+ // QA-2.1-16: the state behind this record is usually in memory already (an attempt is acknowledged, a hold text or a
2176
+ // verdict text is kept, before its append), so the recreation wrote it: once per write, never twice.
2177
+ const identity = recordIdentity(record);
2178
+ if (identity !== undefined && recreatedIdentities.has(identity)) return;
2179
+ await shared.append(...args);
2180
+ }
2181
+ },
2182
+ hasProcessed: (key) => processedKeys.has(key) || finishApi?.journal?.hasProcessed(key) === true,
2183
+ };
2184
+ const syntheticRaw: unknown = Reflect.get(ctx.session, "synthetic");
2185
+ const syntheticOk = typeof syntheticRaw === "function";
2186
+ /** The held store, for the compaction hook registered before it exists. */
2187
+ let heldRef: HeldResults | undefined;
2188
+ /** Memo §4.4 step 5: the compaction hook runs the same matcher over the messages being summarised (C15). Registered only when mode ≠ off. */
2189
+ let compactionRegistered = false;
2190
+ if (bgMode !== "off") {
2191
+ try {
2192
+ registrations.push(await ctx.session.hook("compaction", async (event) => {
2193
+ const messages = event.messages;
2194
+ if (heldRef === undefined || !Array.isArray(messages)) return;
2195
+ adoptSession(String(event.sessionID));
2196
+ if (finishApi !== undefined && reloadFailed) {
2197
+ // QA-2.1-8: fail closed exactly like the context hook (memo §12): a summary must not carry a completion this process
2198
+ // cannot prove processed while the journal is not reloaded.
2199
+ const isProcessed = (child: string): boolean => {
2200
+ const attempt = inflight.byChild(child);
2201
+ return attempt !== undefined && journal.hasProcessed(attempt.key);
2202
+ };
2203
+ messages.forEach((source, index) => {
2204
+ const content: unknown = (source as { content?: unknown }).content;
2205
+ if (!Array.isArray(content)) return;
2206
+ let touched = false;
2207
+ const next = content.map((part: unknown) => {
2208
+ const text: unknown = part !== null && typeof part === "object" ? Reflect.get(part, "text") : undefined;
2209
+ const type: unknown = part !== null && typeof part === "object" ? Reflect.get(part, "type") : undefined;
2210
+ if (typeof text !== "string" || (type !== undefined && type !== "text")) return part;
2211
+ const redacted = redactUnprocessedElements(text, isProcessed);
2212
+ if (redacted === text) return part;
2213
+ touched = true;
2214
+ return { ...(part as object), text: redacted };
2215
+ });
2216
+ if (touched) messages[index] = Object.assign(Object.create(Object.getPrototypeOf(source)), source, { content: next });
2217
+ });
2218
+ }
2219
+ const shaped = messages.map((source) => ({ source, parts: (source as { content?: unknown }).content }));
2220
+ const result = heldRef.apply(String(event.sessionID), shaped);
2221
+ if (result === undefined) return;
2222
+ result.forEach((entry, index) => {
2223
+ if (entry.parts !== (entry.source as { content?: unknown }).content) {
2224
+ messages[index] = Object.assign(Object.create(Object.getPrototypeOf(entry.source)), entry.source, { content: entry.parts });
2225
+ }
2226
+ });
2227
+ }));
2228
+ compactionRegistered = true;
2229
+ } catch (error) {
2230
+ ingestLogger.warn("[router] background: the compaction hook could not be registered; held results are unavailable", { error: String(error) });
2231
+ }
2232
+ }
2233
+ const held: HeldResults = createHeldResults({
2234
+ observations: options.observations,
2235
+ synthetic: async (input) => { if (typeof syntheticRaw === "function") await Reflect.apply(syntheticRaw, ctx.session, [input]); },
2236
+ journal, available: syntheticOk && compactionRegistered, logger: ingestLogger,
2237
+ });
2238
+ heldRef = held;
2239
+ /** The legacy plugin's finish API (2.1.4). Absent (or `off`): no background processing, the guarantees behave as `off`. */
2240
+ let finishApi: FinishApi | undefined;
2241
+ /**
2242
+ * Memo §12: the journal reload failed or timed out, or the journal vanished under this process (QA-2.1-8). Holding is off,
2243
+ * every unprocessed `<subagent>` element is redacted (context and compaction hooks) and a resume of a session this process
2244
+ * does not know is refused (it may be held). A failed reload is retried by `retryReload` (at most every
2245
+ * PENDING_RELOAD_RETRY_MS); a vanished journal is recreated from this process's in-memory state by `recreateJournal`
2246
+ * (QA-2.1-16), and a successful reload or recreation ends the state.
2247
+ */
2248
+ let reloadFailed = false;
2249
+ let lastReloadAt = 0;
2250
+ let reloading: Promise<boolean> | undefined;
2251
+ /** QA-2.1-8: background work that outlives its hook (verdict posts, recoveries, reloads); `dispose` waits for it (bounded). */
2252
+ const inFlightWork = new Set<Promise<unknown>>();
2253
+ const trackBackground = (work: Promise<unknown>): void => {
2254
+ const tracked = work.catch((error: unknown) => {
2255
+ ingestLogger.warn("[router] background: a background task failed", { error: String(error) });
2256
+ });
2257
+ inFlightWork.add(tracked);
2258
+ void tracked.finally(() => inFlightWork.delete(tracked));
2259
+ };
2260
+ /** V2_BACKGROUND_SETTLED: waits until the in-flight set is empty (work a settled task started is waited for too). Never rejects. */
2261
+ const settleBackground = async (): Promise<void> => {
2262
+ for (;;) {
2263
+ while (inFlightWork.size > 0) await Promise.allSettled([...inFlightWork]);
2264
+ // QA-2.1-21: the held gates the plugin runs behind `finish` (and the verdict posts they start here) count too.
2265
+ const api = finishApi;
2266
+ if (api === undefined) return;
2267
+ try {
2268
+ await api.idle();
2269
+ } catch (error) {
2270
+ ingestLogger.warn("[router] background: the plugin's held gates could not be awaited", { error: String(error) });
2271
+ return;
2272
+ }
2273
+ if (inFlightWork.size === 0) return;
2274
+ }
2275
+ };
2276
+ /** QA-2.1-8: one bounded reload of the pending journal (concurrent callers share it); success ends the fail-closed state. */
2277
+ const reloadJournal = (): Promise<boolean> => {
2278
+ if (reloading !== undefined) return reloading;
2279
+ const api = finishApi;
2280
+ if (api === undefined) return Promise.resolve(false);
2281
+ lastReloadAt = nowMs();
2282
+ reloading = (async () => {
2283
+ let timer: ReturnType<typeof setTimeout> | undefined;
2284
+ try {
2285
+ await Promise.race([
2286
+ api.reload(),
2287
+ new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error("pending journal reload timed out")), PENDING_RELOAD_BOUND_MS); }),
2288
+ ]);
2289
+ if (reloadFailed) ingestLogger.warn("[router] background: the pending journal was reloaded; holding is available again");
2290
+ reloadFailed = false;
2291
+ return true;
2292
+ } catch (error) {
2293
+ if (timer !== undefined) clearTimeout(timer);
2294
+ // QA-2.1-16: a vanished journal is never found again by a reload: it is rewritten from the in-memory state.
2295
+ if (error instanceof Error && error.message === PENDING_JOURNAL_VANISHED) {
2296
+ noteVanished();
2297
+ return await recreateJournal();
2298
+ }
2299
+ reloadFailed = true;
2300
+ ingestLogger.warn("[router] background: the pending journal could not be reloaded; holding is off and unprocessed results are redacted", { error: String(error) });
2301
+ return false;
2302
+ } finally {
2303
+ if (timer !== undefined) clearTimeout(timer);
2304
+ reloading = undefined;
2305
+ }
2306
+ })();
2307
+ return reloading;
2308
+ };
2309
+ /** QA-2.1-16: told once per vanishing (until a recreation succeeds). */
2310
+ let vanishedWarned = false;
2311
+ /** QA-2.1-8: a journal that vanished under this process fails closed exactly like a failed reload (until it is recreated). */
2312
+ const noteVanished = (): void => {
2313
+ reloadFailed = true;
2314
+ lastReloadAt = nowMs();
2315
+ if (vanishedWarned) return;
2316
+ vanishedWarned = true;
2317
+ ingestLogger.warn("[router] background: the pending journal vanished; it is recreated from memory, and until then holding is off and unprocessed results are redacted");
2318
+ };
2319
+ /**
2320
+ * QA-2.1-16: the records of this adapter's in-memory state a later restore needs: the live attempts not processed yet
2321
+ * (`inflight`, with their dispatch data), every hold (`hold`, `hold-text`, `posting`, `posted`) and the dormant
2322
+ * `inflight` records of sessions not seen yet. The plugin adds its pending entries and dormant records.
2323
+ */
2324
+ const adapterRecords = (): PersistedRecord[] => {
2325
+ const out: PersistedRecord[] = [];
2326
+ for (const attempt of inflight.list()) {
2327
+ if (attempt.state !== "acknowledged" && attempt.state !== "child-ended" && attempt.state !== "processing") continue;
2328
+ if (journal.hasProcessed(attempt.key)) continue;
2329
+ // QA-3.1-10: an executor-owned attempt is the plan ledger's to recover; journaled here (without its owner) a restart's
2330
+ // `recoverInflight` would take it for an ordinary dispatch.
2331
+ if (isExecutorOwned(attempt)) continue;
2332
+ const dispatch = restoredDispatches.get(attempt.callID) ?? finishApi?.dispatchOf(attempt.callID);
2333
+ out.push({
2334
+ v: 1, kind: "inflight", key: attempt.key, callID: attempt.callID, parentSessionID: attempt.parentSessionID,
2335
+ childSessionID: attempt.childSessionID, label: attemptLabel(attempt), at: attempt.ackAt ?? attempt.at,
2336
+ agent: attempt.agent, description: attempt.description, verifying: attempt.verifying, verificationMode: attempt.verificationMode,
2337
+ ...(attempt.callerAgent === undefined ? {} : { callerAgent: attempt.callerAgent }),
2338
+ ...(attempt.callerMessageID === undefined ? {} : { callerMessageID: attempt.callerMessageID }),
2339
+ ...(attempt.role === undefined ? {} : { role: attempt.role }),
2340
+ ...(attempt.hold === undefined ? {} : { handle: attempt.hold.handle }), hold: attempt.hold?.handle ?? null,
2341
+ ...(dispatch === undefined ? {} : { dispatch }), process: processToken(),
2342
+ });
2343
+ }
2344
+ out.push(...held.persisted());
2345
+ for (const records of dormantInflight.values()) out.push(...records);
2346
+ return out;
2347
+ };
2348
+ /**
2349
+ * QA-2.1-16: what identifies a record a recreation rewrites from memory: its kind and its attempt key or hold handle. The
2350
+ * same identity the recreation itself merges by (QA-2.1-33, `mergePendingSnapshots`).
2351
+ */
2352
+ const recordIdentity = (record: PersistedRecord): string | undefined => pendingRecordIdentity(record);
2353
+ /** QA-2.1-16: the identities the last successful recreation wrote; a retried append among them is not written again. */
2354
+ let recreatedIdentities = new Set<string>();
2355
+ let recreating: Promise<boolean> | undefined;
2356
+ /**
2357
+ * QA-2.1-16: rewrites a vanished journal from the in-memory state (`FinishApi.recreateJournal`); concurrent callers share
2358
+ * one rewrite. Success ends the fail-closed state; a failure keeps it, and the next append or `retryReload` tries again.
2359
+ */
2360
+ const recreateJournal = (): Promise<boolean> => {
2361
+ if (recreating !== undefined) return recreating;
2362
+ const api = finishApi;
2363
+ if (api === undefined) return Promise.resolve(false);
2364
+ lastReloadAt = nowMs();
2365
+ recreating = (async () => {
2366
+ try {
2367
+ const records = adapterRecords();
2368
+ await api.recreateJournal(records);
2369
+ recreatedIdentities = new Set(records.map(recordIdentity).filter((id): id is string => id !== undefined));
2370
+ if (reloadFailed) ingestLogger.warn("[router] background: the pending journal was recreated from memory; holding is available again");
2371
+ reloadFailed = false;
2372
+ vanishedWarned = false;
2373
+ return true;
2374
+ } catch (error) {
2375
+ reloadFailed = true;
2376
+ ingestLogger.warn("[router] background: the pending journal could not be recreated; holding stays off and it is tried again", { error: String(error) });
2377
+ return false;
2378
+ } finally {
2379
+ recreating = undefined;
2380
+ }
2381
+ })();
2382
+ return recreating;
2383
+ };
2384
+ /** QA-2.1-8: while the reload is failed, a hook or event starts another try (never awaited, at most every PENDING_RELOAD_RETRY_MS). */
2385
+ const retryReload = (): void => {
2386
+ if (!reloadFailed || reloading !== undefined || finishApi === undefined || nowMs() - lastReloadAt < PENDING_RELOAD_RETRY_MS) return;
2387
+ trackBackground(reloadJournal());
2388
+ };
2389
+ /** Reloaded in-flight records (memo §11.3): dormant until this process sees the parent session. */
2390
+ const dormantInflight = new Map<string, PersistedRecord[]>();
2391
+ /**
2392
+ * Set once the completion processor exists: recovers the adopted `inflight` records of a session. Returns the call ids
2393
+ * of the attempts acknowledged for recovery (QA-2.1-29: their holds get their verdict from that recovery).
2394
+ */
2395
+ let recoverInflight: ((sessionID: string) => Set<string>) | undefined;
2396
+ /** QA-2.1-17: the dispatch data journaled with the `inflight` records being recovered, by call id (bounded). */
2397
+ const restoredDispatches = new Map<string, RestoredDispatch>();
2398
+ /** QA-2.1-29: restored holds of sessions adopted before the processor existed, waiting for the start-up recovery. */
2399
+ const deferredRestores = new Map<string, RestoredHolds>();
2400
+ /** Background guarantees apply: mode ≠ off AND the finish API attached. Otherwise every code path below behaves as `off`. */
2401
+ const bgActive = (): boolean => bgMode !== "off" && finishApi !== undefined;
2402
+ /** `router_run` contamination notes from `execute.before`, appended in `execute.after` (bounded). */
2403
+ const runNotes = new Map<string, string>();
2404
+ /** 1.3: the process-wide lease registry and the guard over it (every v2 child; roots take none). */
2405
+ let leaseHandle: ReturnType<typeof acquireLeaseRegistry> | undefined;
2406
+ let leaseGuard: LeaseGuard | undefined;
2407
+ let leaseStartupRefusal: string | undefined;
2408
+ const holderLabel = (holderID: string): string => {
2409
+ const attempt = inflight.byChild(holderID);
2410
+ return attempt === undefined ? `session ${holderID}` : `${attemptLabel(attempt)} (session ${holderID})`;
2411
+ };
2412
+ if (startRouting.leases.mode === "enforce") {
2413
+ try {
2414
+ const snapshotPath = join(outcomesDir, "leases.json");
2415
+ const handle = acquireLeaseRegistry({
2416
+ runMode: startRouting.leases.run,
2417
+ seams: { realpath: (path) => realpathSync.native(path), repoKeyOf: leaseRepoKeyOf, now: nowMs },
2418
+ snapshotPath, logger: ingestLogger,
2419
+ loadSnapshot: () => JSON.parse(readFileSync(snapshotPath, "utf8")) as unknown,
2420
+ });
2421
+ leaseHandle = handle;
2422
+ bgDisposers.push(() => handle.release());
2423
+ leaseGuard = createLeaseGuard({
2424
+ registry: handle.registry, sessionKind: sessionKindOf, sessionDir: sessionDirectoryOf, gitRootOf: nearestRepository,
2425
+ holderLabel,
2426
+ // 3.1.7 W3: a plan child (its binding has `plan`) acquires as holder = child, `taskRef`, `until-integrated`, tree = slot;
2427
+ // nothing releases it at child end (`releaseChild` keeps until-integrated leases): only the executor's `releaseTask`.
2428
+ planTaskOf: (sid) => {
2429
+ const binding = currentBinding(sid, { maxOf: () => [] });
2430
+ const slot = binding?.grant.workRoot;
2431
+ return binding?.plan === undefined || typeof slot !== "string" || slot === ""
2432
+ ? undefined
2433
+ : { planId: binding.plan.planId, taskId: binding.plan.taskId, slot };
2434
+ },
2435
+ events: { onRelease: (cb) => handle.onRelease(cb) }, logger: ingestLogger, now: nowMs,
2436
+ });
2437
+ // QA-3.1-6: a lease release can unblock a plan task waiting on a lease, so the executor runtime gets its tick
2438
+ // (`onLeaseReleased`, called only when the runtime offers it). Never throws into the registry.
2439
+ const offLeaseTick = handle.onRelease(() => {
2440
+ const runtime: unknown = executor?.runtime;
2441
+ if (typeof runtime !== "object" || runtime === null) return;
2442
+ const tick: unknown = Reflect.get(runtime, "onLeaseReleased");
2443
+ if (typeof tick !== "function") return;
2444
+ try {
2445
+ Reflect.apply(tick, runtime, []);
2446
+ } catch (error) {
2447
+ ingestLogger.warn("[router] executor: the lease-release tick failed", { error: String(error) });
2448
+ }
2449
+ });
2450
+ bgDisposers.push(() => offLeaseTick());
2451
+ // `router_git_ls_files` searches: child sessions see no entry under edit by another holder (memo §15.1). `root` is the
2452
+ // directory git listed (the work root, or the repository a `root=` call inspects), so the checkout key is that one's own
2453
+ // (DF-1.1-4), never the session's.
2454
+ bgDisposers.push(installGitSearchFilter(({ sessionID, root, paths }) => {
2455
+ if (sessionKinds.get(sessionID) !== "child") return { kept: paths };
2456
+ const tree = repositoryIdentity(root)?.tree ?? root;
2457
+ const absolute = paths.map((path) => join(root, path));
2458
+ const result = handle.registry.filterSearchResults({ holderID: sessionID, tree, isChild: true }, tree, absolute);
2459
+ if (result.omitted === 0 && result.invalid === undefined) return { kept: paths };
2460
+ const keptSet = new Set(result.kept);
2461
+ return {
2462
+ kept: paths.filter((_, index) => keptSet.has(absolute[index]!)),
2463
+ note: `[router] ${result.omitted} result(s) omitted: under edit by ${result.holders.map((h) => holderLabel(h.holderID)).join(", ")}.`,
2464
+ };
2465
+ }));
2466
+ } catch (error) {
2467
+ leaseGuard = undefined;
2468
+ leaseHandle = undefined;
2469
+ leaseStartupRefusal = "[router] Refused: enforced lease checks are unavailable because the lease registry could not start. Repair the shared lease state and restart the plugin.";
2470
+ ingestLogger.warn("[router] leases: the lease registry could not start; enforced file, search, git and run calls are refused", { error: String(error) });
2471
+ }
2472
+ }
2473
+ // Memo §4.1 steps 3-4: the finish API is attached once (with the lease gate when leases are enforced), then the pending journal
2474
+ // is reloaded, AWAITED with a 5 s bound before the context hook registers. A failure falls back to fail-closed redaction (§12).
2475
+ if (bgMode !== "off") {
2476
+ const attachFinish = (hooks as unknown as Record<PropertyKey, unknown>)[ROUTER_FINISH_ATTACH];
2477
+ if (typeof attachFinish === "function") {
2478
+ try {
2479
+ // QA-2.1-8: a verdict the gate posts through the sink is background work `dispose` waits for (bounded), like a recovery.
2480
+ const trackedHeld: HeldResults = {
2481
+ ...held,
2482
+ verdict: (handle, v) => {
2483
+ const posting = held.verdict(handle, v);
2484
+ trackBackground(posting);
2485
+ return posting;
2486
+ },
2487
+ };
2488
+ finishApi = (attachFinish as FinishAttach)({ host: "v2", held: trackedHeld, ...(leaseGuard === undefined ? {} : { leaseGate: leaseGuard }) });
2489
+ // QA-2.1-33: a recreation of the shared journal by another plugin instance of this process writes these records too.
2490
+ finishApi?.setAdapterSnapshot?.(adapterRecords);
2491
+ } catch (error) {
2492
+ ingestLogger.warn("[router] background: the plugin could not attach the finish API; no background processing", { error: String(error) });
2493
+ }
2494
+ }
2495
+ if (finishApi !== undefined) await reloadJournal();
2496
+ }
2497
+ /**
2498
+ * Memo §11.3: the first sight of a parent session adopts its dormant records (claim file); idempotent per session. Bounded
2499
+ * (QA-2.1-13): a forgotten session leaves the set, and the oldest sightings go first past MAX_ADOPTED_SESSIONS (a second
2500
+ * adoption of an evicted session finds no dormant records: `adopt` hands each session over once). QA-2.1-34: a refused
2501
+ * adoption (another live instance holds the claim) leaves the session unmarked; a later sighting tries again, at most
2502
+ * once per ADOPTION_RETRY_MS (`refusedAdoptions`).
2503
+ */
2504
+ const adoptedSessions = new Set<string>();
2505
+ /**
2506
+ * QA-2.1-34: when the adoption of a session was last refused (another live instance holds its claim). The session is not
2507
+ * marked adopted; a later sighting tries again once ADOPTION_RETRY_MS has passed. Bounded like `adoptedSessions`.
2508
+ */
2509
+ const refusedAdoptions = new Map<string, number>();
2510
+ const adoptSession = (sessionID: string): void => {
2511
+ if (reloadFailed) retryReload();
2512
+ if (finishApi === undefined || reloadFailed || adoptedSessions.has(sessionID)) return;
2513
+ const refusedAt = refusedAdoptions.get(sessionID);
2514
+ if (refusedAt !== undefined && nowMs() - refusedAt < ADOPTION_RETRY_MS) return;
2515
+ adoptedSessions.add(sessionID);
2516
+ for (const old of adoptedSessions) {
2517
+ if (adoptedSessions.size <= MAX_ADOPTED_SESSIONS) break;
2518
+ adoptedSessions.delete(old);
2519
+ }
2520
+ try {
2521
+ const adopted = finishApi.adopt(sessionID);
2522
+ if (isAdoptionRefused(adopted)) {
2523
+ adoptedSessions.delete(sessionID);
2524
+ refusedAdoptions.delete(sessionID);
2525
+ refusedAdoptions.set(sessionID, nowMs());
2526
+ for (const old of refusedAdoptions.keys()) {
2527
+ if (refusedAdoptions.size <= MAX_ADOPTED_SESSIONS) break;
2528
+ refusedAdoptions.delete(old);
2529
+ }
2530
+ return;
2531
+ }
2532
+ refusedAdoptions.delete(sessionID);
2533
+ if (adopted === undefined) return;
2534
+ const restored = adopted.holds.length > 0 ? held.restore(adopted.holds) : { reposts: [], unverified: [] };
2535
+ let recovering = new Set<string>();
2536
+ if (adopted.inflight.length > 0) {
2537
+ dormantInflight.set(sessionID, [...adopted.inflight]);
2538
+ if (recoverInflight === undefined) {
2539
+ // Recovered once the processor exists (the start-up loop): their holds wait for that recovery.
2540
+ for (const rec of adopted.inflight) if (typeof rec.callID === "string") recovering.add(rec.callID);
2541
+ deferredRestores.set(sessionID, { reposts: [], unverified: restored.unverified.filter((h) => recovering.has(h.callID)) });
2542
+ } else {
2543
+ // QA-2.1-29: only the attempts actually acknowledged for recovery settle their holds; a record whose recovery is
2544
+ // skipped (`decide` refused, `acknowledge` undefined) leaves its hold to `settleRestoredHolds` below.
2545
+ recovering = recoverInflight(sessionID);
2546
+ }
2547
+ }
2548
+ // R20/R21 (QA-2.1-2, QA-2.1-6): the restored holds still owe their verdict; a hold whose child is recovered above gets it there.
2549
+ if (restored.reposts.length > 0 || restored.unverified.some((h) => !recovering.has(h.callID))) {
2550
+ // QA-PDF12-14: the holds of one pass share their parent lookups.
2551
+ const pendingRestore = duringRestorePass(() => settleRestoredHolds(sessionID, restored, recovering));
2552
+ trackBackground(pendingRestore);
2553
+ }
2554
+ } catch (error) {
2555
+ ingestLogger.warn("[router] background: the persisted records of a session could not be adopted", { sessionID, error: String(error) });
2556
+ }
2557
+ };
2558
+ /** R21 (QA-2.1-2): the handles among `handles` whose verdict already reached `parent` (`metadata.router.handle`, or its entry text). */
2559
+ const postedVerdictHandles = async (parent: string, handles: ReadonlySet<string>): Promise<Set<string>> => {
2560
+ const history: unknown = await ctx.session.context({ sessionID: parent } as Parameters<typeof ctx.session.context>[0]);
2561
+ const found = new Set<string>();
2562
+ const visit = (value: unknown, depth: number): void => {
2563
+ if (typeof value === "string") {
2564
+ const match = /^<router-verdict handle="([^"]+)"/.exec(value);
2565
+ if (match !== null && handles.has(match[1]!)) found.add(match[1]!);
2566
+ return;
2567
+ }
2568
+ if (depth > 8 || value === null || typeof value !== "object") return;
2569
+ if (Array.isArray(value)) {
2570
+ for (const item of value) visit(item, depth + 1);
2571
+ return;
2572
+ }
2573
+ const router: unknown = Reflect.get(value, "router");
2574
+ if (router !== null && typeof router === "object") {
2575
+ const handle: unknown = Reflect.get(router, "handle");
2576
+ if (typeof handle === "string" && handles.has(handle)) found.add(handle);
2577
+ }
2578
+ for (const key of Object.keys(value)) visit(Reflect.get(value, key), depth + 1);
2579
+ };
2580
+ visit(history, 0);
2581
+ return found;
2582
+ };
2583
+ /** Set with the completion processor: runs the gate again for a restored hold that has its child text (R20, QA-2.1-6). */
2584
+ let reverifyRestored: ((hold: RestoredHold) => Promise<void>) | undefined;
2585
+ /**
2586
+ * R20/R21 (QA-2.1-2, QA-2.1-6): settles the restored holds of an adopted parent. A verdict the parent already shows is recorded
2587
+ * as posted; a journaled `posting` text is posted again; any other hold re-runs the gate on its persisted child text (or, with
2588
+ * none, ends UNVERIFIABLE). A hold whose dispatch is recovered from its `inflight` record is left to that recovery.
2589
+ */
2590
+ const settleRestoredHolds = async (parent: string, restored: RestoredHolds, recovering: ReadonlySet<string>): Promise<void> => {
2591
+ const owed = new Set<string>([
2592
+ ...restored.reposts.map((r) => r.handle),
2593
+ ...restored.unverified.filter((h) => !recovering.has(h.callID)).map((h) => h.handle),
2594
+ ]);
2595
+ let posted = new Set<string>();
2596
+ try {
2597
+ posted = await postedVerdictHandles(parent, owed);
2598
+ } catch (error) {
2599
+ // A duplicate verdict is visible and harmless; a missing one keeps the child held for good.
2600
+ ingestLogger.warn("[router] background: the parent's history could not be read; restored verdicts are posted again", { parent, error: String(error) });
2601
+ }
2602
+ // QA-2.1-31: a verdict posted here (or found posted) bypasses the plugin's gate: its restored pending entry is settled
2603
+ // with it, so `router_verify` stops saying that the verdict follows.
2604
+ const settleEntry = (handle: string, verdict: "PASS" | "FAIL" | "UNVERIFIABLE", reason?: string): void => {
2605
+ try {
2606
+ finishApi?.settleHeldDirect(parent, handle, { verdict, ...(reason === undefined ? {} : { reason }) });
2607
+ } catch (error) {
2608
+ ingestLogger.warn("[router] background: the pending entry of a restored hold could not be settled", { handle, error: String(error) });
2609
+ }
2610
+ };
2611
+ for (const r of restored.reposts) {
2612
+ await held.settleRestored(r.handle, posted.has(r.handle));
2613
+ settleEntry(r.handle, verdictOfText(r.text));
2614
+ }
2615
+ for (const h of restored.unverified) {
2616
+ if (recovering.has(h.callID)) continue;
2617
+ if (posted.has(h.handle)) {
2618
+ await held.settleRestored(h.handle, true);
2619
+ settleEntry(h.handle, "UNVERIFIABLE", "verdict posted before the restart");
2620
+ continue;
2621
+ }
2622
+ if (reverifyRestored !== undefined) {
2623
+ await reverifyRestored(h);
2624
+ continue;
2625
+ }
2626
+ await held.verdict(h.handle, { verdict: "UNVERIFIABLE", text: "[router] not verified: lost in restart", reason: "lost in restart" });
2627
+ settleEntry(h.handle, "UNVERIFIABLE", "lost in restart");
2628
+ finishApi?.releaseHeld(h.handle);
2629
+ }
2630
+ };
2631
+ /** QA-2.1-31: the verdict a journaled verdict text names (UNVERIFIABLE when it names none). */
2632
+ const verdictOfText = (text: string): "PASS" | "FAIL" | "UNVERIFIABLE" => {
2633
+ const match = /\b(PASS|FAIL|UNVERIFIABLE)\b/.exec(text);
2634
+ return match === null ? "UNVERIFIABLE" : (match[1] as "PASS" | "FAIL" | "UNVERIFIABLE");
2635
+ };
2636
+ // Sweeps on an unref'd 5-minute interval (memo §4.1): the timing recorder, the in-flight registry and the leases.
2637
+ const sweepTimer = setInterval(() => {
2638
+ try {
2639
+ if (timings !== undefined) void Promise.resolve(timings.sweep()).catch((error: unknown) => ingestLogger.warn("[router] timing: sweep failed", { error: String(error) }));
2640
+ for (const attempt of inflight.sweep(nowMs())) void closeAttempt?.(attempt, "sweep");
2641
+ leaseHandle?.registry.sweep();
2642
+ } catch (error) {
2643
+ ingestLogger.warn("[router] background: the periodic sweep failed", { error: String(error) });
2644
+ }
2645
+ }, 5 * 60_000);
2646
+ sweepTimer.unref?.();
2647
+ bgDisposers.push(() => clearInterval(sweepTimer));
2648
+ // 2.1.5.f: where the plugin runs from (QA records the sink). Logged once per process.
2649
+ if (!pluginRootLogged) {
2650
+ pluginRootLogged = true;
2651
+ try {
2652
+ // Debug level: a static, no-routing session stays silent on warn/info (§1.2); QA reads the debug sink.
2653
+ console.debug(`[router] plugin root ${realpathSync.native(join(fileURLToPath(new URL(".", import.meta.url)), "..", ".."))}`);
2654
+ } catch (error) {
2655
+ ingestLogger.warn("[router] plugin root could not be resolved", { error: String(error) });
2656
+ }
2657
+ }
2658
+ /** W7: an executor's runtime, then its launcher (which aborts the signals it owns); a failure is logged and the next goes on. */
2659
+ const disposeExecutor = async (owned: V2Executor): Promise<void> => {
2660
+ for (const [what, run] of [["runtime", () => owned.runtime.dispose()], ["launcher", () => owned.launcher.dispose()]] as const) {
2661
+ try {
2662
+ await run();
2663
+ } catch (error) {
2664
+ ingestLogger.warn(`[router] executor: the ${what} could not be disposed`, { error: String(error) });
2665
+ }
2666
+ }
2667
+ };
2668
+ const cleanup = async () => {
2669
+ if (disposed) return;
2670
+ disposed = true;
2671
+ abort.abort();
2672
+ // QA-2.1-8: verdict posts, recoveries and reloads in flight finish (bounded) before anything they write to is torn down.
2673
+ if (inFlightWork.size > 0) {
2674
+ let timer: ReturnType<typeof setTimeout> | undefined;
2675
+ await Promise.race([
2676
+ Promise.allSettled([...inFlightWork]),
2677
+ new Promise<void>((resolve) => { timer = setTimeout(resolve, BACKGROUND_DRAIN_MS); }),
2678
+ ]);
2679
+ if (timer !== undefined) clearTimeout(timer);
2680
+ }
2681
+ // QA-2.1-21: the held gates the plugin runs behind `finish` (and the verdict posts they start here) end too, same bound.
2682
+ if (finishApi !== undefined) {
2683
+ let idleTimer: ReturnType<typeof setTimeout> | undefined;
2684
+ await Promise.race([
2685
+ settleBackground(),
2686
+ new Promise<void>((resolve) => { idleTimer = setTimeout(resolve, BACKGROUND_DRAIN_MS); }),
2687
+ ]);
2688
+ if (idleTimer !== undefined) clearTimeout(idleTimer);
2689
+ }
2690
+ // 3.1.7 W7: the executor first (runtime, then its launcher, which aborts the signals it owns), before the background
2691
+ // registry and the child runner it drives go away. Nothing reaches it after this: the emitter is a no-op without it.
2692
+ // QA-5.1-26: the executor `adopt` took, whether the factory's at start or a claim handover's; none is adopted from here on.
2693
+ const ownedExecutor = executor;
2694
+ executor = null;
2695
+ hostEventListeners.clear();
2696
+ if (ownedExecutor !== null) await disposeExecutor(ownedExecutor);
2697
+ executorLifetime.abort();
2698
+ for (const dispose of bgDisposers.reverse()) {
2699
+ try {
2700
+ await dispose();
2701
+ } catch (error) {
2702
+ ingestLogger.warn("[router] background: a disposer failed", { error: String(error) });
2703
+ }
2704
+ }
2705
+ await runtime?.dispose?.();
2706
+ // Before the event task: disposing releases a step handler that waits for the model catalog (QA-2.1-5).
2707
+ await ingest.dispose();
2708
+ dispatchRouter.dispose(); // this location no longer owns its sessions
2709
+ await engine.dispose();
2710
+ await eventTask;
2711
+ await Promise.allSettled(registrations.map((registration) => registration.dispose()));
2712
+ await hooks.dispose?.();
2713
+ };
2714
+
2715
+ try {
2716
+ // Captured once: after our own transform, ctx.agent.list() returns
2717
+ // router-modified agents, which would defeat the originals diff on refresh.
2718
+ const agents = await ctx.agent.list();
2719
+ // The legacy config bridge has no host commands. Capture the real registry before our transform owns /plan.
2720
+ const userPlanCommandDefined = (await ctx.command.list?.())?.data.some((command) => command.name === "plan") ?? false;
2721
+ let warnedPlanCommand = false;
2722
+ const baseSeed: Record<string, LegacyAgent> = {};
2723
+ for (const agent of agents.data) baseSeed[agent.id] = {
2724
+ mode: agent.mode,
2725
+ model: agent.model && `${agent.model.providerID}/${agent.model.id}`,
2726
+ variant: agent.model?.variant,
2727
+ };
2728
+ let config: LegacyConfig = { agent: {}, command: {} };
2729
+ registeredRole = (agent) => roleAgentOf(config.agent[agent]) === agent; // QA-P21-2-4
2730
+ let originals = new Map<string, string>();
2731
+ let agentOptions = new Map<string, Record<string, unknown>>();
2732
+ const warnedPermissions = new Set<string>();
2733
+ const warnPermissionOnce = (message: string) => {
2734
+ if (warnedPermissions.has(message)) return;
2735
+ warnedPermissions.add(message);
2736
+ ingestLogger.warn(message);
2737
+ };
2738
+ const warnedRoles = new Set<string>();
2739
+ const warnRoleOnce = (key: string, message: string) => {
2740
+ if (warnedRoles.has(key)) return;
2741
+ warnedRoles.add(key);
2742
+ ingestLogger.warn(message);
1079
2743
  };
1080
2744
  // Plugin agents (#81) are protected like read-only tiers: readOnly ones and explicit-permission ones
1081
2745
  // (which start from `* deny`) both keep their own deny/ask rules against inherited session grants.
@@ -1135,8 +2799,20 @@ export async function registerV2Hooks(
1135
2799
  const rolesRequested = routerConfig.routing?.delegation === "roles";
1136
2800
  rolesStarted ??= rolesRequested;
1137
2801
  if (rolesStarted) {
2802
+ // Cross-repo Phase 4 (SD-P4-15): the approvals store, read without git and only in roles mode with parents (no store
2803
+ // I/O otherwise, I9). An invalid store or a read failure gives no approved repository (fail closed).
2804
+ let approvedRoots: readonly RepoApproval[] = [];
2805
+ try {
2806
+ if (rolesRequested && resolveRolesRouting(routerConfig, "v2").repoParents.length > 0) {
2807
+ const read = readApprovals(options.approvalsDir !== undefined ? { dir: options.approvalsDir } : {});
2808
+ approvedRoots = read.invalid === undefined ? read.approvals : [];
2809
+ }
2810
+ } catch (error) {
2811
+ warnRoleOnce("roles:approvals", `roles mode (OpenCode v2 only): the repository approvals could not be read (${error instanceof Error ? error.message : String(error)}); no approved repository is granted`);
2812
+ }
1138
2813
  const registration = await registerRoleAgents(next.agent, routerConfig, {
1139
- context7: Boolean(context7), directory: ctx.location.directory, seed: baseSeed, warn: warnRoleOnce,
2814
+ context7: Boolean(context7), directory: ctx.location.directory, seed: baseSeed, warn: warnRoleOnce, approvedRoots,
2815
+ ...(executorPlatformSupported() ? {} : { executorPlatform: false }), // G-16: the plan executor is Windows-only
1140
2816
  ...(options.listRegistrationWorktrees ? { listWorktrees: options.listRegistrationWorktrees } : {}),
1141
2817
  });
1142
2818
  // #84 P2.3 (T2.3.3, §2.5): the ladder tool is a plugin tool, advertised to a deny-by-default agent only with an explicit
@@ -1254,13 +2930,19 @@ export async function registerV2Hooks(
1254
2930
  event.effect = "ask";
1255
2931
  event.message = `Approval required by ${agentLabel(name)} ${name}: ${event.action}`;
1256
2932
  }
1257
- // #84 P2.3 (T2.3.1, P-13, I3/I9): a role session is narrowed to ITS dispatch grant and work root. Only ever a deny: an
1258
- // action the max policy refused stays refused, a sensitive-read ask stays an ask when the grant covers it.
2933
+ // #84 P2.3 (T2.3.1, P-13, I3/I9): a role session is narrowed to ITS dispatch grant and work root: an action the max
2934
+ // policy refused stays refused, a sensitive-read ask stays an ask when the grant covers it. The one widening is D13 below.
1259
2935
  if (role !== undefined && event.effect !== "deny") {
1260
- const refusal = await roleEvaluateRefusal(event, role);
2936
+ const { refusal, lift } = await roleEvaluateRefusal(event, role);
1261
2937
  if (refusal !== undefined) {
1262
2938
  event.effect = "deny";
1263
2939
  event.message = `Permission denied by role agent ${role} for this dispatch: ${refusal}`;
2940
+ } else if (lift && event.effect === "ask" && event.action === "external_directory") {
2941
+ // Cross-repo P4.5 / D13, I18 (lift only inside the grant): a host `ask` for `external_directory` becomes `allow` when the
2942
+ // binding is exact and the router's own decision allowed every resource — inside W (still a listed worktree) or R —
2943
+ // while cross-repo is in use (QA-1 F6: never for the session's own output directory, never without cross-repo: I9).
2944
+ // Never another action, never an unknown binding, never over a `deny` (host or configured: both skip this branch).
2945
+ event.effect = "allow";
1264
2946
  }
1265
2947
  }
1266
2948
  } catch (error) {
@@ -1278,7 +2960,15 @@ export async function registerV2Hooks(
1278
2960
  }));
1279
2961
 
1280
2962
  registrations.push(await ctx.command.transform((editor) => {
1281
- for (const [name, definition] of Object.entries(config.command)) editor.add({
2963
+ const commands = Object.entries(config.command).filter(([name]) => {
2964
+ if (name !== "plan" || !userPlanCommandDefined) return true;
2965
+ if (!warnedPlanCommand) {
2966
+ warnedPlanCommand = true;
2967
+ ingestLogger.warn("[router] /plan command conflict: preserving the user-defined /plan; router_plan remains available");
2968
+ }
2969
+ return false;
2970
+ });
2971
+ for (const [name, definition] of commands) editor.add({
1282
2972
  name,
1283
2973
  description: definition.description,
1284
2974
  execute: async (invocation) => {
@@ -1296,6 +2986,21 @@ export async function registerV2Hooks(
1296
2986
  return;
1297
2987
  }
1298
2988
  if (name === "preset") await refresh();
2989
+ if (name === "router") {
2990
+ // Cross-repo P4.7 (SD-P4-11): after `/router approve|revoke` wrote the store, reload the role agents (their
2991
+ // `external_directory` patterns come from the store), then say whether the change is usable now. The text still goes
2992
+ // through `session.prompt` below, so the orchestrator sees it and dispatches again.
2993
+ const change = approvalsChangedOf(output.parts);
2994
+ if (change !== undefined) {
2995
+ let reloadError: string | undefined;
2996
+ try {
2997
+ await refresh();
2998
+ } catch (error) {
2999
+ reloadError = error instanceof Error ? error.message : String(error);
3000
+ }
3001
+ output.parts.push({ type: "text", text: approvalReloadLine(change, APPROVAL_RELOAD_APPLIES, reloadError) });
3002
+ }
3003
+ }
1299
3004
  await ctx.session.prompt({
1300
3005
  ...invocation.prompt,
1301
3006
  sessionID: invocation.sessionID,
@@ -1323,6 +3028,9 @@ export async function registerV2Hooks(
1323
3028
  const directory = name.startsWith("router_git_")
1324
3029
  ? (await ctx.session.get({ sessionID: context.sessionID })).location?.directory ?? ctx.location.directory
1325
3030
  : ctx.location.directory;
3031
+ // Memo §15.1: the `ls_files` filter is synchronous and reads the session-kind cache; resolve an unknown kind here, once
3032
+ // (memoized by `sessionKindOf`), so the filter applies to EVERY child session. No other tool pays this lookup.
3033
+ if (name === "router_git_ls_files" && leaseGuard !== undefined) await sessionKindOf(String(context.sessionID));
1326
3034
  const result = await definition.execute(args, {
1327
3035
  sessionID: context.sessionID, messageID: context.messageID, agent: context.agent,
1328
3036
  directory, worktree: name.startsWith("router_git_") ? "" : ctx.location.project.directory, // Session.Info.location has no project; discover from its directory, never the plugin's project.
@@ -1346,6 +3054,18 @@ export async function registerV2Hooks(
1346
3054
 
1347
3055
  registrations.push(await ctx.session.hook("prompt", async (event) => {
1348
3056
  const session = await ctx.session.get({ sessionID: event.sessionID });
3057
+ // Phase 2.1 (memo §4.5): a session without a parent is a root: its turns are timed and its kind is known to the leases.
3058
+ noteSessionKind(String(event.sessionID), session.parentID ? "child" : "root");
3059
+ if (!session.parentID) adoptSession(String(event.sessionID));
3060
+ if (!session.parentID && timings !== undefined) {
3061
+ const rootTimings = timings;
3062
+ try {
3063
+ rootTimings.markRootSession(String(event.sessionID));
3064
+ void rootTimings.onRootPrompt(String(event.sessionID), nowMs(), typeof event.messageID === "string" ? event.messageID : undefined).catch((error: unknown) => ingestLogger.warn("[router] timing: the turn boundary could not be recorded", { error: String(error) }));
3065
+ } catch (error) {
3066
+ ingestLogger.warn("[router] timing: the root prompt could not be recorded", { error: String(error) });
3067
+ }
3068
+ }
1349
3069
  const output = { message: { agent: session.agent }, parts: [{ type: "text", text: event.prompt.text }] };
1350
3070
  await legacy["chat.message"]?.({ sessionID: event.sessionID, agent: session.agent }, output);
1351
3071
  event.prompt.text = output.parts.map((part) => part.text).join("\n\n");
@@ -1359,8 +3079,168 @@ export async function registerV2Hooks(
1359
3079
  }
1360
3080
  }
1361
3081
  }));
3082
+ // ---- Phase 2.1 message helpers (memo §4.4): `HeldResults.apply` reads `parts`; the host's context messages carry `content`. ----
3083
+ const withContent = (source: ContextMessage, content: ContextMessage["content"]): ContextMessage =>
3084
+ Object.assign(Object.create(Object.getPrototypeOf(source)), source, { content });
3085
+ /** The held-result matcher over context messages (copies; `undefined` = unchanged). */
3086
+ const applyHeldTo = (sid: string, messages: readonly ContextMessage[]): ContextMessage[] | undefined => {
3087
+ const shaped = messages.map((source) => ({ source, parts: source.content }));
3088
+ const result = held.apply(sid, shaped);
3089
+ if (result === undefined) return undefined;
3090
+ return result.map((entry) => (entry.parts === entry.source.content ? entry.source : withContent(entry.source, entry.parts)));
3091
+ };
3092
+ /** Auto/model: `[router` line starts in every `<subagent …>` element body are defanged (parity with `defangChildResult`). */
3093
+ const defangMessages = (messages: readonly ContextMessage[]): ContextMessage[] | undefined => {
3094
+ let changed = false;
3095
+ const next = messages.map((message) => {
3096
+ if (!Array.isArray(message.content)) return message;
3097
+ let touched = false;
3098
+ const content = message.content.map((part) => {
3099
+ if (part.type !== "text") return part;
3100
+ const text = defangSubagentBodies(part.text, defangRouterLines);
3101
+ if (text === part.text) return part;
3102
+ touched = true;
3103
+ return { ...part, text };
3104
+ });
3105
+ if (!touched) return message;
3106
+ changed = true;
3107
+ return withContent(message, content);
3108
+ });
3109
+ return changed ? next : undefined;
3110
+ };
3111
+ /**
3112
+ * DF-1-4: per child, the completion elements already seen in its parent's context, by the message that holds them (QA-DF1-20:
3113
+ * message id, part and element index; never their content); bounded. Per adapter copy and lost on restart: a `child-ended`
3114
+ * attempt is read again on its parent's next request, so a skipped element never leaves it waiting for the sweep.
3115
+ */
3116
+ const seenCompletionElements = new Map<string, Set<string>>();
3117
+ /** Records a completion element of `child`; true only the first time it is seen. */
3118
+ const noteCompletionElement = (child: string, signature: string): boolean => {
3119
+ let seen = seenCompletionElements.get(child);
3120
+ if (seen?.has(signature)) return false;
3121
+ if (seen === undefined) {
3122
+ seen = new Set<string>();
3123
+ seenCompletionElements.set(child, seen);
3124
+ for (const old of seenCompletionElements.keys()) {
3125
+ if (seenCompletionElements.size <= MAX_SEEN_COMPLETION_CHILDREN) break;
3126
+ seenCompletionElements.delete(old);
3127
+ }
3128
+ }
3129
+ seen.add(signature);
3130
+ for (const old of seen) {
3131
+ if (seen.size <= MAX_SEEN_COMPLETION_ELEMENTS) break;
3132
+ seen.delete(old);
3133
+ }
3134
+ return true;
3135
+ };
3136
+ /** QA-DF1-17: per parent session, the completion elements (child, identity) of its last scanned history; bounded. */
3137
+ const lastScannedElements = new Map<string, ReadonlyArray<{ child: string; signature: string }>>();
3138
+ /**
3139
+ * QA-DF1-17: a resume of `child` is decided. Every completion element of that child in its parent's last scanned history belongs
3140
+ * to an earlier turn, whatever that turn's attempt state was when it was scanned (a `processing` one left it unremembered):
3141
+ * each is remembered now, so the resumed attempt never takes it.
3142
+ */
3143
+ const rememberElementsOnResume = (parent: string, child: string): void => {
3144
+ for (const element of lastScannedElements.get(parent) ?? []) {
3145
+ if (element.child === child) noteCompletionElement(child, element.signature);
3146
+ }
3147
+ };
3148
+ /**
3149
+ * A root session's request: every completion element of an acknowledged attempt starts its processing (not awaited), and the
3150
+ * first request that sees an attempt waits for it at most COMPLETION_SETTLE_MS (one shared budget, never again for that attempt).
3151
+ */
3152
+ const scanCompletions = async (sid: string, messages: readonly ContextMessage[]): Promise<void> => {
3153
+ if (processor === undefined) return;
3154
+ const waits: string[] = [];
3155
+ const scanned: Array<{ child: string; signature: string }> = [];
3156
+ /** The children an element of this request started processing for. */
3157
+ const taken = new Set<string>();
3158
+ for (const [messageIndex, message] of messages.entries()) {
3159
+ if (!Array.isArray(message.content)) continue;
3160
+ const messageKey = completionMessageKey(message, messageIndex);
3161
+ for (const [partIndex, part] of message.content.entries()) {
3162
+ if (part.type !== "text") continue;
3163
+ for (const [elementIndex, element] of completionElementsOf(part.text).entries()) {
3164
+ const attempt = inflight.byChild(element.child);
3165
+ if (attempt === undefined || attempt.parentSessionID !== sid) {
3166
+ ingestLogger.warn("[router] background: a completion element names a child with no attempt of this parent", {
3167
+ parent: sid, child: element.child, state: element.state, attempt: attempt === undefined ? "none" : attempt.parentSessionID,
3168
+ });
3169
+ continue;
3170
+ }
3171
+ // DF-1-4: the parent's history keeps the completion element of every earlier turn of a resumed child. An element is
3172
+ // remembered once an attempt took it or had finished when it was seen; a remembered one never starts a later attempt
3173
+ // (the resume's own element, or its end event, follows). Seen during a processing, it is left for the next request,
3174
+ // unless a resume of its child is decided first (QA-DF1-17: the resume marks every element of the child last scanned).
3175
+ // QA-DF1-20: an element is identified by the message that holds it (message id, part and element index), never by its
3176
+ // state and body: a resumed turn's byte-identical answer is a new element.
3177
+ const signature = `${messageKey}\0${partIndex}\0${elementIndex}`;
3178
+ scanned.push({ child: element.child, signature });
3179
+ const open = attempt.state === "acknowledged" || attempt.state === "child-ended";
3180
+ if (open && !noteCompletionElement(element.child, signature)) continue;
3181
+ if (!open && attempt.state !== "processing") noteCompletionElement(element.child, signature);
3182
+ if (open) {
3183
+ taken.add(element.child);
3184
+ trackBackground(processor.process(element.child, { kind: "completion", state: element.state, body: element.body, at: nowMs() }));
3185
+ }
3186
+ if (!attempt.waitedOnce && !waits.includes(element.child)) {
3187
+ attempt.waitedOnce = true;
3188
+ waits.push(element.child);
3189
+ }
3190
+ }
3191
+ }
3192
+ }
3193
+ // QA-DF1-20: an attempt whose end left it `child-ended` (its answer not readable yet) that no element of this request took
3194
+ // reads its child again now, instead of waiting for an element that may never be new to this copy, or for the sweep.
3195
+ for (const attempt of inflight.listForParent(sid)) {
3196
+ if (attempt.state !== "child-ended" || taken.has(attempt.childSessionID)) continue;
3197
+ if (inflight.byChild(attempt.childSessionID) !== attempt) continue;
3198
+ const outcome = attempt.outcome;
3199
+ if (outcome === undefined || outcome === "unknown") continue;
3200
+ // The end it met is replayed as is (its outcome and time): only the child's answer is read again.
3201
+ const end = { outcome, eventID: `reread:${attempt.key}`, at: attempt.endedAt ?? nowMs() };
3202
+ trackBackground(processor.process(attempt.childSessionID, { kind: "early-end", end }));
3203
+ }
3204
+ lastScannedElements.delete(sid);
3205
+ lastScannedElements.set(sid, scanned);
3206
+ for (const old of lastScannedElements.keys()) {
3207
+ if (lastScannedElements.size <= MAX_SEEN_COMPLETION_CHILDREN) break;
3208
+ lastScannedElements.delete(old);
3209
+ }
3210
+ if (waits.length > 0) await Promise.all(waits.map((child) => processor?.settled(child, COMPLETION_SETTLE_MS)));
3211
+ };
1362
3212
  /** The context hook's body (QA-P23-B5: declared before the hook that calls it). */
1363
3213
  async function buildContext(event: SessionContext, role: string | undefined): Promise<void> {
3214
+ // Phase 2.1 (memo §4.4 step 1-2): FIRST, before `chat.params` and before the augmenter reads `event.messages`: no held output
3215
+ // reaches the request, and (auto/model) child text cannot pose as a router line. Mode `off`: no matcher, no defang.
3216
+ const rawMessages = event.messages;
3217
+ if (bgActive() && event.messages !== undefined) {
3218
+ const sid = String(event.sessionID);
3219
+ adoptSession(sid);
3220
+ if (reloadFailed) {
3221
+ // Memo §12: without a reloaded journal every completion not known as processed is redacted (fail closed).
3222
+ const isProcessed = (child: string): boolean => {
3223
+ const attempt = inflight.byChild(child);
3224
+ return attempt !== undefined && journal.hasProcessed(attempt.key);
3225
+ };
3226
+ event.messages = event.messages.map((message) => {
3227
+ if (!Array.isArray(message.content)) return message;
3228
+ let touched = false;
3229
+ const content = message.content.map((part) => {
3230
+ if (part.type !== "text") return part;
3231
+ const text = redactUnprocessedElements(part.text, isProcessed);
3232
+ if (text === part.text) return part;
3233
+ touched = true;
3234
+ return { ...part, text };
3235
+ });
3236
+ return touched ? withContent(message, content) : message;
3237
+ });
3238
+ }
3239
+ const hidden = applyHeldTo(sid, event.messages);
3240
+ if (hidden !== undefined) event.messages = hidden;
3241
+ const defanged = defangMessages(event.messages);
3242
+ if (defanged !== undefined) event.messages = defanged;
3243
+ }
1364
3244
  if (protectedAgent(event.agent)) {
1365
3245
  try {
1366
3246
  // Catalogs use merged session rules; remove widened tools from this
@@ -1425,7 +3305,7 @@ export async function registerV2Hooks(
1425
3305
  copies.push(part);
1426
3306
  original.set(part.text, copies);
1427
3307
  }
1428
- const output = { system: event.system.map((part) => part.text) };
3308
+ const output: { system: string[]; [TURN_STATE_ROOT]?: boolean } = { system: event.system.map((part) => part.text) };
1429
3309
  // The router pushes its own instructions, but may splice edited user text.
1430
3310
  // Only pushed text belongs to the router and may have its vocabulary translated.
1431
3311
  const added = new Set<string>();
@@ -1470,6 +3350,24 @@ export async function registerV2Hooks(
1470
3350
  }
1471
3351
  }
1472
3352
  }
3353
+ // Phase 1.2: a root session's turn state (pending list, late notices, route hint) rides in a trailing user message; the
3354
+ // system parts above are never changed for it. A failure here only loses the tail, never the request.
3355
+ if (output[TURN_STATE_ROOT] === true && event.messages !== undefined) {
3356
+ if (bgActive() && rawMessages !== undefined) {
3357
+ // The ORIGINAL completion text (before the matcher) feeds the processor; failures never cost the request.
3358
+ try {
3359
+ await scanCompletions(String(event.sessionID), rawMessages);
3360
+ } catch (error) {
3361
+ ingestLogger.warn("[router] background: completions could not be scanned", { error: String(error) });
3362
+ }
3363
+ }
3364
+ try {
3365
+ const placed = placeTurnState(event.messages, turnState.buildTurnState(String(event.sessionID)), tailMessage);
3366
+ if (placed !== undefined) event.messages = placed;
3367
+ } catch (error) {
3368
+ warnTurnStateOnce(error);
3369
+ }
3370
+ }
1473
3371
  }
1474
3372
  // #90 P1.2 (A1): the TUI's `effortOf` rpc, answered from `effortStore`; tiers and roles mode alike. Feature-detected (a host
1475
3373
  // without `ctx.rpc.register` gets nothing), bounded (2 s; a late registration is kept), never throws; disposed with the other
@@ -1481,6 +3379,8 @@ export async function registerV2Hooks(
1481
3379
  // #84 P2.3 (P-3, I9): a role session's context hook never fails the child. ANY error below empties its catalog (the
1482
3380
  // strictest outcome) and is annotated for the parent's `subagent` result; every other agent keeps today's behaviour.
1483
3381
  const role = roleAgentName(event.agent);
3382
+ // 3.1.7 M41 (always on): the first user message of the session decides whether it is an unbound plan child (fail closed).
3383
+ if (typeof event.sessionID === "string") await planChildGuard.check(event.sessionID, firstMessageText(event.messages));
1484
3384
  try {
1485
3385
  await buildContext(event, role);
1486
3386
  } catch (error) {
@@ -1501,7 +3401,11 @@ export async function registerV2Hooks(
1501
3401
  }
1502
3402
  }));
1503
3403
 
3404
+ // 3.1.7 W4: the host's retry hook is registered with the executor below (W1), only when the factory built one (M3).
1504
3405
  registrations.push(await ctx.tool.hook("execute.before", async (event) => {
3406
+ // 3.1.7 M41 (always on): a plan child without its plan binding is refused every tool call (fail closed). The context hook
3407
+ // checks a session's first user message; a first tool call that comes before that hook performs the same check here.
3408
+ await planChildGuard.assertToolAllowed(String(event.sessionID));
1505
3409
  const args = await scopedArgs(event);
1506
3410
  // #84 P2.1 (P-2, handoffs 11/32/33): a role child binds to its dispatch before its tool runs, so `router_run` and
1507
3411
  // `router_git_*` resolve the bound work root and the guard reads the dispatch budget. Tiers mode: no role table, no call.
@@ -1536,6 +3440,79 @@ export async function registerV2Hooks(
1536
3440
  }
1537
3441
  if (refusal !== undefined) throw refused(`[router] Refused for role agent ${callerRole} in this dispatch: ${refusal}`, callerRole);
1538
3442
  }
3443
+ // Phase 2.1 (memo §4.2): authority checks first, then the held refusal, then the leases (all before the legacy hook).
3444
+ if (bgActive()) {
3445
+ adoptSession(String(event.sessionID));
3446
+ // `args` (scopedArgs) rewrites `task_id` from `sessionID`: a call that names the child by `task_id` must still be seen.
3447
+ const rawInput = event.input !== null && typeof event.input === "object" ? event.input as Record<string, unknown> : undefined;
3448
+ const heldArgs = rawInput === undefined || args === null || typeof args !== "object" || typeof rawInput.task_id !== "string"
3449
+ ? args
3450
+ : { ...args, task_id: rawInput.task_id };
3451
+ const heldRefusal = held.refusal(String(event.sessionID), event.tool, heldArgs);
3452
+ if (heldRefusal !== undefined) throw refused(heldRefusal, callerRole);
3453
+ // QA-2.1-8: while the journal is not reloaded the restored holds are unknown, so a resume of a session this process has no
3454
+ // attempt for may be a resume of a held child: refused (fail closed) until a reload succeeds.
3455
+ // QA-2.1-20: Code Mode `execute` code is inspected too, as `held.refusal` does: a session it resumes by name is refused alike.
3456
+ if (reloadFailed) {
3457
+ // QA-2.1-16: the refusal promises a retry; each refused attempt starts one (bounded by PENDING_RELOAD_RETRY_MS).
3458
+ retryReload();
3459
+ for (const target of resumeTargetsOf(event.tool, heldArgs, String(event.sessionID))) {
3460
+ if (inflight.byChild(target) === undefined) throw refused(reloadFailedResumeText(target), callerRole);
3461
+ }
3462
+ }
3463
+ }
3464
+ // Only the tools the guard checks (file tools, `router_git_*`, `router_run`) and the search tools (`glob`/`grep`, whose
3465
+ // result the guard filters, so the actor must be resolved before them) reach it: no host call for any other tool.
3466
+ const leaseClass = roleActionOf(event.tool);
3467
+ if (leaseClass === "read" || leaseClass === "edit" || event.tool === "glob" || event.tool === "grep" || event.tool.startsWith("router_git_") || event.tool === "router_run") {
3468
+ if (leaseStartupRefusal !== undefined) throw refused(leaseStartupRefusal, callerRole);
3469
+ const lease = await leaseGuard?.before({ sessionID: String(event.sessionID), tool: event.tool, args, callID: event.id });
3470
+ if (lease?.refuse !== undefined) throw refused(lease.refuse, callerRole);
3471
+ if (lease?.runNote !== undefined) {
3472
+ runNotes.delete(event.id);
3473
+ runNotes.set(event.id, lease.runNote);
3474
+ while (runNotes.size > 1000) runNotes.delete(runNotes.keys().next().value!);
3475
+ }
3476
+ }
3477
+ // A stale role resume must stop before hostBudget.begin or routing spends an attempt. Never bind a non-role:
3478
+ // even an unknown cached binding would make knownRoleSession treat its agentless events as role events.
3479
+ if ((event.tool === "subagent" || event.tool === "execute") && callerRoles.size > 0) {
3480
+ const cfg = loadConfig(ctx.location.directory);
3481
+ if ((cfg.routing?.orphans?.resume ?? "refuse") === "refuse") {
3482
+ const raw = event.input !== null && typeof event.input === "object" ? event.input as Record<string, unknown> : undefined;
3483
+ const resumeArgs = typeof raw?.task_id === "string" ? { ...args, task_id: raw.task_id } : args;
3484
+ for (const child of [...new Set(resumeTargetsOf(event.tool, resumeArgs, String(event.sessionID)))].slice(0, MAX_ORPHAN_RESUME_TARGETS)) {
3485
+ let stale = false;
3486
+ try {
3487
+ const info = await sessionInfoOf(child);
3488
+ if (info.agent === undefined || !callerRoles.has(info.agent)) continue;
3489
+ // Another live instance may still own the parent's dormant journal; leave its recovery alone.
3490
+ if (info.parentID !== undefined && refusedAdoptions.has(info.parentID)) continue;
3491
+ const attempt = inflight.byChild(child);
3492
+ if (isExecutorOwned(attempt) || (attempt !== undefined && LIVE_STATES.has(attempt.state))) continue;
3493
+ if ([...dormantInflight.values()].some((records) => records.some((rec) => (rec.childSessionID ?? rec.child) === child))) continue;
3494
+ const cached = currentBinding(child, { maxOf: maxOfRoles(callerRoles) });
3495
+ if (cached?.plan !== undefined) continue;
3496
+ if (cached === undefined) {
3497
+ // A restarted plan child may have lost its binding too; its launcher protocol belongs to the executor.
3498
+ const first = withoutHostPreamble(firstMessageText(await ctx.session.context({ sessionID: child } as Parameters<typeof ctx.session.context>[0])) ?? "");
3499
+ if (first.startsWith(PLAN_CONTEXT_PREFIX) || LAUNCH_HEADER_PATTERN.test(first)) continue;
3500
+ }
3501
+ const binding = cached ?? await bind(child, bindingLookup, { maxOf: maxOfRoles(callerRoles) });
3502
+ if (binding.plan === undefined && binding.kind === "unknown" && (binding.cause === "unregistered" || binding.cause === "retired")) stale = true;
3503
+ } catch (error) {
3504
+ ingestLogger.warn("[router] roles: a resume target could not be checked", { child, error: String(error) });
3505
+ }
3506
+ if (stale) {
3507
+ const message = `[router] roles: ${ROLE_REFUSALS.staleResume(child)}`;
3508
+ if (recordRoleOrphan(child, "refused")) ingestLogger.warn(message);
3509
+ else console.debug(message);
3510
+ const agent = typeof args?.agent === "string" ? args.agent : String(event.agent ?? "unknown");
3511
+ throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.staleResume(child));
3512
+ }
3513
+ }
3514
+ }
3515
+ }
1539
3516
  // #84 P-5: a routed role dispatch runs in the foreground (separate from `verifying`).
1540
3517
  let roleForeground = false;
1541
3518
  if (event.tool === "subagent" && args && typeof args.agent === "string") {
@@ -1602,6 +3579,14 @@ export async function registerV2Hooks(
1602
3579
  // #84 P2.1-C: a fresh role dispatch carries its nonce at the END of the description (title marker, handoff 31).
1603
3580
  if (routed.description !== undefined) args.description = routed.description;
1604
3581
  if (routed.role !== undefined) roleForeground = true;
3582
+ // DF-1-9: a role decision read the session (dispatch.ts routeRoleCall): the floor rung is a delegate's (it has a parent), any
3583
+ // other is the orchestrator's — the kind of an unrecorded session is known without another host call. A root is marked for
3584
+ // the timing recorder too, as `session.created` does (a recorded kind skips the step path's own lookup).
3585
+ if (routed.role !== undefined && !sessionKinds.has(String(event.sessionID))) {
3586
+ const kind = routed.role.delegate === true ? "child" : "root";
3587
+ noteSessionKind(String(event.sessionID), kind);
3588
+ if (kind === "root") timings?.markRootSession(String(event.sessionID));
3589
+ }
1605
3590
  if (routed.agent !== undefined) { args.agent = routed.agent; args.subagent_type = routed.agent; }
1606
3591
  if (routed.model !== undefined) args.model = routed.model;
1607
3592
  if (args.model === undefined && tierModel !== undefined) args.model = tierModel;
@@ -1628,13 +3613,83 @@ export async function registerV2Hooks(
1628
3613
  const prompt = typeof original?.prompt === "string" ? original.prompt : typeof original?.description === "string" ? original.description : "";
1629
3614
  output.args.prompt = translateAdded(prompt, output.args.prompt);
1630
3615
  }
1631
- event.input = nativeArgs(event.tool, output.args, original, verifying, roleForeground);
3616
+ // Phase 2.1 (memo §4.2 step 5, §6): under `off` (or without the finish API) this is today's `verifying || roleRouted ? false : undefined`.
3617
+ let background: boolean | undefined = verifying || roleForeground ? false : undefined;
3618
+ /** QA-PDF12-6: another copy of the plugin in this process claimed the call first; its background flag stands. */
3619
+ let lostClaim = false;
3620
+ if (event.tool === "subagent" && bgActive() && finishApi !== undefined) {
3621
+ const parent = String(event.sessionID);
3622
+ // DF-1-9: a parent the plugin never recorded (a reload, past the bound) is resolved, never assumed a root: an
3623
+ // unrecorded child must not reach the `auto` rows (A-2.1-1, root parents only). A lookup that fails stays foreground;
3624
+ // QA-DF1-23: so does one the host has not answered within SESSION_KIND_DISPATCH_TIMEOUT_MS.
3625
+ const recordedKind = sessionKinds.get(parent);
3626
+ const parentKind = recordedKind ?? await dispatchSessionKindOf(parent);
3627
+ if (recordedKind === undefined && parentKind === "root") timings?.markRootSession(parent); // as the step path's lookup does
3628
+ const info = dispatchRouter.decisionOf(event.id);
3629
+ const roleLabel = info?.role ?? "unknown";
3630
+ const verification = finishApi.verificationFor(event.id);
3631
+ const decision = decideBackground({
3632
+ mode: startRouting.background.mode,
3633
+ explicit: typeof output.args?.background === "boolean" ? output.args.background : undefined,
3634
+ verifying, verificationMode: verification?.mode ?? "none", roleRouted: roleForeground,
3635
+ estimate: info === undefined ? undefined : durations?.estimate({ role: roleLabel, class: info.class, scope: info.scope }),
3636
+ minPredictedMs: startRouting.background.minPredictedMs, minSamples: DURATION_MIN_SAMPLES,
3637
+ acceptance: verification?.acceptance ?? { testsPass: false, buildPasses: false },
3638
+ planTask: false,
3639
+ holdingAvailable: held.available && !reloadFailed && finishApi.canHold(parent),
3640
+ parentIsRoot: parentKind === "root", liveCount: inflight.liveCount(),
3641
+ });
3642
+ const resumeOf = typeof output.args?.sessionID === "string" && output.args.sessionID !== "" ? output.args.sessionID : undefined;
3643
+ // QA-DF1-17: the earlier turns' completion elements of a resumed child are never the resume's, whatever their state.
3644
+ if (resumeOf !== undefined) rememberElementsOnResume(parent, resumeOf);
3645
+ const claimed = inflight.decide({
3646
+ callID: event.id, parentSessionID: parent, agent: String(output.args?.agent ?? ""),
3647
+ ...(typeof event.agent === "string" && event.agent !== "" ? { callerAgent: event.agent } : {}),
3648
+ // QA-PDF12-5: the message that made the call, so a rebuilt caller context carries real ids, never an empty one.
3649
+ ...(typeof event.messageID === "string" && event.messageID !== "" ? { callerMessageID: event.messageID } : {}),
3650
+ ...(info?.role === undefined ? {} : { role: info.role }),
3651
+ description: typeof output.args?.description === "string" ? output.args.description : "", verifying,
3652
+ verificationMode: verification?.mode ?? "none", decision,
3653
+ ...(resumeOf === undefined ? {} : { resumeOf }),
3654
+ at: nowMs(),
3655
+ });
3656
+ // QA-PDF12-6: a copy that lost the call's claim to another copy leaves the call's background flag as it found it.
3657
+ if (claimed) background = decision.background;
3658
+ else {
3659
+ // QA-PDF12-10: the owner copy holds the verification and the result; this copy must not treat the call as verifying.
3660
+ lostClaim = true;
3661
+ verifyingCalls.delete(event.id);
3662
+ }
3663
+ }
3664
+ // QA-PDF12-6: without the claim, `undefined` keeps the `background` key the input already has (set by the copy that claimed).
3665
+ event.input = nativeArgs(event.tool, output.args, original, lostClaim ? undefined : background);
3666
+ if (event.tool === "subagent") observeV2(options.observations, (fingerprint) => ({
3667
+ family: "native-args", callID: event.id, sessionID: String(event.sessionID),
3668
+ before: fingerprint(output.args), after: fingerprint(event.input),
3669
+ backgroundDecision: (lostClaim ? undefined : background) ?? null,
3670
+ }));
1632
3671
  } catch (error) {
1633
3672
  dispatchRouter.onCallFinished(event.id); // the hook chain rejected the call: it will never reach execute.after (2.2)
3673
+ inflight.cancel(event.id);
1634
3674
  throw error;
1635
3675
  }
1636
3676
  // The input the host will execute (after the legacy hook): the dispatch is registered for ingestion from it, not from what the engine decided (2.2).
1637
3677
  dispatchRouter.commit(event.id, event.input);
3678
+ // 1.1 handoff: the timing starts after `commit` (not inside it); a hook-chain rejection above makes no call.
3679
+ if (event.tool === "subagent" && timings !== undefined) {
3680
+ try {
3681
+ const info = dispatchRouter.decisionOf(event.id);
3682
+ const sent = event.input as { sessionID?: unknown; background?: unknown };
3683
+ const resumed = sent.sessionID;
3684
+ timings.recordDispatchStart({
3685
+ callID: event.id, childSessionID: typeof resumed === "string" && resumed !== "" ? resumed : null, parentSessionID: String(event.sessionID),
3686
+ role: info?.role ?? "unknown", class: info?.class ?? "unknown", scope: info?.scope ?? "unknown",
3687
+ tier: info?.tier ?? "unknown", model: info?.model ?? "unknown", background: sent.background === true, at: nowMs(),
3688
+ });
3689
+ } catch (error) {
3690
+ ingestLogger.warn("[router] timing: the dispatch start could not be recorded", { error: String(error) });
3691
+ }
3692
+ }
1638
3693
  }));
1639
3694
  /**
1640
3695
  * #84 P2.1 (T2.1.4; handoffs 28, 34, 37): the parent's `subagent` call of a role child ended. Computed BEFORE the legacy hook
@@ -1690,17 +3745,541 @@ export async function registerV2Hooks(
1690
3745
  rememberLastCall(child, end.id);
1691
3746
  if (!running) catalogFailures.delete(child); // P-3: the next attempt's catalog failure is annotated again
1692
3747
  }
1693
- evictCall(end.sessionID, end.id);
3748
+ // Phase 2.1: a running ack under background guarantees keeps the pending binding: the processor evicts it at completion
3749
+ // (otherwise an auto-backgrounded role child loses its binding before its first request).
3750
+ if (!(running && bgActive() && inflight.byCall(end.id) !== undefined)) evictCall(end.sessionID, end.id);
1694
3751
  } catch (error) {
1695
3752
  ingestLogger.warn("[router] roles: the finished role dispatch could not be released", { error: String(error) });
1696
3753
  }
1697
3754
  },
1698
3755
  };
1699
3756
  };
3757
+ // Phase 2.1 (memo §4.7): the completion processor. Only when the plugin attached its finish API; otherwise nothing is processed.
3758
+ let processor: CompletionProcessor | undefined;
3759
+ /**
3760
+ * The child's last assistant message of its current turn (after its newest user prompt, DF-1-4) (`ctx.session.context`,
3761
+ * C7/O1); also the recovery read of a persisted dispatch.
3762
+ */
3763
+ const lastAssistantText = async (child: string): Promise<{ text: string } | undefined> => {
3764
+ const history = await ctx.session.context({ sessionID: child } as Parameters<typeof ctx.session.context>[0]);
3765
+ const messages: readonly unknown[] = Array.isArray(history) ? history : [];
3766
+ for (let index = messages.length - 1; index >= 0; index--) {
3767
+ // The host's context entries are discriminated by `type` ("user" | "assistant" | "synthetic", see the instruction filter in
3768
+ // the system hook); the model-facing messages of the context hook use `role`. Both name the assistant the same way.
3769
+ const message = messages[index] as { type?: unknown; role?: unknown } | undefined;
3770
+ if (message?.type === "assistant" || message?.role === "assistant") {
3771
+ const text = messageText(message);
3772
+ if (text !== undefined) return { text };
3773
+ }
3774
+ // DF-1-4: the newest user prompt opens the current turn; an answer before it belongs to an earlier turn (a resume).
3775
+ if (message?.type === "user" || message?.role === "user") break;
3776
+ }
3777
+ ingestLogger.warn("[router] background: the child's context holds no assistant message", {
3778
+ child,
3779
+ shape: Array.isArray(history) ? `array(${messages.length})` : typeof history,
3780
+ keys: history !== null && typeof history === "object" ? Object.keys(history).slice(0, 12).join(",") : "",
3781
+ lastMessage: JSON.stringify(messages.at(-1) ?? null)?.slice(0, 300) ?? "",
3782
+ });
3783
+ return undefined;
3784
+ };
3785
+ /**
3786
+ * QA-2.1-6: the end state of a persisted dispatch's child, from its own history. The newest non-synthetic entry decides: an
3787
+ * assistant message with an error failed (or was interrupted, for an abort); one with text succeeded only when it carries a
3788
+ * completion marker (QA-2.1-18, `assistantStepCompleted`: a finish reason other than `tool-calls` or a completed time, and no
3789
+ * pending or running tool part); anything else (no entry, a user or tool turn last, a step cut mid-stream) never finished,
3790
+ * which after a restart means lost.
3791
+ */
3792
+ const childEndState = async (child: string): Promise<ChildEndState> => {
3793
+ // QA-4.2-27: the shared end rule (`childHistoryEnd`, also the executor's `HostSessions.context`).
3794
+ const end = childHistoryEnd(await ctx.session.context({ sessionID: child } as Parameters<typeof ctx.session.context>[0]));
3795
+ if (end.kind === "none") return { outcome: "lost" };
3796
+ // QA-DF1-21: a user or tool turn last, or a step without its end, is an execution that has not ended (`incomplete`).
3797
+ if (end.kind === "open") return { outcome: "lost", incomplete: true };
3798
+ // Background's own rule on top (QA-2.1-6, kept): a succeeded step without text is a result that never arrived, so the
3799
+ // dispatch is lost and its parent is told to dispatch it again (the executor reads it as an empty result instead).
3800
+ if (end.outcome === "succeeded" && end.text === undefined) return { outcome: "lost" };
3801
+ return { outcome: end.outcome, ...(end.text === undefined ? {} : { text: end.text }) };
3802
+ };
3803
+ /** QA-2.1-6: one `resume: true` entry tells the parent that a background dispatch was lost in a restart. Never throws. */
3804
+ const wakeParentLost = async (attempt: Attempt): Promise<void> => {
3805
+ if (typeof syntheticRaw !== "function") return;
3806
+ try {
3807
+ const cfg = loadConfig(ctx.location.directory);
3808
+ const resumeRefused = attempt.role !== undefined && rolesOf(cfg).has(attempt.agent)
3809
+ && (cfg.routing?.orphans?.resume ?? "refuse") === "refuse";
3810
+ await Reflect.apply(syntheticRaw, ctx.session, [{
3811
+ sessionID: attempt.parentSessionID,
3812
+ text: `[router] The background dispatch ${attemptLabel(attempt)} (${attempt.childSessionID}) was lost in a restart: its result never arrived. Dispatch it again if you still need it.${resumeRefused ? " Dispatch a fresh task: resuming it is refused." : ""}`,
3813
+ description: "Model router notice",
3814
+ metadata: { router: { kind: "lost-dispatch", child: attempt.childSessionID, callID: attempt.callID } },
3815
+ resume: true,
3816
+ }]);
3817
+ } catch (error) {
3818
+ ingestLogger.warn("[router] background: the parent of a lost dispatch could not be told", { child: attempt.childSessionID, error: String(error) });
3819
+ }
3820
+ };
3821
+ if (finishApi !== undefined) {
3822
+ const api = finishApi;
3823
+ const captureDeltaOf = api.captureDelta?.bind(api);
3824
+ // R20 (QA-2.1-6): a restored hold with its child text runs the gate again; without one it ends UNVERIFIABLE.
3825
+ reverifyRestored = async (hold) => {
3826
+ // QA-2.1-31: every verdict posted here bypasses the plugin's gate; the restored pending entry is settled with it.
3827
+ const settleEntry = (verdict: "PASS" | "FAIL" | "UNVERIFIABLE", reason?: string): void => {
3828
+ try {
3829
+ api.settleHeldDirect(hold.parentSessionID, hold.handle, { verdict, ...(reason === undefined ? {} : { reason }) });
3830
+ } catch (error) {
3831
+ ingestLogger.warn("[router] background: the pending entry of a restored hold could not be settled", { handle: hold.handle, error: String(error) });
3832
+ }
3833
+ };
3834
+ const unverifiable = async (reason: string): Promise<void> => {
3835
+ await held.verdict(hold.handle, { verdict: "UNVERIFIABLE", text: `${hold.childText === undefined ? "" : `${hold.childText}\n`}[router] not verified: ${reason}`, reason });
3836
+ settleEntry("UNVERIFIABLE", reason);
3837
+ api.releaseHeld(hold.handle);
3838
+ };
3839
+ // QA-2.1-17: a verdict the gate reached before the restart (its `state` record) is posted as it was, never recomputed.
3840
+ const stored = hold.verdict;
3841
+ if (stored !== undefined) {
3842
+ const line = `[router] ${stored.verdict}${stored.reason === undefined ? "" : ` — ${stored.reason}`}`;
3843
+ await held.verdict(hold.handle, {
3844
+ verdict: stored.verdict, text: hold.childText === undefined ? line : `${hold.childText}\n\n${line}`,
3845
+ ...(stored.reason === undefined ? {} : { reason: stored.reason }),
3846
+ });
3847
+ settleEntry(stored.verdict, stored.reason);
3848
+ api.releaseHeld(hold.handle);
3849
+ return;
3850
+ }
3851
+ // QA-2.1-17: `hold-text` is journaled for a succeeded child only, so a missing text is a child that did not
3852
+ // succeed, or one the restart cut before its text was kept.
3853
+ const childText = hold.childText;
3854
+ if (childText === undefined) {
3855
+ await unverifiable("lost in restart");
3856
+ return;
3857
+ }
3858
+ try {
3859
+ // QA-2.1-17: the plugin rebuilds the gate inputs from the journaled dispatch and the restored pending entry, and
3860
+ // re-posts a verdict the entry already reached.
3861
+ const result = await withinCaller(hold, () => {
3862
+ observeV2(options.observations, () => ({ family: "completion-effect", effect: "finish-dispatch", source: "restored-hold",
3863
+ parentSessionID: hold.parentSessionID, callID: hold.callID, childSessionID: hold.childSessionID }));
3864
+ return api.finish({
3865
+ callID: hold.callID, parentSessionID: hold.parentSessionID, childSessionID: hold.childSessionID, outputText: childText,
3866
+ status: "succeeded", mode: "background", heldHandle: hold.handle, endedAt: nowMs(), restored: hold.dispatch,
3867
+ });
3868
+ });
3869
+ // The gate runs behind `finish`; it posts the verdict through the HeldSink when it settles.
3870
+ if (result.verification.kind === "held") return;
3871
+ api.releaseHeld(hold.handle);
3872
+ const v = result.verification;
3873
+ if (v.kind === "required") {
3874
+ await held.verdict(hold.handle, { verdict: v.verdict, text: result.outputText });
3875
+ settleEntry(v.verdict, v.verdict === "UNVERIFIABLE" ? "verification data lost in restart" : undefined);
3876
+ return;
3877
+ }
3878
+ await held.verdict(hold.handle, { verdict: "UNVERIFIABLE", text: `${result.outputText}\n[router] not verified: no verification ran`, reason: "no verification ran" });
3879
+ settleEntry("UNVERIFIABLE", "no verification ran");
3880
+ } catch (error) {
3881
+ await unverifiable(`verification after a restart failed: ${String(error)}`);
3882
+ }
3883
+ };
3884
+ processor = executorProcessor = createCompletionProcessor(inflight, { // 3.1.7 W5: also the executor's runner-trigger sink
3885
+ observations: options.observations,
3886
+ // QA-PDF12-9: the caller is the one the processor's attempt carries (journaled at decide), not a capped call-id lookup.
3887
+ // QA-PDF12-14: only a succeeded completion can launch a grader as the caller, so only it waits for the caller lookups.
3888
+ finish: (input, caller) => withinCaller({ parentSessionID: input.parentSessionID, callID: input.callID, ...caller }, () => api.finish(input), input.status === "succeeded"),
3889
+ readChildResult: lastAssistantText,
3890
+ // The `!running` half of `roleAfterCall`: budget and authority notices, plus its evictions (run through its own `finish`).
3891
+ roleCompletion: async (attempt, text) => {
3892
+ const completed = await roleAfterCall({
3893
+ id: attempt.callID, sessionID: attempt.parentSessionID, status: "completed",
3894
+ result: { output: { status: "completed", output: text, sessionID: attempt.childSessionID }, content: [{ type: "text", text }] },
3895
+ input: { agent: attempt.agent },
3896
+ });
3897
+ if (completed === undefined) return [];
3898
+ completed.finish();
3899
+ evictCall(attempt.parentSessionID, attempt.callID);
3900
+ return completed.notice === undefined ? [] : [completed.notice];
3901
+ },
3902
+ releaseLeases: (holderID) => { leaseGuard?.releaseChild(holderID); leaseHandle?.notifyReleased(); },
3903
+ held, persist: journal, now: nowMs, logger: ingestLogger,
3904
+ // 2.1.4.b: the change set at child end, so a background completion verifies what the child changed.
3905
+ ...(captureDeltaOf === undefined ? {} : { captureDelta: captureDeltaOf }),
3906
+ // QA-2.1-4: a held attempt that ends without a held register gives its reserved handle back.
3907
+ releaseHeld: (handle) => api.releaseHeld(handle),
3908
+ // QA-2.1-17: a recovery finishes with the dispatch data its `inflight` record journaled.
3909
+ restoredDispatch: (attempt) => {
3910
+ const dispatch = restoredDispatches.get(attempt.callID);
3911
+ restoredDispatches.delete(attempt.callID);
3912
+ return dispatch;
3913
+ },
3914
+ });
3915
+ const closing = processor;
3916
+ closeAttempt = (attempt, cause) => closing.closeUnknown(attempt, cause);
3917
+ // Memo §11.3: an adopted `inflight` record without `processed` is recovered through the child's own history: finished ->
3918
+ // process; otherwise lost. The attempt is re-registered first so the processor has its key; a failure leaves it to the sweep.
3919
+ recoverInflight = (sessionID) => {
3920
+ const records = dormantInflight.get(sessionID);
3921
+ dormantInflight.delete(sessionID);
3922
+ const recovering = new Set<string>();
3923
+ for (const rec of records ?? []) {
3924
+ const callID = typeof rec.callID === "string" ? rec.callID : undefined;
3925
+ const child = typeof rec.childSessionID === "string" ? rec.childSessionID : typeof rec.child === "string" ? rec.child : undefined;
3926
+ if (callID === undefined || child === undefined) continue;
3927
+ // QA-DF1-21: written by this very process (its token, never just its pid, which a later process may reuse).
3928
+ const sameProcess = rec.process === processToken();
3929
+ const mode = rec.verificationMode === "required" || rec.verificationMode === "deferred" ? rec.verificationMode : "none";
3930
+ const registered = inflight.decide({
3931
+ callID, parentSessionID: sessionID, agent: typeof rec.agent === "string" ? rec.agent : "",
3932
+ ...(typeof rec.callerAgent === "string" && rec.callerAgent !== "" ? { callerAgent: rec.callerAgent } : {}),
3933
+ ...(typeof rec.callerMessageID === "string" && rec.callerMessageID !== "" ? { callerMessageID: rec.callerMessageID } : {}),
3934
+ ...(typeof rec.role === "string" ? { role: rec.role } : {}),
3935
+ description: typeof rec.description === "string" ? rec.description : "",
3936
+ verifying: rec.verifying === true, verificationMode: mode,
3937
+ decision: { background: true, hold: false, reason: "prior" }, at: typeof rec.at === "number" ? rec.at : nowMs(),
3938
+ });
3939
+ const handle = typeof rec.hold === "string" ? rec.hold : typeof rec.handle === "string" ? rec.handle : undefined;
3940
+ // A held dispatch is recovered only while its hold is live here (restored or still journaled); otherwise it is a plain one.
3941
+ const holdHandle = handle !== undefined && held.isHeld(child) ? handle : undefined;
3942
+ const attempt = registered
3943
+ ? inflight.acknowledge(callID, child, { userBackgrounded: true, ...(holdHandle === undefined ? {} : { hold: { handle: holdHandle } }) })
3944
+ : undefined;
3945
+ if (attempt === undefined) continue;
3946
+ recovering.add(callID);
3947
+ restoredDispatches.delete(callID);
3948
+ restoredDispatches.set(callID, restoredDispatchOf(rec.dispatch));
3949
+ while (restoredDispatches.size > MAX_ADOPTED_SESSIONS) restoredDispatches.delete(restoredDispatches.keys().next().value!);
3950
+ trackBackground((async () => {
3951
+ // QA-2.1-6: the child's END STATE decides (succeeded / failed / interrupted / never finished), not just "some text exists".
3952
+ let end: ChildEndState = { outcome: "lost" };
3953
+ try {
3954
+ end = await childEndState(child);
3955
+ } catch (error) {
3956
+ ingestLogger.warn("[router] background: the child of a persisted dispatch could not be read; treated as lost", { child, error: String(error) });
3957
+ }
3958
+ // QA-DF1-21: a record of this very process (an owning location the host evicted, not a restart) whose child's last step
3959
+ // has no end is a child still running here: its attempt stays acknowledged (dormant) until its end event processes it.
3960
+ if (end.outcome === "lost" && end.incomplete === true && sameProcess) {
3961
+ ingestLogger.info?.("[router] background: an adopted dispatch of this process is still running; waiting for its end", { child, callID });
3962
+ return;
3963
+ }
3964
+ await closing.process(child, end.outcome === "lost"
3965
+ ? { kind: "recovery", outcome: "lost", text: undefined, at: nowMs() }
3966
+ : { kind: "recovery", outcome: end.outcome, text: end.text ?? "", at: nowMs() });
3967
+ if (end.outcome === "lost" && attempt.role !== undefined) recordRoleOrphan(child, "lost");
3968
+ // QA-2.1-6: a lost dispatch without a hold wakes its parent once (a held one is woken by its verdict post). Once per child:
3969
+ // the processor runs once per attempt and journals `processed`, so the next start does not recover it again.
3970
+ if (end.outcome === "lost" && holdHandle === undefined) await wakeParentLost(attempt);
3971
+ })());
3972
+ }
3973
+ return recovering;
3974
+ };
3975
+ for (const sessionID of [...dormantInflight.keys()]) {
3976
+ const recovered = recoverInflight(sessionID);
3977
+ // QA-2.1-29: a hold adopted before the processor existed waited for this recovery; a skipped one is settled now.
3978
+ const waiting = deferredRestores.get(sessionID);
3979
+ deferredRestores.delete(sessionID);
3980
+ if (waiting !== undefined && waiting.unverified.some((h) => !recovered.has(h.callID))) {
3981
+ trackBackground(settleRestoredHolds(sessionID, waiting, recovered));
3982
+ }
3983
+ }
3984
+ }
3985
+ // Phase 2.1 (memo §13): the three turn-state providers. They render nothing (and are not registered) under `off`.
3986
+ if (bgActive() && processor !== undefined) {
3987
+ const completing = processor;
3988
+ const unregisters = [
3989
+ turnState.registerTurnStateProvider({
3990
+ name: "completed", order: PROVIDER_ORDER.completed,
3991
+ render: (sid) => renderCompleted(completing.completedFor(sid)),
3992
+ active: (sid) => completing.completedFor(sid).length > 0,
3993
+ }),
3994
+ turnState.registerTurnStateProvider({
3995
+ name: "held", order: PROVIDER_ORDER.held,
3996
+ render: (sid) => renderHeld(held.heldFor(sid)),
3997
+ active: (sid) => held.heldFor(sid).length > 0,
3998
+ }),
3999
+ turnState.registerTurnStateProvider({
4000
+ name: "in-flight", order: PROVIDER_ORDER.inFlight,
4001
+ render: (sid) => renderInFlight(inflight.listForParent(sid).filter((attempt) => LIVE_STATES.has(attempt.state)), nowMs()),
4002
+ active: (sid) => inflight.listForParent(sid).some((attempt) => LIVE_STATES.has(attempt.state)),
4003
+ }),
4004
+ ];
4005
+ registrations.push({ dispose: async () => { for (const unregister of unregisters) unregister(); } });
4006
+ }
4007
+ // 3.1.7 W1: the executor's host adapters and its (nullable, M3) construction. Without `options.executor`, or when it answers
4008
+ // null, nothing below registers anything and every seam above stays a no-op.
4009
+ const childRunner = runtime?.childRunner;
4010
+ if (options.executor !== undefined && childRunner !== undefined) {
4011
+ const hosts: HostSessions = {
4012
+ get: async (sessionID) => {
4013
+ const session = await sessionOf(sessionID) as { id?: unknown; parentID?: unknown } | null | undefined;
4014
+ if (session === null || session === undefined) return null;
4015
+ return { id: typeof session.id === "string" ? session.id : sessionID, parentID: typeof session.parentID === "string" && session.parentID !== "" ? session.parentID : null };
4016
+ },
4017
+ context: async (sessionID) => executorHostContext(await ctx.session.context({ sessionID } as Parameters<typeof ctx.session.context>[0])),
4018
+ activity: async () => "unknown",
4019
+ interrupt: async (sessionID) => { await ctx.session.interrupt({ sessionID }); },
4020
+ synthetic: async (i) => {
4021
+ // QA-3.1 nit 1: the metadata goes through to the host.
4022
+ await ctx.session.synthetic({ sessionID: i.sessionID, text: i.text, description: i.description, metadata: i.metadata, resume: i.resume });
4023
+ },
4024
+ move: async (sessionID, directory) => { await ctx.session.move({ sessionID, directory }); },
4025
+ onEvent: (listener) => {
4026
+ hostEventListeners.add(listener);
4027
+ return () => { hostEventListeners.delete(listener); };
4028
+ },
4029
+ };
4030
+ const bookkeeping: DispatchBookkeeping = {
4031
+ decisionRow: (req) => executorInFlight.remember(req),
4032
+ recordDispatchStart: (req, startedAt) => {
4033
+ const entry = executorLaunches.get(executorAttemptKey(req.taskId, req.attempt));
4034
+ const at = Date.parse(startedAt);
4035
+ timings?.recordDispatchStart({
4036
+ callID: entry?.callID ?? `executor:${req.planId}:${req.taskId}#${req.attempt}:${req.nonce}`, childSessionID: null,
4037
+ parentSessionID: req.orchestratorSessionID, role: req.role, class: "unknown", scope: "unknown",
4038
+ tier: req.route.heavy ? "heavy" : "unknown", model: `${req.route.model.providerID}/${req.route.model.modelID}`,
4039
+ background: true, at: Number.isFinite(at) ? at : nowMs(),
4040
+ });
4041
+ },
4042
+ registerInFlight: (taskId, attempt, child) => executorInFlight.register(taskId, attempt, child),
4043
+ unregisterInFlight: (taskId, attempt, status) => executorInFlight.unregister(taskId, attempt, status),
4044
+ // QA-PDF21-2-11: a budget resume opens a new guard round and a new read-cap round for its child, as a routed resume does.
4045
+ // The host's step count starts over with the resumed round too (handoff 22), as a routed resume's does.
4046
+ beginResumeRound: (childSessionID, agent, prompt) => {
4047
+ hostBudget.begin(childSessionID);
4048
+ options.executorChildGuard?.beginResumeRound(childSessionID, agent, prompt);
4049
+ },
4050
+ };
4051
+ /**
4052
+ * QA-3.1-2: a plan child's grant, computed as the role dispatch path computes one (`grantFor`): the role's base actions
4053
+ * (the local read actions every role gets; an implementer also edits) plus the route `needs` mapped to actions (`edit` →
4054
+ * edit, `shell`/`network` → router_run; `web` and `external_dir` add none, the work root satisfies `external_dir`), all
4055
+ * within the role's maximum and the separation rule. An unknown role gets nothing (fail closed).
4056
+ */
4057
+ const planChildGrant = (agent: string, needs: readonly string[], workRoot: string): string[] => {
4058
+ const spec = rolesOf(loadConfig(ctx.location.directory)).get(agent);
4059
+ if (spec === undefined) {
4060
+ if (rolesStarted === true) ingestLogger.warn("[router] executor: a plan child's agent is no live role agent; it is bound with no action", { agent });
4061
+ return [];
4062
+ }
4063
+ const routeNeeds = needs.filter((n): n is Need => (NEEDS as readonly string[]).includes(n));
4064
+ return [...grantFor(spec, { ...UNKNOWN_FACTS, needs: routeNeeds }, [], workRoot).actions];
4065
+ };
4066
+ const host: V2ExecutorHost = {
4067
+ hosts,
4068
+ routes: null,
4069
+ bindings: {
4070
+ // QA-3.1-2: the launch request's grant holds the route `needs`; the binding gets the role grant they map to.
4071
+ // QA-PDF21-2-20: the bound child is read-capped by its launch prompt's cap line, as a routed role child by its dispatch's.
4072
+ bind: (i) => {
4073
+ const { prompt, ...binding } = i;
4074
+ bindPlanChild({ ...binding, grant: planChildGrant(i.agent, i.grant, i.workRoot) });
4075
+ if (prompt !== undefined) options.executorChildGuard?.applyCap(i.childSessionID, i.agent, prompt);
4076
+ },
4077
+ evict: (childSessionID) => evictBinding(childSessionID),
4078
+ },
4079
+ bookkeeping,
4080
+ verifier: options.slotVerifier ?? null,
4081
+ leases: leaseHandle === undefined ? null : { registry: leaseHandle.registry, notifyReleased: () => leaseHandle?.notifyReleased() },
4082
+ durations: durations ?? null,
4083
+ leaseRegistry: options.leaseRegistry ?? null,
4084
+ runner: childRunner,
4085
+ pinOrchestrator: (sessionID) => childRunner.pin(sessionID),
4086
+ onLauncherMetric: (planId, m) => executor?.runtime.recordMetric(planId, m),
4087
+ knownAgent: (agent) => config.agent[agent] !== undefined,
4088
+ lifetime: executorLifetime.signal,
4089
+ // QA-5.1-26: a claim handover's executor goes through `adopt`, as the factory's does at start.
4090
+ onExecutor: (handed) => {
4091
+ let adopted: boolean;
4092
+ try {
4093
+ adopted = adopt(handed);
4094
+ } catch (error) {
4095
+ ingestLogger.warn("[router] executor: the handed-over executor could not be wired", { error: String(error) });
4096
+ // Adopted before the failure: W7 disposes it, so the caller must not.
4097
+ return executor === handed;
4098
+ }
4099
+ if (adopted) trackBackground(retryHookWiring);
4100
+ return adopted;
4101
+ },
4102
+ };
4103
+ /** Settles once the retry hook of the adopted executor is registered (`adopt`). */
4104
+ let retryHookWiring: Promise<void> = Promise.resolve();
4105
+ /**
4106
+ * QA-5.1-26: the one path an executor is adopted by: the factory's at start, or the one a claim handover assembles later
4107
+ * (`host.onExecutor`). It sets `executor`, which the host events, the step tracking, the launcher metrics and the
4108
+ * lease-release tick read and W7 disposes; it registers the router-tool-call feed, the plan-line and manual-ready
4109
+ * provider, the executor instructions and the retry hook, and starts the runtime (`start()` is memoised: recovery runs
4110
+ * once). Idempotent: the executor already adopted answers true and registers nothing again. Refused (false): another
4111
+ * executor while one is adopted, or any once dispose began (its owner disposes it). The retry hook's registration is
4112
+ * asynchronous: `retryHookWiring` settles with it.
4113
+ */
4114
+ const adopt = (built: V2Executor): boolean => {
4115
+ if (executor === built) return true;
4116
+ if (disposed || executor !== null) return false;
4117
+ executor = built;
4118
+ const unregisters: Array<() => void> = [];
4119
+ registrations.push({ dispose: async () => { for (const unregister of unregisters.splice(0)) unregister(); } });
4120
+ // W2 (3.1.7.a): every router tool call of a bound orchestrator refreshes the executor (guard 6, the ready set).
4121
+ unregisters.push(childRunner.onContextCaptured((c) => {
4122
+ try {
4123
+ built.runtime.onRouterToolCall(c.sessionID);
4124
+ } catch (error) {
4125
+ ingestLogger.warn("[router] executor: a router tool call could not be fed", { error: String(error) });
4126
+ }
4127
+ }));
4128
+ // W6 (3.1.7.e): the plan line and the manual tasks ready for the orchestrator.
4129
+ unregisters.push(turnState.registerTurnStateProvider({
4130
+ name: PLAN_PROVIDER_NAME, order: PLAN_PROVIDER_ORDER,
4131
+ render: (sid) => {
4132
+ const line = built.runtime.planLine(sid);
4133
+ const manual = built.runtime.manualReady(sid);
4134
+ const lines = [
4135
+ ...(line === null ? [] : [line]),
4136
+ ...(manual.length === 0 ? [] : ["[router] Ready for you:", ...manual.map((t) => `- ${t.taskId}: manual (${t.kind})`)]),
4137
+ ];
4138
+ return lines.length === 0 ? undefined : lines.join("\n");
4139
+ },
4140
+ active: (sid) => built.runtime.planLine(sid) !== null || built.runtime.manualReady(sid).length > 0,
4141
+ }));
4142
+ unregisters.push(turnState.registerTurnStateProvider({
4143
+ ...createExecutorInstructionsProvider(built.runtime), order: EXECUTOR_INSTRUCTIONS_ORDER,
4144
+ }));
4145
+ // W4 (3.1.7.c, ADR 0007 D13): the host's retry decision feeds the capacity signals; the executor stops the retry of a plan
4146
+ // child only. Registered only when an executor exists (M3); on any error the decision stays unchanged.
4147
+ retryHookWiring = ctx.session.hook("retry", async (event) => {
4148
+ try {
4149
+ const sessionID = String(event.sessionID);
4150
+ // QA-3.1-21: the step's `step.started` may still wait in the event loop: the key must name this step, not the last one
4151
+ openExecutorStepForHook(sessionID);
4152
+ const { stop } = built.runtime.onRetryHook({ sessionID, stepKey: executorStepKey(sessionID), error: toHostError(event.error) });
4153
+ // QA-3.1-8: a retry is pending only when neither the executor nor the host's own decision (`{retry: false}` for a
4154
+ // usage limit, C10) stops it; a stopped one no longer keeps the step open.
4155
+ const hostRetries = (event.decision as { retry?: unknown } | undefined)?.retry !== false;
4156
+ noteExecutorStep(sessionID, !stop && hostRetries ? "retry" : "retry-stop");
4157
+ // QA-3.1-3: the memo's `decision.retry = false`. The host's `SessionRetry` carries a writable `decision` (C10 probe), so
4158
+ // a plan child's retry stops; the runtime records the stop (`capacityStopped`) either way.
4159
+ if (stop) {
4160
+ if (event.decision !== undefined && event.decision !== null) event.decision = { retry: false };
4161
+ else ingestLogger.warn("[router] executor: a plan child's retry should stop; this host offered no retry decision", { sessionID });
4162
+ }
4163
+ } catch (error) {
4164
+ ingestLogger.warn("[router] executor: the retry signal could not be fed", { error: String(error) });
4165
+ }
4166
+ }).then(async (registration) => {
4167
+ // Registered once dispose collected the registrations (a handover racing dispose): nothing else would remove it.
4168
+ if (disposed) await registration.dispose();
4169
+ else registrations.push(registration);
4170
+ });
4171
+ trackBackground(built.runtime.start().catch((error: unknown) => {
4172
+ ingestLogger.warn("[router] executor: it could not start", { error: String(error) });
4173
+ }));
4174
+ return true;
4175
+ };
4176
+ let built: V2Executor | null = null;
4177
+ try {
4178
+ built = options.executor(host);
4179
+ } catch (error) {
4180
+ ingestLogger.warn("[router] executor: it could not be built; plans are not executed", { error: String(error) });
4181
+ }
4182
+ if (built !== null) {
4183
+ if (adopt(built)) await retryHookWiring;
4184
+ else {
4185
+ ingestLogger.warn("[router] executor: the built executor was not adopted; it is disposed", {});
4186
+ await disposeExecutor(built);
4187
+ }
4188
+ }
4189
+ }
1700
4190
  registrations.push(await ctx.tool.hook("execute.after", async (event) => {
1701
4191
  // 2.2: the result names the child. A dispatch still waiting for it is registered under it, and a heuristic claim that picked
1702
4192
  // the wrong child is corrected here, before the legacy hook below records the verdict. A call without a result is just dropped.
1703
- dispatchRouter.onCallResult(event.id, event.status === "completed" ? childSessionOf(event.result) : null);
4193
+ const resultChild = event.status === "completed" ? childSessionOf(event.result) : null;
4194
+ dispatchRouter.onCallResult(event.id, resultChild);
4195
+ const runNote = runNotes.get(event.id);
4196
+ runNotes.delete(event.id);
4197
+ // Phase 2.1 (memo §4.3 steps 1-2). Timing: a non-null child binds the open start; a null child drops it.
4198
+ let ackText: string | undefined;
4199
+ if (event.tool === "subagent") {
4200
+ const running = resultChild !== null && ((event as { result?: { output?: { status?: unknown } } }).result)?.output?.status === "running";
4201
+ if (timings !== undefined) {
4202
+ try {
4203
+ if (resultChild === null) timings.cancelStart(event.id);
4204
+ else {
4205
+ timings.bindChild(event.id, resultChild);
4206
+ if (running) timings.setBackground(event.id, true);
4207
+ }
4208
+ } catch (error) {
4209
+ ingestLogger.warn("[router] timing: the dispatch result could not be recorded", { error: String(error) });
4210
+ }
4211
+ }
4212
+ if (resultChild === null) inflight.cancel(event.id);
4213
+ // A running result under mode ≠ off with a root parent: register the attempt (and its hold) BEFORE anything can render a completion.
4214
+ const parent = String(event.sessionID);
4215
+ const rec = running && bgActive() && finishApi !== undefined ? inflight.byCall(event.id) : undefined;
4216
+ if (rec !== undefined && resultChild !== null && knownKindOf(parent) === "root") {
4217
+ try {
4218
+ const hold = verifyingCalls.has(event.id) && rec.verificationMode === "required" && held.available && !reloadFailed && finishApi?.canHold(parent) === true;
4219
+ const handle = hold ? finishApi?.reserveHeld(parent, event.id) : undefined;
4220
+ const attempt = inflight.acknowledge(event.id, resultChild, {
4221
+ userBackgrounded: rec.decision.background !== true, ...(handle === undefined ? {} : { hold: { handle } }),
4222
+ });
4223
+ if (attempt !== undefined) {
4224
+ const notRunning = `[router] Running in the background (${resultChild}).`;
4225
+ const unheldText = verifyingCalls.has(event.id) || handle !== undefined
4226
+ ? `${notRunning} Its result will arrive unverified; the verdict follows in the router state.`
4227
+ : `${notRunning} Router guarantees apply when it completes.`;
4228
+ let journaled = true;
4229
+ // QA-2.1-17: the prompt, cwd and work root go with the records, so a gate after a restart has its inputs.
4230
+ let dispatch: RestoredDispatch | undefined;
4231
+ try {
4232
+ dispatch = finishApi?.dispatchOf(event.id);
4233
+ } catch (error) {
4234
+ ingestLogger.warn("[router] background: the dispatch data could not be read; a restart cannot verify it", { error: String(error) });
4235
+ }
4236
+ try {
4237
+ await journal.append({
4238
+ v: 1, kind: "inflight", key: attempt.key, callID: event.id, parentSessionID: parent, childSessionID: resultChild,
4239
+ label: attemptLabel(attempt), ...(handle === undefined ? {} : { handle }), at: nowMs(),
4240
+ agent: rec.agent, description: rec.description, verifying: rec.verifying, verificationMode: rec.verificationMode,
4241
+ ...(rec.callerAgent === undefined ? {} : { callerAgent: rec.callerAgent }),
4242
+ ...(rec.callerMessageID === undefined ? {} : { callerMessageID: rec.callerMessageID }),
4243
+ ...(rec.role === undefined ? {} : { role: rec.role }), hold: handle ?? null,
4244
+ ...(dispatch === undefined ? {} : { dispatch }), process: processToken(),
4245
+ }, { fsync: true });
4246
+ } catch (error) {
4247
+ journaled = false;
4248
+ ingestLogger.warn("[router] background: the dispatch could not be journaled; its result is not held", { error: String(error) });
4249
+ }
4250
+ let holding = false;
4251
+ if (handle !== undefined && journaled) {
4252
+ try {
4253
+ await held.hold({
4254
+ handle, parentSessionID: parent, childSessionID: resultChild, callID: event.id, label: attemptLabel(attempt),
4255
+ ...(rec.callerAgent === undefined ? {} : { callerAgent: rec.callerAgent }),
4256
+ ...(rec.callerMessageID === undefined ? {} : { callerMessageID: rec.callerMessageID }),
4257
+ ...(dispatch === undefined ? {} : { dispatch }),
4258
+ });
4259
+ holding = true;
4260
+ } catch (error) {
4261
+ ingestLogger.warn("[router] background: the result could not be held; it arrives unverified", { error: String(error) });
4262
+ }
4263
+ }
4264
+ if (handle !== undefined && !holding) {
4265
+ // QA-2.1-3: no hold exists, so nothing may say "held": the attempt is a plain verifying one and the handle goes back.
4266
+ delete attempt.hold;
4267
+ try {
4268
+ finishApi?.releaseHeld?.(handle);
4269
+ } catch (error) {
4270
+ ingestLogger.warn("[router] background: the reserved handle could not be released", { error: String(error) });
4271
+ }
4272
+ }
4273
+ // QA-2.1-3: the acknowledgement text is chosen only after both writes settled.
4274
+ ackText = holding ? `${notRunning} Its result is held until verification finishes.` : unheldText;
4275
+ const early = inflight.takeEarlyEnd(resultChild);
4276
+ if (early !== undefined && processor !== undefined) trackBackground(processor.process(resultChild, { kind: "early-end", end: early }));
4277
+ }
4278
+ } catch (error) {
4279
+ ingestLogger.warn("[router] background: the dispatch could not be registered as running", { error: String(error) });
4280
+ }
4281
+ }
4282
+ }
1704
4283
  const role = event.tool === "subagent" ? await roleAfterCall({
1705
4284
  id: event.id, sessionID: String(event.sessionID), status: event.status,
1706
4285
  result: (event as { result?: unknown }).result, input: (event as { input?: unknown }).input,
@@ -1717,7 +4296,21 @@ export async function registerV2Hooks(
1717
4296
  const agent = roleAgentName(event.agent) ?? (typeof event.agent === "string" && event.agent !== "" ? undefined : knownRoleSession(String(event.sessionID)));
1718
4297
  if (agent !== undefined) options.recordRefusal?.(String(event.sessionID), agent, event.tool, (event as { input?: unknown }).input);
1719
4298
  }
1720
- if (event.status !== "completed") return;
4299
+ if (event.status !== "completed") {
4300
+ if (event.tool === "subagent") inflight.cancel(event.id);
4301
+ return;
4302
+ }
4303
+ // Phase 2.1: a completed (non-running) subagent result is terminal for the processor: the legacy path ran in-line.
4304
+ if (event.tool === "subagent" && resultChild !== null && ackText === undefined
4305
+ && (event.result as { output?: { status?: unknown } } | undefined)?.output?.status !== "running") {
4306
+ inflight.foreground(event.id, resultChild);
4307
+ }
4308
+ // 1.3 (memo §14.3): a `router_run` result carries the contamination note the lease check produced in `execute.before`.
4309
+ if (event.tool === "router_run" && runNote !== undefined) {
4310
+ const base = Array.isArray(event.result.content) ? [...event.result.content]
4311
+ : typeof event.result.content === "string" ? [{ type: "text" as const, text: event.result.content }] : [];
4312
+ event.result = { ...event.result, content: [...base, { type: "text" as const, text: runNote }] };
4313
+ }
1721
4314
  if (event.tool === "grep" && protectedAgent(event.agent)) {
1722
4315
  const content = event.result.content;
1723
4316
  event.result = {
@@ -1740,12 +4333,32 @@ export async function registerV2Hooks(
1740
4333
  if (role !== undefined && event.tool === "subagent" && event.result.output?.status !== "running") {
1741
4334
  event.result = defangChildResult(event.result);
1742
4335
  }
4336
+ // 1.3 (memo §14.2): `glob`/`grep` of a child session: entries under edit by another holder are left out, plus one note line.
4337
+ if (leaseGuard !== undefined && (event.tool === "glob" || event.tool === "grep")) {
4338
+ try {
4339
+ // The guard gets the host result exactly as received (`content` + `output`) and filters both forms by the same paths.
4340
+ const searched = leaseGuard.afterSearch({ sessionID: String(event.sessionID), tool: event.tool, result: event.result });
4341
+ if (searched !== undefined && searched.result !== null && typeof searched.result === "object" && !Array.isArray(searched.result)) {
4342
+ const merged: typeof event.result = { ...event.result, ...searched.result };
4343
+ const note = searched.note;
4344
+ const body: unknown = merged.content;
4345
+ event.result = note === undefined ? merged : {
4346
+ ...merged,
4347
+ content: Array.isArray(body) ? [...body, { type: "text" as const, text: note }]
4348
+ : [{ type: "text" as const, text: typeof body === "string" ? `${body.trimEnd()}\n${note}` : note }],
4349
+ };
4350
+ }
4351
+ } catch (error) {
4352
+ ingestLogger.warn("[router] leases: a search result could not be filtered", { error: String(error) });
4353
+ }
4354
+ }
1743
4355
  const structured = event.result.output;
1744
4356
  // A user can background a foreground subagent while it is running. That
1745
4357
  // acknowledgement is not a final result and must never enter acceptance.
1746
4358
  if (event.tool === "subagent" && structured?.status === "running") {
1747
4359
  const notices = [
1748
- ...(verifying ? ["[router] This subagent is still running. Its result has not been verified; automatic acceptance requires a completed foreground return."] : []),
4360
+ ...(ackText !== undefined ? [ackText]
4361
+ : verifying ? ["[router] This subagent is still running. Its result has not been verified; automatic acceptance requires a completed foreground return."] : []),
1749
4362
  ...(banner === undefined ? [] : [banner]),
1750
4363
  ];
1751
4364
  if (!notices.length) return;
@@ -1761,14 +4374,20 @@ export async function registerV2Hooks(
1761
4374
  }
1762
4375
  const text = event.tool === "subagent" && structured && typeof structured === "object" && typeof structured.output === "string"
1763
4376
  ? structured.output : contentText(event.result.content);
1764
- // QA-P21-1-3: the plugin's signals and gate read the child from the legacy metadata; a role result names it there too when
1765
- // the host reports it only in the structured output (spike S1: `result.output.sessionID`). Tier calls: unchanged.
4377
+ // QA-P21-1-3: the plugin's signals and gate read the child from the legacy metadata; a result names it there when the host
4378
+ // reports it only in the structured output (spike S1: `result.output.sessionID`). A role call takes the child the role
4379
+ // path resolved; a tier subagent call takes the structured output's non-empty string `sessionID`, as v1 always had it, so the
4380
+ // child's tool-observed edits and unobservable-writer tally reach the producer lineage. Metadata that already names the
4381
+ // child (`sessionID` or `sessionId`) is never overwritten; every other call's metadata passes through unchanged.
1766
4382
  const resultMetadata = event.result.metadata as Record<string, unknown> | undefined;
4383
+ const structuredChild = event.tool === "subagent" && typeof structured?.sessionID === "string" && structured.sessionID !== ""
4384
+ ? structured.sessionID : undefined;
4385
+ const namedChild = role?.child != null ? role.child : structuredChild;
1767
4386
  const output = {
1768
4387
  title: "", output: text,
1769
4388
  metadata: {
1770
4389
  ...resultMetadata,
1771
- ...(role?.child != null && resultMetadata?.sessionID === undefined && resultMetadata?.sessionId === undefined ? { sessionID: role.child } : {}),
4390
+ ...(namedChild !== undefined && resultMetadata?.sessionID === undefined && resultMetadata?.sessionId === undefined ? { sessionID: namedChild } : {}),
1772
4391
  },
1773
4392
  };
1774
4393
  await within(hookContext(event), async () => {
@@ -1808,6 +4427,10 @@ export async function registerV2Hooks(
1808
4427
  : structured && typeof structured === "object" && typeof structured.output === "string"
1809
4428
  ? { output: { ...structured, output: final } } : {}),
1810
4429
  };
4430
+ if (event.tool === "subagent") observeV2(options.observations, () => ({
4431
+ family: "completion-effect", effect: "annotation-delivery", source: "foreground-result",
4432
+ parentSessionID: String(event.sessionID), callID: event.id, childSessionID: resultChild,
4433
+ }));
1811
4434
  } finally {
1812
4435
  role?.finish();
1813
4436
  if (event.tool === "subagent") forgetRoutedRole(event.id);
@@ -1816,8 +4439,31 @@ export async function registerV2Hooks(
1816
4439
 
1817
4440
  // V2 events are immutable facts. A completed-text warning is a synthetic
1818
4441
  // transcript entry, instead of mutating an already-persisted text part.
4442
+ /**
4443
+ * QA-2.1-21: the handling of each event is background work from the moment the loop takes it until the loop asks for the
4444
+ * next one (a `continue` and a `break` included), so the settled seam and `dispose` never miss what an event starts after
4445
+ * an await (the timing store's file write before the processor starts). Only the events that start background work are
4446
+ * tracked (a child's creation adopts, its end processes): a step event's handler may wait for the model catalog until
4447
+ * `dispose` (QA-2.1-5), which the settled seam must never wait for.
4448
+ */
4449
+ const trackedEvents = async function* <T>(source: AsyncIterable<T>): AsyncGenerator<T> {
4450
+ for await (const event of source) {
4451
+ const type: unknown = event !== null && typeof event === "object" ? Reflect.get(event, "type") : undefined;
4452
+ if (typeof type !== "string" || (type !== "session.created" && !type.startsWith("session.execution."))) {
4453
+ yield event;
4454
+ continue;
4455
+ }
4456
+ let handled: () => void = () => undefined;
4457
+ trackBackground(new Promise<void>((resolve) => { handled = resolve; }));
4458
+ try {
4459
+ yield event;
4460
+ } finally {
4461
+ handled();
4462
+ }
4463
+ }
4464
+ };
1819
4465
  eventTask = (async () => {
1820
- for await (const event of ctx.event.subscribe({ signal: abort.signal })) {
4466
+ for await (const event of trackedEvents(ctx.event.subscribe({ signal: abort.signal }))) {
1821
4467
  if (abort.signal.aborted) break;
1822
4468
  try {
1823
4469
  const data = event.data as Record<string, any>;
@@ -1826,6 +4472,88 @@ export async function registerV2Hooks(
1826
4472
  if (HOST_TOOL_SUCCESS_EVENT.test(event.type) && data && Array.isArray(data.outputPaths)) {
1827
4473
  rememberOutputs(data.sessionID, data.outputPaths.filter((path: unknown): path is string => typeof path === "string"));
1828
4474
  }
4475
+ // Phase 2.1 (memo §4.6): timing, leases and the completion processor, before any existing `continue` below.
4476
+ if (typeof data?.sessionID === "string") {
4477
+ const sid: string = data.sessionID;
4478
+ // 3.1.7 W4/W6 (M46): the executor's one host-event path; a no-op without an executor.
4479
+ forwardHostEvent(event.type, sid, data, (event as { created?: unknown }).created);
4480
+ if (event.type === "session.created") {
4481
+ noteSessionKind(sid, data.parentID ? "child" : "root");
4482
+ if (!data.parentID) timings?.markRootSession(sid);
4483
+ // QA-2.1-6: the event loop adopts too, so a parent that only shows up through events still gets its records.
4484
+ adoptSession(typeof data.parentID === "string" && data.parentID !== "" ? data.parentID : sid);
4485
+ } else if (event.type === "session.step.ended") {
4486
+ if (timings !== undefined) {
4487
+ if (timings.isRootSession(sid)) {
4488
+ const tokens = typeof data.tokens === "object" && data.tokens !== null ? data.tokens as Record<string, any> : {};
4489
+ timings.onRootStep(sid, {
4490
+ input: Number(tokens.input) || 0, cacheRead: Number(tokens.cache?.read) || 0, cacheWrite: Number(tokens.cache?.write) || 0,
4491
+ }, event.id);
4492
+ } else if (!sessionKinds.has(sid)) {
4493
+ const recorder = timings; // one lazy lookup per unregistered session (cached by sessionKindOf), not awaited
4494
+ void sessionKindOf(sid).then((kind) => { if (kind === "root") recorder.markRootSession(sid); });
4495
+ }
4496
+ }
4497
+ } else if (event.type === "session.step.failed" || event.type === "session.retry.scheduled") {
4498
+ const failure: unknown = data.error ?? data;
4499
+ const detail = typeof failure === "object" && failure !== null ? failure as { type?: unknown; status?: unknown } : {};
4500
+ const capacity = classifyCapacity({
4501
+ type: typeof detail.type === "string" ? detail.type : null, status: typeof detail.status === "number" ? detail.status : null,
4502
+ });
4503
+ if (capacity !== null) timings?.onCapacitySignal(sid, capacity, nowMs());
4504
+ } else if (event.type === "session.execution.succeeded" || event.type === "session.execution.failed" || event.type === "session.execution.interrupted") {
4505
+ const outcome = event.type === "session.execution.succeeded" ? "succeeded" : event.type === "session.execution.failed" ? "failed" : "interrupted";
4506
+ const created: unknown = (event as { created?: unknown }).created;
4507
+ const at = created instanceof Date ? created.getTime() : typeof created === "number" ? created : nowMs();
4508
+ // QA-2.1-21: the end handling is background work from its first await on (the timing store writes to disk
4509
+ // before the processor starts): tracked, so the settled seam and `dispose` never miss the processing it starts.
4510
+ const timingDone = timings === undefined ? undefined : timings.onExecutionOutcome(sid, event.id, outcome, at);
4511
+ if (timingDone !== undefined) {
4512
+ const endHandled = Promise.resolve(timingDone).then(() => undefined);
4513
+ trackBackground(endHandled);
4514
+ await endHandled;
4515
+ }
4516
+ // DF-1-5: a root run's end closes its orchestrator turn, whatever the background mode: under background-first dispatch
4517
+ // the kickoff and each synthetic wake-up are runs without a `prompt` hook, so no prompt would ever close them.
4518
+ if (timings?.isRootSession(sid) === true) {
4519
+ const turnDone = timings.onRootExecutionEnd(sid, event.id)
4520
+ .catch((error: unknown) => ingestLogger.warn("[router] timing: the turn boundary could not be recorded", { error: String(error) }));
4521
+ trackBackground(turnDone);
4522
+ await turnDone;
4523
+ }
4524
+ leaseGuard?.releaseChild(sid);
4525
+ leaseHandle?.notifyReleased();
4526
+ // QA-2.1-6: an end event adopts the parent's records: the root itself, or (for a child this process has no attempt for)
4527
+ // its parent, looked up once (`sessionOf`) and never awaited here.
4528
+ if (sessionKinds.get(sid) === "root") adoptSession(sid);
4529
+ else if (bgActive() && inflight.byChild(sid) === undefined && !sessionKinds.has(sid)) {
4530
+ // QA-2.1-30: only a session of unknown kind is looked up: a child seen at `session.created` had its parent
4531
+ // adopted there, and a looked-up child is remembered, so later ends never call `sessionOf` again.
4532
+ trackBackground(sessionOf(sid).then((session) => {
4533
+ const parentID: unknown = session !== null && typeof session === "object" ? Reflect.get(session, "parentID") : undefined;
4534
+ if (typeof parentID === "string" && parentID !== "") {
4535
+ noteSessionKind(sid, "child");
4536
+ adoptSession(parentID);
4537
+ } else {
4538
+ adoptSession(sid);
4539
+ }
4540
+ }));
4541
+ }
4542
+ if (bgActive() && processor !== undefined) {
4543
+ const attempt = inflight.byChild(sid);
4544
+ if (attempt !== undefined) {
4545
+ // QA-2.1-21: tracked, so `dispose` and the settled seam wait for the completion it starts.
4546
+ // DF-1-4: a `child-ended` attempt met an end before its turn had an answer to read: this end delivers it.
4547
+ if (attempt.state === "acknowledged" || attempt.state === "child-ended") trackBackground(processor.process(sid, { kind: "end-event", outcome, eventID: event.id, at }));
4548
+ else ingestLogger.warn("[router] background: an end event met an attempt that is not awaiting one", { child: sid, state: attempt.state, outcome });
4549
+ } else if (sessionKinds.get(sid) !== "root") {
4550
+ // A session whose kind is not yet known may be a child whose acknowledgement is still to come (bounded, TTL).
4551
+ inflight.noteEarlyEnd(sid, { outcome, eventID: event.id, at });
4552
+ }
4553
+ if (sessionKinds.get(sid) === "root") processor.endTurn(sid);
4554
+ }
4555
+ }
4556
+ }
1829
4557
  if (event.type === "session.step.ended" || event.type === "session.step.failed") {
1830
4558
  // Cost and tokens of a registered child dispatch (ingest ignores every other session).
1831
4559
  await ingesting(event.type, () => ingest.onStepEnded(event));
@@ -1839,12 +4567,27 @@ export async function registerV2Hooks(
1839
4567
  // authority requests go with it.
1840
4568
  if (typeof data.sessionID === "string") {
1841
4569
  evictBinding(data.sessionID);
4570
+ forgetWorkingSet(data.sessionID); // cross-repo P1.4: the orchestrator's bound repository locations
1842
4571
  evictAuthority(data.sessionID);
1843
4572
  ownOutputs.delete(data.sessionID); // QA-P23-2-A1
1844
4573
  lookupNamedAgent.delete(data.sessionID);
1845
4574
  lastCallOfChild.delete(data.sessionID);
1846
4575
  hostBudget.forget(data.sessionID);
1847
4576
  effortStore.forget(data.sessionID); // #90 P1.2: a deleted session is no longer answered
4577
+ // Phase 2.1 (memo §4.6): the session's attempts, holds, leases and cached kind go with it.
4578
+ inflight.forgetSession(data.sessionID);
4579
+ seenCompletionElements.delete(data.sessionID);
4580
+ lastScannedElements.delete(data.sessionID);
4581
+ processor?.forgetSession(data.sessionID);
4582
+ held.forgetSession(data.sessionID);
4583
+ leaseGuard?.releaseChild(data.sessionID);
4584
+ leaseHandle?.notifyReleased();
4585
+ sessionKinds.delete(data.sessionID);
4586
+ // QA-2.1-11 / QA-2.1-13: the cached directory, the failed kind lookup and the adoption mark go with the session.
4587
+ sessionDirs.delete(data.sessionID);
4588
+ failedKinds.delete(data.sessionID);
4589
+ adoptedSessions.delete(data.sessionID);
4590
+ refusedAdoptions.delete(data.sessionID);
1848
4591
  }
1849
4592
  await ingesting("session.deleted", () => ingest.onSessionGone(data.sessionID));
1850
4593
  } else if (FLUSH_EVENT_TYPES.has(event.type)) {
@@ -1878,6 +4621,7 @@ export async function registerV2Hooks(
1878
4621
  })().catch((error: unknown) => {
1879
4622
  if (!abort.signal.aborted) console.warn("[model-router] OpenCode 2 event subscription failed", error);
1880
4623
  });
4624
+ Object.defineProperty(cleanup, V2_BACKGROUND_SETTLED, { value: settleBackground, enumerable: false });
1881
4625
  return cleanup;
1882
4626
  } catch (error) {
1883
4627
  await cleanup();