@bitkyc08/opencodex 2.95.0 → 2.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
  3. package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +21 -7
  16. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  17. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  18. package/src/adapters/openai-responses/passthrough.ts +8 -8
  19. package/src/adapters/openai-responses/reasoning.ts +9 -4
  20. package/src/adapters/openai-responses/request-strips.ts +1 -1
  21. package/src/adapters/openai-responses/transport.ts +17 -26
  22. package/src/adapters/physical-send.ts +3 -3
  23. package/src/adapters/qoder/adapter.ts +1 -1
  24. package/src/adapters/qoder/image-input.ts +5 -2
  25. package/src/adapters/zed-openai-stream.ts +2 -1
  26. package/src/bridge/errors.ts +11 -2
  27. package/src/bridge/response-json.ts +2 -1
  28. package/src/bridge/sse.ts +14 -6
  29. package/src/chat/failure-verdict.ts +21 -0
  30. package/src/chat/outbound.ts +139 -21
  31. package/src/claude/outbound.ts +49 -2
  32. package/src/cli/agent.ts +44 -15
  33. package/src/cli/capabilities-agents-routing.ts +9 -0
  34. package/src/cli/capabilities-base.ts +25 -3
  35. package/src/cli/capabilities-command.ts +12 -3
  36. package/src/cli/capability-contracts.ts +2 -0
  37. package/src/cli/codex-launch-auth.ts +30 -1
  38. package/src/cli/codex-launcher.ts +12 -5
  39. package/src/cli/codex-shim-autorestore.ts +5 -4
  40. package/src/cli/dispatch.ts +11 -176
  41. package/src/cli/ensure-desired-integrations.ts +4 -3
  42. package/src/cli/help.ts +2 -2
  43. package/src/cli/index.ts +9 -2
  44. package/src/cli/link.ts +1 -1
  45. package/src/cli/message-command.ts +2 -1
  46. package/src/cli/message-mcp-command.ts +29 -0
  47. package/src/cli/registry.ts +12 -4
  48. package/src/cli/root.ts +8 -0
  49. package/src/cli/sync-command.ts +243 -0
  50. package/src/cli/sync-fanout-process.ts +92 -0
  51. package/src/cli/sync-fanout.ts +150 -0
  52. package/src/cli/sync-flags.ts +10 -0
  53. package/src/cli/sync-link-status.ts +39 -0
  54. package/src/cli/sync-update-guard.ts +18 -0
  55. package/src/client/connect.ts +31 -14
  56. package/src/client/link-home.ts +3 -2
  57. package/src/client/machine-listener.ts +3 -0
  58. package/src/client/restore-ownership.ts +19 -1
  59. package/src/client/runtime-restart.ts +12 -4
  60. package/src/client/runtime.ts +40 -11
  61. package/src/client/stop-routing.ts +62 -0
  62. package/src/client/sync-runtime.ts +65 -0
  63. package/src/clients/config-export.ts +32 -3
  64. package/src/codex/account-store.ts +1 -0
  65. package/src/codex/auth-context-provider.ts +15 -0
  66. package/src/codex/auth-context.ts +59 -122
  67. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  68. package/src/codex/catalog/provider-models.ts +6 -8
  69. package/src/codex/forward-transport-headers.ts +65 -36
  70. package/src/codex/inject/config-toml.ts +88 -0
  71. package/src/codex/inject/multi-agent-v2.ts +30 -4
  72. package/src/codex/inject/plan.ts +34 -7
  73. package/src/codex/inject-coordination.ts +11 -0
  74. package/src/codex/inject.ts +18 -7
  75. package/src/codex/installation-id.ts +72 -0
  76. package/src/codex/lineage.ts +13 -7
  77. package/src/codex/quota.ts +22 -6
  78. package/src/codex/request-owned-affinity-key.ts +11 -0
  79. package/src/codex/request-owned-affinity.ts +118 -0
  80. package/src/codex/request-owned-main-pin.ts +86 -0
  81. package/src/codex/role-capability.ts +52 -41
  82. package/src/codex/routing/active-account.ts +13 -5
  83. package/src/codex/routing/selection.ts +40 -1
  84. package/src/codex/routing/thread-affinity-store.ts +916 -0
  85. package/src/codex/routing/thread-affinity.ts +90 -12
  86. package/src/codex/toml-source-lines.ts +72 -13
  87. package/src/combos/failover.ts +6 -109
  88. package/src/combos/request.ts +2 -2
  89. package/src/combos/resolve.ts +29 -11
  90. package/src/config/process-state.ts +5 -0
  91. package/src/config/schema/leaf-validators.ts +1 -0
  92. package/src/generated/compatibility-version.json +496 -192
  93. package/src/grok/sync.ts +10 -1
  94. package/src/images/loop.ts +2 -1
  95. package/src/lib/client-error-body.ts +184 -0
  96. package/src/lib/client-retry-after.ts +66 -0
  97. package/src/lib/config-ownership.ts +4 -0
  98. package/src/lib/context-overflow-verdict.ts +113 -0
  99. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  100. package/src/lib/desktop-cli-handoff.mjs +11 -1
  101. package/src/lib/empty-tool-catalog.ts +25 -3
  102. package/src/lib/error-destination.ts +47 -0
  103. package/src/lib/failure-detail.ts +66 -0
  104. package/src/lib/model-identity.ts +44 -0
  105. package/src/lib/private-sqlite-path.ts +124 -0
  106. package/src/lib/response-service-tier.ts +17 -0
  107. package/src/lib/retry-after.ts +3 -0
  108. package/src/lib/spend-ledger-owner.ts +43 -4
  109. package/src/lib/upstream-condition.ts +142 -0
  110. package/src/lib/upstream-retry.ts +14 -11
  111. package/src/lib/windows-owner-acl.ts +13 -6
  112. package/src/lib/windows-secret-acl.ts +2 -2
  113. package/src/link/remote-platform.ts +14 -0
  114. package/src/link/remote-windows.ts +51 -9
  115. package/src/link/ssh-argv.ts +63 -10
  116. package/src/messaging/mcp-queue-rpc.ts +102 -0
  117. package/src/messaging/mcp-queue-server.ts +42 -0
  118. package/src/messaging/mcp-queue-tools.ts +39 -0
  119. package/src/oauth/anthropic-identity.ts +2 -6
  120. package/src/oauth/generic-account-failover.ts +13 -11
  121. package/src/oauth/index.ts +41 -74
  122. package/src/oauth/oauth-errors.ts +67 -0
  123. package/src/oauth/store.ts +1 -1
  124. package/src/protocols/codecs/ollama.ts +197 -0
  125. package/src/protocols/encoders/adapter-events.ts +4 -0
  126. package/src/protocols/encoders/chat.ts +18 -10
  127. package/src/protocols/trace.ts +18 -0
  128. package/src/providers/anthropic-subscription.ts +25 -0
  129. package/src/providers/claude-cli-usage.ts +15 -67
  130. package/src/providers/fastwire.ts +3 -2
  131. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  132. package/src/providers/quota/anthropic-usage-windows.ts +65 -0
  133. package/src/providers/quota/vendor-probes-key.ts +60 -24
  134. package/src/providers/request-pacing.ts +3 -2
  135. package/src/responses/apply-patch-envelope.ts +45 -19
  136. package/src/responses/compaction-history-framing.ts +5 -1
  137. package/src/responses/freeform-wrapper-scan.ts +5 -3
  138. package/src/responses/parser-tools.ts +1 -0
  139. package/src/responses/progressive-freeform-input.ts +354 -45
  140. package/src/responses/schema.ts +5 -2
  141. package/src/routing/fallback-policy.ts +3 -1
  142. package/src/server/admission-model-scope.ts +17 -6
  143. package/src/server/admitted-http-turn.ts +56 -0
  144. package/src/server/audio-dictation.ts +3 -0
  145. package/src/server/audio-live.ts +8 -2
  146. package/src/server/audio-upstream.ts +2 -0
  147. package/src/server/auth-cors.ts +5 -0
  148. package/src/server/chat-completions.ts +45 -20
  149. package/src/server/chat-native-sse.ts +52 -7
  150. package/src/server/chat-native.ts +60 -35
  151. package/src/server/claude-bridge-pool-session.ts +59 -0
  152. package/src/server/claude-messages.ts +57 -27
  153. package/src/server/context-history.ts +14 -7
  154. package/src/server/images.ts +14 -5
  155. package/src/server/inbound-body-admission.ts +11 -4
  156. package/src/server/index/live-sideband.ts +16 -2
  157. package/src/server/index/ollama-routes.ts +89 -0
  158. package/src/server/index/serve-options.ts +22 -4
  159. package/src/server/index/websocket-handler.ts +5 -3
  160. package/src/server/index.ts +6 -36
  161. package/src/server/inference/client-encoder-delivery.ts +4 -2
  162. package/src/server/json-serialized-bytes.ts +44 -0
  163. package/src/server/live.ts +30 -5
  164. package/src/server/management/agent-settings-routes.ts +24 -21
  165. package/src/server/management/codex-cli-update-routes.ts +2 -1
  166. package/src/server/management/route-registry.ts +1 -1
  167. package/src/server/messages-native-scope.ts +2 -1
  168. package/src/server/messages-native-tool-guard.ts +1 -1
  169. package/src/server/messages-native.ts +12 -7
  170. package/src/server/messages-shared.ts +6 -2
  171. package/src/server/native-final-log.ts +93 -0
  172. package/src/server/ollama-inbound.ts +349 -0
  173. package/src/server/ollama-native-paths.ts +21 -0
  174. package/src/server/ollama-route-policy.ts +73 -0
  175. package/src/server/relay.ts +22 -3
  176. package/src/server/request-decompress.ts +4 -2
  177. package/src/server/request-log-failure-attribution.ts +22 -0
  178. package/src/server/request-log-failure-detail.ts +80 -0
  179. package/src/server/request-log-terminal-status.ts +4 -2
  180. package/src/server/request-log.ts +79 -42
  181. package/src/server/response-log-body.ts +6 -1
  182. package/src/server/responses/account-change-state.ts +17 -6
  183. package/src/server/responses/adapter-continuation.ts +9 -4
  184. package/src/server/responses/adapter-delivery.ts +5 -4
  185. package/src/server/responses/adapter-dispatch.ts +36 -30
  186. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  187. package/src/server/responses/codex-auth-error.ts +22 -17
  188. package/src/server/responses/codex-ws-exchange.ts +11 -8
  189. package/src/server/responses/codex-ws-metadata.ts +94 -21
  190. package/src/server/responses/codex-ws-request.ts +3 -1
  191. package/src/server/responses/combo-required-tool-contract.ts +24 -12
  192. package/src/server/responses/compact.ts +89 -41
  193. package/src/server/responses/compaction-recovery.ts +4 -2
  194. package/src/server/responses/compaction-routing.ts +9 -4
  195. package/src/server/responses/core-auth.ts +32 -14
  196. package/src/server/responses/core-codex-account.ts +34 -12
  197. package/src/server/responses/core-combo-failure.ts +5 -1
  198. package/src/server/responses/core-combo-native.ts +2 -1
  199. package/src/server/responses/core-combo.ts +51 -33
  200. package/src/server/responses/core-errors.ts +22 -20
  201. package/src/server/responses/core-lifetime.ts +6 -3
  202. package/src/server/responses/core-normalize.ts +8 -1
  203. package/src/server/responses/core-options.ts +7 -0
  204. package/src/server/responses/core-pipeline.ts +4 -3
  205. package/src/server/responses/fetch-helpers.ts +7 -1
  206. package/src/server/responses/input-admission.ts +28 -2
  207. package/src/server/responses/native-injection.ts +1 -1
  208. package/src/server/responses/native-response-json.ts +13 -4
  209. package/src/server/responses/native-response-output.ts +1 -2
  210. package/src/server/responses/non-replayable-error.ts +2 -1
  211. package/src/server/responses/pacing-overload.ts +3 -2
  212. package/src/server/responses/passthrough-build-error.ts +36 -0
  213. package/src/server/responses/passthrough-delivery.ts +55 -14
  214. package/src/server/responses/passthrough-dispatch.ts +26 -39
  215. package/src/server/responses/passthrough-error.ts +9 -9
  216. package/src/server/responses/policy-fallback.ts +2 -1
  217. package/src/server/responses/request-prepare.ts +67 -48
  218. package/src/server/responses/request-sidecar-auth.ts +3 -1
  219. package/src/server/responses/request-transport.ts +35 -31
  220. package/src/server/responses/run-turn-execution.ts +6 -6
  221. package/src/server/responses/sidecar-execution.ts +16 -12
  222. package/src/server/responses/spend-storage-error.ts +2 -1
  223. package/src/server/responses/ws-upstream.ts +9 -0
  224. package/src/server/responses-custom-tool-repair.ts +14 -3
  225. package/src/server/responses-terminal-repair.ts +5 -2
  226. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  227. package/src/server/safe-response-headers.ts +162 -13
  228. package/src/server/search.ts +13 -4
  229. package/src/server/turn-state-handles.ts +164 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/server/ws-bridge.ts +5 -2
  232. package/src/service/ownership-mutation-lease.d.mts +11 -2
  233. package/src/service/ownership-mutation-lease.mjs +53 -11
  234. package/src/types/config.ts +2 -0
  235. package/src/update/index.ts +133 -25
  236. package/src/update/npm-install.d.mts +8 -0
  237. package/src/update/npm-install.mjs +20 -1
  238. package/src/update/orchestrated-admission.d.mts +4 -0
  239. package/src/update/orchestrated-admission.mjs +12 -0
  240. package/src/update/orchestrated-arguments.d.mts +12 -0
  241. package/src/update/orchestrated-arguments.mjs +64 -0
  242. package/src/update/orchestrated-child.d.mts +12 -0
  243. package/src/update/orchestrated-child.mjs +70 -0
  244. package/src/update/orchestrated-entry.ts +234 -0
  245. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  246. package/src/update/orchestrated-identity.ts +53 -0
  247. package/src/update/orchestrated-live-identity.ts +48 -0
  248. package/src/update/orchestrated-node-driver.mjs +99 -0
  249. package/src/update/orchestrated-outcome.d.mts +21 -0
  250. package/src/update/orchestrated-outcome.mjs +40 -0
  251. package/src/update/orchestrated-plan.ts +49 -0
  252. package/src/update/orchestrated-pnpm.d.mts +8 -0
  253. package/src/update/orchestrated-pnpm.mjs +33 -0
  254. package/src/update/orchestrated-session.d.mts +37 -0
  255. package/src/update/orchestrated-session.mjs +264 -0
  256. package/src/update/orchestrated-token.d.mts +10 -0
  257. package/src/update/orchestrated-token.mjs +21 -0
  258. package/src/update/orchestrated-token.ts +3 -0
  259. package/src/update/orchestrated-tree.d.mts +1 -0
  260. package/src/update/orchestrated-tree.mjs +14 -0
  261. package/src/update/pnpm-global-install.d.mts +6 -0
  262. package/src/update/pnpm-global-install.mjs +9 -2
  263. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  264. package/src/update/posix-install-supervisor.d.mts +10 -0
  265. package/src/update/posix-install-supervisor.mjs +88 -0
  266. package/src/update/sync-update-mutex.d.mts +10 -0
  267. package/src/update/sync-update-mutex.mjs +164 -0
  268. package/src/update/sync-update-mutex.ts +1 -0
  269. package/src/update/test-home-guard.mjs +33 -0
  270. package/src/update/transactional-install.mjs +2 -2
  271. package/src/usage/error-detail.ts +225 -0
  272. package/src/usage/log.ts +60 -27
  273. package/src/vision/describe.ts +4 -7
  274. package/src/web-search/executor.ts +4 -7
  275. package/src/web-search/loop.ts +31 -5
  276. package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
@@ -672,6 +672,94 @@ export function buildProfileFileForTarget(
672
672
  return lines.join("\n");
673
673
  }
674
674
 
675
+ /**
676
+ * Root keys this build owns in either profile shape. They are never carried
677
+ * forward: leaving provider-table mode drops `model_provider` from the template,
678
+ * and a caller that passes no catalog path drops `model_catalog_json`, so a
679
+ * carried copy would point the profile at routing this build no longer writes.
680
+ */
681
+ const MANAGED_PROFILE_ROOT_KEYS = new Set([
682
+ "model_provider",
683
+ "model_catalog_json",
684
+ "openai_base_url",
685
+ ]);
686
+
687
+ /**
688
+ * Root keys the previous profile carried that this build does not write.
689
+ *
690
+ * Operators add Codex settings such as `stream_idle_timeout_ms` and
691
+ * `stream_max_retries` to `opencodex.config.toml`. Rebuilding the file from the
692
+ * template dropped them without a word (#8066), so any root key this build does
693
+ * not own is carried over, ahead of the first table. Values that span several
694
+ * lines are copied whole, because one line of a multi-line value would not
695
+ * parse, and every carried assignment keeps its original bytes: nothing is
696
+ * decoded and reserialized, so a 64-bit integer Bun cannot represent survives.
697
+ *
698
+ * A carried root key named like a table the generated profile writes (an inline
699
+ * `features = { ... }` against a generated `[features]`) is dropped: TOML
700
+ * forbids defining the same table twice, and the generated table wins because
701
+ * it carries the settings this build manages.
702
+ */
703
+ export function preserveUnmanagedProfileKeys(existing: string | null, generated: string): string {
704
+ if (!existing) return generated;
705
+ const generatedKeys = rootKeysOf(generated);
706
+ if (generatedKeys.size === 0) return generated;
707
+ const generatedTables = topLevelTableNamesOf(generated);
708
+
709
+ const existingSource = rootSourceLines(existing);
710
+ const carried: string[] = [];
711
+ const carriedKeys = new Set<string>();
712
+ for (let index = 0; index < existingSource.rootEnd; index += 1) {
713
+ if (!existingSource.lines[index]?.structural) continue;
714
+ const span = sourceAssignmentSpan(existingSource.lines, index, existingSource.rootEnd);
715
+ if (!span) continue;
716
+ index = span.end - 1;
717
+ if (generatedKeys.has(span.key) || MANAGED_PROFILE_ROOT_KEYS.has(span.key)) continue;
718
+ if (generatedTables.has(span.key)) continue;
719
+ if (carriedKeys.has(span.key)) continue;
720
+ carriedKeys.add(span.key);
721
+ // Drop only trailing blank lines; the assignment's own bytes, trailing spaces included, stay.
722
+ carried.push(span.text.replace(/(?:\r?\n[ \t]*)+$/, ""));
723
+ }
724
+ if (carried.length === 0) return generated;
725
+
726
+ const lines = generated.split("\n");
727
+ const firstTable = lines.findIndex((line) => /^\s*\[/.test(line));
728
+ lines.splice(firstTable === -1 ? lines.length : firstTable, 0, [
729
+ "# Root keys OpenCodex does not manage, kept from the previous profile:",
730
+ ...carried,
731
+ "",
732
+ ].join("\n"));
733
+ return lines.join("\n");
734
+ }
735
+
736
+ /** Names of the root assignments in a TOML document, before its first table. */
737
+ function rootKeysOf(content: string): Set<string> {
738
+ const keys = new Set<string>();
739
+ const source = rootSourceLines(content);
740
+ for (let index = 0; index < source.rootEnd; index += 1) {
741
+ if (!source.lines[index]?.structural) continue;
742
+ const span = sourceAssignmentSpan(source.lines, index, source.rootEnd);
743
+ if (!span) continue;
744
+ keys.add(span.key);
745
+ index = span.end - 1;
746
+ }
747
+ return keys;
748
+ }
749
+
750
+ /** First path segment of every table header in a generated document. */
751
+ function topLevelTableNamesOf(content: string): Set<string> {
752
+ const names = new Set<string>();
753
+ for (const line of rootSourceLines(content).lines) {
754
+ if (!line.structural || !/^\s*\[/.test(line.text)) continue;
755
+ try {
756
+ const name = Object.keys(Bun.TOML.parse(line.text))[0];
757
+ if (name !== undefined) names.add(name);
758
+ } catch { /* the template only writes valid headers */ }
759
+ }
760
+ return names;
761
+ }
762
+
675
763
  export function chooseCatalogPathForInjection(
676
764
  content: string,
677
765
  requested?: string | null,
@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
2
2
  import type { OcxConfig } from "../../types";
3
3
  import { ConfigWriteDestinationChanged, type LockHandle } from "../config-write-lock";
4
4
  import { CODEX_CONFIG_PATH } from "../paths";
5
+ import type { CodexCliSelectionAsyncParentWrite } from "../cli-update-selection-gate";
5
6
 
6
7
  /**
7
8
  * Reconcile the native `features.multi_agent_v2` override when an injection carries an
@@ -17,7 +18,7 @@ import { CODEX_CONFIG_PATH } from "../paths";
17
18
  */
18
19
  export type InjectedV1SurfaceReconcile =
19
20
  | { ok: true; content: string; changed: boolean }
20
- | { ok: false; message: string };
21
+ | { ok: false; message: string; retryable?: boolean };
21
22
 
22
23
  let toggleForTests: ((enabled: boolean, env: NodeJS.ProcessEnv, validateBeforeSpawn: () => void) => void) | undefined;
23
24
 
@@ -44,6 +45,9 @@ export interface PreparedV1SurfaceReconcile {
44
45
  * only — `run()` re-checks the flag on the bytes present under the lock.
45
46
  */
46
47
  readonly enabledAtPrepare: boolean;
48
+ /** Acquire before the config lock; an already-v1 home needs no selection lease. */
49
+ admit(): Promise<boolean>;
50
+ release(): void;
47
51
  /**
48
52
  * `heldConfigWriteLock` is the injector's own held write-lock handle: the
49
53
  * transition would otherwise re-acquire the same file and refuse itself.
@@ -74,17 +78,39 @@ export async function prepareInjectedV1SurfaceReconcile(
74
78
  toggle = (enabled, env, validate) => runCodexFeaturesCommand(enabled ? "enable" : "disable", "multi_agent_v2", env, validate);
75
79
  }
76
80
  const resolvedToggle = toggle;
81
+ const { beginCodexCliSelectionParentWriteAsync, CodexCliSelectionMutationBusyError } = await import("../cli-update-selection-gate");
82
+ let selection: CodexCliSelectionAsyncParentWrite | undefined;
83
+ const busy = (): InjectedV1SurfaceReconcile => ({
84
+ ok: false, retryable: true,
85
+ message: "Codex config injection refused: the v1 transition has no current CLI selection admission. Retry the injection after the CLI update finishes.",
86
+ });
77
87
  return {
78
88
  enabledAtPrepare,
89
+ async admit() {
90
+ if (!enabledAtPrepare) return true;
91
+ if (selection) return selection.entered;
92
+ selection = await beginCodexCliSelectionParentWriteAsync();
93
+ return selection.entered;
94
+ },
95
+ release() { selection?.exit(); },
79
96
  run(heldConfigWriteLock) {
80
97
  // Decide on the bytes present NOW, under the lock — the prepare-time
81
98
  // answer is stale the moment another writer could have touched the file.
82
99
  if (!isMultiAgentV2Enabled()) {
83
100
  return { ok: true, content: readFileSync(CODEX_CONFIG_PATH, "utf-8"), changed: false };
84
101
  }
85
- const transition = transitionMultiAgentV2(false, resolvedToggle, {
86
- ...(heldConfigWriteLock !== undefined ? { heldConfigWriteLock } : {}),
87
- });
102
+ // A prepare-time no-op may have become a transition. Refuse without a child;
103
+ // a fresh pass can acquire admission before taking the config lock.
104
+ if (!selection?.entered) return busy();
105
+ let transition: ReturnType<typeof transitionMultiAgentV2>;
106
+ try {
107
+ transition = selection.commit(() => transitionMultiAgentV2(false, resolvedToggle, {
108
+ ...(heldConfigWriteLock !== undefined ? { heldConfigWriteLock } : {}),
109
+ }));
110
+ } catch (error) {
111
+ if (error instanceof CodexCliSelectionMutationBusyError) return busy();
112
+ throw error;
113
+ }
88
114
  if (!transition.ok) {
89
115
  if (transition.retryable === false) throw new ConfigWriteDestinationChanged(transition.error);
90
116
  return {
@@ -9,6 +9,7 @@
9
9
  * post-transition bytes is what keeps the committed file from re-enabling the
10
10
  * flag the reconcile just turned off.
11
11
  */
12
+ import { existsSync, readFileSync } from "node:fs";
12
13
  import { websocketsEnabled } from "../../config";
13
14
  import {
14
15
  HISTORY_RELABEL_STANDS_DOWN,
@@ -22,7 +23,7 @@ import {
22
23
  journaledReplacedRootWebSearch,
23
24
  } from "../journal";
24
25
  import { stripJournaledOpenaiBaseUrl } from "../injected-marker";
25
- import { CODEX_CONFIG_PATH, resolveCodexStateDbPath } from "../paths";
26
+ import { CODEX_CONFIG_PATH, CODEX_PROFILE_PATH, resolveCodexStateDbPath } from "../paths";
26
27
  import { transformManagedSubagentDefaults, type WrittenSubagentDefaults } from "../subagent-defaults";
27
28
  import type { OcxConfig } from "../../types";
28
29
  import type { CodexWriteCandidate } from "../write-coordination";
@@ -35,6 +36,7 @@ import {
35
36
  ensureFastModeFeature,
36
37
  ensureRootWebSearchDisabled,
37
38
  normalizeServiceTier,
39
+ preserveUnmanagedProfileKeys,
38
40
  removeProfileSection,
39
41
  setRootModelCatalogPath,
40
42
  setRootModelProvider,
@@ -71,6 +73,11 @@ export interface CodexInjectionPlanOk {
71
73
  content: string;
72
74
  /** The exact string about to replace the profile file. */
73
75
  profileContent: string;
76
+ /**
77
+ * The profile bytes `profileContent` preserved keys from (null when absent).
78
+ * Re-checked under the write lock so an edit landing meanwhile is not overwritten.
79
+ */
80
+ profileSource: string | null;
74
81
  /** The resolved catalog path, never the raw option. */
75
82
  catalogPath: string | null;
76
83
  providerTableMode: boolean;
@@ -323,12 +330,16 @@ export function deriveCodexInjectionPlan(
323
330
  managedDefaultsMessage = ` ⚠️ ${nativeSubagentDefaultsWarning}\n`;
324
331
  }
325
332
 
326
- const profileContent = buildProfileFileForTarget(
327
- routingTarget,
328
- catalogPath,
329
- websocketsForRoutingTarget(config, routingTarget),
330
- config?.fastMode,
331
- config?.codexProviderDisplayName,
333
+ const profileSource = readCodexProfileSource();
334
+ const profileContent = preserveUnmanagedProfileKeys(
335
+ profileSource,
336
+ buildProfileFileForTarget(
337
+ routingTarget,
338
+ catalogPath,
339
+ websocketsForRoutingTarget(config, routingTarget),
340
+ config?.fastMode,
341
+ config?.codexProviderDisplayName,
342
+ ),
332
343
  );
333
344
  content = applyEol(content, eol);
334
345
 
@@ -395,6 +406,7 @@ export function deriveCodexInjectionPlan(
395
406
  baselineContent,
396
407
  content,
397
408
  profileContent,
409
+ profileSource,
398
410
  catalogPath,
399
411
  providerTableMode,
400
412
  keepRootOverrideAlongsideTable,
@@ -414,3 +426,18 @@ export function deriveCodexInjectionPlan(
414
426
  },
415
427
  };
416
428
  }
429
+
430
+
431
+ /**
432
+ * Current profile bytes, or null when absent. Read directly: a profile removed between an
433
+ * existence check and the read is simply absent. If it reappears before the write lock, the
434
+ * lock-time comparison refuses retryably; other read errors propagate.
435
+ */
436
+ export function readCodexProfileSource(): string | null {
437
+ try {
438
+ return readFileSync(CODEX_PROFILE_PATH, "utf-8");
439
+ } catch (error) {
440
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
441
+ return null;
442
+ }
443
+ }
@@ -189,6 +189,9 @@ export function captureCodexPreImages(): CodexPreImages {
189
189
  };
190
190
  }
191
191
 
192
+ /** The profile bytes one injection published, set just before it writes them. */
193
+ export interface CodexProfilePublish { published?: string }
194
+
192
195
  /**
193
196
  * How many transactions of evidence the ledger keeps.
194
197
  *
@@ -366,10 +369,16 @@ export function recordCodexNativeTransactionProvenance(
366
369
  *
367
370
  * Every surface is attempted even after one fails: a second failure is worth
368
371
  * knowing about, and stopping early would leave more unrestored than necessary.
372
+ *
373
+ * `profilePublish`, when given, limits the profile surface to bytes this
374
+ * operation wrote: it is reverted only if `published` is set and the file still
375
+ * holds exactly those bytes. A refusal before the publish, or a profile another
376
+ * writer replaced since, is left as it is.
369
377
  */
370
378
  export function restoreCodexPreImages(
371
379
  pre: CodexPreImages,
372
380
  heldConfigWriteLock?: LockHandle,
381
+ profilePublish?: CodexProfilePublish,
373
382
  ): { complete: boolean; unrestored: readonly string[] } {
374
383
  const locked = withConfigWriteLockHeld(CODEX_CONFIG_PATH, heldConfigWriteLock, held => {
375
384
  const unrestored: string[] = [];
@@ -382,6 +391,8 @@ export function restoreCodexPreImages(
382
391
  // The current journal remains recovery authority until both artifacts are restored.
383
392
  if (name === "journal" && unrestored.length > 0) { unrestored.push(name); continue; }
384
393
  try {
394
+ if (name === "profile" && profilePublish
395
+ && (profilePublish.published === undefined || readOrNull(path) !== profilePublish.published)) continue;
385
396
  publishCodexArtifact(path, held, (destination, hooks) => {
386
397
  if (bytes === null) {
387
398
  hooks.validateBeforeRename?.(destination);
@@ -25,6 +25,7 @@ import {
25
25
  captureCodexPreImages,
26
26
  codexInjectLockOutcome,
27
27
  codexWriteCoordinationEligibility,
28
+ type CodexProfilePublish,
28
29
  CodexPartialWriteError,
29
30
  CodexWriteConflictError,
30
31
  DEFAULT_INJECT_LOCK_TIMEOUT_MS,
@@ -82,6 +83,7 @@ import {
82
83
  deriveCodexInjectionPlan,
83
84
  type CodexInjectionPlanContext,
84
85
  type CodexInjectionPlanOk,
86
+ readCodexProfileSource,
85
87
  } from "./inject/plan";
86
88
 
87
89
  export { effectiveLoopbackListenerPort, isLoopbackHostname, shouldInjectApiAuthHeader } from "./loopback-target";
@@ -378,9 +380,7 @@ async function injectCodexConfigImpl(
378
380
  && rootTomlString(nativeInput, REALTIME_WS_BASE_URL_KEY) === journaledRealtimeWsBaseUrl);
379
381
  return !hasInjectedCodexRouting(nativeInput) && !looksInjectedByValue;
380
382
  };
381
- const readCurrentProfile = (): string | null => existsSync(CODEX_PROFILE_PATH)
382
- ? readFileSync(CODEX_PROFILE_PATH, "utf-8")
383
- : null;
383
+ const readCurrentProfile = readCodexProfileSource;
384
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.";
385
385
  // When the reconcile will rewrite config.toml under the lock, the baseline it
386
386
  // must be journaled against does not exist yet — this check runs inside the
@@ -440,13 +440,15 @@ async function injectCodexConfigImpl(
440
440
  message: "Codex config injection refused: config.toml changed while the write lock was being acquired. Retry to inject on the latest bytes.",
441
441
  });
442
442
  }
443
+ // The profile carries unmanaged root keys from the bytes the plan read; a profile edit since then would be overwritten.
444
+ if (readCurrentProfile() !== admittedPlan.profileSource) throw new CodexInjectRefusal({ success: false, retryable: true, message: "Codex config injection refused: opencodex.config.toml changed while the write lock was being acquired. Retry to inject on the latest bytes." });
443
445
  if (missingConfig) publishCodexArtifact(CODEX_CONFIG_PATH, heldConfigWriteLock, (_path, hooks) => { hooks.validateBeforeRename?.(CODEX_CONFIG_PATH); createEmptyCodexConfigInBoundary(); hooks.afterRename?.(CODEX_CONFIG_PATH); });
444
446
  let nativeInput = rawContent;
445
447
  let plan = admittedPlan;
446
448
  if (v1Reconcile) {
447
449
  const reconciled = v1Reconcile.run(heldConfigWriteLock);
448
450
  if (!reconciled.ok) {
449
- throw new CodexInjectRefusal({ success: false, message: reconciled.message });
451
+ throw new CodexInjectRefusal({ success: false, message: reconciled.message, retryable: reconciled.retryable });
450
452
  }
451
453
  nativeInput = reconciled.content;
452
454
  if (reconciled.content !== rawContent) {
@@ -490,6 +492,7 @@ async function injectCodexConfigImpl(
490
492
  publishCodexArtifact(CODEX_CONFIG_PATH, heldConfigWriteLock, (path, hooks) => atomicWriteFile(path, plan.content, undefined, hooks));
491
493
  historyArtifactStageForTests?.("after-config");
492
494
  assertCodexHomeOwner(getCodexHome());
495
+ profilePublish.published = plan.profileContent;
493
496
  publishCodexArtifact(CODEX_PROFILE_PATH, heldConfigWriteLock, (path, hooks) => atomicWriteFile(path, plan.profileContent, undefined, hooks));
494
497
  publishCodexArtifact(JOURNAL_PATH, heldConfigWriteLock, (_path, hooks) => markJournalInjectedState(plan.content, plan.profileContent, {
495
498
  // A root override is ours whenever we wrote one and no user-owned value won. That is
@@ -529,6 +532,7 @@ async function injectCodexConfigImpl(
529
532
  * legacy-uncoordinated home, which publishes no transition to resolve.
530
533
  */
531
534
  let transitionReceipt: { nativeGeneration: number; currentTxId: string } | undefined;
535
+ const profilePublish: CodexProfilePublish = {}; // rollback reverts only profile bytes this operation published
532
536
 
533
537
  /*
534
538
  * The file-level write lock every config.toml writer shares (see
@@ -548,6 +552,10 @@ async function injectCodexConfigImpl(
548
552
  */
549
553
  let effectivePlan: CodexInjectionPlanOk = admittedPlan;
550
554
 
555
+ if (v1Reconcile && !await v1Reconcile.admit()) {
556
+ return { success: false, retryable: true, message: "Codex config injection refused: the CLI selection is busy. Retry after the CLI update finishes." };
557
+ }
558
+ try {
551
559
  const configLock = await acquireConfigWriteLock(CODEX_CONFIG_PATH, {
552
560
  timeoutMs: Math.min(options.lockTimeoutMs ?? CONFIG_WRITE_LOCK_WAIT_MS, CONFIG_WRITE_LOCK_WAIT_MS),
553
561
  });
@@ -590,7 +598,7 @@ async function injectCodexConfigImpl(
590
598
  effectivePlan = resolved.plan;
591
599
  } catch (error) {
592
600
  if (error instanceof ConfigWriteDestinationChanged || codexHomeOwnerBlocksCompensation(getCodexHome(), error)) throw error;
593
- const restored = restoreCodexPreImages(preImages, heldConfigWriteLock);
601
+ const restored = restoreCodexPreImages(preImages, heldConfigWriteLock, profilePublish);
594
602
  if (!restored.complete) throw new CodexPartialWriteError(restored.unrestored);
595
603
  throw error;
596
604
  }
@@ -610,7 +618,7 @@ async function injectCodexConfigImpl(
610
618
  ...(eligibility.kind === "adopt" ? { adoption: { direction: "apply" as const } } : {}),
611
619
  onPostCallbackFailure: () => {
612
620
  if (!coordinatedPreImages) throw new Error("Codex injection preimages were not captured.");
613
- const restored = restoreCodexPreImages(coordinatedPreImages, heldConfigWriteLock);
621
+ const restored = restoreCodexPreImages(coordinatedPreImages, heldConfigWriteLock, profilePublish);
614
622
  if (!restored.complete) throw new CodexPartialWriteError(restored.unrestored);
615
623
  },
616
624
  admitted: { authoritySnapshotId: witness.comparisonId },
@@ -687,7 +695,7 @@ async function injectCodexConfigImpl(
687
695
  if (error instanceof ConfigWriteDestinationChanged || codexHomeOwnerBlocksCompensation(getCodexHome(), error)) throw error;
688
696
  // Compensate, then ALWAYS throw. Returning a partial result would let the
689
697
  // lock commit a row describing an apply that did not finish.
690
- const restored = restoreCodexPreImages(preImages, heldConfigWriteLock);
698
+ const restored = restoreCodexPreImages(preImages, heldConfigWriteLock, profilePublish);
691
699
  if (!restored.complete) {
692
700
  throw new CodexPartialWriteError(restored.unrestored);
693
701
  }
@@ -725,6 +733,9 @@ async function injectCodexConfigImpl(
725
733
  releaseConfigWriteLock(configLock.handle);
726
734
  heldConfigWriteLock = undefined;
727
735
  }
736
+ } finally {
737
+ v1Reconcile?.release();
738
+ }
728
739
  // Both write paths have committed, including the coordinator's post-callback checks.
729
740
  // Compare against the admitted original, not post-v1-reconcile input: the native
730
741
  // feature transition is part of this transaction too. Refusals/rollbacks return
@@ -0,0 +1,72 @@
1
+ import { createHmac, randomBytes } from "node:crypto";
2
+ import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { getConfigDir } from "../config/paths";
5
+ import { assertNotRealHomeUnderTest } from "../lib/test-home-guard";
6
+ import { hardenSecretDir, hardenSecretPath } from "../lib/windows-secret-acl";
7
+
8
+ const SECRET_BYTES = 32;
9
+ const DOMAIN = "opencodex-codex-installation-id-v1\0";
10
+
11
+ /** Sanitized, retryable refusal: neither a path nor a credential belongs in its cause. */
12
+ export class CodexInstallationIdUnavailableError extends Error {
13
+ constructor() {
14
+ super("Codex installation identity unavailable");
15
+ this.name = "CodexInstallationIdUnavailableError";
16
+ }
17
+ }
18
+
19
+ function readSecret(path: string): Buffer {
20
+ // Refuse links and non-files; never rotate an unreadable or corrupt persisted secret.
21
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
22
+ try {
23
+ const stat = fstatSync(fd);
24
+ if (!stat.isFile() || stat.size !== SECRET_BYTES) throw new CodexInstallationIdUnavailableError();
25
+ if (process.platform !== "win32") fchmodSync(fd, 0o600);
26
+ hardenSecretPath(path, { required: true });
27
+ const bytes = readFileSync(fd);
28
+ if (bytes.length !== SECRET_BYTES) throw new CodexInstallationIdUnavailableError();
29
+ return bytes;
30
+ } finally { closeSync(fd); }
31
+ }
32
+
33
+ function installationSecret(dir: string): Buffer {
34
+ assertNotRealHomeUnderTest(dir);
35
+ // Each secret file gets its own required, inheritance-protected DACL before reading or
36
+ // writing bytes. Optional parent/sibling hardening cannot admit or refuse this file.
37
+ const path = join(dir, "codex-installation-secret");
38
+ try { return readSecret(path); } catch (error) {
39
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
40
+ }
41
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
42
+ // Make new files private at creation: Windows ignores POSIX mode 0600.
43
+ hardenSecretDir(dir, { required: true });
44
+ // Publish complete bytes without replacing another process's winning secret.
45
+ const temporary = join(dir, `.codex-installation-secret-${randomBytes(16).toString("hex")}`);
46
+ const fd = openSync(temporary, "wx", 0o600);
47
+ try {
48
+ try {
49
+ hardenSecretPath(temporary, { required: true });
50
+ writeFileSync(fd, randomBytes(SECRET_BYTES));
51
+ fsyncSync(fd);
52
+ } finally { closeSync(fd); }
53
+ try { linkSync(temporary, path); } catch (error) {
54
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
55
+ }
56
+ return readSecret(path);
57
+ } finally { unlinkSync(temporary); }
58
+ }
59
+
60
+ /** Stable per upstream account and local installation, independent of bearer/caller identity. */
61
+ export function codexInstallationIdForAccount(accountKey: string, configDir = getConfigDir()): string {
62
+ try {
63
+ const account = accountKey.trim();
64
+ if (!account) throw new CodexInstallationIdUnavailableError();
65
+ const bytes = createHmac("sha256", installationSecret(configDir)).update(DOMAIN).update(account).digest().subarray(0, 16);
66
+ // RFC 9562 §5.4 layout; pseudorandom HMAC bits replace per-request randomness.
67
+ bytes[6] = (bytes[6]! & 0x0f) | 0x40;
68
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;
69
+ const hex = bytes.toString("hex");
70
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
71
+ } catch { throw new CodexInstallationIdUnavailableError(); }
72
+ }
@@ -31,12 +31,10 @@
31
31
  * posture as the affinity key itself. Two callers presenting identical thread ids can never read
32
32
  * each other's lineage, and no raw identifier or durable hash is stored.
33
33
  *
34
- * LIFETIME, stated plainly because the word "affinity" invites the opposite assumption: none of
35
- * this survives the process. The binding map is in memory, and the HMAC key above is fresh random
36
- * bytes taken at module load, so a restart does not merely forget the table -- it makes yesterday's
37
- * keys unreproducible. This is a warm-start hint for the life of one proxy process, never durable
38
- * account ownership, and nothing here should be read as a promise to a conversation that outlives
39
- * a restart.
34
+ * LIFETIME: lineage records and their keys remain process-local. The HMAC key is fresh random
35
+ * bytes taken at module load, so yesterday's keys cannot be reproduced after a restart. An
36
+ * affinity store may persist separate digests of cohort anchors under its own secret; it must
37
+ * never persist these process-local keys.
40
38
  *
41
39
  * The one upgrade that is neither a fresh start nor an untouched process is a code swap under a
42
40
  * live conversation, where the binding map is still populated with entries made under the
@@ -50,6 +48,12 @@ import { retainedUtf8Bytes } from "../lib/admission";
50
48
 
51
49
  const CODEX_LINEAGE_COMPONENT_MAX_BYTES = 512;
52
50
  const CODEX_LINEAGE_KEY = randomBytes(32);
51
+ let conversationAnchorObserver: ((key: string, familyId: string, threadId: string) => void) | undefined;
52
+
53
+ /** Register the consumer of derived cohort anchors, or remove it. */
54
+ export function setCodexConversationAnchorObserver(fn?: (key: string, familyId: string, threadId: string) => void): void {
55
+ conversationAnchorObserver = fn;
56
+ }
53
57
 
54
58
  /**
55
59
  * Mirrors `CODEX_THREAD_AFFINITY_IDLE_TTL_MS` in ./routing. Deliberately duplicated rather than
@@ -149,12 +153,14 @@ function boundedLineageComponent(value: string | null): string | undefined {
149
153
  * byte-identical to the key the thread actually binds under.
150
154
  */
151
155
  export function codexConversationKeyFor(familyId: string, threadId: string): string {
152
- return `app:${createHmac("sha256", CODEX_LINEAGE_KEY)
156
+ const key = `app:${createHmac("sha256", CODEX_LINEAGE_KEY)
153
157
  .update("opencodex-app-pool-affinity-v1\0")
154
158
  .update(familyId)
155
159
  .update("\0")
156
160
  .update(threadId)
157
161
  .digest("base64url")}`;
162
+ conversationAnchorObserver?.(key, familyId, threadId);
163
+ return key;
158
164
  }
159
165
 
160
166
  /**
@@ -38,7 +38,7 @@ type QuotaDiskFile = {
38
38
 
39
39
  type MainPolicyQuota = { identityKey: string; quota: StoredAccountQuota };
40
40
  /** Fresh WHAM topology proof is consumed by the merge, never retained in a cache or DTO. */
41
- type MainPolicyQuotaObservation = Omit<StoredAccountQuota, "updatedAt"> & { shortWindowAbsent?: true };
41
+ type MainPolicyQuotaObservation = Omit<StoredAccountQuota, "updatedAt"> & { shortWindowAbsent?: true; monthlyWindowAbsent?: true };
42
42
  let mainPolicyQuota: MainPolicyQuota | null = null;
43
43
  let diskHydrated = false;
44
44
  let persistTimer: ReturnType<typeof setTimeout> | null = null;
@@ -343,9 +343,12 @@ export function setAccountQuotaFromParsed(
343
343
  // Retiring a short tuple releases a routing block, so it needs the same writer proof as
344
344
  // history: a live main writer for main, a live captured pool writer for pool requests.
345
345
  const mayRetireShort = isMain ? mainWriter !== undefined : livePoolEvidence;
346
- const displayQuota: MainPolicyQuotaObservation = mayRetireShort && policyQuota?.shortWindowAbsent === true
347
- ? { ...quota, shortWindowAbsent: true }
348
- : quota;
346
+ // Monthly-window absence (#8067) comes from the same complete topology and needs the same proof.
347
+ const displayQuota: MainPolicyQuotaObservation = {
348
+ ...quota,
349
+ ...(mayRetireShort && policyQuota?.shortWindowAbsent === true ? { shortWindowAbsent: true as const } : {}),
350
+ ...(mayRetireShort && policyQuota?.monthlyWindowAbsent === true ? { monthlyWindowAbsent: true as const } : {}),
351
+ };
349
352
  const next = mergeAccountQuota(displayQuota, legacyExisting, updatedAt);
350
353
  accountQuota.set(accountId, next);
351
354
  if (isMain) {
@@ -448,8 +451,11 @@ function mergeAccountQuota(
448
451
  // while silently dropping `monthlyIsPrimaryWindow` would look like tertiary-only data to
449
452
  // any future reader, and that failure would be invisible.
450
453
  if (quota.monthlyIsPrimaryWindow === true) next.monthlyIsPrimaryWindow = true;
451
- } else if ((snapshotHasWeekly(quota) || snapshotHasShort(quota) || snapshotHasCustom(quota))
454
+ } else if (quota.monthlyWindowAbsent !== true
455
+ && (snapshotHasWeekly(quota) || snapshotHasShort(quota) || snapshotHasCustom(quota))
452
456
  && existing?.monthlyPercent !== undefined) {
457
+ // A complete topology with no monthly-length window retires the carried tuple, so a plan
458
+ // change away from a monthly primary (Free to Pro Lite) cannot keep its old exhausted reading.
453
459
  next.monthlyPercent = existing.monthlyPercent;
454
460
  if (existing.monthlyResetAt !== undefined) next.monthlyResetAt = existing.monthlyResetAt;
455
461
  if (existing.monthlyIsPrimaryWindow === true) next.monthlyIsPrimaryWindow = true;
@@ -991,7 +997,17 @@ export function poolWhamPolicyObservation(
991
997
  }
992
998
  const malformed = readings.some(window => window?.used_percent != null
993
999
  && normalizeUsagePercent(window.used_percent) === undefined);
994
- return data.rate_limit?.allowed === false || malformed ? quota : withWhamShortWindowAbsence(data, quota);
1000
+ if (data.rate_limit?.allowed === false || malformed) return quota;
1001
+ const observation = withWhamShortWindowAbsence(data, quota);
1002
+ // #8067: the same complete topology proves a pool account has no monthly window when no window
1003
+ // declares a monthly duration and no tertiary window is present, so a plan change away from a
1004
+ // monthly primary (Free to Pro Lite) retires the carried tuple. Pool-only: main observations
1005
+ // keep their existing retention rules.
1006
+ const [primary, secondary, tertiary] = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
1007
+ return observation.shortWindowAbsent === true
1008
+ && !isExplicitMonthlyWindow(primary) && !isExplicitMonthlyWindow(secondary) && tertiary == null
1009
+ ? { ...observation, monthlyWindowAbsent: true }
1010
+ : observation;
995
1011
  }
996
1012
 
997
1013
  function isMeasuredLongWindow(window: WhamUsageWindow | null | undefined): boolean {
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The namespace of caller-owned affinity keys, kept in a module with no imports so that stores
3
+ * which must refuse these keys (the durable Codex pool affinity store) can test for them without
4
+ * importing the routing modules that request-owned affinity itself depends on.
5
+ */
6
+ export const REQUEST_OWNED_AFFINITY_KEY_PREFIX = "request-owned:v1:";
7
+
8
+ /** Identify namespace keys that must remain process-local. */
9
+ export function isRequestOwnedAffinityKey(value: string): boolean {
10
+ return value.startsWith(REQUEST_OWNED_AFFINITY_KEY_PREFIX);
11
+ }