opencode-model-router 1.15.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,826 @@
1
+ import { DEFAULT_IDLE_TTL_MS } from "./idle-sweep";
2
+
3
+ export const MAX_DEPTH_HOPS = 32;
4
+ export const DEPTH_LOOKUP_RETRY_MS = 30_000;
5
+ export const DEFAULT_DEPTH_TIMEOUT_MS = 2_000;
6
+ export const DEFAULT_DEPTH_MAX_ENTRIES = 10_000;
7
+ const MAX_PARENT_LINKS = 4;
8
+ const FETCH_BUDGET = 2 * (MAX_DEPTH_HOPS + 1);
9
+
10
+ export interface DepthTrackerSeams {
11
+ getParent(sessionID: string): Promise<string | null>;
12
+ now(): number;
13
+ logger: { warn(msg: string): void };
14
+ }
15
+
16
+ export interface DepthTracker {
17
+ recordRoot(sessionID: string): void;
18
+ recordCreated(sessionID: string, parentID: string | null): void;
19
+ recordPluginChild(sessionID: string, creatorID: string | null): void;
20
+ depthOf(sessionID: string, opts?: { timeoutMs?: number }): Promise<number | undefined>;
21
+ forget(sessionID: string): void;
22
+ sweep(): void;
23
+ /** Tracked sessions, at most `maxEntries`. Ghosts (the remembered links of
24
+ * evicted sessions, at most `maxEntries` more) are not sessions and are not
25
+ * counted. */
26
+ size(): number;
27
+ }
28
+
29
+ interface Node {
30
+ parents: string[];
31
+ depth: number;
32
+ resolved: boolean;
33
+ plugin: boolean;
34
+ rootSeen: boolean;
35
+ pinned: boolean; // carries evidence a backend walk cannot reproduce: never LRU-evicted
36
+ fresh: boolean; // memo is current: no evidence above it changed since it was computed
37
+ gap?: string; // fresh and incomplete: a missing ancestor to fetch
38
+ via?: string; // the parent that gave the depth (the path a read keeps warm)
39
+ lastTouch: number;
40
+ }
41
+ // An evicted node's links, kept so the sweep can cross it (QA-1.2-R3-1).
42
+ interface Ghost {
43
+ parents: string[];
44
+ lastTouch: number; // the node's last touch: a ghost expires like a node
45
+ }
46
+ type LookupResult = { ok: true; node: Node } | { ok: false; reason: string };
47
+ interface Lookup {
48
+ id: string;
49
+ promise: Promise<LookupResult>;
50
+ detached: boolean;
51
+ cancelled: boolean;
52
+ waiters: number; // walks currently awaiting this lookup
53
+ cancel(): void;
54
+ }
55
+ interface Walk {
56
+ id: string;
57
+ promise: Promise<number | undefined>;
58
+ learned: Map<string, Node>;
59
+ pending?: Lookup;
60
+ cancelled: boolean;
61
+ waiters: number; // depthOf callers currently awaiting this walk
62
+ stopped: Promise<undefined>;
63
+ stop(): void;
64
+ }
65
+ interface Done {
66
+ kind: "done";
67
+ depth: number;
68
+ vals: Map<string, number>;
69
+ complete: Set<string>;
70
+ order: string[];
71
+ start: string;
72
+ excess: Set<string>; // complete, with a floor above what its links now derive
73
+ fresh: Set<string>; // finished normally: their values are level-independent
74
+ gaps: Map<string, string>;
75
+ vias: Map<string, string>;
76
+ }
77
+ type Climb = Done | { kind: "need"; id: string };
78
+ type Source = "event" | "backend" | "plugin";
79
+ const validId = (id: unknown): id is string => typeof id === "string" && id !== "";
80
+ const MAX_TIMER_MS = 2_147_483_647;
81
+
82
+ /** Rejection reasons come from the backend seam and may not be printable. */
83
+ function describe(e: unknown): string {
84
+ try {
85
+ return e instanceof Error ? String(e.message) : String(e);
86
+ } catch {
87
+ return "unprintable rejection";
88
+ }
89
+ }
90
+
91
+ /** Options come from JavaScript callers; a throwing getter means "default". */
92
+ function timeoutOf(options: { timeoutMs?: number } | undefined): number {
93
+ try {
94
+ const t = options?.timeoutMs;
95
+ return typeof t === "number" && Number.isFinite(t) && t > 0 ? Math.min(t, MAX_TIMER_MS) : DEFAULT_DEPTH_TIMEOUT_MS;
96
+ } catch {
97
+ return DEFAULT_DEPTH_TIMEOUT_MS;
98
+ }
99
+ }
100
+
101
+ /** Evidence and monotone floors are per tracker, never shared between plugins. */
102
+ export function createDepthTracker(
103
+ seams: DepthTrackerSeams,
104
+ opts: { ttlMs?: number; maxEntries?: number } = {},
105
+ ): DepthTracker {
106
+ const ttlMs = Number.isFinite(opts.ttlMs) && opts.ttlMs! > 0 ? opts.ttlMs! : DEFAULT_IDLE_TTL_MS;
107
+ const maxEntries = Number.isInteger(opts.maxEntries) && opts.maxEntries! >= 1
108
+ ? opts.maxEntries! : DEFAULT_DEPTH_MAX_ENTRIES;
109
+ const lru = new Map<string, Node>(); // Map order IS the LRU list (oldest first)
110
+ const pins = new Map<string, Node>(); // pinned nodes, same recency order, own cap
111
+ const kids = new Map<string, Set<string>>(); // parent id -> tracked nodes linking to it
112
+ const get = (id: string): Node | undefined => lru.get(id) ?? pins.get(id);
113
+ const has = (id: string): boolean => lru.has(id) || pins.has(id);
114
+ // Ghosts (QA-1.2-R3-1): the links of evicted nodes, for the sweep only. Climbs
115
+ // never read them, so they cause no lookup and prove no depth. `held` ghosts
116
+ // have a tracked or ghost child; `loose` ones have none and are dropped first
117
+ // when the ghosts together exceed maxEntries. Each map is oldest first.
118
+ const held = new Map<string, Ghost>();
119
+ const loose = new Map<string, Ghost>();
120
+ const ghostKids = new Map<string, Set<string>>(); // parent id -> ghosts linking to it
121
+ const ghostOf = (id: string): Ghost | undefined => held.get(id) ?? loose.get(id);
122
+ const remembered = (id: string): boolean => has(id) || held.has(id) || loose.has(id);
123
+ const walks = new Map<string, Walk>();
124
+ const lookups = new Map<string, Lookup>();
125
+ const failedAt = new Map<string, number>();
126
+ const warned = new Map<string, number>();
127
+ const live = new Set<Walk>(); // every walk, cancelled or not, until it settles
128
+ const strays = new Map<string, Set<Lookup>>(); // detached lookups until they settle, by id
129
+ const strayOrder = new Set<Lookup>(); // the same lookups, oldest first: FIFO-capped at maxEntries
130
+ let lastNow = 0;
131
+
132
+ // Seams are contained where they are called, so no state change is ever cut
133
+ // short by a throwing clock or logger and no public method throws or rejects.
134
+ function clock(): number {
135
+ try {
136
+ const t = seams.now();
137
+ if (typeof t === "number" && Number.isFinite(t)) lastNow = t;
138
+ } catch {
139
+ return lastNow;
140
+ }
141
+ return lastNow;
142
+ }
143
+
144
+ function say(message: string): boolean {
145
+ try {
146
+ seams.logger.warn(message);
147
+ return true;
148
+ } catch {
149
+ return false;
150
+ }
151
+ }
152
+
153
+ const WARNINGS = {
154
+ lookup: "cannot resolve",
155
+ conflict: "conflicting evidence for",
156
+ evict: "dropping pinned evidence for",
157
+ unlink: "dropping the evicted links of",
158
+ };
159
+
160
+ function warn(id: string, kind: keyof typeof WARNINGS, reason: string): void {
161
+ const key = `${kind}:${id}`;
162
+ if (warned.has(key)) return;
163
+ warned.set(key, clock());
164
+ while (warned.size > maxEntries) warned.delete(warned.keys().next().value!);
165
+ const message = `[router] depth: ${WARNINGS[kind]} session ${id}: ${reason}`;
166
+ // An undelivered warning is not remembered, so a later occurrence retries it.
167
+ if (!say(message)) warned.delete(key);
168
+ }
169
+
170
+ // `kids` and `ghostKids` map a parent id to the nodes or ghosts linking to it;
171
+ // a ghost moves between `held` and `loose` as its first child comes or its
172
+ // last one goes.
173
+ function index(map: Map<string, Set<string>>, parent: string, kid: string): void {
174
+ let set = map.get(parent);
175
+ if (!set) map.set(parent, set = new Set());
176
+ set.add(kid);
177
+ regroup(parent);
178
+ }
179
+
180
+ function unindex(map: Map<string, Set<string>>, parent: string, kid: string): void {
181
+ const set = map.get(parent)!;
182
+ set.delete(kid);
183
+ if (set.size === 0) map.delete(parent);
184
+ regroup(parent);
185
+ }
186
+
187
+ function regroup(id: string): void {
188
+ const g = ghostOf(id);
189
+ if (g === undefined) return;
190
+ const [to, from] = kids.has(id) || ghostKids.has(id) ? [held, loose] : [loose, held];
191
+ if (to.has(id)) return;
192
+ from.delete(id);
193
+ to.set(id, g);
194
+ }
195
+
196
+ const linkKid = (parent: string, kid: string): void => index(kids, parent, kid);
197
+
198
+ // Untracks a node. Its children keep their links and floors; after an eviction
199
+ // or expiry (unlike forget, F4) they lose the frontier memo and so re-resolve
200
+ // the dropped id through the backend instead of trusting a memo that can no
201
+ // longer see conflicts recorded above it. An evicted node with links leaves a
202
+ // ghost; an expired one does not (the sweep found nothing live below it).
203
+ function drop(id: string, why: "evict" | "expire" | "forget"): void {
204
+ const n = get(id)!;
205
+ lru.delete(id);
206
+ pins.delete(id);
207
+ if (why === "evict" && n.parents.length) bury(id, n);
208
+ for (const p of n.parents) unindex(kids, p, id);
209
+ n.fresh = false; // a walk may still hold this object
210
+ if (why !== "forget") for (const kid of kids.get(id) ?? []) get(kid)!.resolved = false;
211
+ invalidate(id);
212
+ }
213
+
214
+ // Remembers an evicted node's links, so that the sweep keeps the ancestors of
215
+ // a live node across it (QA-1.2-R3-1). Ghosts are FIFO-capped at maxEntries,
216
+ // loose ones first: no tracked node depends on them. Dropping a held ghost is
217
+ // logged when a pinned node may lie above it: unless an exact read re-fetches
218
+ // the evicted id first, that pinned evidence can then expire while a tracked
219
+ // descendant is still live.
220
+ function bury(id: string, n: Node): void {
221
+ const g: Ghost = { parents: [...n.parents], lastTouch: n.lastTouch }; // a walk may grow n.parents
222
+ loose.set(id, g);
223
+ for (const p of g.parents) index(ghostKids, p, id);
224
+ regroup(id);
225
+ while (held.size + loose.size > maxEntries) {
226
+ const old = (loose.size ? loose : held).keys().next().value!;
227
+ const above = held.has(old) ? pinnedAbove(ghostOf(old)!.parents) : undefined;
228
+ if (above !== undefined) warn(old, "unlink", `more than ${maxEntries} evicted sessions; ${above} may expire`);
229
+ unbury(old);
230
+ }
231
+ }
232
+
233
+ // Forgets a ghost: its id is tracked again (its own links take over), was
234
+ // forgotten, expired, or was pushed out of the cap.
235
+ function unbury(id: string): void {
236
+ const g = ghostOf(id);
237
+ if (g === undefined) return;
238
+ held.delete(id);
239
+ loose.delete(id);
240
+ for (const p of g.parents) unindex(ghostKids, p, id);
241
+ }
242
+
243
+ // Multi-source BFS over tracked and ghost links, up to MAX_DEPTH_HOPS hops:
244
+ // `hops` (id -> distance, seeded by the caller) gains each remembered ancestor
245
+ // once, at its shortest distance (Map iteration visits entries added during it,
246
+ // in order). Stops early at the first id `stop` accepts.
247
+ function ancestry(hops: Map<string, number>, stop: (id: string) => boolean = () => false): void {
248
+ for (const [id, level] of hops) {
249
+ if (stop(id)) return;
250
+ if (level === MAX_DEPTH_HOPS) continue;
251
+ for (const p of get(id)?.parents ?? ghostOf(id)!.parents) if (!hops.has(p) && remembered(p)) hops.set(p, level + 1);
252
+ }
253
+ }
254
+
255
+ // A pinned node within MAX_DEPTH_HOPS above `links`. The probe visits at most
256
+ // PROBE_BUDGET remembered ids (a bounded cost per dropped ghost); past that it
257
+ // reports a pinned node it could not rule out.
258
+ const PROBE_BUDGET = Math.min(FETCH_BUDGET, maxEntries);
259
+ function pinnedAbove(links: string[]): string | undefined {
260
+ let visited = 0;
261
+ let found: string | undefined;
262
+ ancestry(new Map(links.filter(remembered).map((p): [string, number] => [p, 1])), (id) => {
263
+ if (visited++ === PROBE_BUDGET) found = `a pinned session beyond ${PROBE_BUDGET} probed ancestors`;
264
+ else if (get(id)?.pinned) found = `pinned session ${id}`;
265
+ return found !== undefined;
266
+ });
267
+ return found;
268
+ }
269
+
270
+ // Marks every tracked descendant of `id` stale. Invariant: a stale node has no
271
+ // fresh non-terminal tracked child, so the walk stops at the first stale node.
272
+ // A fresh terminal (MAX) child can sit under a stale parent: its value can no
273
+ // longer change, so it needs no invalidation.
274
+ function invalidate(id: string): void {
275
+ const queue = [id];
276
+ for (let i = 0; i < queue.length; i++) {
277
+ for (const kid of kids.get(queue[i]) ?? []) {
278
+ const k = get(kid)!;
279
+ if (!k.fresh) continue;
280
+ k.fresh = false;
281
+ queue.push(kid);
282
+ }
283
+ }
284
+ }
285
+
286
+ // Evidence on `n` changed in a way that can raise it: its memo and every
287
+ // descendant's memo are stale.
288
+ function changed(id: string, n: Node): void {
289
+ n.fresh = false;
290
+ invalidate(id);
291
+ }
292
+
293
+ // The oldest entry other than `protect`, or `protect` when it is the only one.
294
+ function victim(map: Map<string, Node>, protect: string): string {
295
+ const keys = map.keys();
296
+ const first = keys.next().value!;
297
+ if (first !== protect) return first;
298
+ const second = keys.next();
299
+ return second.done ? first : second.value;
300
+ }
301
+
302
+ // One cap for every node (QA-1.2-R2-3): size() <= maxEntries. Ordinary nodes
303
+ // (backend-reproducible) go first, oldest first; the node a call has just
304
+ // recorded or read goes last of them, so its ancestors go before it and
305
+ // drop() makes it re-resolve them. It goes at all only when pinned nodes fill
306
+ // the cap, after its answer is computed. A pinned node is dropped, with a
307
+ // warning, only when pinned nodes alone exceed the cap (never the current
308
+ // one). Only adopt() adds a node, and every adopt() is followed by a trim in
309
+ // the same synchronous call; pin() moves a node between the maps.
310
+ function trim(protect: string): void {
311
+ while (lru.size + pins.size > maxEntries && lru.size) drop(victim(lru, protect), "evict");
312
+ while (pins.size > maxEntries) {
313
+ const id = victim(pins, protect);
314
+ warn(id, "evict", `more than ${maxEntries} pinned sessions`);
315
+ drop(id, "evict");
316
+ }
317
+ }
318
+
319
+ function pin(id: string, n: Node): void {
320
+ if (n.pinned) return;
321
+ n.pinned = true;
322
+ if (lru.delete(id)) pins.set(id, n);
323
+ }
324
+
325
+ function conflict(id: string, n: Node, reason: string): void {
326
+ warn(id, "conflict", reason);
327
+ pin(id, n);
328
+ }
329
+
330
+ function makeNode(link: string | null, plugin: boolean): Node {
331
+ return {
332
+ parents: link === null ? [] : [link],
333
+ depth: link === null && !plugin ? 0 : 1,
334
+ resolved: link === null,
335
+ plugin,
336
+ rootSeen: link === null && !plugin,
337
+ pinned: plugin,
338
+ fresh: false,
339
+ lastTouch: clock(),
340
+ };
341
+ }
342
+
343
+ // Adds one parent link under the §3 rules.
344
+ function addLink(id: string, n: Node, link: string): void {
345
+ if (n.parents.includes(link)) return;
346
+ if (n.parents.length >= MAX_PARENT_LINKS) {
347
+ n.depth = MAX_DEPTH_HOPS;
348
+ n.resolved = true;
349
+ conflict(id, n, "parent link overflow");
350
+ changed(id, n);
351
+ return;
352
+ }
353
+ if (!n.plugin && (n.rootSeen || n.parents.length)) conflict(id, n, "new parent");
354
+ n.parents.push(link);
355
+ if (get(id) === n) linkKid(link, id);
356
+ n.resolved = false;
357
+ n.depth = Math.max(n.depth, 1);
358
+ changed(id, n);
359
+ }
360
+
361
+ function addRoot(id: string, n: Node): void {
362
+ if (n.plugin) return; // v1 producers have no parentID: root evidence is moot
363
+ if (n.parents.length) conflict(id, n, "root after parent");
364
+ else n.rootSeen = true;
365
+ }
366
+
367
+ // Two objects for one id (a walk's retained copy and a node re-created after
368
+ // eviction) are merged, never replaced: union of links, max of floors, flags.
369
+ function absorb(id: string, into: Node, from: Node): void {
370
+ if (from.plugin && !into.plugin) {
371
+ into.plugin = true;
372
+ pin(id, into);
373
+ into.depth = Math.max(into.depth, 1);
374
+ changed(id, into);
375
+ }
376
+ if (from.rootSeen) addRoot(id, into);
377
+ for (const p of from.parents) addLink(id, into, p);
378
+ if (from.depth > into.depth) {
379
+ into.depth = from.depth;
380
+ changed(id, into);
381
+ }
382
+ into.lastTouch = Math.max(into.lastTouch, from.lastTouch);
383
+ }
384
+
385
+ function mergeInto(map: Map<string, Node>, id: string, n: Node): void {
386
+ const mine = map.get(id);
387
+ if (!mine) map.set(id, n);
388
+ else if (mine !== n) absorb(id, mine, n);
389
+ }
390
+
391
+ // A node entering the map takes over every copy a live walk still holds, so
392
+ // neither side can lose evidence and later readers see the union at once.
393
+ function adopt(id: string, n: Node): void {
394
+ (n.pinned ? pins : lru).set(id, n);
395
+ for (const p of n.parents) linkKid(p, id);
396
+ unbury(id); // tracked again: its own links replace the ghost's
397
+ invalidate(id); // children holding `id` as a gap or frontier must re-climb
398
+ for (const walk of live) {
399
+ const copy = walk.learned.get(id);
400
+ if (copy === undefined || copy === n) continue;
401
+ absorb(id, n, copy);
402
+ walk.learned.set(id, n);
403
+ }
404
+ }
405
+
406
+ // The tracked object for `id`, merged with this climb's retained copy (an
407
+ // untracked id is only ever known through that copy: adopt() unifies copies).
408
+ function node(id: string, learned: Map<string, Node>): Node {
409
+ const tracked = get(id);
410
+ const copy = learned.get(id);
411
+ if (!tracked) return copy!;
412
+ if (copy && copy !== tracked) absorb(id, tracked, copy);
413
+ learned.set(id, tracked);
414
+ return tracked;
415
+ }
416
+
417
+ function applyLink(id: string, link: string | null, source: Source): Node {
418
+ const plugin = source === "plugin";
419
+ const n = get(id);
420
+ if (!n) {
421
+ // Trim only after the floor climb touches this node's ancestors. Trimming
422
+ // here could evict its known parent before deriving the new child's floor.
423
+ const created = makeNode(link, plugin);
424
+ adopt(id, created);
425
+ return created;
426
+ }
427
+ if (plugin && !n.plugin) {
428
+ n.plugin = true;
429
+ pin(id, n);
430
+ n.depth = Math.max(n.depth, 1);
431
+ changed(id, n);
432
+ }
433
+ if (link !== null) addLink(id, n, link);
434
+ else if (!plugin) addRoot(id, n);
435
+ return n;
436
+ }
437
+
438
+ // Each climb is synchronous: no event can interleave with its snapshot. It
439
+ // recurses only into stale nodes and stops at fresh memos (and terminals), so
440
+ // a read whose ancestry is unchanged costs O(links of the start).
441
+ function climb(start: string, learned: Map<string, Node>, mode: "floor"): Done | undefined;
442
+ function climb(start: string, learned: Map<string, Node>, mode: "exact"): Climb;
443
+ function climb(start: string, learned: Map<string, Node>, mode: "exact" | "floor"): Climb | undefined {
444
+ const known = (id: string) => has(id) || learned.has(id);
445
+ if (!known(start)) return mode === "exact" ? { kind: "need", id: start } : undefined;
446
+ // A memo cannot see evidence held only by this walk (an evicted copy), so
447
+ // memos are trusted only while every retained node is still tracked.
448
+ let shortcuts = true;
449
+ for (const id of learned.keys()) if (!has(id)) shortcuts = false;
450
+ const vals = new Map<string, number>();
451
+ const complete = new Set<string>();
452
+ const order: string[] = [];
453
+ const excess = new Set<string>();
454
+ const fresh = new Set<string>();
455
+ const gaps = new Map<string, string>();
456
+ const vias = new Map<string, string>();
457
+ const stack: string[] = [];
458
+ const onStack = new Set<string>();
459
+ let stop: { kind: "need"; id: string } | { kind: "cap"; cycle: boolean } | undefined;
460
+ function visit(id: string, level: number): number {
461
+ const seen = vals.get(id);
462
+ if (seen !== undefined) return seen;
463
+ if (onStack.has(id) || level > MAX_DEPTH_HOPS) {
464
+ stop = { kind: "cap", cycle: onStack.has(id) };
465
+ return MAX_DEPTH_HOPS;
466
+ }
467
+ // Retain visited evidence for the duration of this walk. Backend inserts
468
+ // can evict the start (even with a one-entry cache); that must not turn
469
+ // an event-proven child into a fresh backend root. Node references also
470
+ // retain all conflicting links, not merely the last parent answer.
471
+ const n = node(id, learned);
472
+ if (n.depth >= MAX_DEPTH_HOPS) {
473
+ vals.set(id, MAX_DEPTH_HOPS);
474
+ complete.add(id);
475
+ fresh.add(id);
476
+ order.push(id);
477
+ return MAX_DEPTH_HOPS;
478
+ }
479
+ // A walk (exact mode) climbs through incomplete memos rather than jumping to
480
+ // their gap, so it retains every node it depends on (QA-1.2-1).
481
+ if (shortcuts && n.fresh && (n.gap === undefined || mode === "floor")) {
482
+ vals.set(id, n.depth);
483
+ fresh.add(id);
484
+ order.push(id);
485
+ if (n.via !== undefined) vias.set(id, n.via);
486
+ if (n.gap === undefined) complete.add(id);
487
+ else gaps.set(id, n.gap);
488
+ return n.depth;
489
+ }
490
+ stack.push(id);
491
+ onStack.add(id);
492
+ let d = n.depth;
493
+ let ok = true;
494
+ let gap: string | undefined;
495
+ let best = -1;
496
+ let derived = n.parents.length || n.plugin ? 1 : 0; // what the links alone prove
497
+ for (const p of n.parents) {
498
+ if (!known(p)) {
499
+ if (n.resolved) continue; // Absolute memo at a forgotten frontier (F4).
500
+ if (mode === "exact") {
501
+ stop = { kind: "need", id: p };
502
+ return d;
503
+ }
504
+ ok = false;
505
+ gap ??= p;
506
+ continue;
507
+ }
508
+ const via = visit(p, level + 1) + 1;
509
+ if (stop) return d;
510
+ if (via > best) {
511
+ best = via;
512
+ vias.set(id, p);
513
+ }
514
+ derived = Math.max(derived, via);
515
+ d = Math.max(d, via);
516
+ if (!complete.has(p)) {
517
+ ok = false;
518
+ gap ??= gaps.get(p);
519
+ }
520
+ }
521
+ stack.pop();
522
+ onStack.delete(id);
523
+ const floor0 = n.depth;
524
+ d = Math.min(d, MAX_DEPTH_HOPS);
525
+ vals.set(id, d);
526
+ order.push(id);
527
+ if (ok) {
528
+ complete.add(id);
529
+ fresh.add(id);
530
+ // The stored floor exceeds what the (now complete) links prove: it came
531
+ // from evidence no longer tracked, which a backend walk cannot reproduce.
532
+ if (floor0 > Math.min(derived, MAX_DEPTH_HOPS)) excess.add(id);
533
+ } else if (gap !== undefined) {
534
+ gaps.set(id, gap);
535
+ fresh.add(id);
536
+ }
537
+ return d;
538
+ }
539
+ let depth = visit(start, 0);
540
+ if (stop?.kind === "need") return stop;
541
+ if (stop?.kind === "cap") {
542
+ depth = MAX_DEPTH_HOPS;
543
+ for (const [level, id] of stack.entries()) {
544
+ const d = stop.cycle ? MAX_DEPTH_HOPS : Math.min(MAX_DEPTH_HOPS, MAX_DEPTH_HOPS + 1 - level);
545
+ vals.set(id, d);
546
+ if (d === MAX_DEPTH_HOPS) complete.add(id);
547
+ }
548
+ // Preserve reverse post-order touching even when a climb hits the cap.
549
+ order.push(...stack.slice().reverse());
550
+ }
551
+ return { kind: "done", depth, vals, complete, order, start, excess, fresh, gaps, vias };
552
+ }
553
+
554
+ function touch(id: string, stamp: number): boolean {
555
+ const n = get(id);
556
+ if (!n) return false;
557
+ n.lastTouch = stamp;
558
+ const map = n.pinned ? pins : lru;
559
+ map.delete(id);
560
+ map.set(id, n);
561
+ return true;
562
+ }
563
+
564
+ function memoize(r: Done, learned: Map<string, Node>): void {
565
+ const stamp = clock();
566
+ for (const id of r.order) if (!has(id)) adopt(id, node(id, learned));
567
+ for (const id of r.order) {
568
+ const n = get(id)!;
569
+ n.depth = Math.max(n.depth, r.vals.get(id)!);
570
+ if (r.complete.has(id)) n.resolved = true;
571
+ if (r.fresh.has(id)) {
572
+ n.fresh = true;
573
+ n.gap = r.gaps.get(id);
574
+ n.via = r.vias.get(id);
575
+ } else changed(id, n); // a hop-cap floor depends on the level it was seen at
576
+ if (r.excess.has(id)) pin(id, n);
577
+ }
578
+ // Reverse post-order: the start first, ancestors after it; then the start's
579
+ // max path to the root, so a read keeps its whole critical ancestry warm in
580
+ // O(MAX_DEPTH_HOPS) without touching every ancestor.
581
+ for (let i = r.order.length - 1; i >= 0; i--) touch(r.order[i], stamp);
582
+ let next = get(r.start)!.via;
583
+ for (let hop = 0; next !== undefined && hop < MAX_DEPTH_HOPS && touch(next, stamp); hop++) next = get(next)!.via;
584
+ trim(r.start);
585
+ }
586
+
587
+ function floor(id: string, learned: Map<string, Node>, reason: string): number | undefined {
588
+ const r = climb(id, learned, "floor");
589
+ if (!r) {
590
+ warn(id, "lookup", reason);
591
+ return undefined;
592
+ }
593
+ memoize(r, learned);
594
+ if (!r.complete.has(id)) warn(id, "lookup", reason);
595
+ return r.depth;
596
+ }
597
+
598
+ function throttled(id: string): boolean {
599
+ const stamp = failedAt.get(id);
600
+ if (stamp === undefined) return false;
601
+ const age = clock() - stamp;
602
+ if (age >= 0 && age < DEPTH_LOOKUP_RETRY_MS) return true;
603
+ failedAt.delete(id); // Expired entries go at lookup time, not only on sweep().
604
+ return false;
605
+ }
606
+
607
+ // The blocklist is FIFO-capped like `warned`: the oldest throttle goes first.
608
+ function setFailed(id: string): void {
609
+ failedAt.delete(id);
610
+ failedAt.set(id, clock());
611
+ while (failedAt.size > maxEntries) failedAt.delete(failedAt.keys().next().value!);
612
+ }
613
+
614
+ function startLookup(id: string): Lookup {
615
+ let cancel!: () => void;
616
+ const cancelled = new Promise<LookupResult>((resolve) => {
617
+ cancel = () => resolve({ ok: false, reason: "forgotten" });
618
+ });
619
+ const lookup: Lookup = { id, promise: cancelled, detached: false, cancelled: false, waiters: 0, cancel };
620
+ lookups.set(id, lookup);
621
+ function fail(reason: string): LookupResult {
622
+ if (!lookup.detached && !lookup.cancelled) setFailed(id);
623
+ return { ok: false, reason };
624
+ }
625
+ const request = Promise.resolve().then(() => seams.getParent(id)).then((raw): LookupResult => {
626
+ if (lookup.cancelled) return fail("forgotten");
627
+ if (raw !== null && !validId(raw)) return fail("malformed answer");
628
+ failedAt.delete(id);
629
+ return { ok: true, node: record(id, raw, "backend") };
630
+ }, (e: unknown) => fail(describe(e)));
631
+ lookup.promise = Promise.race([request, cancelled]).finally(() => {
632
+ if (lookups.get(id) === lookup) lookups.delete(id);
633
+ unstray(lookup);
634
+ });
635
+ return lookup;
636
+ }
637
+
638
+ function unstray(lookup: Lookup): void {
639
+ strayOrder.delete(lookup);
640
+ const set = strays.get(lookup.id);
641
+ if (set?.delete(lookup) && set.size === 0) strays.delete(lookup.id);
642
+ }
643
+
644
+ // A lookup that no walk awaits any more is detached: a late success is still
645
+ // applied as evidence, and forget() can still cancel it. The throttle starts
646
+ // now only if its last walk timed out; one released by forget() leaves no
647
+ // throttle, so the next walk that needs the id starts a fresh lookup.
648
+ // Strays are FIFO-capped (QA-1.2-R2-2): the oldest is cancelled, so its late
649
+ // answer (backend evidence a later lookup reproduces) is discarded rather than
650
+ // left beyond forget()'s reach. Strays never gate admission: a new lookup for
651
+ // the same id waits only for its throttle, so dropping one admits nothing.
652
+ function detach(lookup: Lookup, throttle: boolean): void {
653
+ if (lookups.get(lookup.id) !== lookup) return;
654
+ lookups.delete(lookup.id);
655
+ lookup.detached = true;
656
+ if (throttle) setFailed(lookup.id);
657
+ let stray = strays.get(lookup.id);
658
+ if (!stray) strays.set(lookup.id, stray = new Set());
659
+ stray.add(lookup);
660
+ strayOrder.add(lookup);
661
+ while (strayOrder.size > maxEntries) {
662
+ const oldest = strayOrder.values().next().value!;
663
+ unstray(oldest);
664
+ cancelLookup(oldest);
665
+ }
666
+ }
667
+
668
+ function cancelLookup(lookup: Lookup): void {
669
+ lookup.cancelled = true;
670
+ lookup.cancel();
671
+ }
672
+
673
+ // A cancelled walk settles its callers with undefined and resumes at once, so
674
+ // its continuation can never issue another lookup. It stays in `live` (and so
675
+ // within reach of forget) until that continuation has returned. Whatever the
676
+ // cause, it releases its lookup: the last walk out detaches it, so no lookup
677
+ // stays in `lookups` without a walk awaiting it.
678
+ function cancelWalk(walk: Walk, timedOut: boolean): void {
679
+ walk.cancelled = true;
680
+ if (walks.get(walk.id) === walk) walks.delete(walk.id);
681
+ const lookup = walk.pending;
682
+ walk.pending = undefined;
683
+ if (lookup && --lookup.waiters === 0) detach(lookup, timedOut);
684
+ walk.stop();
685
+ }
686
+
687
+ function startWalk(id: string, learned: Map<string, Node>): Walk {
688
+ let stop!: () => void;
689
+ const stopped = new Promise<undefined>((resolve) => { stop = () => resolve(undefined); });
690
+ const walk: Walk = { id, promise: stopped, learned, cancelled: false, waiters: 0, stopped, stop };
691
+ walks.set(id, walk);
692
+ live.add(walk);
693
+ walk.promise = run(walk);
694
+ return walk;
695
+ }
696
+
697
+ async function run(walk: Walk): Promise<number | undefined> {
698
+ const { id, learned } = walk;
699
+ let fetches = 0;
700
+ try {
701
+ for (;;) {
702
+ const r = climb(id, learned, "exact");
703
+ if (r.kind === "done") {
704
+ memoize(r, learned);
705
+ return r.depth;
706
+ }
707
+ if (throttled(r.id) && !lookups.has(r.id)) return floor(id, learned, "throttled");
708
+ if (++fetches > FETCH_BUDGET) {
709
+ warn(id, "lookup", "fetch budget");
710
+ return MAX_DEPTH_HOPS;
711
+ }
712
+ const lookup = lookups.get(r.id) ?? startLookup(r.id);
713
+ walk.pending = lookup;
714
+ lookup.waiters++;
715
+ const result = await Promise.race([lookup.promise, walk.stopped]);
716
+ if (walk.cancelled || result === undefined) return undefined;
717
+ walk.pending = undefined;
718
+ lookup.waiters--;
719
+ if (!result.ok) return floor(id, learned, result.reason);
720
+ mergeInto(learned, r.id, result.node);
721
+ }
722
+ } finally {
723
+ live.delete(walk);
724
+ if (walks.get(id) === walk) walks.delete(id);
725
+ }
726
+ }
727
+
728
+ function record(id: string, link: string | null, source: Source): Node {
729
+ const n = applyLink(id, link, source);
730
+ const learned = new Map<string, Node>([[id, n]]);
731
+ memoize(climb(id, learned, "floor")!, learned);
732
+ return n;
733
+ }
734
+
735
+ return {
736
+ recordRoot(id) {
737
+ if (validId(id)) record(id, null, "event");
738
+ },
739
+ recordCreated(id, parent) {
740
+ if (!validId(id)) return;
741
+ if (parent == null || parent === "") record(id, null, "event");
742
+ else if (validId(parent)) record(id, parent, "event");
743
+ },
744
+ recordPluginChild(id, creator) {
745
+ if (validId(id)) record(id, validId(creator) && creator !== id ? creator : null, "plugin");
746
+ },
747
+ async depthOf(id, options) {
748
+ if (!validId(id)) return undefined;
749
+ const learned = new Map<string, Node>();
750
+ const r = climb(id, learned, "exact");
751
+ if (r.kind === "done") {
752
+ memoize(r, learned);
753
+ return r.depth;
754
+ }
755
+ if (throttled(r.id) && !lookups.has(r.id)) return floor(id, learned, `throttled at ${r.id}`);
756
+ let walk = walks.get(id);
757
+ if (!walk) walk = startWalk(id, learned);
758
+ else for (const [known, n] of learned) mergeInto(walk.learned, known, n);
759
+ walk.waiters++;
760
+ const t = timeoutOf(options);
761
+ const timeout = Symbol("timeout");
762
+ let timer!: ReturnType<typeof setTimeout>;
763
+ const deadline = new Promise<typeof timeout>((resolve) => {
764
+ timer = setTimeout(() => resolve(timeout), t);
765
+ timer.unref?.();
766
+ });
767
+ try {
768
+ const result = await Promise.race([walk.promise, deadline]);
769
+ walk.waiters--;
770
+ if (result !== timeout) {
771
+ if (result === undefined) warn(id, "lookup", "lookup was cancelled because the session was forgotten; treating its depth as unknown");
772
+ return result;
773
+ }
774
+ // Shared callers keep independent deadlines; the last one out cancels.
775
+ if (walk.waiters === 0 && !walk.cancelled) cancelWalk(walk, true);
776
+ // F1 fallback: everything the walk has learned so far, not only the
777
+ // caller's starting snapshot.
778
+ return floor(id, walk.learned, `timed out after ${t} ms`);
779
+ } finally {
780
+ clearTimeout(timer);
781
+ }
782
+ },
783
+ forget(id) {
784
+ if (!validId(id)) return;
785
+ if (has(id)) drop(id, "forget");
786
+ unbury(id);
787
+ failedAt.delete(id);
788
+ for (const kind of Object.keys(WARNINGS)) warned.delete(`${kind}:${id}`);
789
+ // Cancelled before the walks, so releasing them below never strays it.
790
+ const lookup = lookups.get(id);
791
+ if (lookup) {
792
+ cancelLookup(lookup);
793
+ lookups.delete(id);
794
+ }
795
+ for (const walk of live) {
796
+ walk.learned.delete(id);
797
+ if (walk.id === id) cancelWalk(walk, false);
798
+ }
799
+ for (const stray of [...strays.get(id) ?? []]) {
800
+ unstray(stray);
801
+ cancelLookup(stray);
802
+ }
803
+ },
804
+ sweep() {
805
+ const now = clock();
806
+ // A node idle for the TTL expires (pinned ones too: accepted residual F2)
807
+ // unless it is an ancestor, within MAX_DEPTH_HOPS, of a node that did not
808
+ // expire. A read touches only its critical path, so this keeps every
809
+ // ancestor whose evidence a live node's depth depends on (an ancestor
810
+ // further away can only confirm MAX), at O(nodes + ghosts + links) per
811
+ // sweep and no cost per read (QA-1.2-R2-1). Ghosts follow the same rule,
812
+ // and the BFS crosses them, so an evicted intermediate does not cut a live
813
+ // node off from its pinned ancestors (QA-1.2-R3-1).
814
+ const hops = new Map<string, number>();
815
+ for (const map of [lru, pins, held, loose]) {
816
+ for (const [id, x] of map) if (now - x.lastTouch < ttlMs) hops.set(id, 0);
817
+ }
818
+ ancestry(hops);
819
+ for (const map of [lru, pins]) for (const id of map.keys()) if (!hops.has(id)) drop(id, "expire");
820
+ for (const id of [...held.keys(), ...loose.keys()]) if (!hops.has(id)) unbury(id);
821
+ for (const id of failedAt.keys()) throttled(id); // drops every expired entry
822
+ for (const [key, stamp] of warned) if (now - stamp >= ttlMs) warned.delete(key);
823
+ },
824
+ size: () => lru.size + pins.size,
825
+ };
826
+ }