Skip to content

fix(codex): emit neutral JSON from the managed Codex hook - #16439

Closed
maxmilian wants to merge 4 commits into
stablyai:mainfrom
maxmilian:fix/16356-codex-hook-neutral-json
Closed

maxmilian wants to merge 4 commits into
stablyai:mainfrom
maxmilian:fix/16356-codex-hook-neutral-json

Conversation

@maxmilian

@maxmilian maxmilian commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Codex refuses any hook whose output isn't JSON. Orca's Codex hook printed nothing, so Codex marked session start and stop as failed even though the hook's real work succeeded. This prints {} first, which is what Orca's Claude, Gemini, Copilot and Antigravity hooks already do.

What Changed

src/main/codex/hooks/definitions/codex-hook-script.ts, in getManagedScript (+4 lines):

  • POSIX branch: printf "{}\n" immediately after #!/bin/sh, before the payload capture and the tmux pane capture.
  • Windows .cmd branch: echo {} immediately after setlocal.

Placement matters: both branches exit 0 without posting when the payload or the ORCA_* environment is missing, so neutral JSON emitted later would never run.

Tests:

  • src/main/codex/hooks/installation/windows-hook-command.test.ts: its two stdout expectations change from '' to '{}\r\n'.
  • src/main/codex/hooks/definitions/codex-hook-script-neutral-json.test.ts (new, 49 lines) pins the ordering on both branches. Given the "tests are the exception" rule from test: cut the suite to the tests that guard real invariants #46786, I'm happy to drop it if you'd rather not carry it.

Why

Codex fails closed on a hook whose stdout is not valid JSON, so a Codex session launched from an Orca terminal reported:

• SessionStart hook (failed)  error: hook returned invalid session start JSON output
• Stop hook (failed)          error: hook returned invalid stop hook JSON output

The hook's actual job was fine: the POST to the local hook endpoint went through. What broke was only the stdout contract, and the cost is that users learn to ignore red hook errors, including real ones.

On current main the Claude, Gemini, Copilot and Antigravity managed hooks each print neutral JSON; Codex is the one that doesn't. {} is a neutral response because every field in Codex's hook output schema is optional.

Scope

This covers what #16356 reports: a Codex session started from an Orca terminal.

An earlier version of this description said the fix also covered sessions launched from a plain terminal. On POSIX that does not hold. The installed command (codex-hook-command-form.ts) runs the script only when ORCA_PANE_KEY is set and otherwise just drains stdin, so outside Orca nothing here changes. The test that asserted empty stdout outside Orca (hook-script-outside-orca.test.ts) was removed by #46786, and this PR no longer touches it.

Linked Issue

Fixes #16356

Visual Proof

N/A. No UI surface; this changes a generated shell script.

Testing

On the rebased head b1adf3b2af (base f2f0cce6e4), macOS, Node 24:

  • The generated POSIX script (getManagedScript('posix')) run under sh, bash and dash: with main's script stdout is empty; with this branch it is {}. Exit 0 both ways.
  • The real hook command from buildCodexHookCommand(), with a pane key and port set: empty stdout with main's script, {} with this one. Without a pane key: empty in both.
  • The ordering test: 2 passed, and both fail when the script is reverted to main's version.
  • pnpm check:changed: 26 checks passed.

⚠️ Not run on Windows. I have no Windows host, and windows-hook-command.test.ts is skipped on macOS. echo {} sits at the same position relative to setlocal as the line in Claude's .cmd hook. Worth a reviewer's eye on a real Windows box.

I did not run the Codex CLI against the fixed hook; that the empty stdout is what Codex rejects rests on the report in #16356 and the follow-up there.

AI Disclosure

Written with Claude Code. The checks above were run on the rebased head.

Review

  • Cross-platform: both branches changed symmetrically. POSIX uses printf, a shell builtin, so it adds no process and behaves the same under sh/dash/bash. Windows not tested on Windows (see Testing).
  • Agent/integration compatibility: Codex only; no shared helper touched. {} carries no decision, so it cannot alter a permission or turn outcome.
  • Security: no new input handling or process spawn; the emitted string is a constant.
  • Regression risk: additive in the script (+4 lines, 0 removed). The early-exit guards, payload capture and tmux pane capture are untouched.

@coderabbitai

coderabbitai Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review.

Walkthrough

Managed Codex hook scripts print {} followed by a newline before hook processing and early exits on POSIX and Windows. Tests check output order for generated scripts, neutral JSON output when hooks run outside an Orca terminal, and stdout from Windows hook command invocations.

Severity of issue fixed: Low

Merge Risk: Minimal · up to 3db01

The hooks emit neutral JSON without delivery output contaminating it. No concrete merge-blocking risk remains.

Architecture risk: Low · up to 3db01

The change affects 1 system.

Changed systems: src

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — src (service) was modified; 4 changed files map to changed impact.

Before / after behavior

  • observed — Modified behavior in src/main/codex/codex-hook-script.ts: The Windows batch hook script now emits echo {} right after setlocal so stdout begins with valid JSON before any endpoint sourcing or curl post occurs.
  • observed — Modified behavior in src/main/codex/codex-hook-script.ts: The POSIX shell hook script now emits printf "{}\n" immediately after the shebang so stdout begins with valid JSON before payload capture, spooling, or the curl post runs.
  • observed — Modified behavior in src/main/codex/hook-service-neutral-json.test.ts: Sets up the Electron mock with a system-temporary user-data path, imports the hook-material generator, provides platform-specific script generation, and restores the original platform descriptor after each test.
  • observed — Modified behavior in src/main/codex/hook-service-neutral-json.test.ts: Adds POSIX and Windows assertions that managed hook scripts emit neutral JSON before early exits; the Windows test additionally requires echo {} to immediately follow setlocal.
Pre-merge checks: Passed 4

Check name Status Explanation
Linked Issues check Passed The PR satisfies #16356. src/main/codex/codex-hook-script.ts emits printf "{}\\n" immediately after the POSIX shebang and echo {} immediately after Windows setlocal. The existing payload and en…
Out of Scope Changes check Passed The changed files support #16356. The source change adds the required Codex hook output. The tests verify POSIX and Windows ordering, delivery behavior, and inert behavior outside an Orca terminal. No…
Title check Passed The title "fix(codex): emit neutral JSON from the managed Codex hook" states the main change. The changeset adds an early {} output to the managed Codex POSIX and Windows hook scripts, and updates t…
Description check Passed The description follows the repository template. It includes ELI5, What Changed, Why, Linked Issue (Fixes #16356), Visual Proof (N/A with reason), Testing, Performance, Risk, AI Disclosure, Review, an…
Full details: Linked Issues check

Explanation

The PR satisfies #16356. src/main/codex/codex-hook-script.ts emits printf "{}\n" immediately after the POSIX shebang and echo {} immediately after Windows setlocal. The existing payload and environment guards remain after this output, so early exits and successful hook processing remain available. Tests verify output ordering before early exits on both platforms and verify delivery output on Windows. The outside-Orca tests verify valid neutral JSON with exit 0, empty stderr, and no spool files.

Full details: Out of Scope Changes check

Explanation

The changed files support #16356. The source change adds the required Codex hook output. The tests verify POSIX and Windows ordering, delivery behavior, and inert behavior outside an Orca terminal. No unrelated product behavior is shown.

Full details: Title check

Explanation

The title "fix(codex): emit neutral JSON from the managed Codex hook" states the main change. The changeset adds an early {} output to the managed Codex POSIX and Windows hook scripts, and updates tests to match. The title is specific and concise, and it follows a conventional commit style.

Full details: Description check

Explanation

The description follows the repository template. It includes ELI5, What Changed, Why, Linked Issue (Fixes #16356), Visual Proof (N/A with reason), Testing, Performance, Risk, AI Disclosure, Review, and Notes sections. It explains the mechanism, placement rationale, scope, and cross-platform limits. The Risk section names no level, and the Performance section is one line. The Windows path is untested on a Windows host, and the author discloses this. The author also left the Agent skill upstream boundary checkbox unchecked. The Risk section does not state a rollback method. The Performance section gives a one-line answer.

Resolution

Optional tidy-ups: state a Risk level (Low, Medium, or High) and a rollback method, such as a plain revert. Also mark the Agent skill upstream boundary checkbox if it applies.

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

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

ℹ️ Recent review info

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 8448168f-7d87-440d-8c5f-81d1cf3e2240

📥 Commits

Reviewing files that changed from the base of the PR and between 8b24213 and 3db015b.

📒 Files selected for processing (1)

  • src/main/codex/windows-hook-command.test.ts

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

@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

🧹 Nitpick comments (1)
src/main/codex/hook-service-neutral-json.test.ts (1)

5-5: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Build the mocked app-data path portably.

Use path.join or another Node path utility instead of '/tmp/orca-user-data'.

As per coding guidelines: “File paths: Use path.join or Electron/Node path utilities — never assume / or \.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 654281d9-169d-48a3-a22c-a1cf971b876d

📥 Commits

Reviewing files that changed from the base of the PR and between 822087c and 31828cf9862b10e140db40701c3121e80601a0c3.

📒 Files selected for processing (2)
  • src/main/codex/hook-service-neutral-json.test.ts
  • src/main/codex/hook-service.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@maxmilian

Copy link
Copy Markdown
Contributor Author

Thanks — both taken.

1. Windows assertion. You're right that echo {} merely preceding exit /b would still pass if the endpoint load were moved ahead of the neutral JSON, which is exactly the regression this test exists to catch. It now asserts the exact offset, matching the precision the POSIX case already used:

expect(lines.indexOf('echo {}')).toBe(lines.indexOf('setlocal') + 1)

That matches the real generated script (@echo off → setlocal → echo {} → endpoint load), so no loosening was needed. I dropped the now-redundant toBeGreaterThan(-1) — if neither line is found, -1 !== 0 still fails — and kept the exit /b assertion, since it guards the separate property that the JSON precedes every early exit.

2. path.join. The mocked userData path is now built with os.tmpdir() + path.join. The vi.mock factory had to become async so the node:os / node:path imports survive hoisting.

vitest (2 passed), pnpm lint and pnpm typecheck are all green in 481f330d4.

@coderabbitai

coderabbitai Bot commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@greptile-apps

greptile-apps Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Hook script now emits neutral JSON on startup.

The PR appears safe to merge based on the reviewed changes.

Summary

The PR makes the managed Codex hook emit neutral JSON before its early exits, so Codex receives a valid response even when Orca does not post an event.

  • Updates outside-Orca and Windows expectations and adds script-ordering tests.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Codex invokes managed hook] --> B[Emit neutral JSON]
  B --> C{Orca context available?}
  C -->|No| D[Exit successfully]
  C -->|Yes| E[Attempt event delivery]
  E --> F[Exit successfully]
Loading

Reviews (3) · Last reviewed commit: "test(codex): expect neutral JSON from Wi..."

@maxmilian

Copy link
Copy Markdown
Contributor Author

Rebased onto d607a6367 — this was CONFLICTING after #17260 split hook-service.ts. The builder moved to src/main/codex/codex-hook-script.ts, so the two lines now land there, at the same positions relative to setlocal and #!/bin/sh. New head 54f6a1373.

One thing needs a maintainer's call. src/main/agent-hooks/hook-script-outside-orca.test.ts, added in #16685 after this PR was opened, asserts the managed Codex hook is silent (stdout === '') outside an Orca terminal. That silence is precisely the failure #16356 reports: Codex fails closed on non-JSON hook stdout, and the managed hook is installed into the user's Codex config, so it also runs for sessions launched from a plain terminal — exactly where an empty stdout produces invalid session start/stop hook JSON output. As written, the test pins the bug rather than the contract.

Every sibling hook already prints neutral JSON unconditionally, in the same position, on current main: claude/hook-service.ts:71,99, gemini/hook-service.ts:60,74, copilot/copilot-managed-script.ts:57, antigravity/hook-script.ts:30,53,103. The test covers only Codex, so it passes today solely because Codex is the one agent still missing the line. I changed those four stdout assertions to expect {}\n; the inertness they actually guard — exit 0, empty stderr, no spool tree written — is unchanged and still asserted (all four still pass on their other assertions).

If the intent of #16685 was that Codex specifically must stay byte-silent outside Orca, say so and I'll gate the neutral JSON on the Orca environment instead — but that leaves #16356 unfixed for out-of-terminal sessions, which is the majority of them.

Verified on the new base: pnpm typecheck and pnpm lint clean; vitest src/main/codex src/main/agent-hooks src/main/claude → 2472 passed, 0 failed. Red-before-green re-confirmed (expected -1 to be 2 without the fix). Running the generated script by hand: sh/bash/dash × payload-present/empty, all six → stdout=[{}] exit=0 stderr=[], and json.load accepts it. Windows branch still unverified on a real Windows host, as noted in the description.

The PR description is updated to match the new file layout and carries the same note.

@maxmilian

Copy link
Copy Markdown
Contributor Author

Bumping the one open question here, since it's a maintainer decision rather than anything I can settle on the branch.

This PR changes four stdout assertions in src/main/agent-hooks/hook-script-outside-orca.test.ts (added by #16685) from '' to {}\n. I believe that test pins the #16356 bug rather than a contract — every sibling hook already prints neutral JSON unconditionally on main (claude/hook-service.ts:71,99, gemini/hook-service.ts:60,74, copilot/copilot-managed-script.ts:57, antigravity/hook-script.ts:30,53,103), and the test passes today only because Codex is the last one missing it. The inertness #16685 actually guards — exit 0, empty stderr, no spool tree — is untouched and still asserted.

But it is someone else's test, so I don't want to land the change on my own reading. Two ways forward:

  1. Confirm the neutral JSON is the intended contract, and this goes in as-is.
  2. If Codex specifically must stay byte-silent outside an Orca terminal, say so and I'll gate the JSON on the Orca environment instead — with the caveat that this leaves [Bug]: codex-hook.sh emits no stdout — every Codex session reports "invalid session start/stop hook JSON output" #16356 unfixed for sessions launched from a plain terminal, which is where the managed hook mostly runs.

Current head 54f6a1373 is rebased onto d607a6367; pnpm typecheck / pnpm lint clean, vitest src/main/codex src/main/agent-hooks src/main/claude → 2472 passed / 0 failed, and Greptile is green. Happy to take either route.

@maxmilian
maxmilian force-pushed the fix/16356-codex-hook-neutral-json branch from 54f6a13 to 8b24213 Compare October 1, 2026 15:46

@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 · Update the Windows stdout assertions. · codex-hook-script.ts:15-16

src/main/codex/codex-hook-script.ts:15-16
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Update the Windows stdout assertions.

On Windows, echo {} writes '{}\r\n'. runProcess preserves that output. The Windows-only test currently expects stdout: '' for successful and server-close runs, so it fails. Keep the neutral JSON output and update both expectations.

Suggested fix
-            .map((payload) => invoke(getManagedCommand(scriptPath), payload))
+            .map((payload) => invoke(getManagedCommand(scriptPath), payload))
           )
           for (const result of results) {
-            expect(result).toMatchObject({ code: 0, stdout: '', stderr: '', timedOut: false })
+            expect(result).toMatchObject({
+              code: 0,
+              stdout: '{}\r\n',
+              stderr: '',
+              timedOut: false
+            })
           }
@@
         expect(await invoke(getManagedCommand(scriptPath), payloads[0])).toMatchObject({
           code: 0,
-          stdout: '',
+          stdout: '{}\r\n',
           stderr: '',
           timedOut: false
         })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 40597da9-5a2e-4eb1-9fd9-635431b989ab

📥 Commits

Reviewing files that changed from the base of the PR and between 54f6a137389f06705dd25df91f299bfce384ccba and 8b24213.

📒 Files selected for processing (1)
  • src/main/agent-hooks/hook-script-outside-orca.test.ts

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

@maxmilian

Copy link
Copy Markdown
Contributor Author

Rebased onto main c9918931; current head is 3db015b4. The sole conflict came from #23981 removing the redundant “pane key present but no endpoint” case; I kept that deletion. The production change and remaining three outside-Orca assertions are unchanged.

I also fixed the two Windows delivery/fallback assertions flagged by CodeRabbit: the generated batch script intentionally prints neutral JSON first, so both now expect {}\r\n rather than empty stdout.

The latest three targeted suites pass through Node/Vitest: 13 passed, 1 Windows-native test skipped. The earlier four related suites passed 30 tests with 4 skips before the two assertion corrections. Fresh-context Codex reviews found no correctness blocker in either the rebase or the Windows test correction. Native Windows execution was not rerun.

This refresh does not resolve the outstanding outside-Orca stdout contract question from my September 7 comment.

@maxmilian

Copy link
Copy Markdown
Contributor Author

Rebased onto 83f8e6340d. The Codex hook modules moved under src/main/codex/hooks/ (#38023), so the neutral-JSON test now sits next to codex-hook-definition.ts.

#24641 added a fourth outside-Orca case (Claude background job) that also asserts empty stdout. I changed it to {}\n for the same reason as the other three: Codex still parses this hook's stdout under a Claude job, so an empty reply fails closed there too.

The question from 09-07 still stands. If the empty-stdout contract in hook-script-outside-orca.test.ts is intentional, I'm happy to reshape this.

@maxmilian
maxmilian force-pushed the fix/16356-codex-hook-neutral-json branch from e28ccec to f47f004 Compare November 18, 2026 06:05
maxmilian and others added 4 commits November 22, 2026 23:04
Codex fails closed on a hook whose stdout is not valid JSON, so every session
started from an Orca terminal reported "invalid session start/stop hook JSON
output" even though the POST to Orca's listener succeeded (stablyai#16356).

The managed Codex script never wrote anything to stdout. Its siblings all do:
claude (stablyai#14818), gemini, copilot and antigravity each emit neutral JSON as the
first line, before any early-exit guard. Codex was the only one without it.

Rebased onto the module split from stablyai#17260: the builder moved from
hook-service.ts to codex-hook-script.ts, so the two lines land there instead.
Move the neutral-JSON test next to codex-hook-definition after the Codex hook modules moved under hooks/.
@maxmilian
maxmilian force-pushed the fix/16356-codex-hook-neutral-json branch from f47f004 to b1adf3b Compare November 22, 2026 15:08
@maxmilian

Copy link
Copy Markdown
Contributor Author

Rebased onto f2f0cce6e4; new head b1adf3b2af. Two things on main conflicted:

That also retires the question I raised on 09-07. The test asserting empty stdout is gone, and the POSIX command in codex-hook-command-form.ts only runs the script inside an Orca pane, so outside Orca nothing here changes: the wrapper still just drains stdin. My earlier claim that this PR also covered sessions launched from a plain terminal no longer holds on POSIX. The fix is now scoped to what #16356 reports, a Codex session started from an Orca terminal.

Checked on the rebased head (macOS, Node 24):

  • Generated POSIX script run under sh, bash and dash: main prints nothing, this branch prints {}, exit 0 both ways.
  • The real hook command with a pane key and port set: empty stdout with main's script, {} with this one. Without a pane key: empty in both.
  • pnpm check:changed: 26 checks passed.

Not run on Windows; windows-hook-command.test.ts is skipped on macOS.

The diff is now +4 lines in codex-hook-script.ts, the two Windows stdout expectations, and the ordering test. Given the new "tests are the exception" rule I'm happy to drop the ordering test if you'd rather not carry it. I've updated the PR description to match.

@nwparker

Copy link
Copy Markdown
Contributor

Thank you for the PR. Closing it because the root cause doesn't hold up. Codex's hook runner treats empty stdout as success for both SessionStart and Stop, and the "invalid ... JSON output" error only fires when stdout is non-empty and fails to parse. A leading {} can't turn failing output into passing output, since the whole trimmed stdout is parsed. Orca's managed hook already writes nothing to stdout. I'm following up on #16356 to find out what's actually writing to stdout there.

@nwparker nwparker closed this Nov 26, 2026
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]: codex-hook.sh emits no stdout — every Codex session reports "invalid session start/stop hook JSON output"

2 participants