@bitkyc08/opencodex 2.100.3 → 2.100.5-preview.20261118.1

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.
Files changed (249) hide show
  1. package/AGENTS_INSTALL.md +23 -1
  2. package/bin/ocx.mjs +8 -1
  3. package/gui/dist/assets/{App-Dnb6VMsP.js → App-BiOGtxDS.js} +21 -20
  4. package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-BwsMejUO.js} +1 -1
  5. package/gui/dist/assets/brand-mark-BY1dgACL.js +1 -0
  6. package/gui/dist/assets/{index-DCdXsMyZ.js → index-CwHSKMdG.js} +46 -13
  7. package/gui/dist/assets/index-DJxM-imn.css +2 -0
  8. package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bds9Hb_7.js} +1 -1
  9. package/gui/dist/classic/assets/{App-DA-scMPq.js → App-CGLOiqQL.js} +20 -19
  10. package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-Da4r2O70.js} +1 -1
  11. package/gui/dist/classic/assets/{index-BqOaGLf5.js → index-CvoKXKL9.js} +46 -13
  12. package/gui/dist/classic/assets/quota-summary-DvqzfCmr.js +1 -0
  13. package/gui/dist/classic/index.html +1 -1
  14. package/gui/dist/index.html +2 -2
  15. package/native/ocx-child/src/cli.rs +5 -3
  16. package/native/ocx-child/src/codex_home.rs +1 -0
  17. package/native/ocx-child/src/link_ws.rs +24 -19
  18. package/native/ocx-child/src/link_ws_frame.rs +136 -50
  19. package/package.json +3 -3
  20. package/src/adapters/anthropic/per-message-effort.ts +296 -0
  21. package/src/adapters/anthropic-input-schema.ts +270 -0
  22. package/src/adapters/anthropic.ts +4 -63
  23. package/src/adapters/claude-cli/adapter.ts +1 -0
  24. package/src/adapters/command-code-tool-text.ts +9 -1
  25. package/src/adapters/command-code.ts +18 -2
  26. package/src/adapters/devin/cloud-direct/chat.ts +95 -14
  27. package/src/adapters/devin/live-models.ts +11 -1
  28. package/src/adapters/google-errors.ts +14 -2
  29. package/src/adapters/kiro/reasoning.ts +3 -0
  30. package/src/adapters/kiro-tools.ts +14 -9
  31. package/src/adapters/openai-responses/passthrough.ts +3 -1
  32. package/src/adapters/openai-responses/request-strips.ts +1 -0
  33. package/src/adapters/qoder/adapter.ts +9 -1
  34. package/src/adapters/tool-catalog-nudge.ts +1 -1
  35. package/src/adapters/zed.ts +4 -2
  36. package/src/claude/chat-tool-dispatch.ts +4 -1
  37. package/src/claude/desktop-remote-store.ts +60 -10
  38. package/src/cli/account-api.ts +4 -0
  39. package/src/cli/account-auth.ts +30 -2
  40. package/src/cli/account-extended.ts +33 -2
  41. package/src/cli/capabilities-access-remote.ts +3 -3
  42. package/src/cli/capabilities-accounts.ts +3 -3
  43. package/src/cli/capabilities-base.ts +11 -6
  44. package/src/cli/capabilities-observe-system.ts +2 -2
  45. package/src/cli/claude.ts +3 -3
  46. package/src/cli/disconnect-runtime.ts +16 -6
  47. package/src/cli/dispatch.ts +7 -1
  48. package/src/cli/index.ts +2 -2
  49. package/src/cli/link-apply-restart.ts +4 -2
  50. package/src/cli/link-routes.ts +4 -1
  51. package/src/cli/link.ts +5 -4
  52. package/src/cli/logout-command.ts +23 -4
  53. package/src/cli/preflight-exemptions.ts +3 -0
  54. package/src/cli/provider.ts +3 -2
  55. package/src/cli/registry.ts +5 -2
  56. package/src/cli/resolve.ts +23 -8
  57. package/src/cli/restart-failure.ts +11 -1
  58. package/src/cli/runtime-api.ts +4 -0
  59. package/src/cli/status.ts +4 -1
  60. package/src/cli/system-command.ts +1 -1
  61. package/src/cli/system-restart-client.ts +9 -3
  62. package/src/cli/system-settings-parity.ts +2 -1
  63. package/src/client/connect.ts +73 -11
  64. package/src/client/desktop-refusal.ts +38 -0
  65. package/src/client/lifecycle-lock.ts +29 -4
  66. package/src/client/runtime-restart.ts +27 -15
  67. package/src/client/runtime.ts +4 -2
  68. package/src/client/state.ts +14 -0
  69. package/src/clients/config-export.ts +12 -7
  70. package/src/codex/account-lifecycle.ts +3 -1
  71. package/src/codex/account-pause.ts +4 -0
  72. package/src/codex/account-runtime-state.ts +4 -0
  73. package/src/codex/auth-api/main-account-probe.ts +3 -1
  74. package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
  75. package/src/codex/auth-context.ts +40 -2
  76. package/src/codex/catalog/build-entries.ts +10 -0
  77. package/src/codex/catalog/derive-entry.ts +7 -0
  78. package/src/codex/catalog/metadata.ts +8 -0
  79. package/src/codex/catalog/native-models.ts +16 -6
  80. package/src/codex/catalog/pinned-models.ts +1 -0
  81. package/src/codex/catalog/provider-models.ts +5 -5
  82. package/src/codex/catalog/reserve-warn.ts +7 -5
  83. package/src/codex/catalog/reserve.ts +4 -3
  84. package/src/codex/catalog/retained-sync.ts +2 -0
  85. package/src/codex/catalog/routed-defaults.ts +35 -0
  86. package/src/codex/catalog-auto-refresh.ts +13 -2
  87. package/src/codex/config-drift-heal.ts +40 -12
  88. package/src/codex/config-write-lock.ts +39 -1
  89. package/src/codex/convergence.ts +2 -0
  90. package/src/codex/data/roster-pinned-models.json +346 -1
  91. package/src/codex/inject/config-write-section.ts +39 -1
  92. package/src/codex/inject/plan.ts +10 -8
  93. package/src/codex/inject/remove.ts +21 -19
  94. package/src/codex/inject/restore.ts +5 -1
  95. package/src/codex/inject-coordination.ts +58 -7
  96. package/src/codex/inject.ts +10 -12
  97. package/src/codex/journal-config-restore.ts +42 -0
  98. package/src/codex/journal.ts +62 -8
  99. package/src/codex/loopback-target.ts +22 -8
  100. package/src/codex/main-account.ts +94 -30
  101. package/src/codex/native-main-auth-file.ts +14 -0
  102. package/src/codex/native-main-credentials.ts +276 -0
  103. package/src/codex/native-main-owner.ts +3 -0
  104. package/src/codex/native-main-refresh-mode.ts +14 -1
  105. package/src/codex/quota.ts +63 -14
  106. package/src/combos/failover.ts +195 -1
  107. package/src/combos/index.ts +5 -0
  108. package/src/combos/resolve.ts +115 -19
  109. package/src/config/diagnostics.ts +3 -0
  110. package/src/config/live-reconcile.ts +6 -3
  111. package/src/config/load-degrade.ts +2 -0
  112. package/src/config/persisted-mutation.ts +2 -2
  113. package/src/config/persisted-projections.ts +18 -0
  114. package/src/config/process-state.ts +4 -3
  115. package/src/config/reserve-capability.ts +96 -0
  116. package/src/config/schema/config-schema.ts +6 -0
  117. package/src/config/schema/leaf-validators.ts +2 -0
  118. package/src/config/schema/routed-catalog-defaults.ts +49 -0
  119. package/src/config/subagent-models.ts +20 -12
  120. package/src/config.ts +7 -7
  121. package/src/desktop-update/acquire.ts +202 -0
  122. package/src/desktop-update/cli.ts +168 -0
  123. package/src/desktop-update/drain.ts +40 -0
  124. package/src/desktop-update/headless.ts +285 -0
  125. package/src/desktop-update/image.ts +85 -0
  126. package/src/desktop-update/install.ts +53 -0
  127. package/src/desktop-update/msi.ts +72 -0
  128. package/src/desktop-update/release.ts +128 -0
  129. package/src/desktop-update/runtime.ts +155 -0
  130. package/src/desktop-update/staging.ts +118 -0
  131. package/src/desktop-update/trust.ts +45 -0
  132. package/src/generated/compatibility-version.json +327 -195
  133. package/src/generated/model-metadata.ts +3 -3
  134. package/src/images/fulfill-video.ts +3 -3
  135. package/src/images/loop.ts +6 -2
  136. package/src/images/plan.ts +147 -11
  137. package/src/images/types.ts +13 -4
  138. package/src/images/xai-video-client.ts +72 -10
  139. package/src/lib/client-error-body.ts +6 -0
  140. package/src/lib/developer-role-rejection.ts +15 -0
  141. package/src/lib/gcp-adc.ts +48 -4
  142. package/src/lib/offline-resend.ts +150 -0
  143. package/src/lib/paced-stream.ts +3 -3
  144. package/src/lib/provider-outbound.ts +17 -6
  145. package/src/lib/request-failure-model.ts +2 -0
  146. package/src/lib/response-body-inactivity.ts +23 -1
  147. package/src/lib/upstream-retry.ts +39 -6
  148. package/src/link/explicit-route.ts +4 -4
  149. package/src/link/remote-windows.ts +79 -31
  150. package/src/link/residual-recovery.ts +20 -8
  151. package/src/messaging/budget.ts +23 -5
  152. package/src/messaging/remote-ports.ts +22 -10
  153. package/src/messaging/rpc.ts +4 -4
  154. package/src/oauth/antigravity-risk.ts +126 -0
  155. package/src/oauth/credential-siblings.ts +32 -0
  156. package/src/oauth/generic-account-failover.ts +113 -30
  157. package/src/oauth/generic-session-affinity.ts +10 -3
  158. package/src/oauth/index.ts +22 -14
  159. package/src/oauth/login-cli.ts +35 -1
  160. package/src/oauth/pool-kernel.ts +3 -3
  161. package/src/oauth/store.ts +38 -7
  162. package/src/providers/anthropic-billing-refusal.ts +27 -3
  163. package/src/providers/anthropic-reset-grants.ts +4 -0
  164. package/src/providers/claude-cli-usage.ts +2 -0
  165. package/src/providers/codebuddy-models.ts +11 -0
  166. package/src/providers/google-vertex-model-discovery.ts +49 -15
  167. package/src/providers/kiro-models.ts +5 -0
  168. package/src/providers/model-rename-fields.ts +2 -0
  169. package/src/providers/quota/workbuddy.ts +6 -2
  170. package/src/providers/registry/entries-core.ts +9 -3
  171. package/src/providers/registry/entries-extended.ts +20 -9
  172. package/src/providers/registry/model-seeds.ts +4 -1
  173. package/src/providers/stale-context-window-migration.ts +2 -0
  174. package/src/providers/workbuddy-credit-balance.ts +125 -16
  175. package/src/responses/citation-markers.ts +26 -23
  176. package/src/responses/effort-history.ts +732 -0
  177. package/src/routing/history/integrity.ts +41 -4
  178. package/src/server/auth-cors.ts +13 -3
  179. package/src/server/codex-model-list.ts +2 -1
  180. package/src/server/direct-local-http.ts +26 -3
  181. package/src/server/index/link-listener.ts +20 -14
  182. package/src/server/index/serve-options.ts +1 -0
  183. package/src/server/index.ts +3 -2
  184. package/src/server/link-turn.ts +17 -5
  185. package/src/server/management/config-routes.ts +39 -3
  186. package/src/server/management/link-child-preflight.ts +1 -1
  187. package/src/server/management/link-enrollment.ts +3 -3
  188. package/src/server/management/link-route-edit.ts +20 -1
  189. package/src/server/management/link-route-request.ts +11 -5
  190. package/src/server/management/oauth-account-routes.ts +43 -13
  191. package/src/server/management/provider-credential-release.ts +44 -0
  192. package/src/server/management/provider-overwrite-carry.ts +3 -0
  193. package/src/server/management/provider-routes.ts +12 -12
  194. package/src/server/management/static-catalog-probe.ts +33 -0
  195. package/src/server/management/usage-aggregate-cache.ts +6 -3
  196. package/src/server/messages-native.ts +16 -2
  197. package/src/server/proxy-liveness.ts +54 -9
  198. package/src/server/relay.ts +6 -1
  199. package/src/server/request-log-conversation.ts +8 -4
  200. package/src/server/request-log-failure-detail.ts +26 -9
  201. package/src/server/request-log.ts +5 -1
  202. package/src/server/reserve-capability-startup.ts +32 -0
  203. package/src/server/responses/adapter-continuation.ts +59 -25
  204. package/src/server/responses/adapter-delivery.ts +2 -0
  205. package/src/server/responses/adapter-dispatch.ts +39 -18
  206. package/src/server/responses/antigravity-fault-rotation.ts +24 -0
  207. package/src/server/responses/antigravity-validation-refusal.ts +43 -6
  208. package/src/server/responses/codex-tool-catalog.ts +47 -10
  209. package/src/server/responses/combo-selection-keepalive.ts +254 -0
  210. package/src/server/responses/combo-session-recall.ts +26 -1
  211. package/src/server/responses/combo-stream-preflight.ts +35 -26
  212. package/src/server/responses/core-combo-failure.ts +6 -0
  213. package/src/server/responses/core-combo-native.ts +2 -1
  214. package/src/server/responses/core-combo.ts +67 -28
  215. package/src/server/responses/core-errors.ts +9 -6
  216. package/src/server/responses/core-options.ts +10 -0
  217. package/src/server/responses/core.ts +21 -0
  218. package/src/server/responses/estimated-usage.ts +115 -0
  219. package/src/server/responses/input-admission.ts +41 -3
  220. package/src/server/responses/jev-model-invoke.ts +7 -2
  221. package/src/server/responses/passthrough-completion.ts +6 -3
  222. package/src/server/responses/passthrough-delivery.ts +47 -8
  223. package/src/server/responses/passthrough-dispatch.ts +3 -0
  224. package/src/server/responses/request-prepare.ts +9 -5
  225. package/src/server/responses/request-send-budget.ts +1 -1
  226. package/src/server/responses/request-transport.ts +10 -2
  227. package/src/server/responses/sidecar-execution.ts +11 -4
  228. package/src/service/desktop-supervision.d.mts +2 -0
  229. package/src/service/desktop-supervision.mjs +5 -0
  230. package/src/service/windows-checked-stop-live.ts +28 -5
  231. package/src/stall-timeout.ts +11 -0
  232. package/src/types/config.ts +15 -92
  233. package/src/types/provider.ts +13 -0
  234. package/src/types/request.ts +23 -3
  235. package/src/types/routed-catalog-defaults.ts +17 -0
  236. package/src/types/routing-profile.ts +90 -0
  237. package/src/types.ts +1 -0
  238. package/src/update/index.ts +1 -1
  239. package/src/usage/expected-prices.ts +35 -0
  240. package/src/usage/ledger-scanner.ts +44 -10
  241. package/src/usage/log.ts +14 -4
  242. package/src/usage/telemetry-contract.ts +1 -0
  243. package/src/web-search/loop.ts +20 -2
  244. package/src/web-search/parse.ts +2 -12
  245. package/src/web-search/passthrough-bridge.ts +7 -0
  246. package/src/web-search/sources.ts +13 -0
  247. package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
  248. package/gui/dist/assets/index-DQtCRNAw.css +0 -2
  249. package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
@@ -1,7 +1,8 @@
1
1
  import type { AtomicWriteHooks } from "../../config/atomic-write";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { withConfigMutationLockSync } from "../../config";
4
- import { ConfigWriteLockRefusal, assertConfigWriteDestination, publishConfigWriteTarget, removeConfigWriteEntry, watchConfigWriteTargets, withConfigWriteLockHeld, type LockHandle } from "../config-write-lock";
4
+ import { atomicWriteFile } from "../../config/atomic-write";
5
+ import { ConfigWriteContentChanged, ConfigWriteLockRefusal, assertConfigWriteDestination, configDigest, publishConfigWriteTarget, recordPublishedConfigDigest, removeConfigWriteEntry, watchConfigWriteTargets, withConfigWriteLockHeld, type LockHandle } from "../config-write-lock";
5
6
  import { CODEX_CONFIG_PATH, CODEX_PROFILE_PATH } from "../paths";
6
7
  import { getCodexHome } from "../paths";
7
8
  import { codexHomeIsAbsent } from "../codex-home-owner";
@@ -35,3 +36,40 @@ export function cleanExternalProviderJournal(beforeClientWrite?: () => void): vo
35
36
  });
36
37
  if (!locked.ok) throw new ConfigWriteLockRefusal(locked);
37
38
  }
39
+ /** Where OpenCodex publishes config.toml; the test seam below names the site. */
40
+ export type CodexConfigPublishSite = "inject" | "journal" | "remove" | "retain" | "compensate";
41
+ let beforeCodexConfigPublishForTests: ((site: CodexConfigPublishSite) => void) | undefined;
42
+ /** Test seam: runs after a writer decided its bytes and immediately before it publishes config.toml. */
43
+ export function setBeforeCodexConfigPublishForTests(hook: typeof beforeCodexConfigPublishForTests): void {
44
+ beforeCodexConfigPublishForTests = hook;
45
+ }
46
+ function readConfigOrNull(path: string): string | null {
47
+ try { return readFileSync(path, "utf-8"); }
48
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; }
49
+ }
50
+ /**
51
+ * Publish config.toml only while it still holds `expected`, the bytes the caller decided from.
52
+ *
53
+ * The lock excludes other OpenCodex writers and its inode witness refuses an atomic rename, which
54
+ * is how Codex writes. Neither sees a writer that rewrites the file in place, and restore used to
55
+ * rename over such a write and report success. Comparing the bytes in `validateBeforeRename`
56
+ * refuses any write that landed before that comparison; a refusal writes nothing and is retryable.
57
+ *
58
+ * What it cannot do: an in-place write landing after the comparison and before the rename (the
59
+ * rename is the next system call) keeps the inode and is replaced. Closing that needs a
60
+ * replace-if-unchanged primitive the filesystem does not offer, so the window is narrowed, not closed.
61
+ */
62
+ export function publishCodexConfigIfUnchanged(held: LockHandle, site: CodexConfigPublishSite, expected: string | null, next: string): void {
63
+ publishCodexArtifact(CODEX_CONFIG_PATH, held, (path, hooks) => atomicWriteFile(path, next, undefined, {
64
+ ...hooks,
65
+ validateBeforeRename: target => {
66
+ beforeCodexConfigPublishForTests?.(site);
67
+ if (readConfigOrNull(target) !== expected) throw new ConfigWriteContentChanged();
68
+ hooks.validateBeforeRename?.(target);
69
+ },
70
+ afterRename: target => {
71
+ recordPublishedConfigDigest(held, configDigest(next));
72
+ hooks.afterRename?.(target);
73
+ },
74
+ }));
75
+ }
@@ -18,13 +18,12 @@ import {
18
18
  preflightCodexHistoryInjection,
19
19
  } from "../history-provider";
20
20
  import {
21
- journaledInjectedOpenaiBaseUrl,
22
- journaledInjectedRealtimeWsBaseUrl,
21
+ journaledInjectedRootValues,
23
22
  journaledInjectedRootWebSearch,
24
23
  journaledInjectedSubagentDefaults,
25
24
  journaledReplacedRootWebSearch,
26
25
  } from "../journal";
27
- import { stripJournaledOpenaiBaseUrl } from "../injected-marker";
26
+ import { REALTIME_WS_BASE_URL_KEY, stripJournaledOpenaiBaseUrl } from "../injected-marker";
28
27
  import { CODEX_CONFIG_PATH, CODEX_PROFILE_PATH, resolveCodexStateDbPath } from "../paths";
29
28
  import { transformManagedSubagentDefaults, type WrittenSubagentDefaults } from "../subagent-defaults";
30
29
  import type { OcxConfig } from "../../types";
@@ -193,11 +192,14 @@ export function deriveCodexInjectionPlan(
193
192
  // Design B -> provider-table transition (hostname change, authless opt-in) cannot leave our
194
193
  // own root URLs behind as if they were the user's, and so re-inject never journals them as
195
194
  // not-ours (which would make them unrestorable).
196
- content = stripJournaledOpenaiBaseUrl(
197
- content,
198
- journaledInjectedOpenaiBaseUrl({ readOnly: ctx.journalReadOnly }),
199
- journaledInjectedRealtimeWsBaseUrl({ readOnly: ctx.journalReadOnly }),
200
- );
195
+ // Every URL an injection under this journal wrote counts, not only the latest: the Codex app can
196
+ // write back an earlier one from its own copy of the file.
197
+ for (const url of journaledInjectedRootValues("openai_base_url", { readOnly: ctx.journalReadOnly })) {
198
+ content = stripJournaledOpenaiBaseUrl(content, url, null);
199
+ }
200
+ for (const url of journaledInjectedRootValues(REALTIME_WS_BASE_URL_KEY, { readOnly: ctx.journalReadOnly })) {
201
+ content = stripJournaledOpenaiBaseUrl(content, null, url);
202
+ }
201
203
  // Whether this home already published the provider id that its thread rows may reference.
202
204
  // Design B strips the table below; it may only stay stripped if those rows can be relabeled.
203
205
  const hadOcxProviderTableOnDisk = hasOcxProviderTable(content);
@@ -1,7 +1,6 @@
1
- import { beginCodexWriteSection, publishCodexArtifact, removeCodexProfileEntry } from "./config-write-section";
1
+ import { beginCodexWriteSection, publishCodexConfigIfUnchanged, removeCodexProfileEntry } from "./config-write-section";
2
2
  import { existsSync, lstatSync, readFileSync } from "node:fs";
3
3
  import { normalizeStructuralWhitespace, rootAssignmentKey, rootSourceLines, sourceAssignment, sourceText } from "../toml-source-lines";
4
- import { atomicWriteFile } from "../../config";
5
4
  import { ConfigWriteLockRefusal, configWriteLockFailureMessage, withConfigWriteLockHeld, withConfigWriteRecovery } from "../config-write-lock";
6
5
  import type { LockHandle } from "../config-write-lock";
7
6
  import {
@@ -12,8 +11,7 @@ import {
12
11
  } from "../injected-marker";
13
12
  import { HISTORY_RELABEL_STANDS_DOWN, preflightCodexHistoryInjection } from "../history-provider";
14
13
  import {
15
- journaledInjectedOpenaiBaseUrl,
16
- journaledInjectedRealtimeWsBaseUrl,
14
+ journaledInjectedRootValues,
17
15
  journaledInjectedRootWebSearch,
18
16
  journaledInjectedSubagentDefaults,
19
17
  journaledReplacedRootWebSearch,
@@ -62,7 +60,7 @@ export function retainOcxProviderTableOnDisk(block: string, heldConfigWriteLock?
62
60
  const eol = dominantEol(rawContent);
63
61
  const content = applyEol(rawContent, "\n");
64
62
  const next = appendOcxProviderTableBlock(content, block);
65
- if (next !== content) publishCodexArtifact(CODEX_CONFIG_PATH, held, (path, hooks) => atomicWriteFile(path, applyEol(next, eol), undefined, hooks));
63
+ if (next !== content) publishCodexConfigIfUnchanged(held, "retain", rawContent, applyEol(next, eol));
66
64
  return block.replace(/\n+$/, "").split("\n");
67
65
  });
68
66
  if (!locked.ok) throw new ConfigWriteLockRefusal(locked);
@@ -90,8 +88,8 @@ function hasRootOcxProvider(content: string): boolean {
90
88
  */
91
89
  function stripOpencodexConfigResult(
92
90
  content: string,
93
- journaledBaseUrl: string | null = null,
94
- journaledRealtimeWsBaseUrl: string | null = null,
91
+ journaledBaseUrls: readonly string[] = [],
92
+ journaledRealtimeWsBaseUrls: readonly string[] = [],
95
93
  journaledRootWebSearch: string | null = null,
96
94
  journaledReplacedWebSearch: string | null = null,
97
95
  journaledSubagentDefaults: WrittenSubagentDefaults | null = null,
@@ -101,9 +99,9 @@ function stripOpencodexConfigResult(
101
99
  hasRootOcxProvider(out);
102
100
  // #1798: marker adjacency is FORMATTING evidence, and a Codex app rewrite keeps values
103
101
  // while dropping comments. Fall back to VALUE evidence -- the exact URL we recorded
104
- // writing -- so an app-rewritten config is still recognized as ours.
105
- const hadInjectedBaseUrl = hasInjectedOpenaiBaseUrl(out)
106
- || (journaledBaseUrl !== null && rootTomlString(out, "openai_base_url") === journaledBaseUrl);
102
+ // writing, any injection under this journal -- so an app-rewritten config is still recognized as ours.
103
+ const rootBaseUrl = rootTomlString(out, "openai_base_url");
104
+ const hadInjectedBaseUrl = hasInjectedOpenaiBaseUrl(out) || (rootBaseUrl !== null && journaledBaseUrls.includes(rootBaseUrl));
107
105
  out = stripInjectedOpenaiBaseUrl(out); // before removeOcxSection — it keys on the marker line too
108
106
  // The enabled direction of the web-search transform is also the purge: it drops our pair, drops a
109
107
  // marker-less `disabled` the journal proves we wrote, and puts back the operator line we had to
@@ -112,7 +110,8 @@ function stripOpencodexConfigResult(
112
110
  injectedValue: journaledRootWebSearch,
113
111
  replacedUserLine: journaledReplacedWebSearch,
114
112
  }).content;
115
- out = stripJournaledOpenaiBaseUrl(out, journaledBaseUrl, journaledRealtimeWsBaseUrl);
113
+ for (const url of journaledBaseUrls) out = stripJournaledOpenaiBaseUrl(out, url, null);
114
+ for (const url of journaledRealtimeWsBaseUrls) out = stripJournaledOpenaiBaseUrl(out, null, url);
116
115
  if (hasOcxProviderTable(out)) {
117
116
  out = removeOcxSection(out);
118
117
  }
@@ -235,18 +234,21 @@ export function removeCodexConfig(
235
234
  const content = applyEol(rawContent, "\n");
236
235
  // Read the recorded injection once: the strip below consumes it, and so does the
237
236
  // ownership verdict, which must agree with what was actually removed.
238
- const journaledBaseUrl = journaledInjectedOpenaiBaseUrl();
239
- const journaledRealtimeWsBaseUrl = journaledInjectedRealtimeWsBaseUrl();
237
+ const journaledBaseUrls = journaledInjectedRootValues("openai_base_url");
238
+ const journaledRealtimeWsBaseUrls = journaledInjectedRootValues(REALTIME_WS_BASE_URL_KEY);
240
239
  const journaledRootWebSearch = journaledInjectedRootWebSearch();
241
240
  const journaledReplaced = journaledReplacedRootWebSearch();
241
+ const ownedRoot = (key: string, owned: readonly string[]) => {
242
+ const value = rootTomlString(content, key);
243
+ return value !== null && owned.includes(value);
244
+ };
242
245
  const had = hasOpencodexRouting(content)
243
- || (journaledBaseUrl !== null && rootTomlString(content, "openai_base_url") === journaledBaseUrl)
244
- || (journaledRealtimeWsBaseUrl !== null
245
- && rootTomlString(content, REALTIME_WS_BASE_URL_KEY) === journaledRealtimeWsBaseUrl);
246
+ || ownedRoot("openai_base_url", journaledBaseUrls)
247
+ || ownedRoot(REALTIME_WS_BASE_URL_KEY, journaledRealtimeWsBaseUrls);
246
248
  const stripped = stripOpencodexConfigResult(
247
249
  content,
248
- journaledBaseUrl,
249
- journaledRealtimeWsBaseUrl,
250
+ journaledBaseUrls,
251
+ journaledRealtimeWsBaseUrls,
250
252
  journaledRootWebSearch,
251
253
  journaledReplaced,
252
254
  journaledInjectedSubagentDefaults(),
@@ -260,7 +262,7 @@ export function removeCodexConfig(
260
262
  ? stripped.content
261
263
  : appendOcxProviderTableBlock(stripped.content, retainedBlock);
262
264
  if (had || finalContent !== content) {
263
- publishCodexArtifact(CODEX_CONFIG_PATH, held, (path, hooks) => atomicWriteFile(path, applyEol(finalContent, eol), undefined, hooks));
265
+ publishCodexConfigIfUnchanged(held, "remove", rawContent, applyEol(finalContent, eol));
264
266
  }
265
267
  if (!options.preserveProfile && existsSync(CODEX_PROFILE_PATH))
266
268
  removeCodexProfileEntry(held);
@@ -57,6 +57,7 @@ import {
57
57
  acquireConfigWriteLock,
58
58
  releaseConfigWriteLock,
59
59
  configWriteLockFailureMessage, withConfigWriteLockHeld,
60
+ ConfigWriteContentChanged,
60
61
  } from "../config-write-lock";
61
62
  import type { LockHandle } from "../config-write-lock";
62
63
  import { shouldInjectApiAuthHeader } from "../loopback-target";
@@ -523,7 +524,10 @@ function restoreCodexConfigInlineImpl(
523
524
  : { state: "failed", changed: false, action: "failed", message: restored.message };
524
525
  } catch (error) {
525
526
  if (error instanceof CodexHomeOwnerRefusal) throw error;
526
- return { state: "failed", changed: false, action: "failed", message: error instanceof Error ? error.message : String(error) };
527
+ return {
528
+ state: "failed", changed: false, action: "failed", message: error instanceof Error ? error.message : String(error),
529
+ ...(error instanceof ConfigWriteContentChanged ? { retryable: true } : {}),
530
+ };
527
531
  }
528
532
  }
529
533
 
@@ -7,8 +7,8 @@
7
7
  import { createHash } from "node:crypto";
8
8
  import { existsSync, lstatSync, readFileSync } from "node:fs";
9
9
 
10
- import { publishCodexArtifact } from "./inject/config-write-section";
11
- import { withConfigWriteLockHeld, type LockHandle } from "./config-write-lock";
10
+ import { publishCodexArtifact, publishCodexConfigIfUnchanged } from "./inject/config-write-section";
11
+ import { ConfigWriteContentChanged, configDigest, publishedConfigDigest, withConfigWriteLockHeld, type LockHandle } from "./config-write-lock";
12
12
  import { atomicWriteFile } from "../config";
13
13
  import type { CodexWriteLockResult, CodexWriteLockSkipReason } from "./codex-write-lock";
14
14
  import { HUB_GATED_SKIP_MESSAGE } from "./desired-state";
@@ -375,24 +375,70 @@ export function recordCodexNativeTransactionProvenance(
375
375
  * holds exactly those bytes. A refusal before the publish, or a profile another
376
376
  * writer replaced since, is left as it is.
377
377
  */
378
+ let afterCompensationDecisionForTests: ((surface: string) => void) | undefined;
379
+ /** Test seam: runs after compensation decided a surface must be restored and before it publishes. */
380
+ export function setAfterCompensationDecisionForTests(hook: typeof afterCompensationDecisionForTests): void {
381
+ afterCompensationDecisionForTests = hook;
382
+ }
383
+
378
384
  export function restoreCodexPreImages(
379
385
  pre: CodexPreImages,
380
386
  heldConfigWriteLock?: LockHandle,
381
387
  profilePublish?: CodexProfilePublish,
382
388
  ): { complete: boolean; unrestored: readonly string[] } {
383
- const locked = withConfigWriteLockHeld(CODEX_CONFIG_PATH, heldConfigWriteLock, held => {
384
- const unrestored: string[] = [];
385
389
  const surfaces: readonly [string, string, string | null][] = [
386
390
  ["config", CODEX_CONFIG_PATH, pre.config],
387
391
  ["profile", CODEX_PROFILE_PATH, pre.profile],
388
392
  ["journal", JOURNAL_PATH, pre.journal],
389
393
  ];
394
+ /*
395
+ * What a surface needs. One already holding its preimage needs nothing, and must not be made to
396
+ * pass a destination check: a foreign atomic rename of config.toml would otherwise fail the
397
+ * untouched profile and journal too. With a held lock (every injection and restore section),
398
+ * config.toml is reverted only when this section published it and it still holds that
399
+ * publication; any other bytes there belong to another writer. A direct call without a held lock
400
+ * has no publication record and keeps the unconditional config restore it always had.
401
+ */
402
+ // Returns the bytes the decision was made on (undefined when unreadable), so the restore can
403
+ // refuse when the file changed after it was judged to be OpenCodex's.
404
+ type Decision = readonly ["skip" | "foreign" | "restore", (string | null)?];
405
+ const decide = (name: string, path: string, bytes: string | null, held: LockHandle | undefined): Decision => {
406
+ let current: string | null;
407
+ // An unreadable surface proves nothing; the guarded restore attempt reports it as unrestored.
408
+ try { current = readOrNull(path); } catch { return ["restore"]; }
409
+ if (current === bytes) return ["skip", current];
410
+ if (name === "profile" && profilePublish
411
+ && (profilePublish.published === undefined || current !== profilePublish.published)) return ["skip", current];
412
+ if (name !== "config") return ["restore", current];
413
+ const ours = held ? publishedConfigDigest(held) : undefined;
414
+ if (ours === undefined) return [held ? "skip" : "restore", current];
415
+ return [configDigest(current) === ours ? "restore" : "foreign", current];
416
+ };
417
+ if (surfaces.every(([name, path, bytes]) => decide(name, path, bytes, heldConfigWriteLock)[0] === "skip")) {
418
+ return { complete: true, unrestored: [] };
419
+ }
420
+ const locked = withConfigWriteLockHeld(CODEX_CONFIG_PATH, heldConfigWriteLock, held => {
421
+ const unrestored: string[] = [];
390
422
  for (const [name, path, bytes] of surfaces) {
391
423
  // The current journal remains recovery authority until both artifacts are restored.
392
424
  if (name === "journal" && unrestored.length > 0) { unrestored.push(name); continue; }
393
425
  try {
394
- if (name === "profile" && profilePublish
395
- && (profilePublish.published === undefined || readOrNull(path) !== profilePublish.published)) continue;
426
+ const [need, decided] = decide(name, path, bytes, heldConfigWriteLock === undefined ? undefined : held);
427
+ if (need === "skip") continue;
428
+ if (need === "foreign") { unrestored.push(name); continue; }
429
+ afterCompensationDecisionForTests?.(name);
430
+ if (name === "config" && heldConfigWriteLock !== undefined) {
431
+ if (decided === undefined) throw new ConfigWriteContentChanged();
432
+ // Publish over, or remove, only the exact bytes judged to be this section's publication.
433
+ if (bytes !== null) { publishCodexConfigIfUnchanged(held, "compensate", decided, bytes); continue; }
434
+ publishCodexArtifact(path, held, (destination, hooks) => {
435
+ hooks.validateBeforeRename?.(destination);
436
+ if (readOrNull(destination) !== decided) throw new ConfigWriteContentChanged();
437
+ if (existsSync(destination)) require("node:fs").unlinkSync(destination);
438
+ hooks.afterRename?.(destination);
439
+ });
440
+ continue;
441
+ }
396
442
  publishCodexArtifact(path, held, (destination, hooks) => {
397
443
  if (bytes === null) {
398
444
  hooks.validateBeforeRename?.(destination);
@@ -406,7 +452,12 @@ export function restoreCodexPreImages(
406
452
  }
407
453
  return { complete: unrestored.length === 0, unrestored };
408
454
  });
409
- return locked.ok ? locked.value : { complete: false, unrestored: ["config", "profile", "journal"] };
455
+ if (locked.ok) return locked.value;
456
+ // The section can no longer publish (its destination changed). Name only what still differs
457
+ // from its preimage; a surface already holding it was not left partial.
458
+ const unrestored = surfaces.filter(([name, path, bytes]) => decide(name, path, bytes, heldConfigWriteLock)[0] !== "skip").map(([name]) => name);
459
+ if (unrestored.length > 0 && !unrestored.includes("journal")) unrestored.push("journal");
460
+ return { complete: false, unrestored };
410
461
  }
411
462
 
412
463
  export function buildInjectWitness(
@@ -1,5 +1,5 @@
1
1
  import { injectApprovedCodexProvider } from "./provider-routing";
2
- import { beginCodexWriteSection, cleanExternalProviderJournal, publishCodexArtifact } from "./inject/config-write-section";
2
+ import { beginCodexWriteSection, cleanExternalProviderJournal, publishCodexArtifact, publishCodexConfigIfUnchanged } from "./inject/config-write-section";
3
3
  import { closeSync, existsSync, openSync, readFileSync, statSync } from "node:fs";
4
4
  import { dirname } from "node:path";
5
5
  import {
@@ -42,8 +42,7 @@ import {
42
42
  import {
43
43
  JOURNAL_PATH, hasUnverifiedJournalBaseline,
44
44
  markJournalInjectedState,
45
- journaledInjectedOpenaiBaseUrl,
46
- journaledInjectedRealtimeWsBaseUrl,
45
+ journaledInjectedRootValues,
47
46
  removeJournal,
48
47
  writeJournal,
49
48
  } from "./journal";
@@ -373,14 +372,13 @@ async function injectCodexConfigImpl(
373
372
  }
374
373
 
375
374
  const journalBaselineIsNative = (nativeInput: string): boolean => {
376
- // Value evidence survives an app rewrite that removes the ownership comments.
377
- const journaledBaseUrl = journaledInjectedOpenaiBaseUrl({ readOnly: true });
378
- const journaledRealtimeWsBaseUrl = journaledInjectedRealtimeWsBaseUrl({ readOnly: true });
379
- const looksInjectedByValue =
380
- (journaledBaseUrl !== null && rootTomlString(nativeInput, "openai_base_url") === journaledBaseUrl)
381
- || (journaledRealtimeWsBaseUrl !== null
382
- && rootTomlString(nativeInput, REALTIME_WS_BASE_URL_KEY) === journaledRealtimeWsBaseUrl);
383
- return !hasInjectedCodexRouting(nativeInput) && !looksInjectedByValue;
375
+ // Value evidence survives an app rewrite that drops the ownership comments, including one that
376
+ // puts back an EARLIER injection's URL from the app's own copy of the file.
377
+ const ownsRoot = (key: Parameters<typeof journaledInjectedRootValues>[0]) => {
378
+ const value = rootTomlString(nativeInput, key);
379
+ return value !== null && journaledInjectedRootValues(key, { readOnly: true }).includes(value);
380
+ };
381
+ return !hasInjectedCodexRouting(nativeInput) && !ownsRoot("openai_base_url") && !ownsRoot(REALTIME_WS_BASE_URL_KEY);
384
382
  };
385
383
  const readCurrentProfile = readCodexProfileSource;
386
384
  const unverifiedJournalMessage = "Codex configuration was not written: the journal has no verified baseline for the current config/profile. Current files and the journal were preserved.";
@@ -491,7 +489,7 @@ async function injectCodexConfigImpl(
491
489
  // A native snapshot may have been refreshed above. An older hashless routed snapshot
492
490
  // must not gain the new injection's hash and later overwrite preserved user edits.
493
491
  if (hasUnverifiedJournalBaseline(plan.baselineContent, readCurrentProfile())) throw new Error(unverifiedJournalMessage);
494
- publishCodexArtifact(CODEX_CONFIG_PATH, heldConfigWriteLock, (path, hooks) => atomicWriteFile(path, plan.content, undefined, hooks));
492
+ publishCodexConfigIfUnchanged(heldConfigWriteLock!, "inject", nativeInput, plan.content);
495
493
  historyArtifactStageForTests?.("after-config");
496
494
  assertCodexHomeOwner(getCodexHome());
497
495
  profilePublish.published = plan.profileContent;
@@ -97,6 +97,39 @@ export function captureJournalConfigFields(content: string, ownership: Ownership
97
97
  return captured;
98
98
  }
99
99
 
100
+ /** Root routing URLs OpenCodex writes. `model_catalog_json` is excluded: injection keeps and records a user catalog path. */
101
+ export type InjectedRootKey = "openai_base_url" | "experimental_realtime_ws_base_url";
102
+ export type InjectedRootHistory = Partial<Record<InjectedRootKey, string[]>>;
103
+ const INJECTED_ROOT_KEYS: readonly InjectedRootKey[] = ["openai_base_url", "experimental_realtime_ws_base_url"];
104
+ export const INJECTED_ROOT_HISTORY_LIMIT = 8;
105
+
106
+ /** Only string arrays for the known keys count; the journal is read from disk. */
107
+ export function parseInjectedRootHistory(recorded: unknown): InjectedRootHistory {
108
+ const history: InjectedRootHistory = {};
109
+ if (typeof recorded !== "object" || recorded === null) return history;
110
+ for (const key of INJECTED_ROOT_KEYS) {
111
+ const values = (recorded as Record<string, unknown>)[key];
112
+ if (!Array.isArray(values)) continue;
113
+ const strings = values.filter((value): value is string => typeof value === "string" && value.length > 0);
114
+ if (strings.length) history[key] = strings.slice(-INJECTED_ROOT_HISTORY_LIMIT);
115
+ }
116
+ return history;
117
+ }
118
+
119
+ /** Append the values an injection wrote, newest last, deduplicated, bounded per key. */
120
+ export function appendInjectedRootHistory(
121
+ recorded: unknown,
122
+ written: Partial<Record<InjectedRootKey, string | null | undefined>>,
123
+ ): InjectedRootHistory {
124
+ const history = parseInjectedRootHistory(recorded);
125
+ for (const key of INJECTED_ROOT_KEYS) {
126
+ const value = written[key];
127
+ if (typeof value !== "string" || !value) continue;
128
+ history[key] = [...(history[key] ?? []).filter(entry => entry !== value), value].slice(-INJECTED_ROOT_HISTORY_LIMIT);
129
+ }
130
+ return history;
131
+ }
132
+
100
133
  interface Ownership {
101
134
  injectedConfigFields?: JournalConfigFields;
102
135
  injectedOpenaiBaseUrl?: string | null;
@@ -105,6 +138,7 @@ interface Ownership {
105
138
  injectedRootWebSearch?: string | null;
106
139
  replacedRootWebSearch?: string | null;
107
140
  injectedSubagentDefaults?: WrittenSubagentDefaults | null;
141
+ injectedRootHistory?: unknown;
108
142
  }
109
143
 
110
144
  function recordedValues(journal: Ownership): Map<string, unknown> {
@@ -145,6 +179,14 @@ export function restoreJournalConfigFields(current: string, original: string, jo
145
179
  for (const [key, value] of recordedValues(journal)) expected.set(key, value);
146
180
  if (now.get("model_provider")?.value === "opencodex") expected.set("model_provider", "opencodex");
147
181
  }
182
+ // A present root URL an injection under this journal wrote is ours even when the Codex app
183
+ // rewrote it back to an earlier injection's value. Only the current file is reinterpreted;
184
+ // a snapshot value that coincides with one may be the user's and is restored as it was.
185
+ const history = parseInjectedRootHistory(journal.injectedRootHistory);
186
+ for (const key of INJECTED_ROOT_KEYS) {
187
+ const present = now.get(key)?.value;
188
+ if (typeof present === "string" && history[key]?.includes(present)) expected.set(key, present);
189
+ }
148
190
  const { bom, lines } = rootSourceLines(current);
149
191
  if (recoverOwnedEdits) {
150
192
  // Legacy journals lack field snapshots. An exact structural marker is evidence
@@ -1,4 +1,4 @@
1
- import { beginCodexWriteSection, publishCodexArtifact } from "./inject/config-write-section";
1
+ import { beginCodexWriteSection, publishCodexArtifact, publishCodexConfigIfUnchanged } from "./inject/config-write-section";
2
2
  import { createHash } from "node:crypto";
3
3
  import type { AtomicWriteHooks } from "../config/atomic-write";
4
4
  import { existsSync, lstatSync, readFileSync, unlinkSync } from "node:fs";
@@ -6,11 +6,11 @@ import { join } from "node:path";
6
6
  import { atomicWriteFile, withConfigMutationLockSync } from "../config";
7
7
  import { assertCodexHomeOwner, codexHomeIsAbsent, CODEX_HOME_JOURNAL_FILE, CodexHomeOwnerRefusal, opencodexHomeForInjection, readCodexHomeJournal, type CodexHomeOwnerRefusalReason } from "./codex-home-owner";
8
8
  import { hasInjectedCodexRouting } from "./injected-marker";
9
- import { configWriteLockFailureMessage, withConfigWriteLockHeld } from "./config-write-lock";
9
+ import { ConfigWriteContentChanged, configWriteLockFailureMessage, withConfigWriteLockHeld } from "./config-write-lock";
10
10
  import type { LockHandle } from "./config-write-lock";
11
11
  import { CODEX_HOME, CODEX_CONFIG_PATH, CODEX_PROFILE_PATH } from "./paths";
12
12
  import { transformManagedSubagentDefaults, type WrittenSubagentDefaults } from "./subagent-defaults";
13
- import { captureJournalConfigFields, restoreJournalConfigFields, snapshotDisconnectRecovery, type JournalConfigFields } from "./journal-config-restore";
13
+ import { appendInjectedRootHistory, captureJournalConfigFields, parseInjectedRootHistory, restoreJournalConfigFields, snapshotDisconnectRecovery, type InjectedRootHistory, type InjectedRootKey, type JournalConfigFields } from "./journal-config-restore";
14
14
 
15
15
  /**
16
16
  * Exported so that anything reasoning ABOUT the journal points at the journal.
@@ -88,6 +88,15 @@ interface Journal {
88
88
  * untouched managed line apart from an edited one. Null when no managed default was written.
89
89
  */
90
90
  injectedSubagentDefaults?: WrittenSubagentDefaults | null;
91
+ /**
92
+ * Every root routing URL injections under this journal wrote, newest last, bounded.
93
+ *
94
+ * The latest-value fields above prove only the most recent write. The Codex app can rewrite
95
+ * config.toml from its own older copy, putting back an EARLIER injection's URL without the marker
96
+ * comment; with only the latest value as evidence, sync took that URL for the user's, snapshotted
97
+ * it as native and kept pointing Codex at a dead port that restore could never remove.
98
+ */
99
+ injectedRootHistory?: InjectedRootHistory;
91
100
  /** Injection binding survives native snapshot replacement and is released by native restore. */
92
101
  opencodexHome?: string;
93
102
  pid: number;
@@ -213,6 +222,10 @@ export function writeJournal(options: WriteJournalOptions = {}, hooks: AtomicWri
213
222
  originalConfig: Buffer.from(config).toString("base64"),
214
223
  originalProfile: profile !== null ? Buffer.from(profile).toString("base64") : null,
215
224
  opencodexHome: opencodexHomeForInjection(previous?.opencodexHome),
225
+ ...(previous ? { injectedRootHistory: appendInjectedRootHistory(previous.injectedRootHistory, {
226
+ openai_base_url: previous.injectedOpenaiBaseUrl,
227
+ experimental_realtime_ws_base_url: previous.injectedRealtimeWsBaseUrl,
228
+ }) } : {}),
216
229
  pid: process.pid,
217
230
  owner: options.owner?.kind === "client"
218
231
  ? { kind: "client", apiKeyId: options.owner.apiKeyId }
@@ -254,6 +267,12 @@ export function markJournalInjectedState(
254
267
  // The profile file is wholly generated by OpenCodex, so its latest exact hash remains safe
255
268
  // to refresh and lets restore remove the latest generated profile after a port change.
256
269
  journal.injectedProfileHash = sha256(profile);
270
+ // The values about to be replaced were ours too. A journal written before this history existed
271
+ // carries them only in the latest-value fields, so record them before the overwrite below.
272
+ journal.injectedRootHistory = appendInjectedRootHistory(journal.injectedRootHistory, {
273
+ openai_base_url: journal.injectedOpenaiBaseUrl,
274
+ experimental_realtime_ws_base_url: journal.injectedRealtimeWsBaseUrl,
275
+ });
257
276
  // Only the caller knows which values it actually owns. Deriving these from the final TOML
258
277
  // would mistake a preserved user override for injected routing.
259
278
  journal.injectedOpenaiBaseUrl = ownership.injectedOpenaiBaseUrl;
@@ -262,6 +281,10 @@ export function markJournalInjectedState(
262
281
  journal.replacedRootWebSearch = ownership.replacedRootWebSearch ?? null;
263
282
  journal.injectedSubagentDefaults = ownership.injectedSubagentDefaults ?? null;
264
283
  journal.injectedCatalogPath = ownership.injectedCatalogPath;
284
+ journal.injectedRootHistory = appendInjectedRootHistory(journal.injectedRootHistory, {
285
+ openai_base_url: ownership.injectedOpenaiBaseUrl,
286
+ experimental_realtime_ws_base_url: ownership.injectedRealtimeWsBaseUrl,
287
+ });
265
288
  journal.opencodexHome = opencodexHomeForInjection(journal.opencodexHome);
266
289
  atomicWriteFile(JOURNAL_PATH, JSON.stringify(journal), undefined, hooks);
267
290
  }
@@ -283,6 +306,15 @@ export function journaledInjectedRealtimeWsBaseUrl(options: { readOnly?: boolean
283
306
  return readJournal(options.readOnly !== true)?.injectedRealtimeWsBaseUrl ?? null;
284
307
  }
285
308
 
309
+ /** Every value injections under this journal wrote for a root routing URL, latest first. */
310
+ export function journaledInjectedRootValues(key: InjectedRootKey, options: { readOnly?: boolean } = {}): string[] {
311
+ const journal = readJournal(options.readOnly !== true);
312
+ if (!journal) return [];
313
+ const latest = key === "openai_base_url" ? journal.injectedOpenaiBaseUrl : journal.injectedRealtimeWsBaseUrl;
314
+ const values = [latest, ...[...(parseInjectedRootHistory(journal.injectedRootHistory)[key] ?? [])].reverse()];
315
+ return [...new Set(values.filter((value): value is string => typeof value === "string" && value.length > 0))];
316
+ }
317
+
286
318
  /** The root `web_search` value the last injection wrote, or null when it wrote none. */
287
319
  export function journaledInjectedRootWebSearch(options: { readOnly?: boolean } = {}): string | null {
288
320
  return readJournal(options.readOnly !== true)?.injectedRootWebSearch ?? null;
@@ -432,10 +464,15 @@ export function restoreJournalState(
432
464
  let configRewritten = false;
433
465
  let profileRewritten = false;
434
466
  if ((configUnchanged || fieldRestore !== null) && !configRestored) {
435
- options.beforeWrite?.();
436
- publishCodexArtifact(CODEX_CONFIG_PATH, held, (path, hooks) => atomicWriteFile(path, fieldRestore ?? comparison.originalConfig, undefined, hooks));
467
+ const restoredConfig = fieldRestore ?? comparison.originalConfig;
468
+ // Published only over the bytes this decision was computed from; a write that landed since
469
+ // is refused rather than replaced, and the journal stays for a retry.
470
+ if (restoredConfig !== currentConfig) {
471
+ options.beforeWrite?.();
472
+ publishCodexConfigIfUnchanged(held, "journal", currentConfig, restoredConfig);
473
+ configRewritten = true;
474
+ }
437
475
  configRestored = true;
438
- configRewritten = true;
439
476
  }
440
477
  if (profileUnchanged && !profileRestored) {
441
478
  if (comparison.originalProfile !== null) {
@@ -563,6 +600,19 @@ export function adoptJournalForClient(apiKeyId: string, beforeWrite: () => void
563
600
  return locked.value;
564
601
  }
565
602
 
603
+ /**
604
+ * A recovery that found config.toml changed after it read it wrote nothing and kept the journal.
605
+ * That is a reason to retry on a later start, not to abort this one.
606
+ */
607
+ function deferOnConcurrentWrite(restore: () => RestoreJournalResult): RestoreJournalResult | null {
608
+ try { return restore(); }
609
+ catch (error) {
610
+ if (!(error instanceof ConfigWriteContentChanged)) throw error;
611
+ console.error("⚠️ Codex config.toml changed during journal recovery; nothing was overwritten and the journal was kept for the next start.");
612
+ return null;
613
+ }
614
+ }
615
+
566
616
  export function reconcileJournal(options: ReconcileJournalOptions = {}): boolean {
567
617
  if (codexHomeIsAbsent(CODEX_HOME)) return false;
568
618
  const locked = withConfigWriteLockHeld(CODEX_CONFIG_PATH, undefined, handle => {
@@ -578,7 +628,8 @@ export function reconcileJournal(options: ReconcileJournalOptions = {}): boolean
578
628
  const owner = journal.owner ?? (Number.isSafeInteger(journal.pid) && journal.pid > 0 ? { kind: "process" as const, pid: journal.pid } : null);
579
629
  if (owner?.kind === "client") {
580
630
  if (options.activeClientApiKeyId === owner.apiKeyId) return false;
581
- const restored = restoreJournalState({ heldConfigWriteLock: handle });
631
+ const restored = deferOnConcurrentWrite(() => restoreJournalState({ heldConfigWriteLock: handle, preserveConfigEdits: true }));
632
+ if (!restored) return false;
582
633
  if (restored.unverified) {
583
634
  console.error("⚠️ Codex journal recovery was not verified; current configuration files and the journal were preserved.");
584
635
  return false;
@@ -611,7 +662,10 @@ export function reconcileJournal(options: ReconcileJournalOptions = {}): boolean
611
662
  catch { console.error("⚠️ The Codex journal handed over by an update could not be adopted; the journal and configuration were preserved."); }
612
663
  return false;
613
664
  }
614
- const restored = restoreJournalState({ heldConfigWriteLock: handle });
665
+ // Key-level like disconnect: a config changed since injection keeps every later edit and loses
666
+ // only OpenCodex's own fields; only the byte-identical injected file is replayed whole.
667
+ const restored = deferOnConcurrentWrite(() => restoreJournalState({ heldConfigWriteLock: handle, preserveConfigEdits: true }));
668
+ if (!restored) return false;
615
669
  if (restored.unverified) {
616
670
  console.error("⚠️ Codex journal recovery was not verified; current configuration files and the journal were preserved.");
617
671
  return false;