@shumkov/orchestra 0.13.2 → 0.15.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.
@@ -34,8 +34,30 @@ const { createHash, hash } = require('node:crypto');
34
34
  const DEFAULT_BUDGET = 10; // total Σ cost (SDK cost=1, tmux cost=3)
35
35
  const DEFAULT_LRU_WAIT_MS = 300_000;
36
36
  const DEFAULT_CODEX_RETIREMENT_TIMEOUT_MS = 30_000;
37
+ const DEFAULT_MAX_CODEX_SESSIONS = 1;
37
38
  const MAX_RUNTIME_ID_BYTES = 512;
38
39
  const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
40
+ const CODEX_HOME_BLOCK_CODES = new Set([
41
+ 'CODEX_OWNED_CONFIG_DRIFT',
42
+ 'CODEX_OWNED_HOOKS_DRIFT',
43
+ 'CODEX_INSTRUCTION_BINDING_DRIFT',
44
+ 'CODEX_CONFIG_MISMATCH',
45
+ 'CODEX_HOOK_TRUST_UNVERIFIED',
46
+ 'CODEX_STATIC_PROFILE_MISMATCH',
47
+ ]);
48
+ const CODEX_DAEMON_BLOCK_CODES = new Set([
49
+ 'CODEX_PROCESS_CLOSE_TIMEOUT',
50
+ 'CODEX_PROCESS_CLEANUP_UNVERIFIED',
51
+ 'CODEX_STARTUP_CLOSE_UNVERIFIED',
52
+ 'CODEX_CONTAINMENT_CLOSE_TIMEOUT',
53
+ 'CODEX_RETIREMENT_UNVERIFIED',
54
+ 'CODEX_RETIREMENT_VERIFICATION_FAILED',
55
+ 'CODEX_BINARY_MISMATCH',
56
+ 'CODEX_RUNTIME_PIN_MISMATCH',
57
+ 'CODEX_SESSION_LAUNCHER_MISMATCH',
58
+ 'CODEX_DURABILITY_FAILED',
59
+ 'CODEX_BOOT_INTEGRITY_FAILED',
60
+ ]);
39
61
  const QUALIFICATION_PROCESS_STATES = new Set([
40
62
  'Spawning', 'Initializing', 'AttachingThread', 'Idle', 'StartingTurn',
41
63
  'Active', 'BackgroundWorking', 'BackgroundSettling', 'Settling',
@@ -45,9 +67,9 @@ const QUALIFICATION_PROCESS_STATES = new Set([
45
67
  const QUALIFICATION_REASONS = new Set([
46
68
  'eligible', 'active-turn', 'pending-delivery', 'background-owner',
47
69
  'background-terminals', 'pagination-incomplete', 'process-not-idle',
48
- 'process-not-ready', 'no-codex-generation', 'unsupported', 'lease-drift',
49
- 'generation-drift', 'activity-epoch-drift', 'fence-drift',
50
- 'inspection-failed', 'invalid-expectation', 'incoherent',
70
+ 'process-not-ready', 'no-codex-generation', 'multiple-codex-generations',
71
+ 'unsupported', 'lease-drift', 'generation-drift', 'activity-epoch-drift',
72
+ 'fence-drift', 'inspection-failed', 'invalid-expectation', 'incoherent',
51
73
  ]);
52
74
 
53
75
  class ProcessManagerError extends Error {
@@ -238,6 +260,24 @@ function findCodexRetirementVerificationError(error) {
238
260
  return null;
239
261
  }
240
262
 
263
+ function findMatchingErrorCode(errorOrPayload, codeSet) {
264
+ if (!errorOrPayload || typeof errorOrPayload !== 'object') return null;
265
+ let current = errorOrPayload;
266
+ for (let depth = 0; current && depth < 8; depth += 1) {
267
+ for (const candidate of [
268
+ current.code,
269
+ current.errorCode,
270
+ current.clientRootErrorCode,
271
+ ]) {
272
+ if (typeof candidate === 'string' && codeSet.has(candidate)) {
273
+ return candidate;
274
+ }
275
+ }
276
+ current = current.cause;
277
+ }
278
+ return null;
279
+ }
280
+
241
281
  function isOpaqueId(value) {
242
282
  return (
243
283
  typeof value === 'string'
@@ -447,6 +487,7 @@ class ProcessManager {
447
487
  logger = console,
448
488
  callbacks = {},
449
489
  lruWaitMs = DEFAULT_LRU_WAIT_MS,
490
+ maxCodexSessions = DEFAULT_MAX_CODEX_SESSIONS,
450
491
  codexRecoveryState,
451
492
  codexHostIdentity = null,
452
493
  codexBootSessionIdentity = null,
@@ -457,12 +498,18 @@ class ProcessManager {
457
498
  if (typeof processFactory !== 'function') {
458
499
  throw new TypeError('ProcessManager: processFactory function required');
459
500
  }
501
+ if (!Number.isSafeInteger(maxCodexSessions) || maxCodexSessions < 1) {
502
+ throw new TypeError(
503
+ 'ProcessManager: maxCodexSessions positive integer required',
504
+ );
505
+ }
460
506
  this.processFactory = processFactory;
461
507
  this.budget = budget;
462
508
  this.db = db;
463
509
  this.logger = logger;
464
510
  this.callbacks = { ...callbacks };
465
511
  this.lruWaitMs = lruWaitMs;
512
+ this.maxCodexSessions = maxCodexSessions;
466
513
  this.procs = new Map(); // sessionKey → Process
467
514
  this._lruWaiters = []; // [{ resolve, reject, timer }]
468
515
  this._shuttingDown = false;
@@ -480,9 +527,9 @@ class ProcessManager {
480
527
  this._retiring = new WeakSet();
481
528
  this._procIdentities = new WeakMap();
482
529
 
483
- // Native Codex beta ownership. Recovery is deliberately not ready by
484
- // default: the consumer must first restore the persisted daemon-wide
485
- // record, even when that record says no generation was live.
530
+ // Native Codex ownership. Recovery is deliberately not ready by default:
531
+ // the consumer must first restore the persisted record, even when that
532
+ // record says no generation was live.
486
533
  this.codexHostIdentity = codexHostIdentity;
487
534
  this.codexBootSessionIdentity = codexBootSessionIdentity;
488
535
  if (
@@ -513,7 +560,10 @@ class ProcessManager {
513
560
  }
514
561
  this.codexRetirementTimeoutMs = codexRetirementTimeoutMs;
515
562
  this._codexRecoveryReady = false;
516
- this._codexLease = null;
563
+ this._codexLeases = new Map();
564
+ this._blockedCodexHomes = new Set();
565
+ this._codexDaemonBlocked = null;
566
+ this._codexSlotLock = false;
517
567
  if (codexRecoveryState !== undefined) {
518
568
  this.restoreCodexRecoveryState(codexRecoveryState);
519
569
  }
@@ -526,33 +576,95 @@ class ProcessManager {
526
576
  keys() { return [...this.procs.keys()]; }
527
577
  get size() { return this.procs.size; }
528
578
 
579
+ _liveCodexLeases() {
580
+ const live = [];
581
+ for (const lease of this._codexLeases.values()) {
582
+ const proc = lease?.proc ?? null;
583
+ if (proc && this._isCodex(proc) && !proc.closed && this._codexLeaseMatches(proc)) {
584
+ live.push(lease);
585
+ }
586
+ }
587
+ return live;
588
+ }
589
+
590
+ _findCodexLeaseForExpectation(expectation) {
591
+ const parsed = normalizeQualificationExpectation(expectation, {
592
+ requireFence: false,
593
+ });
594
+ const live = this._liveCodexLeases();
595
+ if (!parsed.valid) return live.length === 1 ? live[0] : null;
596
+ if (parsed.expectedGenerationDigest != null) {
597
+ return live.find(
598
+ (lease) => qualificationDigest(lease.proc?.generationId)
599
+ === parsed.expectedGenerationDigest,
600
+ ) ?? null;
601
+ }
602
+ return live.length === 1 ? live[0] : null;
603
+ }
604
+
529
605
  async inspectCleanRestartQualification(expectation, { requireFence = false } = {}) {
530
- const lease = this._codexLease;
531
- const proc = lease?.proc ?? null;
532
- const sessionKey = lease?.sessionKey ?? null;
533
- const capturedFence = {
606
+ const liveLeases = this._liveCodexLeases();
607
+ const parsedExpectation = normalizeQualificationExpectation(expectation, {
608
+ requireFence,
609
+ });
610
+ const captureFenceFor = (proc) => ({
534
611
  generationDigest: qualificationDigest(proc?.generationId),
535
612
  activityEpoch: Number.isSafeInteger(proc?.activityEpoch)
536
613
  ? proc.activityEpoch
537
614
  : null,
538
- };
539
- const parsedExpectation = normalizeQualificationExpectation(expectation, {
540
- requireFence,
541
615
  });
542
616
  if (!parsedExpectation.valid) {
543
- return qualificationResultFor(proc, 'invalid-expectation', capturedFence);
544
- }
545
- if (!proc || !this._isCodex(proc) || proc.closed || !this._codexLeaseMatches(proc)) {
546
- return qualificationResultFor(proc, 'no-codex-generation', capturedFence);
617
+ const singleProc = liveLeases.length === 1 ? liveLeases[0].proc : null;
618
+ return qualificationResultFor(
619
+ singleProc,
620
+ 'invalid-expectation',
621
+ captureFenceFor(singleProc),
622
+ );
547
623
  }
548
624
 
549
625
  const { expectedGenerationDigest, expectedActivityEpoch } = parsedExpectation;
550
- if (
551
- expectedGenerationDigest != null
552
- && expectedGenerationDigest !== capturedFence.generationDigest
553
- ) {
554
- return qualificationResultFor(proc, 'generation-drift', capturedFence);
626
+ let lease = null;
627
+ if (expectedGenerationDigest != null) {
628
+ lease = liveLeases.find(
629
+ (candidate) => qualificationDigest(candidate.proc?.generationId)
630
+ === expectedGenerationDigest,
631
+ ) ?? null;
632
+ if (!lease) {
633
+ if (liveLeases.length === 0) {
634
+ return qualificationResultFor(
635
+ null,
636
+ 'no-codex-generation',
637
+ captureFenceFor(null),
638
+ );
639
+ }
640
+ const driftProc = liveLeases.length === 1 ? liveLeases[0].proc : null;
641
+ return qualificationResultFor(
642
+ driftProc,
643
+ 'generation-drift',
644
+ captureFenceFor(driftProc),
645
+ );
646
+ }
647
+ } else {
648
+ if (liveLeases.length === 0) {
649
+ return qualificationResultFor(
650
+ null,
651
+ 'no-codex-generation',
652
+ captureFenceFor(null),
653
+ );
654
+ }
655
+ if (liveLeases.length > 1) {
656
+ return qualificationResultFor(
657
+ null,
658
+ 'multiple-codex-generations',
659
+ captureFenceFor(null),
660
+ );
661
+ }
662
+ lease = liveLeases[0];
555
663
  }
664
+
665
+ const proc = lease.proc;
666
+ const sessionKey = lease.sessionKey;
667
+ const capturedFence = captureFenceFor(proc);
556
668
  if (
557
669
  expectedActivityEpoch != null
558
670
  && expectedActivityEpoch !== capturedFence.activityEpoch
@@ -565,7 +677,7 @@ class ProcessManager {
565
677
 
566
678
  const assertLease = () => {
567
679
  if (
568
- this._codexLease !== lease
680
+ this._codexLeases.get(sessionKey) !== lease
569
681
  || this.procs.get(sessionKey) !== proc
570
682
  || !this._codexLeaseMatches(proc)
571
683
  || proc.closed
@@ -618,18 +730,17 @@ class ProcessManager {
618
730
 
619
731
  /**
620
732
  * Restore the persisted native-Codex ownership record before accepting any
621
- * Codex spawn. A quarantined record remains fenced until the caller has
622
- * durably settled recovery and explicitly restores a clear record.
623
- *
624
- * @param {{status: 'clear'}|{
625
- * status: 'quarantined',
626
- * hostIdentity: string,
627
- * bootSessionIdentity: string,
628
- * generationId: string
629
- * }} state
733
+ * Codex spawn. Supports `{ status: 'clear' }`, legacy single-lease
734
+ * `{ status: 'quarantined', hostIdentity, bootSessionIdentity, generationId }`
735
+ * (daemon-wide block), and multi-lease `{ status: 'quarantined', leases: [...] }`.
630
736
  */
631
737
  restoreCodexRecoveryState(state) {
632
- if (this._codexLease || this._hasLiveCodexProcess()) {
738
+ if (
739
+ this._codexLeases.size > 0
740
+ || this._codexDaemonBlocked
741
+ || this._blockedCodexHomes.size > 0
742
+ || this._hasLiveCodexProcess()
743
+ ) {
633
744
  throw managerError(
634
745
  'Codex recovery state cannot change while ownership is live',
635
746
  'CODEX_RECOVERY_ALREADY_ACTIVE',
@@ -639,13 +750,68 @@ class ProcessManager {
639
750
  throw new TypeError('ProcessManager: codexRecoveryState object required');
640
751
  }
641
752
  if (state.status === 'clear') {
642
- this._codexLease = null;
753
+ this._codexLeases.clear();
754
+ this._blockedCodexHomes.clear();
755
+ this._codexDaemonBlocked = null;
643
756
  this._codexRecoveryReady = true;
644
757
  return;
645
758
  }
759
+ if (state.status !== 'quarantined') {
760
+ throw new TypeError(
761
+ 'ProcessManager: invalid quarantined codexRecoveryState',
762
+ );
763
+ }
764
+ if (Object.hasOwn(state, 'leases')) {
765
+ if (!Array.isArray(state.leases) || state.leases.length === 0) {
766
+ throw new TypeError(
767
+ 'ProcessManager: invalid quarantined codexRecoveryState',
768
+ );
769
+ }
770
+ const seenSessions = new Set();
771
+ const seenGenerations = new Set();
772
+ const restored = [];
773
+ for (const entry of state.leases) {
774
+ if (
775
+ !entry
776
+ || typeof entry !== 'object'
777
+ || Array.isArray(entry)
778
+ || !isOpaqueId(entry.sessionKey)
779
+ || !isOpaqueId(entry.generationId)
780
+ || !isOpaqueId(entry.hostIdentity)
781
+ || !isOpaqueId(entry.bootSessionIdentity)
782
+ || seenSessions.has(entry.sessionKey)
783
+ || seenGenerations.has(entry.generationId)
784
+ ) {
785
+ throw new TypeError(
786
+ 'ProcessManager: invalid quarantined codexRecoveryState',
787
+ );
788
+ }
789
+ seenSessions.add(entry.sessionKey);
790
+ seenGenerations.add(entry.generationId);
791
+ restored.push({
792
+ kind: 'recovered-quarantine',
793
+ proc: null,
794
+ sessionKey: entry.sessionKey,
795
+ generationId: entry.generationId,
796
+ hostIdentity: entry.hostIdentity,
797
+ bootSessionIdentity: entry.bootSessionIdentity,
798
+ codexHome: null,
799
+ started: false,
800
+ healthyStopped: false,
801
+ transportClosed: false,
802
+ terminalStatus: null,
803
+ turnId: null,
804
+ quarantined: true,
805
+ });
806
+ }
807
+ this._codexRecoveryReady = true;
808
+ for (const lease of restored) {
809
+ this._codexLeases.set(lease.sessionKey, lease);
810
+ }
811
+ return;
812
+ }
646
813
  if (
647
- state.status !== 'quarantined'
648
- || !isOpaqueId(state.hostIdentity)
814
+ !isOpaqueId(state.hostIdentity)
649
815
  || !isOpaqueId(state.bootSessionIdentity)
650
816
  || !isOpaqueId(state.generationId)
651
817
  ) {
@@ -654,11 +820,13 @@ class ProcessManager {
654
820
  );
655
821
  }
656
822
  this._codexRecoveryReady = true;
657
- this._codexLease = {
658
- kind: 'recovered-quarantine',
823
+ this._codexDaemonBlocked = Object.freeze({
824
+ code: 'CODEX_BOOT_INTEGRITY_FAILED',
825
+ reason: 'recovered-quarantine',
659
826
  generationId: state.generationId,
660
- quarantined: true,
661
- };
827
+ hostIdentity: state.hostIdentity,
828
+ bootSessionIdentity: state.bootSessionIdentity,
829
+ });
662
830
  }
663
831
 
664
832
  _hasLiveCodexProcess() {
@@ -927,6 +1095,7 @@ class ProcessManager {
927
1095
  failedStateCodes[existing.state],
928
1096
  );
929
1097
  }
1098
+ this._assertWarmCodexAllowed(sessionKey, existing, spawnContext);
930
1099
  }
931
1100
  // Reload-on-drift (cli): a warm cli proc can't hot-swap model/effort or
932
1101
  // its display hint (all spawn-time). If the resolved config has drifted
@@ -957,6 +1126,14 @@ class ProcessManager {
957
1126
  from_hint_hash: hintFingerprint(existing.displayHint),
958
1127
  to_hint_hash: hintFingerprint(spawnContext?.displayHint),
959
1128
  }),
1129
+ ...(reasons?.includes('auto-compact-window') && {
1130
+ from_auto_compact_window: existing.autoCompactWindow ?? null,
1131
+ to_auto_compact_window: spawnContext.autoCompactWindow,
1132
+ }),
1133
+ ...(reasons?.includes('prompt-cache-ttl') && {
1134
+ from_prompt_cache_ttl: existing.promptCacheTtl ?? null,
1135
+ to_prompt_cache_ttl: spawnContext.promptCacheTtl,
1136
+ }),
960
1137
  });
961
1138
  await this._killLocked(sessionKey, 'config-reload');
962
1139
  this._throwIfShuttingDown();
@@ -995,30 +1172,70 @@ class ProcessManager {
995
1172
  sessionKey,
996
1173
  spawnContext,
997
1174
  desired,
998
- { leaseAlreadyReserved = false } = {},
1175
+ { leaseAlreadyReserved = false, prebuiltProc = null } = {},
999
1176
  ) {
1000
1177
  let leaseReservation = null;
1001
1178
  let startAttempted = false;
1179
+ let preCodexHome = desired.runtime === 'codex'
1180
+ ? (
1181
+ (typeof prebuiltProc?.codexHome === 'string' && prebuiltProc.codexHome.length > 0
1182
+ ? prebuiltProc.codexHome
1183
+ : null)
1184
+ ?? this._resolvePreSpawnCodexHome(spawnContext)
1185
+ )
1186
+ : null;
1002
1187
  if (desired.runtime === 'codex') {
1003
- leaseReservation = leaseAlreadyReserved
1004
- ? this._codexLease
1005
- : this._reserveCodexLease(sessionKey);
1188
+ if (leaseAlreadyReserved) {
1189
+ leaseReservation = this._codexLeases.get(sessionKey) ?? null;
1190
+ if (!leaseReservation || leaseReservation.sessionKey !== sessionKey) {
1191
+ throw managerError(
1192
+ 'Native Codex generation ownership is not reserved',
1193
+ 'CODEX_DAEMON_GENERATION_BUSY',
1194
+ );
1195
+ }
1196
+ if (this._codexDaemonBlocked) {
1197
+ throw managerError(
1198
+ 'Native Codex runtime is blocked pending daemon-wide recovery',
1199
+ 'CODEX_DAEMON_GENERATION_BUSY',
1200
+ );
1201
+ }
1202
+ if (preCodexHome != null && this._blockedCodexHomes.has(preCodexHome)) {
1203
+ throw managerError(
1204
+ 'Native Codex workspace home is blocked pending profile recovery',
1205
+ 'CODEX_DAEMON_GENERATION_BUSY',
1206
+ );
1207
+ }
1208
+ } else {
1209
+ if (!prebuiltProc) {
1210
+ const precheck = this._precheckCodexHomeBeforeEviction(
1211
+ sessionKey,
1212
+ spawnContext,
1213
+ preCodexHome,
1214
+ );
1215
+ prebuiltProc = precheck.prebuiltProc;
1216
+ preCodexHome = precheck.codexHome;
1217
+ }
1218
+ leaseReservation = await this._reserveCodexLeaseOrEvict(
1219
+ sessionKey,
1220
+ preCodexHome,
1221
+ );
1222
+ }
1006
1223
  }
1007
1224
  const releaseDefinitelyUnstartedReservation = () => {
1008
1225
  if (
1009
1226
  desired.runtime === 'codex'
1010
- && this._codexLease === leaseReservation
1227
+ && this._codexLeases.get(sessionKey) === leaseReservation
1011
1228
  && leaseReservation?.sessionKey === sessionKey
1012
1229
  && !startAttempted
1013
1230
  ) {
1014
- this._codexLease = null;
1231
+ this._codexLeases.delete(sessionKey);
1015
1232
  }
1016
1233
  };
1017
1234
 
1018
1235
  // Provisional new-process cost — ask the factory but don't start yet.
1019
1236
  let newProc;
1020
1237
  try {
1021
- newProc = this.processFactory(sessionKey, spawnContext);
1238
+ newProc = prebuiltProc ?? this.processFactory(sessionKey, spawnContext);
1022
1239
  } catch (error) {
1023
1240
  releaseDefinitelyUnstartedReservation();
1024
1241
  throw error;
@@ -1041,6 +1258,23 @@ class ProcessManager {
1041
1258
  'RUNTIME_FACTORY_MISMATCH',
1042
1259
  );
1043
1260
  }
1261
+ if (desired.runtime === 'codex') {
1262
+ const resolvedCodexHome = (
1263
+ typeof newProc.codexHome === 'string' && newProc.codexHome.length > 0
1264
+ ? newProc.codexHome
1265
+ : preCodexHome
1266
+ );
1267
+ if (
1268
+ resolvedCodexHome != null
1269
+ && this._blockedCodexHomes.has(resolvedCodexHome)
1270
+ ) {
1271
+ throw managerError(
1272
+ 'Native Codex workspace home is blocked pending profile recovery',
1273
+ 'CODEX_DAEMON_GENERATION_BUSY',
1274
+ );
1275
+ }
1276
+ leaseReservation.codexHome = resolvedCodexHome;
1277
+ }
1044
1278
  this._procIdentities.set(newProc, desired);
1045
1279
  if (newProc.runtime == null) newProc.runtime = desired.runtime;
1046
1280
  if (
@@ -1102,6 +1336,7 @@ class ProcessManager {
1102
1336
  if (this._identityFor(competitor).key === desired.key) {
1103
1337
  if (this._isCodex(competitor)) {
1104
1338
  this._assertStrictResumeReuse(competitor, spawnContext);
1339
+ this._assertWarmCodexAllowed(sessionKey, competitor, spawnContext);
1105
1340
  }
1106
1341
  return competitor;
1107
1342
  }
@@ -1145,6 +1380,9 @@ class ProcessManager {
1145
1380
  try {
1146
1381
  await startP;
1147
1382
  } catch (err) {
1383
+ if (desired.runtime === 'codex') {
1384
+ this._recordCodexFault(newProc, err, { onlyEscalated: true });
1385
+ }
1148
1386
  const startupReleaseSafe = (
1149
1387
  desired.runtime === 'codex'
1150
1388
  && newProc.startupReleaseSafe === true
@@ -1155,7 +1393,7 @@ class ProcessManager {
1155
1393
  if (this.procs.get(sessionKey) === newProc) {
1156
1394
  this.procs.delete(sessionKey);
1157
1395
  }
1158
- this._codexLease = null;
1396
+ this._codexLeases.delete(sessionKey);
1159
1397
  this._maybeSignalLruWaiter();
1160
1398
  } else if (desired.runtime === 'codex') {
1161
1399
  // A rejected Codex start remains the exact inspectable ownership
@@ -1174,42 +1412,320 @@ class ProcessManager {
1174
1412
  } finally {
1175
1413
  this._starting.delete(sessionKey);
1176
1414
  }
1415
+ if (desired.runtime === 'codex' && this._codexLeaseMatches(newProc)) {
1416
+ this._codexLeases.get(sessionKey).started = true;
1417
+ }
1177
1418
  this._throwIfShuttingDown();
1178
1419
  return newProc;
1179
1420
  }
1180
1421
 
1181
- _reserveCodexLease(sessionKey) {
1422
+ _resolvePreSpawnCodexHome(spawnContext) {
1423
+ return (
1424
+ typeof spawnContext?.codexHome === 'string'
1425
+ && spawnContext.codexHome.length > 0
1426
+ ? spawnContext.codexHome
1427
+ : null
1428
+ );
1429
+ }
1430
+
1431
+ _withCodexSlotLock(fn) {
1432
+ if (this._codexSlotLock) {
1433
+ throw managerError(
1434
+ 'Reentrant Codex slot lock acquisition is forbidden',
1435
+ 'CODEX_DAEMON_GENERATION_BUSY',
1436
+ );
1437
+ }
1438
+ this._codexSlotLock = true;
1439
+ try {
1440
+ return fn();
1441
+ } finally {
1442
+ this._codexSlotLock = false;
1443
+ }
1444
+ }
1445
+
1446
+ _isStrictlyIdleCodexVictim(sessionKey, lease) {
1447
+ if (
1448
+ !lease
1449
+ || lease.kind !== 'generation'
1450
+ || !lease.started
1451
+ || lease.quarantined
1452
+ ) {
1453
+ return false;
1454
+ }
1455
+ const proc = lease.proc;
1456
+ if (!proc || proc.closed || this.procs.get(sessionKey) !== proc) {
1457
+ return false;
1458
+ }
1459
+ if (
1460
+ this._retiring.has(proc)
1461
+ || this._starting.has(sessionKey)
1462
+ || this._lifecycleGates.has(sessionKey)
1463
+ || (this._retirementIntents.get(sessionKey) ?? 0) > 0
1464
+ ) {
1465
+ return false;
1466
+ }
1467
+ if (proc.state !== 'Idle' || this._strictSwitchBlocked(proc)) {
1468
+ return false;
1469
+ }
1470
+ return true;
1471
+ }
1472
+
1473
+ _findIdleCodexEvictionVictim() {
1474
+ let oldestKey = null;
1475
+ let oldestTs = Infinity;
1476
+ for (const [candidateKey, lease] of this._codexLeases.entries()) {
1477
+ if (!this._isStrictlyIdleCodexVictim(candidateKey, lease)) continue;
1478
+ const ts = lease.proc.lastUsedTs || 0;
1479
+ if (oldestKey === null || ts < oldestTs) {
1480
+ oldestKey = candidateKey;
1481
+ oldestTs = ts;
1482
+ }
1483
+ }
1484
+ return oldestKey;
1485
+ }
1486
+
1487
+ _assertWarmCodexAllowed(sessionKey, proc, spawnContext = null) {
1488
+ if (this._codexDaemonBlocked) {
1489
+ throw managerError(
1490
+ 'Native Codex runtime is blocked pending daemon-wide recovery',
1491
+ 'CODEX_DAEMON_GENERATION_BUSY',
1492
+ );
1493
+ }
1494
+ const lease = this._codexLeases.get(sessionKey) ?? null;
1495
+ if (lease?.quarantined) {
1496
+ throw managerError(
1497
+ 'Codex generation remains fenced pending verified cleanup',
1498
+ 'CODEX_DAEMON_GENERATION_BUSY',
1499
+ );
1500
+ }
1501
+ const codexHome = (
1502
+ (typeof proc?.codexHome === 'string' && proc.codexHome.length > 0 && proc.codexHome)
1503
+ || (typeof lease?.codexHome === 'string' && lease.codexHome.length > 0 && lease.codexHome)
1504
+ || this._resolvePreSpawnCodexHome(spawnContext)
1505
+ || null
1506
+ );
1507
+ if (codexHome != null && this._blockedCodexHomes.has(codexHome)) {
1508
+ throw managerError(
1509
+ 'Native Codex workspace home is blocked pending profile recovery',
1510
+ 'CODEX_DAEMON_GENERATION_BUSY',
1511
+ );
1512
+ }
1513
+ }
1514
+
1515
+ _precheckCodexHomeBeforeEviction(
1516
+ sessionKey,
1517
+ spawnContext,
1518
+ preCodexHome,
1519
+ { allowExistingLease = false } = {},
1520
+ ) {
1521
+ if (preCodexHome != null || this._blockedCodexHomes.size === 0) {
1522
+ return { prebuiltProc: null, codexHome: preCodexHome };
1523
+ }
1182
1524
  if (!this._codexRecoveryReady) {
1183
1525
  throw managerError(
1184
1526
  'Codex ownership recovery has not been restored',
1185
1527
  'CODEX_RECOVERY_NOT_READY',
1186
1528
  );
1187
1529
  }
1188
- if (this._codexLease) {
1530
+ if (this._codexDaemonBlocked) {
1531
+ throw managerError(
1532
+ 'Native Codex runtime is blocked pending daemon-wide recovery',
1533
+ 'CODEX_DAEMON_GENERATION_BUSY',
1534
+ );
1535
+ }
1536
+ if (!allowExistingLease && this._codexLeases.has(sessionKey)) {
1189
1537
  throw managerError(
1190
1538
  'Native Codex generation is already active',
1191
1539
  'CODEX_DAEMON_GENERATION_BUSY',
1192
1540
  );
1193
1541
  }
1194
- const reservation = {
1195
- kind: 'reservation',
1196
- proc: null,
1197
- sessionKey,
1198
- generationId: null,
1199
- healthyStopped: false,
1200
- transportClosed: false,
1201
- terminalStatus: null,
1202
- turnId: null,
1203
- quarantined: false,
1204
- };
1205
- this._codexLease = reservation;
1206
- return reservation;
1542
+ const prebuiltProc = this.processFactory(sessionKey, spawnContext);
1543
+ const resolvedHome = (
1544
+ typeof prebuiltProc?.codexHome === 'string' && prebuiltProc.codexHome.length > 0
1545
+ ? prebuiltProc.codexHome
1546
+ : null
1547
+ );
1548
+ if (resolvedHome != null && this._blockedCodexHomes.has(resolvedHome)) {
1549
+ throw managerError(
1550
+ 'Native Codex workspace home is blocked pending profile recovery',
1551
+ 'CODEX_DAEMON_GENERATION_BUSY',
1552
+ );
1553
+ }
1554
+ return { prebuiltProc, codexHome: resolvedHome };
1555
+ }
1556
+
1557
+ _tryReserveCodexSlot(sessionKey, codexHome = null) {
1558
+ if (!this._codexRecoveryReady) {
1559
+ throw managerError(
1560
+ 'Codex ownership recovery has not been restored',
1561
+ 'CODEX_RECOVERY_NOT_READY',
1562
+ );
1563
+ }
1564
+ if (this._codexDaemonBlocked) {
1565
+ throw managerError(
1566
+ 'Native Codex runtime is blocked pending daemon-wide recovery',
1567
+ 'CODEX_DAEMON_GENERATION_BUSY',
1568
+ );
1569
+ }
1570
+ if (codexHome != null && this._blockedCodexHomes.has(codexHome)) {
1571
+ throw managerError(
1572
+ 'Native Codex workspace home is blocked pending profile recovery',
1573
+ 'CODEX_DAEMON_GENERATION_BUSY',
1574
+ );
1575
+ }
1576
+ if (this._codexLeases.has(sessionKey)) {
1577
+ throw managerError(
1578
+ 'Native Codex generation is already active',
1579
+ 'CODEX_DAEMON_GENERATION_BUSY',
1580
+ );
1581
+ }
1582
+ if (this._codexLeases.size < this.maxCodexSessions) {
1583
+ const reservation = {
1584
+ kind: 'reservation',
1585
+ proc: null,
1586
+ sessionKey,
1587
+ generationId: null,
1588
+ codexHome: codexHome ?? null,
1589
+ started: false,
1590
+ healthyStopped: false,
1591
+ transportClosed: false,
1592
+ terminalStatus: null,
1593
+ turnId: null,
1594
+ quarantined: false,
1595
+ };
1596
+ this._codexLeases.set(sessionKey, reservation);
1597
+ return { status: 'reserved', reservation };
1598
+ }
1599
+ const victimKey = this._findIdleCodexEvictionVictim();
1600
+ if (!victimKey) {
1601
+ throw managerError(
1602
+ 'Native Codex generation capacity is full',
1603
+ 'CODEX_DAEMON_GENERATION_BUSY',
1604
+ );
1605
+ }
1606
+ return { status: 'evict', victimKey };
1607
+ }
1608
+
1609
+ _reserveCodexLease(sessionKey, codexHome = null) {
1610
+ const outcome = this._withCodexSlotLock(() => (
1611
+ this._tryReserveCodexSlot(sessionKey, codexHome)
1612
+ ));
1613
+ if (outcome.status !== 'reserved') {
1614
+ throw managerError(
1615
+ 'Native Codex generation capacity is full',
1616
+ 'CODEX_DAEMON_GENERATION_BUSY',
1617
+ );
1618
+ }
1619
+ return outcome.reservation;
1620
+ }
1621
+
1622
+ async _reserveCodexLeaseOrEvict(sessionKey, codexHome = null) {
1623
+ const maxIterations = this.maxCodexSessions + 1;
1624
+ for (let attempt = 0; attempt < maxIterations; attempt += 1) {
1625
+ this._throwIfShuttingDown();
1626
+ const outcome = this._withCodexSlotLock(() => (
1627
+ this._tryReserveCodexSlot(sessionKey, codexHome)
1628
+ ));
1629
+ if (outcome.status === 'reserved') {
1630
+ return outcome.reservation;
1631
+ }
1632
+ const victimKey = outcome.victimKey;
1633
+ // Never hold _codexSlotLock across awaiting another session's gate.
1634
+ try {
1635
+ await this._withInternalLifecycleGate(victimKey, async () => {
1636
+ this._throwIfShuttingDown();
1637
+ const victimLease = this._codexLeases.get(victimKey);
1638
+ const victimProc = victimLease?.proc ?? null;
1639
+ if (
1640
+ !victimLease
1641
+ || victimLease.kind !== 'generation'
1642
+ || !victimLease.started
1643
+ || victimLease.quarantined
1644
+ || !victimProc
1645
+ || victimProc.closed
1646
+ || this.procs.get(victimKey) !== victimProc
1647
+ || this._retiring.has(victimProc)
1648
+ || this._starting.has(victimKey)
1649
+ || victimProc.state !== 'Idle'
1650
+ || this._strictSwitchBlocked(victimProc)
1651
+ ) {
1652
+ return false;
1653
+ }
1654
+ return this._killLocked(victimKey, 'codex-lru-evict');
1655
+ });
1656
+ } catch (error) {
1657
+ if (this._shuttingDown) throw error;
1658
+ }
1659
+ }
1660
+ throw managerError(
1661
+ 'Native Codex generation capacity is full',
1662
+ 'CODEX_DAEMON_GENERATION_BUSY',
1663
+ );
1664
+ }
1665
+
1666
+ _recordCodexFault(proc, errorOrPayload, { onlyEscalated = false } = {}) {
1667
+ const lease = proc?.sessionKey
1668
+ ? this._codexLeases.get(proc.sessionKey) ?? null
1669
+ : null;
1670
+ const daemonCode = (
1671
+ findMatchingErrorCode(errorOrPayload, CODEX_DAEMON_BLOCK_CODES)
1672
+ ?? findMatchingErrorCode(proc?.containmentError, CODEX_DAEMON_BLOCK_CODES)
1673
+ ?? (
1674
+ typeof proc?.containmentErrorCode === 'string'
1675
+ && CODEX_DAEMON_BLOCK_CODES.has(proc.containmentErrorCode)
1676
+ ? proc.containmentErrorCode
1677
+ : null
1678
+ )
1679
+ );
1680
+ if (daemonCode) {
1681
+ if (lease && this._codexLeaseMatches(proc)) lease.quarantined = true;
1682
+ if (!this._codexDaemonBlocked) {
1683
+ this._codexDaemonBlocked = Object.freeze({
1684
+ code: daemonCode,
1685
+ reason: errorOrPayload?.reason ?? null,
1686
+ generationId: proc?.generationId ?? null,
1687
+ });
1688
+ }
1689
+ return;
1690
+ }
1691
+ const homeCode = (
1692
+ findMatchingErrorCode(errorOrPayload, CODEX_HOME_BLOCK_CODES)
1693
+ ?? findMatchingErrorCode(proc?.containmentError, CODEX_HOME_BLOCK_CODES)
1694
+ ?? (
1695
+ typeof proc?.containmentErrorCode === 'string'
1696
+ && CODEX_HOME_BLOCK_CODES.has(proc.containmentErrorCode)
1697
+ ? proc.containmentErrorCode
1698
+ : null
1699
+ )
1700
+ );
1701
+ if (homeCode) {
1702
+ if (lease && this._codexLeaseMatches(proc)) lease.quarantined = true;
1703
+ const codexHome = (
1704
+ (typeof proc?.codexHome === 'string' && proc.codexHome.length > 0 && proc.codexHome)
1705
+ || (typeof lease?.codexHome === 'string' && lease.codexHome.length > 0 && lease.codexHome)
1706
+ || (typeof errorOrPayload?.codexHome === 'string' && errorOrPayload.codexHome.length > 0 && errorOrPayload.codexHome)
1707
+ || null
1708
+ );
1709
+ if (codexHome) {
1710
+ this._blockedCodexHomes.add(codexHome);
1711
+ } else if (!this._codexDaemonBlocked) {
1712
+ this._codexDaemonBlocked = Object.freeze({
1713
+ code: homeCode,
1714
+ reason: 'codex-home-unknown',
1715
+ generationId: proc?.generationId ?? null,
1716
+ });
1717
+ }
1718
+ return;
1719
+ }
1720
+ if (!onlyEscalated && lease && this._codexLeaseMatches(proc)) {
1721
+ lease.quarantined = true;
1722
+ }
1207
1723
  }
1208
1724
 
1209
1725
  _bindCodexLease(lease, sessionKey, proc) {
1210
1726
  if (
1211
1727
  !lease
1212
- || this._codexLease !== lease
1728
+ || this._codexLeases.get(sessionKey) !== lease
1213
1729
  || lease.proc
1214
1730
  || lease.sessionKey !== sessionKey
1215
1731
  ) {
@@ -1239,8 +1755,14 @@ class ProcessManager {
1239
1755
  lease.proc = proc;
1240
1756
  lease.sessionKey = sessionKey;
1241
1757
  lease.generationId = proc.generationId;
1758
+ lease.codexHome = (
1759
+ typeof proc.codexHome === 'string' && proc.codexHome.length > 0
1760
+ ? proc.codexHome
1761
+ : lease.codexHome ?? null
1762
+ );
1242
1763
  lease.hostIdentity = this.codexHostIdentity;
1243
1764
  lease.bootSessionIdentity = this.codexBootSessionIdentity;
1765
+ lease.started = false;
1244
1766
  lease.healthyStopped = false;
1245
1767
  lease.transportClosed = false;
1246
1768
  lease.terminalStatus = null;
@@ -1248,11 +1770,13 @@ class ProcessManager {
1248
1770
  }
1249
1771
 
1250
1772
  _codexLeaseMatches(proc, generationId = proc?.generationId) {
1773
+ if (!proc || typeof proc.sessionKey !== 'string') return false;
1774
+ const lease = this._codexLeases.get(proc.sessionKey);
1251
1775
  return Boolean(
1252
- this._codexLease
1253
- && this._codexLease.proc === proc
1254
- && this._codexLease.generationId === generationId
1255
- && proc?.generationId === generationId
1776
+ lease
1777
+ && lease.proc === proc
1778
+ && lease.generationId === generationId
1779
+ && proc.generationId === generationId
1256
1780
  );
1257
1781
  }
1258
1782
 
@@ -1313,7 +1837,12 @@ class ProcessManager {
1313
1837
  if (!old || old.closed) {
1314
1838
  return this._spawnFresh(sessionKey, spawnContext, desired);
1315
1839
  }
1316
- if (this._identityFor(old).key === desired.key) return old;
1840
+ if (this._identityFor(old).key === desired.key) {
1841
+ if (this._isCodex(old)) {
1842
+ this._assertWarmCodexAllowed(sessionKey, old, spawnContext);
1843
+ }
1844
+ return old;
1845
+ }
1317
1846
  if (this._strictSwitchBlocked(old)) {
1318
1847
  throw managerError(
1319
1848
  'Runtime/profile switch is blocked by live session work',
@@ -1324,18 +1853,53 @@ class ProcessManager {
1324
1853
  const oldIsCodex = this._isCodex(old);
1325
1854
  let reservation = null;
1326
1855
  let transferredLease = false;
1856
+ let prebuiltProc = null;
1857
+ let resolvedPreCodexHome = null;
1327
1858
  if (desired.runtime === 'codex') {
1328
- if (oldIsCodex && this._codexLeaseMatches(old)) {
1329
- reservation = this._codexLease;
1859
+ const canTransferLease = oldIsCodex && this._codexLeaseMatches(old);
1860
+ const precheck = this._precheckCodexHomeBeforeEviction(
1861
+ sessionKey,
1862
+ spawnContext,
1863
+ this._resolvePreSpawnCodexHome(spawnContext),
1864
+ { allowExistingLease: canTransferLease },
1865
+ );
1866
+ prebuiltProc = precheck.prebuiltProc;
1867
+ resolvedPreCodexHome = precheck.codexHome;
1868
+ if (canTransferLease) {
1869
+ if (!this._codexRecoveryReady) {
1870
+ throw managerError(
1871
+ 'Codex ownership recovery has not been restored',
1872
+ 'CODEX_RECOVERY_NOT_READY',
1873
+ );
1874
+ }
1875
+ if (this._codexDaemonBlocked) {
1876
+ throw managerError(
1877
+ 'Native Codex runtime is blocked pending daemon-wide recovery',
1878
+ 'CODEX_DAEMON_GENERATION_BUSY',
1879
+ );
1880
+ }
1881
+ if (resolvedPreCodexHome != null && this._blockedCodexHomes.has(resolvedPreCodexHome)) {
1882
+ throw managerError(
1883
+ 'Native Codex workspace home is blocked pending profile recovery',
1884
+ 'CODEX_DAEMON_GENERATION_BUSY',
1885
+ );
1886
+ }
1887
+ reservation = this._codexLeases.get(sessionKey);
1330
1888
  transferredLease = true;
1331
1889
  } else {
1332
- reservation = this._reserveCodexLease(sessionKey);
1890
+ reservation = await this._reserveCodexLeaseOrEvict(
1891
+ sessionKey,
1892
+ resolvedPreCodexHome,
1893
+ );
1333
1894
  }
1334
1895
  }
1335
1896
 
1336
1897
  try {
1337
1898
  await this._strictRetire(old, 'runtime-switch');
1338
1899
  } catch (cause) {
1900
+ if (oldIsCodex) {
1901
+ this._recordCodexFault(old, cause, { onlyEscalated: true });
1902
+ }
1339
1903
  const verificationFailed = Boolean(
1340
1904
  findCodexRetirementVerificationError(cause),
1341
1905
  );
@@ -1350,9 +1914,9 @@ class ProcessManager {
1350
1914
  if (
1351
1915
  reservation
1352
1916
  && !transferredLease
1353
- && this._codexLease === reservation
1917
+ && this._codexLeases.get(sessionKey) === reservation
1354
1918
  ) {
1355
- this._codexLease = null;
1919
+ this._codexLeases.delete(sessionKey);
1356
1920
  }
1357
1921
  if (old.closed && this.procs.get(sessionKey) === old) {
1358
1922
  this.procs.delete(sessionKey);
@@ -1372,7 +1936,7 @@ class ProcessManager {
1372
1936
  if (oldIsCodex) {
1373
1937
  if (!this._codexLeaseMatches(old)) {
1374
1938
  // A stale lifecycle event or ownership change cannot release the
1375
- // daemon-wide fence.
1939
+ // session ownership fence.
1376
1940
  if (!this.procs.has(sessionKey)) this.procs.set(sessionKey, old);
1377
1941
  throw managerError(
1378
1942
  'Codex generation ownership changed during retirement',
@@ -1380,18 +1944,20 @@ class ProcessManager {
1380
1944
  );
1381
1945
  }
1382
1946
  if (desired.runtime === 'codex') {
1383
- const lease = this._codexLease;
1947
+ const lease = this._codexLeases.get(sessionKey);
1384
1948
  lease.kind = 'reservation';
1385
1949
  lease.proc = null;
1386
1950
  lease.sessionKey = sessionKey;
1387
1951
  lease.generationId = null;
1952
+ lease.codexHome = this._resolvePreSpawnCodexHome(spawnContext);
1953
+ lease.started = false;
1388
1954
  lease.healthyStopped = false;
1389
1955
  lease.transportClosed = false;
1390
1956
  lease.terminalStatus = null;
1391
1957
  lease.turnId = null;
1392
1958
  reservation = lease;
1393
1959
  } else {
1394
- this._codexLease = null;
1960
+ this._codexLeases.delete(sessionKey);
1395
1961
  }
1396
1962
  }
1397
1963
  this._maybeSignalLruWaiter();
@@ -1402,17 +1968,17 @@ class ProcessManager {
1402
1968
  sessionKey,
1403
1969
  spawnContext,
1404
1970
  desired,
1405
- { leaseAlreadyReserved: desired.runtime === 'codex' },
1971
+ { leaseAlreadyReserved: desired.runtime === 'codex', prebuiltProc },
1406
1972
  );
1407
1973
  } catch (error) {
1408
1974
  // Factory/pre-construction failure has no generation to fence. Once the
1409
1975
  // lease is bound to a process, _spawnFresh intentionally retains it.
1410
1976
  if (
1411
1977
  desired.runtime === 'codex'
1412
- && this._codexLease === reservation
1978
+ && this._codexLeases.get(sessionKey) === reservation
1413
1979
  && reservation?.kind === 'reservation'
1414
1980
  ) {
1415
- this._codexLease = null;
1981
+ this._codexLeases.delete(sessionKey);
1416
1982
  }
1417
1983
  throw error;
1418
1984
  }
@@ -1423,28 +1989,39 @@ class ProcessManager {
1423
1989
  if (this._isCodex(proc)) {
1424
1990
  if (!this._codexLeaseMatches(proc)) {
1425
1991
  throw managerError(
1426
- 'Codex generation does not own the daemon lease',
1992
+ 'Codex generation does not own its session lease',
1427
1993
  'CODEX_DAEMON_GENERATION_BUSY',
1428
1994
  );
1429
1995
  }
1430
- await proc.interrupt(reason);
1996
+ const lease = this._codexLeases.get(proc.sessionKey);
1997
+ try {
1998
+ await proc.interrupt(reason);
1999
+ } catch (cause) {
2000
+ this._recordCodexFault(proc, cause, { onlyEscalated: true });
2001
+ throw cause;
2002
+ }
1431
2003
  if (
1432
2004
  proc.state !== 'Stopped'
1433
2005
  || !this._codexLeaseMatches(proc)
1434
- || !this._codexLease.healthyStopped
1435
- || this._codexLease.quarantined
2006
+ || !lease.healthyStopped
2007
+ || lease.quarantined
1436
2008
  ) {
1437
2009
  throw managerError(
1438
2010
  'Codex generation did not prove exact healthy settlement',
1439
2011
  'CODEX_RETIREMENT_UNVERIFIED',
1440
2012
  );
1441
2013
  }
1442
- await proc.kill(reason);
2014
+ try {
2015
+ await proc.kill(reason);
2016
+ } catch (cause) {
2017
+ this._recordCodexFault(proc, cause, { onlyEscalated: true });
2018
+ throw cause;
2019
+ }
1443
2020
  if (
1444
2021
  !proc.closed
1445
2022
  || !this._codexLeaseMatches(proc)
1446
- || !this._codexLease.transportClosed
1447
- || this._codexLease.quarantined
2023
+ || !lease.transportClosed
2024
+ || lease.quarantined
1448
2025
  ) {
1449
2026
  throw managerError(
1450
2027
  'Codex transport did not prove closed after settlement',
@@ -1468,14 +2045,15 @@ class ProcessManager {
1468
2045
  async _verifyCodexRetirement(proc, reason) {
1469
2046
  let timer = null;
1470
2047
  const abortController = new AbortController();
2048
+ const lease = this._codexLeases.get(proc.sessionKey);
1471
2049
  try {
1472
2050
  const verification = await Promise.race([
1473
2051
  Promise.resolve().then(() => this.codexRetirementVerifier({
1474
2052
  sessionKey: proc.sessionKey,
1475
2053
  generationId: proc.generationId,
1476
2054
  reason,
1477
- terminalStatus: this._codexLease.terminalStatus ?? null,
1478
- turnId: this._codexLease.turnId ?? null,
2055
+ terminalStatus: lease?.terminalStatus ?? null,
2056
+ turnId: lease?.turnId ?? null,
1479
2057
  signal: abortController.signal,
1480
2058
  })),
1481
2059
  new Promise((resolve, reject) => {
@@ -1498,7 +2076,14 @@ class ProcessManager {
1498
2076
  return verification;
1499
2077
  } catch (cause) {
1500
2078
  if (this._codexLeaseMatches(proc)) {
1501
- this._codexLease.quarantined = true;
2079
+ this._codexLeases.get(proc.sessionKey).quarantined = true;
2080
+ }
2081
+ if (!this._codexDaemonBlocked) {
2082
+ this._codexDaemonBlocked = Object.freeze({
2083
+ code: 'CODEX_RETIREMENT_VERIFICATION_FAILED',
2084
+ reason: 'retirement-verification-failed',
2085
+ generationId: proc?.generationId ?? null,
2086
+ });
1502
2087
  }
1503
2088
  if (!abortController.signal.aborted) abortController.abort(cause);
1504
2089
  if (findCodexRetirementVerificationError(cause)) throw cause;
@@ -1737,7 +2322,9 @@ class ProcessManager {
1737
2322
  this.procs.delete(sessionKey);
1738
2323
  }
1739
2324
  this._retiring.delete(expectedProcess);
1740
- if (this._codexLeaseMatches(expectedProcess)) this._codexLease = null;
2325
+ if (this._codexLeaseMatches(expectedProcess)) {
2326
+ this._codexLeases.delete(sessionKey);
2327
+ }
1741
2328
  this._maybeSignalLruWaiter();
1742
2329
  return true;
1743
2330
  });
@@ -1750,6 +2337,7 @@ class ProcessManager {
1750
2337
  try {
1751
2338
  await this._strictRetire(proc, reason);
1752
2339
  } catch (error) {
2340
+ this._recordCodexFault(proc, error, { onlyEscalated: true });
1753
2341
  const verificationFailed = Boolean(
1754
2342
  findCodexRetirementVerificationError(error),
1755
2343
  );
@@ -1767,7 +2355,9 @@ class ProcessManager {
1767
2355
  }
1768
2356
  if (this.procs.get(sessionKey) === proc) this.procs.delete(sessionKey);
1769
2357
  this._retiring.delete(proc);
1770
- if (this._codexLeaseMatches(proc)) this._codexLease = null;
2358
+ if (this._codexLeaseMatches(proc)) {
2359
+ this._codexLeases.delete(sessionKey);
2360
+ }
1771
2361
  this._maybeSignalLruWaiter();
1772
2362
  return true;
1773
2363
  }
@@ -1862,7 +2452,7 @@ class ProcessManager {
1862
2452
  const retiredTargets = new Map();
1863
2453
  const qualificationLease = qualificationExpectation === undefined
1864
2454
  ? null
1865
- : this._codexLease;
2455
+ : this._findCodexLeaseForExpectation(qualificationExpectation);
1866
2456
  const qualificationProc = qualificationLease?.proc ?? null;
1867
2457
  let qualification = qualificationExpectation === undefined
1868
2458
  ? null
@@ -1904,9 +2494,12 @@ class ProcessManager {
1904
2494
  const candidate = typeof proc.captureCleanRestartCandidate === 'function'
1905
2495
  ? proc.captureCleanRestartCandidate()
1906
2496
  : null;
1907
- if (qualification?.outcome === 'qualified') {
2497
+ if (
2498
+ qualification?.outcome === 'qualified'
2499
+ && sessionKey === qualificationLease?.sessionKey
2500
+ ) {
1908
2501
  const leaseChanged = Boolean(
1909
- this._codexLease !== qualificationLease
2502
+ this._codexLeases.get(sessionKey) !== qualificationLease
1910
2503
  || qualificationProc !== proc
1911
2504
  || this.procs.get(sessionKey) !== proc
1912
2505
  || !this._codexLeaseMatches(proc)
@@ -1944,8 +2537,9 @@ class ProcessManager {
1944
2537
  deliveryEvidenceError = error;
1945
2538
  }
1946
2539
  const retirement = await retirementPromise;
1947
- const settledTerminalStatus = this._codexLease?.terminalStatus ?? null;
1948
- const settledTurnId = this._codexLease?.turnId ?? null;
2540
+ const lease = this._codexLeases.get(sessionKey);
2541
+ const settledTerminalStatus = lease?.terminalStatus ?? null;
2542
+ const settledTurnId = lease?.turnId ?? null;
1949
2543
  const deliverySafe = Boolean(
1950
2544
  deliveryEvidence?.fenced === true
1951
2545
  && deliveryEvidence.pending === 0
@@ -1965,7 +2559,9 @@ class ProcessManager {
1965
2559
  && settledTerminalStatus === 'interrupted'
1966
2560
  && settledTurnId === candidate.providerTurnId
1967
2561
  );
1968
- if (this._codexLeaseMatches(proc)) this._codexLease = null;
2562
+ if (this._codexLeaseMatches(proc)) {
2563
+ this._codexLeases.delete(sessionKey);
2564
+ }
1969
2565
  const eligible = deliverySafe && exactRetirement;
1970
2566
  let reason = 'output-evidence';
1971
2567
  if (deliverySafe) reason = 'retirement-binding-mismatch';
@@ -2126,23 +2722,23 @@ class ProcessManager {
2126
2722
  return { outcome: 'unavailable', reason: 'quiescing' };
2127
2723
  }
2128
2724
  const selected = this.procs.get(sessionKey);
2725
+ const sessionLease = this._codexLeases.get(sessionKey) ?? null;
2129
2726
  if (!selected || selected.closed) {
2130
2727
  if (!this._codexRecoveryReady) {
2131
2728
  return { outcome: 'unavailable', reason: 'stale-generation' };
2132
2729
  }
2133
- if (this._codexLease?.quarantined) {
2730
+ if (this._codexDaemonBlocked || sessionLease?.quarantined) {
2134
2731
  return { outcome: 'unavailable', reason: 'containment' };
2135
2732
  }
2733
+ if (sessionLease) {
2734
+ return { outcome: 'unavailable', reason: 'stale-generation' };
2735
+ }
2136
2736
  if (
2137
- this._codexLease
2138
- && this._codexLease.sessionKey
2139
- && this._codexLease.sessionKey !== sessionKey
2737
+ this._codexLeases.size >= this.maxCodexSessions
2738
+ && !this._findIdleCodexEvictionVictim()
2140
2739
  ) {
2141
2740
  return { outcome: 'daemon-busy' };
2142
2741
  }
2143
- if (this._codexLease) {
2144
- return { outcome: 'unavailable', reason: 'stale-generation' };
2145
- }
2146
2742
  return { outcome: 'not-loaded' };
2147
2743
  }
2148
2744
  if (!this._isCodex(selected)) {
@@ -2158,8 +2754,11 @@ class ProcessManager {
2158
2754
  ) {
2159
2755
  return { outcome: 'unavailable', reason: 'stale-generation' };
2160
2756
  }
2757
+ const loadedCodexHome = current.codexHome ?? sessionLease.codexHome ?? null;
2161
2758
  if (
2162
- this._codexLease.quarantined
2759
+ this._codexDaemonBlocked
2760
+ || (loadedCodexHome != null && this._blockedCodexHomes.has(loadedCodexHome))
2761
+ || sessionLease.quarantined
2163
2762
  || [
2164
2763
  'ContainmentFailed',
2165
2764
  'FailedAmbiguous',
@@ -2395,6 +2994,9 @@ class ProcessManager {
2395
2994
  // Generic 'error' channel — log + forward via onError if provided.
2396
2995
  proc.on('error', (err) => {
2397
2996
  this.logger.error?.(`[pm:${proc.label}] process error: ${err.message}`);
2997
+ if (this._isCodex(proc) && this._codexLeaseMatches(proc, capturedGeneration)) {
2998
+ this._recordCodexFault(proc, err, { onlyEscalated: true });
2999
+ }
2398
3000
  if (
2399
3001
  isCurrentGeneration()
2400
3002
  && typeof this.callbacks.onError === 'function'
@@ -2409,20 +3011,21 @@ class ProcessManager {
2409
3011
  proc.on('delivery-work-settled', () => this._maybeSignalLruWaiter());
2410
3012
  if (this._isCodex(proc)) {
2411
3013
  proc.on('codex-settled', (payload) => {
3014
+ const lease = this._codexLeases.get(proc.sessionKey);
2412
3015
  if (
2413
3016
  payload?.kind === 'stopped'
2414
3017
  && payload.generationId === capturedGeneration
2415
- && payload.hostIdentity === this._codexLease?.hostIdentity
3018
+ && payload.hostIdentity === lease?.hostIdentity
2416
3019
  && payload.bootSessionIdentity
2417
- === this._codexLease?.bootSessionIdentity
3020
+ === lease?.bootSessionIdentity
2418
3021
  && payload.trackedTerminalCleanupAccepted === true
2419
3022
  && payload.freshRegistryObservedEmpty === true
2420
3023
  && this._codexLeaseMatches(proc, capturedGeneration)
2421
- && !this._codexLease.quarantined
3024
+ && !lease.quarantined
2422
3025
  ) {
2423
- this._codexLease.healthyStopped = true;
2424
- this._codexLease.terminalStatus = payload.terminalStatus ?? null;
2425
- this._codexLease.turnId = payload.turnId ?? null;
3026
+ lease.healthyStopped = true;
3027
+ lease.terminalStatus = payload.terminalStatus ?? null;
3028
+ lease.turnId = payload.turnId ?? null;
2426
3029
  }
2427
3030
  });
2428
3031
  proc.on('containment-failed', (payload) => {
@@ -2430,7 +3033,30 @@ class ProcessManager {
2430
3033
  payload?.generationId === capturedGeneration
2431
3034
  && this._codexLeaseMatches(proc, capturedGeneration)
2432
3035
  ) {
2433
- this._codexLease.quarantined = true;
3036
+ const lease = this._codexLeases.get(proc.sessionKey);
3037
+ lease.quarantined = true;
3038
+ this._recordCodexFault(proc, payload);
3039
+ }
3040
+ });
3041
+ proc.on('codex-lifecycle', (payload) => {
3042
+ if (
3043
+ payload?.kind === 'durability-blocked'
3044
+ && payload.generationId === capturedGeneration
3045
+ && this._codexLeaseMatches(proc, capturedGeneration)
3046
+ ) {
3047
+ this._recordCodexFault(proc, {
3048
+ code: payload.errorCode || 'CODEX_DURABILITY_FAILED',
3049
+ reason: 'durability-blocked',
3050
+ });
3051
+ } else if (
3052
+ payload?.kind === 'containment-cleanup-failed'
3053
+ && payload.generationId === capturedGeneration
3054
+ ) {
3055
+ this._recordCodexFault(proc, {
3056
+ code: payload.errorCode || 'CODEX_PROCESS_CLEANUP_UNVERIFIED',
3057
+ reason: 'containment-cleanup-failed',
3058
+ codexHome: payload.codexHome ?? proc.codexHome ?? null,
3059
+ });
2434
3060
  }
2435
3061
  });
2436
3062
  }
@@ -2451,7 +3077,7 @@ class ProcessManager {
2451
3077
  if (this._codexLeaseMatches(proc, capturedGeneration)) {
2452
3078
  // A generic close is only a transport fact. It never releases the
2453
3079
  // ownership fence by itself.
2454
- this._codexLease.transportClosed = true;
3080
+ this._codexLeases.get(proc.sessionKey).transportClosed = true;
2455
3081
  }
2456
3082
  const detail = args[1];
2457
3083
  const cleanupCommitted = proc.containmentCleanupCommitted;
@@ -2470,7 +3096,7 @@ class ProcessManager {
2470
3096
  return;
2471
3097
  }
2472
3098
  const start = this._starting.get(proc.sessionKey) ?? null;
2473
- const lease = this._codexLease;
3099
+ const lease = this._codexLeases.get(proc.sessionKey);
2474
3100
  this._withInternalLifecycleGate(proc.sessionKey, async () => {
2475
3101
  if (start) await Promise.resolve(start).catch(() => {});
2476
3102
  if (
@@ -2481,11 +3107,11 @@ class ProcessManager {
2481
3107
  || proc.containmentCleanupCommitted !== detail
2482
3108
  || proc.closed !== true
2483
3109
  || proc.state !== 'Closed'
2484
- || this._codexLease !== lease
3110
+ || this._codexLeases.get(proc.sessionKey) !== lease
2485
3111
  || !this._codexLeaseMatches(proc, capturedGeneration)
2486
3112
  ) return;
2487
3113
  this.procs.delete(proc.sessionKey);
2488
- this._codexLease = null;
3114
+ this._codexLeases.delete(proc.sessionKey);
2489
3115
  this._maybeSignalLruWaiter();
2490
3116
  }).catch((error) => {
2491
3117
  this.logger.error?.(