Skip to content

fix(codex): opening a terminal no longer strips Codex hooks from the real ~/.codex - #23552

Merged
brennanb2025 merged 88 commits into
mainfrom
brennanb2025/codex-home-single-writer
Sep 30, 2026
Merged

brennanb2025 merged 88 commits into
mainfrom
brennanb2025/codex-home-single-writer

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 32 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3498 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1396 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2102
Prod 50 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1495 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1232 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​263

Stacked on #23667 (one setting decides whether Codex's status hooks are on).

ELI5

Orca adds one small status hook to Codex's settings folder, ~/.codex. Every Orca on the computer shares that one entry, and so does codex typed in any terminal.

Until now, several parts of Orca each decided on their own what that entry should look like, and deleted or undid whatever did not match. That can wipe the entry and its approvals with just one Orca running. On one laptop, the normal app emptied ~/.codex/hooks.json about 150 ms before it opened a Codex pane with a managed account selected. After that, Codex no longer reported its status to Orca.

You don't need two Orcas open at once for the version clash. The common case is an auto-update: terminals you opened before the update keep running the previous version's code, and typing codex in one of them rewrote the entry the updated app had just written. Running a release build next to a beta or dev build does the same.

Now every Orca version writes exactly the same entry, only the main Orca app writes it, and it only ever adds it when it is missing. Only two things remove an Orca entry: turning Orca's Codex hooks off, and a one-time cleanup of Orca's retired command forms. When either removes one, the approvals of your hooks behind it move with them, so you are not asked to review them again, apart from the few cases listed under User-visible changes.

What Changed

Before

  • Opening a terminal could delete the shared entry. On one laptop the running app shrank ~/.codex/hooks.json from 4139 to 18 bytes and removed eight trust approvals from ~/.codex/config.toml, about 150 ms before it opened a new pane with a managed Codex account selected. A test Mac showed the same thing (3883 to 18 bytes).
  • Each Orca version wrote its own version of the command. When two versions shared a computer, each pane launch rewrote the other's entry, and Codex asked to re-approve it each time.
  • Launch prep also removed Orca entries from any Codex event the running version did not use, so a newer version's events were stripped by an older one.
  • When a Codex trust approval failed, Orca put back whole copies of hooks.json and config.toml from before the attempt, undoing anything saved in between, including another Orca's identical entry.
  • Typing codex in a pane first ran orca agent hooks prepare-codex inside the pane. That process can see the real home folder even when the app uses another one, and it wrote Codex files outside the app's own ordering.
  • Removing an Orca entry (an old command form, or turning hooks off) moves the user's hooks behind it up a slot, and Codex keys approvals by slot. Orca asked a codex app-server session to carry those approvals over, and would not remove anything until that session answered.
  • A Codex launch waited for Codex to approve Orca's entry. On a busy Mac a cold codex app-server took over 10 seconds, the session timed out, and a 5-minute cooldown then blocked the cleanup and the approval on every retry.
  • The approval session held the lock on ~/.codex/config.toml for its whole run, and before a session Orca deleted Orca-entry approvals whose hash matched its own computation, putting them back from a snapshot if the session failed.

After

  • One frozen command. Every Orca version writes the same command bytes. On macOS and Linux it contains no path at all: it runs Orca's shared script only inside an Orca pane with hooks on, just drains its input everywhere else, and always exits 0. On Windows, Codex runs a hook in the turn's shell (PowerShell 7 or Windows PowerShell 5.1), or with %COMSPEC% /C, which is cmd.exe, when a session has no single local turn shell. A profile path made only of letters, digits and _ . : / ~ - is written as the plain forward-slash path to the shared .cmd, which runs under all three. Any other profile path, for example one with a space, &, ^, $, a backtick, ', !, (, ) or a non-ASCII character, is written as <Windows folder>\System32\cmd.exe --% /d /v:off /c @"<path>", which names Windows' own cmd.exe by its full path (for example C:\Windows\System32\cmd.exe, with backslashes, because cmd.exe reads a forward-slash program path as a list of switches); which characters and hosts it ran under live is in Testing. Orca reads the Windows folder from %SystemRoot% when it writes the entry, or from the folder above %ComSpec%'s System32 when %SystemRoot% is unset or is not a plain full path, so which spelling a computer gets, and its bytes, depend only on its profile path and its Windows folder, and every Orca version there writes the same bytes.
  • The command carries a form number (orca-agent-hook-form=1). A version never rewrites an entry with a higher number, and never adds a second entry beside it.
  • One writer, add-only. Only the main app process writes the entry in ~/.codex.
    • Opening or resuming a Codex pane adds the entry to an event that has none, and leaves every Orca entry it finds as it is. A running older version is never fought.
    • App start also converts an older Orca entry to the frozen command, once, in its own slot. It drops a duplicate Orca entry only when no user hook sits behind it; a duplicate with a user hook behind it stays, and both copies are approved.
    • Orca entries in events this version does not use are kept.
    • None of these writes moves a user hook, so none of them touches a user hook's approval.
  • Removal carries approvals with the hooks. When Orca does remove an entry, each user hook that moves up a slot takes its approval record with it, byte for byte. Codex's approval covers what a hook runs, not where it sits in the file, so the record stays exactly as valid as it was: approved stays approved, unapproved stays unapproved, and a hook the user turned off stays off. No Codex session is involved, so no cleanup waits on one.
  • No launch waits for Codex's approval of ~/.codex. Orca's entry in ~/.codex needs Codex's approval, and a cold codex app-server can take over 10 seconds to give it. The launch that adds the entry does not wait: it goes to Orca's managed Codex home, and Codex's approval runs in the background until its own 30-second limit. At most one approval runs at a time in an Orca app. A launch or resume that arrives while one runs is answered from that approval instead of starting another, whatever Orca concluded before it. The approval holds no lock on config.toml and does not stand in for the shared "does this Codex support approvals" check, so a launch during it waits only on the managed home's own setup and the project-trust write. That setup is immediate when Codex's approval of the managed home is on record. When it is not (the managed home's first use, a Codex update, or a lost record), the managed home asks Codex itself, as on main: up to 10 seconds on a cold codex app-server, then at most once per 5 minutes after a failure. The first launch after the ~/.codex approval lands uses ~/.codex.
  • A resume into ~/.codex waits for the running approval, so it does not start in front of Codex's hook review for Orca's hooks. A resumed session that must run in ~/.codex has no managed home to use instead, and Codex puts any unapproved hook entry up for review on a full screen before the session starts. So a resume waits while an approval runs and ~/.codex holds an Orca entry Codex has not approved, and at no other time. Every resumed pane, including panes restored together at app start, waits on that same approval, so this wait is at most 30 seconds. The first launch after this update may pause a resumed Codex pane for that long while Codex approves Orca's hooks. If Codex does not approve in time, Orca takes back the entry it added before the pane starts, so the session starts with no hook review and without Orca's status for that session, as on main after its 10-second wait. Two exceptions remain, both under Known weaknesses: if another program moves Orca's entry while the approval runs, a failed approval cannot take it back; and a resume that starts right after a failed approval can re-add the entry and meet the review. Counting the rest of a resume's setup, the worst case is longer; see Known weaknesses.
  • A failed background approval retries in seconds, not minutes. A timeout starts no cooldown for the first two in a row: the next launch tries again. Any other failure waits 10 seconds instead of 5 minutes. From the third timeout in a row, the next try waits 10 seconds, then 1 minute, then 5 minutes each time. Only a successful approval or an Orca restart resets that count; another kind of failure in between does not. The ~/.codex check keeps this one retry schedule itself; approvals on the launch path (managed homes and WSL) keep their own 5-minute cooldown, which a background approval neither starts nor waits on. Only a success is remembered, in Orca's record of Codex's approvals; the one exception is a Codex too old to approve hooks this way, which Orca stops asking until it restarts or its Codex hooks are turned off.
  • Failed approvals take back only their own write. If Codex cannot approve the entry, Orca re-reads both files and removes only the entry it wrote in that same attempt, at the slot it wrote it, while it is still unapproved, putting back what that slot held before. It refuses to write if hooks.json changed since that read. Anything saved meanwhile survives, in both files, and so does the same entry if another Orca approved it in the meantime. The log says how many entries it took back and when the next try comes.
  • Turning hooks off and on during an approval starts no second one. Launches keep using the managed home until that approval ends. The first launch after it ends, and after its retry wait if it failed, adds the entry again and asks Codex again.
  • A failed approval never removes an existing approval. Orca no longer deletes approvals from ~/.codex/config.toml before an approval session. So when another Orca profile (which keeps its own record of approvals) or a Codex update re-runs the approval and it fails, Orca's already-approved entries stay approved. Managed and WSL homes still clear the approvals Orca itself computed before a session, because their fallback writes them back; each of those installs does that clear itself, only when a session will run, and the ~/.codex approval has no such step.
  • No file restores. The rollbacks that put whole files back are deleted. A Codex approval session only writes approvals for Orca's own entries, and each caller settles those itself.
  • No pane step on macOS, Linux or native Windows. Native panes no longer carry ORCA_CODEX_LAUNCH_PREFLIGHT, so typing codex there starts nothing before Codex; the app already prepares the Codex home before it starts a recognised Codex launch. orca agent hooks prepare-codex does nothing on these hosts, and stays until no supported version's terminal wrapper calls it, so wrappers in terminals opened by older versions still exit cleanly. WSL panes are unchanged and still ask the app to prepare their home.
  • Removal is explicit only. Only turning Orca's agent-status hooks off, or turning Codex off in the per-agent hook settings (fix(codex): turning Codex off per agent keeps its hook entry off #23667), removes the entry and its approvals.

Why

The root cause was not any one caller. Each automatic writer worked out "what Orca's entry must be" from facts local to it: its own version's command, its own events, its own home folder, or its own snapshot of the files. It then removed or reverted everything that differed. A computer runs several writers at once (instances, versions, and the app beside its own pane command), so any fact two of them disagreed on became a deletion.

This change removes the disagreement instead of guarding it:

  • Identical bytes leave nothing to reconcile. Two versions that write the same bytes cannot fight, and "is my entry there?" becomes a simple equality check.
  • Add-only writes cannot delete. No automatic path removes an entry that a user hook sits behind, so a disagreement that remains (an older version that has not updated yet) costs a rewrite, never a missing entry or a moved user hook.
  • One process writes. The pane command no longer writes or asks for a write on native hosts, and native panes no longer run it, so every write goes through the app's own queue.
  • Cleanup re-reads instead of restoring. Withdrawing only a still-unapproved entry of its own cannot undo someone else's save, and with identical bytes, another Orca's approval of the same entry is recognised and kept.
  • Approvals move with their hooks. Codex's approval of a hook does not depend on its position, so moving the record with the hook needs no Codex session. The cleanup no longer depends on Codex answering in time.
  • A launch never depends on Codex answering. The approval is bookkeeping for the next launch, so it runs beside the launch, holding no lock the launch needs, instead of in front of it. A resume into ~/.codex, which has no other home, waits only while an approval runs and an unapproved Orca entry is on disk, and no longer than that approval's 30 seconds.
  • One approval, decided when it runs. Earlier revisions of this change kept a status label, a queue of approvals and a version stamp, and decided from the label when a caller arrived. Review found that resumes restored together then started one approval each, 30 seconds apiece; that a queued approval could run on entries an earlier failure had already taken back; and that settings reading hooks off mid-approval released a waiting resume beside unapproved entries. Now every check runs in the queue that already orders Orca's writes to config.toml, and decides from what is true when it runs: whether an approval is running, what the settings say, and what is on disk. The status the routing check reads is only an output.

This also deletes guards that existed only because the bytes differed or because a session had to answer first:

  • the compare-and-swap check on each rollback, which could not tell two instances' identical writes apart;
  • the check that the pane "runs its own script", which proved the same home folder but not the same process, and then the pane request that replaced it;
  • the per-version rewrite on every pane launch;
  • the app-server sessions that listed and re-keyed moved user hooks, and their 5-minute cooldown.

Alternatives rejected

  • Ship the earlier fix as a stop now, and the frozen command later. Every version released without a form number becomes a permanent "older version" that rewrites any later command by file name. Most of the earlier guards would be deleted by the frozen command anyway.
  • A cross-process lock around every write. An earlier revision had one. It fixed no observed failure, and its own complexity produced five of the defects review found.
  • Write only at app start and on settings changes, never per launch. The launch-time check is what keeps "hooks are installed here" honest after an older version or the user removes the entry. It is now a read that adds only what is missing, so it costs one file read in the normal case.
  • Tell Codex to skip hook approval on each launch. That switch applies to every hook Codex finds, so it would also run the user's own unapproved hooks.
  • Keep restoring snapshots, with a better check. No check can tell an identical write by another Orca from Orca's own, and a restore always risks undoing a save made during the approval session.
  • Keep the pane step and have it ask the app. The case it was added for, a terminal that survives an update and then finds Codex asking for approval again, did not reproduce in a capture across an Orca app update, and the app already prepares the home before each recognised Codex launch. A Codex binary update, the other candidate trigger, was captured separately: across Codex 0.141.0, 0.150.1 and 0.158.0, in all six update directions, Codex's approval hashes for Orca's hook entry shape were byte-identical and no version rewrote config.toml, so an update did not ask for approval again. That stability comes from how Codex serializes a hook, not from a promise, so a later Codex could still change it (see Known weaknesses).
  • Keep asking Codex to re-key moved approvals, but write first. That still fails whenever Codex is slow, and then the user's own hooks ask for approval again. Moving the record needs nothing from Codex.
  • Let the launch wait for the approval, with a longer deadline. Any deadline long enough for a cold start on a busy Mac is too long to hold a launch, and the managed home already serves a launch whose approval is not ready.
  • Let a resume start at once, take the entry back itself at a shorter deadline, or approve Orca's entries for that one process on its command line. Starting at once puts Codex's full-screen hook-review screen in front of the resumed session, and it blocks until the user chooses: "Trust all and continue" also trusts the user's own unreviewed hooks, and "Continue without trusting" leaves that session with no Orca status for its whole life, because Codex does not pick up an approval that lands later. Taking the entry back from the resume itself races the still-running approval: Codex can write the new entry's approval after Orca put the older entry back, which then reads as modified. Approving per process works in Codex, but the resume command is typed into the pane's shell, and Orca keeps hook settings out of typed commands (some shells cannot parse them, and the typed command is saved and can be copied). So the resume waits for the one running approval, at most its 30 seconds, and starts either with Orca's entry approved or with it taken back.

Differences from the common pattern

  • When the entry is written. The common pattern writes agent settings at app start and on settings changes. Orca also runs a check on each Codex pane launch and resume, which only adds a missing entry. The trigger differs; what gets written does not.
  • Approval. The common pattern either skips the agent's hook approval on each launch or writes nothing lasting. Orca asks Codex itself to approve the entry, once per home and Codex binary, in the background, so the user's own hooks keep their approval checks.
  • Moved approvals. Orca edits Codex's trust store in config.toml directly, but only to move a user hook's existing record when an Orca removal shifts that hook to a new slot. The move computes no hash: the record Codex wrote moves to the new key byte for byte, including fields Orca does not know, and a hook with no record gets none. This is safe because Codex's hash excludes the file path and the hook's position. The key format, <path>:<event>:<group>:<handler>, was checked unchanged from Codex 0.141 to 0.158. If any stored key has another shape, Orca moves nothing and Codex asks the user to review, as it would without Orca. The edit re-reads config.toml immediately before an atomic replace and changes only the moved records, so a save made meanwhile survives.
  • Newer versions. The common pattern either strips any matching entry or compares exactly, so an older version rewrites a newer one. Orca leaves a higher form alone. This is stricter than the common pattern.
  • The pane step. The common pattern writes nothing from a terminal or launch wrapper. Orca now matches that on macOS, Linux and native Windows. WSL panes still ask the app to prepare their home, as they did before this change.
  • Windows bytes. The Windows command contains the user's profile path, and for a path that needs cmd.exe the computer's Windows folder, so it differs between users and computers but not between Orca versions.

User-visible changes

  • A one-time rewrite of the Codex entry. On the first start of this version, Orca rewrites each Codex hook entry in ~/.codex/hooks.json to the frozen command, in place. That is one write of the file (so one hooks.json.bak) and one Codex approval write per home; a second Orca profile on the same home runs its own approval session, which finds the approval already recorded and writes nothing. Later starts and pane launches find the same bytes and write nothing. On Windows Orca never writes ~/.codex, because Orca does not run Codex in ~/.codex there (as on main); only Orca's managed Codex homes change. A profile path of only safe characters changes from backslashes to forward slashes, and a profile path with a space or another special character changes from main's PowerShell command to the cmd.exe spelling. Either way each managed home's file is rewritten once; converting from the older encoded launcher took two approval sessions in the Windows test, one of which wrote nothing.
  • Beside an older Orca still running, the older one rewrites the entry to its own command on its pane launches, and this version converts it back on its next start, not on every pane launch. This stops once the older one updates.
  • Removing Orca's entry does not make you re-review your hooks. Orca removes one of its entries only when the user turns Orca's Codex hooks off, or when an old Orca command form is cleaned up, and the approvals of the user hooks behind it move with them. Codex asks for a review only if Orca cannot edit ~/.codex/config.toml at that moment (for example, it is read-only), or the file holds an approval key of a shape Orca does not recognise; Orca then moves nothing and logs the first case. Separately, codex typed in your own terminal can list Orca's entry for review while Orca's background approval of a newly added entry is still running, and if a failed approval could not take its entry back (the entry moved, or hooks.json changed meanwhile), until the next launch's approval.
  • No Codex launch waits for Codex's approval of ~/.codex, and a resume waits at most 30 seconds for it. On a busy computer, the launch that adds Orca's entry runs on Orca's managed Codex home instead, its setup no longer queues behind that approval, and a later launch uses ~/.codex once Codex has approved the entry. The managed home still needs its own approval on record: on its first use, after a Codex update, or after that record is lost, the launch waits for it up to 10 seconds, as on main. A resumed Codex pane may pause for a few seconds, and at most 30 for the approval, while that first approval runs, instead of starting in front of Codex's hook review for Orca's hooks (the two exceptions are under Known weaknesses). If hooks are turned off while an approval runs, launches use the managed home until it ends, up to 30 seconds.
  • The hook no longer passes a script failure back to Codex. On macOS and Linux the command always exits 0, so a broken Orca script can no longer make Codex block a prompt. On Windows the shared script ends with exit 0; if the script file is missing, the hook fails with a non-zero code (cmd.exe's "not recognized" code under the cmd.exe host, 1 under PowerShell).
  • Outside an Orca pane with hooks on, the hook no longer starts Orca's script; it only reads and discards its input.

Scope

Linked Issue

No public issue. Follows up the reports of Orca deleting the shared Codex hook entry in ~/.codex.

Visual Proof

Live QA of this change (commit 3c64322 on macOS and Windows, e8c59f7 on Linux; later commits changed only tests, a CI list, comments, one shared key pattern and merges of main) on background-launched builds, each with its own home and Codex home. Full results are in the status comment.

The frozen hook command, run with a terminal's hook settings, moves that terminal from working to done (macOS):

Hook delivery on macOS: after UserPromptSubmit, the terminal reads working (spinner on the tab and the sidebar row, with the prompt)
Hook delivery on macOS: after Stop, the tab reads Codex ready with a bell and the sidebar row has a green check

On Windows, a turn under each of Codex's three hook hosts:

Windows, Codex hooks under cmd.exe: the turn is working (spinner on the tab and the sidebar row)
Windows, Codex hooks under cmd.exe: the turn is done (bell on the tab, green check on the sidebar row)
Windows, Codex hooks under PowerShell 7: the turn is done (green check on the sidebar row)
Windows, Codex hooks under Windows PowerShell 5.1: the turn is done (green check on the sidebar row)

On Linux (headless), the same hook command run with a terminal's hook settings: after Stop, the tab reads Codex ready with a bell.

Hook delivery on Linux: after Stop, the tab reads Codex ready with a bell

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

For each deleted guard, the test for its replacement was run against the previous head first and failed there, then passes here. Each new mechanism was also removed in turn, and its tests turned red.

  • codex-hook-command-form.test.ts: the POSIX, Windows bare-path and Windows cmd.exe commands match golden bytes; POSIX bytes are the same for any home; a Windows profile path holding any one of a space, &, ^, $, a backtick, ', !, (, ) or a non-ASCII character gets the cmd.exe spelling, a safe path stays bare, and either slash direction gives the same bytes; the cmd.exe spelling names <Windows folder>\System32\cmd.exe from %SystemRoot% on any drive (D:\Windows gives D:\Windows\System32\cmd.exe), else from the folder above %ComSpec%'s System32, which gives the same bytes, and C:\Windows when neither is a full drive path it can write unquoted (unset, relative, spaced, holding &, a network share, or another shell in %ComSpec%); the same inputs always give the same bytes; every form keeps the script name in plain text, so older versions still recognise it; the form number reads as current, higher, or older; app start converts each older Windows form (this change's earlier PowerShell spelling, main's PowerShell text, the encoded launcher, and the unpushed bare-cmd spelling) to the cmd.exe spelling once, in its slot, and a pane launch leaves it (red when the conversion skips entries of the same form number). Always writing the bare path, always writing the cmd.exe spelling, dropping the @, keeping backslashes in the script path, spelling the cmd.exe path with forward slashes, letting a space or a non-ASCII character through bare, writing a bare cmd, quoting the cmd.exe path, dropping /v:off, ignoring %SystemRoot%, dropping the %ComSpec% fallback, taking %ComSpec%'s own folder as the Windows folder, keeping %SystemRoot%'s backslashes, or accepting any %SystemRoot% each turns these red. Under /bin/sh the command runs the shared script only in a pane with hooks on, the root script only with a root and a pane key, nothing outside Orca or in a structured child, and always exits 0 even when the script exits 2. Changing one byte of the builder turns the golden red.
  • codex-real-home-frozen-entry.test.ts (with a stand-in for Codex's approval session and its ledger):
    • converting an older entry at app start writes the file once, leaves one .bak holding the old bytes, and runs one approval write; two more pane launches and another start write nothing and run no session (red on the previous head);
    • a second Orca instance produces identical bytes and writes nothing;
    • a pane launch leaves an older version's entry untouched, with no write and no approval session (red on the previous head, and red when launches are allowed to convert);
    • a pane launch adds the entry only to the event that lost it;
    • a higher form is never rewritten or appended beside, on launch or at start (red on the previous head, and red without the form rule);
    • Orca entries in events this version does not use are kept (red on the previous head, and red when the strip is put back).
  • codex-real-home-user-hook-positions.test.ts: for each automatic write, every user hook keeps its position and its approval record stays byte-identical (the user's config.toml bytes stay a prefix of the file): a launch adding the missing entry, app start converting an older entry in place, a trailing duplicate dropped, a duplicate with a user hook behind it kept with both copies approved, and older duplicates normalised to one entry. The three duplicate cases fail on the previous head; removing the position check, or the in-place conversion, turns its tests red.
  • codex-real-home-slow-app-server.test.ts (QA case 4):
    • with a Codex start that takes 15 seconds, two launches return in under a second on the managed home and start one session between them; the approval lands in the background, and the next launch uses ~/.codex with no new session;
    • a first timeout starts no cooldown, takes back its unapproved entries and logs that the next launch retries; the next launch runs a session at once;
    • a session runs until its own 30-second limit ends it, and a launch during it starts no second session (red with a second timer around the approval, which gave up on the session while it was still running);
    • after a first approval, a second approval that misses Orca's record (as a second Orca profile does) and fails leaves every Orca entry approved (red when the pre-session approval clear runs for ~/.codex);
    • any other failure retries after 10 seconds, not before;
    • turning hooks off and on after a failure retries at once, instead of writing the entry and taking it back (red with a second retry schedule in the approval module);
    • turning hooks off and on while an approval runs adds nothing and starts no second session until it ends, and launches stay on the managed home meanwhile, even right after the opt-out; the first launch after the failed session's 10-second wait re-adds the entries and they are approved (red on the previous head, which re-added at once and queued a second session, and red when the routing check ignores the running approval);
    • settings that read hooks off during an approval keep launches on the managed home, and the approval settles as removed (red on the previous head, which reported the lane usable at once); hooks back on inside that failure's retry wait stay on the managed home (red when the check answers with the status it stored instead);
    • an approval's end writes no new entry: a one-time rewrite that met a running approval is skipped, not run when it ends, so a resume that approval releases never meets a freshly rewritten, unapproved entry (red when that deferral is put back); app start's rewrite is the process's first check, so it never meets one;
    • an opt-out that could not read hooks.json during an approval keeps launches on the managed home after the approval ends (red when the approval's end reports hooks as removed over it);
    • the approval's cleanup waits for a writer that holds the config.toml queue (red when it runs in its caller's queue context);
    • with every session timing out, the old-form cleanup still removes the old entry, and the user hook behind it keeps its approval.
    • three timeouts in a row back off 10 seconds, then 1 minute, then 5 minutes, and a success resets that; a failure of another kind between timeouts does not reset the count (red on the previous head), and an app restart does; timeouts during a slow first start do not stop the attempt after them, which installs once the app server answers (red without the reset, without the growth, without the backoff, and with a threshold of one);
    • Making the launch await the approval, a 10-second deadline, a cooldown after the first timeout, or a 5-minute backoff after any other failure each turns its test red.
  • codex-launch-during-real-home-grant.test.ts (the full launch and resume paths, real files, with a stand-in codex app-server for each home): while the ~/.codex approval session hangs, two launches each settle in under 2 seconds on the managed home, with that home's hooks installed, its approval run once and then found on record, and both project-trust writes in config.toml, and only one ~/.codex approval session runs (red when the approval holds the config.toml lock across its session, and red when it shares the capability check with launch-path approvals). When the managed home's codex app-server is cold too, the first launch waits for that home's own approval and settles at its 10-second limit, and the next launch settles at once (red when that limit changes). A resume into ~/.codex waits for a warm approval and starts with Orca's entries approved; with a hung approval it starts at the 30-second limit with Orca's entries taken back; and three resumes, as panes restored at app start, share one approval session (the first two red when the resume does not wait). With every ~/.codex session timing out, three resumes restored together share one session and all start at its 30-second limit with Orca's entries taken back, whatever Orca had concluded before (not yet checked, installed, failed, or hooks off), and a launch during their wait settles at once on the managed home (red on the previous head, which ran a session per resume, and red without the one-at-a-time check). Resumes restored after the app-start check share its session. After a failed approval no second session runs on the entries it took back, and the next resume approves them fresh (red on the previous head, which ran a second session that could only fail). A resume whose settings read hooks off during an approval still waits while Orca's unapproved entries are on disk (red on the previous head, which started it at once beside them), and a resume after the opt-out removed them starts at once (red when the wait ignores what is on disk).
  • codex-real-home-failed-grant-concurrent-edit.test.ts (QA case 9, real files in a temporary home): Codex's approval session fails after another writer saved both hooks.json and config.toml, and the user approved the newly saved hook meanwhile. Both saves survive, no unapproved Orca entry is left, the saved hook's approval moves with it when Orca's entry is withdrawn, the log names the count and the 10-second retry, and the retry runs. A failed one-time conversion puts the older entry back in its slot and keeps both saves. Both fail on the previous head, which restored config.toml from a snapshot; removing the withdrawal turns both red.
  • codex-user-hook-trust-moves.test.ts: a removal moves approved, turned-off and unapproved hooks' records byte for byte, including the key a removed Orca entry vacated; only the moved records change, every other byte of config.toml stays, and a moved record keeps a field Orca does not know; any stored key of an unknown shape stops every move; a config.toml that cannot be written keeps the hooks.json write and logs. Removing the move, the shape check, or writing a computed record instead of the stored one turns these red. A record in Codex's quoted spelling (["hooks"."state"."…"]) moves unchanged and leaves no second table (red with the quoted-spelling support removed).
  • codex-real-home-trust-withdrawal.test.ts: after a failed approval, only this attempt's entries are withdrawn, while a user hook appended during the session and a new user event survive; an entry another Orca approved during the session is kept; a failed one-time conversion puts the older handler back in its slot, and not into an earlier frozen copy in a matcher group (red when the withdrawal finds the entry by command); a hooks.json save between the withdrawal's read and its write survives (red without the unchanged-file check).
  • codex-real-home-entry-trust.test.ts: an Orca entry's stored approval reads as current, missing, stale (a record for other content at that slot) or turned off. The failed-approval withdrawal uses it, and keeps an entry the user turned off.
  • codex-hook-trust-grant.test.ts, hook-service-trust-grant.test.ts: a config.toml save or creation during a failed approval session is kept, and the managed home still ends with Orca's approvals from its fallback (red on the previous head, which restored the snapshot). A launch-path approval that fails stays cooled down for 5 minutes, even 10 seconds later; a background approval neither starts nor waits on that cooldown (red when it does). A managed home's Windows fallback approvals are cleared by the caller's own step, which runs only when a session runs and never when Codex's approval is on record (red when the step is dropped; clearing before that check instead turns the launch test red, with a managed session on every launch).
  • codex-trust-config-concurrent-launch.test.ts: a project-trust write lands while an approval session is still running, and survives the session's failure (red when the approval holds the lock across its session); a failed approval leaves a concurrent approval's records in place.
  • codex-shell-launch-preflight.test.ts, pty-spawn-env-terminal-basics.test.ts, codex-preflight-profile-path-rewrite.test.ts: a native macOS, Linux or Windows pane gets no ORCA_CODEX_LAUNCH_PREFLIGHT, packaged or not, even with Orca's command-line tool present; a WSL pane still gets the verified absolute path to it, which a profile that rewrites PATH cannot redirect. Letting native panes through again turns the first two red.
  • agent-hooks.test.ts, agent-hooks-load-boundary.test.ts, agent-hooks-prepare-codex-isolated-home.test.ts: on a native host prepare-codex sends no request, loads no installer or profile storage, writes nothing to the real home, the app's home or the managed home, and exits 0; a WSL pane still sends one request and fails open.
  • codex-launch-per-agent-hook-opt-out.test.ts: pane launch and resume call the real-home check with the add-only policy (red on the previous head), and a resume into ~/.codex waits on a running approval while a resume into a managed account home does not.
  • Existing suites kept: the shared-entry tests (a managed-account pane, hooks-off launch prep and hooks-off startup leave ~/.codex byte-identical; only the explicit opt-out removes the entry), the retired-form list (which sweeps neither Windows spelling, with Windows on any drive, nor the earlier PowerShell or bare-cmd spellings), and the Windows delivery test (a missing script now exits non-zero, as the bare path always did).

Checks run: oxlint over the whole tree, check:max-lines-ratchet and check:code-quality:changed, all clean. Tests: 414 files covering src/main/codex, src/main/startup, src/main/codex-accounts, src/main/agent-hooks and the CLI handlers, excluding real-binary, real-CLI, login-shell and integration suites: 4356 passing, 28 skipped, and one unrelated startup test file (browser-process-user-agent-ordering.test.ts) whose cases time out under machine load here, as they also did on an earlier head; that broad run predates the final backslash change, after which the 43 real-home, hook, trust, launch, resume and command-form files ran again: 513 passing, 6 skipped. Automated tests ran on macOS only; three Windows-only managed-install tests now expect the frozen command; they did not run here, and this PR adds their file to CI's Windows test job, which had never run them. The earlier cmd spelling, cmd --% /d /c @"<path>", ran live on a Windows computer through real Codex 0.158.0 with a stand-in hook script: 18 of 18 cells, PowerShell 7, Windows PowerShell 5.1 and cmd.exe each with a profile path holding a space, &, ^, $, a backtick, or non-ASCII characters, ran SessionStart, UserPromptSubmit and Stop with the full input; the bare path ran under PowerShell 7 in the same run. A synthetic run of the exact command lines Codex builds also covered ', !, (, ) and a lone %, which ran, and %NAME%, which did not. Live run of the current spelling (C:\WINDOWS\System32\cmd.exe --% /d /v:off /c @"<path>") on Windows 11 build 26200 under PowerShell 7, Windows PowerShell 5.1 and cmd.exe: 45 profile-path cases, including a space, #, ,, ;, =, @, [, ], {, }, +, &, ^, ', $, a backtick, (), a lone %, a lone !, non-ASCII, and a b;c=d,e; every case ran with full input on all three hosts except %NAME%. A real codex exec 0.158.0 in an isolated Codex home ran SessionStart, UserPromptSubmit and Stop through it for First Last and a b;c=d,e under all three hosts, with cmd.exe forced by leaving the session no local environment. A cmd.bat planted in the session folder never ran; one placed first on PATH did run for a bare cmd under both PowerShell hosts, and never for the full path. Not tested live: a Windows folder that is not C:\WINDOWS, and older Windows builds. The macOS and Windows QA re-run of the final design is under Visual Proof; the Linux re-run is pending.

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Author X: @BrennanKB5

Security: moving an approval record can never approve content the user has not approved. Codex compares a record's hash with the content of the hook at that key, so a record moved to the wrong hook only yields a hash mismatch, which Codex shows as "modified" and asks the user to review. At worst a wrongly moved "turned off" record turns a hook off. The move never computes a hash; it only relocates a record Codex wrote.

Security: on Windows the cmd.exe spelling names Windows' own cmd.exe by its full path, with backslashes. A bare cmd is looked up through PATH under PowerShell 7 and Windows PowerShell 5.1, the hosts Codex normally uses, so a cmd.bat placed earlier on PATH ran instead of Orca's hook in a live test on Windows 11 (build 26200); the full path was immune on every host. The same test found no lookup in the session's folder under the cmd.exe host, which resolves a bare cmd through %ComSpec% on that build; older builds were not tested. /v:off keeps a pair of ! in the profile path (for example x!OS!y) from being expanded when delayed expansion is on, under both PowerShell hosts (the probe showed the pair expands when the hook's own cmd.exe runs with /v:on; that /v:off wins over the registry rests on cmd.exe's help text, and the registry was never changed); under the cmd.exe host, Codex's own outer cmd /C expands the pair first, which Orca cannot change. The path is written unquoted, because PowerShell reads a quoted first word as a value, not a command, and with backslashes, because cmd.exe reads a forward-slash program path as a list of switches (live: the forward-slash spelling ran under both PowerShell hosts and never under cmd.exe, silently).

Known weaknesses:

  • An Orca version from before this change still rewrites the entry to its own command on its pane launches, and its cleanup still matches Orca entries by file name, until it updates. This version converts the entry back at its next start.
  • A Windows profile path containing %NAME%, where NAME is a defined environment variable, fails silently under every host: cmd.exe and PowerShell's --% both expand it, so Codex runs no Orca hook and reports no error. A lone % is fine. Likewise a pair of ! around a name (for example x!OS!y) under the cmd.exe host when delayed expansion is on in the registry, because Codex's own outer cmd /C expands it before Orca's command runs; a lone ! is fine.
  • Under the cmd.exe host only, a profile path written in the cmd.exe spelling adds one cmd.exe process to each hook run; under both PowerShell hosts it starts as many processes as the bare path.
  • If neither %SystemRoot% nor %ComSpec% gives a Windows folder as a full drive path Orca can write unquoted, which Windows Setup does not produce, the cmd.exe spelling names C:\Windows\System32\cmd.exe, still a full path, so it fails closed rather than looking anything up. On a computer whose Windows folder is elsewhere, that profile's hook then fails like a missing script and shows no status. Falling back to a bare cmd would bring back the PATH lookup under PowerShell, and falling back to the bare script path would let cmd.exe split a path holding &.
  • Claude's Windows hook host, Git Bash, is out of scope: Claude keeps its current command, and the cmd.exe spelling is only for the hosts Codex uses.
  • While codex app-server keeps hanging, launches stay on Orca's managed home. One background session of up to 30 seconds runs at a time, and the next launch after it ends starts another, until three have timed out in a row; later tries then wait 10 seconds, 1 minute, and then 5 minutes each. It runs beside any launch-path approval rather than sharing its capability check, so a cold host can briefly run two sessions. Each Orca app runs its own, so two Orca apps on one computer can each run one.
  • A managed-home launch's own approval still holds the config.toml lock across its inline session, as before this change: up to 10 seconds, and at most once per 5 minutes after a failure. A project-trust write or ~/.codex check queued behind it waits that long.
  • A resume into ~/.codex can take longer than 30 seconds end to end. In the worst case it waits for the ~/.codex approval (30 seconds), for that approval's cleanup and for managed homes' own approvals queued ahead of either on config.toml (up to 10 seconds for each one whose first approval is queued ahead, as on main), and then, as every agent start does since feat(agents): pre-trust the folder wherever Orca starts an agent #23744, for the project-trust write (up to 20 seconds). The 30-second limit holds for the approval wait alone.
  • A resume released after a failed approval starts with Orca's entries taken back, but a launch or another resume in the next moments can add them again (the first two timeouts retry at once), and a resumed Codex reads its hooks just after it starts, so it could then show the review. This is inferred from Codex's startup order and has not been observed.
  • A duplicate Orca entry that a user hook sits behind stays, so Orca's status hook runs twice for that event. Both copies are approved. Turning hooks off removes both.
  • A future Codex that changed what goes into a hook's hash would show Orca's entry as "modified" until Orca's next approval of it, which the first launch after that Codex update starts in the background. Orca's record of Codex's approvals is tied to the Codex binary, so every Codex update costs one background approval session even when the hashes are unchanged; that session then finds the entry already approved and writes nothing. Moved user hooks' records rest on the same fact: if a later Codex hashes the path or position, the moved hooks show for review, as any unapproved hook would.
  • Orca's own removals (turning hooks off, and the retired-form cleanup) no longer wait for a running approval session, so if one lands in the single codex app-server round trip between Codex listing the hooks and writing their approvals, a user hook it moved up can end up with Orca's approval record and read as modified, and Codex then asks the user to review that hook. Closing this needs a way to cancel a running approval session, and Orca's app-server session runner takes no cancel signal today.
  • Taking back an older-form entry's approvals on opt-out works only when they match this version's command or Orca's ledger; other leftovers stay in config.toml and approve nothing else.
  • The command finds the shared script through the pane's $HOME. A pane whose home differs from the app's (an app launched with its own home folder, as in some test setups) runs that home's script.
  • Other agents still have the opt-out hazard: turning hooks off in one instance removes their shared entries that other instances rely on. That is a separate change.
  • An opt-out that cannot read or parse ~/.codex/hooks.json leaves the entry and its approvals in place until the next opt-out, as before.

This PR changes no SSH code path; the remote installer is unchanged. WSL panes keep their existing app request. Folder workspaces behave like git worktrees here.

Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

… changed it

Orca writes ~/.codex/hooks.json (and a trust rebase writes config.toml), then
runs a Codex trust session for up to 10 s, then restores the original bytes if
the session fails. The restore wrote unconditionally, so a save that landed
during the session, from the user or another Orca, was silently reverted.

Each restore now compares first: it writes the original back only while the
file still holds the generation Orca's mutation left, and otherwise logs and
leaves it alone. This covers the real-home install and opt-out sweep
(restoreRealHomeHooksJson), the legacy sweep's hooks restore, and config.toml
rollback (restoreCodexTrustConfig).

For hooks.json the generation is the exact bytes Orca wrote. For a config.toml
that a trust rebase changed it is the file as the rebase left it. When Codex
itself wrote config.toml inside the session that just failed, Orca never knew
those bytes, so that rollback compares against the file as the session settled.
The next commit keeps other Orca instances out of that window; a user edit made
during such a session can still be rolled back.
Every Orca on one HOME (a dev and a packaged app, or an offline CLI) writes the
same ~/.codex/hooks.json, config.toml and ~/.orca/agent-hooks/codex-hook.sh.
The per-file lane that orders capture, mutate and restore was in-process only,
so another instance could write inside this one's restore window, or undo it.

The lane for the user's real config.toml now also holds the existing
crash-safe managed-hook install lock (~/.orca/managed-hook-install.lock, the
one relay installers take for the same home). It is taken only by the
outermost acquire, because the lock file is not reentrant and grants and trust
rebases nest inside an install. Managed-home installs, the real-home install
and opt-out sweep, and the legacy sweep all enter through it. Compare-and-swap
on restore stays as the backstop.

A lock that cannot be taken within its 10 s wait fails that install, which is
already best effort: launch prep logs it, and the real-home lane falls back to
the managed lane until its retry.
…y from ~/.codex

Every Orca instance on one HOME writes the same status-hook entry into the
user's ~/.codex/hooks.json, with its trust in config.toml. Launch prep runs on
every pane spawn, and under a managed Codex account it ran the legacy system
sweep. That sweep matched Orca entries by script file name, so it removed the
current shared entry and the trust blocks the grant ledger recorded. On a live
laptop hooks.json went 4139 -> 18 bytes about 150 ms before a new pane opened.
With hooks off, the real-home lane's launch prep swept the same way.

Now nothing automatic removes the current entry or its trust:
- The legacy sweep removes only an enumerated list of retired command forms
  that no build writes any more (#1019's double-quoted form, #1536's
  exec-guarded form, and Windows' per-userData bare path), plus their trust.
- ensureRealHomeCodexHookState with hooks off writes nothing; that covers
  launch prep, session resume and startup.
- Only the user's explicit opt-out (codexHookService.remove()) strips the entry
  and its ledger-recorded trust from the real home.
- The sweep-suppression gate existed only to stop the sweep from deleting the
  current entry, so it is deleted with its main-process wiring.

Startup with hooks off already skipped the real-home install; with this change
the first pane's launch prep with hooks off also leaves ~/.codex untouched.
… app installed

On macOS a pane starts through login(1), so it gets the user's real HOME even
when its Orca app runs with another one. The pane's `codex()` preflight
installed hooks in the CLI process with that real HOME: it rewrote
~/.orca/agent-hooks/codex-hook.sh, promoted trust into the real config.toml,
and wrote the real HOME's script path into the app's managed home.

The preflight now acts only when the managed home's hooks already run this
process's own shared script, which proves the app that installed them shares
its HOME. Otherwise it writes nothing; the app installed the home at spawn.

Why not a no-op: the preflight was added (#14326) because trust can go stale
between opening a pane and typing `codex`, for example in a pane that survives
an app update, and Codex then stops in hook review. For a same-HOME pane it
still repairs that. Why keep promotion: the install drops runtime trust the
system config does not back, so skipping promotion would delete approvals the
user gave inside Orca-launched Codex.
The test fired each managed installer without awaiting it and read
~/.orca/agent-hooks straight after. Codex's install now takes the
cross-process real-home lock before it writes its script, so the script
landed after the read. Await the installers, and stub Codex's trust sessions
so the awaited install cannot start a real `codex app-server`.
The real-home lane wrote two Codex hook forms into ~/.codex that no build
writes any more and that the enumerated retired list did not name:
- POSIX, #9501 until #10885: the file-guarded form draining with a bare `cat`.
- Windows, #9501 until #10221 took Windows off the real-home lane: the encoded
  PowerShell launcher for a non-cmd-safe script path.

The file-name sweep removed both before; the enumerated sweep left them in
place, trusted, still passing the script's exit status to Codex. Both now
match as frozen literals.

Also corrects the startup ordering comment: the real-home install runs first
so its in-slot upgrade lands before the managed install's sweep retires the
prior command; nothing re-arms a legacy sweep any more.
The previous commit made every entry to the real-home config lane take the
cross-process lock. That lane runs on every pane spawn and every typed
`codex` preflight, so the steady state paid an owner probe (a `ps` spawn on
macOS) and could wait up to 10 s behind another instance's trust session,
even though it wrote nothing.

Each real-home writer now compares the desired state with the files on disk
first, without the lock. Only when a write is needed does it take the lock,
re-read and recheck, then write:
- real-home install: the planned hooks.json, the shared script and the
  ledger-recorded grant are compared; the locked path re-plans from disk.
- legacy sweep: locks only when a retired entry is present; the sweep re-reads.
- approval promotion: locks only when there is something to promote; the
  promotions are recomputed under the lock.
- the shared ~/.orca/agent-hooks script: locks only when its bytes differ.
The explicit opt-out always takes the lock. The lock is reentrant through
async context, since grants and rebases nest inside an install, so the
config-lane option the previous commit added is removed.
The compare-first check matched the shared ~/.orca/agent-hooks script on bytes
alone. writeManagedScript also restores 0755 on every call, and the POSIX hook
guard skips a script that is not executable, so a script whose mode was lost
(a dotfiles restore, a plain copy) now stayed that way: every Codex hook
drained stdin and reported nothing until an app restart refreshed the script.

The check now also requires the mode the writer sets, so that case takes the
lock and the write path repairs it.
…d one

The shared encoded Windows launcher is still current for other agents, so the
comment claiming today's launcher is never encoded was wrong. What keeps the
retired matcher off it is the exact payload: since #14825 the shared launcher
prefixes its payload and drops -ExecutionPolicy Bypass. Pin that with a case.
… with an apostrophe

The same-HOME check looked for the script path wrapped in bare single quotes,
but both hook writers escape an apostrophe inside the quotes. A home such as
C:\Users\O'Brien never matched, so the pane-step repair never ran there.
…its lane

The no-write check reported a recorded grant as current, so with
ORCA_DISABLE_CODEX_TRUST_RPC set the real-home lane stayed in use. The grant
itself refuses before reading its ledger; the check now does the same.
…lock

The write is atomic and skips identical bytes; waiting behind another
instance's trust session could only fail a pane's managed-home install.
… real-home lock

The install drops runtime trust the system config does not back, so a
promotion skipped for want of the lock lost the approval for good. It
now writes unlocked, as it did before the lock existed.
The lock fixed no observed failure. The three that were observed each have
their own fix in this series: the legacy sweep matches only frozen retired
command forms, hooks-off launch prep writes nothing, and a pane's
prepare-codex repairs only a home its own HOME's app installed. The lock
instead brought its own defects: a steady-state spawn waiting behind another
instance's trust session, a compare-first split to avoid that, a script
write and an approval promotion that could fail for want of the lock.

Removed, with their tests: the real-home write lock and its async-context
reentrancy, the plan/compare split that kept it off steady-state spawns, the
compare-first legacy sweep, the locked approval promotion and its unlocked
fallback, the compare-first shared script write (writeManagedScript already
skips identical bytes and restores the exec bit), and the CLI tsconfig
entries the lock pulled in.

Kept: the retired-forms matcher, the hooks-off no-op, removal only on an
explicit opt-out, the pane own-script check, and the compare-and-swap
rollbacks. Every instance now writes identical bytes idempotently.
… and ledger

The opt-out swept the real-home entry, then dropped Orca's ledger-proven trust
whenever a ledger existed, even when the sweep could not read hooks.json. The
entry could still be there, now untrusted, and the ledger that proves ownership
was gone for the retry. Drop that trust only after a sweep that read the file.
@brennanb2025

brennanb2025 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Status

Problem this fixes: opening a terminal in Orca could wipe Orca's Codex status hook from the real ~/.codex, together with the approvals of the user's own hooks. Codex then asks to re-approve them, or status stops updating. The PR body lists the two machines where it happened.

User-facing change: every Orca version writes the same hook entry. Only the main app writes it, and only to add it when it is missing. A failed Codex approval undoes only what that attempt added, so edits made at the same time and earlier approvals survive.

Head: a2c2c01f79a. Review loops are done: six rounds, plus an architecture review after the third. After that came a confirmation review of today's main merges and the one test added since; it found nothing. Typecheck is clean for node and CLI. Live QA ran on macOS and Windows at 3c64322b834, and on Linux at e8c59f79c25. a2c2c01f79a adds only a test and a merge of main on top of e8c59f79c25.

Since the last review round

What changed in the round before that

  • Design. The approval tracking is now one approval at a time, decided under the config.toml lock when it runs. The status label, the queue of approvals and the version stamp are gone. The files Orca writes are unchanged.
  • Launch. A launch never waits for Codex's approval of ~/.codex.
  • Resume. A resume into ~/.codex waits at most 30 seconds, on the one running approval, and never starts in front of Codex's hook review.
  • Repeated timeouts. After three timeouts in a row, Orca waits longer between tries: 10 seconds, 1 minute, then 5 minutes. The count resets on success and at app start.
  • Windows command.
    • A profile path the shells can carry as-is keeps the plain script path.
    • Any other path uses Windows' own cmd.exe by full path, with backslashes, /d and /v:off.
    • The encoded launcher is gone.
  • Windows CI. The Windows-only managed-install tests now run in the Windows CI job; nothing ran them before.

Live QA

BEFORE is origin/main at the time of each lane: 31012aeb092 for macOS and Windows, and f33f3093cbe for Linux. AFTER is this change. Each lane used a background-launched build with its own home and Codex home.

  • macOS. Real Codex, signed in and used in place.
    • The user's real ~/.codex and ~/.claude were unchanged at all 13 checks.
    • Failed approval: BEFORE lost both concurrent edits and unapproved 7 of Orca's entries. AFTER kept both edits and left the 7 approved; it withdrew only the entry that approval added.
    • Launch during an approval: BEFORE blocked for 10.65 s. AFTER settled in 15–24 ms on Orca's managed home.
    • Resume: approved at 20.1 s. With the approval held, the entry was withdrawn at 30.0 s. It was never put up for review.
    • Three resumes at once shared one approval.
    • The one-time conversion wrote the file once and made one backup, and left user hooks byte-identical.
    • The live Orca received nothing from the test app.
  • Windows. The box's real files were unchanged at all 75 checks.
    • Both command shapes ran live under PowerShell 7, Windows PowerShell 5.1 and cmd.exe: 9 of 9, including the profile path a b#,;=@[c.
    • Every older Orca form converted once.
    • A cmd.bat first on PATH did not run in place of the hook.
    • Restored panes (5 and 9) shared one approval.
    • A real codex exec turn reported working, then done, 10 of 10.
  • Linux (Ubuntu, headless under Xvfb, Codex CLI 0.154.0).
    • The box's real ~/.codex and ~/.claude were unchanged at all 4 checks.
    • The hook command has no path in it and is byte-identical to macOS's.
    • Failed approval: BEFORE lost both concurrent edits and all 8 of Orca's entries. AFTER kept both edits and moved the concurrent hook's approval with it. The 7 approved entries stayed approved; it withdrew only the entry that approval added and re-added it, approved, on the next launch.
    • Opening terminals with a managed Codex account left the entry byte-identical (BEFORE: stripped to 184 bytes).
    • Launch during an approval: BEFORE blocked for 10.05 s, then removed all 8. AFTER settled in 17–49 ms.
    • Resume: approved at 20.18 s. With the approval held, the entry was withdrawn at 30.05 s. It was never put up for review.
    • Three resumes at once shared one approval.
    • The one-time conversion wrote once and made one backup; hooks off, the opt-out and two app instances on one home all behaved as on macOS.
    • The SSH relay's hook install is byte-identical between BEFORE and AFTER. No other Orca on the box received anything.
  • Hook delivery, end to end on macOS. The exact command bytes from the hooks file were run with a terminal's hook settings. They moved that terminal to working, then done. Run without those settings, the same bytes read their input, exited 0 and delivered nothing.

The frozen hook command moves a terminal from working to done:

Hook delivery on macOS: after UserPromptSubmit, the terminal reads working (spinner on the tab and the sidebar row, with the prompt)
Hook delivery on macOS: after Stop, the tab reads Codex ready with a bell and the sidebar row has a green check

On Windows, one turn under each of Codex's three hook hosts:

Windows, Codex hooks under cmd.exe: the turn is working (spinner on the tab and the sidebar row)
Windows, Codex hooks under cmd.exe: the turn is done (bell on the tab, green check on the sidebar row)
Windows, Codex hooks under PowerShell 7: the turn is done (green check on the sidebar row)
Windows, Codex hooks under Windows PowerShell 5.1: the turn is done (green check on the sidebar row)

On Linux, the same hook command run with a terminal's hook settings: after Stop, the tab reads Codex ready with a bell.

Hook delivery on Linux: after Stop, the tab reads Codex ready with a bell

Not covered, or found along the way

  • Linux, a real Codex turn: blocked. The box has no Codex login in the test home, and copying credentials is not allowed. The hook command itself was delivered, as shown above.
  • Linux, restored panes: simulated with three resumes at once, not with the app's own restore.
  • Linux, a replayed UserPromptSubmit: it shows no working spinner in the test pane; Stop does show Codex ready. BEFORE behaves the same, so this change doesn't cause it. It was not investigated.
  • Follow-up for fix(codex): recognise Codex's quoted spellings in config.toml, and repair Orca's duplicates (#22592) #23958, not this change: Orca reads a hook approval only when its field names are unquoted (trusted_hash = …). Codex's own writer never quotes them, but the file fix(codex): recognise Codex's quoted spellings in config.toml, and repair Orca's duplicates (#22592) #23958 was built for came from a writer that quoted "trust_level", and it's not verified whether that writer also quotes these fields.
  • Structured Codex chat through the hook: by design, a structured chat reports status through Codex's app server, not the hook.
  • Found along the way, not changed here: turning agent status hooks on at runtime, after the app started with them off, left newly opened terminals without hook settings on this change's build. It is already on main: main skips starting the hook server when hooks are off at app start (main-process-pty-startup.ts), and turning hooks on later only resumes WSL relays (main-process-ready-foundation.ts), so nothing starts the server that gives terminals their hook settings. This change does not touch either. Filed as a follow-up.

@brennanb2025
brennanb2025 marked this pull request as ready for review September 28, 2026 08:14

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes — the full 15-commit diff against main, the reentrancy/lock ordering of the new opt-out path, the cross-platform command matching, and the changed test suites.

  • Retired-form matcher — new isRetiredCodexHookCommand replaces the filename-based matcher in the legacy sweep, so it removes only enumerated historical command forms and never the shared current entry.
  • Hooks-off no-op — runRealHomeCodexHookEnsure returns 'removed' without touching disk; removal now lives only in the explicit removeRealHomeCodexHookForOptOut() used by the opt-out path.
  • Gate deleted — setSystemCodexHomeHookSweepSuppressed and its wiring are gone, which is safe once the sweep cannot match a live entry.
  • Guarded rollbacks — restoreRealHomeHooksJson / restoreCodexTrustConfig write the snapshot back only while the file still holds Orca's generation.
  • Pane home check — managedHomeRunsOwnScript gates prepare-codex repair on the managed home referencing this process's own script, closing the login(1) wrong-home write.

I verified tc:node and tc:cli, ran the new/changed suites (retired commands, restore guard, shared entry, rollback, preflight, legacy cleanup, rebase, CLI isolated-home) — all pass — and confirmed CI is green. runExclusivelyForCodexTrustConfig is reentrant via AsyncLocalStorage, so the new opt-out acquire nested inside remove()'s runtime→system lock does not deadlock. The Windows managed command (getManagedCommand returns a bare path or the plain buildWindowsHookPowerShellCommand, never the encoded launcher) is matched by the preflight's quotePowerShellLiteral check, and the current POSIX/Windows forms are negative in the retired matcher.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The changes add versioned Codex hook commands and retired-command cleanup. Real-home hook installation now uses explicit write policies and background trust approval, with retry handling and withdrawal of untrusted writes. Trust entries can move when user hooks change position. Startup and resume paths use the updated real-home hook flow. The pane CLI no longer prepares managed homes on native platforms, and shell preflight is limited to eligible packaged Windows WSL launches.

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to a2c2c

Resuming a Codex session into ~/.codex can wait longer than the promised 30 seconds when many terminals restore at once. This delays the start but does not lose data. The PR is mergeable with this follow-up or a bounded wait.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to a2c2c

The change reduces accidental shared-home rewrites and restricts delegated preparation to validated local paths. However, hook changes and approval-state moves can complete separately: a failed move can leave user hooks out of sync with their stored approvals or enablement settings.

Retained concerns

  • Medium · reliability · observed: Trust-slot migration has no recoverable failure state. The hook file is committed before approval blocks move, and relocation errors are logged without failing the operation or restoring the prior layout. Compared with the base's attempted rollback on repair failure, a handled configuration-write failure now leaves approval and enablement records at their old positions. Content-bound hashes constrain unrelated authorization, but the migration no longer guarantees preservation of user-hook control state.
Security review details

Security Blast Radius

  • inferred — The persistent-state impact extends to Codex processes and Orca versions sharing the affected operating-system user's real home. The inspected delegation path does not establish authority over arbitrary remote clients or unrelated homes.

Security Findings and Attack Paths

  • inferred — The supported introduced concern is approval-state inconsistency after a partial migration, not a verified arbitrary-command execution path. Approval sessions select exact managed commands and expected keys; trusted hashes bind hook content, constraining inheritance by a different command at a reused position.

Trust Boundaries and Controls

  • observed — WSL environment inputs cross into runtime-owned preparation only after local-client checks, matching home values, safe path and distribution validation, managed-home resolution, and realpath equality. Native CLI invocation returns without performing preparation writes.

Resilience and Maintainability Implications

  • observed — Best-effort trust cleanup after command removal already existed in the base. Head adds another cleanup attempt when an ownership ledger remains, and the cleanup implementation retains that ledger until trust removal succeeds. A caught no-ledger cleanup failure is therefore a pre-existing limitation, not independently established as worsened by this PR.

Hardening Proposals

  • proposed — Make failed trust relocation an explicit recoverable state, with an identity- and generation-checked record of pending moves and idempotent recovery. Preserve concurrent user edits and disabled settings, and do not synthesize approvals when recovery cannot establish ownership.
🚥 Pre-merge checks | ✅ 4 | ❓ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ❓ Inconclusive Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 159 functions across 59 files. (17 skippe… 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 and concisely describes the primary fix: preventing terminal opening from removing Codex hooks in the real home.
Description check ✅ Passed The description is detailed and covers the required change summary, rationale, testing, visual proof, scope, risks, and checklist. The Linked Issue section does not provide an actual issue link, despi…
Full details: Docstring Coverage

Explanation

Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 159 functions across 59 files. (17 skipped: 3 unsupported, 14 over the file limit.)

✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR

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: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: dd236018-ac38-451d-ba2b-2f7da962362a

📥 Commits

Reviewing files that changed from the base of the PR and between fae0ae7 and f351c5f.

📒 Files selected for processing (23)
  • config/tsconfig.cli.json
  • src/cli/handlers/agent-hooks-prepare-codex-isolated-home.test.ts
  • src/main/agent-hooks/posix-hook-command.ts
  • src/main/codex/codex-hook-legacy-cleanup.ts
  • src/main/codex/codex-hook-local-maintenance.ts
  • src/main/codex/codex-hook-retired-commands.test.ts
  • src/main/codex/codex-hook-retired-commands.ts
  • src/main/codex/codex-hook-trust-grant.ts
  • src/main/codex/codex-real-home-hook-install.test.ts
  • src/main/codex/codex-real-home-hook-install.ts
  • src/main/codex/codex-real-home-hooks-json.ts
  • src/main/codex/codex-real-home-restore-guard.test.ts
  • src/main/codex/codex-real-home-shared-entry.test.ts
  • src/main/codex/codex-trust-config-rollback.test.ts
  • src/main/codex/codex-trust-config-rollback.ts
  • src/main/codex/codex-user-hook-trust-rebase.ts
  • src/main/codex/hook-service-legacy-cleanup.test.ts
  • src/main/codex/hook-service-trust-grant.test.ts
  • src/main/codex/hook-service.ts
  • src/main/codex/managed-home-shell-preflight.test.ts
  • src/main/codex/managed-home-shell-preflight.ts
  • src/main/startup/main-process-account-services.ts
  • src/main/startup/main-process-ready-runtime.ts
💤 Files with no reviewable changes (2)
  • src/main/startup/main-process-account-services.ts
  • src/main/codex/hook-service.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment on lines +138 to +143
// Why current bytes: Codex, not Orca, wrote config.toml in the session that just
// settled, so there is no Orca generation to compare; the restore follows at once.
function restoreAfterSession(tomlPath: string, snapshot: CodexTrustConfigSnapshot): void {
restoreCodexTrustConfig(tomlPath, snapshot, readCodexTrustConfigGeneration(tomlPath, snapshot))
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Preserve the generation written by the grant operation before awaiting the session.

restoreAfterSession reads the current generation only after the Codex session settles. If a user saves the config before that read, the wrapper can treat the user’s generation as the grant’s written generation. restoreCodexTrustConfig can then restore the older snapshot over the user’s save.

Capture the generation immediately after the grant writes the config, and pass that captured value to restoreAfterSession. Apply the same operation-completion capture independently in the trust-rebase failure wrapper. Changing only restoreCodexTrustConfig cannot identify which operation produced the supplied generation.

Comment on lines 118 to 123
rollbackErrors.push(error)
}
try {
restoreCodexTrustConfig(tomlPath, snapshot)
// Why current bytes: Codex wrote them in the session that just failed.
restoreCodexTrustConfig(tomlPath, snapshot, readCodexTrustConfigGeneration(tomlPath, snapshot))
} catch (error) {

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- rebase source ---'
sed -n '1,270p' src/main/codex/codex-user-hook-trust-rebase.ts
printf '%s\n' '--- client source ---'
sed -n '90,220p' src/main/codex/codex-user-hook-trust-rebase-client.ts
printf '%s\n' '--- rollback helper ---'
sed -n '1,180p' src/main/codex/codex-trust-config-rollback.ts
printf '%s\n' '--- queue ---'
sed -n '1,100p' src/main/codex/codex-trust-config-mutation-queue.ts
printf '%s\n' '--- focused tests ---'
sed -n '200,310p' src/main/codex/codex-user-hook-trust-rebase.test.ts
printf '%s\n' '--- relevant callers ---'
rg -n -C 3 'mutateRealHomeHooksPreservingUserTrust|rollbackMutation|CodexUserHookTrustRebaseRollback|runCodexUserHookTrustRebase|rebase' src/main/codex src/main | head -240
printf '%s\n' '--- diff for implicated files ---'
git diff --unified=20 47b8408e289926cfe4e7ae40eefce29aaa2b32d1 f351c5f148aa090d60562e749d4ec8f904a1d1c8 -- src/main/codex/codex-user-hook-trust-rebase.ts src/main/codex/codex-user-hook-trust-rebase-client.ts src/main/codex/codex-trust-config-rollback.ts src/main/codex/codex-user-hook-trust-rebase.test.ts

Repository: stablyai/orca

Length of output: 42564


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- rebase client declarations ---'
sed -n '1,120p' src/main/codex/codex-user-hook-trust-rebase-client.ts
printf '%s\n' '--- real-home installer rollback flow ---'
sed -n '150,245p' src/main/codex/codex-real-home-hook-install.ts
printf '%s\n' '--- alternate real-home caller ---'
sed -n '260,315p' src/main/codex/codex-real-home-hook-install.ts

Repository: stablyai/orca

Length of output: 10290


Carry the generation captured by config/batchWrite into failure rollback.

If config/batchWrite succeeds, verification fails, and a user saves config.toml before rollback reads it, rollbackMutation treats the user’s save as the rebase generation. restoreCodexTrustConfig can then replace that save with the older snapshot.

Capture the generation immediately after config/batchWrite and propagate it through verification errors. Do not read the current file after the failure. The existing written value is captured only after verification succeeds.

Comment on lines +84 to +105
/**
* True when the managed home's hooks run this process's own shared script,
* which proves the app that installed them shares this process's HOME.
*/
function managedHomeRunsOwnScript(runtimeHomePath: string): boolean {
const scriptPath = getManagedScriptPath()
// Why the writers' own quoting: an apostrophe in the home path is escaped in the command.
const quotedPaths = [quotePosixShellString(scriptPath), quotePowerShellLiteral(scriptPath)]
const hooks = readHooksJson(getConfigPath(runtimeHomePath))?.hooks ?? {}
return Object.values(hooks).some(
(definitions) =>
Array.isArray(definitions) &&
definitions.some((definition) =>
(definition.hooks ?? []).some(
(hook) =>
hook.command === scriptPath ||
quotedPaths.some((quoted) => hook.command?.includes(quoted))
)
)
)
}

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '66,100p' src/main/codex/codex-hook-definition.ts
sed -n '80,110p' src/main/codex/managed-home-shell-preflight.ts
sed -n '35,105p' src/main/codex/managed-home-shell-preflight.test.ts

Repository: stablyai/orca

Length of output: 5015


🏁 Script executed:

set -e
printf '%s\n' '--- command builders and imports ---'
rg -n -C 5 'wrapPosixHookCommand|quotePosixShellString|quotePowerShellLiteral|buildWindowsHookPowerShellCommand|getManagedCommand|getManagedScriptPath' src/main/codex
printf '%s\n' '--- preflight call path ---'
sed -n '1,145p' src/main/codex/managed-home-shell-preflight.ts
printf '%s\n' '--- relevant tests ---'
rg -n -C 8 'managedHomeRunsOwnScript|quoted|inert|another HOME|own script|getManagedCommand|hooks run' src/main/codex '*.test.ts' 2>/dev/null || true
printf '%s\n' '--- PR diff summary and targeted diff ---'
git diff --stat 47b8408e289926cfe4e7ae40eefce29aaa2b32d1 f351c5f148aa090d60562e749d4ec8f904a1d1c8
git diff --unified=35 47b8408e289926cfe4e7ae40eefce29aaa2b32d1 f351c5f148aa090d60562e749d4ec8f904a1d1c8 -- src/main/codex/managed-home-shell-preflight.ts src/main/codex/codex-hook-definition.ts

Repository: stablyai/orca

Length of output: 41983


🏁 Script executed:

set -e
printf '%s\n' '--- canonical command producer ---'
sed -n '1,105p' src/main/codex/codex-hook-definition.ts
printf '%s\n' '--- POSIX command wrapper ---'
sed -n '1,180p' src/main/agent-hooks/posix-hook-command.ts
printf '%s\n' '--- Windows command builder ---'
rg -n -C 12 'function buildWindowsHookPowerShellCommand|export .*buildWindowsHookPowerShellCommand|WINDOWS_CMD_SAFE_PATH|function wrapPosixHookCommand|export .*wrapPosixHookCommand' src/main/agent-hooks src/shared
printf '%s\n' '--- quote helper ---'
rg -n -C 8 'export .*quotePowerShellLiteral|function quotePowerShellLiteral' src/shared
printf '%s\n' '--- preflight imports and tests after the supplied excerpt ---'
sed -n '1,28p' src/main/codex/managed-home-shell-preflight.ts
sed -n '45,180p' src/main/codex/managed-home-shell-preflight.test.ts

Repository: stablyai/orca

Length of output: 37169


Match the complete managed command, not a quoted substring.

getManagedCommand(scriptPath) returns a complete wrapper on POSIX and for quoted Windows paths. The current substring check also accepts inert commands that only mention the quoted script path. This can trigger an unintended persisted hooks update.

Do not use quotedPaths.includes(hook.command ?? ''); that would reject the complete POSIX and PowerShell commands. Match scriptPath and getManagedCommand(scriptPath) exactly.

Suggested fix
-import { quotePowerShellLiteral } from '../../shared/powershell-native-argument'
 import { readHooksJson } from '../agent-hooks/installer-utils'
-import { quotePosixShellString } from '../agent-hooks/posix-hook-command'
-import { getConfigPath, getManagedScriptPath } from './codex-hook-definition'
+import { getConfigPath, getManagedCommand, getManagedScriptPath } from './codex-hook-definition'

...

   const scriptPath = getManagedScriptPath()
-  // Why the writers' own quoting: an apostrophe in the home path is escaped in the command.
-  const quotedPaths = [quotePosixShellString(scriptPath), quotePowerShellLiteral(scriptPath)]
+  const managedCommands = new Set([scriptPath, getManagedCommand(scriptPath)])
   const hooks = readHooksJson(getConfigPath(runtimeHomePath))?.hooks ?? {}
   return Object.values(hooks).some(
     (definitions) =>
       Array.isArray(definitions) &&
       definitions.some((definition) =>
         (definition.hooks ?? []).some(
-          (hook) =>
-            hook.command === scriptPath ||
-            quotedPaths.some((quoted) => hook.command?.includes(quoted))
+          (hook) => managedCommands.has(hook.command ?? '')
         )
       )
   )

…oks are on

"Global switch on and this agent not turned off" was spelled out separately
in the startup controls, the settings reconcile, the retained-home
reconcile, the WSL preflight RPC, the CLI preflight and the OpenCode plugin
selection. They now share one function, in a module light enough for the
CLI's per-launch Codex preflight to load. The PTY spawn env derives the
Codex flag from the switch and opt-out list it already carries, the same way
it does for OpenCode and Pi, instead of receiving a second copy.
Turning Codex off in the per-agent hook settings removes Orca's Codex hook
entry, but launch prep and session resume read only the global hooks switch,
so the next Codex launch or resume wrote the entry straight back into the
real ~/.codex or the account's home. Both now read the per-agent predicate,
which the PTY spawn env and startup already honoured.
While the real-home lane owns ~/.codex/hooks.json, the legacy system-home
sweep stands down. That gate read only the global switch, so turning Codex
off per agent ran remove() with the sweep still suppressed and left Orca's
entry in the real ~/.codex. The gate now reads the per-agent predicate, the
same as turning every hook off.
The gate that lets the legacy system-home sweep run was an inline closure in
startup, so reverting it to the global switch left CI green. It is now a
pure function beside the gate it feeds, with a table test and a remove()
test on a seeded ~/.codex: turning Codex off strips Orca's entry and keeps
user hooks; with Codex on the entry stays.
…r-agent-optout-launch

# Conflicts:
#	src/main/agent-hooks/managed-agent-hook-controls.ts
@brennanb2025
brennanb2025 changed the base branch from main to brennanb2025/codex-per-agent-optout-launch September 28, 2026 19:22
Kept #23724's daemon socket guard on resume beside the real-home wait; took
#23815's deletion of the main-thread boundary source test and its rewrite of the
trust parity test, whose export-list check this branch had edited.
@brennanb2025
brennanb2025 changed the base branch from brennanb2025/codex-per-agent-optout-launch to main September 29, 2026 18:30
#23667 landed as a squash of the branch this PR was built on, identical in
content (22 files, +403/-73). Merged with #23667's branch tip as the base, so
only main's other changes since then come in and nothing of #23667 is
duplicated or reverted.
…ng helper

Now that they run in the Windows lane, a raw recursive rm there can throw EPERM
after the assertions pass.
…3789, #23812, #23852) into brennanb2025/codex-home-single-writer

#23744 moves every agent's folder pre-trust into the PTY spawn hook (and
the structured Codex chat create), removing Codex's launch-prep and
resume-prep trust writes. markCodexProjectTrusted now takes the config
files to write.

Conflicts:
- agent-trust-presets.ts: #23744's configFiles signature and nested lane
  acquisition, with this branch's lane rationale (hook installs read and
  rewrite across awaits); main's "capture->restore window" wording
  described the grant snapshot this branch removed.
- agent-trust-write-deadline.ts: the Codex writer waits only on
  managed-home installs' inline grant; the real-home background approval
  holds no lane. #23744's SSH/SFTP writer is gone, so it is no longer
  named; its 1.5 s short deadline is kept.
- codex-trust-config-concurrent-launch.test.ts: this branch's tests
  (a launch's write lands while a grant session runs; the renamed
  sibling-failure case) with #23744's new call signature.

Outside the conflicts: codex-launch-during-real-home-grant.test.ts passed
launchAgent/workspacePath into launch prep, which #23744 removed; its
launch helper now runs launch prep and then applyAgentWorkspaceTrust, as
the spawn builder does, so it still proves a launch and its project trust
land while the real-home approval hangs.
agent-trust-presets.ts: #23937 trusts the folder Codex starts in (canonicalize,
no guessed repo root); kept, with this branch's lane comment, since no hook
install has a capture->restore window any more.
@brennanb2025
brennanb2025 marked this pull request as ready for review September 30, 2026 08:15

@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: Advanced

Run ID: b340d35d-a3c7-46e3-8c9a-ed189834cb41

📥 Commits

Reviewing files that changed from the base of the PR and between f351c5f and a2c2c01.

📒 Files selected for processing (78)
  • .github/workflows/pr.yml
  • config/build-plugins/plain-node-entry-guard.ts
  • config/scripts/ci-shard-timings.json
  • config/scripts/pr-code-change-scope.mjs
  • config/tsconfig.cli.json
  • src/cli/handlers/agent-hooks-load-boundary.test.ts
  • src/cli/handlers/agent-hooks-prepare-codex-isolated-home.test.ts
  • src/cli/handlers/agent-hooks.test.ts
  • src/cli/handlers/agent-hooks.ts
  • src/cli/runtime-client-deferral.test.ts
  • src/cli/specs/agent-hooks.ts
  • src/main/agent-hooks/managed-agent-hook-controls.ts
  • src/main/agent-hooks/managed-hook-command-contract.test.ts
  • src/main/agent-trust-presets.ts
  • src/main/agent-trust-write-deadline.ts
  • src/main/codex/codex-hook-command-form.test.ts
  • src/main/codex/codex-hook-command-form.ts
  • src/main/codex/codex-hook-definition.ts
  • src/main/codex/codex-hook-legacy-cleanup.ts
  • src/main/codex/codex-hook-local-install.ts
  • src/main/codex/codex-hook-retired-commands.test.ts
  • src/main/codex/codex-hook-retired-commands.ts
  • src/main/codex/codex-hook-sweep-per-agent-opt-out.test.ts
  • src/main/codex/codex-hook-trust-grant.test.ts
  • src/main/codex/codex-hook-trust-grant.ts
  • src/main/codex/codex-hook-trust-queue.ts
  • src/main/codex/codex-hook-wsl-runtime.ts
  • src/main/codex/codex-managed-trust-grant-plan.ts
  • src/main/codex/codex-real-home-background-grant.ts
  • src/main/codex/codex-real-home-entry-trust.test.ts
  • src/main/codex/codex-real-home-entry-trust.ts
  • src/main/codex/codex-real-home-failed-grant-concurrent-edit.test.ts
  • src/main/codex/codex-real-home-frozen-entry.test.ts
  • src/main/codex/codex-real-home-hook-entry-plan.ts
  • src/main/codex/codex-real-home-hook-install.test.ts
  • src/main/codex/codex-real-home-hook-install.ts
  • src/main/codex/codex-real-home-hook-sweep.ts
  • src/main/codex/codex-real-home-hook-withdrawal.ts
  • src/main/codex/codex-real-home-hooks-json.ts
  • src/main/codex/codex-real-home-shared-entry.test.ts
  • src/main/codex/codex-real-home-slow-app-server.test.ts
  • src/main/codex/codex-real-home-trust-withdrawal.test.ts
  • src/main/codex/codex-real-home-user-hook-positions.test.ts
  • src/main/codex/codex-trust-config-concurrent-launch.test.ts
  • src/main/codex/codex-trust-config-mutation-queue.ts
  • src/main/codex/codex-trust-config-rollback.test.ts
  • src/main/codex/codex-trust-config-rollback.ts
  • src/main/codex/codex-trust-grant-cooldown.ts
  • src/main/codex/codex-trust-grant-host.ts
  • src/main/codex/codex-trust-grant-ledger.ts
  • src/main/codex/codex-user-hook-trust-moves.test.ts
  • src/main/codex/codex-user-hook-trust-moves.ts
  • src/main/codex/codex-user-hook-trust-rebase-client.test.ts
  • src/main/codex/codex-user-hook-trust-rebase-client.ts
  • src/main/codex/codex-user-hook-trust-rebase.test.ts
  • src/main/codex/codex-user-hook-trust-rebase.ts
  • src/main/codex/config-toml-hook-trust-edit.ts
  • src/main/codex/config-toml-runtime-owned-sections.ts
  • src/main/codex/config-toml-syntax.ts
  • src/main/codex/config-toml-trust.ts
  • src/main/codex/hook-service-managed-install.test.ts
  • src/main/codex/hook-service-test-harness.ts
  • src/main/codex/hook-service-trust-grant.test.ts
  • src/main/codex/managed-home-shell-preflight.test.ts
  • src/main/codex/managed-home-shell-preflight.ts
  • src/main/codex/windows-hook-command.test.ts
  • src/main/ipc/pty-spawn-env-terminal-basics.test.ts
  • src/main/ipc/pty/host-env/assembly.ts
  • src/main/pty/codex-preflight-profile-path-rewrite.test.ts
  • src/main/pty/codex-shell-launch-preflight.test.ts
  • src/main/pty/codex-shell-launch-preflight.ts
  • src/main/startup/codex-launch-during-real-home-grant.test.ts
  • src/main/startup/codex-launch-per-agent-hook-opt-out.test.ts
  • src/main/startup/codex-launch-preparation.ts
  • src/main/startup/codex-session-resume-launch.ts
  • src/main/startup/main-process-account-services.ts
  • src/main/startup/main-process-ready-runtime.ts
  • src/shared/capability-probe-cache.ts
💤 Files with no reviewable changes (11)
  • config/build-plugins/plain-node-entry-guard.ts
  • src/main/codex/codex-user-hook-trust-rebase.test.ts
  • src/main/codex/codex-trust-config-rollback.test.ts
  • src/main/codex/codex-user-hook-trust-rebase-client.test.ts
  • src/main/agent-hooks/managed-agent-hook-controls.ts
  • src/main/codex/managed-home-shell-preflight.ts
  • src/main/codex/managed-home-shell-preflight.test.ts
  • src/main/ipc/pty/host-env/assembly.ts
  • src/main/codex/codex-trust-config-rollback.ts
  • src/main/codex/codex-user-hook-trust-rebase.ts
  • src/main/codex/codex-user-hook-trust-rebase-client.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

Comment on lines +137 to +142
export async function awaitRealHomeCodexHookTrust(): Promise<void> {
const current = approval
if (current && hasUnapprovedRealHomeOrcaEntry(current.command)) {
await current.done
}
}

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Put an explicit limit on the resume wait. The 30 s session timeout alone does not limit it.

awaitRealHomeCodexHookTrust awaits current.done. The done promise settles only after settleApproval runs. settleApproval runs through runExclusivelyForCodexTrustConfig(getRealHomeConfigTomlPath(), ...) (Line 185). That queue key is the system ~/.codex/config.toml lane.

Managed-home hook installs hold that same lane across their inline trust grant:

  • src/main/codex/codex-hook-trust-queue.ts says they "hold both lanes across their awaits".
  • src/main/agent-trust-write-deadline.ts says each can take "up to 10s native each, with no cap on how many are already queued".

While an approval runs, the lane gate sends every new launch to the managed home. So during a pane restore, the settle can queue behind many managed-home installs. The resume then waits for the session time (up to 30 s) plus every queued install. The doc comment and the PR description both promise a wait of at most 30 seconds.

Fix: race current.done against a timer that clearTimeout stops when the race ends. After the deadline, the resume continues without waiting for the settle.

Proposed fix
 export async function awaitRealHomeCodexHookTrust(): Promise<void> {
   const current = approval
-  if (current && hasUnapprovedRealHomeOrcaEntry(current.command)) {
-    await current.done
-  }
+  if (!current || !hasUnapprovedRealHomeOrcaEntry(current.command)) {
+    return
+  }
+  let timer: ReturnType<typeof setTimeout> | undefined
+  try {
+    await Promise.race([
+      current.done,
+      new Promise<void>((resolve) => {
+        timer = setTimeout(resolve, CODEX_BACKGROUND_TRUST_GRANT_TIMEOUT_MS)
+      })
+    ])
+  } finally {
+    clearTimeout(timer)
+  }
 }

Import CODEX_BACKGROUND_TRUST_GRANT_TIMEOUT_MS from ./codex-hook-trust-grant. Also add that constant to the vi.mock('./codex-hook-trust-grant', ...) factories in src/main/codex/codex-real-home-hook-install.test.ts and src/main/codex/codex-real-home-trust-withdrawal.test.ts. Without it, the mocked value is undefined and the timer fires at once.

@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 3/5

[High risk] Refactors Codex hook installation and trust management across the codebase.

This PR should not merge until Windows percent-delimited profile paths and the failed-withdrawal resume path are handled.

Findings

  1. P1 Percent expansion breaks Windows hooks ▶
  2. P1 Failed withdrawal leaves resume exposed ▶
  3. P2 Root hook ignores opt-out ▶

Summary

The PR freezes Codex hook commands, makes real-home installation add-only during launches, moves approvals when hooks are removed, and runs real-home approval in the background.

  • Windows percent-delimited profile paths can prevent hook delivery.
  • A failed withdrawal can leave a resumed session facing Codex’s hook-review screen.
  • The reserved POSIX root-script path lacks the hooks-off gate.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Codex launch] --> B[Check real-home hooks]
  B --> C{Approval ready?}
  C -->|Yes| D[Launch in real home]
  C -->|No| E[Start background approval]
  E --> F[Launch in managed home]
  G[Real-home resume] --> B
  G --> H[Wait for in-flight approval]
  H --> I[Resume in real home]
Loading

Reviews (1) · Last reviewed commit: "test(codex): the trust move carries a bl..."

// a registry-enabled delayed expansion from expanding a `!NAME!` pair in the path,
// and the `@` stops cmd.exe stripping the quotes around a path holding & or ^.
const cmdExe = `${resolveWindowsDirectory(env)}/System32/cmd.exe`.replaceAll('/', '\\')
return `${cmdExe} --% /d /v:off /c @"${forwardSlashPath}"`

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Percent expansion breaks Windows hooks If a Windows profile path contains a defined %NAME% sequence, this command passes it to cmd.exe /c without preserving the literal percent signs. cmd.exe expands the sequence before locating the script, so Codex silently runs no Orca status hook for that profile.

Comment on lines +137 to +141
export async function awaitRealHomeCodexHookTrust(): Promise<void> {
const current = approval
if (current && hasUnapprovedRealHomeOrcaEntry(current.command)) {
await current.done
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Failed withdrawal leaves resume exposed If an approval fails and a concurrent hooks.json change prevents withdrawal, the unapproved entry remains after the approval is cleared. A resume during the retry delay gets no new approval, and this guard returns immediately because none is in flight. The session then starts in ~/.codex and can encounter Codex's blocking hook-review screen instead of resuming.

Knowledge Base Used: Agent integrations and hooks

// so a pane with hooks off and every shell outside Orca only drain stdin.
return [
`: orca-agent-hook-form=${CODEX_HOOK_COMMAND_FORM};`,
`if [ -n "\${ORCA_PANE_KEY-}" ] && [ -n "\${ORCA_AGENT_HOOK_ROOT-}" ] && [ -f ${rootScript} ]; then /bin/sh ${rootScript} || :;`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Root hook ignores opt-out The reserved root-script branch does not require ORCA_AGENT_HOOK_PORT, unlike the shared-script branch. If a future pane sets ORCA_AGENT_HOOK_ROOT while status hooks are off, it will still run the root script. This branch is dormant today, but leaving the gap in a command intended to stay frozen across builds makes a later activation risk bypassing the opt-out.

Knowledge Base Used: Agent integrations and hooks

@pullfrog pullfrog 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.

ℹ️ No critical issues — two edge cases worth a look.

Reviewed changes

Read the complete diff against main (82 files, +4,993/−2,628) and ran the six focused Codex hook suites on Linux (105 passing). This is the grown "frozen command / one writer" redesign that supersedes the earlier 23-file revision.

  • Frozen command (src/main/codex/codex-hook-command-form.ts, new): one byte-identical POSIX/Windows command with an orca-agent-hook-form=1 marker; readCodexHookCommandForm classifies existing entries.
  • Add-only real-home writer (codex-real-home-hook-entry-plan.ts, codex-real-home-hook-install.ts): launch prep adds a missing entry, app start converts older forms in place; no automatic path removes a live entry.
  • Opt-out-only removal (codex-real-home-hook-sweep.ts, codex-hook-local-maintenance.ts): the shared entry is stripped only on the explicit hooks-off flow.
  • Trust moves (codex-user-hook-trust-moves.ts, config-toml-hook-trust-edit.ts): shifted user hooks' trust records relocate verbatim, with no Codex session.
  • Background approval (codex-real-home-background-grant.ts): the grant runs outside the config.toml lane with a bounded retry schedule; a resume waits only while an unapproved entry is on disk.
  • Retired-command matcher (codex-hook-retired-commands.ts) and the deleted snapshot restores / pane-side writers (codex-trust-config-rollback.ts, managed-home-shell-preflight.ts).

I traced the lane reentrancy through runOutsideCodexTrustConfigLanes/AsyncLocalStorage, verified prepareForCodexLaunchAsync returns null for the system-default real home (so the managed installer never targets it), the frozen POSIX command always exits 0, and the current/frozen commands are negative in the retired matcher. Four independent subagents examined trust-move byte integrity, entry-plan correctness, command bytes, and the withdrawal/approval races; their hypotheses were refuted apart from the two suggestions inline.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

async (policy) => {
resolveCodexCommandMock.mockReturnValue(process.execPath)
const counts = installCodexLikeGrant()
const newer = `: orca-agent-hook-form=2; /bin/sh "\${HOME-}/.orca/agent-hooks/${

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.

This test asserts the "never rewrite a higher form" invariant with a command that carries the POSIX orca-agent-hook-form=2 marker even when process.platform === 'win32'. Real Windows commands have no marker (codex-hook-command-form.ts:16-19), so readCodexHookCommandForm can only identify the current form there by byte equality and would return 0 for any genuinely newer Windows command — exactly the shape this test claims to cover. The invariant is therefore verified only on the platform where it is enforceable; a future Windows form change would be rewritten by convert-older-forms on app start.

Comment on lines +230 to +238
if (
!hasFrozen &&
(args.policy === 'convert-older-forms' ||
(handlers.length === 0 && directOrcaUnits.length === 0))
) {
// Why last: no user hook's positional trust key moves.
const hook = buildManagedCommandHook(command)
definitions = [...definitions, { hooks: [hook] }]
written = { hook, replaced: null }

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.

Under convert-older-forms, when the event's only Orca entry sits in a slot isConvertibleSlot rejects (a matcher group, or a definition carrying a direct command/bash/powershell) and removing it would shift a user hook, the entry is kept, hasFrozen stays false, and this branch appends a second frozen entry — so the shared script runs twice for that event. Suppressing the append when any non-frozen Orca entry remains (the condition the add-missing-only branch already uses) would avoid the duplicate without losing status, since the kept entry still runs the shared script.

Technical details
# Suppress the convert-policy append when a non-frozen Orca entry remains

## Affected sites
- `src/main/codex/codex-real-home-hook-entry-plan.ts:189-238` — `keeper` requires `isConvertibleSlot`; `others` removal is gated by `movesUserHandler`; the append condition `!hasFrozen && args.policy === 'convert-older-forms'` ignores `handlers`/`directOrcaUnits` still present.

## Required outcome
- An event that still holds an Orca-shaped entry after conversion/dedup must not also receive an appended frozen entry, so the shared script is not invoked twice.

## Suggested approach
- For `convert-older-forms`, reuse the `add-missing-only` guard: append only when `handlers.length === 0 && directOrcaUnits.length === 0` (both computed on `current`, so a kept duplicate blocks the append).
- Confirm the double-run is otherwise covered by the PR's Known weaknesses before deciding between suppressing and converting the non-convertible slot in place.

@brennanb2025
brennanb2025 merged commit cfa43e7 into main Sep 30, 2026
87 of 88 checks passed
brennanb2025 added a commit that referenced this pull request Oct 1, 2026
Brings in #23552 (cfa43e7), which moves a shifted user hook's trust block
to its new key (moveHookTrustContent / moveHookTrustEntries) instead of
rebasing it through a Codex session. Conflicts and resolutions:

- config-toml-hook-trust-edit.ts: ported main's moveHookTrustContent into the
  checked writer. One applyCheckedCodexConfigTomlEdit call now strips the old
  and new keys' blocks (every spelling, matched by decoded key) and appends the
  moved bodies verbatim. Owned paths are the old/new keys plus their spellings;
  each new key must hold the old block's parsed values; an invalid result is
  refused. Main's guards stay: nothing to move or a stored key of unknown shape
  returns the file unchanged without parsing. Dropped main's stale
  repairOrcaDuplicateTrustTables import (#23930 moved repair into
  codex-config-toml-repair). appendTrustBlocks became appendTomlBlock, shared
  by the upsert and the move.
- config-toml-syntax.ts: kept main's exported CODEX_HOOK_TRUST_KEY and
  #23930's decoded-key header parsing.
- config-toml-runtime-owned-sections.ts: #23930's import block plus main's
  CODEX_HOOK_TRUST_KEY; main's local copy of the regex stays removed.
- config-toml-trust.ts: union of imports (move, remove, setEnabled, upsert).
  moveHookTrustEntries keeps main's name and signature but now wraps the edit
  in withConfigPath and writes with writeTomlConfigAtomically, like its
  sibling hook-trust writers.

Outside the conflicts: codex-user-hook-trust-moves.ts reports a refused move
through reportCodexConfigTomlEditRefusal (once per file and message) instead
of console.warn on every hooks write. Added tests: a quoted-spelling stale
table at the new key leaves one parseable table, and a hand-broken config is
left untouched with the refusal logged once.
OmarHung pushed a commit to OmarHung/orca that referenced this pull request Oct 3, 2026
…real ~/.codex (stablyai#23552)

* fix(codex): a real-home restore leaves a file alone once someone else changed it

Orca writes ~/.codex/hooks.json (and a trust rebase writes config.toml), then
runs a Codex trust session for up to 10 s, then restores the original bytes if
the session fails. The restore wrote unconditionally, so a save that landed
during the session, from the user or another Orca, was silently reverted.

Each restore now compares first: it writes the original back only while the
file still holds the generation Orca's mutation left, and otherwise logs and
leaves it alone. This covers the real-home install and opt-out sweep
(restoreRealHomeHooksJson), the legacy sweep's hooks restore, and config.toml
rollback (restoreCodexTrustConfig).

For hooks.json the generation is the exact bytes Orca wrote. For a config.toml
that a trust rebase changed it is the file as the rebase left it. When Codex
itself wrote config.toml inside the session that just failed, Orca never knew
those bytes, so that rollback compares against the file as the session settled.
The next commit keeps other Orca instances out of that window; a user edit made
during such a session can still be rolled back.

* fix(codex): serialize real-home Codex writes across Orca instances

Every Orca on one HOME (a dev and a packaged app, or an offline CLI) writes the
same ~/.codex/hooks.json, config.toml and ~/.orca/agent-hooks/codex-hook.sh.
The per-file lane that orders capture, mutate and restore was in-process only,
so another instance could write inside this one's restore window, or undo it.

The lane for the user's real config.toml now also holds the existing
crash-safe managed-hook install lock (~/.orca/managed-hook-install.lock, the
one relay installers take for the same home). It is taken only by the
outermost acquire, because the lock file is not reentrant and grants and trust
rebases nest inside an install. Managed-home installs, the real-home install
and opt-out sweep, and the legacy sweep all enter through it. Compare-and-swap
on restore stays as the backstop.

A lock that cannot be taken within its 10 s wait fails that install, which is
already best effort: launch prep logs it, and the real-home lane falls back to
the managed lane until its retry.

* fix(codex): opening a terminal no longer strips the shared Codex entry from ~/.codex

Every Orca instance on one HOME writes the same status-hook entry into the
user's ~/.codex/hooks.json, with its trust in config.toml. Launch prep runs on
every pane spawn, and under a managed Codex account it ran the legacy system
sweep. That sweep matched Orca entries by script file name, so it removed the
current shared entry and the trust blocks the grant ledger recorded. On a live
laptop hooks.json went 4139 -> 18 bytes about 150 ms before a new pane opened.
With hooks off, the real-home lane's launch prep swept the same way.

Now nothing automatic removes the current entry or its trust:
- The legacy sweep removes only an enumerated list of retired command forms
  that no build writes any more (#1019's double-quoted form, #1536's
  exec-guarded form, and Windows' per-userData bare path), plus their trust.
- ensureRealHomeCodexHookState with hooks off writes nothing; that covers
  launch prep, session resume and startup.
- Only the user's explicit opt-out (codexHookService.remove()) strips the entry
  and its ledger-recorded trust from the real home.
- The sweep-suppression gate existed only to stop the sweep from deleting the
  current entry, so it is deleted with its main-process wiring.

Startup with hooks off already skipped the real-home install; with this change
the first pane's launch prep with hooks off also leaves ~/.codex untouched.

* fix(codex): a pane's prepare-codex only repairs a home its own HOME's app installed

On macOS a pane starts through login(1), so it gets the user's real HOME even
when its Orca app runs with another one. The pane's `codex()` preflight
installed hooks in the CLI process with that real HOME: it rewrote
~/.orca/agent-hooks/codex-hook.sh, promoted trust into the real config.toml,
and wrote the real HOME's script path into the app's managed home.

The preflight now acts only when the managed home's hooks already run this
process's own shared script, which proves the app that installed them shares
its HOME. Otherwise it writes nothing; the app installed the home at spawn.

Why not a no-op: the preflight was added (#14326) because trust can go stale
between opening a pane and typing `codex`, for example in a pane that survives
an app update, and Codex then stops in hook review. For a same-HOME pane it
still repairs that. Why keep promotion: the install drops runtime trust the
system config does not back, so skipping promotion would delete approvals the
user gave inside Orca-launched Codex.

* test(agent-hooks): await every installer in the refresher coverage test

The test fired each managed installer without awaiting it and read
~/.orca/agent-hooks straight after. Codex's install now takes the
cross-process real-home lock before it writes its script, so the script
landed after the read. Await the installers, and stub Codex's trust sessions
so the awaited install cannot start a real `codex app-server`.

* fix(codex): retire the two real-home command forms the list missed

The real-home lane wrote two Codex hook forms into ~/.codex that no build
writes any more and that the enumerated retired list did not name:
- POSIX, #9501 until #10885: the file-guarded form draining with a bare `cat`.
- Windows, #9501 until #10221 took Windows off the real-home lane: the encoded
  PowerShell launcher for a non-cmd-safe script path.

The file-name sweep removed both before; the enumerated sweep left them in
place, trusted, still passing the script's exit status to Codex. Both now
match as frozen literals.

Also corrects the startup ordering comment: the real-home install runs first
so its in-slot upgrade lands before the managed install's sweep retires the
prior command; nothing re-arms a legacy sweep any more.

* fix(codex): take the real-home lock only when a write is needed

The previous commit made every entry to the real-home config lane take the
cross-process lock. That lane runs on every pane spawn and every typed
`codex` preflight, so the steady state paid an owner probe (a `ps` spawn on
macOS) and could wait up to 10 s behind another instance's trust session,
even though it wrote nothing.

Each real-home writer now compares the desired state with the files on disk
first, without the lock. Only when a write is needed does it take the lock,
re-read and recheck, then write:
- real-home install: the planned hooks.json, the shared script and the
  ledger-recorded grant are compared; the locked path re-plans from disk.
- legacy sweep: locks only when a retired entry is present; the sweep re-reads.
- approval promotion: locks only when there is something to promote; the
  promotions are recomputed under the lock.
- the shared ~/.orca/agent-hooks script: locks only when its bytes differ.
The explicit opt-out always takes the lock. The lock is reentrant through
async context, since grants and rebases nest inside an install, so the
config-lane option the previous commit added is removed.

* fix(codex): a shared script without its exec bit is not the steady state

The compare-first check matched the shared ~/.orca/agent-hooks script on bytes
alone. writeManagedScript also restores 0755 on every call, and the POSIX hook
guard skips a script that is not executable, so a script whose mode was lost
(a dotfiles restore, a plain copy) now stayed that way: every Codex hook
drained stdin and reported nothing until an app restart refreshed the script.

The check now also requires the mode the writer sets, so that case takes the
lock and the write path repairs it.

* test(codex): the retired encoded launcher never matches today's shared one

The shared encoded Windows launcher is still current for other agents, so the
comment claiming today's launcher is never encoded was wrong. What keeps the
retired matcher off it is the exact payload: since #14825 the shared launcher
prefixes its payload and drops -ExecutionPolicy Bypass. Pin that with a case.

* fix(codex): the pane step recognises its own script under a home path with an apostrophe

The same-HOME check looked for the script path wrapped in bare single quotes,
but both hook writers escape an apostrophe inside the quotes. A home such as
C:\Users\O'Brien never matched, so the pane-step repair never ran there.

* fix(codex): the trust-RPC escape hatch still keeps the real home off its lane

The no-write check reported a recorded grant as current, so with
ORCA_DISABLE_CODEX_TRUST_RPC set the real-home lane stayed in use. The grant
itself refuses before reading its ledger; the check now does the same.

* fix(codex): the shared script write no longer waits on the real-home lock

The write is atomic and skips identical bytes; waiting behind another
instance's trust session could only fail a pane's managed-home install.

* fix(codex): an in-Orca approval survives a launch that cannot get the real-home lock

The install drops runtime trust the system config does not back, so a
promotion skipped for want of the lock lost the approval for good. It
now writes unlocked, as it did before the lock existed.

* refactor(codex): take the cross-process real-home lock back out

The lock fixed no observed failure. The three that were observed each have
their own fix in this series: the legacy sweep matches only frozen retired
command forms, hooks-off launch prep writes nothing, and a pane's
prepare-codex repairs only a home its own HOME's app installed. The lock
instead brought its own defects: a steady-state spawn waiting behind another
instance's trust session, a compare-first split to avoid that, a script
write and an approval promotion that could fail for want of the lock.

Removed, with their tests: the real-home write lock and its async-context
reentrancy, the plan/compare split that kept it off steady-state spawns, the
compare-first legacy sweep, the locked approval promotion and its unlocked
fallback, the compare-first shared script write (writeManagedScript already
skips identical bytes and restores the exec bit), and the CLI tsconfig
entries the lock pulled in.

Kept: the retired-forms matcher, the hooks-off no-op, removal only on an
explicit opt-out, the pane own-script check, and the compare-and-swap
rollbacks. Every instance now writes identical bytes idempotently.

* fix(codex): an opt-out that cannot read hooks.json keeps Orca's trust and ledger

The opt-out swept the real-home entry, then dropped Orca's ledger-proven trust
whenever a ledger existed, even when the sweep could not read hooks.json. The
entry could still be there, now untrusted, and the ledger that proves ownership
was gone for the retry. Drop that trust only after a sweep that read the file.

* refactor(agent-hooks): one predicate for whether an agent's status hooks are on

"Global switch on and this agent not turned off" was spelled out separately
in the startup controls, the settings reconcile, the retained-home
reconcile, the WSL preflight RPC, the CLI preflight and the OpenCode plugin
selection. They now share one function, in a module light enough for the
CLI's per-launch Codex preflight to load. The PTY spawn env derives the
Codex flag from the switch and opt-out list it already carries, the same way
it does for OpenCode and Pi, instead of receiving a second copy.

* fix(codex): launch and resume prep honour Codex's per-agent hook opt-out

Turning Codex off in the per-agent hook settings removes Orca's Codex hook
entry, but launch prep and session resume read only the global hooks switch,
so the next Codex launch or resume wrote the entry straight back into the
real ~/.codex or the account's home. Both now read the per-agent predicate,
which the PTY spawn env and startup already honoured.

* fix(codex): turning Codex off per agent clears the real ~/.codex entry

While the real-home lane owns ~/.codex/hooks.json, the legacy system-home
sweep stands down. That gate read only the global switch, so turning Codex
off per agent ran remove() with the sweep still suppressed and left Orca's
entry in the real ~/.codex. The gate now reads the per-agent predicate, the
same as turning every hook off.

* test(codex): cover the system ~/.codex sweep gate for Codex turned off

The gate that lets the legacy system-home sweep run was an inline closure in
startup, so reverting it to the global switch left CI green. It is now a
pure function beside the gate it feeds, with a table test and a remove()
test on a seeded ~/.codex: turning Codex off strips Orca's entry and keeps
user hooks; with Codex on the entry stays.

* fix(cli): keep the agent-status hooks predicate loadable by the packaged CLI

The CLI's prepare-codex handler imported the predicate from src/main, but
the Electron build rebuilds out/main from its declared entries only, so the
packaged `orca agent hooks` commands could not load it (package jobs and the
CLI bundle-parity test were red). The predicate reads only settings, so it
now lives in src/shared, which the CLI compiles itself.

* feat(codex): every Orca build writes one frozen Codex hook command

The Codex hook command was built from this build's wrapper, so two builds
on one HOME disagreed about the bytes of the shared ~/.codex entry and kept
rewriting it, with a Codex trust session each time.

The command is now fixed per form and carries its form number:
- POSIX: one command with no path in it. It runs the shared script only in
  an Orca pane with hooks on (pane key and hook port set), drains stdin
  everywhere else, and always exits 0. A branch for a per-build script root
  is written now and stays dormant until Orca sets ORCA_AGENT_HOOK_ROOT, so
  that change will not move these bytes.
- Windows: the bare forward-slash path to the shared .cmd, which runs under
  PowerShell 7 and 5.1, Codex's hook hosts. A profile path that is not one
  PowerShell token gets a plain PowerShell form with the same branches.

The literals live in the form module, so a change to the shared hook
constants cannot move them; goldens pin the bytes. Every form keeps
`agent-hooks/codex-hook.*` in plain text, so older builds still recognize it.

* fix(codex): one main-process owner adds the real-home entry; nothing restores files

Each Orca writer of ~/.codex decided what Orca's entry must be from its own
build and instance, then removed or reverted whatever differed: launch prep
rewrote any Orca-shaped entry to this build's command and stripped Orca
entries from events this build does not use, and a failed trust session
restored hooks.json and config.toml from snapshots. With several instances
and builds on one HOME, every disagreement became a deletion or a revert.

The main process is now the one writer, and its writes are add-only:
- A launch or resume adds Orca's frozen entry to an event that has none and
  leaves every Orca entry it finds, so a running older build is never fought.
- App start also converts an older Orca form to the frozen command, once, in
  its own slot: one hooks.json write (one .bak) and one trust grant per home.
- A newer form is never rewritten or appended beside, and Orca entries in
  events this build does not use are kept.
- After a failed trust grant, only an entry this call wrote that is still
  untrusted is withdrawn, putting back the handler it replaced. Both files
  are re-read, so a concurrent edit, or the identical entry another Orca
  trusted meanwhile, survives.

Deleted: the compare-and-swap hooks.json restore, the config.toml snapshot
restore after a grant session and after a user-trust re-key, and the
rollback module. A grant session writes trust only at Orca's own keys, and
every caller settles those keys itself. A failed re-key of moved user hooks
now keeps the write and reports it; Codex lists those hooks for review.

* fix(codex): the pane CLI asks the app to prepare its Codex home

`orca agent hooks prepare-codex` ran Codex's install inside the pane. That
process can have the real HOME (login(1)) and runs outside the app's
in-process queues, so it was a second writer of ~/.codex and ~/.orca beside
the app. A check that the home ran "its own script" guarded it.

The pane step now only asks the app, over the same kind of local RPC the WSL
pane step already uses (agentHooks.prepareCodexForPane). The app checks that
the pane's CODEX_HOME is one its own userData owns, reads its own hooks
setting, and installs on its own queue. An app that is not running, or is
too old to know the method, makes the step a no-op, as it is on WSL. The
own-script check and the CLI's settings read are gone, and the preflight
module leaves the CLI bundle.

* fix(codex): delete the pane step on native hosts

The previous commit had `orca agent hooks prepare-codex` ask the app to
prepare the pane's Codex home. The case it existed for (#14326, a pane that
survives an app update with stale hook trust) did not reproduce, and no other
desktop agent host writes agent config from a terminal or launch wrapper.

- Deleted: the agentHooks.prepareCodexForPane RPC method, its params and
  catalog entry, and prepareManagedCodexHomeBeforeShellLaunch with its module,
  tests and CLI build entry.
- `agent hooks prepare-codex` is a no-op on native hosts. It stays for one
  release so shell wrappers from older builds, which still call it, exit 0.
- WSL panes are unchanged: they still ask the app over
  agentHooks.prepareCodexForWslPane.

The shell wrappers and ORCA_CODEX_LAUNCH_PREFLIGHT stay, because WSL panes
use the same wrappers and variable (forwarded through WSLENV). A native pane
still starts the CLI once per `codex` it runs; skipping that is a follow-up.

* test(codex): a failed trust session keeps concurrent edits to both files

QA case 9 at host level, on a real file system in a temp HOME: Codex's trust
session fails after another writer saved hooks.json and config.toml.

- Both saves survive, and no Orca entry is left that Codex would list for
  review: this call's entry is withdrawn.
- A failed one-time conversion puts the older Orca entry back in its slot and
  keeps both saves.

Both tests fail on the previous head, which restored config.toml from a
snapshot and left the untrusted entries in hooks.json. Removing the
withdrawal turns both red.

* feat(codex): read whether an Orca entry's stored trust is still current

A Codex release that changes how it hashes a hook leaves Orca's stored trust
stale: the entry is present, but Codex lists it as modified. Checking only
whether the entry is missing cannot see that.

readOrcaEntryTrust sorts a present entry into four states:
- trusted: the stored hash is the current one;
- untrusted: there is no stored hash;
- stale: the stored hash is not the current one;
- disabled: the user turned the entry off.

The caller can pass Codex's current hash, for example one a grant recorded.
The failed-grant withdrawal now uses it, and also keeps an entry the user
turned off. Nothing re-grants on 'stale' yet.

* fix(codex): a slow Codex start retries on the next launch, never for minutes

On a loaded Mac a cold `codex app-server` took over 10 s (QA case 4). The
grant timed out, the entry was withdrawn, and a 5-minute cooldown in both the
grant and the real-home install then refused every retry.

- The native session deadline is 30 s, the same as WSL's.
- A timeout starts no cooldown in the grant or in the real-home install. The
  next launch retries. Other failures keep their cooldown.
- Launches that queue behind a slow session share one follow-up run, so a
  launch waits for at most two sessions, not one per earlier launch.

Tests: a 15 s cold start still grants and keeps the entry; after a timeout,
the next launch runs a session at once; four queued launches run two
sessions. Each is red on the previous head, and each mechanism was removed in
turn to confirm its test turns red.

* fix(codex): Orca's automatic writes never move a user hook

Codex keys a hook's trust by its position in hooks.json. App start's collapse
of Orca duplicates removed every Orca entry and appended one at the end. That
moved any user hook that followed a removed entry, so the write waited on a
session to re-key the moved hook's trust.

App start now:
- converts the first Orca entry that sits in a plain slot to the frozen
  command, in place;
- drops any other Orca entry only when that moves no user hook;
- keeps a duplicate that a user hook follows, and trusts every frozen copy,
  so none is listed for review;
- appends only when no frozen entry is left.

Tests check user positions and user trust blocks byte-for-byte for each
automatic write: add-missing (append), the one-time conversion (in place),
a trailing duplicate, a duplicate before a user hook, and older duplicates
normalized to one entry. The three collapse cases fail on the previous head.
Removing the position check, or the in-place conversion, turns its tests red.
Only the explicit opt-out still removes an entry that user hooks follow.

* fix(codex): removing an Orca entry never waits on a Codex session

Removing an Orca entry from ~/.codex/hooks.json moves every user hook behind
it up a slot, and Codex keys trust by slot. The retired-form sweep, the
opt-out and a failed-grant withdrawal all asked a `codex app-server` session
to list the old trust before writing, and to re-key it afterwards. A timeout
there threw before the write and latched a 5-minute cooldown, so a slow cold
start blocked the retired-form sweep at boot (QA case 4).

Each moved hook's [hooks.state] block now moves to its new key, body bytes
unchanged, straight after the hooks.json write. Codex hashes a hook's content,
not its position or its file path, so the moved block stays exactly as valid
as it was: a trusted hook stays trusted, an untrusted one stays untrusted, and
one the user turned off stays off. No removal waits on or depends on a
session. A failed config.toml write keeps the hooks write and logs.

Deleted: the inspect and repair sessions, their client, and their cooldown.
The generation guards on the hooks.json writes stay, for other processes.

Tests: the retired sweep removes the retired entry and carries the trust of
the user hook behind it while every Codex session times out (red on the
previous head); the opt-out carries an appended user hook's trust; the move
carries trusted, disabled and untrusted states byte for byte. Removing the
move turns all of them red.

* fix(codex): a Codex launch never waits on Codex's approval of Orca's entry

A launch on the real-home lane awaited Codex's trust grant for the entry it
had just added. A cold `codex app-server` on a loaded Mac took over 10 s, so
the launch could wait that long, and a failure then latched a 5-minute
cooldown.

- Codex's approval runs in the background, with a 30 s cold-start budget.
- A launch uses the real home only when the ledger shows trust is already
  current. Otherwise it goes to the managed home at once, and the next launch
  picks up the finished grant.
- A launch that arrives while a grant runs does no work and does not queue
  behind it.
- A resume into the real home has no managed home to fall back to. It waits
  for the grant, but no longer than the 10 s a launch always could.
- A background grant that times out starts no cooldown; the next launch
  retries. Any other failure backs off for 10 s instead of 5 minutes.
  Success is what the ledger remembers.
- A failed grant still withdraws only what that install added and is still
  unapproved. The log now says how many entries it took back and when the
  next try comes.

Managed-home grants keep their 10 s deadline and stay on launch prep, as
before; they fall back to Orca-computed trust.

Tests:
- A 15 s start: the launch returns in under a second on the managed home, a
  second launch starts no session, the grant lands in the background, and the
  next launch uses the real home.
- A timeout sets no cooldown, withdraws its adds and logs it.
- Another failure retries after 10 s, not before.
- A resume waits only as long as allowed.
- Case 9 checks the log line and the retry.

Making the launch await the grant, a 10 s budget, either timeout cooldown, and
a 5-minute backoff were each tried, and each turns its test red.

* fix(codex): move a hook's trust only when every stored key has the known shape

Orca now edits Codex's trust store directly when a removal moves a user
hook. Three safeguards keep that honest:

- Fail safe. If any [hooks.state] key in config.toml does not have the
  shape `<path>:<event>:<group>:<handler>`, nothing moves and Codex asks the
  user to review. That shape was checked unchanged from Codex 0.141 to 0.158.
- Targeted. The file is read immediately before the atomic rename, and only
  the moved keys' blocks change. Every other byte stays, and no snapshot is
  restored.
- Verbatim. Each block's body moves as Codex wrote it, including fields
  Orca does not know. No hash is ever computed, and a hook with no block
  gets none.

Tests:
- An unknown key shape stops every move.
- Everything except the moved block survives byte for byte, and the moved
  body keeps an unknown field.
- In case 9, a hook the user approved during the failed session keeps its
  approval when the withdrawal moves it, beside the concurrent project edit.

Removing the shape check, or writing a computed block instead of the stored
body, turns these tests red.

* refactor(codex): keep only the trust read the failed-grant withdrawal uses

A capture across Codex 0.141, 0.150 and 0.158, switching in all six
directions, showed Orca's entry keeps the same hash and stays trusted. A
Codex upgrade does not make its trust stale, so nothing needs to re-grant
on staleness.

readOrcaEntryTrust keeps the four states the withdrawal needs, but loses
the parameter that let a caller pass a different current hash, and the test
for a Codex that hashes differently.

* fix(codex): native panes no longer start the Orca CLI before each codex

The pane step is a no-op on native hosts, but native panes still carried
ORCA_CODEX_LAUNCH_PREFLIGHT, so every `codex` typed in a pane started the
Orca CLI for nothing. Only a packaged Windows build's WSL pane now gets the
variable; the app prepares every native Codex home itself.

The resolver loses the dev-launcher path and its userDataPath option, which
only native panes used.

Tests: a native macOS, Linux and Windows pane gets no preflight, packaged or
not, even with the bundled CLI present; a WSL pane still gets the verified
absolute launcher. Letting native panes through again turns them red.

* chore(cli): say when the native prepare-codex no-op can go

Native pane wrappers from builds up to v1.4.216 still call it. It can be
deleted once no supported build's wrapper does.

* test(codex): check the WSL launcher path instead of asserting it

* fix(codex): a launch no longer waits behind the background real-home approval

The background grant ran its whole codex app-server session inside the shared
~/.codex/config.toml lane, and on a cold host its session was also the shared
capability probe. A launch sent to the managed home then waited on both: the
managed install and the project-trust write queue on that lane, and the
managed install's own grant waited for the probe. On a cold app-server that
was up to 30 s per launch.

The lane was held across the session only to protect the retired
capture-and-restore. Codex writes its own records, so the lane is now taken
only around Orca's own pre-grant write. The background grant runs its session
without publishing it as the shared probe, and the whole grant is bounded by
its deadline, so a hang outside the session cannot leave the lane 'granting'.

* fix(codex): a failed re-grant no longer strips Codex's own approval of Orca's entries

Before each trust session, the grant deleted every Orca record whose hash
matched the one Orca computes. That exists because a managed home's fallback
writes Orca-computed trust under both Windows path-separator spellings, and
Codex rewrites only its own spelling, so the other copy would linger. On
failure the managed and WSL fallbacks write that trust back, and before this
fold a snapshot restore covered it.

The real ~/.codex has neither: Orca never writes computed trust there (the
real-home lane does not run on Windows at all), so a matching record there is
Codex's own approval. After a ledger miss (another Orca profile, a Codex
update, a lost ledger) and a failed session, nothing put it back, and every
Orca entry showed "Hooks need review".

The clear now runs only for homes whose fallback writes that trust.

* fix(codex): a real-home resume spawns only once Orca's entry is approved or withdrawn

A resume that must run in ~/.codex waited at most 10 s for the background
approval, then spawned anyway. On a cold app-server that left Codex beside an
unapproved Orca entry, so the resumed pane showed hook review.

The resume now waits for the grant to settle. Settled means Codex approved the
entry, or the grant failed and withdrew its own unapproved write; the grant's
deadline bounds the wait (30 s, the cold-start budget), and a failed approval
never fails the resume.

Why this over the alternatives:
- Spawning at 10 s keeps the review prompt this fold exists to remove.
- Withdrawing at 10 s from the resume races the still-running session: Codex
  can write the frozen entry's hash after the withdrawal, and for a converted
  entry that marks the older command Orca put back as modified.
- A resume cannot use the managed home: the session lives in ~/.codex.
So the only states that cannot race Codex are the grant's own settle. The cost
is a longer worst case on a cold app-server (up to the 30 s deadline, plus any
managed-home install that holds the config.toml lane); a warm approval takes
seconds, and an approved entry costs no wait.

* fix(codex): keep the 5-minute trust cooldown for launch-path grants

The fold shortened the host's trust-grant cooldown from 5 minutes to 10
seconds for every grant. That was meant for the background ~/.codex approval,
which blocks no launch. The managed-home and WSL grants run inline on the
launch path, so with a hung app-server every launch more than 10 s after the
last failure paid the full inline timeout again (10 s native, 30 s WSL).

Cooldowns are now kept per lane: inline grants keep 5 minutes, the background
grant retries after 10 s, and neither lane's failure cools the other down. A
success, or a proven-missing surface, still clears both. The real-home
install's own retries (an unreadable hooks.json, unknown keys) are back on the
5-minute interval they had before the fold.

The cooldown moves to its own module so the grant stays within the file limit.

* fix(codex): a failed grant withdraws the exact copy it wrote

The withdrawal re-found "this call's" entry by command, taking the first
frozen handler in the event. When app start converted a later slot while an
earlier frozen copy sat in a matcher group (which conversion skips), a failed
grant acted on that earlier copy: it put the older command into it, or skipped
it, and left the converted, unapproved copy in place.

Each write now records where its handler landed, after any duplicate drops,
and the withdrawal acts only on that slot. A copy that has since moved is left
alone; the next launch's grant retries it.

* fix(codex): the failed-grant withdrawal checks hooks.json is unchanged before writing

The install and the retired-form sweep both refuse to replace ~/.codex/hooks.json
if it changed since they read it. The withdrawal did not: a save landing
between its read and its atomic replace was lost. The window is small, since
the withdrawal is synchronous, but it now carries the same guard.

* refactor(codex): drop rationale left over from the snapshot restore; name the trust-move module for what it does

Comments on the config.toml lanes still justified them by a grant's
capture-and-restore window, which the fold deleted, and the trust-write
deadline still counted a grant session holding the lane. They now give the
reason that remains: Orca's own multi-step reads and writes, and managed-home
installs that hold the lane across their inline grant.

codex-user-hook-trust-rebase no longer rebases through Codex; it moves stored
trust records, so it is now codex-user-hook-trust-moves.

The grant test that pinned two sessions on one config.toml to run one at a
time is removed: its reason was an interleaved capture and restore. Callers
that write config.toml around a grant hold their own lane, which the nested
installer test still covers.

* build(cli): list the trust-grant cooldown module in the CLI program

The CLI's agent-hooks handler loads the hook controls, which reach the Codex
trust grant; the CLI project is composite, so every module in that graph must
be listed.

* docs(codex): say which Windows hosts each hook command form runs under

Codex runs a hook under the turn's shell (PowerShell 7 or 5.1 in every
captured session) and, with no single local turn shell, under %COMSPEC% /C.
The bare forward-slash path ran under all three in the Windows host census.
The PowerShell form used for a profile path with a space does not parse under
cmd.exe; no form valid in all three hosts has been run for such a path, so the
form stays and the gap is stated here and in the PR.

* test(codex): type the withdrawal seam without an assertion

* fix(codex): a real-home resume starts at once, trusting Orca's entries for that process

A resume that must run in ~/.codex waited for Codex's background approval of
Orca's newly written hook entry: up to 30-40 s on a cold app-server. That made
the user's resume wait on bookkeeping, and the alternatives (start at 10 s with
Codex's hook review showing, or withdraw the entry and race Codex's own write)
were worse.

Codex reads hook trust from its session-flag config layer as well as the user's
config.toml, merged per key, and has since hook trust shipped. So the resume no
longer waits. When Orca's own frozen entries in ~/.codex are untrusted (or hold
a stale hash), the resume command carries
`-c hooks.state={'<key>'={trusted_hash='<hash>'},...}` for exactly those entries:
the key under both the logical and the real path of ~/.codex (Codex keys an
explicit CODEX_HOME by its real path), and the hash of that entry's content, so
it can trust nothing else at that slot. The user's hooks are never included,
nothing is written, and the background approval still runs for later plain
`codex` launches. An approved entry adds nothing; a Codex known to lack hook
trust gets nothing.

One inline table, because Codex splits a `-c` key on every `.` and the key holds
`.codex/hooks.json`. TOML literal strings keep `"` out of Windows native-argument
quoting. The flag goes before `resume <id>`, quoted for the pane's shell (portable
Unix, PowerShell or cmd), in the launch command and in the setup-sequenced copy of
it; a cmd line whose path cmd would expand, or a key with an apostrophe, is left
unchanged. SSH and WSL resumes get no preparation, so no local path reaches them.

* Revert "fix(codex): a real-home resume starts at once, trusting Orca's entries for that process"

This reverts commit 1bd30651d65fa33f5feda0e2c65b6b95d39c1368.

* fix(codex): a real-home resume starts at once, without waiting for approval

A resume into the real ~/.codex waited until the background approval settled,
up to its 30 s deadline on a cold app-server: bookkeeping for later launches
gating the resume the user asked for. It now starts at once. If the approval is
still running, that first resume can show Codex's hook review once; the
approval then lands and later resumes and plain codex launches are trusted.

Trusting Orca's entries per process was the alternative, but the resume command
is typed into the pane's shell, and hook settings stay out of typed commands.

* test(codex): read real-home hook groups with the installer's own type

* fix(codex): a background approval is bounded only by its session's own deadline

Review loop 2, L3. grantWithinDeadline raced a second 30 s timer against
the background approval. Loop 1 added it so that a hang upstream of the
session could not leave the lane 'granting' forever.

That hang cannot happen. The only caller is the native real-home grant
(its plan is always host 'native'; the real-home lane is off on Windows,
so WSL never reaches it). Everything before the session is synchronous
there: command resolution and binary stamp, the ledger read, the
state-db backfill check, the capability and cooldown checks, and
runUnshared awaits no shared probe. A synchronous hang would freeze the
main thread, which no timer can rescue. The session itself starts a kill
timer right after spawn (runCodexAppServerSession), with the same 30 s,
and it kills the app-server tree when it fires.

So the outer timer was a second copy of that bound. Because it started
first, it won by the spawn time. It then settled the lane and cleared
backgroundGrant while the app-server was still alive, and the next
launch could start a second concurrent session. It abandoned the
session rather than cancelling it. Deleted, not moved: the session's
own timer is the one bound, and it cancels.

Test: codex-real-home-slow-app-server.test.ts "runs one session at a
time, ended by its own deadline". The fake session starts its timer
after a simulated spawn, as the real one does. A launch at 30 s finds
the session still running and starts none; the lane settles when the
session times out. It replaces the "settles a grant that never answers"
test, whose never-answering session could not time out at all.

* fix(codex): a background approval's retry has one schedule, the real-home lane's

Review loop 2, L4. A non-timeout background failure set two 10 s
schedules for one failure: the real-home lane's installRetryAfterMs,
which gates ensure, and a `<host>#background` cooldown in the grant
module. ensure's gate always tripped first, so the second one was
consulted only after something reset the first (turning hooks off).
Then it answered 'retry-cached', which wrote the entry into
~/.codex/hooks.json only to withdraw it again: churn, not protection.

Background plans now neither start nor consult a grant-module cooldown.
The real-home lane (installRetryAfterMs) is the one source of truth for
when a background approval runs again, and its 10 s interval moves into
codex-real-home-background-grant.ts, the module that sets it. The
cooldown module is back to one host-keyed map for launch-path grants,
with the same 5-minute interval as main. A success or a proven-missing
surface from either lane still clears the host's cooldown.

Tests:
- codex-hook-trust-grant.test.ts "neither starts nor waits on a
  cooldown for a background grant": two failing background grants each
  run a session and leave no cooldown; an inline failure still cools
  down inline grants and not the background one.
- codex-real-home-slow-app-server.test.ts "has one retry schedule:
  turning hooks off and on after a failure retries at once": after a
  failed approval, hooks off then on runs a session and installs,
  instead of a retry-cached write-and-withdraw.

* fix(codex): hooks turned off and on during an approval re-add Orca's entry

Review loop 2, L1. ensure returned at once whenever a background
approval was running, whatever the lane. Turning hooks off during an
approval sets the lane to 'removed' (usable), so turning them back on
returned 'removed' without re-adding the entry. Launches in that window
spawned in ~/.codex with no Orca hook and got no status for their
lifetime, for up to 30 s, until the approval settled and a later launch
re-added it.

ensure now returns early only while the lane is 'granting', which is
what the early return exists for: a launch never waits on Codex's
approval and uses the managed home until it lands. Any other lane runs
the normal add-missing install.

That install can start a second approval while the first is still
running. Approvals are now chained, so Codex still runs one session at
a time, and a finished approval clears the handle only if it is still
the latest one (before, an older approval's finally could clear a newer
one's handle). The older approval's result is already dropped by the
lane generation check.

Test: codex-real-home-slow-app-server.test.ts "re-adds the entry when
hooks go off and on during an approval, one session at a time". While
the approval hangs: opt-out removes the entry; re-enable re-adds every
entry, keeps launches on the managed home, and starts no second
session; once Codex answers, the lane is installed and every entry is
approved.

* test(codex): a launch during the real-home approval shows what it waits on

Review loop 2, M2. The launch test's fake Codex failed every
managed-home session at once with ENOENT, so the managed home's own
approval was an instant "unsupported" fallback, and the test could not
show that a launch sent to the managed home still waits on that home's
inline approval when its ledger misses (first use, a Codex update, a
lost ledger), up to 10 s, as on main.

Now the managed-home session behaves like a real one:
- "settles on the managed home with its hooks and the project trust
  written": the managed app-server answers; two launches settle in
  under 2 s while the real-home approval hangs, and the second launch
  finds the managed approval in its ledger (one managed session).
- new "waits up to the managed home's own 10 s approval when that home
  is cold too": the managed session fails at its own deadline, as the
  real one does. The first launch is still pending at 9.999 s and
  settles on the managed home at 10 s; the request asked for 10 s. The
  next launch settles at once, because the failed inline approval cools
  down for 5 minutes.

No product change.

* refactor(codex): the managed and WSL installs own their pre-approval trust clear

Review loop 2, L7. Before a Codex approval session, a managed or WSL home
clears the approvals Orca itself computed, because on Windows its
fallback writes them under both path spellings and Codex's canonical key
may not overwrite the other one. The fallback writes them back if the
session fails. ~/.codex has no such fallback, so there the clear would
only delete Codex's own records (loop-1 H2). The grant module carried
this as a plan flag, fallbackWritesSelfComputedTrust, and took the
config.toml lane around the clear itself.

The reviewer proposed moving the clear into the two callers. A literal
move, clearing before the grant call, is NOT behaviour-neutral, so this
does not do that:
- The grant first checks its ledger, which compares the stored hash
  with the one Codex recorded. Codex's hash equals Orca's computed one
  (the premise of readOrcaEntryTrust), so a clear before that check
  deletes exactly the record the ledger proves. Every managed launch
  would then miss the ledger and run an inline session (up to 10 s).
- Checked, not inferred: with the clear moved before the call in the
  managed install, codex-launch-during-real-home-grant.test.ts "settles
  on the managed home..." fails (2 managed sessions instead of 1).
  Log: ~/orca-qa/codex-real-home-leak/fb6/l7-literal-move.log

What this does instead: each caller passes its clear as the grant's
`beforeSession` step, which the grant runs only when a session will
actually run (after a ledger miss, and not on a cooldown or cached
fallback), exactly where the flag ran it. So:
- the flag and its "never set for the real home" rule are gone; the
  real-home grant passes no step, so the grant module has no path left
  that deletes a trust record in ~/.codex;
- the grant module's own lane acquisition around the clear is gone. It
  was always a pass-through: both callers already hold that file's
  lane (the managed install holds the runtime and system lanes, the
  WSL install holds its config.toml lane) across the whole grant.

No behaviour change. The loop-1 probes still pass as fixed: trust-strip
prints every entry trusted after a failed re-grant, and lane-hold
prints managedInstall=settled projectTrust=settled.

Tests (codex-hook-trust-grant.test.ts):
- "removes equivalent Windows fallback keys before the RPC writes
  canonical trust" now passes the managed caller's step;
- new "runs the caller's pre-session step only when a session runs":
  the step runs once for a session and not on the ledger hit after it.

* chore(codex): comments stop describing a lock held across the session, or a rollback

Review loop 2, L6 comment sweep (comments and one test name only):
- codex-trust-config-concurrent-launch.test.ts: the test named "does not
  let a failing launch roll back a concurrent launch" said the per-file
  lane was the only thing left and that the doomed run's rollback must
  not resurrect the file. There is no lane across a session and no
  rollback now. Retargeted to what it covers: "leaves a concurrent
  grant's records in place when a sibling grant fails" (a restore would
  still turn it red).
- codex-trust-grant-ledger.ts: "a grant session blocks launch prep" is
  true only of inline grants; the background one still costs an
  app-server start. The drift clause no longer says "before the pane
  launches", which is false for the real home.
- agent-trust-write-deadline.ts: a stray hard wrap.
The install.ts:105 comment was fixed with L1. A sweep of src/main/codex,
src/main/startup, src/main/agent-hooks, the trust presets and the CLI
handlers for rollback, restore, rebase, capture/restore, and a lane held
across a grant or session found nothing else stale; the remaining "no
restore" comments state the current rule.

* fix(codex): a real-home resume waits for the one running approval, up to its 30 s limit

Review loop 2, M1; coordinator ruling. A resume into ~/.codex has no
managed home to fall back to. 5a737261d8c let it start at once beside an
Orca entry still awaiting Codex's approval. Codex's TUI then shows a
full-screen hook-review picker before the session and waits for keys:
"Trust all and continue" also trusts the user's own unreviewed hooks,
and "Continue without trusting" leaves that session with no Orca status
for its whole life, because Codex does not reload hooks when Orca's
approval lands later. Panes restored at app start after an update hit
it too, since the start-time conversion leaves every entry awaiting
approval.

The resume now waits, but only while Orca's entry in ~/.codex is
written and a grant is approving it (lane 'granting'). Every resume
waits on that same in-flight grant: ensure never starts a second one
while the lane is 'granting', so panes restored together share one
session. The bound is the grant's own session limit (30 s). The grant
settles only after Codex approved the entry, or after it withdrew its
own unapproved adds, so the resumed session starts either trusted or
with no Orca entry: never beside an unapproved one, and no picker. On
a withdrawal that session has no Orca status, as on main after its
10 s wait. A failed approval never fails the resume.

Tests (codex-launch-during-real-home-grant.test.ts):
- "waits for a warm approval, and spawns with the entries approved";
- "spawns at the approval session limit with Orca entries withdrawn"
  (fake timers: pending at 29.999 s, spawns at 30 s with no Orca entry);
- "makes panes restored together wait on one approval session" (three
  resumes, one session, all settle once it lands).
codex-launch-per-agent-hook-opt-out.test.ts: a resume into ~/.codex
awaits the approval; a resume into a managed account home does not.

* fix(codex): repeated background approval timeouts back off, growing to 5 minutes

Review loop 2, M3; coordinator ruling. A timeout of the ~/.codex
approval starts no cooldown, so the next launch retries at once. On a
host where codex app-server never starts within 30 s, every launch then
wrote Orca's entry into ~/.codex/hooks.json, withdrew it again, and
started another 30 s session, for the rest of the process: an unbounded
retry with no exit.

After 3 timeouts in a row the retry now waits 10 s, then 1 minute, then
5 minutes for every later one. The first two timeouts still retry on the
next launch, so a slow cold start is not punished. Any other outcome
ends the streak (a success, or any other failure, which keeps its own
10 s wait). The streak lives only in memory, so every app start begins
at zero and a slow boot can never latch.

Tests (codex-real-home-slow-app-server.test.ts):
- "backs off after three timeouts in a row, growing to 5 minutes, and a
  success resets it": the first two timeouts retry at once, then 10 s,
  1 min, 5 min, 5 min; after a success, a fresh approval gets two
  immediate retries again and a 10 s backoff after the third;
- "keeps trying after timeouts during a slow first start, once the app
  server answers": three timeouts, then the next attempt at 10 s
  installs.

* refactor(codex): one approval at a time, decided under the config.toml lane

The real-home check kept a lane label, a generation stamp, a promise chain of
ensures and a chain of approvals, and decided from the label at call time.
Concurrent resumes from any state other than 'granting' each started their own
approval (N x 30 s), a chained approval ran a plan an earlier failure had
withdrawn, a hooks-off check during an approval released a waiting resume beside
unapproved entries, and an app-start conversion during an approval was dropped.

Now each check is one step under the real config.toml lane: an approval in
flight answers 'approving' (unusable), hooks off answers 'removed', an open
retry window answers 'unavailable', and otherwise the unchanged install runs and
starts at most one approval. The approval settles under the lane: it withdraws
its own unapproved adds on failure, sets the retry, and derives the verdict from
the settings and the outcome, then runs an owed conversion. A resume waits only
while an approval runs and an unapproved Orca entry is on disk. The opt-out
sweep moves verbatim into its own module.

* fix(codex): only a success or app start resets the approval timeout streak

The ruling is that three timeouts in a row back off, and the count resets on
success and at app start. A non-timeout failure or an unexpected error also
reset it, so a host alternating those with timeouts never backed off.

* fix(codex): a Windows profile path the shells cannot carry bare runs through cmd.exe

The Windows hook command was the bare forward-slash script path, or, for a
profile path that is not one PowerShell word, a PowerShell script. That script
cannot parse under cmd.exe, which Codex uses when a session has no single local
turn shell, so such a profile got no status there.

A path of only letters, digits and _ . : / ~ - stays bare. Any other path,
including one with a space, & ^ $ ` ' ! ( ) or a non-ASCII character, is written
as cmd --% /d /c @"<path>", which ran under PowerShell 7, Windows PowerShell 5.1
and cmd.exe for each of those characters with a real Codex 0.158.0. The choice
depends only on the path, so every build on a machine writes the same bytes. A
machine holding the earlier PowerShell spelling converts it once at app start.

* build(cli): list the real-home hook sweep module in the CLI program

* fix(codex): the Windows cmd spelling names the system cmd.exe and turns off delayed expansion

A profile path the shells cannot carry bare was written as
cmd --% /d /c @"<path>". Under Codex's cmd.exe host the outer cmd.exe resolves
a bare `cmd` from the hook's working directory first, so a repo holding
cmd.bat (or .cmd, .com, .exe) at the session cwd would run on every hook event.
And with delayed expansion turned on in the registry, a `!` in the path was
dropped.

The spelling is now <SystemRoot>/System32/cmd.exe --% /d /v:off /c @"<path>",
unquoted (PowerShell reads a quoted first token as an expression) and with
forward slashes. The Windows directory comes from %SystemRoot% when written,
else from the directory above %ComSpec%'s System32, so both give the same bytes;
if neither is a drive-absolute path it can spell unquoted, it is C:/Windows,
which is still absolute. The bytes stay a pure function of the profile path and
that directory, so every build on a machine writes the same command. Safe
profile paths keep the bare path. Older Orca forms, including the bare-cmd
spelling, convert once; the new spelling is never swept as retired.

* refactor(codex): an approval's settle runs no deferred conversion

An app-start conversion that arrived while an approval ran was remembered and
run by that approval's settle. The settle then rewrote an older entry in place,
unapproved, and started a second approval inside the same wait that releases
every resume, so a resume could start beside an entry Codex would put up for
review.

That path could not happen: the only conversion caller is app start, and it is
the process's first check, so no approval can be running when it arrives. The
deferral and the settle's second check are deleted. A conversion that met an
approval would now be skipped until the next start, and the test for this case
pins that the settle writes nothing new and runs one session.

* fix(codex): an approval's settle keeps a failed opt-out's verdict and ends only its own flight

With hooks read off, an approval's settle always concluded 'removed', which the
routing check treats as usable. If an opt-out during that approval could not
read hooks.json, it had concluded 'unavailable' because the entry may still be
there, and the settle overwrote that. The settle now keeps 'unavailable' when
hooks are off; the next hooks-off check or opt-out re-derives it as before.

The settle's fallback when it cannot run now clears the running approval only
if it is still its own, and the routing check's comment states its rule: never
usable while an approval runs.

* fix(codex): spell the system cmd.exe with backslashes

Under Codex's cmd.exe host the outer cmd.exe hands the typed program text to
the child verbatim, and cmd.exe scans its whole command line for switches, so a
forward-slash C:/Windows/System32/cmd.exe is read as switches: the hook never
runs ("The syntax of the command is incorrect.") and /d is lost. Measured live
on Windows; both PowerShell hosts rewrite argv0 and were unaffected. The script
path after @" keeps forward slashes.

* chore(codex): say why the cmd.exe path is absolute, as measured on Windows

* test(codex): Windows managed-install tests expect the frozen command

They still asserted main's PowerShell text and a backslash bare path; they only
run on Windows, so nothing here caught it. Also correct the /v:off comment: a
lone ! is never dropped, only a !NAME! pair expands.

* ci: run the Codex managed-install tests in the Windows job

Its Windows-only cases skip everywhere else, so nothing ran them; three of them
still asserted a command this branch no longer writes.

* ci: a change to the Codex managed-install tests starts the Windows job

Also say what the missing-script case asserts: a non-zero exit, which
PowerShell reports as 1.

* chore(codex): name the hook trust key pattern for what it matches

* test(codex): the managed-install tests remove folders with the retrying helper

Now that they run in the Windows lane, a raw recursive rm there can throw EPERM
after the assertions pass.

* refactor(codex): one Codex hook-trust key pattern for the trust move and #23958's carry

* test(codex): the trust move carries a block in Codex's quoted spelling and leaves no second table

(cherry picked from commit cfa43e7eaba15b977ea63e2b85897de8c5f8d9d1)
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.

1 participant