@shumkov/orchestra 0.6.0 → 0.7.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.
@@ -31,6 +31,68 @@
31
31
 
32
32
  const DEFAULT_BUDGET = 10; // total Σ cost (SDK cost=1, tmux cost=3)
33
33
  const DEFAULT_LRU_WAIT_MS = 300_000;
34
+ const DEFAULT_CODEX_RETIREMENT_TIMEOUT_MS = 30_000;
35
+ const MAX_RUNTIME_ID_BYTES = 512;
36
+ const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
37
+
38
+ class ProcessManagerError extends Error {
39
+ constructor(message, code, options) {
40
+ super(message, options);
41
+ this.name = 'ProcessManagerError';
42
+ this.code = code;
43
+ }
44
+ }
45
+
46
+ function managerError(message, code, options) {
47
+ return new ProcessManagerError(message, code, options);
48
+ }
49
+
50
+ function findCodexRetirementVerificationError(error) {
51
+ let current = error;
52
+ for (let depth = 0; current && depth < 8; depth += 1) {
53
+ if (current.code === 'CODEX_RETIREMENT_VERIFICATION_FAILED') {
54
+ return current;
55
+ }
56
+ current = current.cause;
57
+ }
58
+ return null;
59
+ }
60
+
61
+ function isOpaqueId(value) {
62
+ return (
63
+ typeof value === 'string'
64
+ && value.length > 0
65
+ && Buffer.byteLength(value, 'utf8') <= MAX_RUNTIME_ID_BYTES
66
+ && !CONTROL_CHAR_RE.test(value)
67
+ );
68
+ }
69
+
70
+ function snapshotModelSettings(settings) {
71
+ if (settings == null) return null;
72
+ return Object.freeze({
73
+ model: settings.model,
74
+ effort: settings.effort,
75
+ });
76
+ }
77
+
78
+ function requireModelSettings(settings, label) {
79
+ if (
80
+ !settings
81
+ || typeof settings !== 'object'
82
+ || Array.isArray(settings)
83
+ || Object.keys(settings).some((key) => !['model', 'effort'].includes(key))
84
+ || !isOpaqueId(settings.model)
85
+ || !isOpaqueId(settings.effort)
86
+ ) {
87
+ throw new TypeError(
88
+ `ProcessManager: ${label} requires model and effort`,
89
+ );
90
+ }
91
+ return Object.freeze({
92
+ model: settings.model,
93
+ effort: settings.effort,
94
+ });
95
+ }
34
96
 
35
97
  // callback name → event name
36
98
  const CALLBACK_TO_EVENT = {
@@ -167,6 +229,10 @@ class ProcessManager {
167
229
  * @param {object} [opts.callbacks={}] — keys: onInit, onClose, ...
168
230
  * @param {number} [opts.lruWaitMs] — how long getOrSpawn parks
169
231
  * when all entries are in-flight
232
+ * @param {(input: object) => Promise<{committed: true}>}
233
+ * [opts.codexRetirementVerifier] — consumer durability handshake.
234
+ * @param {number} [opts.codexRetirementTimeoutMs=30000]
235
+ * — absolute deadline for the optional durability handshake.
170
236
  */
171
237
  constructor({
172
238
  processFactory,
@@ -175,6 +241,11 @@ class ProcessManager {
175
241
  logger = console,
176
242
  callbacks = {},
177
243
  lruWaitMs = DEFAULT_LRU_WAIT_MS,
244
+ codexRecoveryState,
245
+ codexHostIdentity = null,
246
+ codexBootSessionIdentity = null,
247
+ codexRetirementVerifier = null,
248
+ codexRetirementTimeoutMs = DEFAULT_CODEX_RETIREMENT_TIMEOUT_MS,
178
249
  } = {}) {
179
250
  if (typeof processFactory !== 'function') {
180
251
  throw new TypeError('ProcessManager: processFactory function required');
@@ -192,6 +263,42 @@ class ProcessManager {
192
263
  // getOrSpawn for the same key await the spawn instead of
193
264
  // returning a proc whose start() hasn't resolved (see getOrSpawn).
194
265
  this._starting = new Map();
266
+ // sessionKey → { identityKey, promise }. Runtime/profile replacement is
267
+ // single-flight so concurrent messages cannot install two generations.
268
+ this._replacing = new Map();
269
+ this._lifecycleGates = new Map();
270
+ this._retirementIntents = new Map();
271
+ this._retiring = new WeakSet();
272
+ this._procIdentities = new WeakMap();
273
+
274
+ // Native Codex beta ownership. Recovery is deliberately not ready by
275
+ // default: the consumer must first restore the persisted daemon-wide
276
+ // record, even when that record says no generation was live.
277
+ this.codexHostIdentity = codexHostIdentity;
278
+ this.codexBootSessionIdentity = codexBootSessionIdentity;
279
+ if (
280
+ codexRetirementVerifier != null
281
+ && typeof codexRetirementVerifier !== 'function'
282
+ ) {
283
+ throw new TypeError(
284
+ 'ProcessManager: codexRetirementVerifier function required',
285
+ );
286
+ }
287
+ this.codexRetirementVerifier = codexRetirementVerifier;
288
+ if (
289
+ !Number.isSafeInteger(codexRetirementTimeoutMs)
290
+ || codexRetirementTimeoutMs < 1
291
+ ) {
292
+ throw new TypeError(
293
+ 'ProcessManager: codexRetirementTimeoutMs positive integer required',
294
+ );
295
+ }
296
+ this.codexRetirementTimeoutMs = codexRetirementTimeoutMs;
297
+ this._codexRecoveryReady = false;
298
+ this._codexLease = null;
299
+ if (codexRecoveryState !== undefined) {
300
+ this.restoreCodexRecoveryState(codexRecoveryState);
301
+ }
195
302
  }
196
303
 
197
304
  // ─── Introspection ───────────────────────────────────────────────
@@ -212,6 +319,177 @@ class ProcessManager {
212
319
  return sum;
213
320
  }
214
321
 
322
+ /**
323
+ * Restore the persisted native-Codex ownership record before accepting any
324
+ * Codex spawn. A quarantined record is released only by an explicit restore
325
+ * on the same host with a different boot-session identity.
326
+ *
327
+ * @param {{status: 'clear'}|{
328
+ * status: 'quarantined',
329
+ * hostIdentity: string,
330
+ * bootSessionIdentity: string,
331
+ * generationId: string
332
+ * }} state
333
+ */
334
+ restoreCodexRecoveryState(state) {
335
+ if (this._codexLease || this._hasLiveCodexProcess()) {
336
+ throw managerError(
337
+ 'Codex recovery state cannot change while ownership is live',
338
+ 'CODEX_RECOVERY_ALREADY_ACTIVE',
339
+ );
340
+ }
341
+ if (!state || typeof state !== 'object' || Array.isArray(state)) {
342
+ throw new TypeError('ProcessManager: codexRecoveryState object required');
343
+ }
344
+ if (state.status === 'clear') {
345
+ this._codexLease = null;
346
+ this._codexRecoveryReady = true;
347
+ return;
348
+ }
349
+ if (
350
+ state.status !== 'quarantined'
351
+ || !isOpaqueId(state.hostIdentity)
352
+ || !isOpaqueId(state.bootSessionIdentity)
353
+ || !isOpaqueId(state.generationId)
354
+ ) {
355
+ throw new TypeError(
356
+ 'ProcessManager: invalid quarantined codexRecoveryState',
357
+ );
358
+ }
359
+ const sameHost = (
360
+ isOpaqueId(this.codexHostIdentity)
361
+ && state.hostIdentity === this.codexHostIdentity
362
+ );
363
+ const newBoot = (
364
+ isOpaqueId(this.codexBootSessionIdentity)
365
+ && state.bootSessionIdentity !== this.codexBootSessionIdentity
366
+ );
367
+ this._codexRecoveryReady = true;
368
+ this._codexLease = sameHost && newBoot
369
+ ? null
370
+ : {
371
+ kind: 'recovered-quarantine',
372
+ generationId: state.generationId,
373
+ quarantined: true,
374
+ };
375
+ }
376
+
377
+ _hasLiveCodexProcess() {
378
+ for (const proc of this.procs.values()) {
379
+ if (this._isCodex(proc)) return true;
380
+ }
381
+ return false;
382
+ }
383
+
384
+ _desiredIdentity(spawnContext) {
385
+ const requested = spawnContext?.runtime;
386
+ const runtime = requested == null ? 'claude' : requested;
387
+ if (runtime !== 'claude' && runtime !== 'codex') {
388
+ throw managerError(
389
+ 'Unknown agent runtime',
390
+ 'RUNTIME_UNKNOWN',
391
+ );
392
+ }
393
+ const spawnProfileId = spawnContext?.spawnProfileId ?? null;
394
+ if (
395
+ spawnProfileId != null
396
+ && !isOpaqueId(spawnProfileId)
397
+ ) {
398
+ throw managerError(
399
+ 'Runtime spawnProfileId must be a bounded opaque identifier',
400
+ 'RUNTIME_PROFILE_INVALID',
401
+ );
402
+ }
403
+ if (runtime === 'codex' && spawnProfileId == null) {
404
+ throw managerError(
405
+ 'Codex runtime requires a spawnProfileId',
406
+ 'RUNTIME_PROFILE_INVALID',
407
+ );
408
+ }
409
+ return {
410
+ runtime,
411
+ spawnProfileId,
412
+ key: `${runtime}\0${spawnProfileId ?? ''}`,
413
+ };
414
+ }
415
+
416
+ _identityFor(proc) {
417
+ const recorded = this._procIdentities.get(proc);
418
+ if (recorded) return recorded;
419
+ const runtime = this._isCodex(proc) ? 'codex' : 'claude';
420
+ const spawnProfileId = proc.spawnProfileId ?? null;
421
+ return {
422
+ runtime,
423
+ spawnProfileId,
424
+ key: `${runtime}\0${spawnProfileId ?? ''}`,
425
+ };
426
+ }
427
+
428
+ _isCodex(proc) {
429
+ return proc?.runtime === 'codex' || proc?.backend === 'codex';
430
+ }
431
+
432
+ _isStateMutationFenced(sessionKey) {
433
+ const proc = this.procs.get(sessionKey);
434
+ return Boolean(
435
+ this._shuttingDown
436
+ || this._replacing.has(sessionKey)
437
+ || (this._retirementIntents.get(sessionKey) ?? 0) > 0
438
+ || (proc && this._retiring.has(proc)),
439
+ );
440
+ }
441
+
442
+ _stateMutationFenceError() {
443
+ return managerError(
444
+ 'Runtime replacement is in progress',
445
+ 'RUNTIME_SWITCH_IN_FLIGHT',
446
+ );
447
+ }
448
+
449
+ _throwIfShuttingDown() {
450
+ if (this._shuttingDown) throw new Error('shutdown');
451
+ }
452
+
453
+ _withLifecycleGate(sessionKey, operation) {
454
+ const prior = this._lifecycleGates.get(sessionKey);
455
+ const run = Promise.resolve(prior)
456
+ .catch(() => {})
457
+ .then(operation);
458
+ this._lifecycleGates.set(sessionKey, run);
459
+ run.finally(() => {
460
+ if (this._lifecycleGates.get(sessionKey) === run) {
461
+ this._lifecycleGates.delete(sessionKey);
462
+ this._maybeSignalLruWaiter();
463
+ }
464
+ }).catch(() => {});
465
+ return run;
466
+ }
467
+
468
+ _withRetirementIntent(sessionKey, operation) {
469
+ const count = (this._retirementIntents.get(sessionKey) ?? 0) + 1;
470
+ this._retirementIntents.set(sessionKey, count);
471
+ let run;
472
+ try {
473
+ run = this._withLifecycleGate(sessionKey, operation);
474
+ } catch (error) {
475
+ this._releaseRetirementIntent(sessionKey);
476
+ return Promise.reject(error);
477
+ }
478
+ run.finally(() => {
479
+ this._releaseRetirementIntent(sessionKey);
480
+ }).catch(() => {});
481
+ return run;
482
+ }
483
+
484
+ _releaseRetirementIntent(sessionKey) {
485
+ const remaining = (this._retirementIntents.get(sessionKey) ?? 1) - 1;
486
+ if (remaining <= 0) {
487
+ this._retirementIntents.delete(sessionKey);
488
+ } else {
489
+ this._retirementIntents.set(sessionKey, remaining);
490
+ }
491
+ }
492
+
215
493
  // ─── Spawn + LRU ─────────────────────────────────────────────────
216
494
 
217
495
  /**
@@ -222,10 +500,47 @@ class ProcessManager {
222
500
  * @param {string} sessionKey
223
501
  * @param {object} spawnContext — passed through to processFactory + start()
224
502
  */
225
- async getOrSpawn(sessionKey, spawnContext) {
226
- if (this._shuttingDown) throw new Error('shutdown');
503
+ getOrSpawn(sessionKey, spawnContext) {
504
+ if (this._shuttingDown) return Promise.reject(new Error('shutdown'));
505
+ let desired;
506
+ try {
507
+ desired = this._desiredIdentity(spawnContext);
508
+ } catch (error) {
509
+ return Promise.reject(error);
510
+ }
227
511
 
512
+ const replacement = this._replacing.get(sessionKey);
513
+ if (replacement) {
514
+ if (replacement.identityKey !== desired.key) {
515
+ return Promise.reject(managerError(
516
+ 'A different runtime replacement is already in progress',
517
+ 'RUNTIME_SWITCH_IN_FLIGHT',
518
+ ));
519
+ }
520
+ return replacement.promise;
521
+ }
228
522
  const existing = this.procs.get(sessionKey);
523
+ if (existing && this._retiring.has(existing)) {
524
+ return Promise.reject(this._stateMutationFenceError());
525
+ }
526
+ if (
527
+ existing
528
+ && !existing.closed
529
+ && this._identityFor(existing).key !== desired.key
530
+ ) {
531
+ return this.replaceRuntime(sessionKey, spawnContext, desired);
532
+ }
533
+ return this._withLifecycleGate(sessionKey, () => (
534
+ this._getOrSpawnLocked(sessionKey, spawnContext, desired)
535
+ ));
536
+ }
537
+
538
+ async _getOrSpawnLocked(sessionKey, spawnContext, desired) {
539
+ this._throwIfShuttingDown();
540
+ const existing = this.procs.get(sessionKey);
541
+ if (existing && this._retiring.has(existing)) {
542
+ throw this._stateMutationFenceError();
543
+ }
229
544
  if (existing && !existing.closed) {
230
545
  // getOrSpawn registers the proc in this.procs BEFORE awaiting
231
546
  // start(). A concurrent getOrSpawn for the same key (a second
@@ -236,102 +551,574 @@ class ProcessManager {
236
551
  // production 2026-05-16: msg 2 of a 3-message burst returned
237
552
  // "No response generated"). Await the in-flight spawn so every
238
553
  // caller receives a proc whose start() has fully resolved.
239
- const pendingStart = this._starting.get(sessionKey);
240
- if (pendingStart) await pendingStart;
554
+ if (this._identityFor(existing).key !== desired.key) {
555
+ return this._replaceRuntimeLocked(sessionKey, spawnContext, desired);
556
+ }
241
557
  // Reload-on-drift (cli): a warm cli proc can't hot-swap model/effort
242
558
  // (spawn-time flags). If the resolved config has drifted and the proc is
243
559
  // idle, kill it (preserves session_id) and fall through to a cold respawn
244
560
  // → --resume keeps the conversation, the new --model/--effort takes
245
561
  // effect. In-flight cli procs and SDK procs (no wouldReloadFor — they
246
562
  // apply model live) are reused unchanged.
247
- if (typeof existing.wouldReloadFor === 'function' && existing.wouldReloadFor(spawnContext)) {
563
+ if (this._isCodex(existing) && existing.state === 'Stopped') {
564
+ await this._killLocked(sessionKey, 'stopped-generation');
565
+ this._throwIfShuttingDown();
566
+ } else if (
567
+ typeof existing.wouldReloadFor === 'function'
568
+ && existing.wouldReloadFor(spawnContext)
569
+ ) {
248
570
  this._logEvent('cli-config-reload', {
249
571
  sessionKey,
250
572
  from_model: existing.model,
251
573
  from_effort: existing.effort,
252
574
  });
253
- await this.kill(sessionKey, 'config-reload');
575
+ await this._killLocked(sessionKey, 'config-reload');
576
+ this._throwIfShuttingDown();
254
577
  // fall through to the cold-spawn path below — respawns with --resume
255
578
  } else {
579
+ if (
580
+ this._isCodex(existing)
581
+ && spawnContext?.modelSettings != null
582
+ ) {
583
+ const nextTurn = requireModelSettings(
584
+ spawnContext.modelSettings,
585
+ 'Codex spawnContext.modelSettings',
586
+ );
587
+ const result = await existing.selectModelSettings(nextTurn);
588
+ if (
589
+ result?.outcome !== 'updated-live'
590
+ || result.generationId !== existing.generationId
591
+ || result.nextTurn?.model !== nextTurn.model
592
+ || result.nextTurn?.effort !== nextTurn.effort
593
+ ) {
594
+ throw managerError(
595
+ 'Warm Codex generation did not accept the selected model settings',
596
+ 'CODEX_MODEL_SETTINGS_NOT_APPLIED',
597
+ );
598
+ }
599
+ }
256
600
  return existing;
257
601
  }
258
602
  }
259
603
 
604
+ this._throwIfShuttingDown();
605
+ return this._spawnFresh(sessionKey, spawnContext, desired);
606
+ }
607
+
608
+ async _spawnFresh(
609
+ sessionKey,
610
+ spawnContext,
611
+ desired,
612
+ { leaseAlreadyReserved = false } = {},
613
+ ) {
614
+ let leaseReservation = null;
615
+ let startAttempted = false;
616
+ if (desired.runtime === 'codex') {
617
+ leaseReservation = leaseAlreadyReserved
618
+ ? this._codexLease
619
+ : this._reserveCodexLease(sessionKey);
620
+ }
621
+ const releaseDefinitelyUnstartedReservation = () => {
622
+ if (
623
+ desired.runtime === 'codex'
624
+ && this._codexLease === leaseReservation
625
+ && leaseReservation?.sessionKey === sessionKey
626
+ && !startAttempted
627
+ ) {
628
+ this._codexLease = null;
629
+ }
630
+ };
631
+
260
632
  // Provisional new-process cost — ask the factory but don't start yet.
261
- const newProc = this.processFactory(sessionKey, spawnContext);
262
- const newCost = newProc.cost;
263
-
264
- while (this.totalCost + newCost > this.budget) {
265
- const evicted = this._evictLRU(); // skips inFlight + background-job-pinned
266
- if (evicted) continue;
267
- // _evictLRU freed nothing. Policy C — split by WHY:
268
- if (this._hasPinnedSession()) {
269
- // A DURABLE blocker (live background job) holds a slot. Don't park on it (could be
270
- // ~an hour) and don't kill it. The budget caps RSS, not correctness — so treat it as
271
- // SOFT: spawn over budget + warn; the operator reclaims by /reset-ing a chat.
272
- const pinned = this._pinnedSessionKeys();
273
- this._logEvent('lru-overflow-pinned', {
274
- active: this.procs.size,
275
- totalCost: this.totalCost,
276
- budget: this.budget,
277
- newCost,
278
- pinned,
279
- });
280
- this.logger.warn?.(
281
- `[pm] budget ${this.budget} exceeded (~${this.totalCost + newCost}): all free slots hold ` +
282
- `live background jobs [${pinned.join(', ')}]. Spawning over limit — /reset one of those ` +
283
- `chats to reclaim memory.`,
633
+ let newProc;
634
+ try {
635
+ newProc = this.processFactory(sessionKey, spawnContext);
636
+ } catch (error) {
637
+ releaseDefinitelyUnstartedReservation();
638
+ throw error;
639
+ }
640
+ try {
641
+ const actualRuntime = this._isCodex(newProc) ? 'codex' : 'claude';
642
+ if (
643
+ actualRuntime !== desired.runtime
644
+ || (
645
+ desired.runtime === 'codex'
646
+ ? newProc.spawnProfileId !== desired.spawnProfileId
647
+ : (
648
+ newProc.spawnProfileId != null
649
+ && newProc.spawnProfileId !== desired.spawnProfileId
650
+ )
651
+ )
652
+ ) {
653
+ throw managerError(
654
+ 'Process factory returned a different runtime/profile identity',
655
+ 'RUNTIME_FACTORY_MISMATCH',
656
+ );
657
+ }
658
+ this._procIdentities.set(newProc, desired);
659
+ if (newProc.runtime == null) newProc.runtime = desired.runtime;
660
+ if (
661
+ desired.runtime !== 'codex'
662
+ && newProc.spawnProfileId == null
663
+ && desired.spawnProfileId != null
664
+ ) {
665
+ newProc.spawnProfileId = desired.spawnProfileId;
666
+ }
667
+ } catch (error) {
668
+ releaseDefinitelyUnstartedReservation();
669
+ throw error;
670
+ }
671
+
672
+ try {
673
+ const newCost = newProc.cost;
674
+ while (this.totalCost + newCost > this.budget) {
675
+ const evicted = this._evictLRU(); // skips inFlight + background-job-pinned
676
+ if (evicted) continue;
677
+ // _evictLRU freed nothing. Policy C — split by WHY:
678
+ if (this._hasPinnedSession()) {
679
+ // A DURABLE blocker (live background job) holds a slot. Don't park on it (could be
680
+ // ~an hour) and don't kill it. The budget caps RSS, not correctness — so treat it as
681
+ // SOFT: spawn over budget + warn; the operator reclaims by /reset-ing a chat.
682
+ const pinned = this._pinnedSessionKeys();
683
+ this._logEvent('lru-overflow-pinned', {
684
+ active: this.procs.size,
685
+ totalCost: this.totalCost,
686
+ budget: this.budget,
687
+ newCost,
688
+ pinned,
689
+ });
690
+ this.logger.warn?.(
691
+ `[pm] budget ${this.budget} exceeded (~${this.totalCost + newCost}): all free slots hold ` +
692
+ `live background jobs [${pinned.join(', ')}]. Spawning over limit — /reset one of those ` +
693
+ `chats to reclaim memory.`,
694
+ );
695
+ break; // soft overflow — spawn anyway
696
+ }
697
+ // No pin — the blockers are all in-flight TURNS (transient, finish in seconds). Keep the
698
+ // existing behavior: park briefly for a slot rather than needlessly overflow.
699
+ await this._awaitLruSlot();
700
+ this._throwIfShuttingDown();
701
+ // Loop again — budget may have freed up.
702
+ }
703
+
704
+ this._throwIfShuttingDown();
705
+ // A concurrent lifecycle source may have registered a process while we
706
+ // were parked. The provisional object is definitely unstarted here.
707
+ const competitor = this.procs.get(sessionKey);
708
+ if (competitor && !competitor.closed) {
709
+ releaseDefinitelyUnstartedReservation();
710
+ if (this._identityFor(competitor).key === desired.key) {
711
+ return competitor;
712
+ }
713
+ return this._replaceRuntimeLocked(
714
+ sessionKey,
715
+ spawnContext,
716
+ desired,
284
717
  );
285
- break; // soft overflow — spawn anyway
286
- }
287
- // No pin — the blockers are all in-flight TURNS (transient, finish in seconds). Keep the
288
- // existing behavior: park briefly for a slot rather than needlessly overflow.
289
- await this._awaitLruSlot();
290
- if (this._shuttingDown) {
291
- try { await newProc.kill('shutdown'); } catch {}
292
- throw new Error('shutdown');
293
- }
294
- // Loop again — budget may have freed up.
295
- }
296
-
297
- // A concurrent getOrSpawn for this key may have registered its own
298
- // process while we were suspended above (awaiting the config-reload
299
- // kill or parked on an LRU slot). Registering ours now would
300
- // overwrite that entry — the overwritten process would keep running
301
- // outside the Map (never evicted, never killed, resuming the same
302
- // claude session in parallel). Yield to the competitor instead; our
303
- // provisional process was never started, so dropping it is free.
304
- const competitor = this.procs.get(sessionKey);
305
- if (competitor && !competitor.closed) {
306
- const competitorStart = this._starting.get(sessionKey);
307
- if (competitorStart) await competitorStart;
308
- return competitor;
309
- }
310
-
311
- this._wireCallbacks(newProc);
312
- this.procs.set(sessionKey, newProc);
313
- newProc.lastUsedTs = Date.now();
314
- // Publish the in-flight start() Promise so concurrent getOrSpawn
315
- // callers (above) can await it instead of racing the spawn.
316
- const startP = newProc.start(spawnContext);
317
- this._starting.set(sessionKey, startP);
718
+ }
719
+ this._throwIfShuttingDown();
720
+ } catch (error) {
721
+ releaseDefinitelyUnstartedReservation();
722
+ throw error;
723
+ }
724
+
725
+ let startP;
726
+ try {
727
+ if (desired.runtime === 'codex') {
728
+ this._bindCodexLease(leaseReservation, sessionKey, newProc);
729
+ }
730
+ this._wireCallbacks(newProc);
731
+ this.procs.set(sessionKey, newProc);
732
+ newProc.lastUsedTs = Date.now();
733
+ // Publish the in-flight start() Promise so concurrent getOrSpawn
734
+ // callers (above) can await it instead of racing the spawn.
735
+ // Enter through a promise boundary so a subclass that throws
736
+ // synchronously from start() follows the same map/lease cleanup path as
737
+ // an asynchronous rejection.
738
+ startP = Promise.resolve().then(() => {
739
+ startAttempted = true;
740
+ return newProc.start(newProc.spawnOptions ?? spawnContext);
741
+ });
742
+ this._starting.set(sessionKey, startP);
743
+ } catch (error) {
744
+ if (this.procs.get(sessionKey) === newProc) {
745
+ this.procs.delete(sessionKey);
746
+ }
747
+ releaseDefinitelyUnstartedReservation();
748
+ throw error;
749
+ }
318
750
  try {
319
751
  await startP;
320
752
  } catch (err) {
321
- this.procs.delete(sessionKey);
753
+ const startupReleaseSafe = (
754
+ desired.runtime === 'codex'
755
+ && newProc.startupReleaseSafe === true
756
+ && newProc.closed === true
757
+ && this._codexLeaseMatches(newProc)
758
+ );
759
+ if (startupReleaseSafe) {
760
+ if (this.procs.get(sessionKey) === newProc) {
761
+ this.procs.delete(sessionKey);
762
+ }
763
+ this._codexLease = null;
764
+ this._maybeSignalLruWaiter();
765
+ } else if (desired.runtime === 'codex') {
766
+ // A rejected Codex start remains the exact inspectable ownership
767
+ // fence unless startup proves no child or session mutation escaped.
768
+ this.procs.set(sessionKey, newProc);
769
+ } else if (desired.runtime !== 'codex') {
770
+ if (this.procs.get(sessionKey) === newProc) {
771
+ this.procs.delete(sessionKey);
772
+ }
773
+ this._maybeSignalLruWaiter();
774
+ }
322
775
  throw err;
323
776
  } finally {
324
777
  this._starting.delete(sessionKey);
325
778
  }
779
+ this._throwIfShuttingDown();
326
780
  return newProc;
327
781
  }
328
782
 
783
+ _reserveCodexLease(sessionKey) {
784
+ if (!this._codexRecoveryReady) {
785
+ throw managerError(
786
+ 'Codex ownership recovery has not been restored',
787
+ 'CODEX_RECOVERY_NOT_READY',
788
+ );
789
+ }
790
+ if (this._codexLease) {
791
+ throw managerError(
792
+ 'Native Codex generation is already active',
793
+ 'CODEX_DAEMON_GENERATION_BUSY',
794
+ );
795
+ }
796
+ const reservation = {
797
+ kind: 'reservation',
798
+ proc: null,
799
+ sessionKey,
800
+ generationId: null,
801
+ healthyStopped: false,
802
+ transportClosed: false,
803
+ terminalStatus: null,
804
+ turnId: null,
805
+ quarantined: false,
806
+ };
807
+ this._codexLease = reservation;
808
+ return reservation;
809
+ }
810
+
811
+ _bindCodexLease(lease, sessionKey, proc) {
812
+ if (
813
+ !lease
814
+ || this._codexLease !== lease
815
+ || lease.proc
816
+ || lease.sessionKey !== sessionKey
817
+ ) {
818
+ throw managerError(
819
+ 'Native Codex generation ownership is already reserved',
820
+ 'CODEX_DAEMON_GENERATION_BUSY',
821
+ );
822
+ }
823
+ if (!isOpaqueId(proc.generationId)) {
824
+ throw managerError(
825
+ 'Codex process did not expose a bounded generationId',
826
+ 'CODEX_GENERATION_INVALID',
827
+ );
828
+ }
829
+ if (
830
+ !isOpaqueId(this.codexHostIdentity)
831
+ || !isOpaqueId(this.codexBootSessionIdentity)
832
+ || proc.hostIdentity !== this.codexHostIdentity
833
+ || proc.bootSessionIdentity !== this.codexBootSessionIdentity
834
+ ) {
835
+ throw managerError(
836
+ 'Codex process host/boot identity does not match manager ownership',
837
+ 'CODEX_GENERATION_INVALID',
838
+ );
839
+ }
840
+ lease.kind = 'generation';
841
+ lease.proc = proc;
842
+ lease.sessionKey = sessionKey;
843
+ lease.generationId = proc.generationId;
844
+ lease.hostIdentity = this.codexHostIdentity;
845
+ lease.bootSessionIdentity = this.codexBootSessionIdentity;
846
+ lease.healthyStopped = false;
847
+ lease.transportClosed = false;
848
+ lease.terminalStatus = null;
849
+ lease.turnId = null;
850
+ }
851
+
852
+ _codexLeaseMatches(proc, generationId = proc?.generationId) {
853
+ return Boolean(
854
+ this._codexLease
855
+ && this._codexLease.proc === proc
856
+ && this._codexLease.generationId === generationId
857
+ && proc?.generationId === generationId
858
+ );
859
+ }
860
+
861
+ _strictSwitchBlocked(proc) {
862
+ if (
863
+ proc.inFlight
864
+ || proc.hasActiveBackgroundWork?.()
865
+ || proc.hasOpenQuestions?.()
866
+ || proc.hasPendingDeliveryWork?.()
867
+ ) return true;
868
+ return new Set([
869
+ 'RecoveryConflict',
870
+ 'ContainmentFailed',
871
+ 'FailedAmbiguous',
872
+ 'DurabilityBlocked',
873
+ 'StartingTurn',
874
+ 'Active',
875
+ 'Settling',
876
+ 'BackgroundWorking',
877
+ 'BackgroundSettling',
878
+ 'Quiescing',
879
+ ]).has(proc.state);
880
+ }
881
+
882
+ replaceRuntime(sessionKey, spawnContext, desiredIdentity = null) {
883
+ if (this._shuttingDown) return Promise.reject(new Error('shutdown'));
884
+ let desired;
885
+ try {
886
+ desired = desiredIdentity ?? this._desiredIdentity(spawnContext);
887
+ } catch (error) {
888
+ return Promise.reject(error);
889
+ }
890
+ const active = this._replacing.get(sessionKey);
891
+ if (active) {
892
+ if (active.identityKey === desired.key) return active.promise;
893
+ return Promise.reject(managerError(
894
+ 'A different runtime replacement is already in progress',
895
+ 'RUNTIME_SWITCH_IN_FLIGHT',
896
+ ));
897
+ }
898
+ const operation = this._withLifecycleGate(sessionKey, () => {
899
+ this._throwIfShuttingDown();
900
+ return this._replaceRuntimeLocked(sessionKey, spawnContext, desired);
901
+ });
902
+ const entry = { identityKey: desired.key, promise: operation };
903
+ this._replacing.set(sessionKey, entry);
904
+ operation.finally(() => {
905
+ if (this._replacing.get(sessionKey) === entry) {
906
+ this._replacing.delete(sessionKey);
907
+ }
908
+ }).catch(() => {});
909
+ return operation;
910
+ }
911
+
912
+ async _replaceRuntimeLocked(sessionKey, spawnContext, desired) {
913
+ this._throwIfShuttingDown();
914
+ const old = this.procs.get(sessionKey);
915
+ if (!old || old.closed) {
916
+ return this._spawnFresh(sessionKey, spawnContext, desired);
917
+ }
918
+ if (this._identityFor(old).key === desired.key) return old;
919
+ if (this._strictSwitchBlocked(old)) {
920
+ throw managerError(
921
+ 'Runtime/profile switch is blocked by live session work',
922
+ 'RUNTIME_SWITCH_IN_FLIGHT',
923
+ );
924
+ }
925
+
926
+ const oldIsCodex = this._isCodex(old);
927
+ let reservation = null;
928
+ let transferredLease = false;
929
+ if (desired.runtime === 'codex') {
930
+ if (oldIsCodex && this._codexLeaseMatches(old)) {
931
+ reservation = this._codexLease;
932
+ transferredLease = true;
933
+ } else {
934
+ reservation = this._reserveCodexLease(sessionKey);
935
+ }
936
+ }
937
+
938
+ try {
939
+ await this._strictRetire(old, 'runtime-switch');
940
+ } catch (cause) {
941
+ const retainExactFence = Boolean(
942
+ findCodexRetirementVerificationError(cause)
943
+ && this._codexLeaseMatches(old),
944
+ );
945
+ if (!retainExactFence) {
946
+ this._retiring.delete(old);
947
+ if (
948
+ reservation
949
+ && !transferredLease
950
+ && this._codexLease === reservation
951
+ ) {
952
+ this._codexLease = null;
953
+ }
954
+ if (old.closed && this.procs.get(sessionKey) === old) {
955
+ this.procs.delete(sessionKey);
956
+ } else if (!old.closed && !this.procs.has(sessionKey)) {
957
+ this.procs.set(sessionKey, old);
958
+ }
959
+ }
960
+ throw managerError(
961
+ 'Existing runtime could not be safely retired',
962
+ 'RUNTIME_SWITCH_EVICTION_FAILED',
963
+ { cause },
964
+ );
965
+ }
966
+
967
+ if (this.procs.get(sessionKey) === old) this.procs.delete(sessionKey);
968
+ this._retiring.delete(old);
969
+ if (oldIsCodex) {
970
+ if (!this._codexLeaseMatches(old)) {
971
+ // A stale lifecycle event or ownership change cannot release the
972
+ // daemon-wide fence.
973
+ if (!this.procs.has(sessionKey)) this.procs.set(sessionKey, old);
974
+ throw managerError(
975
+ 'Codex generation ownership changed during retirement',
976
+ 'RUNTIME_SWITCH_EVICTION_FAILED',
977
+ );
978
+ }
979
+ if (desired.runtime === 'codex') {
980
+ const lease = this._codexLease;
981
+ lease.kind = 'reservation';
982
+ lease.proc = null;
983
+ lease.sessionKey = sessionKey;
984
+ lease.generationId = null;
985
+ lease.healthyStopped = false;
986
+ lease.transportClosed = false;
987
+ lease.terminalStatus = null;
988
+ lease.turnId = null;
989
+ reservation = lease;
990
+ } else {
991
+ this._codexLease = null;
992
+ }
993
+ }
994
+ this._maybeSignalLruWaiter();
995
+
996
+ try {
997
+ this._throwIfShuttingDown();
998
+ return await this._spawnFresh(
999
+ sessionKey,
1000
+ spawnContext,
1001
+ desired,
1002
+ { leaseAlreadyReserved: desired.runtime === 'codex' },
1003
+ );
1004
+ } catch (error) {
1005
+ // Factory/pre-construction failure has no generation to fence. Once the
1006
+ // lease is bound to a process, _spawnFresh intentionally retains it.
1007
+ if (
1008
+ desired.runtime === 'codex'
1009
+ && this._codexLease === reservation
1010
+ && reservation?.kind === 'reservation'
1011
+ ) {
1012
+ this._codexLease = null;
1013
+ }
1014
+ throw error;
1015
+ }
1016
+ }
1017
+
1018
+ async _strictRetire(proc, reason) {
1019
+ this._retiring.add(proc);
1020
+ if (this._isCodex(proc)) {
1021
+ if (!this._codexLeaseMatches(proc)) {
1022
+ throw managerError(
1023
+ 'Codex generation does not own the daemon lease',
1024
+ 'CODEX_DAEMON_GENERATION_BUSY',
1025
+ );
1026
+ }
1027
+ await proc.interrupt();
1028
+ if (
1029
+ proc.state !== 'Stopped'
1030
+ || !this._codexLeaseMatches(proc)
1031
+ || !this._codexLease.healthyStopped
1032
+ || this._codexLease.quarantined
1033
+ ) {
1034
+ throw managerError(
1035
+ 'Codex generation did not prove exact healthy settlement',
1036
+ 'CODEX_RETIREMENT_UNVERIFIED',
1037
+ );
1038
+ }
1039
+ await proc.kill(reason);
1040
+ if (
1041
+ !proc.closed
1042
+ || !this._codexLeaseMatches(proc)
1043
+ || !this._codexLease.transportClosed
1044
+ || this._codexLease.quarantined
1045
+ ) {
1046
+ throw managerError(
1047
+ 'Codex transport did not prove closed after settlement',
1048
+ 'CODEX_RETIREMENT_UNVERIFIED',
1049
+ );
1050
+ }
1051
+ if (this.codexRetirementVerifier) {
1052
+ await this._verifyCodexRetirement(proc, reason);
1053
+ }
1054
+ return;
1055
+ }
1056
+ await proc.kill(reason);
1057
+ if (!proc.closed) {
1058
+ throw managerError(
1059
+ 'Runtime transport did not close',
1060
+ 'RUNTIME_RETIREMENT_UNVERIFIED',
1061
+ );
1062
+ }
1063
+ }
1064
+
1065
+ async _verifyCodexRetirement(proc, reason) {
1066
+ let timer = null;
1067
+ const abortController = new AbortController();
1068
+ try {
1069
+ const verification = await Promise.race([
1070
+ Promise.resolve().then(() => this.codexRetirementVerifier({
1071
+ sessionKey: proc.sessionKey,
1072
+ generationId: proc.generationId,
1073
+ reason,
1074
+ terminalStatus: this._codexLease.terminalStatus ?? null,
1075
+ turnId: this._codexLease.turnId ?? null,
1076
+ signal: abortController.signal,
1077
+ })),
1078
+ new Promise((resolve, reject) => {
1079
+ timer = setTimeout(() => {
1080
+ const timeoutError = managerError(
1081
+ 'Codex consumer retirement verification timed out',
1082
+ 'CODEX_RETIREMENT_VERIFICATION_FAILED',
1083
+ );
1084
+ reject(timeoutError);
1085
+ abortController.abort(timeoutError);
1086
+ }, this.codexRetirementTimeoutMs);
1087
+ }),
1088
+ ]);
1089
+ if (verification?.committed !== true) {
1090
+ throw managerError(
1091
+ 'Codex consumer did not commit exact durable retirement',
1092
+ 'CODEX_RETIREMENT_VERIFICATION_FAILED',
1093
+ );
1094
+ }
1095
+ } catch (cause) {
1096
+ if (this._codexLeaseMatches(proc)) {
1097
+ this._codexLease.quarantined = true;
1098
+ }
1099
+ if (!abortController.signal.aborted) abortController.abort(cause);
1100
+ if (findCodexRetirementVerificationError(cause)) throw cause;
1101
+ throw managerError(
1102
+ 'Codex consumer retirement verification failed',
1103
+ 'CODEX_RETIREMENT_VERIFICATION_FAILED',
1104
+ { cause },
1105
+ );
1106
+ } finally {
1107
+ if (timer) clearTimeout(timer);
1108
+ }
1109
+ }
1110
+
329
1111
  _evictLRU() {
330
1112
  let oldest = null;
331
1113
  let oldestKey = null;
332
1114
  let pinnedSkipped = 0;
333
1115
  for (const [k, p] of this.procs.entries()) {
334
1116
  if (p.inFlight) continue;
1117
+ if (this._lifecycleGates.has(k)) continue;
1118
+ // Native Codex beta generations are daemon-wide ownership fences. They
1119
+ // are retired only through the acknowledged strict path, never from the
1120
+ // synchronous best-effort LRU path.
1121
+ if (this._isCodex(p)) { pinnedSkipped++; continue; }
335
1122
  // PIN: a session with a live detached background job is NOT evictable — killing it
336
1123
  // would silently drop the job (and its report-back wakeup). Skip like inFlight.
337
1124
  if (p.hasActiveBackgroundWork()) { pinnedSkipped++; continue; }
@@ -363,8 +1150,12 @@ class ProcessManager {
363
1150
  backend: oldest.backend,
364
1151
  pinnedSkipped,
365
1152
  });
366
- oldest.kill('evict').catch(() => {});
1153
+ this._retiring.add(oldest);
367
1154
  this.procs.delete(oldestKey);
1155
+ this._withLifecycleGate(oldestKey, async () => {
1156
+ try { await oldest.kill('evict'); } catch {}
1157
+ finally { this._retiring.delete(oldest); }
1158
+ }).catch(() => {});
368
1159
  return true;
369
1160
  }
370
1161
 
@@ -375,6 +1166,7 @@ class ProcessManager {
375
1166
  */
376
1167
  _hasPinnedSession() {
377
1168
  for (const p of this.procs.values()) {
1169
+ if (this._isCodex(p)) return true;
378
1170
  if (!p.inFlight && p.hasActiveBackgroundWork()) return true;
379
1171
  if (typeof p.hasPendingDeliveryWork === 'function' && p.hasPendingDeliveryWork()) return true;
380
1172
  // 0.16 (MF-B): an extended busy-aware-ceiling turn is a DURABLE blocker —
@@ -390,7 +1182,8 @@ class ProcessManager {
390
1182
  _pinnedSessionKeys() {
391
1183
  const keys = [];
392
1184
  for (const [k, p] of this.procs.entries()) {
393
- if (!p.inFlight && p.hasActiveBackgroundWork()) keys.push(k);
1185
+ if (this._isCodex(p)) keys.push(k);
1186
+ else if (!p.inFlight && p.hasActiveBackgroundWork()) keys.push(k);
394
1187
  else if (typeof p.hasPendingDeliveryWork === 'function' && p.hasPendingDeliveryWork()) keys.push(k);
395
1188
  else if (p.inFlight && typeof p.hasExtendedTurn === 'function' && p.hasExtendedTurn()) keys.push(k);
396
1189
  }
@@ -422,17 +1215,53 @@ class ProcessManager {
422
1215
  // ─── Per-session dispatch ────────────────────────────────────────
423
1216
 
424
1217
  async send(sessionKey, prompt, opts) {
1218
+ if (this._isStateMutationFenced(sessionKey)) {
1219
+ throw this._stateMutationFenceError();
1220
+ }
425
1221
  const proc = this.procs.get(sessionKey);
426
1222
  if (!proc) throw new Error(`no process for sessionKey ${sessionKey}`);
427
1223
  proc.lastUsedTs = Date.now();
428
1224
  return proc.send(prompt, opts);
429
1225
  }
430
1226
 
431
- async kill(sessionKey, reason = 'kill') {
1227
+ kill(sessionKey, reason = 'kill') {
1228
+ return this._withRetirementIntent(sessionKey, () => (
1229
+ this._killLocked(sessionKey, reason)
1230
+ ));
1231
+ }
1232
+
1233
+ async _killLocked(sessionKey, reason = 'kill') {
432
1234
  const proc = this.procs.get(sessionKey);
433
1235
  if (!proc) return false;
1236
+ if (this._isCodex(proc)) {
1237
+ try {
1238
+ await this._strictRetire(proc, reason);
1239
+ } catch (error) {
1240
+ if (
1241
+ findCodexRetirementVerificationError(error)
1242
+ && this._codexLeaseMatches(proc)
1243
+ ) {
1244
+ throw error;
1245
+ }
1246
+ this._retiring.delete(proc);
1247
+ if (proc.closed && this.procs.get(sessionKey) === proc) {
1248
+ this.procs.delete(sessionKey);
1249
+ } else if (!proc.closed && !this.procs.has(sessionKey)) {
1250
+ this.procs.set(sessionKey, proc);
1251
+ }
1252
+ throw error;
1253
+ }
1254
+ if (this.procs.get(sessionKey) === proc) this.procs.delete(sessionKey);
1255
+ this._retiring.delete(proc);
1256
+ if (this._codexLeaseMatches(proc)) this._codexLease = null;
1257
+ this._maybeSignalLruWaiter();
1258
+ return true;
1259
+ }
1260
+ // Preserve Claude's established best-effort teardown semantics.
1261
+ this._retiring.add(proc);
434
1262
  this.procs.delete(sessionKey);
435
1263
  try { await proc.kill(reason); } catch {}
1264
+ finally { this._retiring.delete(proc); }
436
1265
  this._maybeSignalLruWaiter();
437
1266
  return true;
438
1267
  }
@@ -443,14 +1272,9 @@ class ProcessManager {
443
1272
  for (const [sk, p] of this.procs.entries()) {
444
1273
  if (p.chatId === idStr) targets.push([sk, p]);
445
1274
  }
446
- for (const [sk] of targets) this.procs.delete(sk);
447
- const results = await Promise.allSettled(
448
- targets.map(([_, p]) => p.kill('killChat')),
1275
+ return Promise.allSettled(
1276
+ targets.map(([sk]) => this.kill(sk, 'killChat')),
449
1277
  );
450
- for (let i = 0; i < targets.length; i++) {
451
- this._maybeSignalLruWaiter();
452
- }
453
- return results;
454
1278
  }
455
1279
 
456
1280
  async shutdown() {
@@ -462,9 +1286,28 @@ class ProcessManager {
462
1286
  }
463
1287
  this._lruWaiters.length = 0;
464
1288
 
465
- const all = [...this.procs.values()];
466
- this.procs.clear();
467
- await Promise.allSettled(all.map((p) => p.kill('shutdown')));
1289
+ // First let already-admitted start/replacement/kill operations settle.
1290
+ // New lifecycle operations are rejected by _shuttingDown.
1291
+ const admittedResults = await Promise.allSettled(
1292
+ [...this._lifecycleGates.values()],
1293
+ );
1294
+ // Snapshot only after those gates finish: a start may have published a
1295
+ // process just before observing shutdown.
1296
+ const targets = [...this.procs.entries()]
1297
+ .filter(([, proc]) => !this._retiring.has(proc))
1298
+ .map(([sessionKey]) => sessionKey);
1299
+ const retirementResults = await Promise.allSettled(targets.map((sessionKey) => (
1300
+ this._withLifecycleGate(sessionKey, () => (
1301
+ this._killLocked(sessionKey, 'shutdown')
1302
+ ))
1303
+ )));
1304
+ for (const result of [...admittedResults, ...retirementResults]) {
1305
+ if (result.status !== 'rejected') continue;
1306
+ const retirementError = findCodexRetirementVerificationError(
1307
+ result.reason,
1308
+ );
1309
+ if (retirementError) throw retirementError;
1310
+ }
468
1311
  }
469
1312
 
470
1313
  // ─── Optional async — feature-detect at call site if needed ──────
@@ -488,13 +1331,140 @@ class ProcessManager {
488
1331
  }
489
1332
 
490
1333
  async interrupt(sessionKey) {
491
- return this._invokeOptional(sessionKey, 'interrupt', [], false);
1334
+ const proc = this.procs.get(sessionKey);
1335
+ if (!proc || proc.closed) return false;
1336
+ if (
1337
+ !this._isCodex(proc)
1338
+ || this._isStateMutationFenced(sessionKey)
1339
+ ) {
1340
+ return this._invokeOptional(sessionKey, 'interrupt', [], false);
1341
+ }
1342
+ return this._withRetirementIntent(sessionKey, async () => {
1343
+ if (this.procs.get(sessionKey) !== proc || proc.closed) return false;
1344
+ const interrupted = await proc.interrupt();
1345
+ if (!interrupted) return false;
1346
+ await this._killLocked(sessionKey, 'interrupt');
1347
+ return true;
1348
+ });
1349
+ }
1350
+
1351
+ async steerTurn(sessionKey, text, opts) {
1352
+ if (this._isStateMutationFenced(sessionKey)) {
1353
+ throw this._stateMutationFenceError();
1354
+ }
1355
+ return this._invokeOptional(
1356
+ sessionKey,
1357
+ 'steerTurn',
1358
+ [text, opts],
1359
+ { outcome: 'unavailable', reason: 'missing-or-closed' },
1360
+ );
492
1361
  }
493
1362
 
494
1363
  async setModel(sessionKey, model) {
1364
+ if (this._isStateMutationFenced(sessionKey)) {
1365
+ throw this._stateMutationFenceError();
1366
+ }
495
1367
  return this._invokeOptional(sessionKey, 'setModel', [model], false);
496
1368
  }
497
1369
 
1370
+ _classifyModelSettingsTarget(sessionKey) {
1371
+ if (this._isStateMutationFenced(sessionKey)) {
1372
+ return { outcome: 'unavailable', reason: 'quiescing' };
1373
+ }
1374
+ const selected = this.procs.get(sessionKey);
1375
+ if (!selected || selected.closed) {
1376
+ if (!this._codexRecoveryReady) {
1377
+ return { outcome: 'unavailable', reason: 'stale-generation' };
1378
+ }
1379
+ if (this._codexLease?.quarantined) {
1380
+ return { outcome: 'unavailable', reason: 'containment' };
1381
+ }
1382
+ if (
1383
+ this._codexLease
1384
+ && this._codexLease.sessionKey
1385
+ && this._codexLease.sessionKey !== sessionKey
1386
+ ) {
1387
+ return { outcome: 'daemon-busy' };
1388
+ }
1389
+ if (this._codexLease) {
1390
+ return { outcome: 'unavailable', reason: 'stale-generation' };
1391
+ }
1392
+ return { outcome: 'not-loaded' };
1393
+ }
1394
+ if (!this._isCodex(selected)) {
1395
+ return { outcome: 'unavailable', reason: 'wrong-runtime' };
1396
+ }
1397
+ const generationId = selected.generationId;
1398
+ const current = this.procs.get(sessionKey);
1399
+ if (
1400
+ current !== selected
1401
+ || current.closed
1402
+ || current.generationId !== generationId
1403
+ || !this._codexLeaseMatches(current, generationId)
1404
+ ) {
1405
+ return { outcome: 'unavailable', reason: 'stale-generation' };
1406
+ }
1407
+ if (
1408
+ this._codexLease.quarantined
1409
+ || [
1410
+ 'ContainmentFailed',
1411
+ 'FailedAmbiguous',
1412
+ 'DurabilityBlocked',
1413
+ ].includes(current.state)
1414
+ ) {
1415
+ return { outcome: 'unavailable', reason: 'containment' };
1416
+ }
1417
+ if (
1418
+ current.settingsAdmissionClosed
1419
+ || ['Quiescing', 'Stopped'].includes(current.state)
1420
+ ) {
1421
+ return { outcome: 'unavailable', reason: 'quiescing' };
1422
+ }
1423
+ if (current.state === 'Closed' || current.state === 'RecoveryConflict') {
1424
+ return { outcome: 'unavailable', reason: 'stale-generation' };
1425
+ }
1426
+ return { outcome: 'loaded', proc: current };
1427
+ }
1428
+
1429
+ /**
1430
+ * Return a lifecycle-consistent settings snapshot without spawning a process
1431
+ * or invoking a backend mutation.
1432
+ */
1433
+ getModelSettingsStatus(sessionKey) {
1434
+ return this._withLifecycleGate(sessionKey, () => {
1435
+ const classification = this._classifyModelSettingsTarget(sessionKey);
1436
+ if (classification.outcome !== 'loaded') return classification;
1437
+ const { proc } = classification;
1438
+ const currentSettings = (
1439
+ proc.activeTurnSettings
1440
+ ?? proc.admittingTurnSettings
1441
+ ?? null
1442
+ );
1443
+ return {
1444
+ outcome: 'loaded',
1445
+ threadId: proc.providerSessionId ?? null,
1446
+ generationId: proc.generationId,
1447
+ currentTurn: snapshotModelSettings(currentSettings),
1448
+ nextTurn: snapshotModelSettings(proc.desiredSettings),
1449
+ observedThread: snapshotModelSettings(proc.observedThreadSettings),
1450
+ };
1451
+ });
1452
+ }
1453
+
1454
+ async selectModelSettings(sessionKey, settings) {
1455
+ const nextTurn = requireModelSettings(
1456
+ settings,
1457
+ 'selectModelSettings',
1458
+ );
1459
+ return this._withLifecycleGate(sessionKey, async () => {
1460
+ const classification = this._classifyModelSettingsTarget(sessionKey);
1461
+ if (classification.outcome !== 'loaded') {
1462
+ return { ...classification, nextTurn };
1463
+ }
1464
+ return classification.proc.selectModelSettings(nextTurn);
1465
+ });
1466
+ }
1467
+
498
1468
  /**
499
1469
  * Review F#10: return the backend name for a live process so callers
500
1470
  * (slash-commands) can word their UX accurately. Returns null if no
@@ -506,14 +1476,29 @@ class ProcessManager {
506
1476
  }
507
1477
 
508
1478
  async applyFlagSettings(sessionKey, settings) {
1479
+ if (this._isStateMutationFenced(sessionKey)) {
1480
+ throw this._stateMutationFenceError();
1481
+ }
509
1482
  return this._invokeOptional(sessionKey, 'applyFlagSettings', [settings], false);
510
1483
  }
511
1484
 
512
1485
  async setPermissionMode(sessionKey, mode) {
1486
+ if (this._isStateMutationFenced(sessionKey)) {
1487
+ throw this._stateMutationFenceError();
1488
+ }
513
1489
  return this._invokeOptional(sessionKey, 'setPermissionMode', [mode], false);
514
1490
  }
515
1491
 
516
- async resetSession(sessionKey, opts) {
1492
+ resetSession(sessionKey, opts) {
1493
+ if (this._isStateMutationFenced(sessionKey)) {
1494
+ return Promise.reject(this._stateMutationFenceError());
1495
+ }
1496
+ return this._withRetirementIntent(sessionKey, () => (
1497
+ this._resetSessionLocked(sessionKey, opts)
1498
+ ));
1499
+ }
1500
+
1501
+ async _resetSessionLocked(sessionKey, opts) {
517
1502
  const p = this.procs.get(sessionKey);
518
1503
  // No active process for this key — return no-op. Matches the
519
1504
  // pre-0.10.0 SDK pm semantic (`closed: false` = "we did not close
@@ -532,7 +1517,7 @@ class ProcessManager {
532
1517
  } catch (err) {
533
1518
  if (err.code === 'UNSUPPORTED_OPERATION' || err.code === 'NOT_IMPLEMENTED_YET') {
534
1519
  const drained = p.drainQueue('RESET_SESSION');
535
- await this.kill(sessionKey, 'reset');
1520
+ await this._killLocked(sessionKey, 'reset');
536
1521
  return { closed: true, drainedPendings: drained };
537
1522
  }
538
1523
  throw err;
@@ -552,6 +1537,7 @@ class ProcessManager {
552
1537
  }
553
1538
 
554
1539
  injectUserMessage(sessionKey, opts) {
1540
+ if (this._isStateMutationFenced(sessionKey)) return false;
555
1541
  const p = this.procs.get(sessionKey);
556
1542
  if (!p || p.closed) return false;
557
1543
  return p.injectUserMessage(opts);
@@ -560,12 +1546,14 @@ class ProcessManager {
560
1546
  // 0.12 interactive questions: hand an answer back to a blocking `ask` tool call.
561
1547
  // Returns false if the session is gone (claude is dead → nothing to answer).
562
1548
  answerQuestion(sessionKey, toolCallId, result) {
1549
+ if (this._isStateMutationFenced(sessionKey)) return false;
563
1550
  const p = this.procs.get(sessionKey);
564
1551
  if (!p || p.closed || typeof p.writeQuestionAnswer !== 'function') return false;
565
1552
  return p.writeQuestionAnswer(toolCallId, result);
566
1553
  }
567
1554
 
568
1555
  steer(sessionKey, text, opts) {
1556
+ if (this._isStateMutationFenced(sessionKey)) return false;
569
1557
  const p = this.procs.get(sessionKey);
570
1558
  if (!p || p.closed) return false;
571
1559
  return p.steer(text, opts);
@@ -584,10 +1572,32 @@ class ProcessManager {
584
1572
  * LRU waiters + remove from the Map.
585
1573
  */
586
1574
  _wireCallbacks(proc) {
1575
+ const capturedGeneration = proc.generationId ?? null;
1576
+ const hasCapturedGeneration = () => (
1577
+ capturedGeneration == null
1578
+ || proc.generationId === capturedGeneration
1579
+ );
1580
+ const isCurrentGeneration = () => (
1581
+ this.procs.get(proc.sessionKey) === proc
1582
+ && !this._retiring.has(proc)
1583
+ && hasCapturedGeneration()
1584
+ );
587
1585
  for (const [cbName, eventName] of Object.entries(CALLBACK_TO_EVENT)) {
588
1586
  const fn = this.callbacks[cbName];
589
1587
  if (typeof fn !== 'function') continue;
590
1588
  proc.on(eventName, (...args) => {
1589
+ const isRetirementClose = (
1590
+ eventName === 'close'
1591
+ && this._retiring.has(proc)
1592
+ && hasCapturedGeneration()
1593
+ );
1594
+ if (!isCurrentGeneration() && !isRetirementClose) {
1595
+ this._logEvent('stale-process-callback', {
1596
+ callback: cbName,
1597
+ backend: proc.backend,
1598
+ });
1599
+ return;
1600
+ }
591
1601
  try { fn(proc.sessionKey, ...args, proc); }
592
1602
  catch (err) {
593
1603
  this.logger.error?.(`[pm:${proc.label}] callback ${cbName} threw: ${err.message}`);
@@ -597,7 +1607,10 @@ class ProcessManager {
597
1607
  // Generic 'error' channel — log + forward via onError if provided.
598
1608
  proc.on('error', (err) => {
599
1609
  this.logger.error?.(`[pm:${proc.label}] process error: ${err.message}`);
600
- if (typeof this.callbacks.onError === 'function') {
1610
+ if (
1611
+ isCurrentGeneration()
1612
+ && typeof this.callbacks.onError === 'function'
1613
+ ) {
601
1614
  try { this.callbacks.onError(proc.sessionKey, err, proc); }
602
1615
  catch (e) { this.logger.error?.(`[pm:${proc.label}] onError threw: ${e.message}`); }
603
1616
  }
@@ -606,10 +1619,48 @@ class ProcessManager {
606
1619
  // parked LRU waiter that a non-in-flight slot is available.
607
1620
  proc.on('idle', () => this._maybeSignalLruWaiter());
608
1621
  proc.on('delivery-work-settled', () => this._maybeSignalLruWaiter());
1622
+ if (this._isCodex(proc)) {
1623
+ proc.on('codex-settled', (payload) => {
1624
+ if (
1625
+ payload?.kind === 'stopped'
1626
+ && payload.generationId === capturedGeneration
1627
+ && payload.hostIdentity === this._codexLease?.hostIdentity
1628
+ && payload.bootSessionIdentity
1629
+ === this._codexLease?.bootSessionIdentity
1630
+ && payload.trackedTerminalCleanupAccepted === true
1631
+ && payload.freshRegistryObservedEmpty === true
1632
+ && this._codexLeaseMatches(proc, capturedGeneration)
1633
+ && !this._codexLease.quarantined
1634
+ ) {
1635
+ this._codexLease.healthyStopped = true;
1636
+ this._codexLease.terminalStatus = payload.terminalStatus ?? null;
1637
+ this._codexLease.turnId = payload.turnId ?? null;
1638
+ }
1639
+ });
1640
+ proc.on('containment-failed', (payload) => {
1641
+ if (
1642
+ payload?.generationId === capturedGeneration
1643
+ && this._codexLeaseMatches(proc, capturedGeneration)
1644
+ ) {
1645
+ this._codexLease.quarantined = true;
1646
+ }
1647
+ });
1648
+ }
609
1649
  // 'close': process closed itself (iteration loop exited or
610
1650
  // _closeQuery returned). Remove from the Map + signal LRU.
611
1651
  proc.on('close', () => {
612
- if (this.procs.get(proc.sessionKey) === proc) {
1652
+ if (
1653
+ this._isCodex(proc)
1654
+ && this._codexLeaseMatches(proc, capturedGeneration)
1655
+ ) {
1656
+ // A generic close is only a transport fact. It never releases the
1657
+ // ownership fence by itself.
1658
+ this._codexLease.transportClosed = true;
1659
+ }
1660
+ if (
1661
+ !this._retiring.has(proc)
1662
+ && this.procs.get(proc.sessionKey) === proc
1663
+ ) {
613
1664
  this.procs.delete(proc.sessionKey);
614
1665
  }
615
1666
  this._maybeSignalLruWaiter();
@@ -626,9 +1677,13 @@ class ProcessManager {
626
1677
  // burn LRU budget. Lazy respawn on next message is the right shape.
627
1678
  proc.on('bridge-disconnected', () => {
628
1679
  this.logger.warn?.(`[pm:${proc.label}] channels bridge disconnected — killing dead instance for lazy respawn`);
629
- // Kill is idempotent and removes the proc from the Map via the 'close'
630
- // listener wired just above.
631
- proc.kill('bridge-disconnected').catch(err => {
1680
+ // Serialize with start/replacement/kill. Re-check object identity after
1681
+ // the gate so a late disconnect from an old generation cannot kill its
1682
+ // replacement.
1683
+ this._withLifecycleGate(proc.sessionKey, async () => {
1684
+ if (this.procs.get(proc.sessionKey) !== proc) return;
1685
+ await this._killLocked(proc.sessionKey, 'bridge-disconnected');
1686
+ }).catch(err => {
632
1687
  this.logger.warn?.(`[pm:${proc.label}] kill on bridge-disconnect failed: ${err.message}`);
633
1688
  });
634
1689
  });
@@ -645,6 +1700,7 @@ class ProcessManager {
645
1700
 
646
1701
  module.exports = {
647
1702
  ProcessManager,
1703
+ ProcessManagerError,
648
1704
  DEFAULT_BUDGET,
649
1705
  CALLBACK_TO_EVENT,
650
1706
  };