@shumkov/orchestra 0.10.15 → 0.10.17

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.
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { randomUUID } = require('node:crypto');
3
+ const { hash, randomUUID } = require('node:crypto');
4
4
  const { isDeepStrictEqual } = require('node:util');
5
5
 
6
6
  const { Process, UnsupportedOperationError } = require('./process');
@@ -439,6 +439,7 @@ class CodexProcess extends Process {
439
439
 
440
440
  this.state = 'Spawning';
441
441
  this.lifecycleEpoch = 0;
442
+ this.activityEpoch = 0;
442
443
  this.providerSessionId = null;
443
444
  this._resumeAttestation = null;
444
445
  Object.defineProperty(this, 'resumeAttestation', {
@@ -503,6 +504,16 @@ class CodexProcess extends Process {
503
504
  this.lifecycleEpoch += 1;
504
505
  }
505
506
 
507
+ _advanceActivityEpoch() {
508
+ if (this.activityEpoch === Number.MAX_SAFE_INTEGER) {
509
+ throw processError(
510
+ 'Codex activity epoch is exhausted',
511
+ 'CODEX_ACTIVITY_EPOCH_EXHAUSTED',
512
+ );
513
+ }
514
+ this.activityEpoch += 1;
515
+ }
516
+
506
517
  _assertLifecycle(fence) {
507
518
  if (
508
519
  fence?.epoch !== this.lifecycleEpoch
@@ -1092,6 +1103,7 @@ class CodexProcess extends Process {
1092
1103
  this.emit('queue-drop', pending);
1093
1104
  return pending.promise;
1094
1105
  }
1106
+ this._advanceActivityEpoch();
1095
1107
  this._pump();
1096
1108
  return pending.promise;
1097
1109
  }
@@ -1497,6 +1509,7 @@ class CodexProcess extends Process {
1497
1509
  'CODEX_STEER_QUEUE_OVERFLOW',
1498
1510
  ));
1499
1511
  }
1512
+ this._advanceActivityEpoch();
1500
1513
  this.pendingSteerCount += 1;
1501
1514
  const operation = this.steerChain.then(
1502
1515
  () => this._steerTurn(text, context),
@@ -1954,7 +1967,7 @@ class CodexProcess extends Process {
1954
1967
  );
1955
1968
  this._assertLifecycle(lifecycle);
1956
1969
  if (page.count > 0 || page.nextCursor != null) {
1957
- this.state = 'BackgroundWorking';
1970
+ this._activateBackgroundOwnership();
1958
1971
  this._armBackgroundWatchdog(pending.deadlineAt);
1959
1972
  if (this.threadStatusType === 'idle') {
1960
1973
  this._scheduleBackgroundSettlement();
@@ -1962,6 +1975,179 @@ class CodexProcess extends Process {
1962
1975
  }
1963
1976
  }
1964
1977
 
1978
+ _activateBackgroundOwnership() {
1979
+ if (!this.hasActiveBackgroundWork()) {
1980
+ this._advanceActivityEpoch();
1981
+ this.state = 'BackgroundWorking';
1982
+ }
1983
+ }
1984
+
1985
+ _qualificationFenceError() {
1986
+ return processError(
1987
+ 'Codex clean-restart qualification fence changed',
1988
+ 'CODEX_QUALIFICATION_FENCE',
1989
+ );
1990
+ }
1991
+
1992
+ _assertQualificationFence(fence, assertLease) {
1993
+ if (
1994
+ fence.lifecycleEpoch !== this.lifecycleEpoch
1995
+ || fence.generationId !== this.generationId
1996
+ || fence.activityEpoch !== this.activityEpoch
1997
+ ) {
1998
+ throw this._qualificationFenceError();
1999
+ }
2000
+ if (typeof assertLease !== 'function') return;
2001
+ try {
2002
+ if (assertLease() === false) throw this._qualificationFenceError();
2003
+ } catch (error) {
2004
+ if (
2005
+ error?.code === 'CODEX_QUALIFICATION_FENCE'
2006
+ || error?.code === 'CODEX_QUALIFICATION_LEASE_DRIFT'
2007
+ ) throw error;
2008
+ throw this._qualificationFenceError();
2009
+ }
2010
+ }
2011
+
2012
+ _qualificationResult({
2013
+ outcome,
2014
+ reason,
2015
+ backgroundTerminalCount = 0,
2016
+ backgroundTerminalRegistryComplete = true,
2017
+ observedAtMs = Date.now(),
2018
+ }) {
2019
+ return Object.freeze({
2020
+ outcome,
2021
+ reason,
2022
+ generationDigest: hash('sha256', this.generationId, 'hex'),
2023
+ activityEpoch: this.activityEpoch,
2024
+ processState: PROCESS_STATES.has(this.state) ? this.state : 'unknown',
2025
+ activeTurnCount: this.current ? 1 : 0,
2026
+ pendingDeliveryCount: this.hasPendingDeliveryWork() ? 1 : 0,
2027
+ backgroundOwnerCount: this.hasActiveBackgroundWork() ? 1 : 0,
2028
+ backgroundTerminalCount,
2029
+ backgroundTerminalRegistryComplete,
2030
+ observedAtMs,
2031
+ });
2032
+ }
2033
+
2034
+ async inspectCleanRestartQualification({
2035
+ expectedGenerationDigest = hash('sha256', this.generationId, 'hex'),
2036
+ expectedActivityEpoch = this.activityEpoch,
2037
+ assertLease,
2038
+ } = {}) {
2039
+ const fence = Object.freeze({
2040
+ lifecycleEpoch: this.lifecycleEpoch,
2041
+ generationId: this.generationId,
2042
+ activityEpoch: this.activityEpoch,
2043
+ });
2044
+ const generationDigest = hash('sha256', fence.generationId, 'hex');
2045
+ if (
2046
+ expectedGenerationDigest !== generationDigest
2047
+ || expectedActivityEpoch !== fence.activityEpoch
2048
+ ) {
2049
+ throw this._qualificationFenceError();
2050
+ }
2051
+ this._assertQualificationFence(fence, assertLease);
2052
+
2053
+ if (this.state !== 'Idle') {
2054
+ return this._qualificationResult({
2055
+ outcome: 'mismatch',
2056
+ reason: this.current ? 'active-turn' : 'process-not-idle',
2057
+ });
2058
+ }
2059
+ if (!this.client || !this.providerSessionId) {
2060
+ return this._qualificationResult({
2061
+ outcome: 'mismatch',
2062
+ reason: 'process-not-ready',
2063
+ });
2064
+ }
2065
+
2066
+ let backgroundTerminalCount = 0;
2067
+ try {
2068
+ const page = await this.client.request(
2069
+ 'thread/backgroundTerminals/list',
2070
+ { threadId: this.providerSessionId, limit: 100 },
2071
+ { timeoutMs: this.cleanupTimeoutMs },
2072
+ );
2073
+ this._assertQualificationFence(fence, assertLease);
2074
+ if (
2075
+ !page
2076
+ || !Number.isSafeInteger(page.count)
2077
+ || page.count < 0
2078
+ || page.count > 100
2079
+ || (page.nextCursor != null && typeof page.nextCursor !== 'string')
2080
+ ) {
2081
+ throw processError(
2082
+ 'Codex qualification returned an invalid terminal page',
2083
+ 'CODEX_QUALIFICATION_FAILED',
2084
+ );
2085
+ }
2086
+ backgroundTerminalCount = page.count;
2087
+ this._assertQualificationFence(fence, assertLease);
2088
+ const observedAtMs = Date.now();
2089
+ if (page.nextCursor != null) {
2090
+ return this._qualificationResult({
2091
+ outcome: 'mismatch',
2092
+ reason: page.count > 0 ? 'background-terminals' : 'pagination-incomplete',
2093
+ backgroundTerminalCount,
2094
+ backgroundTerminalRegistryComplete: false,
2095
+ observedAtMs,
2096
+ });
2097
+ }
2098
+ if (backgroundTerminalCount > 0) {
2099
+ return this._qualificationResult({
2100
+ outcome: 'mismatch',
2101
+ reason: 'background-terminals',
2102
+ backgroundTerminalCount,
2103
+ observedAtMs,
2104
+ });
2105
+ }
2106
+ if (this.current) {
2107
+ return this._qualificationResult({
2108
+ outcome: 'mismatch',
2109
+ reason: 'active-turn',
2110
+ observedAtMs,
2111
+ });
2112
+ }
2113
+ if (this.hasPendingDeliveryWork()) {
2114
+ return this._qualificationResult({
2115
+ outcome: 'mismatch',
2116
+ reason: 'pending-delivery',
2117
+ observedAtMs,
2118
+ });
2119
+ }
2120
+ if (this.hasActiveBackgroundWork()) {
2121
+ return this._qualificationResult({
2122
+ outcome: 'mismatch',
2123
+ reason: 'background-owner',
2124
+ observedAtMs,
2125
+ });
2126
+ }
2127
+ if (this.state !== 'Idle') {
2128
+ return this._qualificationResult({
2129
+ outcome: 'mismatch',
2130
+ reason: 'process-not-idle',
2131
+ observedAtMs,
2132
+ });
2133
+ }
2134
+ return this._qualificationResult({
2135
+ outcome: 'qualified',
2136
+ reason: 'eligible',
2137
+ observedAtMs,
2138
+ });
2139
+ } catch (error) {
2140
+ if (
2141
+ error?.code === 'CODEX_QUALIFICATION_FENCE'
2142
+ || error?.code === 'CODEX_QUALIFICATION_LEASE_DRIFT'
2143
+ ) throw error;
2144
+ throw processError(
2145
+ 'Codex clean-restart qualification inspection failed',
2146
+ 'CODEX_QUALIFICATION_FAILED',
2147
+ );
2148
+ }
2149
+ }
2150
+
1965
2151
  async _mutation(method, params, detail) {
1966
2152
  const attemptId = boundedOpaqueId(
1967
2153
  detail.attemptId ?? this.mutationAttemptIdFactory(),
@@ -2206,17 +2392,19 @@ class CodexProcess extends Process {
2206
2392
  }
2207
2393
  if (method === 'thread/status/changed') {
2208
2394
  const statusType = params.status?.type ?? null;
2395
+ const activateBackground = (
2396
+ statusType === 'active'
2397
+ && !this.current
2398
+ && this.state === 'Idle'
2399
+ );
2400
+ if (activateBackground) this._advanceActivityEpoch();
2209
2401
  await this._checkpoint('thread-status-changed', {
2210
2402
  threadId: ownedThreadId,
2211
2403
  statusType,
2212
2404
  }, fence);
2213
2405
  fence.assertActive?.();
2214
2406
  this.threadStatusType = statusType;
2215
- if (
2216
- statusType === 'active'
2217
- && !this.current
2218
- && this.state === 'Idle'
2219
- ) {
2407
+ if (activateBackground && !this.current && this.state === 'Idle') {
2220
2408
  this.state = 'BackgroundWorking';
2221
2409
  } else if (
2222
2410
  statusType === 'idle'
@@ -29,13 +29,26 @@
29
29
 
30
30
  'use strict';
31
31
 
32
- const { createHash } = require('node:crypto');
32
+ const { createHash, hash } = require('node:crypto');
33
33
 
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
37
  const MAX_RUNTIME_ID_BYTES = 512;
38
38
  const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
39
+ const QUALIFICATION_PROCESS_STATES = new Set([
40
+ 'Spawning', 'Initializing', 'AttachingThread', 'Idle', 'StartingTurn',
41
+ 'Active', 'BackgroundWorking', 'BackgroundSettling', 'Settling',
42
+ 'Quiescing', 'Stopped', 'Closing', 'Closed', 'FailedAmbiguous',
43
+ 'RecoveryConflict', 'DurabilityBlocked', 'ContainmentFailed', 'unknown',
44
+ ]);
45
+ const QUALIFICATION_REASONS = new Set([
46
+ 'eligible', 'active-turn', 'pending-delivery', 'background-owner',
47
+ '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',
51
+ ]);
39
52
 
40
53
  class ProcessManagerError extends Error {
41
54
  constructor(message, code, options) {
@@ -62,6 +75,158 @@ function hintFingerprint(hint) {
62
75
  .slice(0, 8);
63
76
  }
64
77
 
78
+ function qualificationDigest(generationId) {
79
+ return typeof generationId === 'string'
80
+ ? hash('sha256', generationId, 'hex')
81
+ : null;
82
+ }
83
+
84
+ function qualificationResultFor(proc, reason, fence = {}) {
85
+ const observedAtMs = Object.hasOwn(fence, 'observedAtMs')
86
+ && Number.isSafeInteger(fence.observedAtMs)
87
+ && fence.observedAtMs >= 0
88
+ ? fence.observedAtMs
89
+ : Date.now();
90
+ return Object.freeze({
91
+ outcome: 'mismatch',
92
+ reason: QUALIFICATION_REASONS.has(reason) ? reason : 'inspection-failed',
93
+ generationDigest: Object.hasOwn(fence, 'generationDigest')
94
+ ? fence.generationDigest
95
+ : qualificationDigest(proc?.generationId),
96
+ activityEpoch: Object.hasOwn(fence, 'activityEpoch')
97
+ ? fence.activityEpoch
98
+ : (Number.isSafeInteger(proc?.activityEpoch) ? proc.activityEpoch : null),
99
+ processState: QUALIFICATION_PROCESS_STATES.has(proc?.state)
100
+ ? proc.state
101
+ : 'unknown',
102
+ activeTurnCount: proc?.current ? 1 : 0,
103
+ pendingDeliveryCount: typeof proc?.hasPendingDeliveryWork === 'function'
104
+ && proc.hasPendingDeliveryWork() ? 1 : 0,
105
+ backgroundOwnerCount: typeof proc?.hasActiveBackgroundWork === 'function'
106
+ && proc.hasActiveBackgroundWork() ? 1 : 0,
107
+ backgroundTerminalCount: 0,
108
+ backgroundTerminalRegistryComplete: false,
109
+ observedAtMs,
110
+ });
111
+ }
112
+
113
+ function normalizeQualificationExpectation(value, { requireFence = false } = {}) {
114
+ if (value === undefined && !requireFence) {
115
+ return { valid: true, expectedGenerationDigest: null, expectedActivityEpoch: null };
116
+ }
117
+ if (
118
+ value === null
119
+ || typeof value !== 'object'
120
+ || Array.isArray(value)
121
+ || Object.getPrototypeOf(value) !== Object.prototype
122
+ ) {
123
+ return { valid: false };
124
+ }
125
+ const keys = Reflect.ownKeys(value);
126
+ if (
127
+ keys.some((key) => (
128
+ typeof key !== 'string'
129
+ || !['expectedGenerationDigest', 'expectedActivityEpoch'].includes(key)
130
+ ))
131
+ || (requireFence && keys.length !== 2)
132
+ || (!requireFence && keys.length !== 0 && keys.length !== 2)
133
+ ) {
134
+ return { valid: false };
135
+ }
136
+ const expectedGenerationDigest = value.expectedGenerationDigest;
137
+ const expectedActivityEpoch = value.expectedActivityEpoch;
138
+ if (
139
+ keys.length === 2
140
+ && (
141
+ !/^[a-f0-9]{64}$/.test(expectedGenerationDigest)
142
+ || !Number.isSafeInteger(expectedActivityEpoch)
143
+ || expectedActivityEpoch < 0
144
+ )
145
+ ) {
146
+ return { valid: false };
147
+ }
148
+ return {
149
+ valid: true,
150
+ expectedGenerationDigest: keys.length === 2 ? expectedGenerationDigest : null,
151
+ expectedActivityEpoch: keys.length === 2 ? expectedActivityEpoch : null,
152
+ };
153
+ }
154
+
155
+ function normalizeQualificationResult(proc, result, expectedFence = {}) {
156
+ const expectedKeys = [
157
+ 'outcome',
158
+ 'reason',
159
+ 'generationDigest',
160
+ 'activityEpoch',
161
+ 'processState',
162
+ 'activeTurnCount',
163
+ 'pendingDeliveryCount',
164
+ 'backgroundOwnerCount',
165
+ 'backgroundTerminalCount',
166
+ 'backgroundTerminalRegistryComplete',
167
+ 'observedAtMs',
168
+ ];
169
+ const resultKeys = result && typeof result === 'object'
170
+ ? Reflect.ownKeys(result)
171
+ : [];
172
+ if (
173
+ !result
174
+ || typeof result !== 'object'
175
+ || Object.getPrototypeOf(result) !== Object.prototype
176
+ || resultKeys.length !== expectedKeys.length
177
+ || expectedKeys.some((key) => !Object.hasOwn(result, key))
178
+ || !['qualified', 'mismatch'].includes(result.outcome)
179
+ || !QUALIFICATION_REASONS.has(result.reason)
180
+ || !/^[a-f0-9]{64}$/.test(result.generationDigest)
181
+ || !Number.isSafeInteger(result.activityEpoch)
182
+ || result.activityEpoch < 0
183
+ || !QUALIFICATION_PROCESS_STATES.has(result.processState)
184
+ || ![0, 1].includes(result.activeTurnCount)
185
+ || ![0, 1].includes(result.pendingDeliveryCount)
186
+ || ![0, 1].includes(result.backgroundOwnerCount)
187
+ || !Number.isSafeInteger(result.backgroundTerminalCount)
188
+ || result.backgroundTerminalCount < 0
189
+ || result.backgroundTerminalCount > 1_600
190
+ || typeof result.backgroundTerminalRegistryComplete !== 'boolean'
191
+ || !Number.isSafeInteger(result.observedAtMs)
192
+ || result.observedAtMs < 0
193
+ ) {
194
+ return qualificationResultFor(proc, 'inspection-failed');
195
+ }
196
+ if (
197
+ result.outcome === 'qualified'
198
+ && (
199
+ result.reason !== 'eligible'
200
+ || result.generationDigest !== expectedFence.generationDigest
201
+ || result.activityEpoch !== expectedFence.activityEpoch
202
+ || result.processState !== 'Idle'
203
+ || result.activeTurnCount !== 0
204
+ || result.pendingDeliveryCount !== 0
205
+ || result.backgroundOwnerCount !== 0
206
+ || result.backgroundTerminalCount !== 0
207
+ || result.backgroundTerminalRegistryComplete !== true
208
+ )
209
+ ) {
210
+ return qualificationResultFor(proc, 'incoherent', {
211
+ ...expectedFence,
212
+ observedAtMs: result.observedAtMs,
213
+ });
214
+ }
215
+ return Object.freeze({
216
+ outcome: result.outcome,
217
+ reason: result.reason,
218
+ generationDigest: result.generationDigest,
219
+ activityEpoch: result.activityEpoch,
220
+ processState: result.processState,
221
+ activeTurnCount: result.activeTurnCount,
222
+ pendingDeliveryCount: result.pendingDeliveryCount,
223
+ backgroundOwnerCount: result.backgroundOwnerCount,
224
+ backgroundTerminalCount: result.backgroundTerminalCount,
225
+ backgroundTerminalRegistryComplete: result.backgroundTerminalRegistryComplete,
226
+ observedAtMs: result.observedAtMs,
227
+ });
228
+ }
229
+
65
230
  function findCodexRetirementVerificationError(error) {
66
231
  let current = error;
67
232
  for (let depth = 0; current && depth < 8; depth += 1) {
@@ -244,10 +409,29 @@ class ProcessManager {
244
409
  * @param {object} [opts.callbacks={}] — keys: onInit, onClose, ...
245
410
  * @param {number} [opts.lruWaitMs] — how long getOrSpawn parks
246
411
  * when all entries are in-flight
412
+ * @param {(input: {
413
+ * sessionKey: string,
414
+ * generationId: string,
415
+ * attemptId: string,
416
+ * providerSessionId: string,
417
+ * providerTurnId: string,
418
+ * sourceMsgId: (string|number),
419
+ * }) => {
420
+ * committed: true,
421
+ * disposition: 'retirement-requested',
422
+ * sessionKey: string,
423
+ * generationId: string,
424
+ * attemptId: string,
425
+ * providerSessionId: string,
426
+ * providerTurnId: string,
427
+ * sourceMsgId: (string|number),
428
+ * }}
429
+ * [opts.codexRetirementPreparer] — synchronous consumer ownership handshake;
430
+ * the acknowledgement echoes every input binding without normalization.
247
431
  * @param {(input: object) => Promise<{committed: true}>}
248
432
  * [opts.codexRetirementVerifier] — consumer durability handshake.
249
433
  * @param {number} [opts.codexRetirementTimeoutMs=30000]
250
- * — absolute deadline for the optional durability handshake.
434
+ * — absolute deadline for the optional post-stop durability handshake.
251
435
  */
252
436
  constructor({
253
437
  processFactory,
@@ -259,6 +443,7 @@ class ProcessManager {
259
443
  codexRecoveryState,
260
444
  codexHostIdentity = null,
261
445
  codexBootSessionIdentity = null,
446
+ codexRetirementPreparer = null,
262
447
  codexRetirementVerifier = null,
263
448
  codexRetirementTimeoutMs = DEFAULT_CODEX_RETIREMENT_TIMEOUT_MS,
264
449
  } = {}) {
@@ -293,6 +478,15 @@ class ProcessManager {
293
478
  // record, even when that record says no generation was live.
294
479
  this.codexHostIdentity = codexHostIdentity;
295
480
  this.codexBootSessionIdentity = codexBootSessionIdentity;
481
+ if (
482
+ codexRetirementPreparer != null
483
+ && typeof codexRetirementPreparer !== 'function'
484
+ ) {
485
+ throw new TypeError(
486
+ 'ProcessManager: codexRetirementPreparer function required',
487
+ );
488
+ }
489
+ this.codexRetirementPreparer = codexRetirementPreparer;
296
490
  if (
297
491
  codexRetirementVerifier != null
298
492
  && typeof codexRetirementVerifier !== 'function'
@@ -325,6 +519,85 @@ class ProcessManager {
325
519
  keys() { return [...this.procs.keys()]; }
326
520
  get size() { return this.procs.size; }
327
521
 
522
+ async inspectCleanRestartQualification(expectation, { requireFence = false } = {}) {
523
+ const lease = this._codexLease;
524
+ const proc = lease?.proc ?? null;
525
+ const sessionKey = lease?.sessionKey ?? null;
526
+ const capturedFence = {
527
+ generationDigest: qualificationDigest(proc?.generationId),
528
+ activityEpoch: Number.isSafeInteger(proc?.activityEpoch)
529
+ ? proc.activityEpoch
530
+ : null,
531
+ };
532
+ const parsedExpectation = normalizeQualificationExpectation(expectation, {
533
+ requireFence,
534
+ });
535
+ if (!parsedExpectation.valid) {
536
+ return qualificationResultFor(proc, 'invalid-expectation', capturedFence);
537
+ }
538
+ if (!proc || !this._isCodex(proc) || proc.closed || !this._codexLeaseMatches(proc)) {
539
+ return qualificationResultFor(proc, 'no-codex-generation', capturedFence);
540
+ }
541
+
542
+ const { expectedGenerationDigest, expectedActivityEpoch } = parsedExpectation;
543
+ if (
544
+ expectedGenerationDigest != null
545
+ && expectedGenerationDigest !== capturedFence.generationDigest
546
+ ) {
547
+ return qualificationResultFor(proc, 'generation-drift', capturedFence);
548
+ }
549
+ if (
550
+ expectedActivityEpoch != null
551
+ && expectedActivityEpoch !== capturedFence.activityEpoch
552
+ ) {
553
+ return qualificationResultFor(proc, 'activity-epoch-drift', capturedFence);
554
+ }
555
+ if (typeof proc.inspectCleanRestartQualification !== 'function') {
556
+ return qualificationResultFor(proc, 'unsupported', capturedFence);
557
+ }
558
+
559
+ const assertLease = () => {
560
+ if (
561
+ this._codexLease !== lease
562
+ || this.procs.get(sessionKey) !== proc
563
+ || !this._codexLeaseMatches(proc)
564
+ || proc.closed
565
+ ) {
566
+ throw managerError(
567
+ 'Codex qualification lease changed',
568
+ 'CODEX_QUALIFICATION_LEASE_DRIFT',
569
+ );
570
+ }
571
+ if (
572
+ qualificationDigest(proc.generationId) !== capturedFence.generationDigest
573
+ || proc.activityEpoch !== capturedFence.activityEpoch
574
+ ) {
575
+ throw managerError(
576
+ 'Codex qualification fence changed',
577
+ 'CODEX_QUALIFICATION_FENCE',
578
+ );
579
+ }
580
+ return true;
581
+ };
582
+ try {
583
+ const result = await proc.inspectCleanRestartQualification({
584
+ expectedGenerationDigest: capturedFence.generationDigest,
585
+ expectedActivityEpoch: capturedFence.activityEpoch,
586
+ assertLease,
587
+ });
588
+ assertLease();
589
+ return normalizeQualificationResult(proc, result, capturedFence);
590
+ } catch (error) {
591
+ if (error?.code === 'CODEX_QUALIFICATION_LEASE_DRIFT') {
592
+ return qualificationResultFor(proc, 'lease-drift', capturedFence);
593
+ }
594
+ if (error?.code === 'CODEX_QUALIFICATION_FENCE') {
595
+ return qualificationResultFor(proc, 'fence-drift', capturedFence);
596
+ }
597
+ return qualificationResultFor(proc, 'inspection-failed', capturedFence);
598
+ }
599
+ }
600
+
328
601
  /**
329
602
  * Current total cost across all live processes.
330
603
  */
@@ -524,6 +797,24 @@ class ProcessManager {
524
797
  return run;
525
798
  }
526
799
 
800
+ async _drainLifecycleGatesToStableEmpty(gateErrors) {
801
+ while (true) {
802
+ const entries = [...this._lifecycleGates.entries()];
803
+ if (entries.length === 0) {
804
+ await Promise.resolve();
805
+ if (this._lifecycleGates.size === 0) return;
806
+ continue;
807
+ }
808
+ await Promise.allSettled(entries.map(async ([sessionKey, gate]) => {
809
+ try {
810
+ await gate;
811
+ } catch (error) {
812
+ gateErrors.set(sessionKey, error);
813
+ }
814
+ }));
815
+ }
816
+ }
817
+
527
818
  _withRetirementIntent(sessionKey, operation) {
528
819
  const count = (this._retirementIntents.get(sessionKey) ?? 0) + 1;
529
820
  this._retirementIntents.set(sessionKey, count);
@@ -1203,6 +1494,64 @@ class ProcessManager {
1203
1494
  }
1204
1495
  }
1205
1496
 
1497
+ _prepareCodexRetirement(candidate) {
1498
+ if (!this.codexRetirementPreparer) {
1499
+ throw managerError(
1500
+ 'Codex continuation retirement requires durable preparation',
1501
+ 'CODEX_RETIREMENT_PREPARATION_FAILED',
1502
+ );
1503
+ }
1504
+ const input = Object.freeze({
1505
+ sessionKey: candidate.sessionKey,
1506
+ generationId: candidate.generationId,
1507
+ attemptId: candidate.attemptId,
1508
+ providerSessionId: candidate.providerSessionId,
1509
+ providerTurnId: candidate.providerTurnId,
1510
+ sourceMsgId: candidate.sourceMsgId,
1511
+ });
1512
+ let preparation;
1513
+ try {
1514
+ preparation = this.codexRetirementPreparer(input);
1515
+ } catch (cause) {
1516
+ throw managerError(
1517
+ 'Codex continuation retirement preparation failed',
1518
+ 'CODEX_RETIREMENT_PREPARATION_FAILED',
1519
+ { cause },
1520
+ );
1521
+ }
1522
+ const expectedKeys = [
1523
+ 'committed',
1524
+ 'disposition',
1525
+ 'sessionKey',
1526
+ 'generationId',
1527
+ 'attemptId',
1528
+ 'providerSessionId',
1529
+ 'providerTurnId',
1530
+ 'sourceMsgId',
1531
+ ];
1532
+ const keys = preparation && typeof preparation === 'object'
1533
+ ? Reflect.ownKeys(preparation)
1534
+ : [];
1535
+ if (
1536
+ typeof preparation?.then === 'function'
1537
+ || keys.length !== expectedKeys.length
1538
+ || expectedKeys.some((key) => !Object.hasOwn(preparation, key))
1539
+ || preparation.committed !== true
1540
+ || preparation.disposition !== 'retirement-requested'
1541
+ || preparation.sessionKey !== input.sessionKey
1542
+ || preparation.generationId !== input.generationId
1543
+ || preparation.attemptId !== input.attemptId
1544
+ || preparation.providerSessionId !== input.providerSessionId
1545
+ || preparation.providerTurnId !== input.providerTurnId
1546
+ || preparation.sourceMsgId !== input.sourceMsgId
1547
+ ) {
1548
+ throw managerError(
1549
+ 'Codex continuation retirement preparation was not exact',
1550
+ 'CODEX_RETIREMENT_PREPARATION_FAILED',
1551
+ );
1552
+ }
1553
+ }
1554
+
1206
1555
  _evictLRU() {
1207
1556
  let oldest = null;
1208
1557
  let oldestKey = null;
@@ -1457,12 +1806,21 @@ class ProcessManager {
1457
1806
  }
1458
1807
  }
1459
1808
 
1460
- async retireForCleanRestart({ getDeliveryEvidence } = {}) {
1809
+ async retireForCleanRestart({
1810
+ getDeliveryEvidence,
1811
+ qualificationExpectation,
1812
+ continuationAuthorized = false,
1813
+ } = {}) {
1461
1814
  if (typeof getDeliveryEvidence !== 'function') {
1462
1815
  throw new TypeError(
1463
1816
  'ProcessManager.retireForCleanRestart: getDeliveryEvidence function required',
1464
1817
  );
1465
1818
  }
1819
+ if (typeof continuationAuthorized !== 'boolean') {
1820
+ throw new TypeError(
1821
+ 'ProcessManager.retireForCleanRestart: continuationAuthorized boolean required',
1822
+ );
1823
+ }
1466
1824
  this._shuttingDown = true;
1467
1825
  this._lifecycleAdmissionClosed = true;
1468
1826
  for (const w of this._lruWaiters) {
@@ -1471,31 +1829,52 @@ class ProcessManager {
1471
1829
  }
1472
1830
  this._lruWaiters.length = 0;
1473
1831
 
1832
+ const admittedGateErrors = new Map();
1474
1833
  const admittedGates = new Map(this._lifecycleGates);
1834
+ await this._drainLifecycleGatesToStableEmpty(admittedGateErrors);
1835
+
1475
1836
  const targets = new Set([
1476
1837
  ...[...this.procs.entries()]
1477
1838
  .filter(([, proc]) => !this._retiring.has(proc))
1478
1839
  .map(([sessionKey]) => sessionKey),
1479
1840
  ...this._cleanRetirementCandidates.keys(),
1480
1841
  ...admittedGates.keys(),
1842
+ ...admittedGateErrors.keys(),
1481
1843
  ]);
1482
1844
  const retiredTargets = new Map();
1845
+ const qualificationLease = qualificationExpectation === undefined
1846
+ ? null
1847
+ : this._codexLease;
1848
+ const qualificationProc = qualificationLease?.proc ?? null;
1849
+ let qualification = qualificationExpectation === undefined
1850
+ ? null
1851
+ : await this.inspectCleanRestartQualification(
1852
+ qualificationExpectation,
1853
+ { requireFence: true },
1854
+ );
1483
1855
 
1484
1856
  let settled;
1485
1857
  try {
1486
1858
  settled = await Promise.allSettled([...targets].map(async (sessionKey) => {
1487
- let gateError = null;
1488
- const gate = admittedGates.get(sessionKey);
1489
- if (gate) {
1490
- try {
1491
- await gate;
1492
- } catch (error) {
1493
- gateError = error;
1494
- }
1495
- }
1859
+ const gateError = admittedGateErrors.get(sessionKey) ?? null;
1496
1860
  const proc = this.procs.get(sessionKey)
1497
1861
  ?? this._cleanRetirementCandidates.get(sessionKey);
1498
1862
  if (!proc || this._retiring.has(proc)) {
1863
+ if (
1864
+ qualification?.outcome === 'qualified'
1865
+ && sessionKey === qualificationLease?.sessionKey
1866
+ && qualificationProc
1867
+ ) {
1868
+ qualification = qualificationResultFor(
1869
+ qualificationProc,
1870
+ 'lease-drift',
1871
+ {
1872
+ generationDigest: qualification.generationDigest,
1873
+ activityEpoch: qualification.activityEpoch,
1874
+ observedAtMs: qualification.observedAtMs,
1875
+ },
1876
+ );
1877
+ }
1499
1878
  if (gateError) throw gateError;
1500
1879
  return null;
1501
1880
  }
@@ -1507,6 +1886,35 @@ class ProcessManager {
1507
1886
  const candidate = typeof proc.captureCleanRestartCandidate === 'function'
1508
1887
  ? proc.captureCleanRestartCandidate()
1509
1888
  : null;
1889
+ if (qualification?.outcome === 'qualified') {
1890
+ const leaseChanged = Boolean(
1891
+ this._codexLease !== qualificationLease
1892
+ || qualificationProc !== proc
1893
+ || this.procs.get(sessionKey) !== proc
1894
+ || !this._codexLeaseMatches(proc)
1895
+ || proc.closed
1896
+ );
1897
+ const fenceChanged = Boolean(
1898
+ qualificationDigest(proc.generationId) !== qualification.generationDigest
1899
+ || proc.activityEpoch !== qualification.activityEpoch
1900
+ );
1901
+ if (leaseChanged || fenceChanged) {
1902
+ qualification = qualificationResultFor(
1903
+ proc,
1904
+ leaseChanged ? 'lease-drift' : 'fence-drift',
1905
+ {
1906
+ generationDigest: qualification.generationDigest,
1907
+ activityEpoch: qualification.activityEpoch,
1908
+ observedAtMs: qualification.observedAtMs,
1909
+ },
1910
+ );
1911
+ }
1912
+ }
1913
+ if (continuationAuthorized && candidate) {
1914
+ this._prepareCodexRetirement(candidate);
1915
+ }
1916
+ const retirementPromise = this._strictRetire(proc, 'clean-restart');
1917
+ retirementPromise.catch(() => {});
1510
1918
  let deliveryEvidence = null;
1511
1919
  let deliveryEvidenceError = null;
1512
1920
  try {
@@ -1517,7 +1925,7 @@ class ProcessManager {
1517
1925
  } catch (error) {
1518
1926
  deliveryEvidenceError = error;
1519
1927
  }
1520
- const retirement = await this._strictRetire(proc, 'clean-restart');
1928
+ const retirement = await retirementPromise;
1521
1929
  const settledTerminalStatus = this._codexLease?.terminalStatus ?? null;
1522
1930
  const settledTurnId = this._codexLease?.turnId ?? null;
1523
1931
  const deliverySafe = Boolean(
@@ -1626,6 +2034,14 @@ class ProcessManager {
1626
2034
  const results = settled
1627
2035
  .filter(result => result.status === 'fulfilled' && result.value != null)
1628
2036
  .map(result => result.value);
2037
+ if (qualification) {
2038
+ Object.defineProperty(results, 'qualification', {
2039
+ value: qualification,
2040
+ enumerable: false,
2041
+ writable: false,
2042
+ configurable: false,
2043
+ });
2044
+ }
1629
2045
  return Object.freeze(results);
1630
2046
  }
1631
2047
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.10.15",
3
+ "version": "0.10.17",
4
4
  "description": "Transport-agnostic session engine for Claude Code and the native Codex app-server: spawn, steer, supervise, observe turns, and recover.",
5
5
  "type": "commonjs",
6
6
  "main": "index.js",