From a0e51d880c1bb6715ae38454af36b1086612e7c8 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 11 Nov 2026 20:36:59 +0900 Subject: [PATCH 1/4] fix(cli): wait once for the config-root ACL flight before a CLI command writes On Windows, loadConfig() starts an unawaited icacls harden of the config root, and its inheritance work can drop a grant a concurrent writer just applied. Admitted writers already wait for it; the synchronous writers a CLI command reaches first did not (#7815). Per the owner decision, runCli now starts the flight and drains it under one ACL deadline before the version-skew notice, the shim preflight and the command, proceeding even on timeout. Read-only, hot-path and validate-first commands (skipsCodexShimAutoRestore), internal helpers and the long-lived server are skipped. The server's synchronous writers stay synchronous; structure/config.md now names that and every other residual risk. Closes #7815 --- scripts/test-layout/layout-clients.json | 1 + src/cli/config-root-startup.ts | 31 +++++ src/cli/root.ts | 4 + structure/config.md | 2 +- tests/fixtures/test-layout-expected.json | 1 + .../windows-cli-config-root-startup.test.ts | 108 ++++++++++++++++++ 6 files changed, 146 insertions(+), 1 deletion(-) create mode 100644 src/cli/config-root-startup.ts create mode 100644 tests/windows/windows-cli-config-root-startup.test.ts diff --git a/scripts/test-layout/layout-clients.json b/scripts/test-layout/layout-clients.json index 9eab95873c5..b9015aa8469 100644 --- a/scripts/test-layout/layout-clients.json +++ b/scripts/test-layout/layout-clients.json @@ -5,6 +5,7 @@ "claude-translated-tool-restrictions.test.ts": "claude-integration", "windows-config-root-async-writers.test.ts": "windows", "windows-config-root-integration-writers.test.ts": "windows", + "windows-cli-config-root-startup.test.ts": "windows", "t3code-client-lifecycle.test.ts": "clients", "fix-jsonc-cr-comments.test.ts": "lib", "fix-jsonc-empty-comma.test.ts": "lib", diff --git a/src/cli/config-root-startup.ts b/src/cli/config-root-startup.ts new file mode 100644 index 00000000000..61feab81e3b --- /dev/null +++ b/src/cli/config-root-startup.ts @@ -0,0 +1,31 @@ +import { getConfigDir, hardenConfigDir, withConfigDirHardeningSettled } from "../config/paths"; +import { WindowsSecretAclSettleTimeoutError, windowsSecretAclApplies } from "../lib/windows-secret-acl"; +import { skipsCodexShimAutoRestore } from "./codex-shim-autorestore"; + +/** + * Wait once, before a CLI command does its first write, for the optional config-root ACL flight + * (#7815). On Windows, loadConfig() starts an unawaited icacls harden of the config root, and its + * inheritance work can drop a grant a concurrent writer just applied. Admitted writers already + * wait for it themselves; this covers the synchronous writers a CLI command reaches before them. + * + * Skipped where waiting would itself be the side effect or the delay matters: + * - the commands skipsCodexShimAutoRestore exempts from preflight repair (read-only, hot-path + * and validate-first commands). Adding a command there also removes this wait for it; + * - every "internal" helper, launched by other processes on hot paths; + * - "start", the long-lived server: the wait would run before Bun.serve and spend up to one ACL + * deadline of fixed startup budgets (update-restart marker, ensure readiness, Desktop cold + * start, service start timeouts). The server's synchronous writers are documented residual. + * + * Bounded by one ACL deadline, which also drains timed-out icacls children. A timeout lets the + * command proceed: writers that admit through withConfigDirHardeningSettled still refuse alone. + */ +export async function settleConfigRootForCli(command: string | undefined, args: readonly string[]): Promise { + if (!windowsSecretAclApplies()) return; + if (command === "start" || command === "internal" || skipsCodexShimAutoRestore(command, [...args])) return; + hardenConfigDir(); + try { + await withConfigDirHardeningSettled(getConfigDir(), () => undefined); + } catch (error) { + if (!(error instanceof WindowsSecretAclSettleTimeoutError)) throw error; + } +} diff --git a/src/cli/root.ts b/src/cli/root.ts index 9d39f9aa7d1..9628af27afc 100644 --- a/src/cli/root.ts +++ b/src/cli/root.ts @@ -19,6 +19,7 @@ import { findCommand } from "./registry"; import { printUnknownCommand } from "./help-recovery"; import { noteCredentialArgv, redactSecretArgs } from "./secret-args"; import { maybeNoticeVersionSkew } from "./version-skew-notice"; +import { settleConfigRootForCli } from "./config-root-startup"; import { isOrchestratedUpdateArgv } from "../update/orchestrated-arguments.mjs"; export interface CliHead { @@ -161,6 +162,9 @@ export async function runCli(argv: string[]): Promise { process.exit(SYNC_EXPECTATION_USAGE_EXIT); } } + // Before any preflight or command write: wait once for the config-root ACL flight (#7815). + // Commands skipsCodexShimAutoRestore exempts are skipped there too; see config-root-startup. + await settleConfigRootForCli(head.command, head.args); await maybeNoticeVersionSkew(head.command, head.args); await maybeAutoRestoreCodexShimAsync(head.command, head.args); return head; diff --git a/structure/config.md b/structure/config.md index 8b8eb60293c..02dcb872e08 100644 --- a/structure/config.md +++ b/structure/config.md @@ -62,7 +62,7 @@ test seam and the mutation types remain re-exported through `src/config.ts`. Suc `src/config/paths.ts` owns `OPENCODEX_HOME` expansion and resolution, the config directory and `config.json` path. A relative home is resolved once per distinct raw environment value, so a later working-directory change cannot silently move the active installation. Config reads in this leaf and `src/config/load-degrade.ts` use NTFS ACLs on Windows and private POSIX modes elsewhere. Optional directory hardening follows directory symlinks/junctions but skips non-directory or unstatable targets before starting chmod or ACL work. Windows reads omit `chmod` before ACL hardening so repeated loads preserve successful object/freshness observations; external metadata changes still invalidate them. Directory flights keep their existing flush/reap lifecycle, and file/required-write failure policy is unchanged. `tests/windows/windows-config-read-acl-memo.test.ts` covers repeated loads, non-directory and directory-link behavior, external invalidation and POSIX permissions. -`withConfigDirHardeningSettled` in `src/config/paths.ts` admits synchronous mutation after the last unrelated await. Its registry includes the optional config flight, ancestors and retained timeout children; one existing ACL deadline bounds admission, including newly overlapping work. Expiry throws sanitized `WindowsSecretAclSettleTimeoutError` (`ETIMEDOUT`) without running the writer or dropping child cleanup ownership. The final empty-registry check and callback share one turn, with no await in the callback. Intercept/picker CA, token, cleanup, profile and snapshot phases re-enter after trust/discovery awaits. Config saves in `src/server/management/agent-settings-routes.ts` and `src/server/management/config-routes.ts`, Desktop intent/mode commits in `src/server/management/native-integration-routes.ts`, and gateway publication/cleanup in those routes and `src/cli/ensure-desired-integrations.ts` use the same admission. `src/cli/claude-desktop.ts` admits local profile/mode commits and the complete remote-store transaction again after hub download. Lifecycle/config locks are acquired inside admission; refresh re-read, mode/freshness checks, profile and marker publication share one callback. Live setting edits and their save/publication share the admitted synchronous callback; a refused admission leaves both live and durable state untouched. Ordered post-commit phases preserve applied-state warnings or settled compensation, including mode/fingerprint marker refusal and retained CLI intent after incomplete rollback. Synchronous leaf APIs retain their contracts. `tests/claude-integration/claude-config-root-writer-barrier.test.ts` holds parent flights and drives refusal deadlines without sleeps. Lexical/canonical aliases and uncertain identities drain conservatively; removal keeps its separate at-or-below scope and actual-exit requirement. Async local config commands (`src/cli/config-command.ts`, `src/cli/effort.ts`, `src/cli/models.ts`, `src/cli/provider.ts`) admit complete synchronous read/validate/save phases through `withConfigDirHardeningSettled`. Preliminary model selection and client-connection diagnostics use passive observations that cannot publish recovery copies. Final authority and recovery publication are re-read inside admission without starting optional hardening. `src/cli/config-mutation.ts` refuses invalid or unreadable authority, including array/non-object roots rejected before defaults repair, with `CliUsageError`; full-config commands retain fresh-install initialization when the file is absent, while set/unset retain the persisted mutation owner's missing-file refusal. Custom-model removal revalidates the confirmed row by identity and contents while retaining current siblings. Import reads its input and checks its target inside admission. Provider-add credential cleanup shares the synchronous post-save phase and retains its existing post-commit warning. Timeout leaves the mutation database and config untouched and follows existing CLI failure handling. `tests/windows/windows-config-root-async-writers.test.ts` covers held parent flights, deadline refusal, recovery copies, invalid authority and concurrent edits. Codex multi-agent management changes that can resolve a runtime additionally await fresh [selection admission](codex-cli-update.md#worker-realm-and-the-selection-commit-window) before entering this barrier, keep that owner across hardening, and re-evaluate the mode plan inside the synchronous callback; neither ACL wait is inserted into the callback, and refusal leaves the combined mutation untouched. Timer-driven caches under the config root admit their write the same way and build the snapshot inside the callback: the provider account quota cache (`src/providers/account-quota-disk.ts`), the Codex account quota cache (`src/codex/quota.ts`) and the reasoning support cache, while a models.dev refresh admits its publication after the network read (`src/providers/reasoning-metadata.ts`). A timed-out admission skips a best-effort cache write and fails that refresh unpublished, a joined refresh reports the same failure, and a cancel, clear or reset invalidates a write still waiting for admission (#7815; `tests/providers/provider-account-quota-persistence.test.ts`, `tests/codex-integration/reasoning-metadata.test.ts`). The integrations writer (`src/integrations/writer.ts`) runs every coordinated transaction (apply, refresh, overwrite, disable, restore; reached by the catalog fan-out, the Aside sync and profile routes, and integration routes) inside admission on its store root, with the store-lock re-probe in the same callback so no await separates it from the transaction; an admission timeout returns a `write_failed` refusal without a write. An async `revalidate` such as the Aside late confirmation check still runs before admission, so the wait sits between it and the transaction while the writer locks stay held. `disconnectClient` in `src/client/connect.ts` admits each of its two synchronous phases (a timeout before the second leaves the prepared receipt it resumes from), and key rotation admits both remote Desktop credential alignments that precede the hub commit; rollback and post-commit finalization keep their unadmitted paths (`tests/windows/windows-config-root-integration-writers.test.ts`). +`withConfigDirHardeningSettled` in `src/config/paths.ts` admits synchronous mutation after the last unrelated await. Its registry includes the optional config flight, ancestors and retained timeout children; one existing ACL deadline bounds admission, including newly overlapping work. Expiry throws sanitized `WindowsSecretAclSettleTimeoutError` (`ETIMEDOUT`) without running the writer or dropping child cleanup ownership. The final empty-registry check and callback share one turn, with no await in the callback. Intercept/picker CA, token, cleanup, profile and snapshot phases re-enter after trust/discovery awaits. Config saves in `src/server/management/agent-settings-routes.ts` and `src/server/management/config-routes.ts`, Desktop intent/mode commits in `src/server/management/native-integration-routes.ts`, and gateway publication/cleanup in those routes and `src/cli/ensure-desired-integrations.ts` use the same admission. `src/cli/claude-desktop.ts` admits local profile/mode commits and the complete remote-store transaction again after hub download. Lifecycle/config locks are acquired inside admission; refresh re-read, mode/freshness checks, profile and marker publication share one callback. Live setting edits and their save/publication share the admitted synchronous callback; a refused admission leaves both live and durable state untouched. Ordered post-commit phases preserve applied-state warnings or settled compensation, including mode/fingerprint marker refusal and retained CLI intent after incomplete rollback. Synchronous leaf APIs retain their contracts. `tests/claude-integration/claude-config-root-writer-barrier.test.ts` holds parent flights and drives refusal deadlines without sleeps. Lexical/canonical aliases and uncertain identities drain conservatively; removal keeps its separate at-or-below scope and actual-exit requirement. Async local config commands (`src/cli/config-command.ts`, `src/cli/effort.ts`, `src/cli/models.ts`, `src/cli/provider.ts`) admit complete synchronous read/validate/save phases through `withConfigDirHardeningSettled`. Preliminary model selection and client-connection diagnostics use passive observations that cannot publish recovery copies. Final authority and recovery publication are re-read inside admission without starting optional hardening. `src/cli/config-mutation.ts` refuses invalid or unreadable authority, including array/non-object roots rejected before defaults repair, with `CliUsageError`; full-config commands retain fresh-install initialization when the file is absent, while set/unset retain the persisted mutation owner's missing-file refusal. Custom-model removal revalidates the confirmed row by identity and contents while retaining current siblings. Import reads its input and checks its target inside admission. Provider-add credential cleanup shares the synchronous post-save phase and retains its existing post-commit warning. Timeout leaves the mutation database and config untouched and follows existing CLI failure handling. `tests/windows/windows-config-root-async-writers.test.ts` covers held parent flights, deadline refusal, recovery copies, invalid authority and concurrent edits. Codex multi-agent management changes that can resolve a runtime additionally await fresh [selection admission](codex-cli-update.md#worker-realm-and-the-selection-commit-window) before entering this barrier, keep that owner across hardening, and re-evaluate the mode plan inside the synchronous callback; neither ACL wait is inserted into the callback, and refusal leaves the combined mutation untouched. Timer-driven caches under the config root admit their write the same way and build the snapshot inside the callback: the provider account quota cache (`src/providers/account-quota-disk.ts`), the Codex account quota cache (`src/codex/quota.ts`) and the reasoning support cache, while a models.dev refresh admits its publication after the network read (`src/providers/reasoning-metadata.ts`). A timed-out admission skips a best-effort cache write and fails that refresh unpublished, a joined refresh reports the same failure, and a cancel, clear or reset invalidates a write still waiting for admission (#7815; `tests/providers/provider-account-quota-persistence.test.ts`, `tests/codex-integration/reasoning-metadata.test.ts`). The integrations writer (`src/integrations/writer.ts`) runs every coordinated transaction (apply, refresh, overwrite, disable, restore; reached by the catalog fan-out, the Aside sync and profile routes, and integration routes) inside admission on its store root, with the store-lock re-probe in the same callback so no await separates it from the transaction; an admission timeout returns a `write_failed` refusal without a write. An async `revalidate` such as the Aside late confirmation check still runs before admission, so the wait sits between it and the transaction while the writer locks stay held. `disconnectClient` in `src/client/connect.ts` admits each of its two synchronous phases (a timeout before the second leaves the prepared receipt it resumes from), and key rotation admits both remote Desktop credential alignments that precede the hub commit; rollback and post-commit finalization keep their unadmitted paths (`tests/windows/windows-config-root-integration-writers.test.ts`). The CLI also waits once at startup (`src/cli/config-root-startup.ts`, called from `runCli`'s command branch before the version-skew notice and Codex-shim preflight): on Windows it starts the optional config-root flight and drains it with `withConfigDirHardeningSettled(root, () => undefined)` under one ACL deadline, then proceeds even on timeout (`tests/windows/windows-cli-config-root-startup.test.ts`). It skips every command `skipsCodexShimAutoRestore` exempts (adding one there also drops this wait), every `internal` helper and `start`; for `start` the wait would spend up to one ACL deadline of fixed startup budgets before `Bun.serve`. Residual risk, accepted by owner decision for #7815: (1) only the first write is covered once a later atomic write invalidates the per-process ctime success memo and a later `loadConfig()` starts a new flight; admitted writers stay safe; (2) a fresh install has no directory to wait for, so the first `loadConfig()` after creating it starts a flight while later writers run; (3) a swallowed timeout can leave a retained icacls child running that synchronous writers may overlap; (4) paths that never reach `runCli` (the `start` service logger, the update-restart child, the health sentinel, MCP entrypoints) and the excluded writing commands (uninstall/remove, sync, orchestrated update, `disconnect --orphaned-token`, codex-shim install/uninstall, internal helpers) keep their previous overlap; (5) the server's synchronous writers (`saveConfig`, persisted mutation, management and GUI session tokens, service secrets, the spend-ledger lease, the link store) stay synchronous and can overlap a flight any `loadConfig()` starts; (6) every eligible CLI run on Windows pays one icacls run, because the success memo is per process and the compliant-ACL precheck is opt-in (`OPENCODEX_ACL_VERIFY_EXISTING`). The writers #7815 named are admitted: config saves and Desktop 3p publication (#7826), the remote Desktop store through `connect.ts` and `claude-desktop.ts` (#7826, #8532) and the integrations writer (#8532). `src/config/process-state.ts` derives `ocx.pid` and `runtime-port.json` from that resolved directory. Ordinary and connected-client runtimes publish their absolute relaunch command in the runtime record; older records can omit it. Tracked runtime inspection retains an omitted hostname as `undefined` for guarded stop's legacy-record check. It owns their byte-compatible writes, parsing, expected-PID filters, cheap liveness, full OCX command diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 7e6101b6bb2..add27ac6d94 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -26,6 +26,7 @@ "graceful-max-output-tokens-exclusions.test.ts": "responses", "windows-config-root-async-writers.test.ts": "windows", "windows-config-root-integration-writers.test.ts": "windows", + "windows-cli-config-root-startup.test.ts": "windows", "windows-atomic-write-acl-rearm.test.ts": "windows", "advisor-web-search.test.ts": "advisor", "codex-launcher-endpoint.test.ts": "codex-integration", diff --git a/tests/windows/windows-cli-config-root-startup.test.ts b/tests/windows/windows-cli-config-root-startup.test.ts new file mode 100644 index 00000000000..4baad86461a --- /dev/null +++ b/tests/windows/windows-cli-config-root-startup.test.ts @@ -0,0 +1,108 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import * as paths from "../../src/config/paths"; +import { settleConfigRootForCli } from "../../src/cli/config-root-startup"; +import { resetHardenedStateForTests, setAsyncIcaclsBeltSchedulerForTests, setAsyncIcaclsRunnerForTests, + setIcaclsRunnerForTests, setNowForTests, setPlatformForTests, type IcaclsResult } from "../../src/lib/windows-secret-acl"; +import { setSyntheticWindowsPrincipalForTests } from "../../src/lib/windows-user-principal"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { repoPath } from "../helpers/repo-root"; + +/** + * #7815 owner decision: the CLI waits once at startup for the optional config-root ACL flight + * before a command that writes under the config root does its first write. Read-only, hot-path + * and validate-first commands, and the long-lived server, never start or wait for it. + */ +const success: IcaclsResult = { success: true, exitCode: 0, timedOut: false, stdout: "" }; +const turn = () => new Promise(done => setImmediate(done)); +const keys = ["OPENCODEX_HOME", "OPENCODEX_ACL_TIMEOUT_MS", "OPENCODEX_ACL_VERIFY_EXISTING"] as const; +let root: string; +let previous: (string | undefined)[]; + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "ocx-cli-config-root-startup-")); + previous = keys.map(key => process.env[key]); + process.env.OPENCODEX_HOME = root; process.env.OPENCODEX_ACL_TIMEOUT_MS = "1000"; + delete process.env.OPENCODEX_ACL_VERIFY_EXISTING; + resetHardenedStateForTests(); setPlatformForTests("win32"); + setSyntheticWindowsPrincipalForTests("*S-1-5-21-1-2-3-1001"); setIcaclsRunnerForTests(() => success); +}); +afterEach(async () => { + await paths.flushConfigDirHardeningAndReaps(root); + setAsyncIcaclsRunnerForTests(null); setAsyncIcaclsBeltSchedulerForTests(null); + setNowForTests(null); setIcaclsRunnerForTests(null); setPlatformForTests(null); + setSyntheticWindowsPrincipalForTests(null); resetHardenedStateForTests(); + keys.forEach((key, index) => { + if (previous[index] === undefined) delete process.env[key]; else process.env[key] = previous[index]; + }); + removeTreeWithRetry(root); +}); + +function holdFlight() { + let entered = 0; + let release!: () => void; + const released = new Promise(done => { release = done; }); + setAsyncIcaclsRunnerForTests(async () => { entered += 1; await released; return success; }); + return { entered: () => entered, release }; +} + +test("a writing command waits for the config-root flight it starts", async () => { + const flight = holdFlight(); + let settled = false; + const work = settleConfigRootForCli("config", ["config", "set", "effortCap", "high"]).then(() => { settled = true; }); + await turn(); await turn(); + expect(flight.entered()).toBeGreaterThan(0); + expect(settled).toBe(false); + flight.release(); + await work; + expect(settled).toBe(true); +}); + +test.each([ + ["resolve", ["resolve", "--json"]], + ["system", ["system", "codex-cli-update", "check"]], + ["stop", ["stop", "--json", "--expect-pid", "4242"]], + ["codex", ["codex", "exec", "hi"]], + ["service", ["service", "status", "--json"]], + ["internal", ["internal", "chatgpt-app-server-filter"]], + ["start", ["start"]], +] as const)("%s %j neither starts nor waits for the flight", async (command, args) => { + const flight = holdFlight(); + await settleConfigRootForCli(command, [...args]); + expect(flight.entered()).toBe(0); +}); + +test("POSIX never waits", async () => { + setPlatformForTests("linux"); + const flight = holdFlight(); + await settleConfigRootForCli("config", ["config", "set", "effortCap", "high"]); + expect(flight.entered()).toBe(0); +}); + +test("a flight that outlives the ACL deadline lets the command proceed", async () => { + let now = 0; + const timers = new Map<() => void, number>(); + setNowForTests(() => now); + setAsyncIcaclsBeltSchedulerForTests((callback, ms) => { timers.set(callback, now + ms); return () => { timers.delete(callback); }; }); + const flight = holdFlight(); + let settled = false; + const work = settleConfigRootForCli("config", ["config", "set", "effortCap", "high"]).then(() => { settled = true; }); + await turn(); await turn(); + expect(settled).toBe(false); + now += 1_000; + for (const [callback, deadline] of timers) if (deadline <= now) { timers.delete(callback); callback(); } + await work; + expect(settled).toBe(true); + flight.release(); +}); + +test("runCli awaits the startup wait before the version-skew notice and the shim preflight", () => { + const source = readFileSync(repoPath("src", "cli", "root.ts"), "utf8"); + const command = source.slice(source.indexOf('case "command":')); + const wait = command.indexOf("await settleConfigRootForCli(head.command, head.args);"); + expect(wait).toBeGreaterThan(-1); + expect(wait).toBeLessThan(command.indexOf("await maybeNoticeVersionSkew(")); + expect(wait).toBeLessThan(command.indexOf("await maybeAutoRestoreCodexShimAsync(")); +}); From fb4309046aca2c3a906d4e8f9f800603d1e37888 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 11 Nov 2026 20:59:21 +0900 Subject: [PATCH 2/4] fix(cli): keep shim mocks linking; skip helpers and ensure in the startup wait The startup wait imported skipsCodexShimAutoRestore from codex-shim-autorestore.ts, so subprocess fixtures that partially mock that module no longer linked (72 failures in cli-help-recovery, cli-version-skew, stop-deferred-teardown and update-teardown-handover). The list now lives in src/cli/preflight-exemptions.ts and is re-exported. Hidden __* helpers and ensure (run by the Windows Codex shim before every launch) are skipped like start; the residual list names message, stop --expect-*, ensure and the identity probe, and says the CLI now waits for the icacls run. Refs #7815 --- src/cli/codex-shim-autorestore.ts | 47 ++----------------- src/cli/config-root-startup.ts | 15 +++--- src/cli/preflight-exemptions.ts | 42 +++++++++++++++++ structure/config.md | 2 +- .../windows-cli-config-root-startup.test.ts | 3 ++ 5 files changed, 60 insertions(+), 49 deletions(-) create mode 100644 src/cli/preflight-exemptions.ts diff --git a/src/cli/codex-shim-autorestore.ts b/src/cli/codex-shim-autorestore.ts index 5762e1f187f..f3f2353dc67 100644 --- a/src/cli/codex-shim-autorestore.ts +++ b/src/cli/codex-shim-autorestore.ts @@ -1,6 +1,10 @@ import { autoRestoreCodexShim, autoRestoreCodexShimAsync } from "../codex/shim"; import { codexShimAutoRestoreEnabled, readConfigDiagnostics } from "../config"; -import { isOrchestratedUpdateArgv } from "../update/orchestrated-arguments.mjs"; +import { skipsCodexShimAutoRestore } from "./preflight-exemptions"; + +// Re-exported for existing importers; the list itself lives in a leaf module so a caller that +// only needs it (the config-root startup wait) does not link the shim repair machinery. +export { skipsCodexShimAutoRestore }; export interface CodexShimAutoRestoreCliDeps { env: NodeJS.ProcessEnv; @@ -16,47 +20,6 @@ const DEFAULT_DEPS: CodexShimAutoRestoreCliDeps = { readConfig: readConfigDiagnostics, }; -/** Identify command namespaces whose execution must not trigger automatic shim repair. */ -export function skipsCodexShimAutoRestore(command: string | undefined, args: string[]): boolean { - if (command === "uninstall" || command === "remove") return true; - // Contract discovery and orchestrated update must validate before any repair. - if (command === "capabilities") return true; - if (command === "update" && isOrchestratedUpdateArgv(args)) return true; - if (command === "sync") return true; - if (command === "status" || command === "doctor") return true; - // Explicit orphan-token recovery must not mutate Codex before its guards run. - if (command === "disconnect" && args.includes("--orphaned-token")) return true; - // The launcher owns shim handoff after classifying routing, including native fast paths. - if (command === "codex") return true; - // Exec admission only observes the selected target; it must never repair a shim first. - if (command === "internal" && args[1] === "codex-exec-target") return true; - // `lab` is read-only inspection; it must not trigger shim side effects. - if (command === "lab") return true; - // Local messaging owns its helpers; even malformed usage must not repair/start anything. - if (command === "message") return true; - // `resolve` is read-only inspection for embedding shells: a lookup made to populate - // a consent surface must not trigger a shim repair side effect first. - if (command === "resolve") return true; - // Local model inventory is read-only; mutations and live commands keep preflight. - if (command === "models" || command === "model") { - const subcommand = args[1]; - if (!subcommand || subcommand.startsWith("-") || subcommand === "list" || subcommand === "list-custom") return true; - } - // `service status --json` is a passive inventory read for peers such as GOAT: a shim repair - // before dispatch would change the installation it was asked only to describe. - // Flags may precede the verb (`ocx service --json status`), exactly as parseServiceArgs reads it. - if (command === "service" && args.includes("--json") - && args.slice(1).find(arg => !arg.startsWith("--")) === "status") return true; - // The desktop's approval-bound stop must validate its snapshot before any unrelated - // CLI repair changes the installation it was approved against. - if (command === "stop" && args.some(arg => arg.startsWith("--expect-"))) return true; - // The entire updater-inspection namespace is zero-effect, including malformed - // or future actions. A later `apply` implementation must own its preflight. - if (command === "system" && args[1] === "codex-cli-update") return true; - if (command === "__update-badge") return true; - return command === "codex-shim" && ["install", "status", "uninstall", "remove"].includes(args[1] ?? ""); -} - export function maybeAutoRestoreCodexShim( command: string | undefined, args: string[], diff --git a/src/cli/config-root-startup.ts b/src/cli/config-root-startup.ts index 61feab81e3b..b2656a8805b 100644 --- a/src/cli/config-root-startup.ts +++ b/src/cli/config-root-startup.ts @@ -1,6 +1,6 @@ import { getConfigDir, hardenConfigDir, withConfigDirHardeningSettled } from "../config/paths"; import { WindowsSecretAclSettleTimeoutError, windowsSecretAclApplies } from "../lib/windows-secret-acl"; -import { skipsCodexShimAutoRestore } from "./codex-shim-autorestore"; +import { skipsCodexShimAutoRestore } from "./preflight-exemptions"; /** * Wait once, before a CLI command does its first write, for the optional config-root ACL flight @@ -11,17 +11,20 @@ import { skipsCodexShimAutoRestore } from "./codex-shim-autorestore"; * Skipped where waiting would itself be the side effect or the delay matters: * - the commands skipsCodexShimAutoRestore exempts from preflight repair (read-only, hot-path * and validate-first commands). Adding a command there also removes this wait for it; - * - every "internal" helper, launched by other processes on hot paths; - * - "start", the long-lived server: the wait would run before Bun.serve and spend up to one ACL - * deadline of fixed startup budgets (update-restart marker, ensure readiness, Desktop cold - * start, service start timeouts). The server's synchronous writers are documented residual. + * - every "internal" helper and every hidden "__*" helper, launched by other processes under their + * own budgets (startup health, tray start/restart/host, version refresh, the GUI update worker); + * - "start", the long-lived server, and "ensure", which the Windows Codex shim runs before every + * launch to start it: the wait would run before Bun.serve and spend up to one ACL deadline of + * fixed budgets (update-restart marker, ensure readiness, Desktop cold start, service start + * timeouts, each Codex launch). The server's synchronous writers are documented residual. * * Bounded by one ACL deadline, which also drains timed-out icacls children. A timeout lets the * command proceed: writers that admit through withConfigDirHardeningSettled still refuse alone. */ export async function settleConfigRootForCli(command: string | undefined, args: readonly string[]): Promise { if (!windowsSecretAclApplies()) return; - if (command === "start" || command === "internal" || skipsCodexShimAutoRestore(command, [...args])) return; + if (command === undefined || command === "start" || command === "ensure" || command === "internal" + || command.startsWith("__") || skipsCodexShimAutoRestore(command, [...args])) return; hardenConfigDir(); try { await withConfigDirHardeningSettled(getConfigDir(), () => undefined); diff --git a/src/cli/preflight-exemptions.ts b/src/cli/preflight-exemptions.ts new file mode 100644 index 00000000000..fb3d6e0e6b2 --- /dev/null +++ b/src/cli/preflight-exemptions.ts @@ -0,0 +1,42 @@ +import { isOrchestratedUpdateArgv } from "../update/orchestrated-arguments.mjs"; + +/** Identify command namespaces whose execution must not trigger automatic shim repair. */ +export function skipsCodexShimAutoRestore(command: string | undefined, args: string[]): boolean { + if (command === "uninstall" || command === "remove") return true; + // Contract discovery and orchestrated update must validate before any repair. + if (command === "capabilities") return true; + if (command === "update" && isOrchestratedUpdateArgv(args)) return true; + if (command === "sync") return true; + if (command === "status" || command === "doctor") return true; + // Explicit orphan-token recovery must not mutate Codex before its guards run. + if (command === "disconnect" && args.includes("--orphaned-token")) return true; + // The launcher owns shim handoff after classifying routing, including native fast paths. + if (command === "codex") return true; + // Exec admission only observes the selected target; it must never repair a shim first. + if (command === "internal" && args[1] === "codex-exec-target") return true; + // `lab` is read-only inspection; it must not trigger shim side effects. + if (command === "lab") return true; + // Local messaging owns its helpers; even malformed usage must not repair/start anything. + if (command === "message") return true; + // `resolve` is read-only inspection for embedding shells: a lookup made to populate + // a consent surface must not trigger a shim repair side effect first. + if (command === "resolve") return true; + // Local model inventory is read-only; mutations and live commands keep preflight. + if (command === "models" || command === "model") { + const subcommand = args[1]; + if (!subcommand || subcommand.startsWith("-") || subcommand === "list" || subcommand === "list-custom") return true; + } + // `service status --json` is a passive inventory read for peers such as GOAT: a shim repair + // before dispatch would change the installation it was asked only to describe. + // Flags may precede the verb (`ocx service --json status`), exactly as parseServiceArgs reads it. + if (command === "service" && args.includes("--json") + && args.slice(1).find(arg => !arg.startsWith("--")) === "status") return true; + // The desktop's approval-bound stop must validate its snapshot before any unrelated + // CLI repair changes the installation it was approved against. + if (command === "stop" && args.some(arg => arg.startsWith("--expect-"))) return true; + // The entire updater-inspection namespace is zero-effect, including malformed + // or future actions. A later `apply` implementation must own its preflight. + if (command === "system" && args[1] === "codex-cli-update") return true; + if (command === "__update-badge") return true; + return command === "codex-shim" && ["install", "status", "uninstall", "remove"].includes(args[1] ?? ""); +} diff --git a/structure/config.md b/structure/config.md index 02dcb872e08..5d8998ac2f2 100644 --- a/structure/config.md +++ b/structure/config.md @@ -62,7 +62,7 @@ test seam and the mutation types remain re-exported through `src/config.ts`. Suc `src/config/paths.ts` owns `OPENCODEX_HOME` expansion and resolution, the config directory and `config.json` path. A relative home is resolved once per distinct raw environment value, so a later working-directory change cannot silently move the active installation. Config reads in this leaf and `src/config/load-degrade.ts` use NTFS ACLs on Windows and private POSIX modes elsewhere. Optional directory hardening follows directory symlinks/junctions but skips non-directory or unstatable targets before starting chmod or ACL work. Windows reads omit `chmod` before ACL hardening so repeated loads preserve successful object/freshness observations; external metadata changes still invalidate them. Directory flights keep their existing flush/reap lifecycle, and file/required-write failure policy is unchanged. `tests/windows/windows-config-read-acl-memo.test.ts` covers repeated loads, non-directory and directory-link behavior, external invalidation and POSIX permissions. -`withConfigDirHardeningSettled` in `src/config/paths.ts` admits synchronous mutation after the last unrelated await. Its registry includes the optional config flight, ancestors and retained timeout children; one existing ACL deadline bounds admission, including newly overlapping work. Expiry throws sanitized `WindowsSecretAclSettleTimeoutError` (`ETIMEDOUT`) without running the writer or dropping child cleanup ownership. The final empty-registry check and callback share one turn, with no await in the callback. Intercept/picker CA, token, cleanup, profile and snapshot phases re-enter after trust/discovery awaits. Config saves in `src/server/management/agent-settings-routes.ts` and `src/server/management/config-routes.ts`, Desktop intent/mode commits in `src/server/management/native-integration-routes.ts`, and gateway publication/cleanup in those routes and `src/cli/ensure-desired-integrations.ts` use the same admission. `src/cli/claude-desktop.ts` admits local profile/mode commits and the complete remote-store transaction again after hub download. Lifecycle/config locks are acquired inside admission; refresh re-read, mode/freshness checks, profile and marker publication share one callback. Live setting edits and their save/publication share the admitted synchronous callback; a refused admission leaves both live and durable state untouched. Ordered post-commit phases preserve applied-state warnings or settled compensation, including mode/fingerprint marker refusal and retained CLI intent after incomplete rollback. Synchronous leaf APIs retain their contracts. `tests/claude-integration/claude-config-root-writer-barrier.test.ts` holds parent flights and drives refusal deadlines without sleeps. Lexical/canonical aliases and uncertain identities drain conservatively; removal keeps its separate at-or-below scope and actual-exit requirement. Async local config commands (`src/cli/config-command.ts`, `src/cli/effort.ts`, `src/cli/models.ts`, `src/cli/provider.ts`) admit complete synchronous read/validate/save phases through `withConfigDirHardeningSettled`. Preliminary model selection and client-connection diagnostics use passive observations that cannot publish recovery copies. Final authority and recovery publication are re-read inside admission without starting optional hardening. `src/cli/config-mutation.ts` refuses invalid or unreadable authority, including array/non-object roots rejected before defaults repair, with `CliUsageError`; full-config commands retain fresh-install initialization when the file is absent, while set/unset retain the persisted mutation owner's missing-file refusal. Custom-model removal revalidates the confirmed row by identity and contents while retaining current siblings. Import reads its input and checks its target inside admission. Provider-add credential cleanup shares the synchronous post-save phase and retains its existing post-commit warning. Timeout leaves the mutation database and config untouched and follows existing CLI failure handling. `tests/windows/windows-config-root-async-writers.test.ts` covers held parent flights, deadline refusal, recovery copies, invalid authority and concurrent edits. Codex multi-agent management changes that can resolve a runtime additionally await fresh [selection admission](codex-cli-update.md#worker-realm-and-the-selection-commit-window) before entering this barrier, keep that owner across hardening, and re-evaluate the mode plan inside the synchronous callback; neither ACL wait is inserted into the callback, and refusal leaves the combined mutation untouched. Timer-driven caches under the config root admit their write the same way and build the snapshot inside the callback: the provider account quota cache (`src/providers/account-quota-disk.ts`), the Codex account quota cache (`src/codex/quota.ts`) and the reasoning support cache, while a models.dev refresh admits its publication after the network read (`src/providers/reasoning-metadata.ts`). A timed-out admission skips a best-effort cache write and fails that refresh unpublished, a joined refresh reports the same failure, and a cancel, clear or reset invalidates a write still waiting for admission (#7815; `tests/providers/provider-account-quota-persistence.test.ts`, `tests/codex-integration/reasoning-metadata.test.ts`). The integrations writer (`src/integrations/writer.ts`) runs every coordinated transaction (apply, refresh, overwrite, disable, restore; reached by the catalog fan-out, the Aside sync and profile routes, and integration routes) inside admission on its store root, with the store-lock re-probe in the same callback so no await separates it from the transaction; an admission timeout returns a `write_failed` refusal without a write. An async `revalidate` such as the Aside late confirmation check still runs before admission, so the wait sits between it and the transaction while the writer locks stay held. `disconnectClient` in `src/client/connect.ts` admits each of its two synchronous phases (a timeout before the second leaves the prepared receipt it resumes from), and key rotation admits both remote Desktop credential alignments that precede the hub commit; rollback and post-commit finalization keep their unadmitted paths (`tests/windows/windows-config-root-integration-writers.test.ts`). The CLI also waits once at startup (`src/cli/config-root-startup.ts`, called from `runCli`'s command branch before the version-skew notice and Codex-shim preflight): on Windows it starts the optional config-root flight and drains it with `withConfigDirHardeningSettled(root, () => undefined)` under one ACL deadline, then proceeds even on timeout (`tests/windows/windows-cli-config-root-startup.test.ts`). It skips every command `skipsCodexShimAutoRestore` exempts (adding one there also drops this wait), every `internal` helper and `start`; for `start` the wait would spend up to one ACL deadline of fixed startup budgets before `Bun.serve`. Residual risk, accepted by owner decision for #7815: (1) only the first write is covered once a later atomic write invalidates the per-process ctime success memo and a later `loadConfig()` starts a new flight; admitted writers stay safe; (2) a fresh install has no directory to wait for, so the first `loadConfig()` after creating it starts a flight while later writers run; (3) a swallowed timeout can leave a retained icacls child running that synchronous writers may overlap; (4) paths that never reach `runCli` (the `start` service logger, the update-restart child, the health sentinel, MCP entrypoints) and the excluded writing commands (uninstall/remove, sync, orchestrated update, `disconnect --orphaned-token`, codex-shim install/uninstall, internal helpers) keep their previous overlap; (5) the server's synchronous writers (`saveConfig`, persisted mutation, management and GUI session tokens, service secrets, the spend-ledger lease, the link store) stay synchronous and can overlap a flight any `loadConfig()` starts; (6) every eligible CLI run on Windows pays one icacls run, because the success memo is per process and the compliant-ACL precheck is opt-in (`OPENCODEX_ACL_VERIFY_EXISTING`). The writers #7815 named are admitted: config saves and Desktop 3p publication (#7826), the remote Desktop store through `connect.ts` and `claude-desktop.ts` (#7826, #8532) and the integrations writer (#8532). +`withConfigDirHardeningSettled` in `src/config/paths.ts` admits synchronous mutation after the last unrelated await. Its registry includes the optional config flight, ancestors and retained timeout children; one existing ACL deadline bounds admission, including newly overlapping work. Expiry throws sanitized `WindowsSecretAclSettleTimeoutError` (`ETIMEDOUT`) without running the writer or dropping child cleanup ownership. The final empty-registry check and callback share one turn, with no await in the callback. Intercept/picker CA, token, cleanup, profile and snapshot phases re-enter after trust/discovery awaits. Config saves in `src/server/management/agent-settings-routes.ts` and `src/server/management/config-routes.ts`, Desktop intent/mode commits in `src/server/management/native-integration-routes.ts`, and gateway publication/cleanup in those routes and `src/cli/ensure-desired-integrations.ts` use the same admission. `src/cli/claude-desktop.ts` admits local profile/mode commits and the complete remote-store transaction again after hub download. Lifecycle/config locks are acquired inside admission; refresh re-read, mode/freshness checks, profile and marker publication share one callback. Live setting edits and their save/publication share the admitted synchronous callback; a refused admission leaves both live and durable state untouched. Ordered post-commit phases preserve applied-state warnings or settled compensation, including mode/fingerprint marker refusal and retained CLI intent after incomplete rollback. Synchronous leaf APIs retain their contracts. `tests/claude-integration/claude-config-root-writer-barrier.test.ts` holds parent flights and drives refusal deadlines without sleeps. Lexical/canonical aliases and uncertain identities drain conservatively; removal keeps its separate at-or-below scope and actual-exit requirement. Async local config commands (`src/cli/config-command.ts`, `src/cli/effort.ts`, `src/cli/models.ts`, `src/cli/provider.ts`) admit complete synchronous read/validate/save phases through `withConfigDirHardeningSettled`. Preliminary model selection and client-connection diagnostics use passive observations that cannot publish recovery copies. Final authority and recovery publication are re-read inside admission without starting optional hardening. `src/cli/config-mutation.ts` refuses invalid or unreadable authority, including array/non-object roots rejected before defaults repair, with `CliUsageError`; full-config commands retain fresh-install initialization when the file is absent, while set/unset retain the persisted mutation owner's missing-file refusal. Custom-model removal revalidates the confirmed row by identity and contents while retaining current siblings. Import reads its input and checks its target inside admission. Provider-add credential cleanup shares the synchronous post-save phase and retains its existing post-commit warning. Timeout leaves the mutation database and config untouched and follows existing CLI failure handling. `tests/windows/windows-config-root-async-writers.test.ts` covers held parent flights, deadline refusal, recovery copies, invalid authority and concurrent edits. Codex multi-agent management changes that can resolve a runtime additionally await fresh [selection admission](codex-cli-update.md#worker-realm-and-the-selection-commit-window) before entering this barrier, keep that owner across hardening, and re-evaluate the mode plan inside the synchronous callback; neither ACL wait is inserted into the callback, and refusal leaves the combined mutation untouched. Timer-driven caches under the config root admit their write the same way and build the snapshot inside the callback: the provider account quota cache (`src/providers/account-quota-disk.ts`), the Codex account quota cache (`src/codex/quota.ts`) and the reasoning support cache, while a models.dev refresh admits its publication after the network read (`src/providers/reasoning-metadata.ts`). A timed-out admission skips a best-effort cache write and fails that refresh unpublished, a joined refresh reports the same failure, and a cancel, clear or reset invalidates a write still waiting for admission (#7815; `tests/providers/provider-account-quota-persistence.test.ts`, `tests/codex-integration/reasoning-metadata.test.ts`). The integrations writer (`src/integrations/writer.ts`) runs every coordinated transaction (apply, refresh, overwrite, disable, restore; reached by the catalog fan-out, the Aside sync and profile routes, and integration routes) inside admission on its store root, with the store-lock re-probe in the same callback so no await separates it from the transaction; an admission timeout returns a `write_failed` refusal without a write. An async `revalidate` such as the Aside late confirmation check still runs before admission, so the wait sits between it and the transaction while the writer locks stay held. `disconnectClient` in `src/client/connect.ts` admits each of its two synchronous phases (a timeout before the second leaves the prepared receipt it resumes from), and key rotation admits both remote Desktop credential alignments that precede the hub commit; rollback and post-commit finalization keep their unadmitted paths (`tests/windows/windows-config-root-integration-writers.test.ts`). The CLI also waits once at startup (`src/cli/config-root-startup.ts`, called from `runCli`'s command branch before the version-skew notice and Codex-shim preflight): on Windows it starts the optional config-root flight and drains it with `withConfigDirHardeningSettled(root, () => undefined)` under one ACL deadline, then proceeds even on timeout (`tests/windows/windows-cli-config-root-startup.test.ts`). It skips every command `skipsCodexShimAutoRestore` (`src/cli/preflight-exemptions.ts`) exempts (adding one there also drops this wait), every `internal` and hidden `__*` helper, `start` and `ensure`; for the server and for `ensure`, which the Windows Codex shim runs before every launch, the wait would spend up to one ACL deadline of fixed startup budgets. Residual risk, accepted by owner decision for #7815: (1) only the first write is covered once a later atomic write invalidates the per-process ctime success memo and a later `loadConfig()` starts a new flight; admitted writers stay safe; (2) a fresh install has no directory to wait for, so the first `loadConfig()` after creating it starts a flight while later writers run; (3) a swallowed timeout can leave a retained icacls child running that synchronous writers may overlap; (4) paths that never reach `runCli` (the `start` service logger, the update-restart child, the orchestrated identity probe, the health sentinel, MCP entrypoints) and the excluded writing commands (uninstall/remove, sync, orchestrated update, `disconnect --orphaned-token`, codex-shim install/uninstall, `message`, `stop --expect-*`, `ensure`, internal and hidden helpers) keep their previous overlap; (5) the server's synchronous writers (`saveConfig`, persisted mutation, management and GUI session tokens, service secrets, the spend-ledger lease, the link store) stay synchronous and can overlap a flight any `loadConfig()` starts; (6) every eligible CLI run on Windows now waits for one icacls run it previously left unawaited, because the success memo is per process and the compliant-ACL precheck is opt-in (`OPENCODEX_ACL_VERIFY_EXISTING`). The writers #7815 named are admitted: config saves and Desktop 3p publication (#7826), the remote Desktop store through `connect.ts` and `claude-desktop.ts` (#7826, #8532) and the integrations writer (#8532). `src/config/process-state.ts` derives `ocx.pid` and `runtime-port.json` from that resolved directory. Ordinary and connected-client runtimes publish their absolute relaunch command in the runtime record; older records can omit it. Tracked runtime inspection retains an omitted hostname as `undefined` for guarded stop's legacy-record check. It owns their byte-compatible writes, parsing, expected-PID filters, cheap liveness, full OCX command diff --git a/tests/windows/windows-cli-config-root-startup.test.ts b/tests/windows/windows-cli-config-root-startup.test.ts index 4baad86461a..66bb750114c 100644 --- a/tests/windows/windows-cli-config-root-startup.test.ts +++ b/tests/windows/windows-cli-config-root-startup.test.ts @@ -68,6 +68,9 @@ test.each([ ["service", ["service", "status", "--json"]], ["internal", ["internal", "chatgpt-app-server-filter"]], ["start", ["start"]], + ["ensure", ["ensure"]], + ["__startup-health", ["__startup-health"]], + ["__tray-start", ["__tray-start"]], ] as const)("%s %j neither starts nor waits for the flight", async (command, args) => { const flight = holdFlight(); await settleConfigRootForCli(command, [...args]); From 5bc2f6048016bebedc2ff2694acd8bbe03e35559 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 11 Nov 2026 21:04:47 +0900 Subject: [PATCH 3/4] docs(structure): name every excluded writing command in the config-root residuals Item (4) becomes a rule (every command skipsCodexShimAutoRestore exempts plus ensure and helpers) with examples including lab automation, lab run, lab public import and doctor --recover-zero-byte-coordinator; item (6) names Remote Link enrollment commands; the test header no longer overclaims. Refs #7815 --- structure/config.md | 2 +- tests/windows/windows-cli-config-root-startup.test.ts | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/structure/config.md b/structure/config.md index 5d8998ac2f2..f9489a68adc 100644 --- a/structure/config.md +++ b/structure/config.md @@ -62,7 +62,7 @@ test seam and the mutation types remain re-exported through `src/config.ts`. Suc `src/config/paths.ts` owns `OPENCODEX_HOME` expansion and resolution, the config directory and `config.json` path. A relative home is resolved once per distinct raw environment value, so a later working-directory change cannot silently move the active installation. Config reads in this leaf and `src/config/load-degrade.ts` use NTFS ACLs on Windows and private POSIX modes elsewhere. Optional directory hardening follows directory symlinks/junctions but skips non-directory or unstatable targets before starting chmod or ACL work. Windows reads omit `chmod` before ACL hardening so repeated loads preserve successful object/freshness observations; external metadata changes still invalidate them. Directory flights keep their existing flush/reap lifecycle, and file/required-write failure policy is unchanged. `tests/windows/windows-config-read-acl-memo.test.ts` covers repeated loads, non-directory and directory-link behavior, external invalidation and POSIX permissions. -`withConfigDirHardeningSettled` in `src/config/paths.ts` admits synchronous mutation after the last unrelated await. Its registry includes the optional config flight, ancestors and retained timeout children; one existing ACL deadline bounds admission, including newly overlapping work. Expiry throws sanitized `WindowsSecretAclSettleTimeoutError` (`ETIMEDOUT`) without running the writer or dropping child cleanup ownership. The final empty-registry check and callback share one turn, with no await in the callback. Intercept/picker CA, token, cleanup, profile and snapshot phases re-enter after trust/discovery awaits. Config saves in `src/server/management/agent-settings-routes.ts` and `src/server/management/config-routes.ts`, Desktop intent/mode commits in `src/server/management/native-integration-routes.ts`, and gateway publication/cleanup in those routes and `src/cli/ensure-desired-integrations.ts` use the same admission. `src/cli/claude-desktop.ts` admits local profile/mode commits and the complete remote-store transaction again after hub download. Lifecycle/config locks are acquired inside admission; refresh re-read, mode/freshness checks, profile and marker publication share one callback. Live setting edits and their save/publication share the admitted synchronous callback; a refused admission leaves both live and durable state untouched. Ordered post-commit phases preserve applied-state warnings or settled compensation, including mode/fingerprint marker refusal and retained CLI intent after incomplete rollback. Synchronous leaf APIs retain their contracts. `tests/claude-integration/claude-config-root-writer-barrier.test.ts` holds parent flights and drives refusal deadlines without sleeps. Lexical/canonical aliases and uncertain identities drain conservatively; removal keeps its separate at-or-below scope and actual-exit requirement. Async local config commands (`src/cli/config-command.ts`, `src/cli/effort.ts`, `src/cli/models.ts`, `src/cli/provider.ts`) admit complete synchronous read/validate/save phases through `withConfigDirHardeningSettled`. Preliminary model selection and client-connection diagnostics use passive observations that cannot publish recovery copies. Final authority and recovery publication are re-read inside admission without starting optional hardening. `src/cli/config-mutation.ts` refuses invalid or unreadable authority, including array/non-object roots rejected before defaults repair, with `CliUsageError`; full-config commands retain fresh-install initialization when the file is absent, while set/unset retain the persisted mutation owner's missing-file refusal. Custom-model removal revalidates the confirmed row by identity and contents while retaining current siblings. Import reads its input and checks its target inside admission. Provider-add credential cleanup shares the synchronous post-save phase and retains its existing post-commit warning. Timeout leaves the mutation database and config untouched and follows existing CLI failure handling. `tests/windows/windows-config-root-async-writers.test.ts` covers held parent flights, deadline refusal, recovery copies, invalid authority and concurrent edits. Codex multi-agent management changes that can resolve a runtime additionally await fresh [selection admission](codex-cli-update.md#worker-realm-and-the-selection-commit-window) before entering this barrier, keep that owner across hardening, and re-evaluate the mode plan inside the synchronous callback; neither ACL wait is inserted into the callback, and refusal leaves the combined mutation untouched. Timer-driven caches under the config root admit their write the same way and build the snapshot inside the callback: the provider account quota cache (`src/providers/account-quota-disk.ts`), the Codex account quota cache (`src/codex/quota.ts`) and the reasoning support cache, while a models.dev refresh admits its publication after the network read (`src/providers/reasoning-metadata.ts`). A timed-out admission skips a best-effort cache write and fails that refresh unpublished, a joined refresh reports the same failure, and a cancel, clear or reset invalidates a write still waiting for admission (#7815; `tests/providers/provider-account-quota-persistence.test.ts`, `tests/codex-integration/reasoning-metadata.test.ts`). The integrations writer (`src/integrations/writer.ts`) runs every coordinated transaction (apply, refresh, overwrite, disable, restore; reached by the catalog fan-out, the Aside sync and profile routes, and integration routes) inside admission on its store root, with the store-lock re-probe in the same callback so no await separates it from the transaction; an admission timeout returns a `write_failed` refusal without a write. An async `revalidate` such as the Aside late confirmation check still runs before admission, so the wait sits between it and the transaction while the writer locks stay held. `disconnectClient` in `src/client/connect.ts` admits each of its two synchronous phases (a timeout before the second leaves the prepared receipt it resumes from), and key rotation admits both remote Desktop credential alignments that precede the hub commit; rollback and post-commit finalization keep their unadmitted paths (`tests/windows/windows-config-root-integration-writers.test.ts`). The CLI also waits once at startup (`src/cli/config-root-startup.ts`, called from `runCli`'s command branch before the version-skew notice and Codex-shim preflight): on Windows it starts the optional config-root flight and drains it with `withConfigDirHardeningSettled(root, () => undefined)` under one ACL deadline, then proceeds even on timeout (`tests/windows/windows-cli-config-root-startup.test.ts`). It skips every command `skipsCodexShimAutoRestore` (`src/cli/preflight-exemptions.ts`) exempts (adding one there also drops this wait), every `internal` and hidden `__*` helper, `start` and `ensure`; for the server and for `ensure`, which the Windows Codex shim runs before every launch, the wait would spend up to one ACL deadline of fixed startup budgets. Residual risk, accepted by owner decision for #7815: (1) only the first write is covered once a later atomic write invalidates the per-process ctime success memo and a later `loadConfig()` starts a new flight; admitted writers stay safe; (2) a fresh install has no directory to wait for, so the first `loadConfig()` after creating it starts a flight while later writers run; (3) a swallowed timeout can leave a retained icacls child running that synchronous writers may overlap; (4) paths that never reach `runCli` (the `start` service logger, the update-restart child, the orchestrated identity probe, the health sentinel, MCP entrypoints) and the excluded writing commands (uninstall/remove, sync, orchestrated update, `disconnect --orphaned-token`, codex-shim install/uninstall, `message`, `stop --expect-*`, `ensure`, internal and hidden helpers) keep their previous overlap; (5) the server's synchronous writers (`saveConfig`, persisted mutation, management and GUI session tokens, service secrets, the spend-ledger lease, the link store) stay synchronous and can overlap a flight any `loadConfig()` starts; (6) every eligible CLI run on Windows now waits for one icacls run it previously left unawaited, because the success memo is per process and the compliant-ACL precheck is opt-in (`OPENCODEX_ACL_VERIFY_EXISTING`). The writers #7815 named are admitted: config saves and Desktop 3p publication (#7826), the remote Desktop store through `connect.ts` and `claude-desktop.ts` (#7826, #8532) and the integrations writer (#8532). +`withConfigDirHardeningSettled` in `src/config/paths.ts` admits synchronous mutation after the last unrelated await. Its registry includes the optional config flight, ancestors and retained timeout children; one existing ACL deadline bounds admission, including newly overlapping work. Expiry throws sanitized `WindowsSecretAclSettleTimeoutError` (`ETIMEDOUT`) without running the writer or dropping child cleanup ownership. The final empty-registry check and callback share one turn, with no await in the callback. Intercept/picker CA, token, cleanup, profile and snapshot phases re-enter after trust/discovery awaits. Config saves in `src/server/management/agent-settings-routes.ts` and `src/server/management/config-routes.ts`, Desktop intent/mode commits in `src/server/management/native-integration-routes.ts`, and gateway publication/cleanup in those routes and `src/cli/ensure-desired-integrations.ts` use the same admission. `src/cli/claude-desktop.ts` admits local profile/mode commits and the complete remote-store transaction again after hub download. Lifecycle/config locks are acquired inside admission; refresh re-read, mode/freshness checks, profile and marker publication share one callback. Live setting edits and their save/publication share the admitted synchronous callback; a refused admission leaves both live and durable state untouched. Ordered post-commit phases preserve applied-state warnings or settled compensation, including mode/fingerprint marker refusal and retained CLI intent after incomplete rollback. Synchronous leaf APIs retain their contracts. `tests/claude-integration/claude-config-root-writer-barrier.test.ts` holds parent flights and drives refusal deadlines without sleeps. Lexical/canonical aliases and uncertain identities drain conservatively; removal keeps its separate at-or-below scope and actual-exit requirement. Async local config commands (`src/cli/config-command.ts`, `src/cli/effort.ts`, `src/cli/models.ts`, `src/cli/provider.ts`) admit complete synchronous read/validate/save phases through `withConfigDirHardeningSettled`. Preliminary model selection and client-connection diagnostics use passive observations that cannot publish recovery copies. Final authority and recovery publication are re-read inside admission without starting optional hardening. `src/cli/config-mutation.ts` refuses invalid or unreadable authority, including array/non-object roots rejected before defaults repair, with `CliUsageError`; full-config commands retain fresh-install initialization when the file is absent, while set/unset retain the persisted mutation owner's missing-file refusal. Custom-model removal revalidates the confirmed row by identity and contents while retaining current siblings. Import reads its input and checks its target inside admission. Provider-add credential cleanup shares the synchronous post-save phase and retains its existing post-commit warning. Timeout leaves the mutation database and config untouched and follows existing CLI failure handling. `tests/windows/windows-config-root-async-writers.test.ts` covers held parent flights, deadline refusal, recovery copies, invalid authority and concurrent edits. Codex multi-agent management changes that can resolve a runtime additionally await fresh [selection admission](codex-cli-update.md#worker-realm-and-the-selection-commit-window) before entering this barrier, keep that owner across hardening, and re-evaluate the mode plan inside the synchronous callback; neither ACL wait is inserted into the callback, and refusal leaves the combined mutation untouched. Timer-driven caches under the config root admit their write the same way and build the snapshot inside the callback: the provider account quota cache (`src/providers/account-quota-disk.ts`), the Codex account quota cache (`src/codex/quota.ts`) and the reasoning support cache, while a models.dev refresh admits its publication after the network read (`src/providers/reasoning-metadata.ts`). A timed-out admission skips a best-effort cache write and fails that refresh unpublished, a joined refresh reports the same failure, and a cancel, clear or reset invalidates a write still waiting for admission (#7815; `tests/providers/provider-account-quota-persistence.test.ts`, `tests/codex-integration/reasoning-metadata.test.ts`). The integrations writer (`src/integrations/writer.ts`) runs every coordinated transaction (apply, refresh, overwrite, disable, restore; reached by the catalog fan-out, the Aside sync and profile routes, and integration routes) inside admission on its store root, with the store-lock re-probe in the same callback so no await separates it from the transaction; an admission timeout returns a `write_failed` refusal without a write. An async `revalidate` such as the Aside late confirmation check still runs before admission, so the wait sits between it and the transaction while the writer locks stay held. `disconnectClient` in `src/client/connect.ts` admits each of its two synchronous phases (a timeout before the second leaves the prepared receipt it resumes from), and key rotation admits both remote Desktop credential alignments that precede the hub commit; rollback and post-commit finalization keep their unadmitted paths (`tests/windows/windows-config-root-integration-writers.test.ts`). The CLI also waits once at startup (`src/cli/config-root-startup.ts`, called from `runCli`'s command branch before the version-skew notice and Codex-shim preflight): on Windows it starts the optional config-root flight and drains it with `withConfigDirHardeningSettled(root, () => undefined)` under one ACL deadline, then proceeds even on timeout (`tests/windows/windows-cli-config-root-startup.test.ts`). It skips every command `skipsCodexShimAutoRestore` (`src/cli/preflight-exemptions.ts`) exempts (adding one there also drops this wait), every `internal` and hidden `__*` helper, `start` and `ensure`; for the server and for `ensure`, which the Windows Codex shim runs before every launch, the wait would spend up to one ACL deadline of fixed startup budgets. Residual risk, accepted by owner decision for #7815: (1) only the first write is covered once a later atomic write invalidates the per-process ctime success memo and a later `loadConfig()` starts a new flight; admitted writers stay safe; (2) a fresh install has no directory to wait for, so the first `loadConfig()` after creating it starts a flight while later writers run; (3) a swallowed timeout can leave a retained icacls child running that synchronous writers may overlap; (4) paths that never reach `runCli` (the `start` service logger, the update-restart child, the orchestrated identity probe, the health sentinel, MCP entrypoints) and every excluded command that writes under the root (any command `skipsCodexShimAutoRestore` exempts plus `ensure`, internal and hidden helpers; among them uninstall/remove, sync, orchestrated update, `disconnect --orphaned-token`, codex-shim install/uninstall, `message`, `stop --expect-*`, `lab automation enable|disable`, `lab run`, `lab public import` and `doctor --recover-zero-byte-coordinator --yes`) keep their previous overlap; (5) the server's synchronous writers (`saveConfig`, persisted mutation, management and GUI session tokens, service secrets, the spend-ledger lease, the link store) stay synchronous and can overlap a flight any `loadConfig()` starts; (6) every eligible CLI run on Windows now waits for one icacls run it previously left unawaited, including the commands Remote Link enrollment runs on a Windows Child over SSH (`link port`, `config show --json`, `connect --link`, `restart`) inside its fixed per-command budget, because the success memo is per process and the compliant-ACL precheck is opt-in (`OPENCODEX_ACL_VERIFY_EXISTING`). The writers #7815 named are admitted: config saves and Desktop 3p publication (#7826), the remote Desktop store through `connect.ts` and `claude-desktop.ts` (#7826, #8532) and the integrations writer (#8532). `src/config/process-state.ts` derives `ocx.pid` and `runtime-port.json` from that resolved directory. Ordinary and connected-client runtimes publish their absolute relaunch command in the runtime record; older records can omit it. Tracked runtime inspection retains an omitted hostname as `undefined` for guarded stop's legacy-record check. It owns their byte-compatible writes, parsing, expected-PID filters, cheap liveness, full OCX command diff --git a/tests/windows/windows-cli-config-root-startup.test.ts b/tests/windows/windows-cli-config-root-startup.test.ts index 66bb750114c..f2a9f8b5a1a 100644 --- a/tests/windows/windows-cli-config-root-startup.test.ts +++ b/tests/windows/windows-cli-config-root-startup.test.ts @@ -12,8 +12,9 @@ import { repoPath } from "../helpers/repo-root"; /** * #7815 owner decision: the CLI waits once at startup for the optional config-root ACL flight - * before a command that writes under the config root does its first write. Read-only, hot-path - * and validate-first commands, and the long-lived server, never start or wait for it. + * before an eligible command does its first write. Commands exempt from preflight repair + * (skipsCodexShimAutoRestore), internal and hidden helpers, ensure and the long-lived server never + * start or wait for it; other read-only commands do wait, as structure/config.md records. */ const success: IcaclsResult = { success: true, exitCode: 0, timedOut: false, stdout: "" }; const turn = () => new Promise(done => setImmediate(done)); From 783ccc4e272cd7a04ccbee7da1793d3a591451ef Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 11 Nov 2026 21:09:12 +0900 Subject: [PATCH 4/4] docs(structure): name ocx ready among the config-root residuals Its own runCli branch runs the Codex-shim restore without the startup wait, kept that way so the readiness probe gains no icacls latency. Refs #7815 --- structure/config.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/structure/config.md b/structure/config.md index f9489a68adc..26ab568c49d 100644 --- a/structure/config.md +++ b/structure/config.md @@ -62,7 +62,7 @@ test seam and the mutation types remain re-exported through `src/config.ts`. Suc `src/config/paths.ts` owns `OPENCODEX_HOME` expansion and resolution, the config directory and `config.json` path. A relative home is resolved once per distinct raw environment value, so a later working-directory change cannot silently move the active installation. Config reads in this leaf and `src/config/load-degrade.ts` use NTFS ACLs on Windows and private POSIX modes elsewhere. Optional directory hardening follows directory symlinks/junctions but skips non-directory or unstatable targets before starting chmod or ACL work. Windows reads omit `chmod` before ACL hardening so repeated loads preserve successful object/freshness observations; external metadata changes still invalidate them. Directory flights keep their existing flush/reap lifecycle, and file/required-write failure policy is unchanged. `tests/windows/windows-config-read-acl-memo.test.ts` covers repeated loads, non-directory and directory-link behavior, external invalidation and POSIX permissions. -`withConfigDirHardeningSettled` in `src/config/paths.ts` admits synchronous mutation after the last unrelated await. Its registry includes the optional config flight, ancestors and retained timeout children; one existing ACL deadline bounds admission, including newly overlapping work. Expiry throws sanitized `WindowsSecretAclSettleTimeoutError` (`ETIMEDOUT`) without running the writer or dropping child cleanup ownership. The final empty-registry check and callback share one turn, with no await in the callback. Intercept/picker CA, token, cleanup, profile and snapshot phases re-enter after trust/discovery awaits. Config saves in `src/server/management/agent-settings-routes.ts` and `src/server/management/config-routes.ts`, Desktop intent/mode commits in `src/server/management/native-integration-routes.ts`, and gateway publication/cleanup in those routes and `src/cli/ensure-desired-integrations.ts` use the same admission. `src/cli/claude-desktop.ts` admits local profile/mode commits and the complete remote-store transaction again after hub download. Lifecycle/config locks are acquired inside admission; refresh re-read, mode/freshness checks, profile and marker publication share one callback. Live setting edits and their save/publication share the admitted synchronous callback; a refused admission leaves both live and durable state untouched. Ordered post-commit phases preserve applied-state warnings or settled compensation, including mode/fingerprint marker refusal and retained CLI intent after incomplete rollback. Synchronous leaf APIs retain their contracts. `tests/claude-integration/claude-config-root-writer-barrier.test.ts` holds parent flights and drives refusal deadlines without sleeps. Lexical/canonical aliases and uncertain identities drain conservatively; removal keeps its separate at-or-below scope and actual-exit requirement. Async local config commands (`src/cli/config-command.ts`, `src/cli/effort.ts`, `src/cli/models.ts`, `src/cli/provider.ts`) admit complete synchronous read/validate/save phases through `withConfigDirHardeningSettled`. Preliminary model selection and client-connection diagnostics use passive observations that cannot publish recovery copies. Final authority and recovery publication are re-read inside admission without starting optional hardening. `src/cli/config-mutation.ts` refuses invalid or unreadable authority, including array/non-object roots rejected before defaults repair, with `CliUsageError`; full-config commands retain fresh-install initialization when the file is absent, while set/unset retain the persisted mutation owner's missing-file refusal. Custom-model removal revalidates the confirmed row by identity and contents while retaining current siblings. Import reads its input and checks its target inside admission. Provider-add credential cleanup shares the synchronous post-save phase and retains its existing post-commit warning. Timeout leaves the mutation database and config untouched and follows existing CLI failure handling. `tests/windows/windows-config-root-async-writers.test.ts` covers held parent flights, deadline refusal, recovery copies, invalid authority and concurrent edits. Codex multi-agent management changes that can resolve a runtime additionally await fresh [selection admission](codex-cli-update.md#worker-realm-and-the-selection-commit-window) before entering this barrier, keep that owner across hardening, and re-evaluate the mode plan inside the synchronous callback; neither ACL wait is inserted into the callback, and refusal leaves the combined mutation untouched. Timer-driven caches under the config root admit their write the same way and build the snapshot inside the callback: the provider account quota cache (`src/providers/account-quota-disk.ts`), the Codex account quota cache (`src/codex/quota.ts`) and the reasoning support cache, while a models.dev refresh admits its publication after the network read (`src/providers/reasoning-metadata.ts`). A timed-out admission skips a best-effort cache write and fails that refresh unpublished, a joined refresh reports the same failure, and a cancel, clear or reset invalidates a write still waiting for admission (#7815; `tests/providers/provider-account-quota-persistence.test.ts`, `tests/codex-integration/reasoning-metadata.test.ts`). The integrations writer (`src/integrations/writer.ts`) runs every coordinated transaction (apply, refresh, overwrite, disable, restore; reached by the catalog fan-out, the Aside sync and profile routes, and integration routes) inside admission on its store root, with the store-lock re-probe in the same callback so no await separates it from the transaction; an admission timeout returns a `write_failed` refusal without a write. An async `revalidate` such as the Aside late confirmation check still runs before admission, so the wait sits between it and the transaction while the writer locks stay held. `disconnectClient` in `src/client/connect.ts` admits each of its two synchronous phases (a timeout before the second leaves the prepared receipt it resumes from), and key rotation admits both remote Desktop credential alignments that precede the hub commit; rollback and post-commit finalization keep their unadmitted paths (`tests/windows/windows-config-root-integration-writers.test.ts`). The CLI also waits once at startup (`src/cli/config-root-startup.ts`, called from `runCli`'s command branch before the version-skew notice and Codex-shim preflight): on Windows it starts the optional config-root flight and drains it with `withConfigDirHardeningSettled(root, () => undefined)` under one ACL deadline, then proceeds even on timeout (`tests/windows/windows-cli-config-root-startup.test.ts`). It skips every command `skipsCodexShimAutoRestore` (`src/cli/preflight-exemptions.ts`) exempts (adding one there also drops this wait), every `internal` and hidden `__*` helper, `start` and `ensure`; for the server and for `ensure`, which the Windows Codex shim runs before every launch, the wait would spend up to one ACL deadline of fixed startup budgets. Residual risk, accepted by owner decision for #7815: (1) only the first write is covered once a later atomic write invalidates the per-process ctime success memo and a later `loadConfig()` starts a new flight; admitted writers stay safe; (2) a fresh install has no directory to wait for, so the first `loadConfig()` after creating it starts a flight while later writers run; (3) a swallowed timeout can leave a retained icacls child running that synchronous writers may overlap; (4) paths that never reach `runCli` (the `start` service logger, the update-restart child, the orchestrated identity probe, the health sentinel, MCP entrypoints) and every excluded command that writes under the root (any command `skipsCodexShimAutoRestore` exempts plus `ensure`, internal and hidden helpers; among them uninstall/remove, sync, orchestrated update, `disconnect --orphaned-token`, codex-shim install/uninstall, `message`, `stop --expect-*`, `lab automation enable|disable`, `lab run`, `lab public import` and `doctor --recover-zero-byte-coordinator --yes`) keep their previous overlap; (5) the server's synchronous writers (`saveConfig`, persisted mutation, management and GUI session tokens, service secrets, the spend-ledger lease, the link store) stay synchronous and can overlap a flight any `loadConfig()` starts; (6) every eligible CLI run on Windows now waits for one icacls run it previously left unawaited, including the commands Remote Link enrollment runs on a Windows Child over SSH (`link port`, `config show --json`, `connect --link`, `restart`) inside its fixed per-command budget, because the success memo is per process and the compliant-ACL precheck is opt-in (`OPENCODEX_ACL_VERIFY_EXISTING`). The writers #7815 named are admitted: config saves and Desktop 3p publication (#7826), the remote Desktop store through `connect.ts` and `claude-desktop.ts` (#7826, #8532) and the integrations writer (#8532). +`withConfigDirHardeningSettled` in `src/config/paths.ts` admits synchronous mutation after the last unrelated await. Its registry includes the optional config flight, ancestors and retained timeout children; one existing ACL deadline bounds admission, including newly overlapping work. Expiry throws sanitized `WindowsSecretAclSettleTimeoutError` (`ETIMEDOUT`) without running the writer or dropping child cleanup ownership. The final empty-registry check and callback share one turn, with no await in the callback. Intercept/picker CA, token, cleanup, profile and snapshot phases re-enter after trust/discovery awaits. Config saves in `src/server/management/agent-settings-routes.ts` and `src/server/management/config-routes.ts`, Desktop intent/mode commits in `src/server/management/native-integration-routes.ts`, and gateway publication/cleanup in those routes and `src/cli/ensure-desired-integrations.ts` use the same admission. `src/cli/claude-desktop.ts` admits local profile/mode commits and the complete remote-store transaction again after hub download. Lifecycle/config locks are acquired inside admission; refresh re-read, mode/freshness checks, profile and marker publication share one callback. Live setting edits and their save/publication share the admitted synchronous callback; a refused admission leaves both live and durable state untouched. Ordered post-commit phases preserve applied-state warnings or settled compensation, including mode/fingerprint marker refusal and retained CLI intent after incomplete rollback. Synchronous leaf APIs retain their contracts. `tests/claude-integration/claude-config-root-writer-barrier.test.ts` holds parent flights and drives refusal deadlines without sleeps. Lexical/canonical aliases and uncertain identities drain conservatively; removal keeps its separate at-or-below scope and actual-exit requirement. Async local config commands (`src/cli/config-command.ts`, `src/cli/effort.ts`, `src/cli/models.ts`, `src/cli/provider.ts`) admit complete synchronous read/validate/save phases through `withConfigDirHardeningSettled`. Preliminary model selection and client-connection diagnostics use passive observations that cannot publish recovery copies. Final authority and recovery publication are re-read inside admission without starting optional hardening. `src/cli/config-mutation.ts` refuses invalid or unreadable authority, including array/non-object roots rejected before defaults repair, with `CliUsageError`; full-config commands retain fresh-install initialization when the file is absent, while set/unset retain the persisted mutation owner's missing-file refusal. Custom-model removal revalidates the confirmed row by identity and contents while retaining current siblings. Import reads its input and checks its target inside admission. Provider-add credential cleanup shares the synchronous post-save phase and retains its existing post-commit warning. Timeout leaves the mutation database and config untouched and follows existing CLI failure handling. `tests/windows/windows-config-root-async-writers.test.ts` covers held parent flights, deadline refusal, recovery copies, invalid authority and concurrent edits. Codex multi-agent management changes that can resolve a runtime additionally await fresh [selection admission](codex-cli-update.md#worker-realm-and-the-selection-commit-window) before entering this barrier, keep that owner across hardening, and re-evaluate the mode plan inside the synchronous callback; neither ACL wait is inserted into the callback, and refusal leaves the combined mutation untouched. Timer-driven caches under the config root admit their write the same way and build the snapshot inside the callback: the provider account quota cache (`src/providers/account-quota-disk.ts`), the Codex account quota cache (`src/codex/quota.ts`) and the reasoning support cache, while a models.dev refresh admits its publication after the network read (`src/providers/reasoning-metadata.ts`). A timed-out admission skips a best-effort cache write and fails that refresh unpublished, a joined refresh reports the same failure, and a cancel, clear or reset invalidates a write still waiting for admission (#7815; `tests/providers/provider-account-quota-persistence.test.ts`, `tests/codex-integration/reasoning-metadata.test.ts`). The integrations writer (`src/integrations/writer.ts`) runs every coordinated transaction (apply, refresh, overwrite, disable, restore; reached by the catalog fan-out, the Aside sync and profile routes, and integration routes) inside admission on its store root, with the store-lock re-probe in the same callback so no await separates it from the transaction; an admission timeout returns a `write_failed` refusal without a write. An async `revalidate` such as the Aside late confirmation check still runs before admission, so the wait sits between it and the transaction while the writer locks stay held. `disconnectClient` in `src/client/connect.ts` admits each of its two synchronous phases (a timeout before the second leaves the prepared receipt it resumes from), and key rotation admits both remote Desktop credential alignments that precede the hub commit; rollback and post-commit finalization keep their unadmitted paths (`tests/windows/windows-config-root-integration-writers.test.ts`). The CLI also waits once at startup (`src/cli/config-root-startup.ts`, called from `runCli`'s command branch before the version-skew notice and Codex-shim preflight): on Windows it starts the optional config-root flight and drains it with `withConfigDirHardeningSettled(root, () => undefined)` under one ACL deadline, then proceeds even on timeout (`tests/windows/windows-cli-config-root-startup.test.ts`). It skips every command `skipsCodexShimAutoRestore` (`src/cli/preflight-exemptions.ts`) exempts (adding one there also drops this wait), every `internal` and hidden `__*` helper, `start` and `ensure`; for the server and for `ensure`, which the Windows Codex shim runs before every launch, the wait would spend up to one ACL deadline of fixed startup budgets. Residual risk, accepted by owner decision for #7815: (1) only the first write is covered once a later atomic write invalidates the per-process ctime success memo and a later `loadConfig()` starts a new flight; admitted writers stay safe; (2) a fresh install has no directory to wait for, so the first `loadConfig()` after creating it starts a flight while later writers run; (3) a swallowed timeout can leave a retained icacls child running that synchronous writers may overlap; (4) paths that never reach `runCli` (the `start` service logger, the update-restart child, the orchestrated identity probe, the health sentinel, MCP entrypoints) and every excluded command that writes under the root (any command `skipsCodexShimAutoRestore` exempts plus `ensure`, internal and hidden helpers; among them uninstall/remove, sync, orchestrated update, `disconnect --orphaned-token`, codex-shim install/uninstall, `message`, `stop --expect-*`, `lab automation enable|disable`, `lab run`, `lab public import` and `doctor --recover-zero-byte-coordinator --yes`), and `ready`, whose own `runCli` branch runs the Codex-shim restore (which can write `codex-shim.json` and its restore lock under the root) without the wait so the readiness probe gains no icacls latency, keep their previous overlap; (5) the server's synchronous writers (`saveConfig`, persisted mutation, management and GUI session tokens, service secrets, the spend-ledger lease, the link store) stay synchronous and can overlap a flight any `loadConfig()` starts; (6) every eligible CLI run on Windows now waits for one icacls run it previously left unawaited, including the commands Remote Link enrollment runs on a Windows Child over SSH (`link port`, `config show --json`, `connect --link`, `restart`) inside its fixed per-command budget, because the success memo is per process and the compliant-ACL precheck is opt-in (`OPENCODEX_ACL_VERIFY_EXISTING`). The writers #7815 named are admitted: config saves and Desktop 3p publication (#7826), the remote Desktop store through `connect.ts` and `claude-desktop.ts` (#7826, #8532) and the integrations writer (#8532). `src/config/process-state.ts` derives `ocx.pid` and `runtime-port.json` from that resolved directory. Ordinary and connected-client runtimes publish their absolute relaunch command in the runtime record; older records can omit it. Tracked runtime inspection retains an omitted hostname as `undefined` for guarded stop's legacy-record check. It owns their byte-compatible writes, parsing, expected-PID filters, cheap liveness, full OCX command