pi-legion 3.0.3 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +263 -2
  2. package/CONTRIBUTING.md +4 -17
  3. package/README.md +29 -22
  4. package/agents/worker.md +1 -1
  5. package/docs/contracts/display-liveness-v1.md +373 -0
  6. package/docs/contracts/drop-non-pi-kinds-v4.md +198 -0
  7. package/docs/contracts/esc-abort-v1.md +4 -4
  8. package/docs/contracts/esc-no-retire-v3.md +2 -2
  9. package/docs/contracts/launch-admission-queue-v1.md +839 -0
  10. package/docs/contracts/status-panel-v1.md +174 -0
  11. package/docs/inprocess-supervisor.md +37 -4
  12. package/docs/legion-v2-contract.md +18 -2
  13. package/docs/performance-2026-10-19.md +199 -0
  14. package/docs/spawn-mode-visibility-v1.md +206 -0
  15. package/docs/vexillatio-contract.md +3 -1
  16. package/index.ts +633 -84
  17. package/package.json +4 -2
  18. package/skills/pi-legion/SKILL.md +2 -3
  19. package/src/agents/agents.ts +17 -10
  20. package/src/agents/overrides.ts +0 -1
  21. package/src/agents/presets.ts +14 -40
  22. package/src/agents/settings.ts +26 -77
  23. package/src/agents/step-model.ts +7 -22
  24. package/src/api.ts +1 -35
  25. package/src/extension/event-bus.ts +80 -8
  26. package/src/extension/legion-commands.ts +43 -17
  27. package/src/extension/legion-doctor.ts +1 -1
  28. package/src/extension/legion-stop.ts +39 -13
  29. package/src/extension/legion-tools.ts +21 -4
  30. package/src/extension/liveness.ts +200 -0
  31. package/src/extension/notify.ts +6 -6
  32. package/src/extension/playbook.ts +6 -6
  33. package/src/extension/recycle.ts +6 -2
  34. package/src/extension/runtime.ts +422 -18
  35. package/src/extension/slash.ts +0 -21
  36. package/src/extension/spawn-render.ts +183 -0
  37. package/src/extension/summary.ts +1 -1
  38. package/src/legion/db.ts +165 -1
  39. package/src/legion/events.ts +81 -16
  40. package/src/legion/nodes.ts +13 -2
  41. package/src/legion/rebuild.ts +7 -1
  42. package/src/legion/usage.ts +58 -4
  43. package/src/runs/orchestrator.ts +1165 -62
  44. package/src/runs/worktree.ts +190 -21
  45. package/src/shared/ignored-kind.ts +57 -0
  46. package/src/shared/progress.ts +11 -0
  47. package/src/shared/session.ts +199 -19
  48. package/src/shared/types.ts +50 -66
  49. package/src/supervisor/admission-queue.ts +516 -0
  50. package/src/supervisor/inprocess-supervisor.ts +108 -33
  51. package/src/supervisor/proc-memory.ts +67 -0
  52. package/src/supervisor/routing-supervisor.ts +58 -1
  53. package/src/tui/live-overlay.ts +14 -0
  54. package/src/tui/session-messages-file.ts +100 -0
  55. package/src/tui/status.ts +103 -21
  56. package/src/tui/tree-view.ts +36 -3
  57. package/src/tui/viz/layout.ts +54 -3
  58. package/src/tui/viz/model.ts +67 -14
  59. package/src/tui/viz/palette.ts +11 -0
  60. package/src/tui/viz/panels.ts +222 -8
  61. package/src/tui/viz/railway.ts +28 -25
  62. package/src/tui/viz/view.ts +110 -23
  63. package/src/backends/legacy/client.ts +0 -638
  64. package/src/backends/legacy/cursor-chat.ts +0 -348
  65. package/src/backends/legacy/runner.ts +0 -101
  66. package/src/backends/legacy/types.ts +0 -138
  67. package/src/runs/kind.ts +0 -260
@@ -0,0 +1,516 @@
1
+ /**
2
+ * Launch admission queue (issue #266, contract `launch-admission-queue-v1`).
3
+ *
4
+ * Turns "over the concurrent/fanout cap → throw `BUDGET_EXCEEDED` and let the
5
+ * caller retry" into "over a *queueable* cap → wait in a queue, then admit
6
+ * automatically once a slot is released". One scheduler for both backends.
7
+ *
8
+ * Scope of this module: the queue itself plus the single gate verdict function.
9
+ * It is deliberately **pure** (contract §4.1 / §13.7-1):
10
+ * - no filesystem, no path module, no database,
11
+ * - no timers (superseded by an injected clock + the caller's single fallback timer, D2-d),
12
+ * - no environment reads,
13
+ * - the only time source is `options.now` (default `Date.now`), and
14
+ * - the only global state is the process-level registry below.
15
+ * A unit test asserts these properties by reading this file's source text.
16
+ *
17
+ * Two consequences that are easy to get wrong:
18
+ * 1. Timeouts are evaluated **only** inside `next()` (R7). Never reject an item
19
+ * that is already being admitted: it has left the queue and its child may
20
+ * already be spawned, so a late reject would orphan it.
21
+ * 2. Ordering is one global `seq`. A smaller `seq` that cannot pass the probe
22
+ * is skipped, never allowed to block later items — and never reordered by
23
+ * parent (D5).
24
+ *
25
+ * The registry lives on `globalThis` under `Symbol.for(...)` because `jiti`
26
+ * reloads modules with `moduleCache: false`: a module-level `Map` would be
27
+ * reset by such a reload, and the five `new Orchestrator` sites in `index.ts`
28
+ * would stop sharing one queue. Keys are namespaced with the process id
29
+ * (I-O6) so a child process cannot inherit a parent's queue by using the same
30
+ * run directory.
31
+ *
32
+ * NOTE: `§` references point at `docs/contracts/launch-admission-queue-v1.md`.
33
+ */
34
+
35
+ export const DEFAULT_LAUNCH_QUEUE_MAX_PENDING = 32;
36
+ export const DEFAULT_LAUNCH_QUEUE_TIMEOUT_MS = 900_000;
37
+ /**
38
+ * D2-d: the fallback recheck window. Even with event-driven pumps, a slot can
39
+ * be released by *another* process (sibling session / hygiene), which sends no
40
+ * event here — so the owner keeps one unref'd timer capped at this interval.
41
+ * Fixed on purpose: no settings key for it.
42
+ */
43
+ export const LAUNCH_QUEUE_RECHECK_MS = 1000;
44
+
45
+ /** D1: which resource the queued item is waiting for. */
46
+ export type AdmissionDimension = "fanout" | "active";
47
+
48
+ /** D1: the four gates that may be queued on. Everything else is a hard refusal. */
49
+ export type QueueableGate =
50
+ | "inprocess.maxChildrenPerNode"
51
+ | "inprocess.maxActive"
52
+ | "ledger.maxChildrenPerNode"
53
+ | "ledger.maxActiveNodes";
54
+
55
+ /**
56
+ * D1/D11: gates that can never be satisfied by waiting — queueing them would
57
+ * disguise a permanent failure (or a config error) as a 15-minute delay.
58
+ */
59
+ export type HardGate =
60
+ | "inprocess.maxSpawnsPerSession"
61
+ | "inprocess.maxDepth"
62
+ | "inprocess.maxChildrenPerNode.disabled"
63
+ | "ledger.maxChildrenPerNode.disabled"
64
+ | "legion.maxDepth"
65
+ | "legion.parentNotFound"
66
+ | "orchestrator.maxDepth"
67
+ | "orchestrator.maxSpawns"
68
+ | "other";
69
+
70
+ /**
71
+ * Structured gate verdict (D1-a). The enqueue/refuse decision must be taken
72
+ * from this shape — never from catching `BUDGET_EXCEEDED` (D1-b): one error
73
+ * code covers eight distinct conditions, some of them permanent.
74
+ */
75
+ export type AdmissionVerdict =
76
+ | { readonly admitted: true }
77
+ | {
78
+ readonly admitted: false;
79
+ readonly queueable: true;
80
+ readonly gate: QueueableGate;
81
+ readonly dimension: AdmissionDimension;
82
+ readonly message: string;
83
+ }
84
+ | { readonly admitted: false; readonly queueable: false; readonly gate: HardGate; readonly message: string };
85
+
86
+ /** In-process count snapshot, provided read-only by `InProcessSupervisor` (I-O1). */
87
+ export interface InProcessAdmissionCounts {
88
+ readonly parentKey: string;
89
+ /** Live children under `parentKey` — same filter as `assertWithinLimits`. */
90
+ readonly siblings: number;
91
+ /** All live children (everything not `exited`/`retired`; `idle` still holds a slot). */
92
+ readonly active: number;
93
+ readonly spawnCount: number;
94
+ /** `inProcessDepth()` at call time. */
95
+ readonly depth: number;
96
+ readonly limits: {
97
+ readonly maxDepth: number;
98
+ readonly maxChildrenPerNode: number;
99
+ readonly maxActive: number;
100
+ readonly maxSpawnsPerSession?: number;
101
+ };
102
+ }
103
+
104
+ // ── Frozen user-visible copy (A6 asserts these byte-for-byte) ──────────────
105
+
106
+ /** `inprocess spawn budget exhausted (n/N); raise …` */
107
+ export function inProcessSpawnsMessage(spawnCount: number, limit: number): string {
108
+ return `inprocess spawn budget exhausted (${spawnCount}/${limit}); raise subagents.inprocess.maxSpawnsPerSession to allow more`;
109
+ }
110
+
111
+ /** `inprocess maxActive reached (n/30); raise …` */
112
+ export function inProcessActiveMessage(active: number, limit: number): string {
113
+ return `inprocess maxActive reached (${active}/${limit}); raise subagents.inprocess.maxActive to allow more`;
114
+ }
115
+
116
+ /** `inprocess nesting limit reached (depth d, max 4); raise …` */
117
+ export function inProcessDepthMessage(depth: number, limit: number): string {
118
+ return `inprocess nesting limit reached (depth ${depth}, max ${limit}); raise subagents.inprocess.maxDepth to allow deeper nesting`;
119
+ }
120
+
121
+ /**
122
+ * `inprocess maxChildrenPerNode reached for '<parent>' (n/8)`.
123
+ * An empty `parentKey` (a root-level child) renders as `<root>`, exactly as
124
+ * `assertWithinLimits` always has.
125
+ */
126
+ export function inProcessFanoutMessage(parentKey: string, siblings: number, limit: number): string {
127
+ return `inprocess maxChildrenPerNode reached for '${parentKey || "<root>"}' (${siblings}/${limit})`;
128
+ }
129
+
130
+ /** D6: `launch queue overflow (<size>/<max>); raise …` */
131
+ export function queueOverflowMessage(size: number, maxPending: number): string {
132
+ return `launch queue overflow (${size}/${maxPending}); raise subagents.inprocess.maxQueuedLaunches to allow more`;
133
+ }
134
+
135
+ /** D6: `launch queue timed out after <N>s ('<name>')` */
136
+ export function queueTimeoutMessage(name: string, waitedMs: number): string {
137
+ return `launch queue timed out after ${Math.round(waitedMs / 1000)}s ('${name}')`;
138
+ }
139
+
140
+ /**
141
+ * The one and only in-process gate implementation (D1-a).
142
+ *
143
+ * `assertWithinLimits` and the Orchestrator's admission probe both call this,
144
+ * so the four user-visible messages cannot drift apart.
145
+ *
146
+ * Evaluation order matches `assertWithinLimits` verbatim:
147
+ * `maxSpawnsPerSession` → `maxActive` → `maxDepth` → `maxChildrenPerNode`.
148
+ *
149
+ * `inflight` is the Orchestrator's in-flight reservation (D2-b): admissions it
150
+ * has already waved through in this tick but which have not reached the
151
+ * supervisor's `children` map yet. It only offsets the two queueable
152
+ * dimensions (fanout/active); it never affects the hard gates.
153
+ */
154
+ export function evaluateInProcessAdmission(
155
+ counts: InProcessAdmissionCounts,
156
+ inflight?: { readonly fanout: number; readonly active: number },
157
+ ): AdmissionVerdict {
158
+ const limits = counts.limits;
159
+ const inflightFanout = inflight?.fanout ?? 0;
160
+ const inflightActive = inflight?.active ?? 0;
161
+
162
+ const spawnLimit = limits.maxSpawnsPerSession;
163
+ if (spawnLimit !== undefined && counts.spawnCount >= spawnLimit) {
164
+ return {
165
+ admitted: false,
166
+ queueable: false,
167
+ gate: "inprocess.maxSpawnsPerSession",
168
+ message: inProcessSpawnsMessage(counts.spawnCount, spawnLimit),
169
+ };
170
+ }
171
+
172
+ const active = counts.active + inflightActive;
173
+ if (active >= limits.maxActive) {
174
+ return {
175
+ admitted: false,
176
+ queueable: true,
177
+ gate: "inprocess.maxActive",
178
+ dimension: "active",
179
+ message: inProcessActiveMessage(active, limits.maxActive),
180
+ };
181
+ }
182
+
183
+ if (counts.depth + 1 > limits.maxDepth) {
184
+ return {
185
+ admitted: false,
186
+ queueable: false,
187
+ gate: "inprocess.maxDepth",
188
+ message: inProcessDepthMessage(counts.depth, limits.maxDepth),
189
+ };
190
+ }
191
+
192
+ const siblings = counts.siblings + inflightFanout;
193
+ if (limits.maxChildrenPerNode === 0) {
194
+ // D11: 0 means "no children at all" — `siblings >= 0` is always true, so
195
+ // this gate can never be satisfied by waiting. Refuse immediately, under
196
+ // a distinct gate name so the decision is assertable and diagnosable.
197
+ return {
198
+ admitted: false,
199
+ queueable: false,
200
+ gate: "inprocess.maxChildrenPerNode.disabled",
201
+ message: inProcessFanoutMessage(counts.parentKey, siblings, limits.maxChildrenPerNode),
202
+ };
203
+ }
204
+ if (siblings >= limits.maxChildrenPerNode) {
205
+ return {
206
+ admitted: false,
207
+ queueable: true,
208
+ gate: "inprocess.maxChildrenPerNode",
209
+ dimension: "fanout",
210
+ message: inProcessFanoutMessage(counts.parentKey, siblings, limits.maxChildrenPerNode),
211
+ };
212
+ }
213
+
214
+ return { admitted: true };
215
+ }
216
+
217
+ // ── Queue ─────────────────────────────────────────────────────────────────
218
+
219
+ export interface QueuedLaunch<T = unknown> {
220
+ readonly name: string;
221
+ readonly parentKey: string;
222
+ readonly seq: number;
223
+ readonly enqueuedAt: number;
224
+ readonly payload: T;
225
+ }
226
+
227
+ export interface AdmissionQueueOptions {
228
+ readonly maxPending?: number;
229
+ readonly timeoutMs?: number;
230
+ /** Injected clock; defaults to `Date.now`. The only time source in this module. */
231
+ readonly now?: () => number;
232
+ }
233
+
234
+ export type EnqueueOutcome<T> =
235
+ | { readonly ok: true; readonly item: QueuedLaunch<T>; readonly position: number }
236
+ | { readonly ok: false; readonly kind: "overflow"; readonly message: string };
237
+
238
+ export type NextAdmission<T> =
239
+ | { readonly kind: "none" }
240
+ | { readonly kind: "admit"; readonly item: QueuedLaunch<T>; readonly waitedMs: number }
241
+ | { readonly kind: "expired"; readonly item: QueuedLaunch<T>; readonly waitedMs: number; readonly message: string };
242
+
243
+ export interface AdmissionQueueEntry {
244
+ readonly name: string;
245
+ readonly parentKey: string;
246
+ readonly seq: number;
247
+ /** 1-based position in the queue as it stands right now. */
248
+ readonly position: number;
249
+ readonly waitedMs: number;
250
+ }
251
+
252
+ export interface AdmissionQueue<T = unknown> {
253
+ /** Number of *waiting* items (an item under admission has already left). */
254
+ readonly size: number;
255
+ readonly maxPending: number;
256
+ readonly timeoutMs: number;
257
+ enqueue(
258
+ payload: T,
259
+ meta: {
260
+ name: string;
261
+ parentKey: string;
262
+ /**
263
+ * The clock reading this item should be *accounted from* (D2-c).
264
+ *
265
+ * A requeue must not restart the wait: without an override the queue would
266
+ * stamp a fresh `enqueuedAt`, which both under-reports `waitedMs` (the
267
+ * `async:false` "waited Ns" line) and hands the item a second full
268
+ * `timeoutMs`, so a launch that keeps losing the admission race could wait
269
+ * nearly twice the configured bound. The caller passes the ORIGINAL
270
+ * timestamp it captured on first enqueue; omitting it means "now", which is
271
+ * what a first enqueue wants.
272
+ */
273
+ enqueuedAt?: number;
274
+ },
275
+ ): EnqueueOutcome<T>;
276
+ positionOf(name: string): number | undefined;
277
+ waitedMs(name: string): number | undefined;
278
+ /** Dequeue and return (stop / abort flush). `undefined` when absent. */
279
+ remove(name: string): QueuedLaunch<T> | undefined;
280
+ /** Clear and return, in ascending `seq` order. */
281
+ flush(): QueuedLaunch<T>[];
282
+ /**
283
+ * Decide who leaves the queue next.
284
+ *
285
+ * Scans in `seq` order and returns the first item that either (a) has
286
+ * outlived `timeoutMs` or (b) passes `probe`. Items whose probe fails are
287
+ * skipped without blocking the scan (head-of-line skip, D5-2).
288
+ *
289
+ * The returned item is **dequeued**: an item being admitted is no longer
290
+ * "waiting", so a concurrent `next()` can never hand out the same item
291
+ * twice and a timeout can never fire against it (R7).
292
+ */
293
+ next(probe: (item: QueuedLaunch<T>) => AdmissionVerdict): NextAdmission<T>;
294
+ entries(): readonly AdmissionQueueEntry[];
295
+ /** When the owner should re-check: `min(earliest expiry, now + LAUNCH_QUEUE_RECHECK_MS)`. */
296
+ nextDeadlineAt(): number | undefined;
297
+ }
298
+
299
+ /** A non-positive/invalid option falls back to the documented default. */
300
+ function normalizeLimit(value: number | undefined, fallback: number): number {
301
+ if (value === undefined || !Number.isFinite(value) || value <= 0) return fallback;
302
+ return Math.floor(value);
303
+ }
304
+
305
+ let listener: ((event: LaunchQueueEvent) => void) | undefined;
306
+
307
+ /** D9: process-local UI hook. Same shape as verify's listener, different function. */
308
+ export function setLaunchQueueListener(fn: ((event: LaunchQueueEvent) => void) | undefined): void {
309
+ listener = fn;
310
+ }
311
+
312
+ /** A UI hook must never be able to break admission. */
313
+ function emit(event: LaunchQueueEvent): void {
314
+ const fn = listener;
315
+ if (!fn) return;
316
+ try {
317
+ fn(event);
318
+ } catch {
319
+ /* swallow: the pill is cosmetic */
320
+ }
321
+ }
322
+
323
+ export function createAdmissionQueue<T = unknown>(options: AdmissionQueueOptions = {}): AdmissionQueue<T> {
324
+ const maxPending = normalizeLimit(options.maxPending, DEFAULT_LAUNCH_QUEUE_MAX_PENDING);
325
+ const timeoutMs = normalizeLimit(options.timeoutMs, DEFAULT_LAUNCH_QUEUE_TIMEOUT_MS);
326
+ const now = options.now ?? (() => Date.now());
327
+ /** Ascending `seq`: appended on enqueue, so array order IS queue order (D5). */
328
+ const items: QueuedLaunch<T>[] = [];
329
+ let nextSeq = 1;
330
+
331
+ return {
332
+ get size() {
333
+ return items.length;
334
+ },
335
+ maxPending,
336
+ timeoutMs,
337
+
338
+ enqueue(payload, meta) {
339
+ if (items.length >= maxPending) {
340
+ // D6: overflow is an immediate hard refusal — nothing is enqueued, so
341
+ // nothing needs timing out later.
342
+ const message = queueOverflowMessage(items.length, maxPending);
343
+ emit({ phase: "overflow", name: meta.name, queued: items.length, message });
344
+ return { ok: false, kind: "overflow", message };
345
+ }
346
+ const item: QueuedLaunch<T> = {
347
+ name: meta.name,
348
+ parentKey: meta.parentKey,
349
+ // D2-c: `seq` is always freshly assigned (a requeue lands at the back — D5
350
+ // gives no one priority), but the DEADLINE is carried over when the caller
351
+ // re-enqueues an item that already waited.
352
+ seq: nextSeq,
353
+ enqueuedAt: meta.enqueuedAt ?? now(),
354
+ payload,
355
+ };
356
+ nextSeq += 1;
357
+ items.push(item);
358
+ const position = items.length;
359
+ emit({ phase: "queued", name: item.name, position, queued: items.length });
360
+ return { ok: true, item, position };
361
+ },
362
+
363
+ positionOf(name) {
364
+ const index = items.findIndex((item) => item.name === name);
365
+ return index === -1 ? undefined : index + 1;
366
+ },
367
+
368
+ waitedMs(name) {
369
+ const item = items.find((candidate) => candidate.name === name);
370
+ return item === undefined ? undefined : now() - item.enqueuedAt;
371
+ },
372
+
373
+ remove(name) {
374
+ const index = items.findIndex((item) => item.name === name);
375
+ const removed = index === -1 ? undefined : items[index];
376
+ if (removed === undefined) return undefined;
377
+ items.splice(index, 1);
378
+ emit({ phase: "stopped", name: removed.name, queued: items.length });
379
+ return removed;
380
+ },
381
+
382
+ flush() {
383
+ // Array order IS seq order (append-only), so a copy is already sorted.
384
+ const flushed = [...items];
385
+ items.length = 0;
386
+ if (flushed.length > 0) {
387
+ emit({ phase: "flushed", queued: 0, message: `launch queue flushed (${flushed.length} pending)` });
388
+ }
389
+ return flushed;
390
+ },
391
+
392
+ next(probe) {
393
+ const at = now();
394
+ for (let index = 0; index < items.length; index += 1) {
395
+ const item = items[index];
396
+ if (item === undefined) continue;
397
+ const waitedMs = at - item.enqueuedAt;
398
+ if (item.enqueuedAt + timeoutMs <= at) {
399
+ items.splice(index, 1);
400
+ const message = queueTimeoutMessage(item.name, waitedMs);
401
+ emit({ phase: "expired", name: item.name, position: index + 1, waitedMs, queued: items.length, message });
402
+ return { kind: "expired", item, waitedMs, message };
403
+ }
404
+ const verdict = probe(item);
405
+ if (!verdict.admitted) continue; // head-of-line skip (D5-2)
406
+ items.splice(index, 1);
407
+ emit({ phase: "admitted", name: item.name, position: index + 1, waitedMs, queued: items.length });
408
+ return { kind: "admit", item, waitedMs };
409
+ }
410
+ return { kind: "none" };
411
+ },
412
+
413
+ entries() {
414
+ const at = now();
415
+ return items.map((item, index) => ({
416
+ name: item.name,
417
+ parentKey: item.parentKey,
418
+ seq: item.seq,
419
+ position: index + 1,
420
+ waitedMs: at - item.enqueuedAt,
421
+ }));
422
+ },
423
+
424
+ nextDeadlineAt() {
425
+ if (items.length === 0) return undefined;
426
+ let earliest = Number.POSITIVE_INFINITY;
427
+ for (const item of items) earliest = Math.min(earliest, item.enqueuedAt + timeoutMs);
428
+ return Math.min(earliest, now() + LAUNCH_QUEUE_RECHECK_MS);
429
+ },
430
+ };
431
+ }
432
+
433
+ // ── Process-level registry (D5/I-O6) ──────────────────────────────────────
434
+
435
+ const REGISTRY_KEY = Symbol.for("pi-legion.launch-admission-queue");
436
+
437
+ /** Symbol-indexed view of `globalThis` so the registry survives a module reload. */
438
+ type RegistryHolder = {
439
+ [key: symbol]: Map<string, AdmissionQueue<unknown>> | undefined;
440
+ };
441
+
442
+ function registry(): Map<string, AdmissionQueue<unknown>> {
443
+ // SAFETY: `globalThis` is an object, so a `Symbol.for`-keyed property is
444
+ // readable on it; the invariant TypeScript cannot check is that the slot
445
+ // holds this module's registry map. Both writer and reader of the slot live
446
+ // in this file (plus `resetAdmissionQueuesForTests`), and the declared slot
447
+ // type is the only thing ever stored there.
448
+ const holder = globalThis as unknown as RegistryHolder;
449
+ return (holder[REGISTRY_KEY] ??= new Map<string, AdmissionQueue<unknown>>());
450
+ }
451
+
452
+ /** I-O6: the pid keeps a child process from sharing its parent's queue. */
453
+ function registryKey(scope: string): string {
454
+ return `${process.pid}:${scope}`;
455
+ }
456
+
457
+ /**
458
+ * One queue per (process, scope). `scope` is the parent run directory — not the
459
+ * cwd — because the control-action Orchestrators (`index.ts` has five
460
+ * `new Orchestrator` sites) must find the queue a `launch` created, so that
461
+ * `subagent stop` can dequeue an item that never spawned.
462
+ *
463
+ * `options` only apply when this scope has no queue yet: the first acquisition
464
+ * wins, so a later reader cannot silently shrink a live queue's bounds.
465
+ */
466
+ export function acquireAdmissionQueue<T = unknown>(
467
+ scope: string,
468
+ options?: AdmissionQueueOptions,
469
+ ): AdmissionQueue<T> {
470
+ const queues = registry();
471
+ const key = registryKey(scope);
472
+ const existing = queues.get(key);
473
+ // SAFETY: a scope has exactly one payload type (the `LaunchQueuePayload` of
474
+ // the run that owns it), so the erased entry is this call site's `T`. The
475
+ // erasure is what lets one registry serve every run in the process.
476
+ if (existing) return existing as AdmissionQueue<T>;
477
+ const created = createAdmissionQueue<T>(options);
478
+ // SAFETY: see above — the write-side half of the same erasure. `T` is only
479
+ // a compile-time parameter and never appears at runtime.
480
+ queues.set(key, created as unknown as AdmissionQueue<unknown>);
481
+ return created;
482
+ }
483
+
484
+ /**
485
+ * Read the queue a **different** instance created, without creating one.
486
+ *
487
+ * The control-action paths (`subagent stop`/`status`/`collect`) build their own
488
+ * Orchestrator (`index.ts` has five `new Orchestrator` sites), so an instance
489
+ * that never launched anything must still be able to see — and dequeue from — the
490
+ * queue its sibling owns (§13.6 / §6.1). `acquireAdmissionQueue` cannot be used
491
+ * for that: "first acquisition wins" would install an EMPTY queue with default
492
+ * bounds and shadow the real owner's settings. This returns `undefined` instead,
493
+ * so a read-only path can never mutate the registry.
494
+ */
495
+ export function peekAdmissionQueue<T = unknown>(scope: string): AdmissionQueue<T> | undefined {
496
+ // SAFETY: one scope has exactly one payload type, the same erasure
497
+ // `acquireAdmissionQueue` relies on. Nothing is written here.
498
+ return registry().get(registryKey(scope)) as AdmissionQueue<T> | undefined;
499
+ }
500
+
501
+ /** Tests only (A17): drop every registered queue so suites cannot pollute each other. */
502
+ export function resetAdmissionQueuesForTests(): void {
503
+ registry().clear();
504
+ }
505
+
506
+ /** D9: process-local UI events. Phases with no name are queue-wide transitions. */
507
+ export interface LaunchQueueEvent {
508
+ readonly phase: "queued" | "admitted" | "expired" | "overflow" | "stopped" | "flushed";
509
+ readonly name?: string;
510
+ readonly position?: number;
511
+ readonly waitedMs?: number;
512
+ readonly queued: number;
513
+ readonly slotsInUse?: number;
514
+ readonly slots?: number;
515
+ readonly message?: string;
516
+ }