opencode-model-router 2.8.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 (90) hide show
  1. package/CHANGELOG.md +364 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
@@ -27,13 +27,14 @@ import type { Ingest } from "../routing/outcomes/ingest";
27
27
  import { createEngineRuntime } from "../routing/wire/runtime";
28
28
  import {
29
29
  annotateSubagentResult, childSessionOf, createDispatchRouter, forgetRoutedRole, gitWorktreeList, normalizeRootText, parseWorktreeList,
30
- roleMaxActions, routedRoleOf, takeSubagentAnnotations,
30
+ ROLE_REFUSALS, RoleDispatchRefusal, roleMaxActions, routedRoleOf, takeSubagentAnnotations,
31
31
  } from "../routing/wire/dispatch";
32
32
  import type { RouterConfig } from "../router/config";
33
33
  import { resolveRoles, type AuthorityAction, type RoleSpec } from "../router/roles";
34
34
  import {
35
- 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,
36
36
  } from "../routing/roles/binding";
37
+ import { recordRoleOrphan, takeRoleBindingLookupNotice } from "../routing/roles/orphans";
37
38
  import type { DispatchGrant } from "../routing/roles/policy";
38
39
  import { forgetWorkingSet, workingSetOf } from "../routing/wire/working-set";
39
40
  import {
@@ -48,10 +49,165 @@ import { ROUTER_BUDGET_NOTE_PREFIX } from "../router/prompts";
48
49
  import { parseReturnPrefix } from "../routing/outcomes/signals";
49
50
  import { lookupDispatch } from "../router/sessions";
50
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";
51
56
  import { CONTEXT7_DOC_TOOLS, evaluatePermission, permissionMatches, permissionRules, publishReadOnlyPermissions } from "../router/read-only";
52
57
  import { filterSensitiveGrep, isSensitivePath } from "../router/sensitive-paths";
53
58
  import { canonicalAuthorityPath, insideWorkRoot } from "../routing/roles/work-root";
54
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
+ }
55
211
 
56
212
  /** Translate the router's own v1 tool vocabulary at the v2 boundary. */
57
213
  export function v2Instructions(text: string): string {
@@ -84,14 +240,16 @@ function taskArgs(toolName: string, input: unknown): any {
84
240
  }
85
241
 
86
242
  /**
87
- * `foreground` (#84 P-5): a role dispatch is forced to the foreground whatever the verification settings, so the router can
88
- * 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.
89
247
  */
90
- 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 {
91
249
  if (!args || typeof args !== "object") return args;
92
250
  if (toolName === "subagent") {
93
251
  const { subagent_type, task_id, ...rest } = args;
94
- 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 }) };
95
253
  }
96
254
  if (toolName === "shell") { const { cwd, ...rest } = args; return { ...rest, ...(cwd === undefined ? {} : { workdir: cwd }) }; }
97
255
  if (["read", "write", "edit"].includes(toolName)) {
@@ -128,6 +286,7 @@ function messageText(message: unknown): string | undefined {
128
286
  if (!message || typeof message !== "object") return undefined;
129
287
  const m = message as Record<string, unknown>;
130
288
  if (typeof m.text === "string") return m.text;
289
+ if (typeof m.content === "string") return m.content;
131
290
  const parts = Array.isArray(m.content) ? m.content : Array.isArray(m.parts) ? m.parts : undefined;
132
291
  if (parts === undefined) return undefined;
133
292
  const texts = parts.flatMap((part) => part && typeof part === "object" && (part as Record<string, unknown>).type === "text"
@@ -784,10 +943,230 @@ export function normalizeAgentOptions(options: Readonly<Record<string, unknown>>
784
943
  }
785
944
 
786
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
+
787
1166
  export async function registerV2Hooks(
788
1167
  ctx: Context,
789
1168
  hooks: Hooks,
790
- runtime?: Pick<V2Runtime, "withToolContext" | "applyChildSystem"> & Partial<Pick<V2Runtime, "dispose" | "forgetSession">>,
1169
+ runtime?: Pick<V2Runtime, "withToolContext" | "applyChildSystem"> & Partial<Pick<V2Runtime, "dispose" | "forgetSession" | "childRunner">>,
791
1170
  /**
792
1171
  * `ingest`: the plugin instance's telemetry ingest (M6, QA-2.1-7); without one the adapter ingests nothing.
793
1172
  * `isBypassed`: the plugin's `/bypass` state (#84 P2.1: the role path's router-gate condition, S10/P-9).
@@ -796,6 +1175,7 @@ export async function registerV2Hooks(
796
1175
  * `hostSettleMs`: how long a role dispatch's result waits for the child's execution-end event (default 500 ms).
797
1176
  */
798
1177
  options: {
1178
+ observations?: V2Observations;
799
1179
  ingest?: Ingest; isBypassed?: () => boolean; hostBudget?: HostBudgetObserver; hostSettleMs?: number;
800
1180
  onHostBudget?: (observe: (childSessionID: string, stepLimit: number | null) => HostBudgetObservation) => void;
801
1181
  /**
@@ -822,6 +1202,20 @@ export async function registerV2Hooks(
822
1202
  * add to the refusal (its denied_cap stop or advisory banner), or undefined. Absent: refusals are not counted.
823
1203
  */
824
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;
825
1219
  } = {},
826
1220
  ): Promise<() => Promise<void>> {
827
1221
  // The old plugin surface uses separate mutable input/output bags. Keep those
@@ -855,6 +1249,27 @@ export async function registerV2Hooks(
855
1249
  // M6 (2.1.3): child-session outcomes and costs reach the outcome store through the plugin instance's ingest, which
856
1250
  // does nothing unless routing.engine != static (its settings are null otherwise: no bundle, no files).
857
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 }] });
858
1273
  const ingest: Ingest = options.ingest ?? NOOP_INGEST;
859
1274
  // An ingestion error is logged and the loop carries on: it must never cost the router an event.
860
1275
  const ingesting = async (what: string, run: () => void | Promise<void>): Promise<void> => {
@@ -864,6 +1279,230 @@ export async function registerV2Hooks(
864
1279
  if (!abort.signal.aborted) ingestLogger.warn(`[router] telemetry ingestion: ${what} failed`, { error: error instanceof Error ? error.message : String(error) });
865
1280
  }
866
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
+ };
867
1506
  // M7 (2.2): dispatch routing and the protocol/hint adaptation share one runtime; it touches nothing (no host call, no
868
1507
  // store, no disk) while routing.engine is static, which is the default and what every config without a `routing` block is.
869
1508
  const sessionOf = (sessionID: string): Promise<unknown> => ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]);
@@ -915,13 +1554,25 @@ export async function registerV2Hooks(
915
1554
  return live.length === roles.size ? roles : new Map(live);
916
1555
  };
917
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
+ };
918
1562
  /** Handoff 32: what the binding reads of a child session (parent, agent, title, first message text). */
919
1563
  const bindingLookup: SessionLookup = async (id) => {
920
- 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
+ }
921
1571
  let firstText: string | undefined;
922
1572
  try {
923
1573
  firstText = firstMessageText(await ctx.session.context({ sessionID: id } as Parameters<typeof ctx.session.context>[0]));
924
- } catch {
1574
+ } catch (error) {
1575
+ warnBindingLookup("[router] roles: a child's first message could not be read", id, error);
925
1576
  firstText = undefined; // the title marker still binds
926
1577
  }
927
1578
  const text = (value: unknown): string | undefined => (typeof value === "string" && value !== "" ? value : undefined);
@@ -1011,19 +1662,42 @@ export async function registerV2Hooks(
1011
1662
  };
1012
1663
  /**
1013
1664
  * The directory the host resolves a session's relative paths against (its location), else the plugin's; and the session's
1014
- * parent (cross-repo P1.5: the orchestrator whose working set widens R).
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.
1015
1668
  */
1016
- const sessionInfoOf = async (sessionID: string): Promise<{ directory: string; parentID: string | undefined }> => {
1017
- const session = await ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]) as unknown as {
1018
- location?: { directory?: unknown }; parentID?: unknown;
1019
- };
1020
- const directory = session?.location?.directory;
1021
- const parentID = session?.parentID;
1022
- return {
1023
- directory: typeof directory === "string" && directory !== "" ? directory : ctx.location.directory,
1024
- parentID: typeof parentID === "string" && parentID !== "" ? parentID : undefined,
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 }),
1025
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;
1026
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);
1027
1701
  /**
1028
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
1029
1703
  * orchestrator's working set (the session that dispatched it: its dispatch record, else the session's parent) and the
@@ -1184,11 +1858,18 @@ export async function registerV2Hooks(
1184
1858
  };
1185
1859
  /** P-3: role children whose catalog failure is already annotated for the parent's current call (cleared when it ends). */
1186
1860
  const catalogFailures = new Set<string>();
1187
- 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
+ });
1188
1866
  let eventTask: Promise<void> | undefined;
1189
1867
  let disposed = false;
1190
1868
  const within = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
1191
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();
1192
1873
  const scopedArgs = async (event: { tool: string; input: unknown; sessionID: any }): Promise<any> => {
1193
1874
  const args = taskArgs(event.tool, event.input);
1194
1875
  if (["read", "write", "edit"].includes(event.tool) && typeof args?.filePath === "string" && !isAbsolute(args.filePath)) {
@@ -1200,94 +1881,914 @@ export async function registerV2Hooks(
1200
1881
  const hookContext = (event: { sessionID: any; agent: any; messageID: any; id: any }): ToolContext => ({
1201
1882
  ...event, signal: abort.signal, progress: async () => {},
1202
1883
  });
1203
- const cleanup = async () => {
1204
- if (disposed) return;
1205
- disposed = true;
1206
- abort.abort();
1207
- await runtime?.dispose?.();
1208
- // Before the event task: disposing releases a step handler that waits for the model catalog (QA-2.1-5).
1209
- await ingest.dispose();
1210
- dispatchRouter.dispose(); // this location no longer owns its sessions
1211
- await engine.dispose();
1212
- await eventTask;
1213
- await Promise.allSettled(registrations.map((registration) => registration.dispose()));
1214
- 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
+ }
1215
1905
  };
1216
-
1217
- try {
1218
- // Captured once: after our own transform, ctx.agent.list() returns
1219
- // router-modified agents, which would defeat the originals diff on refresh.
1220
- const agents = await ctx.agent.list();
1221
- const baseSeed: Record<string, LegacyAgent> = {};
1222
- for (const agent of agents.data) baseSeed[agent.id] = {
1223
- mode: agent.mode,
1224
- model: agent.model && `${agent.model.providerID}/${agent.model.id}`,
1225
- variant: agent.model?.variant,
1226
- };
1227
- let config: LegacyConfig = { agent: {}, command: {} };
1228
- registeredRole = (agent) => roleAgentOf(config.agent[agent]) === agent; // QA-P21-2-4
1229
- let originals = new Map<string, string>();
1230
- let agentOptions = new Map<string, Record<string, unknown>>();
1231
- const warnedPermissions = new Set<string>();
1232
- const warnPermissionOnce = (message: string) => {
1233
- if (warnedPermissions.has(message)) return;
1234
- warnedPermissions.add(message);
1235
- ingestLogger.warn(message);
1236
- };
1237
- const warnedRoles = new Set<string>();
1238
- const warnRoleOnce = (key: string, message: string) => {
1239
- if (warnedRoles.has(key)) return;
1240
- warnedRoles.add(key);
1241
- ingestLogger.warn(message);
1242
- };
1243
- // Plugin agents (#81) are protected like read-only tiers: readOnly ones and explicit-permission ones
1244
- // (which start from `* deny`) both keep their own deny/ask rules against inherited session grants.
1245
- // The config hook builds plugin agents in the v1 vocabulary (`bash`, `task`); the v2 host evaluates `shell`/`subagent`.
1246
- const V2_ACTIONS: Readonly<Record<string, string>> = { bash: "shell", task: "subagent" };
1247
- const v2Actions = (rules: ReturnType<typeof permissionRules>) => rules.map((rule) => ({ ...rule, action: V2_ACTIONS[rule.action] ?? rule.action }));
1248
- const protectedAgent = (name: string | undefined) => name !== undefined
1249
- && (config.agent[name]?.permission?.["*"] === "deny" || pluginAgentMarker(config.agent[name]) !== undefined);
1250
- const agentLabel = (name: string | undefined): string => {
1251
- const marker = name === undefined ? undefined : pluginAgentMarker(config.agent[name]);
1252
- return marker !== undefined && !marker.readOnly ? "plugin agent" : "read-only agent";
1253
- };
1254
- // Host agents appear after setup (the host's config-agent plugin activates after the router). Names
1255
- // the router created itself never count as host agents, or a tier would look like an existing one.
1256
- const routerCreated = new Set<string>();
1257
- let promptChecked = false;
1258
- const pendingSubagentNames = (): string[] => {
1259
- const routerConfig = loadConfig(ctx.location.directory);
1260
- const tiers = getActiveTiers(routerConfig);
1261
- return Object.keys(routerConfig.subagentTiers ?? {}).filter((name) =>
1262
- !Object.hasOwn(tiers, name) && !Object.hasOwn(routerConfig.agents ?? {}, name) && !Object.hasOwn(baseSeed, name));
1263
- };
1264
- /** Adds host agents that appeared since setup to the seed; true when the seed grew. */
1265
- const discoverHostAgents = async (): Promise<boolean> => {
1266
- const pending = pendingSubagentNames();
1267
- if (pending.length === 0) return false;
1268
- let grew = false;
1269
- for (const agent of (await ctx.agent.list()).data) {
1270
- if (!pending.includes(agent.id) || routerCreated.has(agent.id) || Object.hasOwn(baseSeed, agent.id)) continue;
1271
- baseSeed[agent.id] = {
1272
- mode: agent.mode,
1273
- model: agent.model && `${agent.model.providerID}/${agent.model.id}`,
1274
- variant: agent.model?.variant,
1275
- };
1276
- grew = true;
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;
1277
1954
  }
1278
- return grew;
1279
- };
1280
- let lastConfig: unknown;
1281
- // Returns the router config the registry state was built from; the caller
1282
- // advances `lastConfig` only once the host registries have reloaded from it.
1283
- const buildConfig = async (): Promise<unknown> => {
1284
- const next: LegacyConfig = { agent: JSON.parse(JSON.stringify(baseSeed)), command: {} };
1285
- const context7 = ctx.mcp && (await ctx.mcp.list()).data.some(server => server.name === "context7" && server.status.status !== "disabled");
1286
- // Presence-only bridge input, never registered as an MCP definition.
1287
- if (context7) next.mcp = { context7: { type: "local", command: [], enabled: true } };
1288
- const nextOriginals = new Map(Object.entries(next.agent).map(([id, agent]) => [id, JSON.stringify(agent)]));
1289
- // The "no such agent" notice for `subagentTiers` waits for the first prompt-time check (see the prompt hook).
1290
- Object.defineProperty(next, DEFER_MISSING_SUBAGENT_NOTICE, { value: !promptChecked, enumerable: false });
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;
1989
+ try {
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);
2743
+ };
2744
+ // Plugin agents (#81) are protected like read-only tiers: readOnly ones and explicit-permission ones
2745
+ // (which start from `* deny`) both keep their own deny/ask rules against inherited session grants.
2746
+ // The config hook builds plugin agents in the v1 vocabulary (`bash`, `task`); the v2 host evaluates `shell`/`subagent`.
2747
+ const V2_ACTIONS: Readonly<Record<string, string>> = { bash: "shell", task: "subagent" };
2748
+ const v2Actions = (rules: ReturnType<typeof permissionRules>) => rules.map((rule) => ({ ...rule, action: V2_ACTIONS[rule.action] ?? rule.action }));
2749
+ const protectedAgent = (name: string | undefined) => name !== undefined
2750
+ && (config.agent[name]?.permission?.["*"] === "deny" || pluginAgentMarker(config.agent[name]) !== undefined);
2751
+ const agentLabel = (name: string | undefined): string => {
2752
+ const marker = name === undefined ? undefined : pluginAgentMarker(config.agent[name]);
2753
+ return marker !== undefined && !marker.readOnly ? "plugin agent" : "read-only agent";
2754
+ };
2755
+ // Host agents appear after setup (the host's config-agent plugin activates after the router). Names
2756
+ // the router created itself never count as host agents, or a tier would look like an existing one.
2757
+ const routerCreated = new Set<string>();
2758
+ let promptChecked = false;
2759
+ const pendingSubagentNames = (): string[] => {
2760
+ const routerConfig = loadConfig(ctx.location.directory);
2761
+ const tiers = getActiveTiers(routerConfig);
2762
+ return Object.keys(routerConfig.subagentTiers ?? {}).filter((name) =>
2763
+ !Object.hasOwn(tiers, name) && !Object.hasOwn(routerConfig.agents ?? {}, name) && !Object.hasOwn(baseSeed, name));
2764
+ };
2765
+ /** Adds host agents that appeared since setup to the seed; true when the seed grew. */
2766
+ const discoverHostAgents = async (): Promise<boolean> => {
2767
+ const pending = pendingSubagentNames();
2768
+ if (pending.length === 0) return false;
2769
+ let grew = false;
2770
+ for (const agent of (await ctx.agent.list()).data) {
2771
+ if (!pending.includes(agent.id) || routerCreated.has(agent.id) || Object.hasOwn(baseSeed, agent.id)) continue;
2772
+ baseSeed[agent.id] = {
2773
+ mode: agent.mode,
2774
+ model: agent.model && `${agent.model.providerID}/${agent.model.id}`,
2775
+ variant: agent.model?.variant,
2776
+ };
2777
+ grew = true;
2778
+ }
2779
+ return grew;
2780
+ };
2781
+ let lastConfig: unknown;
2782
+ // Returns the router config the registry state was built from; the caller
2783
+ // advances `lastConfig` only once the host registries have reloaded from it.
2784
+ const buildConfig = async (): Promise<unknown> => {
2785
+ const next: LegacyConfig = { agent: JSON.parse(JSON.stringify(baseSeed)), command: {} };
2786
+ const context7 = ctx.mcp && (await ctx.mcp.list()).data.some(server => server.name === "context7" && server.status.status !== "disabled");
2787
+ // Presence-only bridge input, never registered as an MCP definition.
2788
+ if (context7) next.mcp = { context7: { type: "local", command: [], enabled: true } };
2789
+ const nextOriginals = new Map(Object.entries(next.agent).map(([id, agent]) => [id, JSON.stringify(agent)]));
2790
+ // The "no such agent" notice for `subagentTiers` waits for the first prompt-time check (see the prompt hook).
2791
+ Object.defineProperty(next, DEFER_MISSING_SUBAGENT_NOTICE, { value: !promptChecked, enumerable: false });
1291
2792
  // Names in the setup seed are host built-in agents (not opencode.json entries the config hook can tell apart).
1292
2793
  Object.defineProperty(next, HOST_SEED_AGENTS, { value: new Set(Object.keys(baseSeed)), enumerable: false });
1293
2794
  await hooks.config?.(next);
@@ -1311,6 +2812,7 @@ export async function registerV2Hooks(
1311
2812
  }
1312
2813
  const registration = await registerRoleAgents(next.agent, routerConfig, {
1313
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
1314
2816
  ...(options.listRegistrationWorktrees ? { listWorktrees: options.listRegistrationWorktrees } : {}),
1315
2817
  });
1316
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
@@ -1458,7 +2960,15 @@ export async function registerV2Hooks(
1458
2960
  }));
1459
2961
 
1460
2962
  registrations.push(await ctx.command.transform((editor) => {
1461
- 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({
1462
2972
  name,
1463
2973
  description: definition.description,
1464
2974
  execute: async (invocation) => {
@@ -1518,6 +3028,9 @@ export async function registerV2Hooks(
1518
3028
  const directory = name.startsWith("router_git_")
1519
3029
  ? (await ctx.session.get({ sessionID: context.sessionID })).location?.directory ?? ctx.location.directory
1520
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));
1521
3034
  const result = await definition.execute(args, {
1522
3035
  sessionID: context.sessionID, messageID: context.messageID, agent: context.agent,
1523
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.
@@ -1541,6 +3054,18 @@ export async function registerV2Hooks(
1541
3054
 
1542
3055
  registrations.push(await ctx.session.hook("prompt", async (event) => {
1543
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
+ }
1544
3069
  const output = { message: { agent: session.agent }, parts: [{ type: "text", text: event.prompt.text }] };
1545
3070
  await legacy["chat.message"]?.({ sessionID: event.sessionID, agent: session.agent }, output);
1546
3071
  event.prompt.text = output.parts.map((part) => part.text).join("\n\n");
@@ -1554,8 +3079,168 @@ export async function registerV2Hooks(
1554
3079
  }
1555
3080
  }
1556
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
+ };
1557
3212
  /** The context hook's body (QA-P23-B5: declared before the hook that calls it). */
1558
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
+ }
1559
3244
  if (protectedAgent(event.agent)) {
1560
3245
  try {
1561
3246
  // Catalogs use merged session rules; remove widened tools from this
@@ -1620,7 +3305,7 @@ export async function registerV2Hooks(
1620
3305
  copies.push(part);
1621
3306
  original.set(part.text, copies);
1622
3307
  }
1623
- 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) };
1624
3309
  // The router pushes its own instructions, but may splice edited user text.
1625
3310
  // Only pushed text belongs to the router and may have its vocabulary translated.
1626
3311
  const added = new Set<string>();
@@ -1665,6 +3350,24 @@ export async function registerV2Hooks(
1665
3350
  }
1666
3351
  }
1667
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
+ }
1668
3371
  }
1669
3372
  // #90 P1.2 (A1): the TUI's `effortOf` rpc, answered from `effortStore`; tiers and roles mode alike. Feature-detected (a host
1670
3373
  // without `ctx.rpc.register` gets nothing), bounded (2 s; a late registration is kept), never throws; disposed with the other
@@ -1676,6 +3379,8 @@ export async function registerV2Hooks(
1676
3379
  // #84 P2.3 (P-3, I9): a role session's context hook never fails the child. ANY error below empties its catalog (the
1677
3380
  // strictest outcome) and is annotated for the parent's `subagent` result; every other agent keeps today's behaviour.
1678
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));
1679
3384
  try {
1680
3385
  await buildContext(event, role);
1681
3386
  } catch (error) {
@@ -1696,7 +3401,11 @@ export async function registerV2Hooks(
1696
3401
  }
1697
3402
  }));
1698
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).
1699
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));
1700
3409
  const args = await scopedArgs(event);
1701
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
1702
3411
  // `router_git_*` resolve the bound work root and the guard reads the dispatch budget. Tiers mode: no role table, no call.
@@ -1731,6 +3440,79 @@ export async function registerV2Hooks(
1731
3440
  }
1732
3441
  if (refusal !== undefined) throw refused(`[router] Refused for role agent ${callerRole} in this dispatch: ${refusal}`, callerRole);
1733
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
+ }
1734
3516
  // #84 P-5: a routed role dispatch runs in the foreground (separate from `verifying`).
1735
3517
  let roleForeground = false;
1736
3518
  if (event.tool === "subagent" && args && typeof args.agent === "string") {
@@ -1797,6 +3579,14 @@ export async function registerV2Hooks(
1797
3579
  // #84 P2.1-C: a fresh role dispatch carries its nonce at the END of the description (title marker, handoff 31).
1798
3580
  if (routed.description !== undefined) args.description = routed.description;
1799
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
+ }
1800
3590
  if (routed.agent !== undefined) { args.agent = routed.agent; args.subagent_type = routed.agent; }
1801
3591
  if (routed.model !== undefined) args.model = routed.model;
1802
3592
  if (args.model === undefined && tierModel !== undefined) args.model = tierModel;
@@ -1823,13 +3613,83 @@ export async function registerV2Hooks(
1823
3613
  const prompt = typeof original?.prompt === "string" ? original.prompt : typeof original?.description === "string" ? original.description : "";
1824
3614
  output.args.prompt = translateAdded(prompt, output.args.prompt);
1825
3615
  }
1826
- 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
+ }));
1827
3671
  } catch (error) {
1828
3672
  dispatchRouter.onCallFinished(event.id); // the hook chain rejected the call: it will never reach execute.after (2.2)
3673
+ inflight.cancel(event.id);
1829
3674
  throw error;
1830
3675
  }
1831
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).
1832
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
+ }
1833
3693
  }));
1834
3694
  /**
1835
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
@@ -1885,17 +3745,541 @@ export async function registerV2Hooks(
1885
3745
  rememberLastCall(child, end.id);
1886
3746
  if (!running) catalogFailures.delete(child); // P-3: the next attempt's catalog failure is annotated again
1887
3747
  }
1888
- 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);
1889
3751
  } catch (error) {
1890
3752
  ingestLogger.warn("[router] roles: the finished role dispatch could not be released", { error: String(error) });
1891
3753
  }
1892
3754
  },
1893
3755
  };
1894
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
+ }
1895
4190
  registrations.push(await ctx.tool.hook("execute.after", async (event) => {
1896
4191
  // 2.2: the result names the child. A dispatch still waiting for it is registered under it, and a heuristic claim that picked
1897
4192
  // the wrong child is corrected here, before the legacy hook below records the verdict. A call without a result is just dropped.
1898
- 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
+ }
1899
4283
  const role = event.tool === "subagent" ? await roleAfterCall({
1900
4284
  id: event.id, sessionID: String(event.sessionID), status: event.status,
1901
4285
  result: (event as { result?: unknown }).result, input: (event as { input?: unknown }).input,
@@ -1912,7 +4296,21 @@ export async function registerV2Hooks(
1912
4296
  const agent = roleAgentName(event.agent) ?? (typeof event.agent === "string" && event.agent !== "" ? undefined : knownRoleSession(String(event.sessionID)));
1913
4297
  if (agent !== undefined) options.recordRefusal?.(String(event.sessionID), agent, event.tool, (event as { input?: unknown }).input);
1914
4298
  }
1915
- 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
+ }
1916
4314
  if (event.tool === "grep" && protectedAgent(event.agent)) {
1917
4315
  const content = event.result.content;
1918
4316
  event.result = {
@@ -1935,12 +4333,32 @@ export async function registerV2Hooks(
1935
4333
  if (role !== undefined && event.tool === "subagent" && event.result.output?.status !== "running") {
1936
4334
  event.result = defangChildResult(event.result);
1937
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
+ }
1938
4355
  const structured = event.result.output;
1939
4356
  // A user can background a foreground subagent while it is running. That
1940
4357
  // acknowledgement is not a final result and must never enter acceptance.
1941
4358
  if (event.tool === "subagent" && structured?.status === "running") {
1942
4359
  const notices = [
1943
- ...(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."] : []),
1944
4362
  ...(banner === undefined ? [] : [banner]),
1945
4363
  ];
1946
4364
  if (!notices.length) return;
@@ -2009,6 +4427,10 @@ export async function registerV2Hooks(
2009
4427
  : structured && typeof structured === "object" && typeof structured.output === "string"
2010
4428
  ? { output: { ...structured, output: final } } : {}),
2011
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
+ }));
2012
4434
  } finally {
2013
4435
  role?.finish();
2014
4436
  if (event.tool === "subagent") forgetRoutedRole(event.id);
@@ -2017,8 +4439,31 @@ export async function registerV2Hooks(
2017
4439
 
2018
4440
  // V2 events are immutable facts. A completed-text warning is a synthetic
2019
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
+ };
2020
4465
  eventTask = (async () => {
2021
- for await (const event of ctx.event.subscribe({ signal: abort.signal })) {
4466
+ for await (const event of trackedEvents(ctx.event.subscribe({ signal: abort.signal }))) {
2022
4467
  if (abort.signal.aborted) break;
2023
4468
  try {
2024
4469
  const data = event.data as Record<string, any>;
@@ -2027,6 +4472,88 @@ export async function registerV2Hooks(
2027
4472
  if (HOST_TOOL_SUCCESS_EVENT.test(event.type) && data && Array.isArray(data.outputPaths)) {
2028
4473
  rememberOutputs(data.sessionID, data.outputPaths.filter((path: unknown): path is string => typeof path === "string"));
2029
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
+ }
2030
4557
  if (event.type === "session.step.ended" || event.type === "session.step.failed") {
2031
4558
  // Cost and tokens of a registered child dispatch (ingest ignores every other session).
2032
4559
  await ingesting(event.type, () => ingest.onStepEnded(event));
@@ -2047,6 +4574,20 @@ export async function registerV2Hooks(
2047
4574
  lastCallOfChild.delete(data.sessionID);
2048
4575
  hostBudget.forget(data.sessionID);
2049
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);
2050
4591
  }
2051
4592
  await ingesting("session.deleted", () => ingest.onSessionGone(data.sessionID));
2052
4593
  } else if (FLUSH_EVENT_TYPES.has(event.type)) {
@@ -2080,6 +4621,7 @@ export async function registerV2Hooks(
2080
4621
  })().catch((error: unknown) => {
2081
4622
  if (!abort.signal.aborted) console.warn("[model-router] OpenCode 2 event subscription failed", error);
2082
4623
  });
4624
+ Object.defineProperty(cleanup, V2_BACKGROUND_SETTLED, { value: settleBackground, enumerable: false });
2083
4625
  return cleanup;
2084
4626
  } catch (error) {
2085
4627
  await cleanup();