opencode-model-router 2.8.0 → 2.9.1

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 (91) hide show
  1. package/CHANGELOG.md +372 -0
  2. package/README.md +22 -2
  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
  91. package/tiers.json +5 -5
@@ -0,0 +1,2439 @@
1
+ /**
2
+ * Background-first dispatch (Phase 2.1, memo §2.1): the policy, the in-flight registry, the completion
3
+ * processor, the held-result machinery and the lease guard of the Claude Code v2 adapter.
4
+ *
5
+ * Nothing here runs at load: every function is pure or driven through injected seams (journal, synthetic
6
+ * posting, clock, logger). Claude Code v1 never imports a behaviour from this module.
7
+ */
8
+ import type { DurationEstimate } from "../routing/outcomes/durations";
9
+ import { createLeaseRegistry, foldKeyPath, formatRunNote } from "../router/leases";
10
+ import type { LeaseActor, LeaseRegistry, LeaseSeams, Holder, HolderInput } from "../router/leases";
11
+ import { toolTargets } from "../router/tool-paths";
12
+ import { observeV2, type V2Observations } from "./v2-observations";
13
+
14
+ // ---- constants -------------------------------------------------------------------------------
15
+
16
+ /** Quiet period after a child's end event before the processor reads the child's result. */
17
+ export const COMPLETION_SETTLE_MS = 2000;
18
+ /** Live attempts (decided, acknowledged or processing) the registry tracks. */
19
+ export const MAX_LIVE_ATTEMPTS = 1000;
20
+ /** Call records kept between `decide` and the acknowledgement. */
21
+ export const MAX_CALL_RECORDS = 1000;
22
+ /** Child ends seen before their acknowledgement (= timings MAX_UNBOUND_OUTCOMES). */
23
+ export const MAX_EARLY_ENDS = 200;
24
+ /** Lifetime of an early end (= timings UNBOUND_OUTCOME_TTL_MS). */
25
+ export const EARLY_END_TTL_MS = 10 * 60_000;
26
+ /** Idempotency keys remembered (= timings MAX_SEEN_EVENT_IDS). */
27
+ export const MAX_PROCESSED_KEYS = 5000;
28
+ /** An attempt open longer than this is closed as unknown (= timings OPEN_START_TTL_MS). */
29
+ export const ATTEMPT_SWEEP_AGE_MS = 6 * 3600_000;
30
+ export const MAX_COMPLETED_PER_PARENT = 32;
31
+ export const MAX_COMPLETED_PARENTS = 1000;
32
+ export const MAX_HOLDS_PER_PARENT = 256;
33
+ export const MAX_HOLDS_GLOBAL = 10_000;
34
+
35
+ /**
36
+ * Attach channel: the legacy plugin (index.ts) defines it non-enumerable on its hooks object; v2-hooks calls it
37
+ * once at setup. It lives here, never in `main` (QA-1.2-1).
38
+ */
39
+ export const ROUTER_FINISH_ATTACH: unique symbol = Symbol.for("router.finishDispatch.attach");
40
+
41
+ // ---- D1 policy -------------------------------------------------------------------------------
42
+
43
+ export type BackgroundMode = "auto" | "model" | "off";
44
+ export type VerificationMode = "required" | "deferred" | "none";
45
+
46
+ export interface BackgroundInput {
47
+ mode: BackgroundMode;
48
+ /** Only a boolean `background` argument counts. */
49
+ explicit: boolean | undefined;
50
+ /** TASK_VERIFICATION is set for the call (v2-hooks.ts:1652). */
51
+ verifying: boolean;
52
+ /** `FinishApi.verificationFor(callID)`. */
53
+ verificationMode: VerificationMode;
54
+ /** Today's `roleForeground`: the call was routed to a role. */
55
+ roleRouted: boolean;
56
+ estimate: DurationEstimate | undefined;
57
+ /** `routing.background.minPredictedMs`. */
58
+ minPredictedMs: number;
59
+ /** DURATION_MIN_SAMPLES (durations.ts:34). */
60
+ minSamples: number;
61
+ acceptance: { testsPass: boolean; buildPasses: boolean };
62
+ /** Seam; false in 2.1 (launcher A bypasses execute.before, D14). */
63
+ planTask: boolean;
64
+ /** `HeldResults.available && FinishApi.canHold(parent) && holds under cap`. */
65
+ holdingAvailable: boolean;
66
+ parentIsRoot: boolean;
67
+ /** `InFlightRegistry.liveCount()`. */
68
+ liveCount: number;
69
+ }
70
+
71
+ export type BackgroundReason =
72
+ | "off" | "model-unset" | "child-parent" | "cap" | "explicit" | "explicit-no-holding"
73
+ | "estimate" | "acceptance" | "plan-task" | "no-holding" | "short" | "prior";
74
+
75
+ export interface BackgroundDecision {
76
+ /** The value for the native `background` argument; `undefined` = send no key. */
77
+ background: boolean | undefined;
78
+ /** The result is held until its verdict arrives. */
79
+ hold: boolean;
80
+ reason: BackgroundReason;
81
+ }
82
+
83
+ /**
84
+ * The D1 policy (memo §6): decides whether a `subagent` call runs in the background and whether its result is
85
+ * held for verification. Pure; the first matching row of the table wins.
86
+ */
87
+ export function decideBackground(input: BackgroundInput): BackgroundDecision {
88
+ // Row 1: the value every "not selected" row falls back to; byte-identical to today's `nativeArgs`.
89
+ const legacy: boolean | undefined = input.verifying || input.roleRouted ? false : undefined;
90
+ const needsHold = input.verificationMode === "required";
91
+ if (input.mode === "off") return { background: legacy, hold: false, reason: "off" };
92
+ if (!input.parentIsRoot) return { background: legacy, hold: false, reason: "child-parent" };
93
+ if (input.liveCount >= MAX_LIVE_ATTEMPTS) return { background: legacy, hold: false, reason: "cap" };
94
+ if (input.explicit === true) {
95
+ if (needsHold && !input.holdingAvailable) return { background: false, hold: false, reason: "explicit-no-holding" };
96
+ return { background: true, hold: needsHold, reason: "explicit" };
97
+ }
98
+ if (input.explicit === false) return { background: false, hold: false, reason: "explicit" };
99
+ if (input.mode === "model") return { background: legacy, hold: false, reason: "model-unset" };
100
+
101
+ // auto
102
+ let selected: BackgroundReason | undefined;
103
+ const est = input.estimate;
104
+ if (est !== undefined && est.source !== "prior" && est.n >= input.minSamples && est.p50 >= input.minPredictedMs) {
105
+ selected = "estimate";
106
+ } else if (input.acceptance.testsPass || input.acceptance.buildPasses) {
107
+ selected = "acceptance";
108
+ } else if (input.planTask) {
109
+ selected = "plan-task";
110
+ }
111
+ if (selected !== undefined) {
112
+ if (needsHold && !input.holdingAvailable) return { background: false, hold: false, reason: "no-holding" };
113
+ return { background: true, hold: needsHold, reason: selected };
114
+ }
115
+ // Not selected: a role dispatch with a thin store gets no key (role-spikes update).
116
+ const unselected: boolean | undefined = input.verifying ? false : undefined;
117
+ return { background: unselected, hold: false, reason: est !== undefined && est.source === "prior" ? "prior" : "short" };
118
+ }
119
+
120
+ // ---- shared seams ----------------------------------------------------------------------------
121
+
122
+ /** The logging seam. Structurally compatible with the adapter's ingest logger. */
123
+ export interface Logger {
124
+ warn(message: string, meta?: object): void;
125
+ debug?(message: string, meta?: object): void;
126
+ }
127
+
128
+ /** Logs through `logger`, never throwing (a logger fault must not fail a request). */
129
+ function warnSafe(logger: Logger, message: string, meta?: object): void {
130
+ try {
131
+ logger.warn(message, meta);
132
+ } catch (error) {
133
+ // A broken logger is the one failure with nowhere to report to; keep the caller alive.
134
+ void error;
135
+ }
136
+ }
137
+
138
+ function errorText(error: unknown): string {
139
+ if (error instanceof Error) return error.message;
140
+ return String(error);
141
+ }
142
+
143
+ /** Posts a synthetic message into a session (`ctx.session.synthetic`); injected, never imported. */
144
+ export type SyntheticFn = (input: {
145
+ sessionID: string;
146
+ text: string;
147
+ description: string;
148
+ metadata: Record<string, unknown>;
149
+ resume: boolean;
150
+ }) => Promise<unknown>;
151
+
152
+ /** A record in the persistence journal (memo §11.1); the shape is owned by `src\verify\pending.ts`. */
153
+ export type PersistedRecord = { v: 1; kind: string } & Record<string, unknown>;
154
+
155
+ /** The append-only journal seam (memo §11.2). Absent persistence is a journal that accepts and forgets. */
156
+ export interface InflightJournal {
157
+ append(record: PersistedRecord, opts?: { fsync?: boolean }): Promise<void>;
158
+ /** True when the journal holds a `processed` record for the idempotency key (§10). */
159
+ hasProcessed(key: string): boolean;
160
+ }
161
+
162
+ // ---- finish API (memo §2.2; implemented by index.ts, attached through ROUTER_FINISH_ATTACH) ---------
163
+
164
+ export interface FinishInput {
165
+ callID: string;
166
+ parentSessionID: string;
167
+ childSessionID: string;
168
+ /** The child's final text (defanged for role children). */
169
+ outputText: string;
170
+ status: "succeeded" | "failed" | "interrupted" | "unknown";
171
+ mode: "foreground" | "background";
172
+ heldHandle?: string;
173
+ endedAt: number;
174
+ /** The change set computed at child end (verify/dispatch.ts, 2.1.4.b); opaque here. */
175
+ delta?: unknown;
176
+ /**
177
+ * QA-2.1-17: set on a finish after a restart (an adopted `inflight` record, a restored hold): the dispatch as journaled
178
+ * with its record. A restart lost the in-memory call arguments and change set, so the plugin rebuilds the gate inputs from
179
+ * this and from the restored pending entry (its DoD and changed files), re-posts a verdict reached before the restart, and
180
+ * ends UNVERIFIABLE ("verification data lost in restart") when the data is missing. Absent on a live finish.
181
+ */
182
+ restored?: RestoredDispatch;
183
+ }
184
+
185
+ /**
186
+ * QA-PDF12-9: the caller of the dispatch a completion finishes, from the attempt the completion processor holds (never a
187
+ * capped lookup by call id), so the finish seam runs the graders as that caller.
188
+ */
189
+ export interface FinishCaller {
190
+ callerAgent?: string;
191
+ callerMessageID?: string;
192
+ }
193
+
194
+ /**
195
+ * QA-2.1-17: the dispatch data journaled with an `inflight` and a `hold` record (field `dispatch`), from `FinishApi.dispatchOf`.
196
+ * Any field may be missing (an older record, or a dispatch the plugin did not see).
197
+ */
198
+ export interface RestoredDispatch {
199
+ prompt?: string;
200
+ description?: string;
201
+ subagentType?: string;
202
+ /** The directory the dispatch ran in (`args.cwd`, else the plugin's project directory). */
203
+ cwd?: string;
204
+ /** The work root the dispatch named (`root=`), when there was one. */
205
+ workRoot?: string;
206
+ /**
207
+ * QA-SYNC1-13: the routed-role record of a role dispatch, as far as its gate needs it (the live record is in memory only).
208
+ * Absent on a tier dispatch, on an older record, and when the journaled snapshot is malformed.
209
+ */
210
+ routed?: RoutedRoleSnapshot;
211
+ }
212
+
213
+ /**
214
+ * QA-SYNC1-13: what a role dispatch's gate reads of its routed-role record (`RoleRouted`): the verification root, the parent
215
+ * (the role's read set), and whether the dispatch is a resume that carries an earlier attempt's acceptance, with the child.
216
+ */
217
+ export interface RoutedRoleSnapshot {
218
+ readonly verifyRoot: string;
219
+ readonly parentSessionID: string;
220
+ readonly carried?: true;
221
+ /** Gating lowered this dispatch's final floor; UNVERIFIABLE at return also records its raise. Absent for strict children. */
222
+ readonly gated?: true;
223
+ readonly resumeID: string | null;
224
+ }
225
+
226
+ const ROUTED_SNAPSHOT_KEYS: ReadonlySet<string> = new Set(["verifyRoot", "parentSessionID", "carried", "gated", "resumeID"]);
227
+
228
+ /**
229
+ * QA-SYNC1-13: the journaled routed-role snapshot, validated strictly: a plain object with only the known keys, a non-empty
230
+ * `verifyRoot`, a string `parentSessionID`, `resumeID` a non-empty string or null, `carried` absent or `true` (and only with a
231
+ * `resumeID`), `gated` absent or `true`. Anything else is malformed: undefined, and the record is dropped (never a partial or
232
+ * a guessed snapshot).
233
+ * Pure; never throws.
234
+ */
235
+ export function routedRoleSnapshotOf(value: unknown): RoutedRoleSnapshot | undefined {
236
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
237
+ if (Object.keys(value).some((key) => !ROUTED_SNAPSHOT_KEYS.has(key))) return undefined;
238
+ const verifyRoot: unknown = Reflect.get(value, "verifyRoot");
239
+ const parentSessionID: unknown = Reflect.get(value, "parentSessionID");
240
+ const resumeID: unknown = Reflect.get(value, "resumeID");
241
+ const carried: unknown = Reflect.get(value, "carried");
242
+ const gated: unknown = Reflect.get(value, "gated");
243
+ if (typeof verifyRoot !== "string" || verifyRoot === "") return undefined;
244
+ // An empty parent is the dispatch module's own "no orchestrator" value (roleReadSetFor reads it as no read set).
245
+ if (typeof parentSessionID !== "string") return undefined;
246
+ if (resumeID !== null && (typeof resumeID !== "string" || resumeID === "")) return undefined;
247
+ if (carried !== undefined && (carried !== true || resumeID === null)) return undefined;
248
+ if (gated !== undefined && gated !== true) return undefined;
249
+ return { verifyRoot, parentSessionID, resumeID, ...(carried === true ? { carried: true as const } : {}), ...(gated === true ? { gated: true as const } : {}) };
250
+ }
251
+
252
+ /** QA-2.1-17: the `dispatch` field of a journaled record, keeping only string fields. Pure; never throws. */
253
+ export function restoredDispatchOf(value: unknown): RestoredDispatch {
254
+ if (value === null || typeof value !== "object") return {};
255
+ const out: RestoredDispatch = {};
256
+ const read = (key: "prompt" | "description" | "subagentType" | "cwd" | "workRoot"): void => {
257
+ const field: unknown = Reflect.get(value, key);
258
+ if (typeof field === "string") out[key] = field;
259
+ };
260
+ read("prompt");
261
+ read("description");
262
+ read("subagentType");
263
+ read("cwd");
264
+ read("workRoot");
265
+ // QA-SYNC1-13: a malformed routed-role snapshot is dropped (the gate then runs without it, as on an older record).
266
+ const routed = routedRoleSnapshotOf(Reflect.get(value, "routed"));
267
+ if (routed !== undefined) out.routed = routed;
268
+ return out;
269
+ }
270
+
271
+ export type FinishResult = {
272
+ /** What the foreground path writes into `output.output`. */
273
+ outputText: string;
274
+ /** `outputText` minus the child's text: router lines only. */
275
+ suffix: string;
276
+ verification:
277
+ | { kind: "none" }
278
+ | { kind: "deferred"; handle: string }
279
+ | { kind: "held"; handle: string }
280
+ | { kind: "required"; verdict: "PASS" | "FAIL" | "UNVERIFIABLE" };
281
+ metadata: Record<string, unknown>;
282
+ };
283
+
284
+ export interface FinishApi {
285
+ verificationFor(callID: string): { mode: VerificationMode; acceptance: { testsPass: boolean; buildPasses: boolean } } | undefined;
286
+ /** A pending slot exists (MAX_ENTRIES_PER_SESSION / MAX_ENTRIES_GLOBAL). */
287
+ canHold(parentSessionID: string): boolean;
288
+ /** `pending.reserveHandle`. */
289
+ reserveHeld(parentSessionID: string, callID: string): string | undefined;
290
+ /**
291
+ * `pending.releaseHandle` (QA-2.1-3, QA-2.1-4): gives a reserved handle back when its attempt ends without a held register
292
+ * (the hold write failed, the child failed or was interrupted, the attempt was closed unknown). Idempotent. A reservation
293
+ * that is never given back expires after `HELD_RESERVATION_TTL_MS` (verify/pending.ts).
294
+ */
295
+ releaseHeld(handle: string): void;
296
+ /**
297
+ * QA-2.1-31: a restored hold's verdict was posted (or found posted) by the adapter directly, not through the plugin's
298
+ * gate: the restored pending entry of `handle` is settled with it, without a second post, so `router_verify` stops
299
+ * saying the verdict follows. Unknown or already settled handles are ignored.
300
+ */
301
+ settleHeldDirect(parentSessionID: string, handle: string, verdict: { verdict: "PASS" | "FAIL" | "UNVERIFIABLE"; reason?: string }): void;
302
+ /**
303
+ * QA-2.1-17: the journal-able dispatch data of a live `task` call (prompt, description, subagent type, cwd, work root),
304
+ * written with its `inflight` and `hold` records; undefined when the plugin does not know the call.
305
+ */
306
+ dispatchOf(callID: string): RestoredDispatch | undefined;
307
+ finish(input: FinishInput): Promise<FinishResult>;
308
+ /**
309
+ * The ONE journal (memo §11): `pending.jsonl`, shared by the pending store, the in-flight registry and the held results.
310
+ * `inflight` and `hold` appends are fsync'd by the caller (`{fsync: true}`).
311
+ */
312
+ journal: InflightJournal;
313
+ /**
314
+ * The change set of a dispatch at child end (verify/dispatch.ts `captureDelta`, 2.1.4.b); absent = none. QA-2.1-7:
315
+ * `dispatchID` is the change-set key `task:<parent>:<callID>`; absent, the implementation derives it from the call id.
316
+ */
317
+ captureDelta?(callID: string, childSessionID: string, dispatchID?: string): Promise<unknown>;
318
+ /**
319
+ * Memo §4.1 step 3 / §11.3: reloads `pending.jsonl` (parsed per line, folded by key, TTL applied) and keeps the surviving
320
+ * records dormant. Rejects when the file cannot be read (the caller then fails closed, §12).
321
+ */
322
+ reload(): Promise<void>;
323
+ /**
324
+ * QA-2.1-16: rewrites a vanished `pending.jsonl` from in-memory state: the plugin's live pending entries (and their
325
+ * verdicts), its dormant records, and `records` (the caller's live `inflight` attempts, holds with their `hold-text` and
326
+ * `posting` lines, and its own dormant records). QA-2.1-33: plus the same snapshot of every other plugin instance of this
327
+ * process on the same journal, each record once, so one instance's rewrite never drops another's records. Afterwards
328
+ * appends and reloads succeed again. Rejects when the rewrite fails (the caller stays fail closed and may retry).
329
+ */
330
+ recreateJournal(records: readonly PersistedRecord[]): Promise<void>;
331
+ /**
332
+ * QA-2.1-33: registers the adapter's snapshot of its live records (the `records` it passes to `recreateJournal`), so a
333
+ * `recreate` of the shared journal by ANOTHER plugin instance of this process writes them too. Absent: only this
334
+ * adapter's own `recreateJournal` calls carry them.
335
+ */
336
+ setAdapterSnapshot?(provider: () => readonly PersistedRecord[]): void;
337
+ /**
338
+ * QA-2.1-21: resolves once the held gates the plugin started (`finish` with a held handle runs its gate without awaiting
339
+ * it) and their verdict posts have ended, including gates started meanwhile. The adapter's settled seam and `dispose`
340
+ * wait for it. Never rejects.
341
+ */
342
+ idle(): Promise<void>;
343
+ /**
344
+ * Memo §11.3: this process saw `sessionID`. Takes the exclusive claim file `pending.claims\<id>` and hands over the dormant
345
+ * records of that session; `undefined` when there are none. QA-2.1-34: `ADOPTION_REFUSED` when another live instance holds
346
+ * the claim: its records stay dormant and the caller tries again at a later sighting (rate-limited,
347
+ * `ADOPTION_RETRY_MS`). Synchronous.
348
+ */
349
+ adopt(sessionID: string): AdoptedRecords | AdoptionRefused | undefined;
350
+ }
351
+
352
+ /** QA-2.1-34: `FinishApi.adopt` found dormant records but another live instance holds the session's claim. */
353
+ export interface AdoptionRefused {
354
+ readonly refused: true;
355
+ }
356
+
357
+ /** QA-2.1-34: the one refusal value of `FinishApi.adopt`. */
358
+ export const ADOPTION_REFUSED: AdoptionRefused = Object.freeze({ refused: true });
359
+
360
+ /** QA-2.1-34: a refused adoption is tried again at a sighting at least this long after the last attempt (per session). */
361
+ export const ADOPTION_RETRY_MS = 30_000;
362
+
363
+ /** QA-2.1-34: whether an `adopt` result is a refusal (not adopted records, not "nothing to adopt"). Pure. */
364
+ export function isAdoptionRefused(result: AdoptedRecords | AdoptionRefused | undefined): result is AdoptionRefused {
365
+ return result !== undefined && "refused" in result && result.refused;
366
+ }
367
+
368
+ /** The reloaded records of one adopted parent session (memo §11.3). */
369
+ export interface AdoptedRecords {
370
+ /** `hold` records not yet posted or forgotten (for `HeldResults.restore`). */
371
+ holds: readonly PersistedRecord[];
372
+ /** `inflight` records without a `processed` record (for recovery). */
373
+ inflight: readonly PersistedRecord[];
374
+ }
375
+
376
+ export type FinishAttach = (deps: {
377
+ host: "v2";
378
+ held: HeldSink;
379
+ /** The lease gate before plugin verification runs (memo §2.5); absent when `routing.leases.mode` is not `enforce`. */
380
+ leaseGate?: Pick<LeaseGuard, "waitTreeFree">;
381
+ }) => FinishApi | undefined;
382
+
383
+ // ---- in-flight registry ----------------------------------------------------------------------
384
+
385
+ export type AttemptState =
386
+ | "decided" | "acknowledged" | "child-ended" | "processing" | "annotated" | "held" | "verdict"
387
+ | "released" | "foreground" | "cancelled" | "closed-unknown";
388
+
389
+ export interface CallRecord {
390
+ callID: string;
391
+ parentSessionID: string;
392
+ /** The DISPATCHED agent (`output.args.agent`). */
393
+ agent: string;
394
+ /**
395
+ * DF-1.1-1: the CALLER (orchestrator) agent that made the `subagent` call. The completion finish (grader launch) runs
396
+ * as this agent: the host checks the caller's `subagent:<grader>` permission, never the dispatched child's.
397
+ * Absent for a record journaled before this field existed.
398
+ */
399
+ callerAgent?: string;
400
+ /**
401
+ * QA-PDF12-5: the id of the caller's message that made the `subagent` call, so the completion finish runs in a context with
402
+ * the call's real ids (never an empty message id). Absent for a record journaled before this field existed.
403
+ */
404
+ callerMessageID?: string;
405
+ role?: string;
406
+ description: string;
407
+ verifying: boolean;
408
+ verificationMode: VerificationMode;
409
+ decision: BackgroundDecision;
410
+ resumeOf?: string;
411
+ at: number;
412
+ /**
413
+ * 3.1.7 W5: an attempt the plan executor registered (`DispatchBookkeeping.registerInFlight`). It is excluded from the ordinary
414
+ * completion and verification path: its launch completion is its only settle point, submitted as a `runner` trigger.
415
+ */
416
+ owner?: "executor";
417
+ }
418
+
419
+ export interface Attempt extends CallRecord {
420
+ /** `${childSessionID}\u0000${callID}` (memo §10). */
421
+ key: string;
422
+ childSessionID: string;
423
+ state: AttemptState;
424
+ userBackgrounded: boolean;
425
+ hold?: { handle: string };
426
+ ackAt?: number;
427
+ endedAt?: number;
428
+ outcome?: "succeeded" | "failed" | "interrupted" | "unknown";
429
+ annotations: string[];
430
+ pendingShown: boolean;
431
+ waitedOnce: boolean;
432
+ shownInTurn?: number;
433
+ }
434
+
435
+ export interface EndFact {
436
+ outcome: "succeeded" | "failed" | "interrupted";
437
+ eventID: string;
438
+ at: number;
439
+ }
440
+
441
+ export interface InFlightRegistry {
442
+ /** execute.before (subagent). `false`: another instance claimed this callID (process-wide set, like `claimCall`). */
443
+ decide(rec: CallRecord): boolean;
444
+ acknowledge(callID: string, child: string, ack: { userBackgrounded: boolean; hold?: { handle: string } }): Attempt | undefined;
445
+ /** A completed (non-running) result: terminal for the processor. */
446
+ foreground(callID: string, child: string | null): void;
447
+ /** Error, null child or `onCallFinished`. */
448
+ cancel(callID: string): void;
449
+ /** The newest attempt of the child. */
450
+ byChild(child: string): Attempt | undefined;
451
+ byCall(callID: string): CallRecord | Attempt | undefined;
452
+ /** An end seen before the acknowledgement; bounded, with a TTL. */
453
+ noteEarlyEnd(child: string, end: EndFact): void;
454
+ takeEarlyEnd(child: string): EndFact | undefined;
455
+ listForParent(parent: string): readonly Attempt[];
456
+ /** QA-2.1-16: every attempt this registry knows (any parent, any state). */
457
+ list(): readonly Attempt[];
458
+ liveCount(): number;
459
+ forgetSession(sessionID: string): void;
460
+ /** Open for longer than `ATTEMPT_SWEEP_AGE_MS` becomes `closed-unknown`; the closed attempts are returned. */
461
+ sweep(now: number): readonly Attempt[];
462
+ /** Gives this instance's process-wide call claims back (plugin dispose / reload, QA-2.1-13). */
463
+ dispose(): void;
464
+ }
465
+
466
+ /** QA-2.1-13: a background decision counts as live this long while it waits for its acknowledgement. */
467
+ export const DECIDED_LIVE_MS = EARLY_END_TTL_MS;
468
+
469
+ /** Why the registry closed an open attempt without an end (the owner posts the verdict of a held one). */
470
+ export type CloseCause = "superseded" | "sweep";
471
+
472
+ const OPEN_STATES: ReadonlySet<AttemptState> = new Set<AttemptState>(["acknowledged", "child-ended", "processing", "held"]);
473
+ const TERMINAL_STATES: ReadonlySet<AttemptState> = new Set<AttemptState>(["released", "foreground", "cancelled", "closed-unknown"]);
474
+
475
+ /** Process-wide call claims (`bg:<callID>`), shared by every plugin instance of the process; bounded. */
476
+ export const MAX_CLAIMS = 1000;
477
+ /** QA-PDF12-13: the bound of the whole shared set, whichever instances own its claims. */
478
+ export const MAX_PROCESS_CLAIMS = 8 * MAX_CLAIMS;
479
+
480
+ /**
481
+ * DF-1.1-1: the plugin can be loaded as several module copies in one process (one per booted host location), and a
482
+ * module-level set would then be one set per copy, so two copies would both claim a callID and complete it twice. The
483
+ * set lives on `globalThis` under a versioned registry key instead, so every copy shares it.
484
+ */
485
+ const PROCESS_CLAIMS_KEY = Symbol.for("opencode-model-router.background-claims.v1");
486
+ function processClaims(): Set<string> {
487
+ const registry = globalThis as unknown as Record<symbol, Set<string> | undefined>;
488
+ const existing = registry[PROCESS_CLAIMS_KEY];
489
+ if (existing instanceof Set) return existing;
490
+ const created = new Set<string>();
491
+ Object.defineProperty(globalThis, PROCESS_CLAIMS_KEY, { value: created, configurable: true, enumerable: false, writable: true });
492
+ return created;
493
+ }
494
+
495
+ /** The attempt key (memo §10). */
496
+ export function attemptKey(childSessionID: string, callID: string): string {
497
+ return `${childSessionID}\u0000${callID}`;
498
+ }
499
+
500
+ /** 3.1.7 W5: the record belongs to the plan executor (excluded from the ordinary completion and verification path). */
501
+ export function isExecutorOwned(rec: CallRecord | undefined): boolean {
502
+ return rec?.owner === "executor";
503
+ }
504
+
505
+ function isAttempt(rec: CallRecord | Attempt): rec is Attempt {
506
+ return "key" in rec;
507
+ }
508
+
509
+ /** Evicts the oldest entries of an insertion-ordered map until it holds at most `max`, preferring entries `prefer` accepts. */
510
+ function trimMap<K, V>(map: Map<K, V>, max: number, prefer: (value: V) => boolean, onEvict?: (key: K, value: V) => void): void {
511
+ if (map.size <= max) return;
512
+ for (const pass of [true, false]) {
513
+ for (const [key, value] of map) {
514
+ if (map.size <= max) return;
515
+ if (pass && !prefer(value)) continue;
516
+ map.delete(key);
517
+ onEvict?.(key, value);
518
+ }
519
+ }
520
+ }
521
+
522
+ /**
523
+ * Creates the in-flight registry (memo §3, §10). Every collection is bounded. `claims` defaults to the
524
+ * process-wide set; tests pass their own.
525
+ */
526
+ export function createInFlightRegistry(deps: {
527
+ now(): number;
528
+ logger: Logger;
529
+ claims?: Set<string>;
530
+ onClosed?(attempt: Attempt, cause: CloseCause): void;
531
+ }): InFlightRegistry {
532
+ const claims = deps.claims ?? processClaims();
533
+ /** QA-2.1-13: the claims this instance added, so `forgetSession` and `dispose` give exactly those back. */
534
+ const own = new Set<string>();
535
+ function releaseClaim(callID: string): void {
536
+ const claim = `bg:${callID}`;
537
+ if (own.delete(claim)) claims.delete(claim);
538
+ }
539
+ const calls = new Map<string, CallRecord | Attempt>();
540
+ const attempts = new Map<string, Attempt>();
541
+ const newestByChild = new Map<string, string>();
542
+ const earlyEnds = new Map<string, { end: EndFact; seen: number }>();
543
+
544
+ function dropAttempt(key: string): void {
545
+ const a = attempts.get(key);
546
+ if (a === undefined) return;
547
+ attempts.delete(key);
548
+ if (newestByChild.get(a.childSessionID) === key) newestByChild.delete(a.childSessionID);
549
+ }
550
+
551
+ function enforceBounds(): void {
552
+ trimMap(calls, MAX_CALL_RECORDS, (rec) => isAttempt(rec) && TERMINAL_STATES.has(rec.state), (_id, rec) => {
553
+ if (isAttempt(rec)) dropAttempt(rec.key);
554
+ });
555
+ }
556
+
557
+ function closeOpen(a: Attempt, cause: CloseCause): void {
558
+ a.state = "closed-unknown";
559
+ a.outcome = "unknown";
560
+ try {
561
+ deps.onClosed?.(a, cause);
562
+ } catch (error) {
563
+ warnSafe(deps.logger, "[router] background close handler failed", { error: errorText(error) });
564
+ }
565
+ }
566
+
567
+ function makeAttempt(rec: CallRecord, child: string, state: AttemptState): Attempt {
568
+ const attempt: Attempt = {
569
+ ...rec,
570
+ key: attemptKey(child, rec.callID),
571
+ childSessionID: child,
572
+ state,
573
+ userBackgrounded: false,
574
+ annotations: [],
575
+ pendingShown: false,
576
+ waitedOnce: false,
577
+ };
578
+ attempts.set(attempt.key, attempt);
579
+ newestByChild.set(child, attempt.key);
580
+ calls.set(rec.callID, attempt);
581
+ return attempt;
582
+ }
583
+
584
+ return {
585
+ decide(rec) {
586
+ const claim = `bg:${rec.callID}`;
587
+ if (claims.has(claim)) return false;
588
+ claims.add(claim);
589
+ own.add(claim);
590
+ // QA-PDF12-6: the cap is per owner. An instance evicts only its own oldest claims, never a live claim of another copy
591
+ // sharing the process-wide set (which is then bounded by MAX_CLAIMS per live instance).
592
+ for (const old of own) {
593
+ if (own.size <= MAX_CLAIMS) break;
594
+ own.delete(old);
595
+ claims.delete(old);
596
+ }
597
+ // QA-PDF12-13: a process-wide backstop past the per-owner cap: the oldest claims of ANY owner go once the shared set
598
+ // outgrows MAX_PROCESS_CLAIMS (leaked claims of instances that never disposed cannot grow it without bound).
599
+ for (const old of claims) {
600
+ if (claims.size <= MAX_PROCESS_CLAIMS) break;
601
+ claims.delete(old);
602
+ own.delete(old);
603
+ }
604
+ calls.set(rec.callID, rec);
605
+ enforceBounds();
606
+ return true;
607
+ },
608
+
609
+ acknowledge(callID, child, ack) {
610
+ const rec = calls.get(callID);
611
+ if (rec === undefined) return undefined;
612
+ if (isAttempt(rec)) return rec.childSessionID === child ? rec : undefined;
613
+ // A resume: the previous open attempt of the child is closed unknown; the new one owns the next end (R12).
614
+ const previousKey = newestByChild.get(child);
615
+ const previous = previousKey === undefined ? undefined : attempts.get(previousKey);
616
+ if (previous !== undefined && OPEN_STATES.has(previous.state)) closeOpen(previous, "superseded");
617
+ const attempt = makeAttempt(rec, child, "acknowledged");
618
+ attempt.userBackgrounded = ack.userBackgrounded;
619
+ if (ack.hold !== undefined) attempt.hold = { handle: ack.hold.handle };
620
+ attempt.ackAt = deps.now();
621
+ enforceBounds();
622
+ return attempt;
623
+ },
624
+
625
+ foreground(callID, child) {
626
+ const rec = calls.get(callID);
627
+ if (child !== null) earlyEnds.delete(child);
628
+ if (rec === undefined) return;
629
+ if (isAttempt(rec)) {
630
+ if (OPEN_STATES.has(rec.state) || rec.state === "decided") rec.state = "foreground";
631
+ return;
632
+ }
633
+ if (child === null) {
634
+ calls.delete(callID);
635
+ return;
636
+ }
637
+ makeAttempt(rec, child, "foreground");
638
+ enforceBounds();
639
+ },
640
+
641
+ cancel(callID) {
642
+ const rec = calls.get(callID);
643
+ if (rec === undefined) return;
644
+ if (isAttempt(rec)) {
645
+ if (!TERMINAL_STATES.has(rec.state)) rec.state = "cancelled";
646
+ return;
647
+ }
648
+ calls.delete(callID);
649
+ },
650
+
651
+ byChild(child) {
652
+ const key = newestByChild.get(child);
653
+ return key === undefined ? undefined : attempts.get(key);
654
+ },
655
+
656
+ byCall(callID) {
657
+ return calls.get(callID);
658
+ },
659
+
660
+ noteEarlyEnd(child, end) {
661
+ earlyEnds.delete(child);
662
+ // The TTL runs on this process's clock from the moment the end was parked, not on the host event's own timestamp.
663
+ earlyEnds.set(child, { end, seen: deps.now() });
664
+ trimMap(earlyEnds, MAX_EARLY_ENDS, () => false);
665
+ },
666
+
667
+ takeEarlyEnd(child) {
668
+ const parked = earlyEnds.get(child);
669
+ if (parked === undefined) return undefined;
670
+ earlyEnds.delete(child);
671
+ // DF-1-4: an end parked before a resume of the child was decided ended an earlier turn, never the resumed one: it is
672
+ // dropped, and the attempt waits for its own end.
673
+ const newestKey = newestByChild.get(child);
674
+ const newest = newestKey === undefined ? undefined : attempts.get(newestKey);
675
+ if (newest?.resumeOf === child && parked.seen < newest.at) return undefined;
676
+ return deps.now() - parked.seen > EARLY_END_TTL_MS ? undefined : parked.end;
677
+ },
678
+
679
+ listForParent(parent) {
680
+ const out: Attempt[] = [];
681
+ for (const a of attempts.values()) if (a.parentSessionID === parent) out.push(a);
682
+ return out;
683
+ },
684
+
685
+ list() {
686
+ return [...attempts.values()];
687
+ },
688
+
689
+ liveCount() {
690
+ let n = 0;
691
+ const at = deps.now();
692
+ for (const rec of calls.values()) {
693
+ if (isAttempt(rec)) {
694
+ if (OPEN_STATES.has(rec.state)) n += 1;
695
+ } else if (rec.decision.background === true && at - rec.at <= DECIDED_LIVE_MS) {
696
+ // QA-2.1-13: only a fresh background decision awaits its acknowledgement; a foreground one or a stale one is not live.
697
+ n += 1;
698
+ }
699
+ }
700
+ return n;
701
+ },
702
+
703
+ forgetSession(sessionID) {
704
+ for (const [callID, rec] of calls) {
705
+ if (rec.parentSessionID === sessionID || (isAttempt(rec) && rec.childSessionID === sessionID)) {
706
+ calls.delete(callID);
707
+ releaseClaim(callID);
708
+ if (isAttempt(rec)) dropAttempt(rec.key);
709
+ }
710
+ }
711
+ earlyEnds.delete(sessionID);
712
+ },
713
+
714
+ dispose() {
715
+ // QA-2.1-13: a disposed instance (a reload) gives its process-wide call claims back.
716
+ for (const claim of own) claims.delete(claim);
717
+ own.clear();
718
+ },
719
+
720
+ sweep(now) {
721
+ const closed: Attempt[] = [];
722
+ for (const a of attempts.values()) {
723
+ if (!OPEN_STATES.has(a.state)) continue;
724
+ if (now - (a.ackAt ?? a.at) <= ATTEMPT_SWEEP_AGE_MS) continue;
725
+ closeOpen(a, "sweep");
726
+ closed.push(a);
727
+ }
728
+ for (const [child, parked] of earlyEnds) if (now - parked.seen > EARLY_END_TTL_MS) earlyEnds.delete(child);
729
+ for (const [callID, rec] of calls) {
730
+ if (!isAttempt(rec) && now - rec.at > ATTEMPT_SWEEP_AGE_MS) {
731
+ calls.delete(callID);
732
+ releaseClaim(callID);
733
+ }
734
+ }
735
+ return closed;
736
+ },
737
+ };
738
+ }
739
+
740
+ // ---- held results (memo §5, §7) ----------------------------------------------------------------
741
+
742
+ export type HeldVerdict = { verdict: "PASS" | "FAIL" | "UNVERIFIABLE"; text: string; reason?: string };
743
+
744
+ export interface HeldSink {
745
+ verdict(handle: string, v: HeldVerdict): Promise<void>;
746
+ }
747
+
748
+ export interface HeldRecord {
749
+ handle: string;
750
+ parentSessionID: string;
751
+ childSessionID: string;
752
+ callID: string;
753
+ /** `<role> "<description>"`, for the "held" provider. */
754
+ label?: string;
755
+ /** The completion body known to the owner (persisted digest or child text); lets the matcher cut precisely. */
756
+ body?: string;
757
+ /** The child's final text, persisted with the hold so a restart can re-run the gate (QA-2.1-6). */
758
+ childText?: string;
759
+ /** QA-2.1-17: the dispatch data (`FinishApi.dispatchOf`), persisted with the hold so a restart can rebuild the gate inputs. */
760
+ dispatch?: RestoredDispatch;
761
+ /** DF-1.1-1: the CALLER agent of the dispatch, persisted so a restored hold launches its grader as the caller. Absent in an old entry. */
762
+ callerAgent?: string;
763
+ /** QA-PDF12-5: the caller's message that made the dispatch, persisted with the hold. Absent in an old entry. */
764
+ callerMessageID?: string;
765
+ }
766
+
767
+ /** A restored hold whose verdict was being posted (`posting` without `posted`): re-post after a parent check (R21). */
768
+ export interface RestoredPosting {
769
+ handle: string;
770
+ parentSessionID: string;
771
+ childSessionID: string;
772
+ text: string;
773
+ }
774
+
775
+ /** A restored hold with no verdict yet: the gate runs again at adoption (R20, QA-2.1-6). */
776
+ export interface RestoredHold {
777
+ handle: string;
778
+ parentSessionID: string;
779
+ childSessionID: string;
780
+ callID: string;
781
+ /** Present only when the child succeeded: `hold-text` is journaled for succeeded children only (QA-2.1-17). */
782
+ childText?: string;
783
+ /** QA-2.1-17: the dispatch data journaled with the hold (empty fields when an older record had none). */
784
+ dispatch: RestoredDispatch;
785
+ /** DF-1.1-1: the caller agent journaled with the hold; absent for an older record. */
786
+ callerAgent?: string;
787
+ /** QA-PDF12-5: the caller's message id journaled with the hold; absent for an older record. */
788
+ callerMessageID?: string;
789
+ /** QA-2.1-17: a verdict the gate reached before the restart but never started posting: posted, never recomputed. */
790
+ verdict?: StoredVerdict;
791
+ }
792
+
793
+ /** QA-2.1-17: a gate verdict read back from a journaled `state` record. */
794
+ export interface StoredVerdict {
795
+ verdict: "PASS" | "FAIL" | "UNVERIFIABLE";
796
+ reason?: string;
797
+ }
798
+
799
+ /** QA-2.1-17: the verdict of a `state` record's `verdict` field (a pending.ts `Verdict`); undefined when it holds none. Pure. */
800
+ export function storedVerdictOf(value: unknown): StoredVerdict | undefined {
801
+ if (value === null || typeof value !== "object") return undefined;
802
+ const pass: unknown = Reflect.get(value, "pass");
803
+ const outcome: unknown = Reflect.get(value, "outcome");
804
+ const reasons: unknown = Reflect.get(value, "reasons");
805
+ if (typeof pass !== "boolean") return undefined;
806
+ const verdict = outcome === "unverifiable" ? "UNVERIFIABLE" : pass ? "PASS" : "FAIL";
807
+ const reason = Array.isArray(reasons) && typeof reasons[0] === "string" ? reasons[0] : undefined;
808
+ return { verdict, ...(reason === undefined ? {} : { reason }) };
809
+ }
810
+
811
+ /** What `HeldResults.restore` hands back to the adopter. */
812
+ export interface RestoredHolds {
813
+ reposts: readonly RestoredPosting[];
814
+ unverified: readonly RestoredHold[];
815
+ }
816
+
817
+ export interface HeldEntryView {
818
+ handle: string;
819
+ child: string;
820
+ label: string;
821
+ status: string;
822
+ }
823
+
824
+ export interface HeldResults extends HeldSink {
825
+ /** Context AND compaction hooks registered AND `ctx.session.synthetic` is a function. */
826
+ readonly available: boolean;
827
+ /**
828
+ * Makes the hold active, then appends the hold record (fsync); a failed append removes it again and rejects. A verdict
829
+ * that arrives before the append settles waits for it; one that arrives before `hold` is queued (QA-2.1-2).
830
+ */
831
+ hold(rec: HeldRecord): Promise<void>;
832
+ /** Persists the child's final text with an active hold (`hold-text`), so a restart can re-run the gate (QA-2.1-6). */
833
+ noteText(handle: string, text: string): Promise<void>;
834
+ /** True until the verdict entry is posted. */
835
+ isHeld(child: string): boolean;
836
+ /** Pure (§7.1). */
837
+ placeholder(handle: string, child: string): string;
838
+ /** The matcher (§7.2). */
839
+ applyText(sessionID: string, text: string): string;
840
+ /** Copies the messages and parts it changes; `undefined` = unchanged. */
841
+ apply<M>(sessionID: string, messages: readonly M[]): M[] | undefined;
842
+ /** The resume / Code Mode refusal (§7.4); `undefined` = allowed. */
843
+ refusal(sessionID: string, tool: string, args: unknown): string | undefined;
844
+ heldFor(parent: string): readonly HeldEntryView[];
845
+ forgetSession(sessionID: string): void;
846
+ /**
847
+ * Restores adopted records: an unposted hold becomes active again, a posted one an inactive placeholder (QA-2.1-10).
848
+ * Returns the holds whose verdict was being posted and the holds that still need a verdict (R20, R21).
849
+ */
850
+ restore(records: readonly PersistedRecord[]): RestoredHolds;
851
+ /**
852
+ * Settles a restored `posting` hold (R21): `alreadyPosted` (the parent context carries the verdict's
853
+ * `metadata.router.handle`) records `posted`; otherwise the journaled verdict text is posted again.
854
+ */
855
+ settleRestored(handle: string, alreadyPosted: boolean): Promise<void>;
856
+ /**
857
+ * QA-2.1-16: the journal records of every live hold (its `hold` record with the dispatch data, its `hold-text` and an
858
+ * unposted `posting`), and of every posted placeholder (`hold` and `posted`), for rewriting a vanished journal.
859
+ */
860
+ persisted(): PersistedRecord[];
861
+ }
862
+
863
+ const SUBAGENT_CLOSE = "</subagent>";
864
+ const VERDICT_PREFIX = "<router-verdict ";
865
+ const SYNTHETIC_ATTEMPTS = 3;
866
+ /** = BACKGROUND_RETRY_BASE_MS (verify/pending.ts:442); kept local so this module imports nothing heavy. */
867
+ const DEFAULT_RETRY_BASE_MS = 30_000;
868
+
869
+ /** The placeholder that replaces a held completion (memo §7.1); a pure function of the handle and the child. */
870
+ export function heldPlaceholder(handle: string, child: string): string {
871
+ return `<subagent sessionID="${child}" state="held">held — verdict pending (${handle})</subagent>`;
872
+ }
873
+
874
+ /** The verdict entry text (memo §5). */
875
+ export function verdictText(handle: string, child: string, v: HeldVerdict): string {
876
+ return `<router-verdict handle="${handle}" sessionID="${child}" verdict="${v.verdict}">\n${v.text}\n</router-verdict>`;
877
+ }
878
+
879
+ /**
880
+ * QA-2.1-24: the plain notice that carries the verdict of a result that could not be held (its hold record failed): the result
881
+ * reached the parent unverified, so this is not a `<router-verdict>` release, only the verdict after it.
882
+ */
883
+ export function unheldVerdictText(handle: string, child: string, v: HeldVerdict): string {
884
+ return `[router] Verdict for session ${child} (${handle}): ${v.verdict}. Its result could not be held, so it reached you unverified; this is the verification that followed.\n${v.text}`;
885
+ }
886
+
887
+ /** The refusal for a resume of, or a Code Mode reference to, a held child (memo §7.4). */
888
+ export function heldRefusalText(child: string, handle: string): string {
889
+ return `[router] Refused: session ${child} is held for verification (${handle}). Its result arrives with the verdict; resume it after that.`;
890
+ }
891
+
892
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
893
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
894
+ const out: Record<string, unknown> = {};
895
+ for (const key of Object.keys(value)) out[key] = Reflect.get(value, key);
896
+ return out;
897
+ }
898
+
899
+ /** Rewrites the text parts of one message; returns `undefined` when no part changed. The input is never mutated. */
900
+ function redactMessage<M>(message: M, redact: (text: string) => string): M | undefined {
901
+ if (typeof message !== "object" || message === null) return undefined;
902
+ const parts: unknown = Reflect.get(message, "parts");
903
+ if (!Array.isArray(parts)) return undefined;
904
+ let changed = false;
905
+ const next: unknown[] = parts.map((part: unknown) => {
906
+ const rec = asRecord(part);
907
+ if (rec === undefined || typeof rec.text !== "string") return part;
908
+ if (rec.type !== undefined && rec.type !== "text") return part;
909
+ const text = redact(rec.text);
910
+ if (text === rec.text) return part;
911
+ changed = true;
912
+ return { ...rec, text };
913
+ });
914
+ return changed ? { ...message, parts: next } : undefined;
915
+ }
916
+
917
+ interface HoldEntry extends HeldRecord {
918
+ /** Verdict not yet posted. */
919
+ active: boolean;
920
+ /** A post is in flight or was journaled as `posting`. */
921
+ posting: boolean;
922
+ status: string;
923
+ /** The verdict text being (or last) posted; journaled with `posting` (QA-2.1-2). */
924
+ verdictText?: string;
925
+ /** The `hold` append is in flight; a verdict arriving meanwhile waits for it (QA-2.1-2). */
926
+ ready?: Promise<boolean>;
927
+ }
928
+
929
+ /** Verdicts that arrive for a handle before its hold is inserted; consumed by `hold` (QA-2.1-2). */
930
+ const MAX_EARLY_VERDICTS = 200;
931
+
932
+ /**
933
+ * Creates the held-result store (memo §5, §7). Holds are bounded per parent and globally; the placeholder of a
934
+ * released hold stays in force for the session's life (the host history keeps the original, C4).
935
+ */
936
+ export function createHeldResults(deps: {
937
+ observations?: V2Observations;
938
+ synthetic: SyntheticFn;
939
+ journal: InflightJournal;
940
+ available: boolean;
941
+ logger: Logger;
942
+ now?(): number;
943
+ retryBaseMs?: number;
944
+ sleep?(ms: number): Promise<void>;
945
+ }): HeldResults {
946
+ const byHandle = new Map<string, HoldEntry>();
947
+ const byParent = new Map<string, Map<string, HoldEntry>>();
948
+ const early = new Map<string, { v: HeldVerdict; at: number }>();
949
+ /** QA-2.1-24: holds whose append failed, until their verdict is posted as a plain notice (bounded, oldest first out). */
950
+ const unheld = new Map<string, HeldRecord>();
951
+ const now = deps.now ?? (() => Date.now());
952
+ const retryBase = deps.retryBaseMs ?? DEFAULT_RETRY_BASE_MS;
953
+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
954
+
955
+ function remove(entry: HoldEntry): void {
956
+ byHandle.delete(entry.handle);
957
+ const children = byParent.get(entry.parentSessionID);
958
+ if (children === undefined) return;
959
+ if (children.get(entry.childSessionID) === entry) children.delete(entry.childSessionID);
960
+ if (children.size === 0) byParent.delete(entry.parentSessionID);
961
+ }
962
+
963
+ function insert(entry: HoldEntry): void {
964
+ let children = byParent.get(entry.parentSessionID);
965
+ if (children === undefined) {
966
+ children = new Map();
967
+ byParent.set(entry.parentSessionID, children);
968
+ }
969
+ children.set(entry.childSessionID, entry);
970
+ byHandle.set(entry.handle, entry);
971
+ }
972
+
973
+ /** Makes room for one more hold by evicting released holds, oldest first; false when only active holds remain. */
974
+ function makeRoom(parent: string): boolean {
975
+ const evict = (limit: number, count: () => number, pool: Iterable<HoldEntry>): boolean => {
976
+ if (count() < limit) return true;
977
+ for (const e of [...pool]) {
978
+ if (count() < limit) return true;
979
+ if (!e.active && !e.posting) remove(e);
980
+ }
981
+ return count() < limit;
982
+ };
983
+ const perParent = (): number => byParent.get(parent)?.size ?? 0;
984
+ return (
985
+ evict(MAX_HOLDS_PER_PARENT, perParent, byParent.get(parent)?.values() ?? []) &&
986
+ evict(MAX_HOLDS_GLOBAL, () => byHandle.size, byHandle.values())
987
+ );
988
+ }
989
+
990
+ function heldChildren(sessionID: string): HoldEntry[] {
991
+ return [...(byParent.get(sessionID)?.values() ?? [])];
992
+ }
993
+
994
+ function applyText(sessionID: string, text: string): string {
995
+ if (text.startsWith(VERDICT_PREFIX)) return text;
996
+ let out = text;
997
+ for (const entry of heldChildren(sessionID)) {
998
+ const marker = `<subagent sessionID="${entry.childSessionID}"`;
999
+ const placeholder = heldPlaceholder(entry.handle, entry.childSessionID);
1000
+ let from = 0;
1001
+ for (;;) {
1002
+ const at = out.indexOf(marker, from);
1003
+ if (at < 0) break;
1004
+ if (out.startsWith(placeholder, at)) {
1005
+ from = at + placeholder.length;
1006
+ continue;
1007
+ }
1008
+ if (at === 0) {
1009
+ // C2: the part is the whole completion message.
1010
+ out = placeholder;
1011
+ break;
1012
+ }
1013
+ // O13: an embedded record. Cut precisely only when the known body follows verbatim, else through the end.
1014
+ let end = out.length;
1015
+ const tagEnd = out.indexOf(">", at);
1016
+ if (entry.body !== undefined && tagEnd >= 0) {
1017
+ const bodyEnd = tagEnd + 1 + entry.body.length;
1018
+ if (out.startsWith(entry.body, tagEnd + 1) && out.startsWith(SUBAGENT_CLOSE, bodyEnd)) {
1019
+ end = bodyEnd + SUBAGENT_CLOSE.length;
1020
+ }
1021
+ }
1022
+ out = out.slice(0, at) + placeholder + out.slice(end);
1023
+ from = at + placeholder.length;
1024
+ }
1025
+ }
1026
+ return out;
1027
+ }
1028
+
1029
+ async function post(entry: HoldEntry, v: HeldVerdict): Promise<void> {
1030
+ await postText(entry, verdictText(entry.handle, entry.childSessionID, v));
1031
+ }
1032
+
1033
+ /**
1034
+ * QA-2.1-2: deliver one verdict text. The text is journaled with `posting` (so the next start can re-post it, R21),
1035
+ * a journal failure never blocks or repeats the post, and only a failed `synthetic` call is retried.
1036
+ */
1037
+ async function postText(entry: HoldEntry, text: string): Promise<void> {
1038
+ entry.verdictText = text;
1039
+ try {
1040
+ await deps.journal.append({ v: 1, kind: "posting", handle: entry.handle, text, at: now() });
1041
+ } catch (error) {
1042
+ warnSafe(deps.logger, "[router] held verdict posting not journaled; posting anyway", {
1043
+ handle: entry.handle,
1044
+ error: errorText(error),
1045
+ });
1046
+ }
1047
+ let lastError: unknown;
1048
+ let delivered = false;
1049
+ for (let attempt = 0; attempt < SYNTHETIC_ATTEMPTS && !delivered; attempt += 1) {
1050
+ try {
1051
+ observeV2(deps.observations, () => ({ family: "completion-effect", effect: "annotation-delivery", source: "held-synthetic",
1052
+ parentSessionID: entry.parentSessionID, callID: entry.callID, childSessionID: entry.childSessionID, handle: entry.handle }));
1053
+ await deps.synthetic({
1054
+ sessionID: entry.parentSessionID,
1055
+ text,
1056
+ description: "Model router verdict",
1057
+ metadata: { router: { kind: "held-verdict", handle: entry.handle, child: entry.childSessionID } },
1058
+ resume: true,
1059
+ });
1060
+ delivered = true;
1061
+ } catch (error) {
1062
+ lastError = error;
1063
+ if (attempt < SYNTHETIC_ATTEMPTS - 1) await sleep(retryBase * 2 ** attempt);
1064
+ }
1065
+ }
1066
+ if (!delivered) {
1067
+ // Keep `posting`: the next start finds the journal entry and decides again (R21).
1068
+ warnSafe(deps.logger, "[router] held verdict not posted; kept for the next start", {
1069
+ handle: entry.handle,
1070
+ error: errorText(lastError),
1071
+ });
1072
+ return;
1073
+ }
1074
+ entry.active = false;
1075
+ entry.status = "released";
1076
+ entry.childText = undefined;
1077
+ try {
1078
+ await deps.journal.append({ v: 1, kind: "posted", handle: entry.handle, at: now() });
1079
+ } catch (error) {
1080
+ // Never post again for a journal failure: the parent context check at the next start finds the delivered post.
1081
+ warnSafe(deps.logger, "[router] held verdict posted but not journaled", { handle: entry.handle, error: errorText(error) });
1082
+ }
1083
+ }
1084
+
1085
+ /**
1086
+ * QA-2.1-24: the verdict of a hold whose append failed (it settled before or during the append): nothing is held or journaled,
1087
+ * so it is posted once as a plain notice to the parent (the result itself was never withheld). The ack said a verdict
1088
+ * follows; it is never dropped. Only a failed `synthetic` call is retried. Never throws.
1089
+ */
1090
+ async function postUnheld(rec: HeldRecord, v: HeldVerdict): Promise<void> {
1091
+ let lastError: unknown;
1092
+ for (let attempt = 0; attempt < SYNTHETIC_ATTEMPTS; attempt += 1) {
1093
+ try {
1094
+ observeV2(deps.observations, () => ({ family: "completion-effect", effect: "annotation-delivery", source: "unheld-synthetic",
1095
+ parentSessionID: rec.parentSessionID, callID: rec.callID, childSessionID: rec.childSessionID, handle: rec.handle }));
1096
+ await deps.synthetic({
1097
+ sessionID: rec.parentSessionID,
1098
+ text: unheldVerdictText(rec.handle, rec.childSessionID, v),
1099
+ description: "Model router verdict",
1100
+ metadata: { router: { kind: "unheld-verdict", handle: rec.handle, child: rec.childSessionID } },
1101
+ resume: true,
1102
+ });
1103
+ return;
1104
+ } catch (error) {
1105
+ lastError = error;
1106
+ if (attempt < SYNTHETIC_ATTEMPTS - 1) await sleep(retryBase * 2 ** attempt);
1107
+ }
1108
+ }
1109
+ warnSafe(deps.logger, "[router] verdict of a result that could not be held was not posted", {
1110
+ handle: rec.handle,
1111
+ error: errorText(lastError),
1112
+ });
1113
+ }
1114
+
1115
+ /** Delivers one verdict for an entry; waits for an in-flight `hold` append first. Never throws. */
1116
+ async function deliver(entry: HoldEntry, v: HeldVerdict): Promise<void> {
1117
+ if (entry.ready !== undefined && !(await entry.ready)) {
1118
+ // QA-2.1-24: the hold was never journaled, so nothing is held; the verdict that settled meanwhile still reaches the parent.
1119
+ unheld.delete(entry.handle);
1120
+ await postUnheld(entry, v);
1121
+ return;
1122
+ }
1123
+ if (!entry.active || entry.posting) return;
1124
+ entry.posting = true;
1125
+ try {
1126
+ await post(entry, v);
1127
+ } catch (error) {
1128
+ warnSafe(deps.logger, "[router] held verdict post failed", { handle: entry.handle, error: errorText(error) });
1129
+ } finally {
1130
+ entry.posting = false;
1131
+ }
1132
+ }
1133
+
1134
+ return {
1135
+ available: deps.available,
1136
+
1137
+ async hold(rec) {
1138
+ if (!deps.available) throw new Error("holding is not available");
1139
+ if (!makeRoom(rec.parentSessionID)) throw new Error("hold capacity reached");
1140
+ // QA-2.1-2: the entry exists before the fsync; a verdict that settles meanwhile waits for the write instead of being dropped.
1141
+ let settle: (ok: boolean) => void = () => undefined;
1142
+ const entry: HoldEntry = {
1143
+ ...rec,
1144
+ active: true,
1145
+ posting: false,
1146
+ status: "verifying",
1147
+ ready: new Promise<boolean>((resolve) => {
1148
+ settle = resolve;
1149
+ }),
1150
+ };
1151
+ unheld.delete(rec.handle);
1152
+ insert(entry);
1153
+ try {
1154
+ await deps.journal.append(
1155
+ {
1156
+ v: 1,
1157
+ kind: "hold",
1158
+ handle: rec.handle,
1159
+ parent: rec.parentSessionID,
1160
+ child: rec.childSessionID,
1161
+ callID: rec.callID,
1162
+ ...(rec.label === undefined ? {} : { label: rec.label }),
1163
+ ...(rec.childText === undefined ? {} : { text: rec.childText }),
1164
+ ...(rec.dispatch === undefined ? {} : { dispatch: rec.dispatch }),
1165
+ ...(rec.callerAgent === undefined ? {} : { callerAgent: rec.callerAgent }),
1166
+ ...(rec.callerMessageID === undefined ? {} : { callerMessageID: rec.callerMessageID }),
1167
+ at: now(),
1168
+ },
1169
+ { fsync: true },
1170
+ );
1171
+ } catch (error) {
1172
+ entry.active = false;
1173
+ if (byHandle.get(rec.handle) === entry) remove(entry);
1174
+ // QA-2.1-24: a verdict that settled during the append is posted by its `deliver` (it sees `false`); one queued before
1175
+ // `hold` is posted here; one that settles later is posted by `verdict` (the handle is remembered as unheld).
1176
+ unheld.delete(rec.handle);
1177
+ unheld.set(rec.handle, { handle: rec.handle, parentSessionID: rec.parentSessionID, childSessionID: rec.childSessionID, callID: rec.callID });
1178
+ trimMap(unheld, MAX_EARLY_VERDICTS, () => false);
1179
+ settle(false);
1180
+ entry.ready = undefined;
1181
+ const queued = early.get(rec.handle);
1182
+ if (queued !== undefined) {
1183
+ early.delete(rec.handle);
1184
+ unheld.delete(rec.handle);
1185
+ if (now() - queued.at <= EARLY_END_TTL_MS) void postUnheld(rec, queued.v);
1186
+ }
1187
+ throw error;
1188
+ }
1189
+ settle(true);
1190
+ entry.ready = undefined;
1191
+ const queued = early.get(rec.handle);
1192
+ if (queued !== undefined) {
1193
+ early.delete(rec.handle);
1194
+ if (now() - queued.at <= EARLY_END_TTL_MS) void deliver(entry, queued.v);
1195
+ }
1196
+ },
1197
+
1198
+ isHeld(child) {
1199
+ for (const children of byParent.values()) if (children.get(child)?.active === true) return true;
1200
+ return false;
1201
+ },
1202
+
1203
+ placeholder: heldPlaceholder,
1204
+ applyText,
1205
+
1206
+ apply<M>(sessionID: string, messages: readonly M[]): M[] | undefined {
1207
+ if (!byParent.has(sessionID)) return undefined;
1208
+ let changed = false;
1209
+ const out = messages.map((message) => {
1210
+ const next = redactMessage(message, (text) => applyText(sessionID, text));
1211
+ if (next === undefined) return message;
1212
+ changed = true;
1213
+ return next;
1214
+ });
1215
+ return changed ? out : undefined;
1216
+ },
1217
+
1218
+ refusal(sessionID, tool, args) {
1219
+ const active = heldChildren(sessionID).filter((e) => e.active);
1220
+ if (active.length === 0) return undefined;
1221
+ const rec = asRecord(args);
1222
+ if (rec === undefined) return undefined;
1223
+ if (tool === "subagent") {
1224
+ for (const key of ["sessionID", "task_id"]) {
1225
+ const id = rec[key];
1226
+ const hit = typeof id === "string" ? active.find((e) => e.childSessionID === id) : undefined;
1227
+ if (hit !== undefined) return heldRefusalText(hit.childSessionID, hit.handle);
1228
+ }
1229
+ return undefined;
1230
+ }
1231
+ if (tool === "execute" && typeof rec.code === "string") {
1232
+ const code = rec.code;
1233
+ const hit = active.find((e) => code.includes(e.childSessionID));
1234
+ if (hit !== undefined) return heldRefusalText(hit.childSessionID, hit.handle);
1235
+ }
1236
+ return undefined;
1237
+ },
1238
+
1239
+ heldFor(parent) {
1240
+ return heldChildren(parent)
1241
+ .filter((e) => e.active)
1242
+ .map((e) => ({ handle: e.handle, child: e.childSessionID, label: e.label ?? `session ${e.childSessionID}`, status: e.status }));
1243
+ },
1244
+
1245
+ async verdict(handle, v) {
1246
+ const entry = byHandle.get(handle);
1247
+ if (entry === undefined) {
1248
+ // QA-2.1-24: its hold failed: the verdict that settles after the failure is posted as a plain notice too.
1249
+ const failed = unheld.get(handle);
1250
+ if (failed !== undefined) {
1251
+ unheld.delete(handle);
1252
+ await postUnheld(failed, v);
1253
+ return;
1254
+ }
1255
+ // QA-2.1-2: the verdict settled before `hold` inserted the entry; `hold` delivers it.
1256
+ early.delete(handle);
1257
+ early.set(handle, { v, at: now() });
1258
+ trimMap(early, MAX_EARLY_VERDICTS, () => false);
1259
+ return;
1260
+ }
1261
+ await deliver(entry, v);
1262
+ },
1263
+
1264
+ async noteText(handle, text) {
1265
+ const entry = byHandle.get(handle);
1266
+ if (entry === undefined || !entry.active) return;
1267
+ entry.childText = text;
1268
+ entry.body ??= text;
1269
+ try {
1270
+ // QA-2.1-17: written for a succeeded child only (the processor checks the status first); the status is journaled with it.
1271
+ await deps.journal.append({ v: 1, kind: "hold-text", handle, text, status: "succeeded", at: now() }, { fsync: true });
1272
+ } catch (error) {
1273
+ warnSafe(deps.logger, "[router] held child text not journaled", { handle, error: errorText(error) });
1274
+ }
1275
+ },
1276
+
1277
+ forgetSession(sessionID) {
1278
+ for (const entry of heldChildren(sessionID)) {
1279
+ remove(entry);
1280
+ early.delete(entry.handle);
1281
+ }
1282
+ for (const [handle, rec] of unheld) if (rec.parentSessionID === sessionID) unheld.delete(handle);
1283
+ deps.journal.append({ v: 1, kind: "forget", session: sessionID, at: now() }).catch((error: unknown) => {
1284
+ warnSafe(deps.logger, "[router] held forget not journaled", { sessionID, error: errorText(error) });
1285
+ });
1286
+ },
1287
+
1288
+ restore(records) {
1289
+ const restored: HoldEntry[] = [];
1290
+ const postingText = new Map<string, string>();
1291
+ const delivered = new Set<string>();
1292
+ const stored = new Map<string, StoredVerdict>();
1293
+ for (const r of records) {
1294
+ // QA-2.1-17: the verdict a gate reached before the restart (the entry's `verified` state), never posted.
1295
+ if (r.kind === "state" && typeof r.handle === "string" && r.state === "verified") {
1296
+ const verdict = storedVerdictOf(r.verdict);
1297
+ if (verdict !== undefined) stored.set(r.handle, verdict);
1298
+ continue;
1299
+ }
1300
+ if (r.kind === "hold" && typeof r.handle === "string" && typeof r.parent === "string" && typeof r.child === "string") {
1301
+ // A hold this process already knows stays as it is (a second adoption never resets it).
1302
+ if (byHandle.has(r.handle)) continue;
1303
+ const entry: HoldEntry = {
1304
+ handle: r.handle,
1305
+ parentSessionID: r.parent,
1306
+ childSessionID: r.child,
1307
+ callID: typeof r.callID === "string" ? r.callID : "",
1308
+ ...(typeof r.label === "string" ? { label: r.label } : {}),
1309
+ ...(typeof r.text === "string" ? { childText: r.text, body: r.text } : {}),
1310
+ ...(r.dispatch === undefined ? {} : { dispatch: restoredDispatchOf(r.dispatch) }),
1311
+ ...(typeof r.callerAgent === "string" && r.callerAgent !== "" ? { callerAgent: r.callerAgent } : {}),
1312
+ ...(typeof r.callerMessageID === "string" && r.callerMessageID !== "" ? { callerMessageID: r.callerMessageID } : {}),
1313
+ active: true,
1314
+ posting: false,
1315
+ status: "verifying",
1316
+ };
1317
+ insert(entry);
1318
+ restored.push(entry);
1319
+ } else if (r.kind === "hold-text" && typeof r.handle === "string" && typeof r.text === "string"
1320
+ // QA-2.1-17: only a succeeded child's text is gated after a restart (a line without `status` predates the field).
1321
+ && (r.status === undefined || r.status === "succeeded")) {
1322
+ const e = byHandle.get(r.handle);
1323
+ if (e !== undefined && restored.includes(e)) {
1324
+ e.childText = r.text;
1325
+ e.body ??= r.text;
1326
+ }
1327
+ } else if (r.kind === "posting" && typeof r.handle === "string") {
1328
+ if (typeof r.text === "string") postingText.set(r.handle, r.text);
1329
+ } else if (r.kind === "posted" && typeof r.handle === "string") {
1330
+ delivered.add(r.handle);
1331
+ } else if (r.kind === "forget" && typeof r.session === "string") {
1332
+ for (const e of heldChildren(r.session)) remove(e);
1333
+ }
1334
+ }
1335
+ const reposts: RestoredPosting[] = [];
1336
+ const unverified: RestoredHold[] = [];
1337
+ for (const e of restored) {
1338
+ if (byHandle.get(e.handle) !== e) continue;
1339
+ if (delivered.has(e.handle)) {
1340
+ // QA-2.1-10: a posted hold stays as an inactive placeholder (the host history still holds the raw completion).
1341
+ e.active = false;
1342
+ e.status = "released";
1343
+ e.childText = undefined;
1344
+ continue;
1345
+ }
1346
+ const text = postingText.get(e.handle);
1347
+ if (text !== undefined) {
1348
+ e.verdictText = text;
1349
+ e.posting = true;
1350
+ e.status = "posting";
1351
+ reposts.push({ handle: e.handle, parentSessionID: e.parentSessionID, childSessionID: e.childSessionID, text });
1352
+ } else {
1353
+ unverified.push({
1354
+ handle: e.handle,
1355
+ parentSessionID: e.parentSessionID,
1356
+ childSessionID: e.childSessionID,
1357
+ callID: e.callID,
1358
+ ...(e.childText === undefined ? {} : { childText: e.childText }),
1359
+ dispatch: e.dispatch ?? {},
1360
+ ...(e.callerAgent === undefined ? {} : { callerAgent: e.callerAgent }),
1361
+ ...(e.callerMessageID === undefined ? {} : { callerMessageID: e.callerMessageID }),
1362
+ ...(stored.has(e.handle) ? { verdict: stored.get(e.handle) } : {}),
1363
+ });
1364
+ }
1365
+ }
1366
+ return { reposts, unverified };
1367
+ },
1368
+
1369
+ async settleRestored(handle, alreadyPosted) {
1370
+ const entry = byHandle.get(handle);
1371
+ if (entry === undefined || !entry.active) return;
1372
+ if (alreadyPosted) {
1373
+ entry.active = false;
1374
+ entry.posting = false;
1375
+ entry.status = "released";
1376
+ entry.childText = undefined;
1377
+ try {
1378
+ await deps.journal.append({ v: 1, kind: "posted", handle, at: now() });
1379
+ } catch (error) {
1380
+ warnSafe(deps.logger, "[router] held verdict posted but not journaled", { handle, error: errorText(error) });
1381
+ }
1382
+ return;
1383
+ }
1384
+ const text = entry.verdictText;
1385
+ if (text === undefined) return;
1386
+ entry.posting = true;
1387
+ try {
1388
+ await postText(entry, text);
1389
+ } catch (error) {
1390
+ warnSafe(deps.logger, "[router] held verdict re-post failed", { handle, error: errorText(error) });
1391
+ } finally {
1392
+ entry.posting = false;
1393
+ }
1394
+ },
1395
+
1396
+ persisted() {
1397
+ const at = now();
1398
+ const out: PersistedRecord[] = [];
1399
+ for (const e of byHandle.values()) {
1400
+ // A hold whose first append is still in flight (or failed) is not journaled yet: its own append writes it.
1401
+ if (e.ready !== undefined) continue;
1402
+ out.push({
1403
+ v: 1, kind: "hold", handle: e.handle, parent: e.parentSessionID, child: e.childSessionID, callID: e.callID,
1404
+ ...(e.label === undefined ? {} : { label: e.label }),
1405
+ ...(e.dispatch === undefined ? {} : { dispatch: e.dispatch }),
1406
+ ...(e.callerAgent === undefined ? {} : { callerAgent: e.callerAgent }),
1407
+ ...(e.callerMessageID === undefined ? {} : { callerMessageID: e.callerMessageID }),
1408
+ at,
1409
+ });
1410
+ if (!e.active) {
1411
+ out.push({ v: 1, kind: "posted", handle: e.handle, at });
1412
+ continue;
1413
+ }
1414
+ if (e.childText !== undefined) out.push({ v: 1, kind: "hold-text", handle: e.handle, text: e.childText, status: "succeeded", at });
1415
+ if (e.verdictText !== undefined) out.push({ v: 1, kind: "posting", handle: e.handle, text: e.verdictText, at });
1416
+ }
1417
+ return out;
1418
+ },
1419
+ };
1420
+ }
1421
+
1422
+ // ---- completion processor (memo §4.7, §9, §10) --------------------------------------------------
1423
+
1424
+ export type Trigger =
1425
+ | { kind: "end-event"; outcome: EndFact["outcome"]; eventID: string; at: number }
1426
+ | { kind: "completion"; state: "completed" | "error" | "cancelled"; body: string | undefined; at: number }
1427
+ | { kind: "early-end"; end: EndFact }
1428
+ | { kind: "recovery"; outcome: EndFact["outcome"] | "lost"; text: string | undefined; at: number }
1429
+ /** 3.1 (launcher A). */
1430
+ | { kind: "runner"; status: EndFact["outcome"]; text: string; at: number };
1431
+
1432
+ export interface CompletionDeps {
1433
+ observations?: V2Observations;
1434
+ /** `caller` (QA-PDF12-9): the caller journaled on the attempt being finished, for the context the finish runs in. */
1435
+ finish(input: FinishInput, caller: FinishCaller): Promise<FinishResult>;
1436
+ /** The child's last assistant message (`ctx.session.context`, C7/O1). */
1437
+ readChildResult(child: string): Promise<{ outcome?: EndFact["outcome"]; text?: string } | undefined>;
1438
+ /** The `!running` half of `roleAfterCall` (§4.2): budget and authority notices, plus its evictions. */
1439
+ roleCompletion(a: Attempt, text: string): Promise<string[]>;
1440
+ /** Idempotent by holder id. */
1441
+ releaseLeases(holderID: string): void;
1442
+ held: HeldResults;
1443
+ persist: InflightJournal;
1444
+ now(): number;
1445
+ logger: Logger;
1446
+ /** The change set at child end (verify/dispatch.ts `captureDelta`, 2.1.4.b); absent = none. `dispatchID`: `task:<parent>:<callID>`. */
1447
+ captureDelta?(callID: string, child: string, dispatchID?: string): Promise<unknown>;
1448
+ /**
1449
+ * `pending.releaseHandle` (QA-2.1-4): frees the reserved handle of a held attempt that ends without a held register
1450
+ * (failed, interrupted, lost, closed unknown, or a gate that answered at once). Idempotent; a registered entry is kept.
1451
+ */
1452
+ releaseHeld?(handle: string): void;
1453
+ /**
1454
+ * QA-2.1-17: the dispatch data journaled with a recovered attempt's `inflight` record (`FinishApi.dispatchOf` at
1455
+ * acknowledgement); passed to `finish` as `restored` on a recovery. Absent: an empty record (the plugin then ends
1456
+ * UNVERIFIABLE when it has nothing to verify with).
1457
+ */
1458
+ restoredDispatch?(a: Attempt): RestoredDispatch | undefined;
1459
+ }
1460
+
1461
+ export interface CompletedLine {
1462
+ child: string;
1463
+ label: string;
1464
+ /** The annotations, or `router guarantees pending`. */
1465
+ text: string;
1466
+ }
1467
+
1468
+ export interface CompletionProcessor {
1469
+ /** Once per attempt; never throws. */
1470
+ process(childSessionID: string, trigger: Trigger): Promise<void>;
1471
+ /** True when the child's processing finished (or none is due) within `timeoutMs`. */
1472
+ settled(childSessionID: string, timeoutMs: number): Promise<boolean>;
1473
+ /** Synchronous, for the "completed" provider. */
1474
+ completedFor(parent: string): readonly CompletedLine[];
1475
+ /** A root execution end: drops the lines already shown. */
1476
+ endTurn(parent: string): void;
1477
+ forgetSession(sessionID: string): void;
1478
+ /**
1479
+ * Closes an attempt the registry gave up on (`onClosed`: superseded by a resume, or swept after
1480
+ * `ATTEMPT_SWEEP_AGE_MS`): a held result is released as UNVERIFIABLE, the leases end.
1481
+ */
1482
+ closeUnknown(a: Attempt, reason: string): Promise<void>;
1483
+ }
1484
+
1485
+ export const PENDING_GUARANTEES_TEXT = "router guarantees pending";
1486
+
1487
+ /** `<role or agent> "<description>"`, on one line. */
1488
+ export function attemptLabel(a: CallRecord): string {
1489
+ return `${a.role ?? a.agent} "${a.description.replace(/\s+/g, " ").trim()}"`;
1490
+ }
1491
+
1492
+ function addBounded(set: Set<string>, key: string, max: number): void {
1493
+ set.delete(key);
1494
+ set.add(key);
1495
+ for (const old of set) {
1496
+ if (set.size <= max) break;
1497
+ set.delete(old);
1498
+ }
1499
+ }
1500
+
1501
+ function endOf(trigger: Trigger): { status: Attempt["outcome"]; at: number } {
1502
+ switch (trigger.kind) {
1503
+ case "end-event":
1504
+ return { status: trigger.outcome, at: trigger.at };
1505
+ case "early-end":
1506
+ return { status: trigger.end.outcome, at: trigger.end.at };
1507
+ case "completion":
1508
+ return { status: trigger.state === "completed" ? "succeeded" : trigger.state === "error" ? "failed" : "interrupted", at: trigger.at };
1509
+ case "recovery":
1510
+ return { status: trigger.outcome === "lost" ? "unknown" : trigger.outcome, at: trigger.at };
1511
+ case "runner":
1512
+ return { status: trigger.status, at: trigger.at };
1513
+ }
1514
+ }
1515
+
1516
+ function triggerText(trigger: Trigger): string | undefined {
1517
+ if (trigger.kind === "completion") return trigger.body;
1518
+ if (trigger.kind === "runner") return trigger.text;
1519
+ if (trigger.kind === "recovery") return trigger.text;
1520
+ return undefined;
1521
+ }
1522
+
1523
+ /**
1524
+ * Creates the completion processor (memo §4.7). It runs once per attempt (the key is `child\0callID`, §10),
1525
+ * holds nothing back from the registry's state machine, and never throws: a fault is logged and turns into the
1526
+ * annotation `router guarantees failed: <reason>` (§4.7 step 8).
1527
+ */
1528
+ export function createCompletionProcessor(reg: InFlightRegistry, deps: CompletionDeps): CompletionProcessor {
1529
+ const processed = new Set<string>();
1530
+ const settling = new Map<string, Promise<void>>();
1531
+ const turns = new Map<string, number>();
1532
+
1533
+ function turnOf(parent: string): number {
1534
+ return turns.get(parent) ?? 0;
1535
+ }
1536
+
1537
+ function wasProcessed(key: string): boolean {
1538
+ if (processed.has(key)) return true;
1539
+ try {
1540
+ return deps.persist.hasProcessed(key);
1541
+ } catch (error) {
1542
+ warnSafe(deps.logger, "[router] processed-key lookup failed", { error: errorText(error) });
1543
+ return false;
1544
+ }
1545
+ }
1546
+
1547
+ async function journal(record: PersistedRecord, opts?: { fsync?: boolean }): Promise<void> {
1548
+ try {
1549
+ await deps.persist.append(record, opts);
1550
+ } catch (error) {
1551
+ warnSafe(deps.logger, "[router] background journal append failed", { kind: record.kind, error: errorText(error) });
1552
+ }
1553
+ }
1554
+
1555
+ async function markProcessed(a: Attempt): Promise<void> {
1556
+ addBounded(processed, a.key, MAX_PROCESSED_KEYS);
1557
+ await journal({ v: 1, kind: "processed", callID: a.callID, child: a.childSessionID, at: deps.now() });
1558
+ }
1559
+
1560
+ function releaseLeasesSafe(child: string): void {
1561
+ try {
1562
+ deps.releaseLeases(child);
1563
+ } catch (error) {
1564
+ warnSafe(deps.logger, "[router] lease release failed", { child, error: errorText(error) });
1565
+ }
1566
+ }
1567
+
1568
+ async function verdictSafe(handle: string, v: HeldVerdict): Promise<void> {
1569
+ try {
1570
+ await deps.held.verdict(handle, v);
1571
+ } catch (error) {
1572
+ warnSafe(deps.logger, "[router] held verdict failed", { handle, error: errorText(error) });
1573
+ }
1574
+ }
1575
+
1576
+ /** QA-2.1-4: a held attempt that ends without a held register gives its reserved handle back. */
1577
+ function releaseHandleSafe(handle: string): void {
1578
+ try {
1579
+ deps.releaseHeld?.(handle);
1580
+ } catch (error) {
1581
+ warnSafe(deps.logger, "[router] held handle release failed", { handle, error: errorText(error) });
1582
+ }
1583
+ }
1584
+
1585
+ /** QA-2.1-17: the dispatch data journaled with a recovered attempt's `inflight` record; empty when none. Never throws. */
1586
+ function restoredDispatchSafe(a: Attempt): RestoredDispatch {
1587
+ try {
1588
+ return deps.restoredDispatch?.(a) ?? {};
1589
+ } catch (error) {
1590
+ warnSafe(deps.logger, "[router] restored dispatch data unreadable", { callID: a.callID, error: errorText(error) });
1591
+ return {};
1592
+ }
1593
+ }
1594
+
1595
+ async function noteTextSafe(handle: string, text: string): Promise<void> {
1596
+ try {
1597
+ await deps.held.noteText(handle, text);
1598
+ } catch (error) {
1599
+ warnSafe(deps.logger, "[router] held child text not kept", { handle, error: errorText(error) });
1600
+ }
1601
+ }
1602
+
1603
+ /** A held attempt whose verdict was posted has left the hold. */
1604
+ function refresh(a: Attempt): void {
1605
+ if (a.state === "held" && !deps.held.isHeld(a.childSessionID)) a.state = "released";
1606
+ }
1607
+
1608
+ async function readSafe(child: string): Promise<{ outcome?: EndFact["outcome"]; text?: string } | undefined> {
1609
+ try {
1610
+ return await deps.readChildResult(child);
1611
+ } catch (error) {
1612
+ warnSafe(deps.logger, "[router] child result read failed; waiting for the completion", { child, error: errorText(error) });
1613
+ return undefined;
1614
+ }
1615
+ }
1616
+
1617
+ async function body(a: Attempt, trigger: Trigger, ctx: { text?: string }): Promise<void> {
1618
+ const end = endOf(trigger);
1619
+ let text = triggerText(trigger);
1620
+ if (text === undefined && !(trigger.kind === "recovery" && trigger.outcome === "lost")) {
1621
+ const read = await readSafe(a.childSessionID);
1622
+ if (read?.text === undefined) {
1623
+ // Nothing to process yet: wait for the completion trigger (the context-hook wait covers it).
1624
+ warnSafe(deps.logger, "[router] child result not readable yet; waiting for the completion trigger", {
1625
+ child: a.childSessionID,
1626
+ trigger: trigger.kind,
1627
+ readShape: read === undefined ? "undefined" : Object.keys(read).join(","),
1628
+ });
1629
+ a.state = "child-ended";
1630
+ a.endedAt = end.at;
1631
+ a.outcome = end.status;
1632
+ return;
1633
+ }
1634
+ text = read.text;
1635
+ }
1636
+ a.endedAt = end.at;
1637
+ a.outcome = end.status;
1638
+ const handle = a.hold?.handle;
1639
+
1640
+ if (text === undefined) {
1641
+ // Lost across a restart (R18): no result exists, so nothing can be verified.
1642
+ a.annotations = ["[router] the dispatch was lost in a restart"];
1643
+ releaseLeasesSafe(a.childSessionID);
1644
+ await markProcessed(a);
1645
+ if (handle !== undefined) {
1646
+ await verdictSafe(handle, { verdict: "UNVERIFIABLE", text: "[router] not verified: lost in restart", reason: "lost in restart" });
1647
+ releaseHandleSafe(handle);
1648
+ }
1649
+ a.state = handle !== undefined ? "released" : "annotated";
1650
+ return;
1651
+ }
1652
+
1653
+ ctx.text = text;
1654
+ const status = end.status ?? "unknown";
1655
+ // QA-2.1-6: the child text lives in the journal with the hold, so a restart can re-run the gate. QA-2.1-17: only a
1656
+ // succeeded child's text, so a restart never gates a failed or interrupted child.
1657
+ if (handle !== undefined && status === "succeeded") await noteTextSafe(handle, text);
1658
+ let delta: unknown;
1659
+ if (deps.captureDelta !== undefined) {
1660
+ try {
1661
+ // QA-2.1-7: the change-set store keys a dispatch by `task:<parent>:<callID>`; the parent is known here.
1662
+ observeV2(deps.observations, () => ({ family: "completion-effect", effect: "change-set-capture", source: "background-delta",
1663
+ parentSessionID: a.parentSessionID, callID: a.callID, childSessionID: a.childSessionID }));
1664
+ delta = await deps.captureDelta(a.callID, a.childSessionID, `task:${a.parentSessionID}:${a.callID}`);
1665
+ } catch (error) {
1666
+ warnSafe(deps.logger, "[router] change-set capture failed", { callID: a.callID, error: errorText(error) });
1667
+ }
1668
+ }
1669
+ const notices = await deps.roleCompletion(a, text);
1670
+ const holdForGate = status === "succeeded" ? handle : undefined;
1671
+ observeV2(deps.observations, () => ({ family: "completion-effect", effect: "finish-dispatch", source: "background",
1672
+ parentSessionID: a.parentSessionID, callID: a.callID, childSessionID: a.childSessionID }));
1673
+ const result = await deps.finish({
1674
+ callID: a.callID,
1675
+ parentSessionID: a.parentSessionID,
1676
+ childSessionID: a.childSessionID,
1677
+ outputText: text,
1678
+ status,
1679
+ mode: "background",
1680
+ ...(holdForGate === undefined ? {} : { heldHandle: holdForGate }),
1681
+ endedAt: end.at,
1682
+ ...(delta === undefined ? {} : { delta }),
1683
+ // QA-2.1-17: a recovery runs after a restart: the plugin rebuilds the gate inputs from the journaled dispatch.
1684
+ ...(trigger.kind === "recovery" ? { restored: restoredDispatchSafe(a) } : {}),
1685
+ }, {
1686
+ // QA-PDF12-9: the caller comes from the attempt itself, never from a capped call-id lookup a `forgetSession` may clear.
1687
+ ...(a.callerAgent === undefined ? {} : { callerAgent: a.callerAgent }),
1688
+ ...(a.callerMessageID === undefined ? {} : { callerMessageID: a.callerMessageID }),
1689
+ });
1690
+ releaseLeasesSafe(a.childSessionID);
1691
+ await markProcessed(a);
1692
+ a.annotations = [...notices, result.suffix].map((s) => s.trim()).filter((s) => s.length > 0);
1693
+
1694
+ if (handle === undefined) {
1695
+ a.state = "annotated";
1696
+ return;
1697
+ }
1698
+ if (holdForGate !== undefined && result.verification.kind === "held") {
1699
+ // The gate runs behind `finish`; it posts the verdict through the HeldSink when it settles.
1700
+ a.state = "held";
1701
+ refresh(a);
1702
+ return;
1703
+ }
1704
+ // No gate will post for this hold: release it with the verdict the result implies (§4.7 step 7).
1705
+ releaseHandleSafe(handle);
1706
+ const v = result.verification;
1707
+ if (status !== "succeeded") {
1708
+ await verdictSafe(handle, {
1709
+ verdict: "UNVERIFIABLE",
1710
+ text: `${result.outputText}\n[router] not verified: the dispatch ended ${status}`,
1711
+ reason: `the dispatch ended ${status}`,
1712
+ });
1713
+ } else if (v.kind === "required") {
1714
+ await verdictSafe(handle, { verdict: v.verdict, text: result.outputText });
1715
+ } else {
1716
+ await verdictSafe(handle, {
1717
+ verdict: "UNVERIFIABLE",
1718
+ text: `${result.outputText}\n[router] not verified: no verification ran`,
1719
+ reason: "no verification ran",
1720
+ });
1721
+ }
1722
+ a.state = deps.held.isHeld(a.childSessionID) ? "held" : "released";
1723
+ }
1724
+
1725
+ async function fail(a: Attempt, error: unknown, ctx: { text?: string }): Promise<void> {
1726
+ const reason = errorText(error);
1727
+ warnSafe(deps.logger, "[router] completion processing failed", { callID: a.callID, child: a.childSessionID, error: reason });
1728
+ addBounded(processed, a.key, MAX_PROCESSED_KEYS);
1729
+ a.annotations = [`router guarantees failed: ${reason}`];
1730
+ releaseLeasesSafe(a.childSessionID);
1731
+ const handle = a.hold?.handle;
1732
+ if (handle !== undefined) {
1733
+ const shown = ctx.text === undefined ? "" : `${ctx.text}\n`;
1734
+ await verdictSafe(handle, { verdict: "UNVERIFIABLE", text: `${shown}[router] not verified: ${reason}`, reason });
1735
+ releaseHandleSafe(handle);
1736
+ }
1737
+ a.state = deps.held.isHeld(a.childSessionID) ? "held" : handle !== undefined ? "released" : "annotated";
1738
+ }
1739
+
1740
+ async function run(child: string, trigger: Trigger): Promise<void> {
1741
+ // Everything up to the first await is synchronous: the state flip below is what makes a second trigger a no-op.
1742
+ const a = reg.byChild(child);
1743
+ if (a === undefined) {
1744
+ warnSafe(deps.logger, "[router] completion trigger ignored: no attempt for the child", { child, trigger: trigger.kind });
1745
+ return;
1746
+ }
1747
+ if (a.state !== "acknowledged" && a.state !== "child-ended") {
1748
+ warnSafe(deps.logger, "[router] completion trigger ignored: attempt not open", { child, trigger: trigger.kind, state: a.state });
1749
+ return;
1750
+ }
1751
+ if (wasProcessed(a.key)) {
1752
+ warnSafe(deps.logger, "[router] completion trigger ignored: already processed", { child, trigger: trigger.kind });
1753
+ return;
1754
+ }
1755
+ if (isExecutorOwned(a)) {
1756
+ // 3.1.7 W5: an executor-owned attempt settles only through its launch completion, submitted as a `runner` trigger. It is
1757
+ // marked processed (D2), so a later `execution.*` trigger for it is a duplicate. No result post, verification or lease
1758
+ // release here: the executor owns all three (plan-child leases end with `releaseTask` only).
1759
+ if (trigger.kind !== "runner") return;
1760
+ const end = endOf(trigger);
1761
+ a.endedAt = end.at;
1762
+ a.outcome = end.status;
1763
+ await markProcessed(a);
1764
+ a.state = "released";
1765
+ return;
1766
+ }
1767
+ a.state = "processing";
1768
+ let done: () => void = () => undefined;
1769
+ settling.set(
1770
+ a.key,
1771
+ new Promise<void>((resolve) => {
1772
+ done = resolve;
1773
+ }),
1774
+ );
1775
+ const ctx: { text?: string } = {};
1776
+ try {
1777
+ await body(a, trigger, ctx);
1778
+ } catch (error) {
1779
+ await fail(a, error, ctx);
1780
+ } finally {
1781
+ settling.delete(a.key);
1782
+ done();
1783
+ }
1784
+ }
1785
+
1786
+ return {
1787
+ async process(childSessionID, trigger) {
1788
+ try {
1789
+ await run(childSessionID, trigger);
1790
+ } catch (error) {
1791
+ warnSafe(deps.logger, "[router] completion processor failed", { child: childSessionID, error: errorText(error) });
1792
+ }
1793
+ },
1794
+
1795
+ async settled(childSessionID, timeoutMs) {
1796
+ const a = reg.byChild(childSessionID);
1797
+ if (a === undefined) return true;
1798
+ const gate = settling.get(a.key);
1799
+ if (gate === undefined) return a.state !== "acknowledged" && a.state !== "child-ended";
1800
+ let timer: ReturnType<typeof setTimeout> | undefined;
1801
+ const timeout = new Promise<boolean>((resolve) => {
1802
+ timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));
1803
+ });
1804
+ try {
1805
+ return await Promise.race([gate.then(() => a.state !== "child-ended"), timeout]);
1806
+ } finally {
1807
+ if (timer !== undefined) clearTimeout(timer);
1808
+ }
1809
+ },
1810
+
1811
+ completedFor(parent) {
1812
+ const turn = turnOf(parent);
1813
+ const lines: Array<{ at: number; line: CompletedLine; attempt: Attempt; annotated: boolean }> = [];
1814
+ for (const a of reg.listForParent(parent)) {
1815
+ refresh(a);
1816
+ const at = a.endedAt ?? a.at;
1817
+ const line = (text: string): CompletedLine => ({ child: a.childSessionID, label: attemptLabel(a), text });
1818
+ if (a.state === "child-ended" || a.state === "processing") {
1819
+ a.pendingShown = true;
1820
+ lines.push({ at, line: line(PENDING_GUARANTEES_TEXT), attempt: a, annotated: false });
1821
+ } else if (a.state === "annotated" || (a.state === "closed-unknown" && a.annotations.length > 0)) {
1822
+ if (a.shownInTurn !== undefined && a.shownInTurn !== turn) continue;
1823
+ a.shownInTurn = turn;
1824
+ const text = a.annotations.join(" ").replace(/\s+/g, " ").trim();
1825
+ lines.push({ at, line: line(text.length > 0 ? text : "completed"), attempt: a, annotated: true });
1826
+ }
1827
+ }
1828
+ lines.sort((x, y) => x.at - y.at);
1829
+ return lines.slice(-MAX_COMPLETED_PER_PARENT).map((l) => {
1830
+ // Only returned annotations, never the lines dropped by the provider's cap or a pending placeholder.
1831
+ if (l.annotated) observeV2(deps.observations, () => ({ family: "completion-effect", effect: "annotation-delivery", source: "completed-provider",
1832
+ parentSessionID: l.attempt.parentSessionID, callID: l.attempt.callID, childSessionID: l.attempt.childSessionID }));
1833
+ return l.line;
1834
+ });
1835
+ },
1836
+
1837
+ endTurn(parent) {
1838
+ for (const a of reg.listForParent(parent)) {
1839
+ if (a.state === "annotated" && a.shownInTurn !== undefined) a.state = "released";
1840
+ refresh(a);
1841
+ }
1842
+ turns.delete(parent);
1843
+ turns.set(parent, turnOf(parent) + 1);
1844
+ trimMap(turns, MAX_COMPLETED_PARENTS, () => false);
1845
+ },
1846
+
1847
+ forgetSession(sessionID) {
1848
+ turns.delete(sessionID);
1849
+ },
1850
+
1851
+ async closeUnknown(a, reason) {
1852
+ try {
1853
+ addBounded(processed, a.key, MAX_PROCESSED_KEYS);
1854
+ // 3.1.7 W3/W5: a plan child's leases are `until-integrated`: the executor releases them (`releaseTask`), never its end.
1855
+ if (isExecutorOwned(a)) return;
1856
+ a.annotations = [`[router] the dispatch ended without a result (${reason})`];
1857
+ releaseLeasesSafe(a.childSessionID);
1858
+ const handle = a.hold?.handle;
1859
+ if (handle !== undefined && deps.held.isHeld(a.childSessionID)) {
1860
+ await verdictSafe(handle, { verdict: "UNVERIFIABLE", text: `[router] not verified: ${reason}`, reason });
1861
+ }
1862
+ if (handle !== undefined) releaseHandleSafe(handle);
1863
+ } catch (error) {
1864
+ warnSafe(deps.logger, "[router] closing an attempt failed", { callID: a.callID, error: errorText(error) });
1865
+ }
1866
+ },
1867
+ };
1868
+ }
1869
+
1870
+ // ---- turn-state providers: pure renderers (memo §13; registration is 2.1.5) -----------------------
1871
+
1872
+ /** Provider order of the three background providers (`late` 10, `pending` 20, `route-hint` 90 stay). */
1873
+ export const PROVIDER_ORDER = { completed: 30, held: 40, inFlight: 50 } as const;
1874
+
1875
+ /** `completed` (order 30): the lines of attempts that ended since the orchestrator's last turn. */
1876
+ export function renderCompleted(lines: readonly CompletedLine[]): string | undefined {
1877
+ if (lines.length === 0) return undefined;
1878
+ return [
1879
+ "[router] Completed since your last turn:",
1880
+ ...lines.map((l) => `- ${l.label} (${l.child}): ${l.text}`),
1881
+ ].join("\n");
1882
+ }
1883
+
1884
+ /** `held` (order 40): results the orchestrator may not use before their verdict. */
1885
+ export function renderHeld(items: readonly HeldEntryView[]): string | undefined {
1886
+ if (items.length === 0) return undefined;
1887
+ return [
1888
+ "[router] Held for verification — not usable until the verdict:",
1889
+ ...items.map((h) => `- ${h.label} (${h.child}) ${h.handle}: ${h.status}`),
1890
+ ].join("\n");
1891
+ }
1892
+
1893
+ /** `in-flight` (order 50): background dispatches that have not ended. `now` is epoch ms. */
1894
+ export function renderInFlight(attempts: readonly Attempt[], now: number): string | undefined {
1895
+ // 3.1.7 W5: plan children are the executor's (the `plan` provider shows them), not background dispatches of the orchestrator.
1896
+ const live = attempts.filter((a) => a.state === "acknowledged" && !isExecutorOwned(a));
1897
+ if (live.length === 0) return undefined;
1898
+ return [
1899
+ `[router] In flight (background): ${live.length}`,
1900
+ ...live.map((a) => {
1901
+ const minutes = Math.max(0, Math.floor((now - (a.ackAt ?? a.at)) / 60_000));
1902
+ return `- ${attemptLabel(a)} (${a.childSessionID}) — ${minutes} min`;
1903
+ }),
1904
+ "Do not report the task done while dispatches are listed here.",
1905
+ ].join("\n");
1906
+ }
1907
+
1908
+ // ---- leases (memo §14; a process-wide registry over Phase 1.3) ---------------------------------------
1909
+
1910
+ export interface LeaseRegistryHandle {
1911
+ registry: LeaseRegistry;
1912
+ /** Subscribes to lease releases (verification deferral wakes on them); returns the unsubscribe. */
1913
+ onRelease(cb: () => void): () => void;
1914
+ /** Tells the subscribers a release happened (event loop, after `releaseChild`). */
1915
+ notifyReleased(): void;
1916
+ /** Drops this holder's reference; the last release discards the shared registry. */
1917
+ release(): Promise<void>;
1918
+ }
1919
+
1920
+ interface SharedLeases {
1921
+ registry: LeaseRegistry;
1922
+ listeners: Set<() => void>;
1923
+ refs: number;
1924
+ logger: Logger;
1925
+ initializing: boolean;
1926
+ }
1927
+
1928
+ interface SharedLeaseRegistries {
1929
+ readonly version: 1;
1930
+ readonly registries: Map<string, unknown>;
1931
+ }
1932
+
1933
+ /** Versioned process state, shared even when plugin instances load separate copies of this module. */
1934
+ const SHARED_LEASES_KEY = Symbol.for("opencode-model-router.leases@1");
1935
+
1936
+ function isSharedLeaseRegistries(value: unknown): value is SharedLeaseRegistries {
1937
+ if (typeof value !== "object" || value === null) return false;
1938
+ const state = value as Partial<SharedLeaseRegistries>;
1939
+ return state.version === 1 && state.registries instanceof Map;
1940
+ }
1941
+
1942
+ /** Validate each entry independently: a malformed neighbour must not replace a live registry or replay its snapshot. */
1943
+ function isSharedLeases(value: unknown): value is SharedLeases {
1944
+ if (typeof value !== "object" || value === null) return false;
1945
+ try {
1946
+ const state = value as Partial<SharedLeases>;
1947
+ const registry = state.registry;
1948
+ return state.listeners instanceof Set
1949
+ && typeof state.refs === "number" && Number.isSafeInteger(state.refs)
1950
+ && typeof state.initializing === "boolean" && (state.initializing ? state.refs === 0 : state.refs > 0)
1951
+ && typeof state.logger?.warn === "function"
1952
+ && typeof registry === "object" && registry !== null
1953
+ && ["acquireWrite", "checkRead", "checkRun", "filterSearchResults", "planHolderOf", "release", "releaseTask", "sweep", "snapshot", "restore"]
1954
+ .every(method => typeof Reflect.get(registry, method) === "function");
1955
+ } catch {
1956
+ return false;
1957
+ }
1958
+ }
1959
+
1960
+ function sharedLeaseRegistries(): Map<string, unknown> {
1961
+ const existing: unknown = Reflect.get(globalThis, SHARED_LEASES_KEY);
1962
+ if (isSharedLeaseRegistries(existing)) return existing.registries;
1963
+ const state: SharedLeaseRegistries = { version: 1, registries: new Map() };
1964
+ Reflect.set(globalThis, SHARED_LEASES_KEY, state);
1965
+ return state.registries;
1966
+ }
1967
+
1968
+ /**
1969
+ * Acquires the process-wide lease registry (ref-counted). The first acquirer's seams, run mode and snapshot win.
1970
+ * Initialization is synchronous: no guard can acquire a live lease before restoration completes, and subsequent
1971
+ * adapters never restore over live state (including when the first snapshot was absent or invalid).
1972
+ */
1973
+ export function acquireLeaseRegistry(opts: {
1974
+ runMode: "annotate" | "refuse";
1975
+ seams: LeaseSeams;
1976
+ snapshotPath: string;
1977
+ logger: Logger;
1978
+ /** Optional synchronous loader, called only when creating the shared registry. */
1979
+ loadSnapshot?(): unknown;
1980
+ }): LeaseRegistryHandle {
1981
+ const registries = sharedLeaseRegistries();
1982
+ let shared: SharedLeases;
1983
+ if (registries.has(opts.snapshotPath)) {
1984
+ const existing = registries.get(opts.snapshotPath);
1985
+ // Do not guess whether malformed state still owns live leases. Refuse acquisition without replacing it.
1986
+ if (!isSharedLeases(existing)) throw new Error("lease registry state is invalid");
1987
+ shared = existing;
1988
+ } else {
1989
+ shared = {
1990
+ registry: createLeaseRegistry(opts.seams, { runMode: opts.runMode }),
1991
+ listeners: new Set(),
1992
+ refs: 0,
1993
+ logger: opts.logger,
1994
+ initializing: true,
1995
+ };
1996
+ registries.set(opts.snapshotPath, shared);
1997
+ try {
1998
+ if (opts.loadSnapshot !== undefined) {
1999
+ const restored = shared.registry.restore(opts.loadSnapshot(), { dropCompleteHolders: true });
2000
+ if (!restored.ok) warnSafe(shared.logger, "[router] leases: the snapshot was rejected", { error: restored.message });
2001
+ else if (restored.skipped !== undefined) warnSafe(shared.logger, "[router] leases: snapshot lines skipped on restore", { skipped: restored.skipped });
2002
+ }
2003
+ } catch (error) {
2004
+ if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") warnSafe(shared.logger, "[router] leases: the snapshot could not be restored", { error: String(error) });
2005
+ } finally {
2006
+ shared.initializing = false;
2007
+ }
2008
+ }
2009
+ // A synchronous loader must not re-enter acquisition and expose the registry before its restore.
2010
+ if (shared.initializing) throw new Error("lease registry initialization is already in progress");
2011
+ shared.refs += 1;
2012
+ const state = shared;
2013
+ let released = false;
2014
+ return {
2015
+ registry: state.registry,
2016
+ onRelease(cb) {
2017
+ state.listeners.add(cb);
2018
+ return () => {
2019
+ state.listeners.delete(cb);
2020
+ };
2021
+ },
2022
+ notifyReleased() {
2023
+ for (const cb of [...state.listeners]) {
2024
+ try {
2025
+ cb();
2026
+ } catch (error) {
2027
+ warnSafe(state.logger, "[router] lease release listener failed", { error: errorText(error) });
2028
+ }
2029
+ }
2030
+ },
2031
+ async release() {
2032
+ if (released) return;
2033
+ released = true;
2034
+ state.refs -= 1;
2035
+ if (state.refs <= 0 && registries.get(opts.snapshotPath) === state) registries.delete(opts.snapshotPath);
2036
+ },
2037
+ };
2038
+ }
2039
+
2040
+ /** Observes an existing, initialized registry without creating one or extending its lifetime. */
2041
+ export function peekLeaseRegistry(snapshotPath: string): LeaseRegistry | undefined {
2042
+ const state: unknown = Reflect.get(globalThis, SHARED_LEASES_KEY);
2043
+ if (!isSharedLeaseRegistries(state)) return undefined;
2044
+ const shared = state.registries.get(snapshotPath);
2045
+ return isSharedLeases(shared) && !shared.initializing ? shared.registry : undefined;
2046
+ }
2047
+
2048
+ export interface LeaseGuard {
2049
+ /** Before a file / git / run tool call: a refusal text, and/or a note to append to a run's result. */
2050
+ before(e: { sessionID: string; tool: string; args: unknown; callID: string }): Promise<{ refuse?: string; runNote?: string }>;
2051
+ /** After a host `glob`/`grep` of a child session: the filtered result plus one note line; `undefined` = unchanged. */
2052
+ /**
2053
+ * `e.result` is the host's `execute.after` result of a `glob`/`grep` call, exactly as received: `content` is a string or an array
2054
+ * of `{type:"text", text}` parts (the model-facing text, one hit per line), and `output` is the structured form (a string, an
2055
+ * object with a string `output`, or an array of hits: a path string, `{path}` or `{entry:{path}}`). Returns the rewritten host
2056
+ * result (both forms filtered together) plus one note line, or `undefined` when nothing is omitted.
2057
+ */
2058
+ afterSearch(e: { sessionID: string; tool: "glob" | "grep"; result: unknown }): { result: unknown; note?: string } | undefined;
2059
+ /** Until-complete leases only; until-integrated ones are retained (leases.ts §5). */
2060
+ releaseChild(child: string): void;
2061
+ /** Waits until no other holder edits `tree` (or the deadline); never throws. */
2062
+ waitTreeFree(
2063
+ tree: string,
2064
+ owner: { producer: string; taskRef?: string },
2065
+ deadlineMs: number,
2066
+ signal: AbortSignal,
2067
+ ): Promise<{ waitedMs: number; holders: string[]; fileCount: number }>;
2068
+ }
2069
+
2070
+ export interface LeaseGuardDeps {
2071
+ registry: LeaseRegistry;
2072
+ /** `unknown` (or a rejection): the kind could not be read; root semantics, child wording (QA-2.1-11). */
2073
+ sessionKind(sid: string): Promise<"root" | "child" | "unknown">;
2074
+ sessionDir(sid: string): Promise<string>;
2075
+ gitRootOf(dir: string): string | undefined;
2076
+ holderLabel(holderID: string): string;
2077
+ /** Seam; `undefined` in 2.1 (filled in by 3.1). */
2078
+ planTaskOf(sid: string): { planId: string; taskId: string; slot: string } | undefined;
2079
+ events: { onRelease(cb: () => void): () => void };
2080
+ logger?: Logger;
2081
+ now?(): number;
2082
+ }
2083
+
2084
+ const TREE_POLL_MS = 5000;
2085
+ /** Bound of one host lookup (session kind / directory) made from inside a tool hook. */
2086
+ const LOOKUP_TIMEOUT_MS = 5000;
2087
+ const MAX_ACTOR_CACHE = 1000;
2088
+ /**
2089
+ * QA-2.1-11: a failed session-directory lookup is not repeated for this long. QA-2.1-25: short, because the failure means no
2090
+ * lease check and no lease for the call (a child's write goes unguarded); the window only spares a burst of tool calls.
2091
+ */
2092
+ export const LEASE_LOOKUP_NEGATIVE_TTL_MS = 2_000;
2093
+ /** QA-2.1-13: warn-once keys remembered. */
2094
+ const MAX_WARNED_KEYS = 1000;
2095
+
2096
+ /** A resolved lease actor (QA-2.1-11: `childWording` = the kind is child, or unknown). */
2097
+ interface Actor {
2098
+ kind: "root" | "child";
2099
+ tree: string;
2100
+ dir: string;
2101
+ childWording: boolean;
2102
+ }
2103
+
2104
+ /** The task reference of a plan task (the owner of the leases of its slot); = `leaseTaskRef` (executor/types.ts:1446). */
2105
+ function planTaskRef(planId: string, taskId: string): string {
2106
+ return `${planId}:${taskId}`;
2107
+ }
2108
+
2109
+ function holderLabels(deps: LeaseGuardDeps, holders: readonly Holder[]): string {
2110
+ return holders.map((h) => deps.holderLabel(h.holderID)).join(", ");
2111
+ }
2112
+
2113
+ /** The entry of a search result line that names a file. */
2114
+ function searchEntryPath(tool: "glob" | "grep", line: string): string {
2115
+ if (tool === "glob") return line.trim();
2116
+ const match = /^((?:[A-Za-z]:)?[^:]+?):\d+[:-]/.exec(line);
2117
+ return match === null ? line.trim() : (match[1] ?? line.trim());
2118
+ }
2119
+
2120
+ /**
2121
+ * Creates the lease guard (memo §14): maps tool calls to registry calls and registry answers to the router's
2122
+ * refusal texts. Roots take no lease; a failed session-kind lookup means root semantics.
2123
+ */
2124
+ export function createLeaseGuard(deps: LeaseGuardDeps): LeaseGuard {
2125
+ /** QA-2.1-11: resolved actors, cached per session (bounded); an actor whose kind lookup failed is not cached (retried). */
2126
+ const actors = new Map<string, Actor>();
2127
+ /** QA-2.1-11: negative cache: a failed directory lookup is not repeated for LEASE_LOOKUP_NEGATIVE_TTL_MS. */
2128
+ const failedLookups = new Map<string, number>();
2129
+ /** QA-2.1-13: bounded (oldest first out), so per-session keys cannot grow it without end. */
2130
+ const warned = new Set<string>();
2131
+ const now = deps.now ?? (() => Date.now());
2132
+
2133
+ function warnOnce(key: string, message: string, meta?: object): void {
2134
+ if (warned.has(key) || deps.logger === undefined) return;
2135
+ addBounded(warned, key, MAX_WARNED_KEYS);
2136
+ warnSafe(deps.logger, message, meta);
2137
+ }
2138
+
2139
+ /** A host lookup that never answers must not hang the tool call it guards (memo §14.1: fall back to root semantics). */
2140
+ async function bounded<T>(lookup: Promise<T>, what: string): Promise<T> {
2141
+ let timer: ReturnType<typeof setTimeout> | undefined;
2142
+ const timeout = new Promise<never>((_resolve, reject) => {
2143
+ timer = setTimeout(() => reject(new Error(`${what} timed out after ${LOOKUP_TIMEOUT_MS} ms`)), LOOKUP_TIMEOUT_MS);
2144
+ });
2145
+ try {
2146
+ return await Promise.race([lookup, timeout]);
2147
+ } finally {
2148
+ if (timer !== undefined) clearTimeout(timer);
2149
+ }
2150
+ }
2151
+
2152
+ async function resolveActor(sessionID: string): Promise<Actor | undefined> {
2153
+ // QA-2.1-11: one host lookup per session, not one per tool call.
2154
+ const cached = actors.get(sessionID);
2155
+ if (cached !== undefined) return cached;
2156
+ const failedAt = failedLookups.get(sessionID);
2157
+ if (failedAt !== undefined && now() - failedAt < LEASE_LOOKUP_NEGATIVE_TTL_MS) return undefined;
2158
+ let kind: "root" | "child" = "root";
2159
+ let kindKnown = true;
2160
+ try {
2161
+ const looked = await bounded(deps.sessionKind(sessionID), "session kind lookup");
2162
+ // QA-2.1-11: a lookup that answers `unknown` (the adapter's own failed or negatively cached lookup) is a failed one.
2163
+ if (looked === "unknown") kindKnown = false;
2164
+ else kind = looked;
2165
+ } catch (error) {
2166
+ kindKnown = false;
2167
+ warnOnce(`kind:${sessionID}`, "[router] lease session kind lookup failed; treating as root", { error: errorText(error) });
2168
+ }
2169
+ let dir: string;
2170
+ try {
2171
+ dir = await bounded(deps.sessionDir(sessionID), "session directory lookup");
2172
+ } catch (error) {
2173
+ failedLookups.delete(sessionID);
2174
+ failedLookups.set(sessionID, now());
2175
+ trimMap(failedLookups, MAX_ACTOR_CACHE, () => false);
2176
+ warnOnce(`dir:${sessionID}`, "[router] lease session directory lookup failed; no lease check", { error: errorText(error) });
2177
+ return undefined;
2178
+ }
2179
+ failedLookups.delete(sessionID);
2180
+ const gitRoot = deps.gitRootOf(dir);
2181
+ // QA-2.1-11: an unknown kind keeps root semantics (no lease taken) but gets the child's wording: it may well be a child.
2182
+ const entry: Actor = { kind, dir, tree: foldKeyPath(gitRoot ?? dir), childWording: kind === "child" || !kindKnown };
2183
+ if (kindKnown) {
2184
+ actors.delete(sessionID);
2185
+ actors.set(sessionID, entry);
2186
+ trimMap(actors, MAX_ACTOR_CACHE, () => false);
2187
+ }
2188
+ return entry;
2189
+ }
2190
+
2191
+ function holderOf(sessionID: string, a: { kind: "root" | "child"; tree: string }): HolderInput {
2192
+ if (a.kind === "root") return { holderID: sessionID, tree: a.tree, isChild: false, scope: "until-complete" };
2193
+ const task = deps.planTaskOf(sessionID);
2194
+ if (task === undefined) return { holderID: sessionID, tree: a.tree, isChild: true, scope: "until-complete" };
2195
+ return {
2196
+ holderID: sessionID,
2197
+ tree: foldKeyPath(task.slot),
2198
+ isChild: true,
2199
+ taskRef: planTaskRef(task.planId, task.taskId),
2200
+ scope: "until-integrated",
2201
+ };
2202
+ }
2203
+
2204
+ function actorOf(h: HolderInput): LeaseActor {
2205
+ return h.taskRef === undefined
2206
+ ? { holderID: h.holderID, tree: h.tree, isChild: h.isChild }
2207
+ : { holderID: h.holderID, tree: h.tree, isChild: h.isChild, taskRef: h.taskRef };
2208
+ }
2209
+
2210
+ return {
2211
+ async before(e) {
2212
+ try {
2213
+ const a = await resolveActor(e.sessionID);
2214
+ if (a === undefined) return {};
2215
+ const gitRoot = deps.gitRootOf(a.dir);
2216
+ const targets = toolTargets(e.tool, e.args, a.dir, gitRoot === undefined ? undefined : { gitRoot });
2217
+ const holder = holderOf(e.sessionID, a);
2218
+ const registry = deps.registry;
2219
+
2220
+ if (targets.access !== "write" && targets.gitRootRequired === true) {
2221
+ // A git call with no known git root names no concrete target: an unknown target (leases.ts handoffs). Outside any
2222
+ // repository the registry cannot scope the check to one, so a child is refused while any other holder has leases.
2223
+ if (!holder.isChild) return {};
2224
+ const snapshot = registry.snapshot();
2225
+ const others = snapshot.holders.filter((h) => h.holderID !== holder.holderID && snapshot.leases.some((l) => l.holderID === h.holderID));
2226
+ if (others.length === 0) return {};
2227
+ return {
2228
+ refuse: `[router] Refused: this ${e.tool} call names no file the router can check, and ${holderLabels(deps, others)} is editing files in this repository. Pass the file path explicitly, or return \`NEED MORE: lease ${holder.tree}\`.`,
2229
+ };
2230
+ }
2231
+
2232
+ if (targets.access === "write") {
2233
+ const known = targets.paths.length > 0 && targets.gitRootRequired !== true;
2234
+ const r = registry.acquireWrite(holder, known ? targets.paths : null);
2235
+ if (r.ok) return {};
2236
+ if (r.reason === "held") {
2237
+ const who = holderLabels(deps, r.holders);
2238
+ // QA-PDF13-7: the text names the file under edit (`heldPath`, the holder's copy); the `NEED MORE: lease` names the
2239
+ // requester's own path (`path`, repo-relative for a plan task, as the plan runtime resolves it).
2240
+ if (!holder.isChild && !a.childWording) return { refuse: `[router] Refused: ${r.heldPath} is being edited by ${who}. Wait for that session to end.` };
2241
+ return {
2242
+ refuse: `[router] Refused: ${r.heldPath} is being edited by ${who}. Finish without that file, or return \`NEED MORE: lease ${r.path}\`. Do not retry: the lease ends when that session ends.`,
2243
+ };
2244
+ }
2245
+ if (r.reason === "unknown-target") {
2246
+ // DF-1.1-4: an unknown target is checked in the writer's checkout, a plan task's across the repository; a spelling
2247
+ // that may name any file fails closed against every holder (QA-PDF13-10).
2248
+ const place = r.where === "anywhere" ? "anywhere (this path may name any file)" : `in this ${r.where}`;
2249
+ return {
2250
+ refuse: `[router] Refused: this ${e.tool} call names no file the router can check, and ${holderLabels(deps, r.holders)} is editing files ${place}. Pass the file path explicitly, or return \`NEED MORE: lease ${holder.tree}\`.`,
2251
+ };
2252
+ }
2253
+ if (r.reason === "cap") {
2254
+ return { refuse: `[router] Refused: too many files are leased (${r.limit}). Return \`NEED MORE: lease ${targets.paths[0] ?? holder.tree}\`.` };
2255
+ }
2256
+ // invalid-holder: writes fail closed.
2257
+ warnOnce(`invalid:${e.sessionID}`, "[router] lease holder invalid; writes are refused", { message: r.message });
2258
+ return { refuse: `[router] Refused: the lease registry rejected this session (${r.message}).` };
2259
+ }
2260
+
2261
+ if (targets.access === "read") {
2262
+ const actor = actorOf(holder);
2263
+ for (const path of targets.paths) {
2264
+ const r = registry.checkRead(actor, path);
2265
+ if (r.ok) continue;
2266
+ if (r.reason === "underEdit") {
2267
+ return {
2268
+ refuse: `[router] Refused: ${r.path} is under edit by ${holderLabels(deps, r.holders)}. Finish without it, or return \`NEED MORE: lease ${r.path}\`.`,
2269
+ };
2270
+ }
2271
+ warnOnce(`invalid:${e.sessionID}`, "[router] lease holder invalid; reads are allowed", { message: r.message });
2272
+ }
2273
+ return {};
2274
+ }
2275
+
2276
+ if (targets.access === "run") {
2277
+ const tree = targets.roots[0] === undefined ? a.tree : foldKeyPath(targets.roots[0]);
2278
+ const r = registry.checkRun(actorOf(holder), tree);
2279
+ if (r.ok) {
2280
+ if ("contaminatedBy" in r) {
2281
+ return { runNote: formatRunNote(r.contaminatedBy.map((h) => deps.holderLabel(h.holderID)), r.fileCount) };
2282
+ }
2283
+ return {};
2284
+ }
2285
+ if (r.reason === "run-refused") {
2286
+ return {
2287
+ refuse: `[router] Refused: router_run in ${tree} while ${holderLabels(deps, r.holders)} edits ${r.fileCount} file(s) there. Wait for that session to end, or return \`NEED MORE: lease ${tree}\`.`,
2288
+ };
2289
+ }
2290
+ warnOnce(`invalid:${e.sessionID}`, "[router] lease holder invalid; runs are allowed", { message: r.message });
2291
+ return {};
2292
+ }
2293
+ return {};
2294
+ } catch (error) {
2295
+ // The guard must never block the orchestrator because of its own fault.
2296
+ warnOnce("before-fault", "[router] lease guard failed; call allowed", { error: errorText(error) });
2297
+ return {};
2298
+ }
2299
+ },
2300
+
2301
+ afterSearch(e) {
2302
+ try {
2303
+ const a = actors.get(e.sessionID);
2304
+ if (a === undefined || a.kind !== "child") return undefined;
2305
+ const actor = actorOf(holderOf(e.sessionID, a));
2306
+ /** Filters `items` by the path each names; an item naming no path is always kept. */
2307
+ const filterBy = <T,>(items: readonly T[], pathOf: (item: T) => string | undefined): { kept: T[]; omitted: number; label: string } | undefined => {
2308
+ const paths = items.map(pathOf);
2309
+ const named = paths.filter((p): p is string => p !== undefined);
2310
+ const r = deps.registry.filterSearchResults(actor, actor.tree, named);
2311
+ if (r.omitted === 0) return undefined;
2312
+ const left = new Map<string, number>();
2313
+ for (const p of r.kept) left.set(p, (left.get(p) ?? 0) + 1);
2314
+ const kept = items.filter((_, i) => {
2315
+ const p = paths[i];
2316
+ if (p === undefined) return true;
2317
+ const n = left.get(p) ?? 0;
2318
+ if (n === 0) return false;
2319
+ left.set(p, n - 1);
2320
+ return true;
2321
+ });
2322
+ return { kept, omitted: r.omitted, label: holderLabels(deps, r.holders) };
2323
+ };
2324
+ const noteOf = (omitted: number, label: string): string => `[router] ${omitted} result(s) omitted: under edit by ${label}.`;
2325
+ // Plain text or a list of lines (callers that already extracted the text).
2326
+ if (typeof e.result === "string") {
2327
+ const f = filterBy(e.result.split("\n"), (line) => searchEntryPath(e.tool, line));
2328
+ return f === undefined ? undefined : { result: f.kept.join("\n"), note: noteOf(f.omitted, f.label) };
2329
+ }
2330
+ if (Array.isArray(e.result) && e.result.every((x: unknown) => typeof x === "string")) {
2331
+ const f = filterBy(e.result as string[], (line) => searchEntryPath(e.tool, line));
2332
+ return f === undefined ? undefined : { result: f.kept, note: noteOf(f.omitted, f.label) };
2333
+ }
2334
+ // The host's `execute.after` result: `content` (text or text parts) and `output` (text, `{output}` or an array of hits).
2335
+ const host = asRecord(e.result);
2336
+ if (host === undefined || (!("content" in host) && !("output" in host))) return undefined;
2337
+ let omitted = 0;
2338
+ let label = "";
2339
+ const lines = (text: string): string => {
2340
+ const f = filterBy(text.split("\n"), (line) => searchEntryPath(e.tool, line));
2341
+ if (f === undefined) return text;
2342
+ if (f.omitted > omitted) { omitted = f.omitted; label = f.label; }
2343
+ return f.kept.join("\n");
2344
+ };
2345
+ const next: Record<string, unknown> = { ...host };
2346
+ const content = host.content;
2347
+ if (typeof content === "string") next.content = lines(content);
2348
+ else if (Array.isArray(content)) {
2349
+ next.content = content.map((part: unknown) => {
2350
+ const p = asRecord(part);
2351
+ if (p === undefined || typeof p.text !== "string" || (p.type !== undefined && p.type !== "text")) return part;
2352
+ const text = lines(p.text);
2353
+ return text === p.text ? part : { ...p, text };
2354
+ });
2355
+ }
2356
+ const output = host.output;
2357
+ if (typeof output === "string") next.output = lines(output);
2358
+ else if (Array.isArray(output)) {
2359
+ const f = filterBy(output as unknown[], (item) => {
2360
+ if (typeof item === "string") return item;
2361
+ const rec = asRecord(item);
2362
+ const entry = asRecord(rec?.entry);
2363
+ const path = entry?.path ?? rec?.path;
2364
+ return typeof path === "string" ? path : undefined;
2365
+ });
2366
+ if (f !== undefined) {
2367
+ next.output = f.kept;
2368
+ if (f.omitted > omitted) { omitted = f.omitted; label = f.label; }
2369
+ }
2370
+ } else {
2371
+ const wrapped = asRecord(output);
2372
+ if (wrapped !== undefined && typeof wrapped.output === "string") next.output = { ...wrapped, output: lines(wrapped.output) };
2373
+ }
2374
+ return omitted === 0 ? undefined : { result: next, note: noteOf(omitted, label) };
2375
+ } catch (error) {
2376
+ warnOnce("search-fault", "[router] lease search filter failed; result unchanged", { error: errorText(error) });
2377
+ return undefined;
2378
+ }
2379
+ },
2380
+
2381
+ releaseChild(child) {
2382
+ try {
2383
+ deps.registry.release(child);
2384
+ } catch (error) {
2385
+ warnOnce("release-fault", "[router] lease release failed", { error: errorText(error) });
2386
+ }
2387
+ actors.delete(child);
2388
+ },
2389
+
2390
+ async waitTreeFree(tree, owner, deadlineMs, signal) {
2391
+ const started = now();
2392
+ const actor: LeaseActor =
2393
+ owner.taskRef === undefined
2394
+ ? { holderID: `verify:${owner.producer}`, tree, isChild: true }
2395
+ : { holderID: `verify:${owner.producer}`, tree, isChild: true, taskRef: owner.taskRef };
2396
+ let holders: string[] = [];
2397
+ let fileCount = 0;
2398
+ const probe = (): boolean => {
2399
+ try {
2400
+ const r = deps.registry.checkRun(actor, tree);
2401
+ if (r.ok && !("contaminatedBy" in r)) return true;
2402
+ if (r.ok) {
2403
+ holders = r.contaminatedBy.map((h) => h.holderID);
2404
+ fileCount = r.fileCount;
2405
+ return false;
2406
+ }
2407
+ if (r.reason === "run-refused") {
2408
+ holders = r.holders.map((h) => h.holderID);
2409
+ fileCount = r.fileCount;
2410
+ return false;
2411
+ }
2412
+ return true;
2413
+ } catch (error) {
2414
+ warnOnce("wait-fault", "[router] lease wait probe failed; not waiting", { error: errorText(error) });
2415
+ return true;
2416
+ }
2417
+ };
2418
+ while (!probe()) {
2419
+ const left = deadlineMs - (now() - started);
2420
+ if (left <= 0 || signal.aborted) break;
2421
+ await new Promise<void>((resolve) => {
2422
+ let unsubscribe: () => void = () => undefined;
2423
+ let timer: ReturnType<typeof setTimeout> | undefined;
2424
+ const done = (): void => {
2425
+ if (timer !== undefined) clearTimeout(timer);
2426
+ unsubscribe();
2427
+ signal.removeEventListener("abort", done);
2428
+ resolve();
2429
+ };
2430
+ unsubscribe = deps.events.onRelease(done);
2431
+ signal.addEventListener("abort", done);
2432
+ timer = setTimeout(done, Math.min(left, TREE_POLL_MS));
2433
+ });
2434
+ }
2435
+ if (!probe()) return { waitedMs: now() - started, holders, fileCount };
2436
+ return { waitedMs: now() - started, holders: [], fileCount: 0 };
2437
+ },
2438
+ };
2439
+ }