@shumkov/orchestra 0.14.0 → 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;
756
+ this._codexRecoveryReady = true;
757
+ return;
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
+ }
643
807
  this._codexRecoveryReady = true;
808
+ for (const lease of restored) {
809
+ this._codexLeases.set(lease.sessionKey, lease);
810
+ }
644
811
  return;
645
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
@@ -1003,30 +1172,70 @@ class ProcessManager {
1003
1172
  sessionKey,
1004
1173
  spawnContext,
1005
1174
  desired,
1006
- { leaseAlreadyReserved = false } = {},
1175
+ { leaseAlreadyReserved = false, prebuiltProc = null } = {},
1007
1176
  ) {
1008
1177
  let leaseReservation = null;
1009
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;
1010
1187
  if (desired.runtime === 'codex') {
1011
- leaseReservation = leaseAlreadyReserved
1012
- ? this._codexLease
1013
- : 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
+ }
1014
1223
  }
1015
1224
  const releaseDefinitelyUnstartedReservation = () => {
1016
1225
  if (
1017
1226
  desired.runtime === 'codex'
1018
- && this._codexLease === leaseReservation
1227
+ && this._codexLeases.get(sessionKey) === leaseReservation
1019
1228
  && leaseReservation?.sessionKey === sessionKey
1020
1229
  && !startAttempted
1021
1230
  ) {
1022
- this._codexLease = null;
1231
+ this._codexLeases.delete(sessionKey);
1023
1232
  }
1024
1233
  };
1025
1234
 
1026
1235
  // Provisional new-process cost — ask the factory but don't start yet.
1027
1236
  let newProc;
1028
1237
  try {
1029
- newProc = this.processFactory(sessionKey, spawnContext);
1238
+ newProc = prebuiltProc ?? this.processFactory(sessionKey, spawnContext);
1030
1239
  } catch (error) {
1031
1240
  releaseDefinitelyUnstartedReservation();
1032
1241
  throw error;
@@ -1049,6 +1258,23 @@ class ProcessManager {
1049
1258
  'RUNTIME_FACTORY_MISMATCH',
1050
1259
  );
1051
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
+ }
1052
1278
  this._procIdentities.set(newProc, desired);
1053
1279
  if (newProc.runtime == null) newProc.runtime = desired.runtime;
1054
1280
  if (
@@ -1110,6 +1336,7 @@ class ProcessManager {
1110
1336
  if (this._identityFor(competitor).key === desired.key) {
1111
1337
  if (this._isCodex(competitor)) {
1112
1338
  this._assertStrictResumeReuse(competitor, spawnContext);
1339
+ this._assertWarmCodexAllowed(sessionKey, competitor, spawnContext);
1113
1340
  }
1114
1341
  return competitor;
1115
1342
  }
@@ -1153,6 +1380,9 @@ class ProcessManager {
1153
1380
  try {
1154
1381
  await startP;
1155
1382
  } catch (err) {
1383
+ if (desired.runtime === 'codex') {
1384
+ this._recordCodexFault(newProc, err, { onlyEscalated: true });
1385
+ }
1156
1386
  const startupReleaseSafe = (
1157
1387
  desired.runtime === 'codex'
1158
1388
  && newProc.startupReleaseSafe === true
@@ -1163,7 +1393,7 @@ class ProcessManager {
1163
1393
  if (this.procs.get(sessionKey) === newProc) {
1164
1394
  this.procs.delete(sessionKey);
1165
1395
  }
1166
- this._codexLease = null;
1396
+ this._codexLeases.delete(sessionKey);
1167
1397
  this._maybeSignalLruWaiter();
1168
1398
  } else if (desired.runtime === 'codex') {
1169
1399
  // A rejected Codex start remains the exact inspectable ownership
@@ -1182,42 +1412,320 @@ class ProcessManager {
1182
1412
  } finally {
1183
1413
  this._starting.delete(sessionKey);
1184
1414
  }
1415
+ if (desired.runtime === 'codex' && this._codexLeaseMatches(newProc)) {
1416
+ this._codexLeases.get(sessionKey).started = true;
1417
+ }
1185
1418
  this._throwIfShuttingDown();
1186
1419
  return newProc;
1187
1420
  }
1188
1421
 
1189
- _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
+ }
1190
1524
  if (!this._codexRecoveryReady) {
1191
1525
  throw managerError(
1192
1526
  'Codex ownership recovery has not been restored',
1193
1527
  'CODEX_RECOVERY_NOT_READY',
1194
1528
  );
1195
1529
  }
1196
- 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)) {
1197
1537
  throw managerError(
1198
1538
  'Native Codex generation is already active',
1199
1539
  'CODEX_DAEMON_GENERATION_BUSY',
1200
1540
  );
1201
1541
  }
1202
- const reservation = {
1203
- kind: 'reservation',
1204
- proc: null,
1205
- sessionKey,
1206
- generationId: null,
1207
- healthyStopped: false,
1208
- transportClosed: false,
1209
- terminalStatus: null,
1210
- turnId: null,
1211
- quarantined: false,
1212
- };
1213
- this._codexLease = reservation;
1214
- 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
+ }
1215
1723
  }
1216
1724
 
1217
1725
  _bindCodexLease(lease, sessionKey, proc) {
1218
1726
  if (
1219
1727
  !lease
1220
- || this._codexLease !== lease
1728
+ || this._codexLeases.get(sessionKey) !== lease
1221
1729
  || lease.proc
1222
1730
  || lease.sessionKey !== sessionKey
1223
1731
  ) {
@@ -1247,8 +1755,14 @@ class ProcessManager {
1247
1755
  lease.proc = proc;
1248
1756
  lease.sessionKey = sessionKey;
1249
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
+ );
1250
1763
  lease.hostIdentity = this.codexHostIdentity;
1251
1764
  lease.bootSessionIdentity = this.codexBootSessionIdentity;
1765
+ lease.started = false;
1252
1766
  lease.healthyStopped = false;
1253
1767
  lease.transportClosed = false;
1254
1768
  lease.terminalStatus = null;
@@ -1256,11 +1770,13 @@ class ProcessManager {
1256
1770
  }
1257
1771
 
1258
1772
  _codexLeaseMatches(proc, generationId = proc?.generationId) {
1773
+ if (!proc || typeof proc.sessionKey !== 'string') return false;
1774
+ const lease = this._codexLeases.get(proc.sessionKey);
1259
1775
  return Boolean(
1260
- this._codexLease
1261
- && this._codexLease.proc === proc
1262
- && this._codexLease.generationId === generationId
1263
- && proc?.generationId === generationId
1776
+ lease
1777
+ && lease.proc === proc
1778
+ && lease.generationId === generationId
1779
+ && proc.generationId === generationId
1264
1780
  );
1265
1781
  }
1266
1782
 
@@ -1321,7 +1837,12 @@ class ProcessManager {
1321
1837
  if (!old || old.closed) {
1322
1838
  return this._spawnFresh(sessionKey, spawnContext, desired);
1323
1839
  }
1324
- 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
+ }
1325
1846
  if (this._strictSwitchBlocked(old)) {
1326
1847
  throw managerError(
1327
1848
  'Runtime/profile switch is blocked by live session work',
@@ -1332,18 +1853,53 @@ class ProcessManager {
1332
1853
  const oldIsCodex = this._isCodex(old);
1333
1854
  let reservation = null;
1334
1855
  let transferredLease = false;
1856
+ let prebuiltProc = null;
1857
+ let resolvedPreCodexHome = null;
1335
1858
  if (desired.runtime === 'codex') {
1336
- if (oldIsCodex && this._codexLeaseMatches(old)) {
1337
- 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);
1338
1888
  transferredLease = true;
1339
1889
  } else {
1340
- reservation = this._reserveCodexLease(sessionKey);
1890
+ reservation = await this._reserveCodexLeaseOrEvict(
1891
+ sessionKey,
1892
+ resolvedPreCodexHome,
1893
+ );
1341
1894
  }
1342
1895
  }
1343
1896
 
1344
1897
  try {
1345
1898
  await this._strictRetire(old, 'runtime-switch');
1346
1899
  } catch (cause) {
1900
+ if (oldIsCodex) {
1901
+ this._recordCodexFault(old, cause, { onlyEscalated: true });
1902
+ }
1347
1903
  const verificationFailed = Boolean(
1348
1904
  findCodexRetirementVerificationError(cause),
1349
1905
  );
@@ -1358,9 +1914,9 @@ class ProcessManager {
1358
1914
  if (
1359
1915
  reservation
1360
1916
  && !transferredLease
1361
- && this._codexLease === reservation
1917
+ && this._codexLeases.get(sessionKey) === reservation
1362
1918
  ) {
1363
- this._codexLease = null;
1919
+ this._codexLeases.delete(sessionKey);
1364
1920
  }
1365
1921
  if (old.closed && this.procs.get(sessionKey) === old) {
1366
1922
  this.procs.delete(sessionKey);
@@ -1380,7 +1936,7 @@ class ProcessManager {
1380
1936
  if (oldIsCodex) {
1381
1937
  if (!this._codexLeaseMatches(old)) {
1382
1938
  // A stale lifecycle event or ownership change cannot release the
1383
- // daemon-wide fence.
1939
+ // session ownership fence.
1384
1940
  if (!this.procs.has(sessionKey)) this.procs.set(sessionKey, old);
1385
1941
  throw managerError(
1386
1942
  'Codex generation ownership changed during retirement',
@@ -1388,18 +1944,20 @@ class ProcessManager {
1388
1944
  );
1389
1945
  }
1390
1946
  if (desired.runtime === 'codex') {
1391
- const lease = this._codexLease;
1947
+ const lease = this._codexLeases.get(sessionKey);
1392
1948
  lease.kind = 'reservation';
1393
1949
  lease.proc = null;
1394
1950
  lease.sessionKey = sessionKey;
1395
1951
  lease.generationId = null;
1952
+ lease.codexHome = this._resolvePreSpawnCodexHome(spawnContext);
1953
+ lease.started = false;
1396
1954
  lease.healthyStopped = false;
1397
1955
  lease.transportClosed = false;
1398
1956
  lease.terminalStatus = null;
1399
1957
  lease.turnId = null;
1400
1958
  reservation = lease;
1401
1959
  } else {
1402
- this._codexLease = null;
1960
+ this._codexLeases.delete(sessionKey);
1403
1961
  }
1404
1962
  }
1405
1963
  this._maybeSignalLruWaiter();
@@ -1410,17 +1968,17 @@ class ProcessManager {
1410
1968
  sessionKey,
1411
1969
  spawnContext,
1412
1970
  desired,
1413
- { leaseAlreadyReserved: desired.runtime === 'codex' },
1971
+ { leaseAlreadyReserved: desired.runtime === 'codex', prebuiltProc },
1414
1972
  );
1415
1973
  } catch (error) {
1416
1974
  // Factory/pre-construction failure has no generation to fence. Once the
1417
1975
  // lease is bound to a process, _spawnFresh intentionally retains it.
1418
1976
  if (
1419
1977
  desired.runtime === 'codex'
1420
- && this._codexLease === reservation
1978
+ && this._codexLeases.get(sessionKey) === reservation
1421
1979
  && reservation?.kind === 'reservation'
1422
1980
  ) {
1423
- this._codexLease = null;
1981
+ this._codexLeases.delete(sessionKey);
1424
1982
  }
1425
1983
  throw error;
1426
1984
  }
@@ -1431,28 +1989,39 @@ class ProcessManager {
1431
1989
  if (this._isCodex(proc)) {
1432
1990
  if (!this._codexLeaseMatches(proc)) {
1433
1991
  throw managerError(
1434
- 'Codex generation does not own the daemon lease',
1992
+ 'Codex generation does not own its session lease',
1435
1993
  'CODEX_DAEMON_GENERATION_BUSY',
1436
1994
  );
1437
1995
  }
1438
- 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
+ }
1439
2003
  if (
1440
2004
  proc.state !== 'Stopped'
1441
2005
  || !this._codexLeaseMatches(proc)
1442
- || !this._codexLease.healthyStopped
1443
- || this._codexLease.quarantined
2006
+ || !lease.healthyStopped
2007
+ || lease.quarantined
1444
2008
  ) {
1445
2009
  throw managerError(
1446
2010
  'Codex generation did not prove exact healthy settlement',
1447
2011
  'CODEX_RETIREMENT_UNVERIFIED',
1448
2012
  );
1449
2013
  }
1450
- 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
+ }
1451
2020
  if (
1452
2021
  !proc.closed
1453
2022
  || !this._codexLeaseMatches(proc)
1454
- || !this._codexLease.transportClosed
1455
- || this._codexLease.quarantined
2023
+ || !lease.transportClosed
2024
+ || lease.quarantined
1456
2025
  ) {
1457
2026
  throw managerError(
1458
2027
  'Codex transport did not prove closed after settlement',
@@ -1476,14 +2045,15 @@ class ProcessManager {
1476
2045
  async _verifyCodexRetirement(proc, reason) {
1477
2046
  let timer = null;
1478
2047
  const abortController = new AbortController();
2048
+ const lease = this._codexLeases.get(proc.sessionKey);
1479
2049
  try {
1480
2050
  const verification = await Promise.race([
1481
2051
  Promise.resolve().then(() => this.codexRetirementVerifier({
1482
2052
  sessionKey: proc.sessionKey,
1483
2053
  generationId: proc.generationId,
1484
2054
  reason,
1485
- terminalStatus: this._codexLease.terminalStatus ?? null,
1486
- turnId: this._codexLease.turnId ?? null,
2055
+ terminalStatus: lease?.terminalStatus ?? null,
2056
+ turnId: lease?.turnId ?? null,
1487
2057
  signal: abortController.signal,
1488
2058
  })),
1489
2059
  new Promise((resolve, reject) => {
@@ -1506,7 +2076,14 @@ class ProcessManager {
1506
2076
  return verification;
1507
2077
  } catch (cause) {
1508
2078
  if (this._codexLeaseMatches(proc)) {
1509
- 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
+ });
1510
2087
  }
1511
2088
  if (!abortController.signal.aborted) abortController.abort(cause);
1512
2089
  if (findCodexRetirementVerificationError(cause)) throw cause;
@@ -1745,7 +2322,9 @@ class ProcessManager {
1745
2322
  this.procs.delete(sessionKey);
1746
2323
  }
1747
2324
  this._retiring.delete(expectedProcess);
1748
- if (this._codexLeaseMatches(expectedProcess)) this._codexLease = null;
2325
+ if (this._codexLeaseMatches(expectedProcess)) {
2326
+ this._codexLeases.delete(sessionKey);
2327
+ }
1749
2328
  this._maybeSignalLruWaiter();
1750
2329
  return true;
1751
2330
  });
@@ -1758,6 +2337,7 @@ class ProcessManager {
1758
2337
  try {
1759
2338
  await this._strictRetire(proc, reason);
1760
2339
  } catch (error) {
2340
+ this._recordCodexFault(proc, error, { onlyEscalated: true });
1761
2341
  const verificationFailed = Boolean(
1762
2342
  findCodexRetirementVerificationError(error),
1763
2343
  );
@@ -1775,7 +2355,9 @@ class ProcessManager {
1775
2355
  }
1776
2356
  if (this.procs.get(sessionKey) === proc) this.procs.delete(sessionKey);
1777
2357
  this._retiring.delete(proc);
1778
- if (this._codexLeaseMatches(proc)) this._codexLease = null;
2358
+ if (this._codexLeaseMatches(proc)) {
2359
+ this._codexLeases.delete(sessionKey);
2360
+ }
1779
2361
  this._maybeSignalLruWaiter();
1780
2362
  return true;
1781
2363
  }
@@ -1870,7 +2452,7 @@ class ProcessManager {
1870
2452
  const retiredTargets = new Map();
1871
2453
  const qualificationLease = qualificationExpectation === undefined
1872
2454
  ? null
1873
- : this._codexLease;
2455
+ : this._findCodexLeaseForExpectation(qualificationExpectation);
1874
2456
  const qualificationProc = qualificationLease?.proc ?? null;
1875
2457
  let qualification = qualificationExpectation === undefined
1876
2458
  ? null
@@ -1912,9 +2494,12 @@ class ProcessManager {
1912
2494
  const candidate = typeof proc.captureCleanRestartCandidate === 'function'
1913
2495
  ? proc.captureCleanRestartCandidate()
1914
2496
  : null;
1915
- if (qualification?.outcome === 'qualified') {
2497
+ if (
2498
+ qualification?.outcome === 'qualified'
2499
+ && sessionKey === qualificationLease?.sessionKey
2500
+ ) {
1916
2501
  const leaseChanged = Boolean(
1917
- this._codexLease !== qualificationLease
2502
+ this._codexLeases.get(sessionKey) !== qualificationLease
1918
2503
  || qualificationProc !== proc
1919
2504
  || this.procs.get(sessionKey) !== proc
1920
2505
  || !this._codexLeaseMatches(proc)
@@ -1952,8 +2537,9 @@ class ProcessManager {
1952
2537
  deliveryEvidenceError = error;
1953
2538
  }
1954
2539
  const retirement = await retirementPromise;
1955
- const settledTerminalStatus = this._codexLease?.terminalStatus ?? null;
1956
- 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;
1957
2543
  const deliverySafe = Boolean(
1958
2544
  deliveryEvidence?.fenced === true
1959
2545
  && deliveryEvidence.pending === 0
@@ -1973,7 +2559,9 @@ class ProcessManager {
1973
2559
  && settledTerminalStatus === 'interrupted'
1974
2560
  && settledTurnId === candidate.providerTurnId
1975
2561
  );
1976
- if (this._codexLeaseMatches(proc)) this._codexLease = null;
2562
+ if (this._codexLeaseMatches(proc)) {
2563
+ this._codexLeases.delete(sessionKey);
2564
+ }
1977
2565
  const eligible = deliverySafe && exactRetirement;
1978
2566
  let reason = 'output-evidence';
1979
2567
  if (deliverySafe) reason = 'retirement-binding-mismatch';
@@ -2134,23 +2722,23 @@ class ProcessManager {
2134
2722
  return { outcome: 'unavailable', reason: 'quiescing' };
2135
2723
  }
2136
2724
  const selected = this.procs.get(sessionKey);
2725
+ const sessionLease = this._codexLeases.get(sessionKey) ?? null;
2137
2726
  if (!selected || selected.closed) {
2138
2727
  if (!this._codexRecoveryReady) {
2139
2728
  return { outcome: 'unavailable', reason: 'stale-generation' };
2140
2729
  }
2141
- if (this._codexLease?.quarantined) {
2730
+ if (this._codexDaemonBlocked || sessionLease?.quarantined) {
2142
2731
  return { outcome: 'unavailable', reason: 'containment' };
2143
2732
  }
2733
+ if (sessionLease) {
2734
+ return { outcome: 'unavailable', reason: 'stale-generation' };
2735
+ }
2144
2736
  if (
2145
- this._codexLease
2146
- && this._codexLease.sessionKey
2147
- && this._codexLease.sessionKey !== sessionKey
2737
+ this._codexLeases.size >= this.maxCodexSessions
2738
+ && !this._findIdleCodexEvictionVictim()
2148
2739
  ) {
2149
2740
  return { outcome: 'daemon-busy' };
2150
2741
  }
2151
- if (this._codexLease) {
2152
- return { outcome: 'unavailable', reason: 'stale-generation' };
2153
- }
2154
2742
  return { outcome: 'not-loaded' };
2155
2743
  }
2156
2744
  if (!this._isCodex(selected)) {
@@ -2166,8 +2754,11 @@ class ProcessManager {
2166
2754
  ) {
2167
2755
  return { outcome: 'unavailable', reason: 'stale-generation' };
2168
2756
  }
2757
+ const loadedCodexHome = current.codexHome ?? sessionLease.codexHome ?? null;
2169
2758
  if (
2170
- this._codexLease.quarantined
2759
+ this._codexDaemonBlocked
2760
+ || (loadedCodexHome != null && this._blockedCodexHomes.has(loadedCodexHome))
2761
+ || sessionLease.quarantined
2171
2762
  || [
2172
2763
  'ContainmentFailed',
2173
2764
  'FailedAmbiguous',
@@ -2403,6 +2994,9 @@ class ProcessManager {
2403
2994
  // Generic 'error' channel — log + forward via onError if provided.
2404
2995
  proc.on('error', (err) => {
2405
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
+ }
2406
3000
  if (
2407
3001
  isCurrentGeneration()
2408
3002
  && typeof this.callbacks.onError === 'function'
@@ -2417,20 +3011,21 @@ class ProcessManager {
2417
3011
  proc.on('delivery-work-settled', () => this._maybeSignalLruWaiter());
2418
3012
  if (this._isCodex(proc)) {
2419
3013
  proc.on('codex-settled', (payload) => {
3014
+ const lease = this._codexLeases.get(proc.sessionKey);
2420
3015
  if (
2421
3016
  payload?.kind === 'stopped'
2422
3017
  && payload.generationId === capturedGeneration
2423
- && payload.hostIdentity === this._codexLease?.hostIdentity
3018
+ && payload.hostIdentity === lease?.hostIdentity
2424
3019
  && payload.bootSessionIdentity
2425
- === this._codexLease?.bootSessionIdentity
3020
+ === lease?.bootSessionIdentity
2426
3021
  && payload.trackedTerminalCleanupAccepted === true
2427
3022
  && payload.freshRegistryObservedEmpty === true
2428
3023
  && this._codexLeaseMatches(proc, capturedGeneration)
2429
- && !this._codexLease.quarantined
3024
+ && !lease.quarantined
2430
3025
  ) {
2431
- this._codexLease.healthyStopped = true;
2432
- this._codexLease.terminalStatus = payload.terminalStatus ?? null;
2433
- this._codexLease.turnId = payload.turnId ?? null;
3026
+ lease.healthyStopped = true;
3027
+ lease.terminalStatus = payload.terminalStatus ?? null;
3028
+ lease.turnId = payload.turnId ?? null;
2434
3029
  }
2435
3030
  });
2436
3031
  proc.on('containment-failed', (payload) => {
@@ -2438,7 +3033,30 @@ class ProcessManager {
2438
3033
  payload?.generationId === capturedGeneration
2439
3034
  && this._codexLeaseMatches(proc, capturedGeneration)
2440
3035
  ) {
2441
- 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
+ });
2442
3060
  }
2443
3061
  });
2444
3062
  }
@@ -2459,7 +3077,7 @@ class ProcessManager {
2459
3077
  if (this._codexLeaseMatches(proc, capturedGeneration)) {
2460
3078
  // A generic close is only a transport fact. It never releases the
2461
3079
  // ownership fence by itself.
2462
- this._codexLease.transportClosed = true;
3080
+ this._codexLeases.get(proc.sessionKey).transportClosed = true;
2463
3081
  }
2464
3082
  const detail = args[1];
2465
3083
  const cleanupCommitted = proc.containmentCleanupCommitted;
@@ -2478,7 +3096,7 @@ class ProcessManager {
2478
3096
  return;
2479
3097
  }
2480
3098
  const start = this._starting.get(proc.sessionKey) ?? null;
2481
- const lease = this._codexLease;
3099
+ const lease = this._codexLeases.get(proc.sessionKey);
2482
3100
  this._withInternalLifecycleGate(proc.sessionKey, async () => {
2483
3101
  if (start) await Promise.resolve(start).catch(() => {});
2484
3102
  if (
@@ -2489,11 +3107,11 @@ class ProcessManager {
2489
3107
  || proc.containmentCleanupCommitted !== detail
2490
3108
  || proc.closed !== true
2491
3109
  || proc.state !== 'Closed'
2492
- || this._codexLease !== lease
3110
+ || this._codexLeases.get(proc.sessionKey) !== lease
2493
3111
  || !this._codexLeaseMatches(proc, capturedGeneration)
2494
3112
  ) return;
2495
3113
  this.procs.delete(proc.sessionKey);
2496
- this._codexLease = null;
3114
+ this._codexLeases.delete(proc.sessionKey);
2497
3115
  this._maybeSignalLruWaiter();
2498
3116
  }).catch((error) => {
2499
3117
  this.logger.error?.(