Skip to content

fix(codex): grant hook trust via Codex app-server RPCs instead of self-computed trusted_hash - #8847

Closed
brennanb2025 wants to merge 13 commits into
mainfrom
brennanb2025/codex-trust-rpc-grant
Closed

brennanb2025 wants to merge 13 commits into
mainfrom
brennanb2025/codex-trust-rpc-grant

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Orca pre-trusts its managed Codex status hooks by re-implementing Codex's private command_hook_hash algorithm (computeTrustedHash in config-toml-trust.ts) and writing [hooks.state] blocks into the managed runtime home's config.toml with a byte-preserving regex editor. Every time the replica drifted from Codex's real algorithm or key shape, users got stuck in "hooks pending review" / endless re-approval loops — #7896, #7110, #8699 are all instances of this one bug class. Upstream has no stable public contract for the hash (openai/codex#21615).

Mechanism

Codex ships a sanctioned equivalent: the TUI "Trust all" button calls two codex app-server JSON-RPCs — hooks/list (returns each discovered hook's state key, Codex-computed currentHash, and trustStatus) and config/batchWrite (upserts hooks.state.<key>.trusted_hash through Codex's own comment-preserving config writer). Upstream references: codex-rs/tui/src/hooks_rpc.rs, codex-rs/tui/src/startup_hooks_review.rs, codex-rs/app-server-protocol/src/protocol/common.rs.

Hook install/refresh now grants trust through that pair, with Codex as the only hash authority:

  1. After the managed hooks.json is written, a short-lived codex app-server session (stdio JSONL) runs initialize → hooks/list → config/batchWrite → hooks/list, granting trust for exactly Orca's managed entries — matched by trust key and exact command string, with duplicate-normalized-key rejection; user hooks are never written — and verifying via re-list that every expected entry reports trusted before launch proceeds.
  2. Because install/refresh is synchronous launch prep, the session runs in a bundled ELECTRON_RUN_AS_NODE entry (codex/codex-app-server-grant-entry.js, same pattern as the daemon/watcher entries) while the caller blocks on spawnSync with a hard deadline and SIGKILL reap; a killed entry closes the server's stdin, which makes it exit on EOF (no orphans on any path). Timeouts are classified end-to-end (entry hard-deadline envelope is written with a synchronous flush; spawnSync ETIMEDOUT maps to the typed timeout error).
  3. A capability cache modeled on GitCapabilityCache (per docs/reference/git-compatibility.md) scopes support per execution host — native vs each WSL distro — and only a positive absence signal (JSON-RPC -32601 / missing app-server subcommand) marks a host unsupported, with a 30-minute retry so an in-place CLI upgrade self-heals. Transient failures fall back without poisoning the capability and enter a short transient cooldown so a wedged CLI cannot charge its RPC timeout to every launch.
  4. A grant ledger (codex-runtime-home/trust-grant-ledger.json) records each verified grant (hook identity signature, Codex's hash, codex binary stamp). Steady-state launches skip the RPC entirely — zero subprocesses — while any drift (hook change, config wipe, codex upgrade via binary stamp) re-grants before the pane launches. getStatus validates ledger hashes against the current binary stamp so a codex upgrade reads conservatively.
  5. Fallback is unchanged and byte-identical: before each session the runtime config.toml is snapshotted (contents + mode, single-fd capture) and restored on any failure path, so the previous computeTrustedHash + regex-editor lane always runs against the same input it would have seen pre-RPC. The entire pre-existing hook-service suite executes through the fallback branch unmodified. getStatus and the removal paths recognize ledger-recorded Codex hashes (including prior-ledger records across WSL canonical-path changes) so granted entries are never misreported or stranded.

WSL runtime homes grant through wsl.exe -d <distro> running codex inside the distro (login-shell PATH lookup), so the hash authority is the same binary the pane runs; native grants resolve the codex binary once per grant. The SSH remote install path is untouched by design — installRemote and installer-utils-remote.ts are byte-identical to the merge base (content-hash verified).

No settings, no UI changes. Ops escape hatch: ORCA_DISABLE_CODEX_TRUST_RPC=1 forces the fallback lane. Diagnostics: [codex-trust-grant] logs plus a low-cardinality codex_trust_grant telemetry event (granted / fallback / verify_failed + reason; emission isolated so a tracker fault can never fail a grant).

Verification

Unit/integration (315 tests across the codex suites, all green): client session against a scripted stdio stub (grant+verify, already-trusted with write-rejection proof, missing-entry verify-fail, -32601 and missing-subcommand → unsupported class, hung-server kill at deadline, spawn ENOENT ≠ capability signal, user hooks excluded from the batch write); capability cache (retry interval, first-fallback, cached calls, native/WSL-distro isolation, support dropped on later unsupported, transients rethrown unmarked); grant orchestrator (verbatim-hash mapping, ledger hits and drift re-grants, kill switch, WSL invocation, rollback + cooldown paths, duplicate-key rejection); hook service (codex hash authoritative in status even when it differs from the self-computed hash — the drift case that used to misreport; byte-stable repeat install with zero extra sessions; upgrade over self-written entries leaves one table per key; user trust preserved; forced fallback writes the previous lane's exact hashes); config rollback (fd-consistent capture, byte and permission restoration); WSL parity suites.

Real-binary round trips (installed codex-cli, throwaway isolated CODEX_HOMEs, run against the built entry exactly as production spawns it):

  • Scenario suite on 0.144.4 — fresh grant untrusted → trusted 6/6 (~150 ms) with comments and a user enabled = false block preserved byte-for-byte; upgrade over stale self-written [hooks.state] blocks granted in place (one table per key, enabled lines preserved, stale hash gone); idempotent second run issues no write and is byte-stable; user-disabled entries stay disabled; deadline timeout and SIGKILL mid-session leave no orphan processes and an intact, parseable config; post-grant hooks/list (the same discovery codex's startup review gate runs) reports zero hooks needing review.
  • CLI version matrix (real npm releases): 0.136.0 / 0.140.0 / 0.143.0 / 0.144.4 all grant 6/6 with verification; 0.120.0 / 0.129.0 (app-server predates hooks/list and exits silently) land in the transient fallback with the home byte-untouched and no orphans; a CLI with no app-server subcommand classifies as unsupported and stays on the cached fallback.
  • Config matrix (0.144.4): malformed config.toml → verify-failed with the file untouched; BOM+CRLF with profiles/projects → granted with sections preserved; user hooks with matchers → zero user trust keys written; 300-hook/180 KB hooks.json → granted; missing hooks.json → safe verify-failed.

Live interactive TUI sessions (real PTY, API-key auth): a positive control — same home shape with stale hashes and no grant — shows the hooks-review screen, proving the "no modal" results are meaningful; the identical home after a grant reaches the session UI with no review screen; and the in-session /hooks browser lists all six managed events as Installed 1 / Active 1 with no review grouping.

Electron end-to-end (dev build, isolated ORCA_DEV_USER_DATA_PATH, CDP-driven): first PTY spawn logs [codex-trust-grant] granted 6 managed hook entries via codex app-server (host=native, wrote=true, 454ms); a real codex pane reaches the session UI with no review prompt and a prompt round-trip surfaces in the sidebar (working → done, matching assistant message, session history); two racing panes produce exactly one grant session (ledger hits after) and zero orphan processes; a forced-fallback run (PATH shim rejecting app-server) logs reason=unsupported then reason=unsupported-cached, writes the previous lane's self-computed hashes, and still completes a session with sidebar status. This run also exercised a custom model_providers config end-to-end.

Gates: full typecheck (node/cli/web), lint, max-lines and reliability gates, production build (including the plain-node entry guard that keeps the grant entry's chunk graph electron-free).

CI note: the native-smoke (windows-latest) failure is pre-existing on main — the same cpu-features node-gyp Visual Studio–finder failure during pnpm install appears on main's scheduled runs since at least 2026-07-11 (e.g. run 29395564260); this PR changes no dependencies or native modules.

Follow-ups (not in this PR)

  • WSL binary stamp: no cheap way to fingerprint the in-distro codex binary from the host, so a WSL codex upgrade re-grants on the next drift signal rather than pre-emptively (native hosts re-grant pre-emptively via the binary stamp).
  • The plain-node CLI hook controls (orca agent hooks on) resolve the grant entry relative to the emitted chunk; if unresolvable they fall back to the previous lane (logged). Electron main is the rollout target.
  • Mirrored user hook trust still carries hashes verbatim from ~/.codex (existing lane); a later phase could move user-hook mirroring onto hooks/list as well.
  • Pre-existing: the config mirror can drop comments adjacent to runtime-owned hooks.state sections when the system config.toml is absent (observed while writing tests; unrelated to this change).

…nt ledger

Short-lived codex app-server JSON-RPC client (hooks/list + config/batchWrite,
the same pair the Codex TUI 'Trust all' flow calls), run in a bundled
ELECTRON_RUN_AS_NODE entry so synchronous launch prep can block on it with a
hard deadline and guaranteed child reap. Capability cache modeled on
GitCapabilityCache, scoped per execution host (native vs each WSL distro),
with a narrow unknown-method/missing-subcommand unsupported predicate. The
grant ledger records verified grants so steady-state launches skip the RPC.
…tall/refresh

Host and WSL installs now grant trust for Orca's managed status hooks through
codex's own hooks/list -> config/batchWrite -> re-list verify, scoped to
exactly the managed entries; the previous computeTrustedHash lane is the
unchanged fallback for incapable/erroring CLIs. getStatus and the removal
paths recognize ledger-recorded codex hashes so drift between codex's real
algorithm and the replica no longer misreports or strands trust. SSH remote
install is untouched by design.
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a Codex app-server JSON-RPC trust-grant client, a synchronous Node-mode bundle entry, WSL command construction, capability caching, persistent trust-grant ledgers, and configuration rollback. Integrates granted trust hashes into native and WSL hook installation, cleanup, stale-entry reconciliation, and status checks. Adds telemetry schema and startup wiring, Rollup and CLI build configuration, and comprehensive tests for protocol handling, retries, ledger behavior, fallback paths, rollback, WSL flows, and reconciliation.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: moving Codex hook trust granting to app-server RPCs instead of local hash computation.
Description check ✅ Passed The description is thorough and covers summary, testing, and notes, but it does not follow the template headings for Screenshots, AI Review Report, or Security Audit.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/main/codex/hook-service.ts (3)

775-805: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Preserve the previous ledger until stale WSL grants are removed.

A successful grant replaces the home ledger before stale cleanup reloads it. After a canonical WSL path changes, old keys with Codex-computed hashes are absent from the new ledger and may not match computeTrustedHash, so their trust blocks survive cleanup.

Capture the pre-grant ledger for cleanup, or merge old records and prune them only after cleanup succeeds.

Also applies to: 970-976


1182-1237: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Validate the ledger’s binary stamp before accepting its hashes.

Unlike the grant ledger-hit path, getStatus() accepts a matching signature without comparing the recorded stamp to the current Codex binary. After an upgrade, this can report installed using a grant produced by the previous binary.

Reuse the same binary-stamp validation used by findLedgerGrant.


639-805: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Split the new trust-grant flow instead of extending max-lines-disabled files.

  • src/main/codex/hook-service.ts#L639-L805: extract ledger recognition and cleanup into a trust-reconciliation module.
  • src/main/codex/hook-service.ts#L961-L977: delegate WSL grant reconciliation to that module.
  • src/main/codex/hook-service.ts#L1182-L1237: extract ledger-backed status validation.
  • src/main/codex/hook-service.ts#L1337-L1400: delegate native grant reconciliation.
  • src/main/codex/hook-service.test.ts#L1468-L1652: move the standalone grant-lane suite to a dedicated test file.

As per coding guidelines, never disable max-lines through ESLint or oxlint.

Source: Coding guidelines

🧹 Nitpick comments (1)
src/main/codex/codex-wsl-hook-install-plan.ts (1)

192-192: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use pathPosix.join for the Linux trust path.
Import pathPosix here and build trustConfigPath with pathPosix.join(linuxRuntimeHome, 'hooks.json') to keep Linux-side path handling explicit and consistent with the rest of the WSL code.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 6d08faf3-2aa6-40e6-a894-8c64827992cb

📥 Commits

Reviewing files that changed from the base of the PR and between e74a8e0 and c9837fe.

📒 Files selected for processing (19)
  • build-plugins/plain-node-entry-guard.ts
  • electron.vite.config.ts
  • src/main/codex-accounts/wsl-codex-command.ts
  • src/main/codex/codex-app-server-capability-cache.test.ts
  • src/main/codex/codex-app-server-capability-cache.ts
  • src/main/codex/codex-app-server-client.test.ts
  • src/main/codex/codex-app-server-client.ts
  • src/main/codex/codex-app-server-grant-bridge.ts
  • src/main/codex/codex-app-server-grant-entry.ts
  • src/main/codex/codex-hook-trust-grant.test.ts
  • src/main/codex/codex-hook-trust-grant.ts
  • src/main/codex/codex-trust-grant-ledger.test.ts
  • src/main/codex/codex-trust-grant-ledger.ts
  • src/main/codex/codex-wsl-hook-install-plan.ts
  • src/main/codex/hook-service-wsl-runtime.test.ts
  • src/main/codex/hook-service.test.ts
  • src/main/codex/hook-service.ts
  • src/main/index.ts
  • src/shared/telemetry-events.ts

Comment thread src/main/codex/hook-service.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: efe0a4ed-76f6-4b03-a4f8-498bac04fdec

📥 Commits

Reviewing files that changed from the base of the PR and between c9837fe and 5c68a50.

📒 Files selected for processing (13)
  • config/tsconfig.cli.json
  • src/main/codex/codex-app-server-client.test.ts
  • src/main/codex/codex-app-server-client.ts
  • src/main/codex/codex-app-server-grant-bridge.ts
  • src/main/codex/codex-app-server-grant-entry.ts
  • src/main/codex/codex-app-server-grant-envelope.ts
  • src/main/codex/codex-hook-trust-grant.test.ts
  • src/main/codex/codex-hook-trust-grant.ts
  • src/main/codex/codex-trust-config-rollback.ts
  • src/main/codex/hook-service-wsl-runtime.test.ts
  • src/main/codex/hook-service.test.ts
  • src/main/codex/hook-service.ts
  • src/shared/telemetry-events.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • src/main/codex/hook-service.test.ts
  • src/main/codex/codex-app-server-grant-entry.ts
  • src/main/codex/codex-app-server-client.test.ts
  • src/shared/telemetry-events.ts
  • src/main/codex/hook-service-wsl-runtime.test.ts
  • src/main/codex/codex-hook-trust-grant.test.ts
  • src/main/codex/codex-hook-trust-grant.ts
  • src/main/codex/hook-service.ts

…ies stay electron-free

The build guard rejects any electron require reachable from plain-node
entries; the bridge now maps app.asar to app.asar.unpacked by string
replacement instead of consulting electron app paths. CLI typecheck project
lists the new trust-grant module graph.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 2204b449-4689-47f7-9ef5-fb3131fa7183

📥 Commits

Reviewing files that changed from the base of the PR and between 5c68a50 and d4f5493.

📒 Files selected for processing (15)
  • config/tsconfig.cli.json
  • src/main/codex/codex-app-server-client.test.ts
  • src/main/codex/codex-app-server-grant-bridge.ts
  • src/main/codex/codex-hook-trust-grant.test.ts
  • src/main/codex/codex-hook-trust-grant.ts
  • src/main/codex/codex-managed-trust-reconciliation.ts
  • src/main/codex/codex-trust-config-rollback.test.ts
  • src/main/codex/codex-trust-config-rollback.ts
  • src/main/codex/codex-trust-grant-host.test.ts
  • src/main/codex/codex-trust-grant-host.ts
  • src/main/codex/codex-wsl-hook-install-plan.test.ts
  • src/main/codex/codex-wsl-hook-install-plan.ts
  • src/main/codex/hook-service-trust-grant.test.ts
  • src/main/codex/hook-service-wsl-runtime.test.ts
  • src/main/codex/hook-service.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • config/tsconfig.cli.json
  • src/main/codex/codex-app-server-client.test.ts
  • src/main/codex/codex-hook-trust-grant.test.ts
  • src/main/codex/hook-service-wsl-runtime.test.ts
  • src/main/codex/codex-hook-trust-grant.ts
  • src/main/codex/hook-service.ts

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Extended verification: version matrix, config matrix, and live interactive TUI sessions

Follow-up evidence beyond the PR body, run against real codex binaries (npm releases installed into isolated prefixes) and real interactive TUI sessions (PTY-driven), all in throwaway CODEX_HOMEs.

CLI version matrix (real binaries, built grant entry — exactly what production spawns)

codex version app-server behavior grant outcome home integrity
0.120.0 exits silently before answering initialize (exit 0, no stderr) transient error → unchanged fallback lane config untouched, no orphans
0.129.0 same same same
0.136.0 hooks/list + config/batchWrite work granted 6/6, verified sentinel comment preserved, no orphans
0.140.0 same granted 6/6 same
0.143.0 same granted 6/6 same
0.144.4 (installed) same granted 6/6 same

So the RPC lane works across ≥0.136.x, and the two pre-hooks/list generations land in the safe fallback with zero damage. They classify as transient (not unsupported) because a clean exit leaves no protocol-absence signal to key on — the transient cooldown bounds the cost to one instant failed spawn per drift-state launch at most, and steady-state launches never spawn at all (ledger). A CLI with no app-server subcommand does produce the clean signal and lands in unsupported/unsupported-cached (proven end-to-end in the forced-fallback Electron run).

Config-variation matrix (0.144.4)

home shape outcome
malformed config.toml (parse error) codex lists 0 hooks → verify-failed → fallback lane; file byte-untouched
BOM + CRLF + [profiles.*] + [projects.*] granted 6/6; profiles/projects preserved (codex's own writer drops the BOM — upstream normalization; Orca's reader tolerates both)
user hooks alongside ours, incl. matcher groups granted for exactly our 6 keys; zero user trust keys written
300 user hooks / 180 KB hooks.json granted 6/6, well inside response-size bounds
missing hooks.json verify-failed → fallback; file untouched

Live interactive TUI sessions (real PTY, API-key auth, default provider — the Electron e2e separately covered a custom model_providers config)

  • Positive control: home seeded with stale self-written trusted_hash, no grant → the hooks-review screen appears ("Trust all and continue…"). This is what makes every "no modal" claim in this PR meaningful.
  • Same drifted home, grant run first → no review screen anywhere in the transcript; session UI reached.
  • /hooks browser inside the granted session: all six managed events show Installed 1 / Active 1, no review/untrusted grouping — codex itself reports the RPC-granted trust as active.

Residual risk (unchanged from PR body)

Windows native and live-WSL grants are covered by unit suites + the host-scoped capability cache, not by a live machine in this run; any surprise there degrades to the byte-identical fallback lane, i.e. exactly today's shipped behavior.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/codex/codex-app-server-client.ts (1)

363-372: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Clear timers to prevent event loop leaks.

Un-cleared timeouts inside Promise.race will keep the Node.js event loop alive and leak memory handles for their full duration, even if exitPromise resolves immediately. This can inadvertently delay process exit or cause temporary resource spikes. Store the timeout IDs and clear them when the race completes.

🐛 Proposed fix
     if (!exited) {
       // Why: the server exits promptly on stdin EOF; the grace period only
       // bounds a wedged child before the guaranteed SIGKILL reap.
-      const grace = new Promise<void>((resolve) => setTimeout(resolve, 1500))
+      let graceTimer!: ReturnType<typeof setTimeout>
+      const grace = new Promise<void>((resolve) => {
+        graceTimer = setTimeout(resolve, 1500)
+      })
       await Promise.race([exitPromise, grace])
+      clearTimeout(graceTimer)
       if (!exited) {
         child.kill('SIGKILL')
-        await Promise.race([exitPromise, new Promise<void>((resolve) => setTimeout(resolve, 1000))])
+        let killTimer!: ReturnType<typeof setTimeout>
+        const killGrace = new Promise<void>((resolve) => {
+          killTimer = setTimeout(resolve, 1000)
+        })
+        await Promise.race([exitPromise, killGrace])
+        clearTimeout(killTimer)
       }
     }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 674bd752-efee-4c44-977b-6f47690f9184

📥 Commits

Reviewing files that changed from the base of the PR and between 8f9da3e and 1581e32.

📒 Files selected for processing (5)
  • src/main/codex/codex-app-server-client.test.ts
  • src/main/codex/codex-app-server-client.ts
  • src/main/codex/codex-trust-grant-host.ts
  • src/main/codex/hook-service-trust-grant.test.ts
  • src/main/codex/hook-service.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/codex/codex-trust-grant-host.ts
  • src/main/codex/hook-service-trust-grant.test.ts
  • src/main/codex/hook-service.ts
  • src/main/codex/codex-app-server-client.test.ts

@OrcaWin

OrcaWin commented Jul 15, 2026

Copy link
Copy Markdown
Collaborator

Windows-native / WSL validation result: FAIL — two Windows/WSL findings need follow-up. The direct real-binary grant paths pass, but the live WSL Electron pane still asks to review all 6 hooks, and the requested Windows Codex Vitest suite has 2 failures. I made no production changes and did not push anything.

Environment:

Item Value
Checkout brennanb2025/codex-trust-rpc-grant at 1581e324a
Host Windows 11 Pro 10.0.26200 (build 26200), Node v24.18.0, pnpm 10.24.0
Host Codex codex-cli 0.144.4
WSL Ubuntu, Ubuntu 26.04 LTS, Codex codex-cli 0.144.1
Isolation Throwaway host CODEX_HOMEs and disposable WSL users/homes only; real host %USERPROFILE%\.codex and real WSL ~/.codex were not used

Setup:

Check Result Evidence
pnpm install --frozen-lockfile PASS Completed without the known cpu-features / VS-finder failure
pnpm run build:electron-vite PASS Build completed
pnpm run build:relay PASS Built for the WSL Electron run
Electron skill reference NOTE .claude/skills/electron/SKILL.md is absent in this checkout; I used the repository E2E/CDP helpers and the documented isolated-profile variables

1. Native Windows real-binary grant

Check Result Evidence
Initial real-binary grant PASS Envelope ok:true, outcome:"granted", wroteTrust:true, 6 entries; re-list reported all 6 trusted
Windows key normalization PASS hooks/list returned native-backslash keys such as C:\Users\...\hooks.json:pre_tool_use:0:0; normalizeHookTrustKeyForLookup matched them and the grant succeeded
Byte preservation PASS Seed comment and fake user [hooks.state.'C:\fake\user-hooks.json:stop:9:9'] block were byte-preserved
npm .cmd shim PASS C:\Users\neil\AppData\Roaming\npm\codex.cmd granted 6/6 through the cmd.exe spawn lane
Process cleanup PASS No new host node.exe / codex.exe remained after the scenarios

2. Windows idempotency and stale-hash upgrade

Check Result Evidence
Second real-binary run PASS outcome:"granted", wroteTrust:false; config.toml byte-identical to the first result
sha256:stale upgrade PASS outcome:"granted", wroteTrust:true, 6 entries, all trusted on re-list
Duplicate tables PASS Exactly one table per key and 6 managed headers total

3. Windows timeout and forced-kill behavior

Check Result Evidence
timeoutMs:1 PASS Typed timeout envelope; config before/after byte-identical; no additional process
taskkill /F entry mid-session PASS Entry was killed without /T; its real codex.exe child did not survive; config remained byte-identical and parseable by a real hooks/list probe
Deterministic timing NOTE A disposable proxy only buffered the real RPC session before the write, making the kill window deterministic; the spawned app-server child was the installed real binary

Timeout envelope:

{"ok":false,"errorName":"CodexAppServerTimeoutError","message":"codex app-server session exceeded 1ms (codex)"}

Timeout/kill config before and after:

[hooks.state]
# PR #8847 byte-preservation sentinel
[hooks.state.'C:\fake\user-hooks.json:stop:9:9']
enabled = false

Both entry stderr streams were empty.

4. Direct live WSL grant

Check Result Evidence
Real WSL grant with built command args PASS Used the built buildWslCodexAppServerArgs("Ubuntu", linuxHome) output; outcome:"granted", wroteTrust:true, 6/6 trusted; fake user block preserved
WSL process cleanup PASS pgrep -f "codex app-server" empty after grant
Missing-Codex classification PASS Temporary PATH shadow returned errorName:"Error" (transient), not unsupported; config byte-stable and shadow removed

Missing-Codex envelope:

{"ok":false,"errorName":"Error","message":"codex app-server exited before completing the session: Codex intentionally shadowed for PR #8847 evidence."}

Missing-Codex config before and after:

[hooks.state]
# PR #8847 byte-preservation sentinel
[hooks.state.'C:\fake\user-hooks.json:stop:9:9']
enabled = false

stderr was empty.

5. Electron E2E

Target Result Evidence
Native RPC PASS [codex-trust-grant] granted 6 managed hook entries via codex app-server (host=native, wrote=true, 2254ms); no hook-review pane; local /v1/responses mock called; ORCA_E2E_ACK; sidebar state working → done
WSL RPC FAIL Grant log says host=wsl, wrote=true, but the real WSL Codex 0.144.1 pane shows Hooks need review / 6 hooks are new or changed.
Native fallback (ORCA_DISABLE_CODEX_TRUST_RPC=1) PASS reason=disabled, host=native; no hook-review pane; local mock round trip returned ORCA_E2E_ACK; sidebar state working → done

WSL Electron failure capture (focused reproduction):

  • Exact Codex version: codex-cli 0.144.1.

  • Observable service logs:

    [codex-trust-grant] granted 6 managed hook entries via codex app-server (host=native, wrote=true, 2271ms)
    [codex-trust-grant] granted 6 managed hook entries via codex app-server (host=wsl, wrote=true, 3821ms)
    
  • Pane text:

    Hooks need review
    6 hooks are new or changed.
    Hooks can run outside the sandbox after you trust them.
    
  • JSON envelope: not exposed by the Electron integration boundary; the service log above is the returned observable result.

  • Driver stderr: empty.

  • Managed runtime home: /home/pr8847e2e641562/.local/share/orca/codex-runtime-home/home under a disposable WSL user.

  • Runtime config.toml before launch: absent.

  • Runtime config.toml after the logged successful grant:

    model = "orca-e2e"
    model_provider = "orca_e2e"
    approval_policy = "never"
    sandbox_mode = "read-only"
    disable_response_storage = true
    
    [model_providers.orca_e2e]
    name = "Orca PR 8847 local mock"
    base_url = "http://127.0.0.1:56595/v1"
    env_key = "OPENAI_API_KEY"
    wire_api = "responses"
    request_max_retries = 0
    stream_max_retries = 0
    
    [projects.'/home/pr8847e2e641562/workspace']
    trust_level = "trusted"
    
    [hooks.state]

    The after-file contains no per-hook trust tables despite the wrote=true log. The disposable source-profile config was byte-stable.

6. Windows suites

Command Result Evidence
npx vitest run --config config/vitest.config.ts src/main/codex/ FAIL 18 files: 17 passed, 1 failed. 316 tests: 303 passed, 11 skipped, 2 failed. Duration 14.43s
pnpm run typecheck:node PASS tsc --noEmit -p config/tsconfig.node.json exited 0

Vitest failures (not fixed):

  1. CodexHookService app-server trust grant lane > keeps config byte-stable and skips the session on a repeat ledger hit
    • runner was correctly called once, but the second config.toml buffer was not byte-equal to the first. The Windows result removed/reformatted the empty parent [hooks.state] header before the first per-key table.
    • Assertion: src/main/codex/hook-service-trust-grant.test.ts:142.
  2. CodexHookService app-server trust grant lane > upgrades self-computed trust in place without duplicate tables
    • First observed count was 2 tables for session_start, expected 1 (the loop stops at the first failing key).
    • Assertion: src/main/codex/hook-service-trust-grant.test.ts:187.

Final cleanup audit:

Check Result
Host Codex processes Only the two pre-existing agent processes remained (node.exe PID 1996, codex.exe PID 8352)
WSL default user Restored to root
Temporary WSL users/homes 0
WSL codex app-server processes 0
Production worktree changes None

… probe

The async wsl.exe canonical-path settlement could report the runtime home
'missing' immediately after a verified RPC grant (a false negative — codex
had just written and re-listed trust there), which drove the reconciliation
'remove' branch to delete all six granted [hooks.state] tables, leaving a bare
[hooks.state] the launching pane read as 'hooks need review'. A 'missing'
settlement now revokes only when no successful install ran this generation; a
genuinely moved home still resolves to a different path and reinstalls.
The grant-lane stub simulated codex by calling Orca's upsertHookTrustEntries,
which writes both separator variants for a Windows key (a fallback-lane compat
shim real codex never does) — fabricating duplicate tables and whitespace the
RPC path never produces, so the byte-stable and no-duplicate assertions failed
on win32. Replace it with a single-variant, blank-line-separated writer that
matches the real 0.144.x binary's output.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Windows/WSL agent findings — investigated and fixed

Thanks for the thorough Windows+WSL run. Both findings were real; both are now addressed on the branch. macOS suites (src/main/codex/ = 18 files, 311 pass), full typecheck, and lint are green after the fixes. These specific changes need a Windows/WSL re-run to confirm behavior, since neither is reproducible on macOS.

Finding 1 — WSL pane still shows "Hooks need review" despite wrote=true (real product bug)

Root cause: a config mutation after the verified grant stripped the six granted [hooks.state."…"] child tables, leaving the bare [hooks.state] parent the pane then read as untrusted. The empty-parent-with-no-children shape is the fingerprint of removeHookTrustEntries (it removes child blocks but not the parent).

Two independent post-grant mutation paths are now guarded:

  • Config mirror (87db673fc): isRuntimeHookTrustTomlSection now also matches the bare [hooks.state] parent so the mirror treats it as runtime-owned, and the synchronous WSL removeStale was moved before the grant so codex's verified RPC write is the final synchronous mutation.
  • Async canonical-path reconciliation (caf6cac3d): the off-thread wsl.exe readlink -f probe could report the runtime home missing immediately after a verified grant — a false negative, since codex had just written and re-listed trust in that exact home. That drove getWslHookReconciliationAction to 'remove', which called removeStaleWslRuntimeManagedHookTrustEntries(config, []) and deleted the fresh grant. It now takes an installSucceeded flag and returns 'none' for missing when an install/grant succeeded this generation; a genuinely relocated home still resolves to a different path and takes the 'reinstall' branch. Unit-tested in hook-service-wsl-runtime.test.ts.

Finding 2 — two Windows Vitest failures (test-fidelity, not product)

Both failing tests exercised a stub that simulated codex's grant by calling Orca's upsertHookTrustEntries, which writes both path-separator variants for a Windows key — a fallback-lane compatibility shim that real codex's config/batchWrite never does (your own native run confirmed real codex writes exactly one table per key). That fabricated duplicate tables and whitespace the RPC path never produces.

  • The "no duplicate tables" test now counts normalized trust identities (87db673fc).
  • The "byte-stable repeat" test's stub now writes single-variant, blank-line-separated tables matching the real 0.144.x binary's output (1f9ab948e).

One residual, pre-existing dual-variant wart (not introduced here, not fixed here): upgrading a Windows config that the fallback lane wrote (dual variants) via a later RPC grant can leave one inert forward-slash self-computed table behind; it dedupes away on normalized read and getStatus validates trust through the ledger, so it's harmless. Noted as a follow-up.

Re-validation request

Please re-run at the current branch HEAD (1f9ab948e), focused on the two things macOS can't cover:

  1. The live WSL Electron pane — confirm the codex pane reaches its session with no "Hooks need review", and the runtime config.toml retains the six [hooks.state."…"] tables after launch.
  2. npx vitest run --config config/vitest.config.ts src/main/codex/ on Windows — confirm the two previously-failing tests now pass (and none regressed).

@OrcaWin

OrcaWin commented Jul 16, 2026

Copy link
Copy Markdown
Collaborator

Windows/WSL revalidation after restarting Orca, at 1f9ab948e8d7795bca0da83f438faaea4785b79b:

Scenario Result Evidence
Rebuild PASS pnpm install --frozen-lockfile, pnpm run build:electron-vite, and pnpm run build:relay completed successfully.
Live WSL Electron pane (Ubuntu, Codex 0.144.1) PASS Codex reached the session UI; no Hooks need review / N hooks are new or changed screen appeared. The disposable WSL runtime config.toml had exactly six child [hooks.state."…hooks.json:<event>:0:0"] tables and all six had sha256: trusted_hash values. Dev log: [codex-trust-grant] granted 6 managed hook entries via codex app-server (host=wsl, wrote=true, 2108ms) (also a later successful host=wsl, wrote=true refresh). No stale-WSL-trust revoke failure was logged.
Windows Codex Vitest suite PASS npx vitest run --config config/vitest.config.ts src/main/codex/: 18/18 files passed; 305 tests passed, 11 skipped. Both previously failing config-byte-stability / stale-trust-upgrade tests now pass.
Post-run process/home cleanup PASS WSL default user restored to root; disposable WSL user removed; no codex app-server process remained. All CODEX_HOME / Orca profile state used by the run was disposable.

The WSL finding-1 regression and Windows Vitest finding-2 regression are both resolved in this recheck.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Live E2E validation — PASS (6/6)

Validated live against the real Electron app at head f64fb1396 (codex-cli 0.144.4), using four sandboxed app instances (HOME + ORCA_DEV_USER_DATA_PATH overridden, leaked env scrubbed). No codex was ever typed into an app pane; all Codex executions were app-internal grant sessions against sandbox homes or direct drives of the built grant entry with explicit CODEX_HOME. The real ~/.codex was never touched (checksum-guarded before/after — unchanged).

1. Real grant, not forged — PASS. Launch prep logged granted 6 managed hook entries via codex app-server (host=native, wrote=true, 252ms); sandbox config.toml gained 6 [hooks.state."…"] tables carrying Codex's own writer fingerprint (bare [hooks.state] parent, blank-line separators, implicit enabled) — a shape the legacy self-hash lane never produces (control runs confirm). A deliberately corrupted hash was repaired by Codex to its own value. Caveat: on 0.144.4 our replica hash still equals Codex's, so hash value alone can't discriminate — the lane/log/fingerprint evidence is what proves authorship.

2. Config preservation — PASS. Seeded comments, model/approval_policy lines, a [projects] comment, and blank-line separators all survived the grant. A hand-added enabled = false + comment inside a granted table survived a forced hash repair (in-place trusted_hash update; exactly 6 child tables, zero duplicates).

3. Malformed config — PASS at the grant boundary. Driving the exact spawned artifact against a malformed-TOML sandbox home returned verify-failed with the file byte-identical (same sha256). (In the full in-app flow the config mirror heals a malformed runtime config before the grant — strictly better; noted for completeness.)

4. Old-codex fallback — PASS. A shim erroring unrecognized subcommand 'app-server' → reason=unsupported, then unsupported-cached next launch (no re-probe). A silent-exit shim → reason=error (transient) then retry-cached — never marked unsupported. Fallback config is byte-identical to the ORCA_DISABLE_CODEX_TRUST_RPC=1 control (modulo sandbox root), every hash equal to computeTrustedHash of its own root.

5. No revoke of just-granted hooks — PASS. Three subsequent launch preps + a forced full re-grant left config.toml byte-identical each time; no stripping fingerprint appeared. (The WSL false-'missing' revoke guard was live-validated on Windows 11 + WSL in a prior round; not testable on macOS.)

6. Steady state — PASS. Repeat preps with a settled ledger are fully silent; config + ledger byte/mtime-unchanged; zero codex app-server processes in sampling; no orphaned processes after teardown. Grant round trip ~114–238 ms.

Automated live validation run as part of the pre-RC hardening sweep.

@AmethystLiang AmethystLiang self-assigned this Jul 18, 2026
@AmethystLiang
AmethystLiang self-requested a review July 18, 2026 16:47
brennanb2025 added a commit that referenced this pull request Jul 20, 2026
…9501)

* feat(codex): backfill managed-home sessions into the real Codex home once per host

Orca-launched Codex sessions currently land only in the Orca-managed
runtime home, so the user's own `codex resume` picker and app history
never see them (#4444, #8612). Backfill the managed sessions tree into
the real ~/.codex/sessions/YYYY/MM/DD layout once per host:

- hardlink first (one physical rollout log), copy as the cross-volume
  fallback; existing target files are always skipped, nothing in either
  home is deleted or moved
- idempotent; per-file failures leave the completion marker unset so the
  next startup retries cheaply
- JSONL audit log of every link/copy/failure under
  <userData>/codex-session-backfill/
- honors the custom Codex session source home override, mirroring the
  existing system->managed bridge

WSL managed homes are distro-local and need an in-distro variant; that
is a follow-up.

* feat(codex): flag-gated system-default real-home routing scaffolding

Staged internal flag (default OFF, no settings UI): route the SYSTEM-DEFAULT
Codex account at the user's real ~/.codex instead of Orca's managed runtime
home. Flag OFF is byte-identical to today; managed (multi-account) selections
are unchanged in either state.

Routing (flag ON + host system default = no managed account):
- CodexRuntimeHomeService.prepareForCodexLaunch / prepareForRateLimitFetch
  return null so the PTY/env layer injects no managed CODEX_HOME and the
  rate-limit fetcher + auth-presence gate fall back to ~/.codex (the background
  poller stops spawning Codex against the managed home — the #5370 auth war).
- buildPtyHostEnv strips only a nested-Orca-inherited Orca-owned override
  (CODEX_HOME matching the private ORCA_CODEX_HOME marker), preserving a
  user-set CODEX_HOME. Shell-ready re-exports already no-op without the marker.
- The headless commit-message Codex path strips the same inherited override.

Hook install for the real-home lane (append-last into ~/.codex/hooks.json,
trust via the app-server client) lands with the trust plumbing; the managed
hook install is skipped for this lane meanwhile.

Credit @jellychoco (#8606) for the native-home routing direction.

Depends on the codex trust-rpc-grant plumbing for the real-home hook installer.

* fix(codex): strip the daemon-inherited Orca CODEX_HOME override for real-home routing

The daemon spawns PTYs from its own inherited environment and honors only
spawnOptions.envToDelete, so mutating the sparse env object was not enough to
strip an Orca-owned CODEX_HOME the daemon already carries. Add the strip to
envToDelete for both daemon host-spawn paths, preserving a user-set CODEX_HOME.

Verified live via CDP against a sandboxed dev instance (flag ON): an
Orca-spawned pane reports empty CODEX_HOME/ORCA_CODEX_HOME, so Codex resolves
its own ~/.codex. Adds daemon-path unit coverage (strip Orca-owned, preserve
user-owned, no-op when flag OFF).

* fix(codex): harden one-time session backfill

* test(codex): cover staged cross-volume install

* feat(codex): app-server trust-grant client, capability cache, and grant ledger

Short-lived codex app-server JSON-RPC client (hooks/list + config/batchWrite,
the same pair the Codex TUI 'Trust all' flow calls), run in a bundled
ELECTRON_RUN_AS_NODE entry so synchronous launch prep can block on it with a
hard deadline and guaranteed child reap. Capability cache modeled on
GitCapabilityCache, scoped per execution host (native vs each WSL distro),
with a narrow unknown-method/missing-subcommand unsupported predicate. The
grant ledger records verified grants so steady-state launches skip the RPC.

* fix(codex): grant managed hook trust via codex app-server RPCs in install/refresh

Host and WSL installs now grant trust for Orca's managed status hooks through
codex's own hooks/list -> config/batchWrite -> re-list verify, scoped to
exactly the managed entries; the previous computeTrustedHash lane is the
unchanged fallback for incapable/erroring CLIs. getStatus and the removal
paths recognize ledger-recorded codex hashes so drift between codex's real
algorithm and the replica no longer misreports or strands trust. SSH remote
install is untouched by design.

* test(codex): cover app-server trust grant client, cache, ledger, and lanes

* test(codex): cover commit-message real-home override strip/preserve

Adds the two cases for the headless commit-message Codex env under real-home
routing: a nested-Orca-inherited Orca-owned CODEX_HOME is stripped, and a
user-owned CODEX_HOME is preserved.

* test(codex): WSL grant-lane coverage — in-distro invocation and fallback parity

* feat(codex): real-home hook installer trusted via the codex app-server grant client

With the real-home flag ON and the system-default selection, install Orca's
status hook into the user's real ~/.codex before any pane spawns:

- entry APPENDED LAST per managed event: codex hook trust keys are positional
  (source:event:group:handler), so appending keeps every user entry's position
  and trust record intact; user entries and unknown top-level hooks.json fields
  are preserved verbatim
- trust is granted exclusively through the codex app-server client
  (hooks/list + config/batchWrite, verified by re-list); Orca never writes
  [hooks.state] into the user's real config.toml itself
- if the grant lane is unavailable (old binary, unsupported RPC, verify
  failure), the appended entry is rolled back byte-exactly and the host keeps
  the managed-home lane end to end (PTY env, rate limits, commit messages)
  via a lane gate on the runtime-home service
- one-time pristine backup of the user's hooks.json under Orca's userData;
  a rolling .bak sits next to the file (existing atomic writer)
- hook opt-out sweeps Orca entries from the real home and drops Orca-owned
  trust records; flag-off downgrade re-arms the existing legacy system-home
  sweep, which removes the entry and its trust keys cleanly
- the legacy system-home sweep is suppressed only while the real-home lane
  owns ~/.codex/hooks.json, so managed installs cannot delete the entry

* fix(codex): resolve the trust-grant entry without requiring electron

The grant bridge is reachable from plain-Node CLI entries, where the
plain-node entry guard rejects any chunk containing require("electron").
Resolve the bundled session entry from __dirname (root chunk and chunks/
layouts) with an app.asar -> app.asar.unpacked rewrite for packaged runs,
instead of electron's app path APIs.

* fix(codex): keep session backfill off main thread

Use asynchronous, sequential filesystem operations for the one-time rollout backfill, and avoid repeated target-directory probes. Treat inaccessible managed session roots as retryable failures instead of writing a false completion marker.

* fix(codex): harden app-server trust grant fallback

* fix(codex): install cross-volume session backfill copies atomically

On a real Codex home whose filesystem supports no hardlinks (exFAT/FAT,
some network mounts), the staged cross-volume copy was installed with a
non-atomic copyFile(..., COPYFILE_EXCL) straight into the final
rollout-*.jsonl name. An install interrupted mid-copy (app quit, crash,
ENOSPC during the deferred run) could strand a truncated rollout that the
next run then skips as already-present, defeating the staging design's own
guarantee that a failed copy never leaves a partial session behind.

Install the fully-staged copy with an atomic rename instead, guarded by an
existence re-check so it keeps the never-overwrite contract (and the rename
source is the same immutable managed rollout, so any clobber would be
byte-identical). Cover the no-hardlink-support target and an interrupted
install that must leave no partial in the user's sessions tree.

* fix(codex): resolve grant entry from __dirname so plain-node CLI entries stay electron-free

The build guard rejects any electron require reachable from plain-node
entries; the bridge now maps app.asar to app.asar.unpacked by string
replacement instead of consulting electron app paths. CLI typecheck project
lists the new trust-grant module graph.

* fix(codex): harden trust grant reconciliation

* fix(codex): restore trust config permissions on rollback

* fix(codex): harden real-home routing cleanup and retries

* fix(codex): preserve unicode trust RPC responses

* fix(codex): preserve remote env and complete real-home cleanup

* fix(codex): preserve real-home lane invariants

* test(terminal): isolate replacement idle reset assertion

* fix(codex): preserve real-home dotfile links

* fix(codex): preserve verified trust grants across launch prep

* fix(codex): preserve dangling config symlinks on rollback

* fix(codex): don't revoke a just-granted WSL home on a false 'missing' probe

The async wsl.exe canonical-path settlement could report the runtime home
'missing' immediately after a verified RPC grant (a false negative — codex
had just written and re-listed trust there), which drove the reconciliation
'remove' branch to delete all six granted [hooks.state] tables, leaving a bare
[hooks.state] the launching pane read as 'hooks need review'. A 'missing'
settlement now revokes only when no successful install ran this generation; a
genuinely moved home still resolves to a different path and reinstalls.

* test(codex): model codex config/batchWrite faithfully on Windows

The grant-lane stub simulated codex by calling Orca's upsertHookTrustEntries,
which writes both separator variants for a Windows key (a fallback-lane compat
shim real codex never does) — fabricating duplicate tables and whitespace the
RPC path never produces, so the byte-stable and no-duplicate assertions failed
on win32. Replace it with a single-variant, blank-line-separated writer that
matches the real 0.144.x binary's output.

* feat(codex): collapse duplicate session listings across Codex roots

Backfilled/bridged rollouts are hardlinked into both the real ~/.codex and
Orca's managed runtime home, so AI Vault listed each session once per root
(#7521). Dedup candidates by rollout file name pre-parse and parsed sessions
by session id post-parse, keeping the canonical root: host real home first
(unprefixed resume), then the managed runtime home, then other homes. Applies
to local, WSL, and SSH-remote scans.

* feat(codex): background sqlite index heal for backfilled sessions

Codex's own state-DB metadata backfill is one-shot, so rollouts hardlinked in
by Orca's session backfill never become visible to Codex's DB-driven surfaces.
Extract the app-server stdio JSONL transport into codex-app-server-session
(shared with the trust-grant client) and add a bounded, resumable background
pass that drives Codex's lazy indexing via thread/read per backfilled session:
recent-first, batched onto one short-lived server per batch with small
concurrency, ledger + marker so steady-state startups are a no-op, stop-aware
on quit, and capability-aware on CLIs without the app-server surface.

* fix(codex): preserve session identity during dedup heal

* fix(codex): preserve user trust during real-home cleanup

* fix(codex): harden real-home heal boundaries

* fix(codex): fail closed on unsafe backfill install

* fix: harden real-home hook cleanup

* fix(ai-vault): preserve execution boundaries and reap children

* fix(codex): narrow app-server unsupported detection

* fix(codex): bound user hook trust rebase retries per host

The rebase lane ran a codex app-server session on every launch prep while a
host was stuck (CLI without app-server support, or keys hooks/list cannot
match). Gate the transaction on the shared capability cache and add the same
5-minute transient cooldown the grant lane uses, so sweep and legacy-cleanup
retries cost plain fs reads instead of a codex session per pane spawn.

* fix(codex): enforce real-home resume and heal boundaries

* fix(codex): establish real-home lane before cleanup

* fix(codex): stop index heal before delayed spawn

* fix(codex): protect symlinked rolling backups

* fix(ai-vault): preserve resume env deletion through drag

* fix(codex): strip inherited Codex homes on mobile real-home resume

The mobile resume surface types a bare real-home codex resume into a
freshly created pane, but never asked for CODEX_HOME/ORCA_CODEX_HOME
deletion at pane spawn, so an agentDefaultEnv-pinned or daemon-inherited
Codex home rerouted the resume away from the user's real ~/.codex while
the same session resumed correctly on desktop. Share the deletion helper
from the AI Vault resume builders and forward it through the mobile
launch and session.tabs.createTerminal call.

* fix(codex): gate session migration on real-home lane

* fix(codex): stop session backfill after opt-out

* fix(codex): keep session heal failures retryable

* fix(codex): keep session migration state recoverable

* fix(codex): retry republished missing session heals

* fix(codex): preserve hook symlink trust path

* fix(codex): disambiguate POSIX trust paths

* fix(codex): align hook trust source paths

* fix(codex): harden trust grant lifecycle

* fix(codex): restore envToDelete on client invocation type after base reconcile

* test(codex): type child.stdout as PassThrough for oversized-output write

* Assemble RC: reconcile app-server transport API across PRs

Unify on the object RPC surface from the index-heal transport (#8921) while
preserving the default-home env strip (#8828) and the narrowed missing-app-server
capability signal (#8847): adapt the user-hook-trust-rebase consumer + tests,
port envToDelete stripping into the shared session, and route stderr
classification through the canonical capability-signal module.

* RC: enable system-default real-home routing by default (flag ON)

Flip codexSystemDefaultRealHomeEnabled to default ON for this RC's staged
rollout (a user can still opt out by setting it false, which stays byte-identical
to managed-home behavior). This is the only intended behavior difference between
the RC branch and the individual PRs. Updates the two tests that assumed the
prior OFF default.

* fix(codex): snapshot hooks.json bytes+parse in one read to close real-home clobber race

The install/sweep/legacy-cleanup paths parsed hooks.json, then did a separate
later read to capture the previous bytes for the pre-write generation guard.
A concurrent save (second Orca instance or the user editing the file) could
land between the parse and that second read and be silently overwritten.
readHooksJsonWithRaw returns the raw bytes and parse from a single read so the
guard compares against exactly what it parsed. Adds a regression test that
mutates hooks.json mid-RPC and asserts the sweep aborts without clobbering.

* fix(codex): sanitize managed account config trust

* fix(codex): guard OAuth add for custom providers

* fix(codex): persist outgoing managed tokens before real-home lane takeover (PR-C)

prepareForCodexLaunch returns null early for the real-home / system-default
lane before syncForCurrentSelection runs. If a managed account is still
recorded as synced when the selection has dropped to the system default
(nulled without a sync pass, or auto-deselect on missing managed auth), a
Codex-refreshed token stranded in the shared runtime home is never persisted
to its canonical per-account home -> token loss.

Read the outgoing managed account's refreshed token back before the real home
takes over. The real-home lane implies host === null, so running the
managed->system-default transition restores only Orca's runtime mirror from
~/.codex and never writes the real ~/.codex. It is a no-op once the selection
has already been reconciled, so the normal select path does not double-write.

* fix(codex): preserve refreshes across all default transitions

* feat(codex): show system-default/real-home account identity in switcher (PR-B)

The account switcher modeled the system-default Codex account as
activeAccountId:null with no identity fields, so the null row rendered
blank ("System default" / generic subtitle) even though its effective
login is whatever ~/.codex/auth.json currently is.

Add a CodexSystemDefaultIdentity descriptor {hasAuth, authKind, email,
providerAccountId, workspaceLabel} to CodexRateLimitAccountsState,
resolved live and READ-ONLY from ~/.codex by the accounts service and
returned from listAccounts()/getSnapshot(). The settings switcher now
renders the null (system-default) row as that real identity: the OAuth
email when signed in, "Custom provider — no usage tracked." for
env-key/custom-provider logins (auth.json with OPENAI_API_KEY, or an
OPENAI_API_KEY env with no auth.json), and the generic fallback when
signed out. Identity is host-scoped (per-distro WSL keeps the generic
label). Orca never writes ~/.codex; managed-account switches only touch
Orca-owned homes, so the system-default identity stays a stable,
displayed source of truth. Usage already routes to the real home via
getSystemCodexHomePath, so the switcher now attributes it to a real face.

Tests (sandboxed temp homes only): OAuth email/provider resolution,
api-key auth.json and env-key (no auth.json) as custom-provider,
signed-out, and select/deselect of a managed account never mutating
~/.codex/auth.json.

* fix(codex): parse multiline provider pins in OAuth guard

* fix(codex): harden managed trust sanitization

* fix(codex): harden system-default identity rendering

* feat(codex): give each managed account a self-contained CODEX_HOME; retire shared mirror (PR-E)

With the real-home flag ON, a host managed account now launches directly
against its own codex-accounts/<id>/home instead of the shared runtime
mirror + auth.json hot-swap:

- codex-home-paths: syncSystemCodexResourcesIntoManagedHome links system
  resources into any managed home (ownership-marker discipline; never
  symlinks into / mutates ~/.codex).
- runtime-home-service: prepareForCodexLaunch / prepareForRateLimitFetch /
  syncForCurrentSelection route the per-account home directly and skip the
  shared-home hot-swap + token read-back; each home keeps its own auth in
  place (fixes GAP-5 concurrent auth race). Session discovery scans every
  per-account home.
- hook-service / hook-trust-promotion: install/getStatus/refresh accept a
  runtimeHomePath so hooks + RPC-granted trust land in the per-account home.
- service: config mirror into a self-contained home uses the trust-
  preserving merge so granted hook/project trust survives account switches.
- codex-session-root-dedup: rank codex-accounts/<id>/home as canonical
  managed alongside the shared runtime home.

Flag-OFF and the system-default real-home (null) lane are unchanged; the
nested-Orca CODEX_HOME===ORCA_CODEX_HOME daemon strip (#5370) is preserved.
Sandboxed tests only; ~/.codex is never mutated.

* fix(codex): validate per-account home ownership

* fix(codex): keep managed rollouts discoverable across real-home opt-out

WI-4 lossless migration/rollback validation for pre-E shared-mirror managed
accounts. Session discovery gated the per-account home scan on the real-home
flag, so opting back out (flag OFF) hid every rollout an account accumulated
while the flag was ON — the data stayed on disk but vanished from the AI Vault
until the flag flipped back on.

Scan a managed host home whenever it holds a sessions/ tree, independent of the
flag; a never-enabled install keeps its homes credential-only so opt-out stays
byte-identical to today. Forward migration was already lossless (the shared
mirror is always scanned) and the opt-out credential read-back already refuses
to overwrite a fresher per-account token; add tests locking all three
invariants. Sandboxed tests only; ~/.codex is never touched.

* fix(codex): migrate stranded shared auth on E takeover

* test(e2e): isolate Electron from developer Codex home

* test(codex): add real-account validation harness

* fix(codex): finish C and E matcher composition

* fix(codex): bound validation harness shutdown

* test(codex): isolate hook lifecycle user data

* test(codex): cover realistic account-home migration

* fix(codex): keep standalone home tripwire active

* test(codex): fingerprint system auth in validation reports

* fix(codex): bind managed homes to account ownership

* fix(codex): normalize Windows trust source identity

* fix(codex): make Windows trust upgrade transactional

* test(codex): use TypeScript pipeline for validation scripts

* test(codex): run validation modules through native node

* test(codex): allow slow Windows tripwire startup

* fix(codex): survive lingering Windows codex login processes in add-account

On Windows, codex login can keep running (with descendants) after it has
written auth.json, holding OS handles on the per-account managed home
(log/codex-login.log). That made doAddAccount's post-login cleanup fail
with ENOTEMPTY (rmSync) and left an orphaned codex-accounts/<id>/home.

- runCodexLogin now watches for auth.json on Windows and force-kills the
  login process tree (taskkill /t) if it lingers past a short grace
  period; the forced exit is treated as a successful login. The 120s
  timeout path also kills the whole tree instead of only the direct
  child. macOS/Linux behavior is unchanged.
- safeRemoveManagedHome now removes homes with rmSync maxRetries /
  retryDelay (mirroring the local-worktree-filesystem Windows policy)
  and no longer lets a cleanup failure mask the original add error.
- run-codex-real-account-validation.mjs accepts --temp-parent /
  ORCA_CODEX_VALIDATION_TEMP_PARENT so the disposable root can live
  outside %USERPROFILE% on Windows, and fails with an actionable message
  before creating anything when the temp parent is inside the primary
  home. The real-home guard is unchanged.

* fix(codex): preserve managed-account MCP .credentials.json on per-account-home migration (#8440)

Codex file-mode MCP OAuth tokens live in $CODEX_HOME/.credentials.json,
keyed by MCP server URL with no account identity of their own. The legacy
shared-mirror -> per-account-home migration only carried auth.json, so an
existing managed account with authed MCP servers had its tokens stranded on
upgrade and silently needed re-auth.

Carry the shared mirror's .credentials.json into the same identity-proven
per-account home alongside auth.json: only into the single uniquely-matched
active account (no cross-account leak), only when the destination has none yet
(never clobber a newer file the account authed in its own home), atomic 0600,
absent-source no-op. New MCP auth already lands in the per-account home since
that home is CODEX_HOME.

* fix(codex): preserve Windows reauthentication login flow

* test(codex): build real-account validation harness cross-platform on Windows

The harness built its app with execFileSync('npx', ['electron-vite', ...]),
but npx resolves to a .cmd shim on Windows that execFileSync cannot launch
(ENOENT), so the harness could not build its own app there and required
--skip-build with a prebuilt out/main/index.js.

Extract resolveElectronViteBuildCommand(repoRoot): it runs the repository-local
electron-vite JS entry (node_modules/electron-vite/bin/electron-vite.js) with
the current Node binary (process.execPath), which resolves identically on
macOS, Linux, and Windows with no shell. It throws a clear error if the local
entry is missing (install deps or pass --skip-build). --skip-build behavior is
unchanged.

Add regression coverage asserting the build command uses process.execPath and
the repo-local JS entry (not npx), and that a missing entry fails clearly.

* fix(codex): version the MCP creds migration independently of the auth marker

The auth carry and the MCP .credentials.json carry (#8440) shared one
existence-only v1 marker, so any build that stamped the auth-only marker
first would strand the MCP store forever. The MCP carry now concludes via
its own per-account-mcp-creds-migration-v1.json marker and runs even when
the auth marker is already present; ordering is code-enforced instead of
landing-discipline-enforced.

Also isolate per-account read failures: one stale or deleted account home
no longer aborts the whole migration. The broken account stays in the
unique-identity ambiguity gate via its stored fields but is never read or
written, so the active account still migrates.

* fix(codex): fail corrupt managed auth.json without echoing credential bytes

A raw JSON.parse SyntaxError from loadOAuthCredentials could carry auth
file fragments into logs and the add/reauth error surface. Throw a
sanitized error instead; filesystem errors still propagate unchanged.

* fix(mobile): give the pairing runtime a disposable home for the E2E boot guard

The main-process guard now refuses to start with ORCA_E2E_USER_DATA_DIR
set but the real user home, and this was the one caller not updated —
the temporary pairing runtime crashed before emitting its pairing URL.

* test(codex): canonicalize harness containment guards and retry cleanup

Resolve symlinks before the disposable-root containment checks so a
symlinked temp parent cannot smuggle the throwaway home inside the
primary home, and give the final cleanup rm Windows retry/force so a
briefly lingering codex handle cannot strand the credential-bearing
root.

* test(codex): add lane-aware containment mode to the real-account harness

The Windows gate-D run proved strict zero-event whole-profile containment
is structurally unreachable with the real-home flag ON: system-default
spawn sites deliberately delete CODEX_HOME so native codex resolves the
real ~/.codex, and on Windows the binary ignores the USERPROFILE sandbox.
Its own volatile runtime churn (root sqlite/WAL/SHM, tmp/, log/) is the
shipped Phase-1 design, not a candidate defect.

--lane-aware-containment records those designed events without aborting
while every other real-home write — auth.json, config.toml,
.credentials.json, hooks.json, sessions/, anything unknown — remains a
hard violation and still aborts the run. Default behavior is unchanged
(strict); the absolute zero-event claim stays carried by macOS runs,
where HOME does sandbox native codex.

* test(codex): allow the real-account harness to pin the real-home flag off

--system-default-real-home off seeds and env-pins the flag OFF so every
codex spawn gets an explicit managed CODEX_HOME and native codex never
resolves the OS profile. This is the only Windows configuration where the
strict zero-event whole-profile tripwire is reachable, and it matches the
stable-rollout default; flag-ON runs keep lane-aware classification.

* test(codex): correct the flag-off harness comment to kill-switch rationale

The rollout ships all codex-home changes at once (no phased rollout), so
flag OFF is the emergency kill-switch lane, not the stable default.

* test(e2e): canonicalize the isolated E2E home path

The disposable HOME lives under os.tmpdir(), whose spelling is an alias
on CI (macOS /var symlink, Windows 8.3 RUNNER~1). Git canonicalizes
worktree paths, so worktrees created under the aliased home never
matched the app's listing — golden core flows and the packaged
crash-survival harness failed with 'worktree created but not found in
listing'. Resolve the home to its canonical spelling at creation in
both the e2e helper and the packaged-app driver.

* fix(codex): address CodeRabbit review on the landing PR

- carry envToDelete through the mobile agent-resume startup plan so a
  real-home Codex resume cannot inherit an ambient CODEX_HOME
- strip Orca-owned Codex overrides in the commit-message WSL fallback,
  matching the host fallback
- strip ELECTRON_RUN_AS_NODE in the computer-e2e driver like every other
  home-isolation caller
- drop the unused hooksEnabled parameter from isRealHomeCodexHookLaneUsable

* feat(codex): ship real-home routing unconditionally, remove the rollout flag

The codexSystemDefaultRealHomeEnabled setting is gone from types and
constants and the helper no longer consults settings — the system-default
real-home lane and per-account homes ship for everyone in one release.
This also un-strands profiles that rc-era builds stamped with false (the
setting had no UI, so every stored false was a seeded artifact that would
have silently kept those users on the legacy mirror forever).

The ORCA_CODEX_SYSTEM_DEFAULT_REAL_HOME env override survives strictly as
a test-rig control: the containment harness pins the legacy lane for
strict zero-event Windows runs, e2e home isolation pins lanes inside
disposable homes, and the legacy-lane test suites now route their
per-test lane selection through it.

---------

Co-authored-by: OrcaWin <[email protected]>
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing as superseded: this work landed on main via #9501 (real-home routing + self-contained multi-account homes) and shipped in v1.4.149 stable. Content verified present on main (module + wiring spot-checked).

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#9501)

* feat(codex): backfill managed-home sessions into the real Codex home once per host

Orca-launched Codex sessions currently land only in the Orca-managed
runtime home, so the user's own `codex resume` picker and app history
never see them (stablyai#4444, stablyai#8612). Backfill the managed sessions tree into
the real ~/.codex/sessions/YYYY/MM/DD layout once per host:

- hardlink first (one physical rollout log), copy as the cross-volume
  fallback; existing target files are always skipped, nothing in either
  home is deleted or moved
- idempotent; per-file failures leave the completion marker unset so the
  next startup retries cheaply
- JSONL audit log of every link/copy/failure under
  <userData>/codex-session-backfill/
- honors the custom Codex session source home override, mirroring the
  existing system->managed bridge

WSL managed homes are distro-local and need an in-distro variant; that
is a follow-up.

* feat(codex): flag-gated system-default real-home routing scaffolding

Staged internal flag (default OFF, no settings UI): route the SYSTEM-DEFAULT
Codex account at the user's real ~/.codex instead of Orca's managed runtime
home. Flag OFF is byte-identical to today; managed (multi-account) selections
are unchanged in either state.

Routing (flag ON + host system default = no managed account):
- CodexRuntimeHomeService.prepareForCodexLaunch / prepareForRateLimitFetch
  return null so the PTY/env layer injects no managed CODEX_HOME and the
  rate-limit fetcher + auth-presence gate fall back to ~/.codex (the background
  poller stops spawning Codex against the managed home — the stablyai#5370 auth war).
- buildPtyHostEnv strips only a nested-Orca-inherited Orca-owned override
  (CODEX_HOME matching the private ORCA_CODEX_HOME marker), preserving a
  user-set CODEX_HOME. Shell-ready re-exports already no-op without the marker.
- The headless commit-message Codex path strips the same inherited override.

Hook install for the real-home lane (append-last into ~/.codex/hooks.json,
trust via the app-server client) lands with the trust plumbing; the managed
hook install is skipped for this lane meanwhile.

Credit @jellychoco (stablyai#8606) for the native-home routing direction.

Depends on the codex trust-rpc-grant plumbing for the real-home hook installer.

* fix(codex): strip the daemon-inherited Orca CODEX_HOME override for real-home routing

The daemon spawns PTYs from its own inherited environment and honors only
spawnOptions.envToDelete, so mutating the sparse env object was not enough to
strip an Orca-owned CODEX_HOME the daemon already carries. Add the strip to
envToDelete for both daemon host-spawn paths, preserving a user-set CODEX_HOME.

Verified live via CDP against a sandboxed dev instance (flag ON): an
Orca-spawned pane reports empty CODEX_HOME/ORCA_CODEX_HOME, so Codex resolves
its own ~/.codex. Adds daemon-path unit coverage (strip Orca-owned, preserve
user-owned, no-op when flag OFF).

* fix(codex): harden one-time session backfill

* test(codex): cover staged cross-volume install

* feat(codex): app-server trust-grant client, capability cache, and grant ledger

Short-lived codex app-server JSON-RPC client (hooks/list + config/batchWrite,
the same pair the Codex TUI 'Trust all' flow calls), run in a bundled
ELECTRON_RUN_AS_NODE entry so synchronous launch prep can block on it with a
hard deadline and guaranteed child reap. Capability cache modeled on
GitCapabilityCache, scoped per execution host (native vs each WSL distro),
with a narrow unknown-method/missing-subcommand unsupported predicate. The
grant ledger records verified grants so steady-state launches skip the RPC.

* fix(codex): grant managed hook trust via codex app-server RPCs in install/refresh

Host and WSL installs now grant trust for Orca's managed status hooks through
codex's own hooks/list -> config/batchWrite -> re-list verify, scoped to
exactly the managed entries; the previous computeTrustedHash lane is the
unchanged fallback for incapable/erroring CLIs. getStatus and the removal
paths recognize ledger-recorded codex hashes so drift between codex's real
algorithm and the replica no longer misreports or strands trust. SSH remote
install is untouched by design.

* test(codex): cover app-server trust grant client, cache, ledger, and lanes

* test(codex): cover commit-message real-home override strip/preserve

Adds the two cases for the headless commit-message Codex env under real-home
routing: a nested-Orca-inherited Orca-owned CODEX_HOME is stripped, and a
user-owned CODEX_HOME is preserved.

* test(codex): WSL grant-lane coverage — in-distro invocation and fallback parity

* feat(codex): real-home hook installer trusted via the codex app-server grant client

With the real-home flag ON and the system-default selection, install Orca's
status hook into the user's real ~/.codex before any pane spawns:

- entry APPENDED LAST per managed event: codex hook trust keys are positional
  (source:event:group:handler), so appending keeps every user entry's position
  and trust record intact; user entries and unknown top-level hooks.json fields
  are preserved verbatim
- trust is granted exclusively through the codex app-server client
  (hooks/list + config/batchWrite, verified by re-list); Orca never writes
  [hooks.state] into the user's real config.toml itself
- if the grant lane is unavailable (old binary, unsupported RPC, verify
  failure), the appended entry is rolled back byte-exactly and the host keeps
  the managed-home lane end to end (PTY env, rate limits, commit messages)
  via a lane gate on the runtime-home service
- one-time pristine backup of the user's hooks.json under Orca's userData;
  a rolling .bak sits next to the file (existing atomic writer)
- hook opt-out sweeps Orca entries from the real home and drops Orca-owned
  trust records; flag-off downgrade re-arms the existing legacy system-home
  sweep, which removes the entry and its trust keys cleanly
- the legacy system-home sweep is suppressed only while the real-home lane
  owns ~/.codex/hooks.json, so managed installs cannot delete the entry

* fix(codex): resolve the trust-grant entry without requiring electron

The grant bridge is reachable from plain-Node CLI entries, where the
plain-node entry guard rejects any chunk containing require("electron").
Resolve the bundled session entry from __dirname (root chunk and chunks/
layouts) with an app.asar -> app.asar.unpacked rewrite for packaged runs,
instead of electron's app path APIs.

* fix(codex): keep session backfill off main thread

Use asynchronous, sequential filesystem operations for the one-time rollout backfill, and avoid repeated target-directory probes. Treat inaccessible managed session roots as retryable failures instead of writing a false completion marker.

* fix(codex): harden app-server trust grant fallback

* fix(codex): install cross-volume session backfill copies atomically

On a real Codex home whose filesystem supports no hardlinks (exFAT/FAT,
some network mounts), the staged cross-volume copy was installed with a
non-atomic copyFile(..., COPYFILE_EXCL) straight into the final
rollout-*.jsonl name. An install interrupted mid-copy (app quit, crash,
ENOSPC during the deferred run) could strand a truncated rollout that the
next run then skips as already-present, defeating the staging design's own
guarantee that a failed copy never leaves a partial session behind.

Install the fully-staged copy with an atomic rename instead, guarded by an
existence re-check so it keeps the never-overwrite contract (and the rename
source is the same immutable managed rollout, so any clobber would be
byte-identical). Cover the no-hardlink-support target and an interrupted
install that must leave no partial in the user's sessions tree.

* fix(codex): resolve grant entry from __dirname so plain-node CLI entries stay electron-free

The build guard rejects any electron require reachable from plain-node
entries; the bridge now maps app.asar to app.asar.unpacked by string
replacement instead of consulting electron app paths. CLI typecheck project
lists the new trust-grant module graph.

* fix(codex): harden trust grant reconciliation

* fix(codex): restore trust config permissions on rollback

* fix(codex): harden real-home routing cleanup and retries

* fix(codex): preserve unicode trust RPC responses

* fix(codex): preserve remote env and complete real-home cleanup

* fix(codex): preserve real-home lane invariants

* test(terminal): isolate replacement idle reset assertion

* fix(codex): preserve real-home dotfile links

* fix(codex): preserve verified trust grants across launch prep

* fix(codex): preserve dangling config symlinks on rollback

* fix(codex): don't revoke a just-granted WSL home on a false 'missing' probe

The async wsl.exe canonical-path settlement could report the runtime home
'missing' immediately after a verified RPC grant (a false negative — codex
had just written and re-listed trust there), which drove the reconciliation
'remove' branch to delete all six granted [hooks.state] tables, leaving a bare
[hooks.state] the launching pane read as 'hooks need review'. A 'missing'
settlement now revokes only when no successful install ran this generation; a
genuinely moved home still resolves to a different path and reinstalls.

* test(codex): model codex config/batchWrite faithfully on Windows

The grant-lane stub simulated codex by calling Orca's upsertHookTrustEntries,
which writes both separator variants for a Windows key (a fallback-lane compat
shim real codex never does) — fabricating duplicate tables and whitespace the
RPC path never produces, so the byte-stable and no-duplicate assertions failed
on win32. Replace it with a single-variant, blank-line-separated writer that
matches the real 0.144.x binary's output.

* feat(codex): collapse duplicate session listings across Codex roots

Backfilled/bridged rollouts are hardlinked into both the real ~/.codex and
Orca's managed runtime home, so AI Vault listed each session once per root
(stablyai#7521). Dedup candidates by rollout file name pre-parse and parsed sessions
by session id post-parse, keeping the canonical root: host real home first
(unprefixed resume), then the managed runtime home, then other homes. Applies
to local, WSL, and SSH-remote scans.

* feat(codex): background sqlite index heal for backfilled sessions

Codex's own state-DB metadata backfill is one-shot, so rollouts hardlinked in
by Orca's session backfill never become visible to Codex's DB-driven surfaces.
Extract the app-server stdio JSONL transport into codex-app-server-session
(shared with the trust-grant client) and add a bounded, resumable background
pass that drives Codex's lazy indexing via thread/read per backfilled session:
recent-first, batched onto one short-lived server per batch with small
concurrency, ledger + marker so steady-state startups are a no-op, stop-aware
on quit, and capability-aware on CLIs without the app-server surface.

* fix(codex): preserve session identity during dedup heal

* fix(codex): preserve user trust during real-home cleanup

* fix(codex): harden real-home heal boundaries

* fix(codex): fail closed on unsafe backfill install

* fix: harden real-home hook cleanup

* fix(ai-vault): preserve execution boundaries and reap children

* fix(codex): narrow app-server unsupported detection

* fix(codex): bound user hook trust rebase retries per host

The rebase lane ran a codex app-server session on every launch prep while a
host was stuck (CLI without app-server support, or keys hooks/list cannot
match). Gate the transaction on the shared capability cache and add the same
5-minute transient cooldown the grant lane uses, so sweep and legacy-cleanup
retries cost plain fs reads instead of a codex session per pane spawn.

* fix(codex): enforce real-home resume and heal boundaries

* fix(codex): establish real-home lane before cleanup

* fix(codex): stop index heal before delayed spawn

* fix(codex): protect symlinked rolling backups

* fix(ai-vault): preserve resume env deletion through drag

* fix(codex): strip inherited Codex homes on mobile real-home resume

The mobile resume surface types a bare real-home codex resume into a
freshly created pane, but never asked for CODEX_HOME/ORCA_CODEX_HOME
deletion at pane spawn, so an agentDefaultEnv-pinned or daemon-inherited
Codex home rerouted the resume away from the user's real ~/.codex while
the same session resumed correctly on desktop. Share the deletion helper
from the AI Vault resume builders and forward it through the mobile
launch and session.tabs.createTerminal call.

* fix(codex): gate session migration on real-home lane

* fix(codex): stop session backfill after opt-out

* fix(codex): keep session heal failures retryable

* fix(codex): keep session migration state recoverable

* fix(codex): retry republished missing session heals

* fix(codex): preserve hook symlink trust path

* fix(codex): disambiguate POSIX trust paths

* fix(codex): align hook trust source paths

* fix(codex): harden trust grant lifecycle

* fix(codex): restore envToDelete on client invocation type after base reconcile

* test(codex): type child.stdout as PassThrough for oversized-output write

* Assemble RC: reconcile app-server transport API across PRs

Unify on the object RPC surface from the index-heal transport (stablyai#8921) while
preserving the default-home env strip (stablyai#8828) and the narrowed missing-app-server
capability signal (stablyai#8847): adapt the user-hook-trust-rebase consumer + tests,
port envToDelete stripping into the shared session, and route stderr
classification through the canonical capability-signal module.

* RC: enable system-default real-home routing by default (flag ON)

Flip codexSystemDefaultRealHomeEnabled to default ON for this RC's staged
rollout (a user can still opt out by setting it false, which stays byte-identical
to managed-home behavior). This is the only intended behavior difference between
the RC branch and the individual PRs. Updates the two tests that assumed the
prior OFF default.

* fix(codex): snapshot hooks.json bytes+parse in one read to close real-home clobber race

The install/sweep/legacy-cleanup paths parsed hooks.json, then did a separate
later read to capture the previous bytes for the pre-write generation guard.
A concurrent save (second Orca instance or the user editing the file) could
land between the parse and that second read and be silently overwritten.
readHooksJsonWithRaw returns the raw bytes and parse from a single read so the
guard compares against exactly what it parsed. Adds a regression test that
mutates hooks.json mid-RPC and asserts the sweep aborts without clobbering.

* fix(codex): sanitize managed account config trust

* fix(codex): guard OAuth add for custom providers

* fix(codex): persist outgoing managed tokens before real-home lane takeover (PR-C)

prepareForCodexLaunch returns null early for the real-home / system-default
lane before syncForCurrentSelection runs. If a managed account is still
recorded as synced when the selection has dropped to the system default
(nulled without a sync pass, or auto-deselect on missing managed auth), a
Codex-refreshed token stranded in the shared runtime home is never persisted
to its canonical per-account home -> token loss.

Read the outgoing managed account's refreshed token back before the real home
takes over. The real-home lane implies host === null, so running the
managed->system-default transition restores only Orca's runtime mirror from
~/.codex and never writes the real ~/.codex. It is a no-op once the selection
has already been reconciled, so the normal select path does not double-write.

* fix(codex): preserve refreshes across all default transitions

* feat(codex): show system-default/real-home account identity in switcher (PR-B)

The account switcher modeled the system-default Codex account as
activeAccountId:null with no identity fields, so the null row rendered
blank ("System default" / generic subtitle) even though its effective
login is whatever ~/.codex/auth.json currently is.

Add a CodexSystemDefaultIdentity descriptor {hasAuth, authKind, email,
providerAccountId, workspaceLabel} to CodexRateLimitAccountsState,
resolved live and READ-ONLY from ~/.codex by the accounts service and
returned from listAccounts()/getSnapshot(). The settings switcher now
renders the null (system-default) row as that real identity: the OAuth
email when signed in, "Custom provider — no usage tracked." for
env-key/custom-provider logins (auth.json with OPENAI_API_KEY, or an
OPENAI_API_KEY env with no auth.json), and the generic fallback when
signed out. Identity is host-scoped (per-distro WSL keeps the generic
label). Orca never writes ~/.codex; managed-account switches only touch
Orca-owned homes, so the system-default identity stays a stable,
displayed source of truth. Usage already routes to the real home via
getSystemCodexHomePath, so the switcher now attributes it to a real face.

Tests (sandboxed temp homes only): OAuth email/provider resolution,
api-key auth.json and env-key (no auth.json) as custom-provider,
signed-out, and select/deselect of a managed account never mutating
~/.codex/auth.json.

* fix(codex): parse multiline provider pins in OAuth guard

* fix(codex): harden managed trust sanitization

* fix(codex): harden system-default identity rendering

* feat(codex): give each managed account a self-contained CODEX_HOME; retire shared mirror (PR-E)

With the real-home flag ON, a host managed account now launches directly
against its own codex-accounts/<id>/home instead of the shared runtime
mirror + auth.json hot-swap:

- codex-home-paths: syncSystemCodexResourcesIntoManagedHome links system
  resources into any managed home (ownership-marker discipline; never
  symlinks into / mutates ~/.codex).
- runtime-home-service: prepareForCodexLaunch / prepareForRateLimitFetch /
  syncForCurrentSelection route the per-account home directly and skip the
  shared-home hot-swap + token read-back; each home keeps its own auth in
  place (fixes GAP-5 concurrent auth race). Session discovery scans every
  per-account home.
- hook-service / hook-trust-promotion: install/getStatus/refresh accept a
  runtimeHomePath so hooks + RPC-granted trust land in the per-account home.
- service: config mirror into a self-contained home uses the trust-
  preserving merge so granted hook/project trust survives account switches.
- codex-session-root-dedup: rank codex-accounts/<id>/home as canonical
  managed alongside the shared runtime home.

Flag-OFF and the system-default real-home (null) lane are unchanged; the
nested-Orca CODEX_HOME===ORCA_CODEX_HOME daemon strip (stablyai#5370) is preserved.
Sandboxed tests only; ~/.codex is never mutated.

* fix(codex): validate per-account home ownership

* fix(codex): keep managed rollouts discoverable across real-home opt-out

WI-4 lossless migration/rollback validation for pre-E shared-mirror managed
accounts. Session discovery gated the per-account home scan on the real-home
flag, so opting back out (flag OFF) hid every rollout an account accumulated
while the flag was ON — the data stayed on disk but vanished from the AI Vault
until the flag flipped back on.

Scan a managed host home whenever it holds a sessions/ tree, independent of the
flag; a never-enabled install keeps its homes credential-only so opt-out stays
byte-identical to today. Forward migration was already lossless (the shared
mirror is always scanned) and the opt-out credential read-back already refuses
to overwrite a fresher per-account token; add tests locking all three
invariants. Sandboxed tests only; ~/.codex is never touched.

* fix(codex): migrate stranded shared auth on E takeover

* test(e2e): isolate Electron from developer Codex home

* test(codex): add real-account validation harness

* fix(codex): finish C and E matcher composition

* fix(codex): bound validation harness shutdown

* test(codex): isolate hook lifecycle user data

* test(codex): cover realistic account-home migration

* fix(codex): keep standalone home tripwire active

* test(codex): fingerprint system auth in validation reports

* fix(codex): bind managed homes to account ownership

* fix(codex): normalize Windows trust source identity

* fix(codex): make Windows trust upgrade transactional

* test(codex): use TypeScript pipeline for validation scripts

* test(codex): run validation modules through native node

* test(codex): allow slow Windows tripwire startup

* fix(codex): survive lingering Windows codex login processes in add-account

On Windows, codex login can keep running (with descendants) after it has
written auth.json, holding OS handles on the per-account managed home
(log/codex-login.log). That made doAddAccount's post-login cleanup fail
with ENOTEMPTY (rmSync) and left an orphaned codex-accounts/<id>/home.

- runCodexLogin now watches for auth.json on Windows and force-kills the
  login process tree (taskkill /t) if it lingers past a short grace
  period; the forced exit is treated as a successful login. The 120s
  timeout path also kills the whole tree instead of only the direct
  child. macOS/Linux behavior is unchanged.
- safeRemoveManagedHome now removes homes with rmSync maxRetries /
  retryDelay (mirroring the local-worktree-filesystem Windows policy)
  and no longer lets a cleanup failure mask the original add error.
- run-codex-real-account-validation.mjs accepts --temp-parent /
  ORCA_CODEX_VALIDATION_TEMP_PARENT so the disposable root can live
  outside %USERPROFILE% on Windows, and fails with an actionable message
  before creating anything when the temp parent is inside the primary
  home. The real-home guard is unchanged.

* fix(codex): preserve managed-account MCP .credentials.json on per-account-home migration (stablyai#8440)

Codex file-mode MCP OAuth tokens live in $CODEX_HOME/.credentials.json,
keyed by MCP server URL with no account identity of their own. The legacy
shared-mirror -> per-account-home migration only carried auth.json, so an
existing managed account with authed MCP servers had its tokens stranded on
upgrade and silently needed re-auth.

Carry the shared mirror's .credentials.json into the same identity-proven
per-account home alongside auth.json: only into the single uniquely-matched
active account (no cross-account leak), only when the destination has none yet
(never clobber a newer file the account authed in its own home), atomic 0600,
absent-source no-op. New MCP auth already lands in the per-account home since
that home is CODEX_HOME.

* fix(codex): preserve Windows reauthentication login flow

* test(codex): build real-account validation harness cross-platform on Windows

The harness built its app with execFileSync('npx', ['electron-vite', ...]),
but npx resolves to a .cmd shim on Windows that execFileSync cannot launch
(ENOENT), so the harness could not build its own app there and required
--skip-build with a prebuilt out/main/index.js.

Extract resolveElectronViteBuildCommand(repoRoot): it runs the repository-local
electron-vite JS entry (node_modules/electron-vite/bin/electron-vite.js) with
the current Node binary (process.execPath), which resolves identically on
macOS, Linux, and Windows with no shell. It throws a clear error if the local
entry is missing (install deps or pass --skip-build). --skip-build behavior is
unchanged.

Add regression coverage asserting the build command uses process.execPath and
the repo-local JS entry (not npx), and that a missing entry fails clearly.

* fix(codex): version the MCP creds migration independently of the auth marker

The auth carry and the MCP .credentials.json carry (stablyai#8440) shared one
existence-only v1 marker, so any build that stamped the auth-only marker
first would strand the MCP store forever. The MCP carry now concludes via
its own per-account-mcp-creds-migration-v1.json marker and runs even when
the auth marker is already present; ordering is code-enforced instead of
landing-discipline-enforced.

Also isolate per-account read failures: one stale or deleted account home
no longer aborts the whole migration. The broken account stays in the
unique-identity ambiguity gate via its stored fields but is never read or
written, so the active account still migrates.

* fix(codex): fail corrupt managed auth.json without echoing credential bytes

A raw JSON.parse SyntaxError from loadOAuthCredentials could carry auth
file fragments into logs and the add/reauth error surface. Throw a
sanitized error instead; filesystem errors still propagate unchanged.

* fix(mobile): give the pairing runtime a disposable home for the E2E boot guard

The main-process guard now refuses to start with ORCA_E2E_USER_DATA_DIR
set but the real user home, and this was the one caller not updated —
the temporary pairing runtime crashed before emitting its pairing URL.

* test(codex): canonicalize harness containment guards and retry cleanup

Resolve symlinks before the disposable-root containment checks so a
symlinked temp parent cannot smuggle the throwaway home inside the
primary home, and give the final cleanup rm Windows retry/force so a
briefly lingering codex handle cannot strand the credential-bearing
root.

* test(codex): add lane-aware containment mode to the real-account harness

The Windows gate-D run proved strict zero-event whole-profile containment
is structurally unreachable with the real-home flag ON: system-default
spawn sites deliberately delete CODEX_HOME so native codex resolves the
real ~/.codex, and on Windows the binary ignores the USERPROFILE sandbox.
Its own volatile runtime churn (root sqlite/WAL/SHM, tmp/, log/) is the
shipped Phase-1 design, not a candidate defect.

--lane-aware-containment records those designed events without aborting
while every other real-home write — auth.json, config.toml,
.credentials.json, hooks.json, sessions/, anything unknown — remains a
hard violation and still aborts the run. Default behavior is unchanged
(strict); the absolute zero-event claim stays carried by macOS runs,
where HOME does sandbox native codex.

* test(codex): allow the real-account harness to pin the real-home flag off

--system-default-real-home off seeds and env-pins the flag OFF so every
codex spawn gets an explicit managed CODEX_HOME and native codex never
resolves the OS profile. This is the only Windows configuration where the
strict zero-event whole-profile tripwire is reachable, and it matches the
stable-rollout default; flag-ON runs keep lane-aware classification.

* test(codex): correct the flag-off harness comment to kill-switch rationale

The rollout ships all codex-home changes at once (no phased rollout), so
flag OFF is the emergency kill-switch lane, not the stable default.

* test(e2e): canonicalize the isolated E2E home path

The disposable HOME lives under os.tmpdir(), whose spelling is an alias
on CI (macOS /var symlink, Windows 8.3 RUNNER~1). Git canonicalizes
worktree paths, so worktrees created under the aliased home never
matched the app's listing — golden core flows and the packaged
crash-survival harness failed with 'worktree created but not found in
listing'. Resolve the home to its canonical spelling at creation in
both the e2e helper and the packaged-app driver.

* fix(codex): address CodeRabbit review on the landing PR

- carry envToDelete through the mobile agent-resume startup plan so a
  real-home Codex resume cannot inherit an ambient CODEX_HOME
- strip Orca-owned Codex overrides in the commit-message WSL fallback,
  matching the host fallback
- strip ELECTRON_RUN_AS_NODE in the computer-e2e driver like every other
  home-isolation caller
- drop the unused hooksEnabled parameter from isRealHomeCodexHookLaneUsable

* feat(codex): ship real-home routing unconditionally, remove the rollout flag

The codexSystemDefaultRealHomeEnabled setting is gone from types and
constants and the helper no longer consults settings — the system-default
real-home lane and per-account homes ship for everyone in one release.
This also un-strands profiles that rc-era builds stamped with false (the
setting had no UI, so every stored false was a seeded artifact that would
have silently kept those users on the legacy mirror forever).

The ORCA_CODEX_SYSTEM_DEFAULT_REAL_HOME env override survives strictly as
a test-rig control: the containment harness pins the legacy lane for
strict zero-event Windows runs, e2e home isolation pins lanes inside
disposable homes, and the legacy-lane test suites now route their
per-test lane selection through it.

---------

Co-authored-by: OrcaWin <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants