@shumkov/orchestra 0.10.15 → 0.10.16

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) {
@@ -325,6 +490,85 @@ class ProcessManager {
325
490
  keys() { return [...this.procs.keys()]; }
326
491
  get size() { return this.procs.size; }
327
492
 
493
+ async inspectCleanRestartQualification(expectation, { requireFence = false } = {}) {
494
+ const lease = this._codexLease;
495
+ const proc = lease?.proc ?? null;
496
+ const sessionKey = lease?.sessionKey ?? null;
497
+ const capturedFence = {
498
+ generationDigest: qualificationDigest(proc?.generationId),
499
+ activityEpoch: Number.isSafeInteger(proc?.activityEpoch)
500
+ ? proc.activityEpoch
501
+ : null,
502
+ };
503
+ const parsedExpectation = normalizeQualificationExpectation(expectation, {
504
+ requireFence,
505
+ });
506
+ if (!parsedExpectation.valid) {
507
+ return qualificationResultFor(proc, 'invalid-expectation', capturedFence);
508
+ }
509
+ if (!proc || !this._isCodex(proc) || proc.closed || !this._codexLeaseMatches(proc)) {
510
+ return qualificationResultFor(proc, 'no-codex-generation', capturedFence);
511
+ }
512
+
513
+ const { expectedGenerationDigest, expectedActivityEpoch } = parsedExpectation;
514
+ if (
515
+ expectedGenerationDigest != null
516
+ && expectedGenerationDigest !== capturedFence.generationDigest
517
+ ) {
518
+ return qualificationResultFor(proc, 'generation-drift', capturedFence);
519
+ }
520
+ if (
521
+ expectedActivityEpoch != null
522
+ && expectedActivityEpoch !== capturedFence.activityEpoch
523
+ ) {
524
+ return qualificationResultFor(proc, 'activity-epoch-drift', capturedFence);
525
+ }
526
+ if (typeof proc.inspectCleanRestartQualification !== 'function') {
527
+ return qualificationResultFor(proc, 'unsupported', capturedFence);
528
+ }
529
+
530
+ const assertLease = () => {
531
+ if (
532
+ this._codexLease !== lease
533
+ || this.procs.get(sessionKey) !== proc
534
+ || !this._codexLeaseMatches(proc)
535
+ || proc.closed
536
+ ) {
537
+ throw managerError(
538
+ 'Codex qualification lease changed',
539
+ 'CODEX_QUALIFICATION_LEASE_DRIFT',
540
+ );
541
+ }
542
+ if (
543
+ qualificationDigest(proc.generationId) !== capturedFence.generationDigest
544
+ || proc.activityEpoch !== capturedFence.activityEpoch
545
+ ) {
546
+ throw managerError(
547
+ 'Codex qualification fence changed',
548
+ 'CODEX_QUALIFICATION_FENCE',
549
+ );
550
+ }
551
+ return true;
552
+ };
553
+ try {
554
+ const result = await proc.inspectCleanRestartQualification({
555
+ expectedGenerationDigest: capturedFence.generationDigest,
556
+ expectedActivityEpoch: capturedFence.activityEpoch,
557
+ assertLease,
558
+ });
559
+ assertLease();
560
+ return normalizeQualificationResult(proc, result, capturedFence);
561
+ } catch (error) {
562
+ if (error?.code === 'CODEX_QUALIFICATION_LEASE_DRIFT') {
563
+ return qualificationResultFor(proc, 'lease-drift', capturedFence);
564
+ }
565
+ if (error?.code === 'CODEX_QUALIFICATION_FENCE') {
566
+ return qualificationResultFor(proc, 'fence-drift', capturedFence);
567
+ }
568
+ return qualificationResultFor(proc, 'inspection-failed', capturedFence);
569
+ }
570
+ }
571
+
328
572
  /**
329
573
  * Current total cost across all live processes.
330
574
  */
@@ -524,6 +768,24 @@ class ProcessManager {
524
768
  return run;
525
769
  }
526
770
 
771
+ async _drainLifecycleGatesToStableEmpty(gateErrors) {
772
+ while (true) {
773
+ const entries = [...this._lifecycleGates.entries()];
774
+ if (entries.length === 0) {
775
+ await Promise.resolve();
776
+ if (this._lifecycleGates.size === 0) return;
777
+ continue;
778
+ }
779
+ await Promise.allSettled(entries.map(async ([sessionKey, gate]) => {
780
+ try {
781
+ await gate;
782
+ } catch (error) {
783
+ gateErrors.set(sessionKey, error);
784
+ }
785
+ }));
786
+ }
787
+ }
788
+
527
789
  _withRetirementIntent(sessionKey, operation) {
528
790
  const count = (this._retirementIntents.get(sessionKey) ?? 0) + 1;
529
791
  this._retirementIntents.set(sessionKey, count);
@@ -1457,7 +1719,10 @@ class ProcessManager {
1457
1719
  }
1458
1720
  }
1459
1721
 
1460
- async retireForCleanRestart({ getDeliveryEvidence } = {}) {
1722
+ async retireForCleanRestart({
1723
+ getDeliveryEvidence,
1724
+ qualificationExpectation,
1725
+ } = {}) {
1461
1726
  if (typeof getDeliveryEvidence !== 'function') {
1462
1727
  throw new TypeError(
1463
1728
  'ProcessManager.retireForCleanRestart: getDeliveryEvidence function required',
@@ -1471,31 +1736,52 @@ class ProcessManager {
1471
1736
  }
1472
1737
  this._lruWaiters.length = 0;
1473
1738
 
1739
+ const admittedGateErrors = new Map();
1474
1740
  const admittedGates = new Map(this._lifecycleGates);
1741
+ await this._drainLifecycleGatesToStableEmpty(admittedGateErrors);
1742
+
1475
1743
  const targets = new Set([
1476
1744
  ...[...this.procs.entries()]
1477
1745
  .filter(([, proc]) => !this._retiring.has(proc))
1478
1746
  .map(([sessionKey]) => sessionKey),
1479
1747
  ...this._cleanRetirementCandidates.keys(),
1480
1748
  ...admittedGates.keys(),
1749
+ ...admittedGateErrors.keys(),
1481
1750
  ]);
1482
1751
  const retiredTargets = new Map();
1752
+ const qualificationLease = qualificationExpectation === undefined
1753
+ ? null
1754
+ : this._codexLease;
1755
+ const qualificationProc = qualificationLease?.proc ?? null;
1756
+ let qualification = qualificationExpectation === undefined
1757
+ ? null
1758
+ : await this.inspectCleanRestartQualification(
1759
+ qualificationExpectation,
1760
+ { requireFence: true },
1761
+ );
1483
1762
 
1484
1763
  let settled;
1485
1764
  try {
1486
1765
  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
- }
1766
+ const gateError = admittedGateErrors.get(sessionKey) ?? null;
1496
1767
  const proc = this.procs.get(sessionKey)
1497
1768
  ?? this._cleanRetirementCandidates.get(sessionKey);
1498
1769
  if (!proc || this._retiring.has(proc)) {
1770
+ if (
1771
+ qualification?.outcome === 'qualified'
1772
+ && sessionKey === qualificationLease?.sessionKey
1773
+ && qualificationProc
1774
+ ) {
1775
+ qualification = qualificationResultFor(
1776
+ qualificationProc,
1777
+ 'lease-drift',
1778
+ {
1779
+ generationDigest: qualification.generationDigest,
1780
+ activityEpoch: qualification.activityEpoch,
1781
+ observedAtMs: qualification.observedAtMs,
1782
+ },
1783
+ );
1784
+ }
1499
1785
  if (gateError) throw gateError;
1500
1786
  return null;
1501
1787
  }
@@ -1507,6 +1793,32 @@ class ProcessManager {
1507
1793
  const candidate = typeof proc.captureCleanRestartCandidate === 'function'
1508
1794
  ? proc.captureCleanRestartCandidate()
1509
1795
  : null;
1796
+ if (qualification?.outcome === 'qualified') {
1797
+ const leaseChanged = Boolean(
1798
+ this._codexLease !== qualificationLease
1799
+ || qualificationProc !== proc
1800
+ || this.procs.get(sessionKey) !== proc
1801
+ || !this._codexLeaseMatches(proc)
1802
+ || proc.closed
1803
+ );
1804
+ const fenceChanged = Boolean(
1805
+ qualificationDigest(proc.generationId) !== qualification.generationDigest
1806
+ || proc.activityEpoch !== qualification.activityEpoch
1807
+ );
1808
+ if (leaseChanged || fenceChanged) {
1809
+ qualification = qualificationResultFor(
1810
+ proc,
1811
+ leaseChanged ? 'lease-drift' : 'fence-drift',
1812
+ {
1813
+ generationDigest: qualification.generationDigest,
1814
+ activityEpoch: qualification.activityEpoch,
1815
+ observedAtMs: qualification.observedAtMs,
1816
+ },
1817
+ );
1818
+ }
1819
+ }
1820
+ const retirementPromise = this._strictRetire(proc, 'clean-restart');
1821
+ retirementPromise.catch(() => {});
1510
1822
  let deliveryEvidence = null;
1511
1823
  let deliveryEvidenceError = null;
1512
1824
  try {
@@ -1517,7 +1829,7 @@ class ProcessManager {
1517
1829
  } catch (error) {
1518
1830
  deliveryEvidenceError = error;
1519
1831
  }
1520
- const retirement = await this._strictRetire(proc, 'clean-restart');
1832
+ const retirement = await retirementPromise;
1521
1833
  const settledTerminalStatus = this._codexLease?.terminalStatus ?? null;
1522
1834
  const settledTurnId = this._codexLease?.turnId ?? null;
1523
1835
  const deliverySafe = Boolean(
@@ -1626,6 +1938,14 @@ class ProcessManager {
1626
1938
  const results = settled
1627
1939
  .filter(result => result.status === 'fulfilled' && result.value != null)
1628
1940
  .map(result => result.value);
1941
+ if (qualification) {
1942
+ Object.defineProperty(results, 'qualification', {
1943
+ value: qualification,
1944
+ enumerable: false,
1945
+ writable: false,
1946
+ configurable: false,
1947
+ });
1948
+ }
1629
1949
  return Object.freeze(results);
1630
1950
  }
1631
1951
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.10.15",
3
+ "version": "0.10.16",
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",