opencode-model-router 2.10.0 → 2.11.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 (47) hide show
  1. package/CHANGELOG.md +306 -0
  2. package/README.md +3 -2
  3. package/package.json +8 -1
  4. package/src/compat/background.ts +5 -0
  5. package/src/compat/session-lookup.ts +21 -0
  6. package/src/compat/v2-hooks.ts +256 -88
  7. package/src/compat/v2-observations.ts +1 -0
  8. package/src/compat/v2-vocabulary.ts +14 -0
  9. package/src/executor/create.ts +3 -0
  10. package/src/executor/git.ts +110 -26
  11. package/src/executor/integrate/checks.ts +29 -11
  12. package/src/executor/integrate/queue.ts +95 -13
  13. package/src/executor/ledger.ts +16 -12
  14. package/src/executor/lfs-restore.ts +492 -0
  15. package/src/executor/paths.ts +7 -2
  16. package/src/executor/recovery.ts +2 -1
  17. package/src/executor/runtime.ts +1010 -226
  18. package/src/executor/slots/pool.ts +120 -19
  19. package/src/executor/slots/provision.ts +111 -23
  20. package/src/executor/slots/root.ts +81 -0
  21. package/src/executor/types.ts +28 -2
  22. package/src/executor/unattended.ts +6 -1
  23. package/src/executor/verify-trees.ts +507 -0
  24. package/src/guard/enforce.ts +2 -1
  25. package/src/guard/fingerprint.ts +9 -0
  26. package/src/guard/guards.ts +7 -1
  27. package/src/index.ts +107 -27
  28. package/src/router/answer-dedup.ts +198 -0
  29. package/src/router/common-dir.ts +241 -0
  30. package/src/router/config.ts +71 -12
  31. package/src/router/diff-handles.ts +322 -0
  32. package/src/router/diff-summary.ts +318 -0
  33. package/src/router/git-metadata-guard.ts +144 -7
  34. package/src/router/git-tools.ts +930 -73
  35. package/src/router/role-agents.ts +100 -36
  36. package/src/router/run-summary.ts +253 -0
  37. package/src/router/run-tools.ts +145 -23
  38. package/src/router/sessions.ts +14 -1
  39. package/src/routing/classify/rules.ts +93 -14
  40. package/src/routing/wire/hint.ts +9 -2
  41. package/src/v2.ts +3 -1
  42. package/src/verify/exec.ts +454 -2
  43. package/src/verify/plan-task.ts +86 -26
  44. package/src/verify/runner.ts +14 -6
  45. package/src/verify/tree.ts +5 -1
  46. package/src/verify/types.ts +44 -0
  47. package/src/verify/wiring.ts +87 -10
@@ -70,6 +70,8 @@ import type { TimingRecorderHolder } from "../routing/outcomes/timings";
70
70
  import { createSideLogs, durationSeamsFor, nodePersistDeps, resolveOutcomesDir } from "../routing/outcomes/persist";
71
71
  import { homedir, tmpdir } from "node:os";
72
72
  import { installGitSearchFilter, nearestRepository, repositoryIdentity } from "../router/git-tools";
73
+ import { ANSWER_FORGET_EVENTS, disableAnswerDedup, forgetAnswers } from "../router/answer-dedup";
74
+ import { SESSION_INFO_LOOKUP_MS, sessionLookupWithin } from "./session-lookup";
73
75
  import { readFileSync } from "node:fs";
74
76
  import { fileURLToPath } from "node:url";
75
77
  import { resolveRouting } from "../router/config";
@@ -83,6 +85,7 @@ import type {
83
85
  RestoredDispatch, RestoredHold, RestoredHolds,
84
86
  } from "./background";
85
87
  import { PENDING_JOURNAL_VANISHED, pendingRecordIdentity } from "../verify/pending";
88
+ import { v2Instructions } from "./v2-vocabulary";
86
89
  import type { ExecutorRuntimeHandle, LeaseRegistryPort, PlanTaskVerifier } from "../executor/runtime";
87
90
  import type { LeaseRegistry } from "../router/leases";
88
91
  import type {
@@ -211,16 +214,8 @@ export function executorHostContext(history: unknown): HostSessionContext {
211
214
  return { messages, toolInFlight: historyToolInFlight(entries) };
212
215
  }
213
216
 
214
- /** Translate the router's own v1 tool vocabulary at the v2 boundary. */
215
- export function v2Instructions(text: string): string {
216
- return text
217
- .replace(/\bTask(?=\s*\()/g, "subagent")
218
- .replace(/\bTask (calls?|tool)\b/g, "subagent $1")
219
- .replace(/\btask tool\b/g, "subagent tool")
220
- .replace(/`task`/g, "`subagent`")
221
- .replace(/\bsubagent_type\b/g, "agent")
222
- .replace(/\btask_id\b/g, "sessionID");
223
- }
217
+ /** Translate the router's own v1 tool vocabulary at the v2 boundary (src/compat/v2-vocabulary.ts, shared with the finish API). */
218
+ export { v2Instructions };
224
219
 
225
220
  type LegacyAgent = Record<string, any>;
226
221
  type LegacyConfig = { agent: Record<string, LegacyAgent>; command: Record<string, any>; mcp?: Parameters<NonNullable<Hooks["config"]>>[0]["mcp"] };
@@ -984,26 +979,20 @@ type ChildEndState =
984
979
  * 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.
985
980
  */
986
981
  export const SESSION_DIR_NEGATIVE_TTL_MS = 2_000;
987
- /**
988
- * #161: how long the shared session record (`sessionInfoOf`: the directory, parent and agent the role checks, the file leases and
989
- * the stale-resume check read) waits for the host's `session.get`; past it the lookup counts as failed. Long on purpose, above
990
- * background.ts's 5 s LOOKUP_TIMEOUT_MS: a miss refuses a role agent's call, so a slow but healthy host must not cause one.
991
- */
992
- export const SESSION_INFO_LOOKUP_MS = 10_000;
982
+ /** #161: SESSION_INFO_LOOKUP_MS and `sessionLookupWithin` live in a leaf module, so index.ts bounds its v2 lookups without this one. */
983
+ export { SESSION_INFO_LOOKUP_MS };
993
984
  /**
994
985
  * #161: how long a tool call waits for the session's current location (its one fresh `session.get`, shared by `scopedArgs` and
995
986
  * the git metadata guard). Short: a miss falls back to the session record's directory.
996
987
  */
997
988
  export const CALL_DIRECTORY_LOOKUP_MS = 2_000;
998
- /** #161: `lookup`'s answer, or a rejection once `ms` pass without one (the host call itself is left running). */
999
- function sessionLookupWithin<T>(lookup: PromiseLike<T>, ms: number): Promise<T> {
1000
- let timer: ReturnType<typeof setTimeout> | undefined;
1001
- const timeout = new Promise<never>((_resolve, reject) => {
1002
- timer = setTimeout(() => reject(new Error(`session lookup timed out after ${ms} ms`)), ms);
1003
- if (typeof timer === "object" && typeof timer.unref === "function") timer.unref();
1004
- });
1005
- return Promise.race([lookup, timeout]).finally(() => clearTimeout(timer));
1006
- }
989
+ /**
990
+ * #161: how long `execute.after` may still take the directory its call's `execute.before` used. Long: a write can wait on a
991
+ * permission prompt that long; past it (or once the store's bound drops the entry) the after-hook looks the directory up itself.
992
+ */
993
+ export const CALL_DIRECTORY_STORE_TTL_MS = 60 * 60_000;
994
+ /** #161: calls whose before-hook directory is kept for their `execute.after` (oldest first out). */
995
+ const MAX_CALL_DIRECTORIES = 1000;
1007
996
  /**
1008
997
  * QA-2.1-25: a failed session-kind lookup is not repeated for this long. Short on purpose: the failure answers `unknown` (root
1009
998
  * 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.
@@ -1040,6 +1029,24 @@ export const PENDING_RELOAD_RETRY_MS = 30_000;
1040
1029
  const BACKGROUND_DRAIN_MS = 5_000;
1041
1030
  /** Host-facing executor wait: allow the runtime's 10 s per-plan queue bound plus runtime/pool teardown headroom. */
1042
1031
  const EXECUTOR_DISPOSE_MS = 30_000;
1032
+ /**
1033
+ * #190 (QA-5.1-29): the `/plan` description each live router copy of this process registered, keyed by copy. A hot reload
1034
+ * starts the new copy while the old one still has its `/plan` registered; that `/plan` is the router's own, never a user
1035
+ * command. Process-wide (every module copy shares it) under a versioned registry key; a copy's entry goes at its cleanup.
1036
+ */
1037
+ const ROUTER_PLAN_COMMANDS_KEY = Symbol.for("opencode-model-router.v2.router-plan-commands@1");
1038
+ function routerPlanCommands(): Map<object, string> {
1039
+ const existing: unknown = Reflect.get(globalThis, ROUTER_PLAN_COMMANDS_KEY);
1040
+ if (existing instanceof Map) return existing;
1041
+ const created = new Map<object, string>();
1042
+ Reflect.set(globalThis, ROUTER_PLAN_COMMANDS_KEY, created);
1043
+ return created;
1044
+ }
1045
+ /** QA-5.1-29: whether a listed host command is a `/plan` some live router copy of this process registered. */
1046
+ function isRouterPlanCommand(command: unknown): boolean {
1047
+ const description: unknown = typeof command === "object" && command !== null ? Reflect.get(command, "description") : undefined;
1048
+ return typeof description === "string" && [...routerPlanCommands().values()].includes(description);
1049
+ }
1043
1050
  /**
1044
1051
  * Non-enumerable slot on the cleanup function `registerV2Hooks` returns: `() => Promise<void>` that resolves once no background
1045
1052
  * work is in flight (verdict posts, recoveries, reloads, including work they start). Lets integration tests await what an
@@ -1144,7 +1151,8 @@ export interface V2ExecutorHost {
1144
1151
  /**
1145
1152
  * QA-5.1-26: hands the adapter an executor assembled after the factory returned (a claim handover). The adapter adopts it
1146
1153
  * through the path it adopts the factory's executor by (its providers and hooks, `start()`, the W7 dispose) and answers
1147
- * true. False: not adopted (the adapter is disposing, or it already holds another executor); the caller disposes it.
1154
+ * true. False: not adopted (the adapter is disposing, it already holds another executor, or the wiring failed and was
1155
+ * undone, QA-5.1-32); the caller disposes it.
1148
1156
  */
1149
1157
  onExecutor(built: V2Executor): boolean;
1150
1158
  }
@@ -1434,11 +1442,14 @@ export async function registerV2Hooks(
1434
1442
  if (sessionID !== "" && sessionKinds.get(sessionID) !== "root") {
1435
1443
  let check = planChildChecks.get(sessionID);
1436
1444
  if (check === undefined) {
1437
- /** True when a verdict was reached; false when the first message could not be read. */
1445
+ /**
1446
+ * True when a verdict was reached; false when the first message could not be read. #161: a host that has not answered
1447
+ * within SESSION_INFO_LOOKUP_MS (the bound of the other session reads a tool call waits for) has not been read either.
1448
+ */
1438
1449
  const verdict = (async (): Promise<boolean> => {
1439
1450
  let firstText: string | undefined;
1440
1451
  try {
1441
- firstText = firstMessageText(await ctx.session.context({ sessionID } as Parameters<typeof ctx.session.context>[0]));
1452
+ firstText = firstMessageText(await sessionLookupWithin(ctx.session.context({ sessionID } as Parameters<typeof ctx.session.context>[0]), SESSION_INFO_LOOKUP_MS));
1442
1453
  } catch {
1443
1454
  firstText = undefined;
1444
1455
  }
@@ -1554,18 +1565,22 @@ export async function registerV2Hooks(
1554
1565
  if (takeRoleBindingLookupNotice()) ingestLogger.warn(message, extra);
1555
1566
  else console.debug(message, extra);
1556
1567
  };
1557
- /** Handoff 32: what the binding reads of a child session (parent, agent, title, first message text). */
1568
+ /**
1569
+ * Handoff 32: what the binding reads of a child session (parent, agent, title, first message text). #161: each host call gives up
1570
+ * after SESSION_INFO_LOOKUP_MS, as the session record does (a miss refuses a role agent's call, so a slow but healthy host must
1571
+ * not cause one), and then counts as failed: the session's as lookupFailed, the first message's as no text.
1572
+ */
1558
1573
  const bindingLookup: SessionLookup = async (id) => {
1559
1574
  let session: Record<string, unknown>;
1560
1575
  try {
1561
- session = await ctx.session.get({ sessionID: id } as Parameters<typeof ctx.session.get>[0]) as unknown as Record<string, unknown>;
1576
+ session = await sessionLookupWithin(ctx.session.get({ sessionID: id } as Parameters<typeof ctx.session.get>[0]), SESSION_INFO_LOOKUP_MS) as unknown as Record<string, unknown>;
1562
1577
  } catch (error) {
1563
1578
  warnBindingLookup("[router] roles: a binding session could not be read", id, error);
1564
1579
  throw error; // bind treats this as lookupFailed, without caching it
1565
1580
  }
1566
1581
  let firstText: string | undefined;
1567
1582
  try {
1568
- firstText = firstMessageText(await ctx.session.context({ sessionID: id } as Parameters<typeof ctx.session.context>[0]));
1583
+ firstText = firstMessageText(await sessionLookupWithin(ctx.session.context({ sessionID: id } as Parameters<typeof ctx.session.context>[0]), SESSION_INFO_LOOKUP_MS));
1569
1584
  } catch (error) {
1570
1585
  warnBindingLookup("[router] roles: a child's first message could not be read", id, error);
1571
1586
  firstText = undefined; // the title marker still binds
@@ -1731,6 +1746,29 @@ export async function registerV2Hooks(
1731
1746
  return { known: false, error: failure };
1732
1747
  }
1733
1748
  };
1749
+ /**
1750
+ * #161: per tool call (its id), the known directory its `execute.before` used ({@link callDirectoryOf}), so its `execute.after`
1751
+ * resolves the call's paths (the changed-file record, the trajectory, the guard's after-call) against that same answer instead
1752
+ * of a lookup of its own, which can fail and skip that bookkeeping, or see a session moved since. Taken once; bounded
1753
+ * (MAX_CALL_DIRECTORIES, oldest first out), ignored past CALL_DIRECTORY_STORE_TTL_MS, and forgotten with the session.
1754
+ */
1755
+ const callDirectories = new Map<string, { readonly at: number; readonly sessionID: string; readonly found: CallDirectory }>();
1756
+ const rememberCallDirectory = (callID: string, sessionID: string, found: CallDirectory): void => {
1757
+ if (!found.known || callID === "") return; // an unknown directory: the after-hook tries its own lookup, as before
1758
+ callDirectories.delete(callID);
1759
+ callDirectories.set(callID, { at: Date.now(), sessionID, found });
1760
+ while (callDirectories.size > MAX_CALL_DIRECTORIES) callDirectories.delete(callDirectories.keys().next().value!);
1761
+ };
1762
+ /** Takes (and drops) the entry of `callID`; undefined when there is none, it expired, or another session stored it. */
1763
+ const takeCallDirectory = (callID: string, sessionID: string): CallDirectory | undefined => {
1764
+ const stored = callDirectories.get(callID);
1765
+ callDirectories.delete(callID);
1766
+ if (stored === undefined || stored.sessionID !== sessionID) return undefined;
1767
+ return Date.now() - stored.at >= CALL_DIRECTORY_STORE_TTL_MS ? undefined : stored.found;
1768
+ };
1769
+ const forgetCallDirectories = (sessionID: string): void => {
1770
+ for (const [callID, stored] of callDirectories) if (stored.sessionID === sessionID) callDirectories.delete(callID);
1771
+ };
1734
1772
  /**
1735
1773
  * 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
1736
1774
  * orchestrator's working set (the session that dispatched it: its dispatch record, else the session's parent) and the
@@ -1898,6 +1936,10 @@ export async function registerV2Hooks(
1898
1936
  });
1899
1937
  let eventTask: Promise<void> | undefined;
1900
1938
  let disposed = false;
1939
+ /** QA-5.1-29: this copy's key in the process-wide `/plan` registry (`routerPlanCommands`). */
1940
+ const routerPlanOwner = {};
1941
+ /** QA-5.1-29: set once cleanup removed this copy's command registration and its registry entry. */
1942
+ let routerPlanReleased = false;
1901
1943
  const within = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
1902
1944
  runtime ? runtime.withToolContext(context, operation) : operation();
1903
1945
  /** QA-PDF12-7: a context rebuilt from journaled data runs its operation but never becomes the parent's retained context. */
@@ -2016,7 +2058,8 @@ export async function registerV2Hooks(
2016
2058
  };
2017
2059
  // ---------------------------------------------------------------------------------------------------------------------
2018
2060
  // Phase 2.1 startup (memo §4.1). Everything below is v2-only (this module is loaded by server.ts alone) and inert under
2019
- // `routing.background.mode: "off"` + `routing.leases.mode: "off"` except the timing rows (telemetry, not visible to the user).
2061
+ // `routing.background.mode: "off"` + `routing.leases.mode: "off"` except the timing rows (telemetry, not visible to the user)
2062
+ // and, #191, the hold and verification of a verifying call the host runs in the background anyway (OpenCode 2.3+).
2020
2063
  // ---------------------------------------------------------------------------------------------------------------------
2021
2064
  const startRouting = resolveRouting(loadConfig(ctx.location.directory), "v2", ingestLogger);
2022
2065
  const outcomesDir = resolveOutcomesDir(startRouting.outcomes.path, { tmpdir: tmpdir(), homedir: homedir() });
@@ -2099,9 +2142,10 @@ export async function registerV2Hooks(
2099
2142
  /**
2100
2143
  * The kind of a session WITHOUT a host call (`session.created` and the `prompt` hook record it): an unknown session is a root,
2101
2144
  * 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),
2102
- * with one exception: DF-1-9 / QA-DF1-23, never for the background decision — while background routing is active
2103
- * (`bgActive()`), an unrecorded parent is resolved once with `dispatchSessionKindOf` (one `session.get`, bounded by
2104
- * SESSION_KIND_DISPATCH_TIMEOUT_MS, cached once answered; `unknown` is no root).
2145
+ * with one exception: DF-1-9 / QA-DF1-23, never for the background decision — for a call the background path tracks
2146
+ * (`bgActive()`; under `off` only a verifying call, #191), an unrecorded parent is resolved once with
2147
+ * `dispatchSessionKindOf` (one `session.get`, bounded by SESSION_KIND_DISPATCH_TIMEOUT_MS, cached once answered; `unknown`
2148
+ * is no root).
2105
2149
  */
2106
2150
  const knownKindOf = (sessionID: string): "root" | "child" => sessionKinds.get(sessionID) ?? "root";
2107
2151
  /** The in-flight registry and held results exist whatever the mode; they hold nothing until a background dispatch is acknowledged. */
@@ -2240,26 +2284,37 @@ export async function registerV2Hooks(
2240
2284
  /**
2241
2285
  * #174: the children of the `subagent` calls this adapter's tool hooks saw (orchestrator and role dispatches, in every mode).
2242
2286
  * The runner's own native calls reach no tool hook, so a child in here is never given the runner-description fallback above.
2243
- * Bounded, oldest first out.
2287
+ * Child -> the session whose call dispatched it (#191, the latest). Bounded, oldest first out.
2244
2288
  */
2245
- const dispatchedChildren = new Set<string>();
2246
- const noteDispatchedChild = (child: string): void => {
2289
+ const dispatchedChildren = new Map<string, string>();
2290
+ const noteDispatchedChild = (parent: string, child: string): void => {
2247
2291
  dispatchedChildren.delete(child);
2248
- dispatchedChildren.add(child);
2249
- for (const old of dispatchedChildren) {
2292
+ dispatchedChildren.set(child, parent);
2293
+ for (const old of dispatchedChildren.keys()) {
2250
2294
  if (dispatchedChildren.size <= MAX_DISPATCHED_CHILDREN) break;
2251
2295
  dispatchedChildren.delete(old);
2252
2296
  }
2253
2297
  };
2298
+ /**
2299
+ * #191: under `off` a child this process dispatched from `session` without tracking it (no verification and no role, so never
2300
+ * held) can never be a held result of that session. The fail-closed state of a journal that is not reloaded (memo §12) neither
2301
+ * withholds its report from that session nor refuses that session's resume of it; a child another session dispatched, or one
2302
+ * this process never dispatched (a previous process's), is still withheld and refused.
2303
+ */
2304
+ const untrackedUnderOff = (session: string, child: string): boolean =>
2305
+ bgMode === "off" && dispatchedChildren.get(child) === session && inflight.byChild(child) === undefined;
2254
2306
  /** The held store, for the compaction hook registered before it exists. */
2255
2307
  let heldRef: HeldResults | undefined;
2256
2308
  /**
2257
- * Memo §4.4 step 5: the compaction hook runs the same matcher over the messages being summarised (C15) when mode ≠ off.
2309
+ * Memo §4.4 step 5: the compaction hook runs the same matcher over the messages being summarised (C15).
2258
2310
  * #174: it is registered in every mode, for the runner-child rewrite the context hook also makes in every mode.
2311
+ * #191: the matcher runs in every mode too: under `off` a verifying call the host backgrounds anyway is held.
2259
2312
  */
2260
2313
  let compactionRegistered = false;
2261
2314
  try {
2262
2315
  registrations.push(await ctx.session.hook("compaction", async (event) => {
2316
+ // #108 slice 4: the summary drops the answers a stub would point back to, so the session's deduplicated answers go too.
2317
+ forgetAnswers(String(event.sessionID));
2263
2318
  const messages = event.messages;
2264
2319
  if (!Array.isArray(messages)) return;
2265
2320
  /** `rewrite` over the text parts of the messages being summarised; a changed message is replaced by a copy. */
@@ -2280,12 +2335,15 @@ export async function registerV2Hooks(
2280
2335
  if (touched) messages[index] = Object.assign(Object.create(Object.getPrototypeOf(source)), source, { content: next });
2281
2336
  });
2282
2337
  };
2283
- if (bgMode !== "off" && heldRef !== undefined) {
2338
+ // #191: in every mode (without the finish API the adoption, the redaction and the matcher have nothing to act on).
2339
+ if (heldRef !== undefined) {
2284
2340
  adoptSession(String(event.sessionID));
2285
2341
  if (finishApi !== undefined && reloadFailed) {
2286
2342
  // QA-2.1-8: fail closed exactly like the context hook (memo §12): a summary must not carry a completion this process
2287
- // cannot prove processed while the journal is not reloaded.
2343
+ // cannot prove processed while the journal is not reloaded. #191: an untracked child under `off` is never held.
2344
+ const summarised = String(event.sessionID);
2288
2345
  const isProcessed = (child: string): boolean => {
2346
+ if (untrackedUnderOff(summarised, child)) return true;
2289
2347
  const attempt = inflight.byChild(child);
2290
2348
  return attempt !== undefined && journal.hasProcessed(attempt.key);
2291
2349
  };
@@ -2302,10 +2360,13 @@ export async function registerV2Hooks(
2302
2360
  // #174: a summary never carries the raw text of one of the router's own children (the same lookup and line as the context hook).
2303
2361
  rewriteTexts((text) => rewriteRunnerChildReports(text, isRunnerReport));
2304
2362
  }));
2305
- compactionRegistered = bgMode !== "off";
2363
+ compactionRegistered = true;
2306
2364
  } catch (error) {
2307
- // Under `off` nothing depends on it but the #174 rewrite of summaries; as before #174, a failure there is not logged.
2308
- if (bgMode !== "off") ingestLogger.warn("[router] background: the compaction hook could not be registered; held results are unavailable", { error: String(error) });
2365
+ // #108 slice 4: without the hook a compaction would not clear the deduplicated answers, so a stub could name an answer the
2366
+ // summary dropped: dedup is off for this process (logged once, in every mode).
2367
+ if (disableAnswerDedup()) ingestLogger.warn("[router] answer dedup is off: the compaction hook could not be registered; every answer is given in full", { error: String(error) });
2368
+ // #191: held results depend on it in every mode (under `off`, for a verifying call the host backgrounds anyway).
2369
+ ingestLogger.warn("[router] background: the compaction hook could not be registered; held results are unavailable", { error: String(error) });
2309
2370
  }
2310
2371
  const held: HeldResults = createHeldResults({
2311
2372
  observations: options.observations,
@@ -2313,7 +2374,7 @@ export async function registerV2Hooks(
2313
2374
  journal, available: syntheticOk && compactionRegistered, logger: ingestLogger,
2314
2375
  });
2315
2376
  heldRef = held;
2316
- /** The legacy plugin's finish API (2.1.4). Absent (or `off`): no background processing, the guarantees behave as `off`. */
2377
+ /** The legacy plugin's finish API (2.1.4), attached in every mode (#191). Absent: no background processing at all. */
2317
2378
  let finishApi: FinishApi | undefined;
2318
2379
  /**
2319
2380
  * Memo §12: the journal reload failed or timed out, or the journal vanished under this process (QA-2.1-8). Holding is off,
@@ -2474,8 +2535,14 @@ export async function registerV2Hooks(
2474
2535
  const restoredDispatches = new Map<string, RestoredDispatch>();
2475
2536
  /** QA-2.1-29: restored holds of sessions adopted before the processor existed, waiting for the start-up recovery. */
2476
2537
  const deferredRestores = new Map<string, RestoredHolds>();
2477
- /** Background guarantees apply: mode ≠ off AND the finish API attached. Otherwise every code path below behaves as `off`. */
2478
- const bgActive = (): boolean => bgMode !== "off" && finishApi !== undefined;
2538
+ /**
2539
+ * Background guarantees apply: the finish API attached. Otherwise no call is tracked and nothing is held or processed.
2540
+ * #191: in every mode, because OpenCode 2.3+ runs every native child in the background whatever `background` says. Under
2541
+ * `off` the router never asks for the background and tracks only verifying and role-routed calls (`execute.before`), so a
2542
+ * verifying call the host backgrounds anyway is held and verified like one `auto` did not select, and a role call keeps its
2543
+ * binding and notices; every other call stays untracked (`untrackedUnderOff`).
2544
+ */
2545
+ const bgActive = (): boolean => finishApi !== undefined;
2479
2546
  /** `router_run` contamination notes from `execute.before`, appended in `execute.after` (bounded). */
2480
2547
  const runNotes = new Map<string, string>();
2481
2548
  /** 1.3: the process-wide lease registry and the guard over it (every v2 child; roots take none). */
@@ -2549,7 +2616,9 @@ export async function registerV2Hooks(
2549
2616
  }
2550
2617
  // Memo §4.1 steps 3-4: the finish API is attached once (with the lease gate when leases are enforced), then the pending journal
2551
2618
  // is reloaded, AWAITED with a 5 s bound before the context hook registers. A failure falls back to fail-closed redaction (§12).
2552
- if (bgMode !== "off") {
2619
+ // #191: attached in every mode, so a verifying call the host backgrounds under `off` is still verified. Under `off` only a
2620
+ // held gate waits for the lease gate (`leaseGateScope: "held"`): a foreground check (OpenCode 2.0.x) keeps its timing and result.
2621
+ {
2553
2622
  const attachFinish = (hooks as unknown as Record<PropertyKey, unknown>)[ROUTER_FINISH_ATTACH];
2554
2623
  if (typeof attachFinish === "function") {
2555
2624
  try {
@@ -2562,7 +2631,10 @@ export async function registerV2Hooks(
2562
2631
  return posting;
2563
2632
  },
2564
2633
  };
2565
- finishApi = (attachFinish as FinishAttach)({ host: "v2", held: trackedHeld, ...(leaseGuard === undefined ? {} : { leaseGate: leaseGuard }) });
2634
+ finishApi = (attachFinish as FinishAttach)({
2635
+ host: "v2", held: trackedHeld,
2636
+ ...(leaseGuard === undefined ? {} : { leaseGate: leaseGuard, ...(bgMode === "off" ? { leaseGateScope: "held" as const } : {}) }),
2637
+ });
2566
2638
  // QA-2.1-33: a recreation of the shared journal by another plugin instance of this process writes these records too.
2567
2639
  finishApi?.setAdapterSnapshot?.(adapterRecords);
2568
2640
  } catch (error) {
@@ -2804,6 +2876,10 @@ export async function registerV2Hooks(
2804
2876
  await engine.dispose();
2805
2877
  await eventTask;
2806
2878
  await Promise.allSettled(registrations.map((registration) => registration.dispose()));
2879
+ // QA-5.1-29: only now is this copy's `/plan` gone from the host; a copy starting while this one disposes still sees it
2880
+ // as the router's. `routerPlanReleased`: a late call of the disposed transform never records it again.
2881
+ routerPlanReleased = true;
2882
+ routerPlanCommands().delete(routerPlanOwner);
2807
2883
  await hooks.dispose?.();
2808
2884
  };
2809
2885
 
@@ -2812,7 +2888,9 @@ export async function registerV2Hooks(
2812
2888
  // router-modified agents, which would defeat the originals diff on refresh.
2813
2889
  const agents = await ctx.agent.list();
2814
2890
  // The legacy config bridge has no host commands. Capture the real registry before our transform owns /plan.
2815
- const userPlanCommandDefined = (await ctx.command.list?.())?.data.some((command) => command.name === "plan") ?? false;
2891
+ // QA-5.1-29: a `/plan` a live router copy registered (the old copy of a hot reload) is not a user command.
2892
+ const userPlanCommandDefined = (await ctx.command.list?.())?.data
2893
+ .some((command) => command.name === "plan" && !isRouterPlanCommand(command)) ?? false;
2816
2894
  let warnedPlanCommand = false;
2817
2895
  const baseSeed: Record<string, LegacyAgent> = {};
2818
2896
  for (const agent of agents.data) baseSeed[agent.id] = {
@@ -3063,6 +3141,12 @@ export async function registerV2Hooks(
3063
3141
  }
3064
3142
  return false;
3065
3143
  });
3144
+ // QA-5.1-29: this copy's `/plan`, so a hot-reload copy that lists the commands meanwhile does not take it for a user's.
3145
+ const planDescription = commands.find(([name]) => name === "plan")?.[1].description;
3146
+ if (!routerPlanReleased && typeof planDescription === "string" && planDescription !== "") {
3147
+ routerPlanCommands().set(routerPlanOwner, planDescription);
3148
+ }
3149
+ else routerPlanCommands().delete(routerPlanOwner);
3066
3150
  for (const [name, definition] of commands) editor.add({
3067
3151
  name,
3068
3152
  description: definition.description,
@@ -3206,6 +3290,13 @@ export async function registerV2Hooks(
3206
3290
  /** Auto/model: `[router` line starts in every completion element body (either envelope) are defanged (parity with `defangChildResult`). */
3207
3291
  const defangMessages = (messages: readonly ContextMessage[]): ContextMessage[] | undefined =>
3208
3292
  rewriteTextParts(messages, (text) => defangSubagentBodies(text, defangRouterLines));
3293
+ /**
3294
+ * #191, `off`: only the completion element bodies of role children (their tracked attempt names a role) are defanged, as the
3295
+ * foreground path defangs a role child's result (`defangChildResult`); every other report stays as the host sent it.
3296
+ */
3297
+ const defangRoleMessages = (messages: readonly ContextMessage[]): ContextMessage[] | undefined =>
3298
+ rewriteTextParts(messages, (text) => rewriteChildReportBodies(text, (report) =>
3299
+ inflight.byChild(report.child)?.role === undefined ? undefined : defangRouterLines(report.body)));
3209
3300
  /**
3210
3301
  * #174: since OpenCode 2.3.0 the host reports every finished child to its parent, the router's own children too: their raw
3211
3302
  * text (a grader's JSON, a producer's answer) is not for the orchestrator. Their element bodies become one neutral line in
@@ -3272,8 +3363,9 @@ export async function registerV2Hooks(
3272
3363
  const attempt = inflight.byChild(element.child);
3273
3364
  if (attempt === undefined || attempt.parentSessionID !== sid) {
3274
3365
  // #174: the host reports the router's own children too (nothing to process, nothing to say); any other child is
3275
- // warned about once, not on every request whose history still holds its element.
3276
- if (!isRunnerReport(element) && !warnedCompletionChildren.has(element.child)) {
3366
+ // warned about once, not on every request whose history still holds its element. #191: under `off` only verifying
3367
+ // calls are tracked, so a report of any other dispatch is expected and never warned about.
3368
+ if (bgMode !== "off" && !isRunnerReport(element) && !warnedCompletionChildren.has(element.child)) {
3277
3369
  warnedCompletionChildren.add(element.child);
3278
3370
  for (const old of warnedCompletionChildren) {
3279
3371
  if (warnedCompletionChildren.size <= MAX_WARNED_COMPLETION_CHILDREN) break;
@@ -3334,14 +3426,17 @@ export async function registerV2Hooks(
3334
3426
  /** The context hook's body (QA-P23-B5: declared before the hook that calls it). */
3335
3427
  async function buildContext(event: SessionContext, role: string | undefined): Promise<void> {
3336
3428
  // Phase 2.1 (memo §4.4 step 1-2): FIRST, before `chat.params` and before the augmenter reads `event.messages`: no held output
3337
- // reaches the request, and (auto/model) child text cannot pose as a router line. Mode `off`: no matcher, no defang.
3429
+ // reaches the request, and (auto/model) child text cannot pose as a router line. Mode `off`: the matcher (#191), and the
3430
+ // defang of role children's reports only.
3338
3431
  const rawMessages = event.messages;
3339
3432
  if (bgActive() && event.messages !== undefined) {
3340
3433
  const sid = String(event.sessionID);
3341
3434
  adoptSession(sid);
3342
3435
  if (reloadFailed) {
3343
3436
  // Memo §12: without a reloaded journal every completion not known as processed is redacted (fail closed).
3437
+ // #191: an untracked child this session dispatched under `off` is never held, so its report is not withheld.
3344
3438
  const isProcessed = (child: string): boolean => {
3439
+ if (untrackedUnderOff(sid, child)) return true;
3345
3440
  const attempt = inflight.byChild(child);
3346
3441
  return attempt !== undefined && journal.hasProcessed(attempt.key);
3347
3442
  };
@@ -3360,7 +3455,7 @@ export async function registerV2Hooks(
3360
3455
  }
3361
3456
  const hidden = applyHeldTo(sid, event.messages);
3362
3457
  if (hidden !== undefined) event.messages = hidden;
3363
- const defanged = defangMessages(event.messages);
3458
+ const defanged = bgMode === "off" ? defangRoleMessages(event.messages) : defangMessages(event.messages);
3364
3459
  if (defanged !== undefined) event.messages = defanged;
3365
3460
  }
3366
3461
  // #174: in every mode, after the defang (its neutral line is the router's own). `rawMessages` keeps the original for the scan.
@@ -3538,12 +3633,17 @@ export async function registerV2Hooks(
3538
3633
  sessionID: event.sessionID, tool: event.tool,
3539
3634
  input: handed !== null && typeof handed === "object" && !Array.isArray(handed) ? { ...(handed as Record<string, unknown>) } : handed,
3540
3635
  };
3636
+ const callID = typeof event.id === "string" ? event.id : "";
3541
3637
  // 3.1.7 M41 (always on): a plan child without its plan binding is refused every tool call (fail closed). The context hook
3542
3638
  // checks a session's first user message; a first tool call that comes before that hook performs the same check here.
3543
3639
  await planChildGuard.assertToolAllowed(String(event.sessionID));
3544
- // #161: one session-directory answer per call, taken when first needed: `scopedArgs` and the git metadata guard below share it.
3640
+ // #161: one session-directory answer per call, taken when first needed: `scopedArgs` and the git metadata guard below share it,
3641
+ // and the call's `execute.after` takes it too (a known one).
3545
3642
  let callDirectory: Promise<CallDirectory> | undefined;
3546
- const directoryOfCall = (): Promise<CallDirectory> => (callDirectory ??= callDirectoryOf(String(call.sessionID)));
3643
+ const directoryOfCall = (): Promise<CallDirectory> => (callDirectory ??= callDirectoryOf(String(call.sessionID)).then((found) => {
3644
+ rememberCallDirectory(callID, String(call.sessionID), found);
3645
+ return found;
3646
+ }));
3547
3647
  const args = await scopedArgs(call, directoryOfCall);
3548
3648
  // #84 P2.1 (P-2, handoffs 11/32/33): a role child binds to its dispatch before its tool runs, so `router_run` and
3549
3649
  // `router_git_*` resolve the bound work root and the guard reads the dispatch budget. Tiers mode: no role table, no call.
@@ -3561,6 +3661,7 @@ export async function registerV2Hooks(
3561
3661
  // QA-G-A3-2: a refusal here is thrown before the legacy hook (and its guard) sees the call: the plugin counts it on the
3562
3662
  // child's guard state, and the guard's stop (denied_cap) or advisory banner is added to the refusal the child sees.
3563
3663
  const refused = (message: string, agent: string | undefined): Error => {
3664
+ takeCallDirectory(callID, String(call.sessionID)); // #161: a refused call never reaches execute.after
3564
3665
  const guard = options.recordRefusal?.(String(event.sessionID), agent, call.tool, args);
3565
3666
  return new Error(guard === undefined ? message : `${message}\n${guard}`);
3566
3667
  };
@@ -3595,7 +3696,10 @@ export async function registerV2Hooks(
3595
3696
  // QA-2.1-16: the refusal promises a retry; each refused attempt starts one (bounded by PENDING_RELOAD_RETRY_MS).
3596
3697
  retryReload();
3597
3698
  for (const target of resumeTargetsOf(event.tool, heldArgs, String(event.sessionID))) {
3598
- if (inflight.byChild(target) === undefined) throw refused(reloadFailedResumeText(target), callerRole);
3699
+ // #191: an untracked child this session dispatched under `off` was never held; its resume is not refused.
3700
+ if (inflight.byChild(target) === undefined && !untrackedUnderOff(String(event.sessionID), target)) {
3701
+ throw refused(reloadFailedResumeText(target), callerRole);
3702
+ }
3599
3703
  }
3600
3704
  }
3601
3705
  }
@@ -3633,7 +3737,9 @@ export async function registerV2Hooks(
3633
3737
  if (cached?.plan !== undefined) continue;
3634
3738
  if (cached === undefined) {
3635
3739
  // A restarted plan child may have lost its binding too; its launcher protocol belongs to the executor.
3636
- const first = withoutHostPreamble(firstMessageText(await ctx.session.context({ sessionID: child } as Parameters<typeof ctx.session.context>[0])) ?? "");
3740
+ // #161: a host that has not answered within SESSION_INFO_LOOKUP_MS is a target that could not be checked (below).
3741
+ const context = ctx.session.context({ sessionID: child } as Parameters<typeof ctx.session.context>[0]);
3742
+ const first = withoutHostPreamble(firstMessageText(await sessionLookupWithin(context, SESSION_INFO_LOOKUP_MS)) ?? "");
3637
3743
  if (first.startsWith(PLAN_CONTEXT_PREFIX) || LAUNCH_HEADER_PATTERN.test(first)) continue;
3638
3744
  }
3639
3745
  const binding = cached ?? await bind(child, bindingLookup, { maxOf: maxOfRoles(callerRoles) });
@@ -3646,6 +3752,7 @@ export async function registerV2Hooks(
3646
3752
  if (recordRoleOrphan(child, "refused")) ingestLogger.warn(message);
3647
3753
  else console.debug(message);
3648
3754
  const agent = typeof args?.agent === "string" ? args.agent : String(event.agent ?? "unknown");
3755
+ takeCallDirectory(callID, String(call.sessionID)); // #161: a refused call never reaches execute.after
3649
3756
  throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.staleResume(child));
3650
3757
  }
3651
3758
  }
@@ -3763,7 +3870,10 @@ export async function registerV2Hooks(
3763
3870
  let background: boolean | undefined = verifying || roleForeground ? false : undefined;
3764
3871
  /** QA-PDF12-6: another copy of the plugin in this process claimed the call first; its background flag stands. */
3765
3872
  let lostClaim = false;
3766
- if (event.tool === "subagent" && bgActive() && finishApi !== undefined) {
3873
+ // #191: under `off` a verifying or role-routed call is tracked too (its decision is the `off` row: the same `background`
3874
+ // value as above), so a running acknowledgement from a host that backgrounds every child (OpenCode 2.3+) holds and
3875
+ // verifies a verifying call, and keeps a role call's binding and its budget and authority notices until it completes.
3876
+ if (event.tool === "subagent" && bgActive() && finishApi !== undefined && (bgMode !== "off" || verifying || roleForeground)) {
3767
3877
  const parent = String(event.sessionID);
3768
3878
  // DF-1-9: a parent the plugin never recorded (a reload, past the bound) is resolved, never assumed a root: an
3769
3879
  // unrecorded child must not reach the `auto` rows (A-2.1-1, root parents only). A lookup that fails stays foreground;
@@ -3817,6 +3927,7 @@ export async function registerV2Hooks(
3817
3927
  } catch (error) {
3818
3928
  dispatchRouter.onCallFinished(event.id); // the hook chain rejected the call: it will never reach execute.after (2.2)
3819
3929
  inflight.cancel(event.id);
3930
+ takeCallDirectory(callID, String(call.sessionID)); // #161: nor take its directory
3820
3931
  throw error;
3821
3932
  }
3822
3933
  // 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).
@@ -4120,7 +4231,9 @@ export async function registerV2Hooks(
4120
4231
  }
4121
4232
  }
4122
4233
  }
4123
- // Phase 2.1 (memo §13): the three turn-state providers. They render nothing (and are not registered) under `off`.
4234
+ // Phase 2.1 (memo §13): the three turn-state providers. #191: registered in every mode; under `off` they can only list the
4235
+ // verifying calls the host ran in the background anyway (nothing else is tracked there): on 2.0.x, only one the user
4236
+ // backgrounded, so a foreground result leaves them empty.
4124
4237
  if (bgActive() && processor !== undefined) {
4125
4238
  const completing = processor;
4126
4239
  const unregisters = [
@@ -4225,21 +4338,17 @@ export async function registerV2Hooks(
4225
4338
  knownAgent: (agent) => config.agent[agent] !== undefined,
4226
4339
  lifetime: executorLifetime.signal,
4227
4340
  // QA-5.1-26: a claim handover's executor goes through `adopt`, as the factory's does at start.
4341
+ // QA-5.1-32: `adopt` never throws; a wiring that failed partway is undone and answers false (the caller disposes it).
4228
4342
  onExecutor: (handed) => {
4229
- let adopted: boolean;
4230
- try {
4231
- adopted = adopt(handed);
4232
- } catch (error) {
4233
- ingestLogger.warn("[router] executor: the handed-over executor could not be wired", { error: String(error) });
4234
- // Adopted before the failure: W7 disposes it, so the caller must not.
4235
- return executor === handed;
4236
- }
4343
+ const adopted = adopt(handed);
4237
4344
  if (adopted) trackBackground(retryHookWiring);
4238
4345
  return adopted;
4239
4346
  },
4240
4347
  };
4241
- /** Settles once the retry hook of the adopted executor is registered (`adopt`). */
4348
+ /** Settles once the retry hook of the adopted executor is registered and its runtime started (`adopt`). */
4242
4349
  let retryHookWiring: Promise<void> = Promise.resolve();
4350
+ /** QA-5.1-32: executors whose wiring failed (`adopt` logged the failure; the startup path logs it no second time). */
4351
+ const unwired = new WeakSet<V2Executor>();
4243
4352
  /**
4244
4353
  * 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
4245
4354
  * (`host.onExecutor`). It sets `executor`, which the host events, the step tracking, the launcher metrics and the
@@ -4247,14 +4356,59 @@ export async function registerV2Hooks(
4247
4356
  * provider, the executor instructions and the retry hook, and starts the runtime (`start()` is memoised: recovery runs
4248
4357
  * once). Idempotent: the executor already adopted answers true and registers nothing again. Refused (false): another
4249
4358
  * executor while one is adopted, or any once dispose began (its owner disposes it). The retry hook's registration is
4250
- * asynchronous: `retryHookWiring` settles with it.
4359
+ * asynchronous: `retryHookWiring` settles with it. QA-5.1-32: never throws; a wiring that fails partway is undone (false).
4251
4360
  */
4252
- const adopt = (built: V2Executor): boolean => {
4361
+ const adopt = (built: V2Executor, startup = false): boolean => {
4253
4362
  if (executor === built) return true;
4254
4363
  if (disposed || executor !== null) return false;
4255
4364
  executor = built;
4256
4365
  const unregisters: Array<() => void> = [];
4257
- registrations.push({ dispose: async () => { for (const unregister of unregisters.splice(0)) unregister(); } });
4366
+ const unregisterAll = (): void => {
4367
+ for (const unregister of unregisters.splice(0)) {
4368
+ try {
4369
+ unregister();
4370
+ } catch (error) {
4371
+ ingestLogger.warn("[router] executor: a registration could not be removed", { error: String(error) });
4372
+ }
4373
+ }
4374
+ };
4375
+ registrations.push({ dispose: async () => { unregisterAll(); } });
4376
+ let wiring: Promise<void>;
4377
+ try {
4378
+ wiring = wireExecutor(built, unregisters);
4379
+ } catch (error) {
4380
+ // QA-5.1-32: a partial adopt leaves nothing behind: the executor is not adopted and the caller disposes it. The
4381
+ // one visible line for this failure (the startup path below adds none).
4382
+ unregisterAll();
4383
+ executor = null;
4384
+ unwired.add(built);
4385
+ ingestLogger.warn("[router] executor: it could not be wired; it is disposed and plans are not executed", { error: String(error) });
4386
+ return false;
4387
+ }
4388
+ // QA-5.1-33/-34: the runtime starts once the retry hook is registered, so no plan child it launches or recovers has a
4389
+ // host retry the hook does not see. A failed registration of a handed-over executor still starts it (adopted means
4390
+ // started, QA-5.1-32), without the hook, as before; at startup the caller undoes the adopt instead (`unwireAdopted`).
4391
+ // Nothing starts once dispose began.
4392
+ const startRuntime = (): void => {
4393
+ if (disposed || executor !== built) return;
4394
+ trackBackground((async () => built.runtime.start())().catch((error: unknown) => {
4395
+ ingestLogger.warn("[router] executor: it could not start", { error: String(error) });
4396
+ }));
4397
+ };
4398
+ unwireAdopted = () => {
4399
+ unregisterAll();
4400
+ if (executor === built) executor = null;
4401
+ };
4402
+ retryHookWiring = wiring.then(startRuntime, (error: unknown) => {
4403
+ if (!startup) startRuntime();
4404
+ throw error;
4405
+ });
4406
+ return true;
4407
+ };
4408
+ /** #190: undoes the latest successful `adopt` (its registrations and `executor`); the startup path's async failure. */
4409
+ let unwireAdopted: () => void = () => undefined;
4410
+ /** `adopt`'s registrations (each one's removal goes to `unregisters`); resolves once the retry hook is registered. */
4411
+ const wireExecutor = (built: V2Executor, unregisters: Array<() => void>): Promise<void> => {
4258
4412
  // W2 (3.1.7.a): every router tool call of a bound orchestrator refreshes the executor (guard 6, the ready set).
4259
4413
  unregisters.push(childRunner.onContextCaptured((c) => {
4260
4414
  try {
@@ -4282,7 +4436,7 @@ export async function registerV2Hooks(
4282
4436
  }));
4283
4437
  // 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
4284
4438
  // child only. Registered only when an executor exists (M3); on any error the decision stays unchanged.
4285
- retryHookWiring = ctx.session.hook("retry", async (event) => {
4439
+ return ctx.session.hook("retry", async (event) => {
4286
4440
  try {
4287
4441
  const sessionID = String(event.sessionID);
4288
4442
  // 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
@@ -4306,10 +4460,6 @@ export async function registerV2Hooks(
4306
4460
  if (disposed) await registration.dispose();
4307
4461
  else registrations.push(registration);
4308
4462
  });
4309
- trackBackground(built.runtime.start().catch((error: unknown) => {
4310
- ingestLogger.warn("[router] executor: it could not start", { error: String(error) });
4311
- }));
4312
- return true;
4313
4463
  };
4314
4464
  let built: V2Executor | null = null;
4315
4465
  try {
@@ -4318,9 +4468,19 @@ export async function registerV2Hooks(
4318
4468
  ingestLogger.warn("[router] executor: it could not be built; plans are not executed", { error: String(error) });
4319
4469
  }
4320
4470
  if (built !== null) {
4321
- if (adopt(built)) await retryHookWiring;
4322
- else {
4323
- ingestLogger.warn("[router] executor: the built executor was not adopted; it is disposed", {});
4471
+ if (adopt(built, true)) {
4472
+ try {
4473
+ await retryHookWiring;
4474
+ } catch (error) {
4475
+ // #190 (L1): a retry hook the host refused asynchronously fails the wiring as a synchronous failure does: one
4476
+ // warning, the adopt undone, the executor disposed (never started), and the plugin starts without it.
4477
+ unwireAdopted();
4478
+ ingestLogger.warn("[router] executor: it could not be wired; it is disposed and plans are not executed", { error: String(error) });
4479
+ await disposeExecutor(built);
4480
+ }
4481
+ } else {
4482
+ // QA-5.1-32: a failed wiring was logged by `adopt`; startup goes on without the executor.
4483
+ if (!unwired.has(built)) ingestLogger.warn("[router] executor: the built executor was not adopted; it is disposed", {});
4324
4484
  await disposeExecutor(built);
4325
4485
  }
4326
4486
  }
@@ -4332,11 +4492,13 @@ export async function registerV2Hooks(
4332
4492
  dispatchRouter.onCallResult(event.id, resultChild);
4333
4493
  const runNote = runNotes.get(event.id);
4334
4494
  runNotes.delete(event.id);
4495
+ // #161: the directory this call's `execute.before` used, taken (and dropped) on every path, used by the legacy hook below.
4496
+ const beforeDirectory = takeCallDirectory(typeof event.id === "string" ? event.id : "", String(event.sessionID));
4335
4497
  // Phase 2.1 (memo §4.3 steps 1-2). Timing: a non-null child binds the open start; a null child drops it.
4336
4498
  let ackText: string | undefined;
4337
4499
  if (event.tool === "subagent") {
4338
4500
  // #174: in every mode, so the runner-description fallback never takes this dispatch's report for the runner's.
4339
- if (resultChild !== null) noteDispatchedChild(resultChild);
4501
+ if (resultChild !== null) noteDispatchedChild(String(event.sessionID), resultChild);
4340
4502
  const running = resultChild !== null && ((event as { result?: { output?: { status?: unknown } } }).result)?.output?.status === "running";
4341
4503
  if (timings !== undefined) {
4342
4504
  try {
@@ -4350,7 +4512,8 @@ export async function registerV2Hooks(
4350
4512
  }
4351
4513
  }
4352
4514
  if (resultChild === null) inflight.cancel(event.id);
4353
- // A running result under mode ≠ off with a root parent: register the attempt (and its hold) BEFORE anything can render a completion.
4515
+ // A running result of a tracked call (under `off`: a verifying or role-routed one, #191) with a root parent: register the
4516
+ // attempt (and its hold) BEFORE anything can render a completion.
4354
4517
  const parent = String(event.sessionID);
4355
4518
  const rec = running && bgActive() && finishApi !== undefined ? inflight.byCall(event.id) : undefined;
4356
4519
  if (rec !== undefined && resultChild !== null && knownKindOf(parent) === "root") {
@@ -4542,11 +4705,12 @@ export async function registerV2Hooks(
4542
4705
  },
4543
4706
  };
4544
4707
  await within(hookContext(event), async () => {
4545
- // #161: no store keeps the before-hook's directory per call, so this is a lookup of its own; an unknown directory makes
4546
- // `scopedArgs` throw before the legacy hook runs, so no changed file is recorded against the plugin's directory.
4708
+ // #161: the directory the call's `execute.before` used, so the bookkeeping does not depend on a lookup of its own; without
4709
+ // one (none was needed or known, or it expired) a lookup of its own, where an unknown directory makes `scopedArgs` throw
4710
+ // before the legacy hook runs, so no changed file is recorded against the plugin's directory.
4547
4711
  await legacy["tool.execute.after"]?.({
4548
4712
  ...event, tool: legacyToolName(event.tool),
4549
- callID: event.id, args: await scopedArgs(event),
4713
+ callID: event.id, args: await scopedArgs(event, beforeDirectory === undefined ? undefined : () => Promise.resolve(beforeDirectory)),
4550
4714
  }, output);
4551
4715
  });
4552
4716
  const changed = output.output !== text;
@@ -4621,6 +4785,8 @@ export async function registerV2Hooks(
4621
4785
  try {
4622
4786
  const data = event.data as Record<string, any>;
4623
4787
  hostBudget.onEvent(event.type, data); // handoff 22 (S4): step counts, step-limit tool refusals, overflow failures
4788
+ // #108 slice 4: a revert takes answers out of the session's context; a compaction summarizes them (this backs the hook).
4789
+ if (ANSWER_FORGET_EVENTS.has(event.type) && typeof data?.sessionID === "string") forgetAnswers(data.sessionID);
4624
4790
  // QA-P23-2-A1 / QA-P23-3-1: the host names a tool result's saved full output on that session's tool-success event only.
4625
4791
  if (HOST_TOOL_SUCCESS_EVENT.test(event.type) && data && Array.isArray(data.outputPaths)) {
4626
4792
  rememberOutputs(data.sessionID, data.outputPaths.filter((path: unknown): path is string => typeof path === "string"));
@@ -4698,7 +4864,8 @@ export async function registerV2Hooks(
4698
4864
  // QA-2.1-21: tracked, so `dispose` and the settled seam wait for the completion it starts.
4699
4865
  // DF-1-4: a `child-ended` attempt met an end before its turn had an answer to read: this end delivers it.
4700
4866
  if (attempt.state === "acknowledged" || attempt.state === "child-ended") trackBackground(processor.process(sid, { kind: "end-event", outcome, eventID: event.id, at }));
4701
- else ingestLogger.warn("[router] background: an end event met an attempt that is not awaiting one", { child: sid, state: attempt.state, outcome });
4867
+ // A foreground attempt was finished in-line at its completed result: its end event is expected, not a stray one.
4868
+ else if (attempt.state !== "foreground") ingestLogger.warn("[router] background: an end event met an attempt that is not awaiting one", { child: sid, state: attempt.state, outcome });
4702
4869
  } else if (sessionKinds.get(sid) !== "root") {
4703
4870
  // A session whose kind is not yet known may be a child whose acknowledgement is still to come (bounded, TTL).
4704
4871
  inflight.noteEarlyEnd(sid, { outcome, eventID: event.id, at });
@@ -4739,6 +4906,7 @@ export async function registerV2Hooks(
4739
4906
  // QA-2.1-11 / QA-2.1-13: the cached directory, the failed kind lookup and the adoption mark go with the session.
4740
4907
  sessionDirs.delete(data.sessionID);
4741
4908
  lastCallDirs.delete(data.sessionID); // #161: and its last per-call directory
4909
+ forgetCallDirectories(data.sessionID); // #161: and its calls' before-hook directories
4742
4910
  failedKinds.delete(data.sessionID);
4743
4911
  adoptedSessions.delete(data.sessionID);
4744
4912
  refusedAdoptions.delete(data.sessionID);