Skip to content

fix(codex): skip the Codex hook under a Claude background job - #24641

Merged
nwparker merged 1 commit into
stablyai:mainfrom
stakost:fix/codex-hook-claude-background-job
Oct 26, 2026
Merged

nwparker merged 1 commit into
stablyai:mainfrom
stakost:fix/codex-hook-claude-background-job

Conversation

@stakost

@stakost stakost commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When Claude Code runs a task in the background, its helper process keeps the Orca pane variables of whichever pane first started it. If that background task runs codex exec, Orca's Codex hook reported the run against that old pane, so a pane running Claude got labelled "Codex". The Claude hook already ignores events from Claude background jobs. This change makes the Codex hook ignore them too.

What Changed

Before: a codex exec under a Claude background job (CLAUDE_JOB_DIR set) inherited the dispatching pane's ORCA_* env. The managed Codex hook posted, or spooled, events with that pane's key, so an unrelated pane showed a Codex run that never happened there.

After: the Codex hook exits quietly when CLAUDE_JOB_DIR is non-empty. Nothing is posted and nothing is spooled. Codex runs that are not under a Claude background job behave as before.

Mechanism:

  • New src/main/agent-hooks/claude-background-job-guard.ts holds the one shared guard: WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD (cmd) and buildPosixClaudeBackgroundJobGuardLines() (sh). The Claude hook, the Claude statusline script, the Windows Claude entry and the Codex hook all use it now, in place of their inline copies. The generated Claude hook and statusline scripts are byte-identical to main. All 72 script variants were checked.
  • Codex POSIX script: the guard runs after stdin is captured and before the endpoint loads, so Codex never sees EPIPE.
  • Codex Windows .cmd script: the guard runs right after the existing env guards. It is an exit /b 0 before curl reads stdin, so an abandoned stdin cannot hang the hook ([Bug]: Codex managed hook leaves persistent cmd.exe windows outside Orca on Windows #11549).
  • PTY spawns (getInheritedAgentSessionStampEnvKeysToDelete) now drop an inherited CLAUDE_JOB_DIR. A pane is never a Claude background job, so an Orca launched from inside one no longer silences its panes' Claude and Codex hooks.
  • Hook tests that run the real scripts pin CLAUDE_JOB_DIR: '', so a test runner started inside a Claude background job still exercises the posting path.

Why

CLAUDE_JOB_DIR is the signal the Claude hook already uses for background jobs (#15304). With this change both hooks agree. Real per-process pane attribution (#23643) needs a process lookup that is not reliable on every platform, WSL and SSH included, so this PR takes only the part that is safe today. One shared guard replaces three copies of the same lines, so they cannot drift apart.

Out of scope: a foreground Claude running codex exec in the same pane (#13341).

Linked Issue

Fixes #24516

Visual Proof

N/A. Nothing on screen changes. The fix is in the text of a generated hook script and in the PTY env. Instead, here is a probe that runs the generated POSIX Codex hook with a fake curl and an inherited pane env:

main   job-set:        exit=0 curl_calls=1 spool=pane-tab_0.jsonl
main   job-empty:      exit=0 curl_calls=1 spool=pane-tab_0.jsonl
main   job-unset:      exit=0 curl_calls=1 spool=pane-tab_0.jsonl
branch job-set:        exit=0 curl_calls=0 spool=none
branch job-set+set-e:  exit=0 curl_calls=0 spool=none
branch job-empty:      exit=0 curl_calls=1 spool=pane-tab_0.jsonl
branch job-unset:      exit=0 curl_calls=1 spool=pane-tab_0.jsonl

The diff of the generated scripts versus main is only the added guard lines: one if not "%CLAUDE_JOB_DIR%"=="" exit /b 0 in codex-hook.cmd and a 3-line if [ -n "$CLAUDE_JOB_DIR" ] block in codex-hook.sh.

Testing

  • Reproduced on main: the new case in hook-script-outside-orca.test.ts (real Codex POSIX script, inherited pane env, CLAUDE_JOB_DIR set, unreachable endpoint) fails because the failed post leaves a spool dir. It passes on this branch.

  • Added a drain-before-skip case in managed-hook-stdin-lifecycle.test.ts (POSIX, no EPIPE). Added codex-hook.cmd with CLAUDE_JOB_DIR to the Windows open-stdin skip list, which runs on Windows CI.

  • Added a PTY spawn env case: an inherited CLAUDE_JOB_DIR is stripped.

  • pnpm test over src/main/claude/, src/main/codex/ and the touched agent-hooks and PTY test files: 357 files, 3847 tests passed on macOS.

  • oxlint and oxfmt passed on the changed files (pre-commit).

  • Platforms: macOS run locally. Windows cmd behaviour is covered by the Windows-only stdin lifecycle case in CI. SSH and WSL use the same POSIX script, and each host refreshes its own managed script, so mixed client/server versions are unaffected.

  • I manually tested these changes locally

  • Automated tests added/updated

Notes

Original fix by @stakost in #24641; maintainer follow-ups add the shared statusline guard, Windows and drain coverage, and the PTY env strip.

@coderabbitai

coderabbitai Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Walkthrough

Shared Windows and POSIX guards now check whether CLAUDE_JOB_DIR is nonempty. Claude hook and statusline scripts and Codex hook scripts use these guards. The PTY spawn environment also removes inherited CLAUDE_JOB_DIR. Tests cover background-job skips, stdin handling, and the absence of the variable in spawned environments.

Priority: Normal

Severity of issue fixed: Medium

Merge Risk: Low · up to bd44f

A narrow PTY configuration path can misattribute background Codex hook events; preserve explicitly configured CLAUDE_JOB_DIR before merging.

Security architecture risk: Low · up to 063d4

The change prevents background work from being reported against an inherited pane identity. No exploitable security regression was established. Windows handling remains less certain because the worker-directory value is expanded into command syntax and its production trust boundary was not established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — The affected reporting sinks include pane-attributed posts to loopback hook endpoints and endpoint-adjacent spool files. The guard precedes these event-producing operations in both consumers.

Security Findings and Attack Paths

  • inferred — Windows newly adds CLAUDE_JOB_DIR expansion to the Codex command stream; the same expression already existed for Claude. Whether hostile contents can cross a trust boundary remains unresolved because the production producer and attacker influence were not established. This is an evidence gap, not a verified injection finding.

Trust Boundaries and Controls

  • observed — Windows calls the environment-selected endpoint script before background-job suppression. That ordering predates this PR, so suppression is not a sandbox against endpoint-script execution. POSIX Codex exits before loading the endpoint.

Resilience and Maintainability Implications

  • inferred — After reaching the guard, repeated or concurrent suppressed invocations have no event-state commit to retry, roll back, or clean up. Transport failures and spool fallback are unreachable on that branch. Existing posted or spooled events are not removed.

Hardening Proposals

  • proposed — Consider a Windows presence-only check such as if defined CLAUDE_JOB_DIR so the directory value is not expanded into command syntax. This is defensive hardening, not remediation of a demonstrated vulnerability.
Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Linked Issues check Warning Issue #24516 requires agent hooks to attribute events only to a pane where the process runs. This pull request adds a CLAUDE_JOB_DIR skip for Codex hooks and removes inherited CLAUDE_JOB_DIR from … Implement and test a pane-attribution check for the affected agent hooks. The check must confirm that the process runs in the pane identified by ORCA_PANE_KEY, or reject the event when ownership cannot be confirmed. Keep the `CLAUDE_JOB_D…
Docstring Coverage Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 13 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 3 passed
Check name Status Explanation
Title check Passed The title clearly identifies the main change: the Codex hook skips execution under a Claude background job.
Description check Passed The description is complete and directly matches the changes. It explains the user impact, mechanism, rationale, scope, linked issue, testing, and the absence of visual changes. Some optional template…
Out of Scope Changes check Passed The changed code supports the linked issue. The shared guard prevents false Codex events from Claude background jobs. The Claude hook and statusline refactors preserve one shared guard implementation.…
Full details: Description check

Explanation

The description is complete and directly matches the changes. It explains the user impact, mechanism, rationale, scope, linked issue, testing, and the absence of visual changes. Some optional template sections, such as Review and Checklist, are not included, but the required information is otherwise covered.

Full details: Out of Scope Changes check

Explanation

The changed code supports the linked issue. The shared guard prevents false Codex events from Claude background jobs. The Claude hook and statusline refactors preserve one shared guard implementation. The PTY environment change prevents an Orca-launched pane from inheriting the background-job suppression signal. The tests cover guard behavior, stdin handling, spool suppression, and PTY environment cleanup. No unrelated product change is demonstrated.

Full details: Linked Issues check

Explanation

Issue #24516 requires agent hooks to attribute events only to a pane where the process runs. This pull request adds a CLAUDE_JOB_DIR skip for Codex hooks and removes inherited CLAUDE_JOB_DIR from PTY environments. The Codex script still uses inherited ORCA_* values when CLAUDE_JOB_DIR is empty or unset. The change does not verify the process terminal or parent chain against ORCA_PANE_KEY, including the foreground-Claude codex exec case that the PR marks out of scope. The added tests verify the background-job skip and stdin handling, not general pane ownership.

Resolution

Implement and test a pane-attribution check for the affected agent hooks. The check must confirm that the process runs in the pane identified by ORCA_PANE_KEY, or reject the event when ownership cannot be confirmed. Keep the CLAUDE_JOB_DIR guard as a mitigation if required.

  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.

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.

@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 — one minor test observation inline.

Reviewed changes

  • Shared background-job guard extracted — the three inline CLAUDE_JOB_DIR guard lines move from src/main/claude/hook-script.ts into src/main/agent-hooks/claude-background-job-guard.ts as POSIX and Windows builders, matching the grok-replay-guard.ts shape.
  • Claude hook reuses the builder at the same position — POSIX after the Devin skip and before buildHookProcessCapture, Windows after the env guards; the re-export of WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD keeps windows-hook-files.ts importing unchanged.
  • Codex hook now applies the guard — POSIX after buildPosixHookSpoolLines and before endpoint load, Windows after the env guards and before the curl post, so a codex exec under a Claude background job neither posts nor spools.
  • New test exercises the generated POSIX script against a fake curl, plus a text check that the Windows guard precedes the post.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

const { res, curlCalls, spoolExists } = runCodexHook({ CLAUDE_JOB_DIR: '/fake/job' })
expect(res.status).toBe(0)
expect(curlCalls).toBe(0)
expect(spoolExists).toBe(false)

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 assertion cannot currently fail: the test always supplies ORCA_AGENT_HOOK_ENDPOINT, ORCA_AGENT_HOOK_PORT, ORCA_AGENT_HOOK_TOKEN and ORCA_PANE_KEY, so the unguarded path takes the curl branch and never reaches spool_hook_event either. Dropping the vars (or a second case without them) would let the no-spool claim actually pin the guard. Non-blocking — the curlCalls assertions carry the test.

Claude background-job workers, and the `codex exec` runs they spawn,
inherit the dispatching pane's ORCA_* env, so the Codex hook posted
events against a pane the run never lived in. The Codex hook now exits
when CLAUDE_JOB_DIR is set, like the Claude hook already does.

The guard moves into agent-hooks/claude-background-job-guard.ts and is
shared by the Claude hook, Claude statusline, Windows Claude entry and
Codex hook. POSIX exits after stdin capture; Windows exits before
owning stdin so an abandoned stdin cannot hang the drain.

Pane spawns now drop an inherited CLAUDE_JOB_DIR so an Orca launched
from a Claude background job does not silence its panes' hooks.

Fixes stablyai#24516

Co-authored-by: Neil <[email protected]>
@nwparker
nwparker force-pushed the fix/codex-hook-claude-background-job branch from 063d434 to bd44f35 Compare October 26, 2026 13:47

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (1)

Minor · Preserve an explicitly configured CLAUDE_JOB_DIR. · pi-agent.ts:145-155

src/main/ipc/pty/host-env/pi-agent.ts:145-155
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Preserve an explicitly configured CLAUDE_JOB_DIR.

PtySpawnIpcArgs.env accepts explicit child environment values, and the runtime copies that value into the PTY spawn environment. This helper still adds CLAUDE_JOB_DIR to envToDelete, so the provider removes it after merging the child environment. The Codex hook then misses its background-job guard and can post or spool an event.

Suggested fix
   return [
     ...CLAUDE_CHILD_SESSION_STAMP_ENV_KEYS.filter((key) => env[key] === undefined),
     ...ORCA_AGENT_SESSION_CALLER_ENV_KEYS,
-    // A pane is never a Claude background job; an inherited job dir would silence its agent hooks.
-    'CLAUDE_JOB_DIR'
+    ...['CLAUDE_JOB_DIR'].filter((key) => env[key] === undefined)
   ]

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 295bc116-28c4-4895-9a89-79b6f8af0efe
Commits

Reviewing files that changed from the base of the PR and between 063d434 and bd44f35.

Files selected for processing: 12
  • src/main/agent-hooks/claude-background-job-guard.ts
  • src/main/agent-hooks/hook-script-outside-orca.test.ts
  • src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts
  • src/main/agent-hooks/managed-hook-timeout.test.ts
  • src/main/agent-hooks/spool.test.ts
  • src/main/claude/hook-script.ts
  • src/main/claude/statusline-script.ts
  • src/main/claude/windows-hook-files.ts
  • src/main/codex/codex-hook-script.ts
  • src/main/codex/hook-service-wsl-runtime.test.ts
  • src/main/ipc/pty/host-env/pi-agent.ts
  • src/main/ipc/pty/pty-spawn-env-terminal-basics.test.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.

@nwparker
nwparker merged commit 2bcf5b2 into stablyai:main Oct 26, 2026
41 checks passed
maxmilian added a commit to maxmilian/orca that referenced this pull request Nov 8, 2026
Move the neutral-JSON test next to codex-hook-definition after the Codex hook modules moved under hooks/, and expect '{}' from the Claude background-job guard path (stablyai#24641) too: Codex still parses the hook's stdout there, so an empty reply fails closed the same way (stablyai#16356).
maxmilian added a commit to maxmilian/orca that referenced this pull request Nov 18, 2026
Move the neutral-JSON test next to codex-hook-definition after the Codex hook modules moved under hooks/, and expect '{}' from the Claude background-job guard path (stablyai#24641) too: Codex still parses the hook's stdout there, so an empty reply fails closed the same way (stablyai#16356).
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.

[Bug]: Agent hooks attribute a process to the pane in its inherited ORCA_* env, so a pane is relabelled by an agent running elsewhere

2 participants