@shumkov/orchestra 0.10.17 → 0.10.19

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.
@@ -740,3 +740,162 @@ prepared/write-attempted/response-observed ledger, Codex-owned retry rule,
740
740
  unknown-effect non-replay rule, immutable model/effort thread policy, exact
741
741
  profile provenance, one-live daemon lease, and accepted quarantine contract.
742
742
  No Orchestra backend or Claude behavior has been changed by U1.
743
+
744
+ ## Credential-free hook notification probe passed
745
+
746
+ Codex 0.145.0 emits `hook/started` and `hook/completed` whenever the active
747
+ configuration enables hooks. `lib/codex/protocol-schema.json` lists both as
748
+ dropped server notifications and `lib/codex/app-server-client.js` enforces that
749
+ drop. The characterization allowlist in `scripts/spikes/codex-app-server-rpc.mjs`
750
+ admits the same two methods without retaining them. Every other `hook/*` method
751
+ remains an exact-match fail-closed protocol fault; that is proved
752
+ deterministically by "Codex U1a faults a well-formed but unlisted hook
753
+ notification" in `tests/codex-app-server-spike.test.js` rather than by a live
754
+ peer.
755
+
756
+ `scripts/spikes/codex-app-server-hook-probe.mjs` is the reproducible gate:
757
+
758
+ ```sh
759
+ node scripts/spikes/codex-app-server-hook-probe.mjs \
760
+ --binary /absolute/versioned/path/to/codex \
761
+ --probe-root /absolute/non-temporary/probe-root
762
+ ```
763
+
764
+ It exits 0 only when every gate check passes, and deliberately exits 1
765
+ otherwise, including on a thrown failure.
766
+
767
+ Containment holds on the complete successful envelope, not only on failure, and
768
+ it is a closed-key projection rather than denylist filtering. Every emitted
769
+ object is built key by key from an approved name list with an approved scalar
770
+ type; no evidence-derived object is ever spread. An unapproved key is therefore
771
+ dropped and cannot be emitted whatever it contains, including benign plain text
772
+ no regex would catch. An approved slot holding a wrong type or an
773
+ off-enum value collapses the whole result to a content-free `STOP` with a
774
+ category. Raw turn ids are stripped from both lanes. The trailing
775
+ content-free assertion is retained as defense in depth, not as the mechanism.
776
+
777
+ Nothing raw is persisted. The hook handler parses stdin in place and writes only
778
+ closed fields — event name, whether a `turn_id` was supplied, and its SHA-256 —
779
+ so the user prompt, cwd, and transcript path never reach disk, and no raw turn
780
+ id is stored. The raw JSON-RPC lane routes each response directly to its pending
781
+ request and keeps no session-wide result cache; a result exists only as a local
782
+ value for the duration of that request, and callers digest or project what they
783
+ need and discard the rest. Only bounded closed-field summaries survive the
784
+ request.
785
+
786
+ ### What the authoritative lane is
787
+
788
+ The hooks-on and hooks-off lanes drive the production `CodexAppServerClient`
789
+ with the real `attestPinnedCodexBinary` target-pin attestation, an isolated
790
+ mode-0700 owned `codexHome`, the exact `expectedConfigSha256`, and the
791
+ production delivery-checkpoint ledger. Each lane awaits an actual delivered
792
+ `turn/completed` rather than sleeping. The gate therefore fails if the
793
+ production schema-backed boundary breaks, even when a raw stdio session would
794
+ still have completed.
795
+
796
+ The hooks-off control lane is held to the same predicates as hooks-on —
797
+ completed status, an assistant item, no fault, and the same three-way
798
+ start/started/completed identity equality — and additionally must see no hook
799
+ traffic at all.
800
+
801
+ A raw stdio session remains only as a secondary characterization of the payloads
802
+ the production client intentionally drops. Its outcome can never satisfy
803
+ authoritative completion: the gate requires
804
+ `authoritative.source === 'production-client'`.
805
+
806
+ That session enforces the same exact envelope key sets the production client
807
+ accepts — `{id, result}` / `{id, error}` for responses and
808
+ `{method, params, emittedAtMs}` for notifications. Ambiguous response and
809
+ notification shapes, arbitrary extra top-level members, unlisted notification
810
+ methods, and unexpected response ids all fail closed. It bounds stdout lines,
811
+ undelimited partials, aggregate bytes, message count and stderr bytes; on stream
812
+ end it flushes the decoder and fails on a trailing partial or on EOF with
813
+ requests still pending. Its terminal failure is re-checked **after** child
814
+ teardown and stream drain, so malformed bytes that arrive while the child is
815
+ being killed cannot be reported as success. Cleanup signals the owned process
816
+ group, and proves the group is empty by enumerating it with
817
+ `/bin/ps -axo pid=,pgid=` — the same mechanism the U1b effect proxy uses —
818
+ rather than trusting leader exit alone; an exit or a non-empty group that cannot
819
+ be proved is a `cleanup` failure.
820
+
821
+ Close-time faults count. The production lane reads its settled fault outcome
822
+ **after** `client.close()`, so a fault the client delivers during close cannot
823
+ be lost, and a close failure is reported rather than swallowed. Loopback
824
+ provider shutdown force-closes idle and active connections under a bound; a
825
+ provider close rejection or timeout yields a content-free `cleanup` STOP even
826
+ when the lanes themselves passed. Probe-root creation and provider acquisition
827
+ both sit inside nested guards so scratch removal always runs.
828
+
829
+ The turn completes against a loopback Responses provider declaring
830
+ `requires_openai_auth = false`, inside homes that contain no `auth.json`.
831
+ Credential-free is a property of that construction, gated on those two concrete
832
+ conditions, not an observation of file reads. No product credential is read,
833
+ copied, or required, and no existing Codex home is touched.
834
+
835
+ ### Observed
836
+
837
+ - both lanes reached delivered `turn/completed` status `completed` with an
838
+ assistant item and no fault;
839
+ - the `turn/start` response id, the single delivered `turn/started.params.turn.id`,
840
+ and the completed turn id were equal;
841
+ - no `hook/*` method reached the production delivered notification sink in
842
+ either lane;
843
+ - the exact configured event multiset (`sessionStart`, `userPromptSubmit`)
844
+ appeared, each with exactly one `hook/started` (`running`) followed by one
845
+ `hook/completed` (`completed`), all timestamps 10-digit epoch seconds;
846
+ - exactly one hook stdin capture existed per configured event, counted from
847
+ per-invocation capture files rather than a last-writer-wins name, so a
848
+ repeated invocation fails the gate;
849
+ - the owned `config.toml` digest was byte-identical across each lane run;
850
+ - removing only the two schema drop entries flipped the gate to `STOP` with
851
+ `authoritative.faultCategory` `protocol` and exit 1, while the hooks-off
852
+ control stayed fault-free;
853
+ - no probe directory or child process survived either a passing or a failing
854
+ run.
855
+
856
+ ### Two distinct turn identities
857
+
858
+ App-server notification `params.turnId` and hook stdin `turn_id` are different
859
+ surfaces and must not be conflated.
860
+
861
+ - `params.turnId` rides on the `hook/started` and `hook/completed`
862
+ notifications, which the production client drops. It is characterized only in
863
+ the secondary raw lane, which runs its own separate turn: the probe emits
864
+ `notificationTurnIdMatchesRawTurn`, a boolean comparing the digest of each
865
+ hook notification's `params.turnId` against the digest of *that lane's* own
866
+ `turn/start` turn id. It is deliberately not compared against the
867
+ authoritative lane's turn, which belongs to a different turn entirely.
868
+ - Hook stdin `turn_id` is supplied to the hook process itself. The probe proves
869
+ from the authoritative lane's own captures that `userPromptSubmit` stdin
870
+ `turn_id` equals the authoritative turn id. It is **absent** for
871
+ `sessionStart`, whose stdin carries `cwd`, `hook_event_name`, `model`,
872
+ `permission_mode`, `session_id`, `source`, and `transcript_path` but no
873
+ `turn_id`. Hook stdin identifies the thread as `session_id`, not `thread_id`.
874
+
875
+ The probe requires the `sessionStart` capture to exist while omitting
876
+ `turn_id`; a missing capture fails. It records that event as
877
+ `present-without-turn-id`, never as a satisfied equality. Any receipt design
878
+ keyed on hook stdin `turn_id` must select an event that supplies one; a
879
+ `sessionStart` hook cannot discharge that correlation.
880
+
881
+ ### What the config digest does and does not attest
882
+
883
+ The probe drives the full drift sequence and gates every step: hooks are
884
+ discovered `untrusted`, rendered `trusted`, then the hook handler is mutated.
885
+ After mutation `hooks/list` reports a new `currentHash` and `trustStatus:
886
+ modified` **while `config.toml` and its digest are unchanged**. Only after the
887
+ new trusted hash is re-rendered does the owned-config digest change and the hook
888
+ return to `trusted`/enabled.
889
+
890
+ Digest-only attestation therefore does not detect an un-rendered hook-file
891
+ mutation; the `trustStatus` returned by `hooks/list` is the signal that does.
892
+
893
+ Scope limits. This is a protocol-boundary and correlation result, not a hosted
894
+ product result: the completed turn is served by a loopback provider, not by the
895
+ real model backend. `CodexProcess` is not exercised; `CodexAppServerClient` is
896
+ the smallest production boundary for this two-method change. The named-profile
897
+ checker (`scripts/spikes/codex-app-server-real.mjs`) still rejects any
898
+ configuration where `effective.hooks != null`, so the reviewed hook-free
899
+ validation profile above is unchanged and was not re-run with hooks. A
900
+ hook-enabled authenticated run against the hosted backend, and the
901
+ wrapper/absolute-binary-path rejection, remain unproved here.
@@ -157,6 +157,8 @@
157
157
  "item/reasoning/summaryTextDelta",
158
158
  "item/reasoning/summaryPartAdded",
159
159
  "item/reasoning/textDelta",
160
+ "hook/started",
161
+ "hook/completed",
160
162
  "warning",
161
163
  "deprecationNotice",
162
164
  "configWarning",
@@ -469,6 +469,7 @@ class CodexProcess extends Process {
469
469
  this.killPromise = null;
470
470
  this.interruptPromise = null;
471
471
  this.backgroundSettlementPromise = null;
472
+ this.backgroundOwner = null;
472
473
  this.backgroundWatchdog = null;
473
474
  this.backgroundWatchdogDeadlineAt = null;
474
475
  this.backgroundWatchdogPromise = null;
@@ -1059,9 +1060,10 @@ class CodexProcess extends Process {
1059
1060
  turnId: null,
1060
1061
  responseSeen: false,
1061
1062
  startedSeen: false,
1062
- startDeliveryState: 'preparing',
1063
+ startDeliveryState: 'queued',
1063
1064
  startResponseOutcome: null,
1064
1065
  startCancellationRequested: false,
1066
+ startPreparationDisposition: makeDeferred(),
1065
1067
  startDisposition: makeDeferred(),
1066
1068
  terminal: null,
1067
1069
  terminalDeferred: makeDeferred(),
@@ -1134,6 +1136,7 @@ class CodexProcess extends Process {
1134
1136
  }
1135
1137
  this.current = pending;
1136
1138
  this.inFlight = true;
1139
+ pending.startDeliveryState = 'attesting';
1137
1140
  pending.startedAt = Date.now();
1138
1141
  pending.deadlineAt = pending.startedAt + pending.maxTurnMs;
1139
1142
  this.state = 'StartingTurn';
@@ -1192,6 +1195,8 @@ class CodexProcess extends Process {
1192
1195
  }
1193
1196
  this._assertLifecycle(lifecycle);
1194
1197
  };
1198
+ assertTurnStartAdmission();
1199
+ pending.startDeliveryState = 'preparing';
1195
1200
  const result = await this._mutation('turn/start', params, {
1196
1201
  source: pending.context?.sourceMsgId ?? null,
1197
1202
  clientUserMessageId: pending.clientUserMessageId,
@@ -1203,6 +1208,9 @@ class CodexProcess extends Process {
1203
1208
  pending.startResponseOutcome = outcome;
1204
1209
  }
1205
1210
  },
1211
+ onPreparationDisposition: (disposition) => {
1212
+ pending.startPreparationDisposition.resolve(disposition);
1213
+ },
1206
1214
  assertCanWrite: assertTurnStartAdmission,
1207
1215
  assertCanCommit: assertTurnStartAdmission,
1208
1216
  });
@@ -1324,15 +1332,50 @@ class CodexProcess extends Process {
1324
1332
  return remaining;
1325
1333
  }
1326
1334
 
1335
+ _resolveStartAsNotStarted(pending) {
1336
+ pending.startDeliveryState = 'definitely-not-sent';
1337
+ pending.startPreparationDisposition.resolve({ kind: 'not-started' });
1338
+ pending.startDisposition.resolve({ kind: 'not-started' });
1339
+ }
1340
+
1327
1341
  _resolveStartDispositionFromError(pending, error) {
1328
1342
  if (pending.startDeliveryState === 'accepted') return;
1329
1343
  const durability = this._durabilityFailure(error);
1344
+ if (
1345
+ pending.startDeliveryState === 'queued'
1346
+ || pending.startDeliveryState === 'attesting'
1347
+ ) {
1348
+ this._resolveStartAsNotStarted(pending);
1349
+ return;
1350
+ }
1351
+ if (pending.startDeliveryState === 'checkpoint-not-committed') {
1352
+ const disposition = {
1353
+ kind: 'checkpoint-not-committed',
1354
+ cause: durability ?? error,
1355
+ };
1356
+ pending.startDisposition.resolve(disposition);
1357
+ return;
1358
+ }
1359
+ if (pending.startDeliveryState === 'checkpoint-unknown') {
1360
+ const disposition = {
1361
+ kind: 'checkpoint-unknown',
1362
+ cause: durability ?? error,
1363
+ };
1364
+ pending.startDisposition.resolve(disposition);
1365
+ return;
1366
+ }
1330
1367
  if (
1331
1368
  error?.code === 'CODEX_RPC_NOT_SENT'
1332
1369
  || durability?.deliveryState === 'not-sent'
1333
1370
  ) {
1334
- pending.startDeliveryState = 'definitely-not-sent';
1335
- pending.startDisposition.resolve({ kind: 'definitely-not-sent' });
1371
+ if (
1372
+ pending.startDeliveryState === 'prepared'
1373
+ || pending.startDeliveryState === 'write-checkpointing'
1374
+ ) {
1375
+ pending.startDisposition.resolve({ kind: 'checkpoint-committed' });
1376
+ return;
1377
+ }
1378
+ this._resolveStartAsNotStarted(pending);
1336
1379
  return;
1337
1380
  }
1338
1381
  if (
@@ -1346,8 +1389,67 @@ class CodexProcess extends Process {
1346
1389
  pending.startDisposition.resolve({ kind: 'outcome-unknown' });
1347
1390
  return;
1348
1391
  }
1349
- pending.startDeliveryState = 'definitely-not-sent';
1350
- pending.startDisposition.resolve({ kind: 'definitely-not-sent' });
1392
+ this._resolveStartAsNotStarted(pending);
1393
+ }
1394
+
1395
+ async _resolveInterruptStartDisposition(
1396
+ pending,
1397
+ controlDeadline,
1398
+ lifecycle,
1399
+ ) {
1400
+ if (
1401
+ pending.startDeliveryState === 'queued'
1402
+ || pending.startDeliveryState === 'attesting'
1403
+ || pending.startDeliveryState === 'definitely-not-sent'
1404
+ ) {
1405
+ return { kind: 'not-started' };
1406
+ }
1407
+ const waitMs = Math.max(
1408
+ 1,
1409
+ Math.min(this.turnStartTimeoutMs, controlDeadline - Date.now()),
1410
+ );
1411
+ if (
1412
+ pending.startDeliveryState === 'preparing'
1413
+ || pending.startDeliveryState === 'checkpoint-not-committed'
1414
+ || pending.startDeliveryState === 'checkpoint-unknown'
1415
+ ) {
1416
+ try {
1417
+ return await timeout(
1418
+ pending.startPreparationDisposition.promise,
1419
+ waitMs,
1420
+ 'Codex turn preparation disposition was not observed before interruption',
1421
+ 'CODEX_TURN_START_TIMEOUT',
1422
+ );
1423
+ } catch (error) {
1424
+ return { kind: 'checkpoint-unknown', cause: error };
1425
+ }
1426
+ }
1427
+ if (pending.startDeliveryState === 'prepared') {
1428
+ return { kind: 'checkpoint-committed' };
1429
+ }
1430
+ if (
1431
+ pending.startDeliveryState === 'write-checkpointing'
1432
+ || pending.startDeliveryState === 'write-attempted'
1433
+ || pending.startDeliveryState === 'response-observed'
1434
+ || pending.startDeliveryState === 'outcome-unknown'
1435
+ ) {
1436
+ try {
1437
+ const disposition = await timeout(
1438
+ pending.startDisposition.promise,
1439
+ waitMs,
1440
+ 'Codex turn start disposition was not observed before interruption',
1441
+ 'CODEX_TURN_START_TIMEOUT',
1442
+ );
1443
+ this._assertLifecycle(lifecycle);
1444
+ return disposition;
1445
+ } catch (error) {
1446
+ return { kind: 'checkpoint-unknown', cause: error };
1447
+ }
1448
+ }
1449
+ if (pending.startDeliveryState === 'accepted') {
1450
+ return { kind: 'accepted', turnId: pending.turnId };
1451
+ }
1452
+ return { kind: pending.startDeliveryState };
1351
1453
  }
1352
1454
 
1353
1455
  async _classifyTurnFailure(error, pending) {
@@ -1374,7 +1476,7 @@ class CodexProcess extends Process {
1374
1476
  && pending.responseSeen
1375
1477
  ) {
1376
1478
  try {
1377
- await this.interrupt();
1479
+ await this.interrupt('timeout');
1378
1480
  } catch (interruptError) {
1379
1481
  if (this.state !== 'ContainmentFailed') {
1380
1482
  await this._enterContainment(
@@ -1666,13 +1768,14 @@ class CodexProcess extends Process {
1666
1768
  }
1667
1769
  }
1668
1770
 
1669
- async interrupt() {
1771
+ async interrupt(reason = 'interrupt') {
1670
1772
  if (this.interruptPromise) return this.interruptPromise;
1671
- this.interruptPromise = this._interrupt();
1773
+ const interruptionReason = boundedOpaqueId(reason, 'interruption reason');
1774
+ this.interruptPromise = this._interrupt(interruptionReason);
1672
1775
  return this.interruptPromise;
1673
1776
  }
1674
1777
 
1675
- async _interrupt(controlDeadlineOverride = null) {
1778
+ async _interrupt(interruptionReason, controlDeadlineOverride = null) {
1676
1779
  if (this.closed) return false;
1677
1780
  if (this.state === 'ContainmentFailed') {
1678
1781
  throw processError(
@@ -1694,23 +1797,35 @@ class CodexProcess extends Process {
1694
1797
  this._clearBackgroundWatchdog();
1695
1798
  const backgroundSettlement = this.backgroundSettlementPromise;
1696
1799
  const pending = this.current;
1800
+ let backgroundOwnership = null;
1801
+ if (
1802
+ priorState === 'BackgroundWorking'
1803
+ || priorState === 'BackgroundSettling'
1804
+ ) {
1805
+ try {
1806
+ backgroundOwnership = this._requireBackgroundOwner();
1807
+ } catch (error) {
1808
+ await this._enterContainment(
1809
+ 'background-ownership-unknown',
1810
+ error,
1811
+ );
1812
+ throw error;
1813
+ }
1814
+ }
1697
1815
  const controlDeadline = controlDeadlineOverride
1698
1816
  ?? pending?.deadlineAt
1699
- ?? this.lastTerminal?.deadlineAt
1817
+ ?? backgroundOwnership?.owner.deadlineAt
1700
1818
  ?? (Date.now() + this.interruptTimeoutMs + this.cleanupTimeoutMs);
1701
1819
  let turnId = this.activeTurnId
1702
1820
  ?? pending?.turnId
1703
- ?? (
1704
- (
1705
- priorState === 'BackgroundWorking'
1706
- || priorState === 'BackgroundSettling'
1707
- )
1708
- ? this.lastTerminal?.turnId
1709
- : null
1710
- );
1821
+ ?? backgroundOwnership?.owner.turnId
1822
+ ?? null;
1823
+ if (pending && priorState === 'StartingTurn') {
1824
+ pending.startCancellationRequested = true;
1825
+ }
1711
1826
  this.state = 'Quiescing';
1712
1827
  const lifecycle = this._captureLifecycle();
1713
- this._drainWaiting('INTERRUPTED');
1828
+ this._drainWaiting('INTERRUPTED', interruptionReason);
1714
1829
  await this.steerChain;
1715
1830
  this._assertLifecycle(lifecycle);
1716
1831
  await this._flushPendingCancellations();
@@ -1721,50 +1836,31 @@ class CodexProcess extends Process {
1721
1836
  }
1722
1837
  let interruptEventEmitted = false;
1723
1838
  if (pending && priorState === 'StartingTurn') {
1724
- pending.startCancellationRequested = true;
1725
- let disposition;
1726
- if (
1727
- pending.startDeliveryState === 'preparing'
1728
- || pending.startDeliveryState === 'prepared'
1729
- ) {
1730
- disposition = { kind: 'definitely-not-sent' };
1731
- } else if (
1732
- pending.startDeliveryState === 'write-checkpointing'
1733
- ||
1734
- pending.startDeliveryState === 'write-attempted'
1735
- || pending.startDeliveryState === 'response-observed'
1736
- ) {
1737
- try {
1738
- disposition = await timeout(
1739
- pending.startDisposition.promise,
1740
- Math.max(
1741
- 1,
1742
- Math.min(
1743
- this.turnStartTimeoutMs,
1744
- controlDeadline - Date.now(),
1745
- ),
1746
- ),
1747
- 'Codex turn start disposition was not observed before interruption',
1748
- 'CODEX_TURN_START_TIMEOUT',
1749
- );
1750
- this._assertLifecycle(lifecycle);
1751
- } catch (error) {
1752
- disposition = { kind: 'outcome-unknown', cause: error };
1753
- }
1754
- } else if (pending.startDeliveryState === 'accepted') {
1755
- disposition = { kind: 'accepted', turnId: pending.turnId };
1756
- } else {
1757
- disposition = { kind: pending.startDeliveryState };
1758
- }
1839
+ const disposition = await this._resolveInterruptStartDisposition(
1840
+ pending,
1841
+ controlDeadline,
1842
+ lifecycle,
1843
+ );
1759
1844
  if (disposition.kind === 'accepted') {
1760
1845
  turnId = disposition.turnId ?? pending.turnId;
1761
- } else if (disposition.kind === 'definitely-not-sent') {
1846
+ } else if (disposition.kind === 'not-started') {
1847
+ turnId = null;
1848
+ const cancelled = processError(
1849
+ 'Codex turn start was interrupted before preparation',
1850
+ 'INTERRUPTED',
1851
+ );
1852
+ pending.cancelled = true;
1853
+ this._rejectPending(pending, cancelled);
1854
+ this._finishPending(pending);
1855
+ } else if (disposition.kind === 'checkpoint-committed') {
1762
1856
  turnId = null;
1763
1857
  try {
1764
1858
  await this._checkpoint('active-start-cancelled', {
1765
1859
  ...this._turnDetail(pending),
1860
+ method: 'turn/start',
1766
1861
  attemptId: pending.attemptId,
1767
1862
  deliveryState: 'definitely-not-sent',
1863
+ reason: interruptionReason,
1768
1864
  });
1769
1865
  this._assertLifecycle(lifecycle);
1770
1866
  } catch (error) {
@@ -1783,6 +1879,17 @@ class CodexProcess extends Process {
1783
1879
  pending.cancelled = true;
1784
1880
  this._rejectPending(pending, cancelled);
1785
1881
  this._finishPending(pending);
1882
+ } else if (disposition.kind === 'checkpoint-not-committed') {
1883
+ const cause = disposition.cause ?? processError(
1884
+ 'Codex turn preparation was rejected without a committed attempt',
1885
+ 'CODEX_DURABILITY_FAILED',
1886
+ );
1887
+ this._blockDurability(cause, pending);
1888
+ throw processError(
1889
+ 'Codex turn preparation was not durably committed',
1890
+ 'CODEX_DURABILITY_FAILED',
1891
+ { cause },
1892
+ );
1786
1893
  } else {
1787
1894
  const error = disposition.cause ?? processError(
1788
1895
  'Codex turn start delivery outcome is unknown',
@@ -1802,6 +1909,7 @@ class CodexProcess extends Process {
1802
1909
  const reuseBackgroundCleanup = (
1803
1910
  cleanupProof?.turnId != null
1804
1911
  && cleanupProof.turnId === turnId
1912
+ && cleanupProof.deadlineAt === backgroundOwnership?.owner.deadlineAt
1805
1913
  );
1806
1914
  let terminal = pending?.terminal
1807
1915
  ?? (
@@ -1896,6 +2004,7 @@ class CodexProcess extends Process {
1896
2004
  turnId,
1897
2005
  });
1898
2006
  }
2007
+ this.backgroundOwner = null;
1899
2008
  this.state = 'Stopped';
1900
2009
  this.inFlight = false;
1901
2010
  this.emit('codex-settled', this._lifecyclePayload('stopped', {
@@ -1958,6 +2067,8 @@ class CodexProcess extends Process {
1958
2067
  || this.state === 'FailedAmbiguous'
1959
2068
  || this.state === 'DurabilityBlocked'
1960
2069
  ) return;
2070
+ if (this.state !== 'Settling' || this.current !== pending) return;
2071
+ const probeState = this.state;
1961
2072
  const page = await this.client.request(
1962
2073
  'thread/backgroundTerminals/list',
1963
2074
  { threadId: this.providerSessionId, limit: 100 },
@@ -1966,9 +2077,11 @@ class CodexProcess extends Process {
1966
2077
  },
1967
2078
  );
1968
2079
  this._assertLifecycle(lifecycle);
2080
+ if (this.state !== probeState || this.current !== pending) return;
1969
2081
  if (page.count > 0 || page.nextCursor != null) {
2082
+ this._bindBackgroundOwnerFromPending(pending);
1970
2083
  this._activateBackgroundOwnership();
1971
- this._armBackgroundWatchdog(pending.deadlineAt);
2084
+ this._armBackgroundWatchdog();
1972
2085
  if (this.threadStatusType === 'idle') {
1973
2086
  this._scheduleBackgroundSettlement();
1974
2087
  }
@@ -1976,12 +2089,130 @@ class CodexProcess extends Process {
1976
2089
  }
1977
2090
 
1978
2091
  _activateBackgroundOwnership() {
2092
+ this._requireBackgroundOwner();
1979
2093
  if (!this.hasActiveBackgroundWork()) {
1980
2094
  this._advanceActivityEpoch();
1981
2095
  this.state = 'BackgroundWorking';
1982
2096
  }
1983
2097
  }
1984
2098
 
2099
+ _backgroundOwnershipError(message) {
2100
+ return processError(message, 'CODEX_BACKGROUND_OWNERSHIP_UNKNOWN');
2101
+ }
2102
+
2103
+ _ownerFromTerminal(terminal, { requireLive = false } = {}) {
2104
+ if (
2105
+ !terminal
2106
+ || !Number.isSafeInteger(terminal.deadlineAt)
2107
+ || terminal.deadlineAt < 1
2108
+ || !['completed', 'interrupted', 'failed'].includes(terminal.status)
2109
+ || (requireLive && terminal.deadlineAt <= Date.now())
2110
+ ) {
2111
+ throw this._backgroundOwnershipError(
2112
+ 'Codex background work had no exact live terminal owner',
2113
+ );
2114
+ }
2115
+ let turnId;
2116
+ try {
2117
+ turnId = boundedOpaqueId(terminal.turnId, 'background owner turnId');
2118
+ } catch {
2119
+ throw this._backgroundOwnershipError(
2120
+ 'Codex background work had no exact live terminal owner',
2121
+ );
2122
+ }
2123
+ return Object.freeze({
2124
+ turnId,
2125
+ deadlineAt: terminal.deadlineAt,
2126
+ });
2127
+ }
2128
+
2129
+ _bindBackgroundOwner(terminal, options = {}) {
2130
+ const owner = this._ownerFromTerminal(terminal, options);
2131
+ if (this.backgroundOwner) {
2132
+ if (
2133
+ !Object.isFrozen(this.backgroundOwner)
2134
+ || this.backgroundOwner.turnId !== owner.turnId
2135
+ || this.backgroundOwner.deadlineAt !== owner.deadlineAt
2136
+ ) {
2137
+ throw this._backgroundOwnershipError(
2138
+ 'Codex background owner changed before cleanup',
2139
+ );
2140
+ }
2141
+ return this.backgroundOwner;
2142
+ }
2143
+ this.backgroundCleanupProof = null;
2144
+ this.backgroundOwner = owner;
2145
+ return owner;
2146
+ }
2147
+
2148
+ _bindBackgroundOwnerFromPending(pending) {
2149
+ const terminal = pending?.terminal;
2150
+ if (
2151
+ pending !== this.current
2152
+ || !terminal
2153
+ || terminal !== this.lastTerminal
2154
+ || terminal.turnId !== pending.turnId
2155
+ || terminal.deadlineAt !== pending.deadlineAt
2156
+ ) {
2157
+ throw this._backgroundOwnershipError(
2158
+ 'Codex background registry had no exact pending terminal owner',
2159
+ );
2160
+ }
2161
+ return this._bindBackgroundOwner(terminal);
2162
+ }
2163
+
2164
+ _captureBackgroundPromotionCandidate() {
2165
+ const terminal = this.lastTerminal;
2166
+ if (!terminal) return null;
2167
+ return Object.freeze({
2168
+ terminal,
2169
+ turnId: terminal.turnId,
2170
+ status: terminal.status,
2171
+ deadlineAt: terminal.deadlineAt,
2172
+ });
2173
+ }
2174
+
2175
+ _promoteBackgroundCandidateToOwner(admission) {
2176
+ const candidate = admission?.candidate;
2177
+ const terminal = this.lastTerminal;
2178
+ if (
2179
+ !admission
2180
+ || this.activityEpoch !== admission.activityEpoch
2181
+ || this.state !== admission.state
2182
+ || this.current !== admission.current
2183
+ || !candidate
2184
+ || candidate.terminal !== terminal
2185
+ || candidate.turnId !== terminal?.turnId
2186
+ || candidate.status !== terminal?.status
2187
+ || candidate.deadlineAt !== terminal?.deadlineAt
2188
+ ) {
2189
+ throw this._backgroundOwnershipError(
2190
+ 'Codex background status candidate changed before ownership',
2191
+ );
2192
+ }
2193
+ return this._bindBackgroundOwner(terminal, {
2194
+ requireLive: true,
2195
+ });
2196
+ }
2197
+
2198
+ _requireBackgroundOwner() {
2199
+ const owner = this.backgroundOwner;
2200
+ const terminal = this.lastTerminal;
2201
+ if (
2202
+ !owner
2203
+ || !Object.isFrozen(owner)
2204
+ || !terminal
2205
+ || owner.turnId !== terminal.turnId
2206
+ || owner.deadlineAt !== terminal.deadlineAt
2207
+ ) {
2208
+ throw this._backgroundOwnershipError(
2209
+ 'Codex background work had missing or mismatched ownership',
2210
+ );
2211
+ }
2212
+ this._ownerFromTerminal(terminal);
2213
+ return { owner, terminal };
2214
+ }
2215
+
1985
2216
  _qualificationFenceError() {
1986
2217
  return processError(
1987
2218
  'Codex clean-restart qualification fence changed',
@@ -2164,15 +2395,35 @@ class CodexProcess extends Process {
2164
2395
  try {
2165
2396
  await this._checkpoint('request-prepared', prepared);
2166
2397
  } catch (error) {
2398
+ const dispositionAware = (
2399
+ typeof detail.onPreparationDisposition === 'function'
2400
+ );
2401
+ const notCommitted = (
2402
+ dispositionAware
2403
+ && error?.checkpointDisposition === 'not-committed'
2404
+ );
2167
2405
  const durability = processError(
2168
2406
  `Codex ${method} prepared checkpoint failed`,
2169
2407
  'CODEX_DURABILITY_FAILED',
2170
2408
  { cause: error },
2171
2409
  );
2172
- durability.deliveryState = 'not-sent';
2410
+ durability.deliveryState = (
2411
+ dispositionAware && !notCommitted ? 'ambiguous' : 'not-sent'
2412
+ );
2413
+ if (dispositionAware) {
2414
+ const disposition = {
2415
+ kind: notCommitted
2416
+ ? 'checkpoint-not-committed'
2417
+ : 'checkpoint-unknown',
2418
+ cause: durability,
2419
+ };
2420
+ detail.onDeliveryState?.(disposition.kind);
2421
+ detail.onPreparationDisposition(disposition);
2422
+ }
2173
2423
  throw durability;
2174
2424
  }
2175
2425
  detail.onDeliveryState?.('prepared');
2426
+ detail.onPreparationDisposition?.({ kind: 'checkpoint-committed' });
2176
2427
  detail.assertCanWrite?.();
2177
2428
  return this.client.request(method, params, {
2178
2429
  timeoutMs: detail.timeoutMs,
@@ -2301,6 +2552,9 @@ class CodexProcess extends Process {
2301
2552
  { cause: error },
2302
2553
  );
2303
2554
  durability.deliveryState = 'ambiguous';
2555
+ if (error?.checkpointDisposition === 'not-committed') {
2556
+ durability.checkpointDisposition = 'not-committed';
2557
+ }
2304
2558
  throw durability;
2305
2559
  }
2306
2560
  fence?.assertActive?.();
@@ -2397,15 +2651,38 @@ class CodexProcess extends Process {
2397
2651
  && !this.current
2398
2652
  && this.state === 'Idle'
2399
2653
  );
2654
+ const backgroundCandidate = activateBackground
2655
+ ? this._captureBackgroundPromotionCandidate()
2656
+ : null;
2400
2657
  if (activateBackground) this._advanceActivityEpoch();
2658
+ const backgroundAdmission = activateBackground
2659
+ ? Object.freeze({
2660
+ candidate: backgroundCandidate,
2661
+ activityEpoch: this.activityEpoch,
2662
+ state: this.state,
2663
+ current: this.current,
2664
+ })
2665
+ : null;
2401
2666
  await this._checkpoint('thread-status-changed', {
2402
2667
  threadId: ownedThreadId,
2403
2668
  statusType,
2404
2669
  }, fence);
2405
2670
  fence.assertActive?.();
2406
2671
  this.threadStatusType = statusType;
2407
- if (activateBackground && !this.current && this.state === 'Idle') {
2672
+ if (activateBackground) {
2673
+ try {
2674
+ this._promoteBackgroundCandidateToOwner(backgroundAdmission);
2675
+ } catch (error) {
2676
+ await this._enterContainment(
2677
+ 'background-ownership-unknown',
2678
+ error,
2679
+ null,
2680
+ fence,
2681
+ );
2682
+ return;
2683
+ }
2408
2684
  this.state = 'BackgroundWorking';
2685
+ this._armBackgroundWatchdog();
2409
2686
  } else if (
2410
2687
  statusType === 'idle'
2411
2688
  && this.state === 'BackgroundWorking'
@@ -2707,19 +2984,13 @@ class CodexProcess extends Process {
2707
2984
 
2708
2985
  async _settleNaturalBackgroundWork() {
2709
2986
  const lifecycle = this._captureLifecycle();
2710
- const terminal = this.lastTerminal;
2711
- const deadline = terminal?.deadlineAt ?? Date.now();
2712
2987
  try {
2713
2988
  this._assertLifecycle(lifecycle);
2714
- if (!terminal) {
2715
- throw processError(
2716
- 'Codex background work had no owned terminal turn',
2717
- 'CODEX_BACKGROUND_OWNERSHIP_UNKNOWN',
2718
- );
2719
- }
2989
+ const { owner, terminal } = this._requireBackgroundOwner();
2990
+ const deadline = owner.deadlineAt;
2720
2991
  await this._checkpoint('background-terminal-reconciled', {
2721
2992
  threadId: this.providerSessionId,
2722
- turnId: terminal.turnId,
2993
+ turnId: owner.turnId,
2723
2994
  terminalStatus: terminal.status,
2724
2995
  });
2725
2996
  this._assertLifecycle(lifecycle);
@@ -2727,35 +2998,36 @@ class CodexProcess extends Process {
2727
2998
  threadId: this.providerSessionId,
2728
2999
  }, {
2729
3000
  source: null,
2730
- turnId: terminal.turnId,
3001
+ turnId: owner.turnId,
2731
3002
  timeoutMs: Math.max(1, deadline - Date.now()),
2732
3003
  });
2733
3004
  this._assertLifecycle(lifecycle);
2734
3005
  await this._checkpoint('background-clean-accepted', {
2735
3006
  threadId: this.providerSessionId,
2736
- turnId: terminal.turnId,
3007
+ turnId: owner.turnId,
2737
3008
  });
2738
3009
  this._assertLifecycle(lifecycle);
2739
3010
  await this._waitForFreshEmptyRegistry(deadline, lifecycle);
2740
3011
  this._assertLifecycle(lifecycle);
2741
3012
  await this._checkpoint('background-empty-registry-observed', {
2742
3013
  threadId: this.providerSessionId,
2743
- turnId: terminal.turnId,
3014
+ turnId: owner.turnId,
2744
3015
  });
2745
3016
  this._assertLifecycle(lifecycle);
2746
3017
  this.backgroundCleanupProof = Object.freeze({
2747
- turnId: terminal.turnId,
3018
+ turnId: owner.turnId,
2748
3019
  terminalStatus: terminal.status,
2749
3020
  deadlineAt: deadline,
2750
3021
  });
2751
3022
  this._clearBackgroundWatchdog();
3023
+ this.backgroundOwner = null;
2752
3024
  if (this.state === 'Quiescing') return this.backgroundCleanupProof;
2753
3025
  this.state = 'Idle';
2754
3026
  this.inFlight = false;
2755
3027
  this.emit('codex-settled', this._lifecyclePayload(
2756
3028
  'background-settled',
2757
3029
  {
2758
- turnId: terminal.turnId,
3030
+ turnId: owner.turnId,
2759
3031
  terminalStatus: terminal.status,
2760
3032
  trackedTerminalCleanupAccepted: true,
2761
3033
  freshRegistryObservedEmpty: true,
@@ -2790,8 +3062,12 @@ class CodexProcess extends Process {
2790
3062
  this.backgroundSettlementPromise.catch(() => {});
2791
3063
  }
2792
3064
 
2793
- _armBackgroundWatchdog(deadlineAt) {
2794
- if (!Number.isFinite(deadlineAt)) return;
3065
+ _armBackgroundWatchdog() {
3066
+ const { owner } = this._requireBackgroundOwner();
3067
+ const { deadlineAt } = owner;
3068
+ const retirementReserveMs = (
3069
+ this.interruptTimeoutMs + this.cleanupTimeoutMs
3070
+ );
2795
3071
  if (
2796
3072
  this.backgroundWatchdog
2797
3073
  && this.backgroundWatchdogDeadlineAt === deadlineAt
@@ -2805,9 +3081,22 @@ class CodexProcess extends Process {
2805
3081
  this.state !== 'BackgroundWorking'
2806
3082
  && this.state !== 'BackgroundSettling'
2807
3083
  ) return;
3084
+ let currentOwner;
3085
+ try {
3086
+ currentOwner = this._requireBackgroundOwner().owner;
3087
+ } catch (error) {
3088
+ this.backgroundWatchdogPromise = this._enterContainment(
3089
+ 'background-ownership-unknown',
3090
+ error,
3091
+ ).finally(() => {
3092
+ this.backgroundWatchdogPromise = null;
3093
+ });
3094
+ return;
3095
+ }
2808
3096
  if (!this.interruptPromise) {
2809
3097
  this.interruptPromise = this._interrupt(
2810
- Date.now() + this.interruptTimeoutMs + this.cleanupTimeoutMs,
3098
+ 'timeout',
3099
+ currentOwner.deadlineAt,
2811
3100
  );
2812
3101
  }
2813
3102
  this.backgroundWatchdogPromise = this.interruptPromise
@@ -2825,7 +3114,7 @@ class CodexProcess extends Process {
2825
3114
  .finally(() => {
2826
3115
  this.backgroundWatchdogPromise = null;
2827
3116
  });
2828
- }, Math.max(1, deadlineAt - Date.now()));
3117
+ }, Math.max(1, deadlineAt - retirementReserveMs - Date.now()));
2829
3118
  this.backgroundWatchdog.unref?.();
2830
3119
  }
2831
3120
 
@@ -3132,11 +3421,11 @@ class CodexProcess extends Process {
3132
3421
  this._settlePending(pending, 'reject', error);
3133
3422
  }
3134
3423
 
3135
- _drainWaiting(code) {
3424
+ _drainWaiting(code, reason = 'interrupt') {
3136
3425
  let count = 0;
3137
3426
  for (const pending of [...this.pendingQueue]) {
3138
3427
  if (pending === this.current) continue;
3139
- this._reserveCancellation(pending, code);
3428
+ this._reserveCancellation(pending, code, reason);
3140
3429
  count += 1;
3141
3430
  }
3142
3431
  return count;
@@ -3147,16 +3436,16 @@ class CodexProcess extends Process {
3147
3436
  return this._drainAll(code);
3148
3437
  }
3149
3438
 
3150
- _drainAll(code) {
3439
+ _drainAll(code, reason = 'interrupt') {
3151
3440
  let count = 0;
3152
3441
  for (const pending of [...this.pendingQueue]) {
3153
- this._reserveCancellation(pending, code);
3442
+ this._reserveCancellation(pending, code, reason);
3154
3443
  count += 1;
3155
3444
  }
3156
3445
  return count;
3157
3446
  }
3158
3447
 
3159
- _reserveCancellation(pending, code) {
3448
+ _reserveCancellation(pending, code, reason) {
3160
3449
  const index = this.pendingQueue.indexOf(pending);
3161
3450
  if (index !== -1) this.pendingQueue.splice(index, 1);
3162
3451
  try {
@@ -3168,6 +3457,7 @@ class CodexProcess extends Process {
3168
3457
  this.pendingCancellations.push({
3169
3458
  pending,
3170
3459
  code,
3460
+ reason,
3171
3461
  attemptId: pending?.attemptId
3172
3462
  ?? `${this.generationId}:cancel:${this.cancellationSequence}`,
3173
3463
  });
@@ -3182,12 +3472,14 @@ class CodexProcess extends Process {
3182
3472
  const { pending } = cancellation;
3183
3473
  try {
3184
3474
  await this._checkpoint('queued-send-cancelled', {
3475
+ method: 'queued/send',
3185
3476
  threadId: this.providerSessionId,
3186
3477
  turnId: pending.turnId ?? null,
3187
3478
  source: pending.context?.sourceMsgId ?? null,
3188
3479
  clientUserMessageId: pending.clientUserMessageId ?? null,
3189
3480
  attemptId: cancellation.attemptId,
3190
3481
  cancellationCode: cancellation.code,
3482
+ reason: cancellation.reason,
3191
3483
  });
3192
3484
  } catch (error) {
3193
3485
  const durability = processError(
@@ -3311,7 +3603,7 @@ class CodexProcess extends Process {
3311
3603
  || pending.startDeliveryState !== 'accepted'
3312
3604
  || pending.turnId == null
3313
3605
  || pending.turnId !== this.activeTurnId
3314
- || this.pendingQueue.length !== 1
3606
+ || this.pendingQueue.length < 1
3315
3607
  || this.pendingQueue[0] !== pending
3316
3608
  || this.pendingSteerCount !== 0
3317
3609
  || this.pendingCancellations.length !== 0
@@ -3329,6 +3621,29 @@ class CodexProcess extends Process {
3329
3621
  || typeof this.spawnProfileId !== 'string'
3330
3622
  || this.spawnProfileId.length === 0
3331
3623
  ) return null;
3624
+ const seenClientIds = new Set([pending.clientUserMessageId]);
3625
+ const seenAttemptIds = new Set([pending.attemptId]);
3626
+ for (const follower of this.pendingQueue.slice(1)) {
3627
+ const followerSource = follower?.context?.sourceMsgId ?? null;
3628
+ if (
3629
+ !follower
3630
+ || follower === pending
3631
+ || follower.settled
3632
+ || follower.terminal
3633
+ || follower.turnId != null
3634
+ || follower.startedAt != null
3635
+ || follower.startDeliveryState !== 'queued'
3636
+ || followerSource == null
3637
+ || typeof follower.clientUserMessageId !== 'string'
3638
+ || follower.clientUserMessageId.length === 0
3639
+ || typeof follower.attemptId !== 'string'
3640
+ || follower.attemptId.length === 0
3641
+ || seenClientIds.has(follower.clientUserMessageId)
3642
+ || seenAttemptIds.has(follower.attemptId)
3643
+ ) return null;
3644
+ seenClientIds.add(follower.clientUserMessageId);
3645
+ seenAttemptIds.add(follower.attemptId);
3646
+ }
3332
3647
  return Object.freeze({
3333
3648
  runtime: 'codex',
3334
3649
  namespace: 'codex:app-server',
@@ -3362,7 +3677,8 @@ class CodexProcess extends Process {
3362
3677
 
3363
3678
  kill(reason = 'kill') {
3364
3679
  if (this.killPromise) return this.killPromise;
3365
- this.killPromise = this._kill(reason);
3680
+ const interruptionReason = boundedOpaqueId(reason, 'interruption reason');
3681
+ this.killPromise = this._kill(interruptionReason);
3366
3682
  return this.killPromise;
3367
3683
  }
3368
3684
 
@@ -3388,8 +3704,8 @@ class CodexProcess extends Process {
3388
3704
  return;
3389
3705
  }
3390
3706
 
3391
- this._drainWaiting('KILLED');
3392
- if (!this.current) this._drainAll('KILLED');
3707
+ this._drainWaiting('KILLED', reason);
3708
+ if (!this.current) this._drainAll('KILLED', reason);
3393
3709
  await this._flushPendingCancellations();
3394
3710
  this._assertLifecycle(lifecycle);
3395
3711
 
@@ -3402,13 +3718,13 @@ class CodexProcess extends Process {
3402
3718
  || this.state === 'BackgroundWorking'
3403
3719
  || this.state === 'Settling'
3404
3720
  ) {
3405
- await this.interrupt();
3721
+ await this.interrupt(reason);
3406
3722
  this._assertLifecycle(lifecycle);
3407
3723
  } else if (
3408
3724
  this.state !== 'Stopped'
3409
3725
  && this.state !== 'Idle'
3410
3726
  ) {
3411
- await this.interrupt();
3727
+ await this.interrupt(reason);
3412
3728
  this._assertLifecycle(lifecycle);
3413
3729
  }
3414
3730
 
@@ -1409,7 +1409,7 @@ class ProcessManager {
1409
1409
  'CODEX_DAEMON_GENERATION_BUSY',
1410
1410
  );
1411
1411
  }
1412
- await proc.interrupt();
1412
+ await proc.interrupt(reason);
1413
1413
  if (
1414
1414
  proc.state !== 'Stopped'
1415
1415
  || !this._codexLeaseMatches(proc)
@@ -2077,7 +2077,7 @@ class ProcessManager {
2077
2077
  }
2078
2078
  return this._withRetirementIntent(sessionKey, async () => {
2079
2079
  if (this.procs.get(sessionKey) !== proc || proc.closed) return false;
2080
- const interrupted = await proc.interrupt();
2080
+ const interrupted = await proc.interrupt('interrupt');
2081
2081
  if (!interrupted) return false;
2082
2082
  await this._killLocked(sessionKey, 'interrupt');
2083
2083
  return true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.10.17",
3
+ "version": "0.10.19",
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",