Skip to content

feat(integrations): add suv init codex for first-class Codex integration - #31

Merged
MadhuAppachi merged 1 commit into
AppachiTech:devfrom
benediktms:feat/codex-init
Sep 7, 2026
Merged

MadhuAppachi merged 1 commit into
AppachiTech:devfrom
benediktms:feat/codex-init

Conversation

@benediktms

Copy link
Copy Markdown
Contributor

Summary

  • Add suv init codex — a first-class Codex CLI integration on par with the Claude Code and OpenCode integrations. It installs PostToolUse + UserPromptSubmit hooks into ~/.codex/hooks.json (merging into any existing hooks such as synapse/plannotator rather than overwriting) and auto-registers the suvadu MCP server in ~/.codex/config.toml.
  • New hidden subcommands suv hook-codex / suv hook-codex-prompt record Codex-run bash commands as executor=openai-codex (session prefix codex-) and capture prompts for prompt-grouped sessions on the agent dashboard. Exit code is recorded only when Codex exposes it (it does not reliably), so it is left unknown rather than mislabeled.
  • MCP registration and hook installation merge idempotently into existing configs.

Linked Issue

Closes #30

Changes

  • src/cli.rs — InitTarget::Codex, init codex help text, hook-codex / hook-codex-prompt subcommands
  • src/integrations.rs — handle_init_codex, handle_hook_codex, handle_hook_codex_prompt, try_configure_codex_mcp, try_merge_codex_hooks
  • src/main.rs — dispatch wiring
  • Docs — README init list, CONTRIBUTING file map, CHANGELOG

Test Plan

  • cargo build, cargo test (1098 pass), cargo clippy clean
  • Live-verified end to end: a real Codex session's commands are recorded as executor=openai-codex with agent_prompt context grouped on the agent dashboard
  • MCP reachable: removed [mcp_servers.suvadu], re-ran suv init codex, and completed the Codex handshake (initialize → tools/list returns 15 tools)

@MadhuAppachi
MadhuAppachi changed the base branch from main to dev August 7, 2026 06:50

@MadhuAppachi MadhuAppachi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for this — nice test coverage, especially around hook-merge idempotency and exit-code parsing.

Requesting one change: handle_init_codex propagates try_merge_codex_hooks(...) failures via ?, aborting the whole command on a malformed ~/.codex/hooks.json (and skipping MCP config too, since that step runs after). Both handle_init_claude_code and handle_init_cursor treat this as a soft failure instead — falling back to printing manual setup instructions. Worth matching that here, especially since this integration's whole point is coexisting with third-party hook files (synapse, plannotator) whose shape we don't control.

Non-blocking notes:

  • try_configure_codex_mcp always overwrites the command/args on rerun, unlike Claude/Cursor which skip if suvadu is already present — looks intentional (refreshes stale binary paths) but a comment would help.
  • The type -P suv PATH fallback in the hook script is a nice addition Claude/Cursor's scripts lack — worth backporting separately.

Comment thread src/integrations.rs Outdated
/// Codex runs `PostToolUse` after both successful and failed Bash calls, so a
/// single handler captures both. The payload shares Claude Code's shape
/// (`tool_name`, `tool_input.command`, `cwd`, `session_id`).
pub fn handle_hook_codex() -> Result<(), Box<dyn std::error::Error>> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

handle_hook_codex() re-implements the same stdin-read/parse/session-id/prompt-context/entry-building logic already duplicated between handle_hook_claude_code() and handle_hook_claude_code_failure(), now tripling it instead of factoring it into a shared helper.

The risk is already visible in this PR: this function falls back to a random UUID when session_id is invalid, while the sibling handle_hook_codex_prompt silently drops the event instead — an inconsistency inherited from copying rather than sharing code. Worth deciding which behavior is intended and consolidating into one helper both hooks call.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Consolidated in 1b8be3f — record_agent_bash_hook now backs all three Bash-tool handlers and cache_agent_prompt both prompt handlers (153+/238−). Cursor keeps its own: different payload keys and a {"continue":true} protocol response.

On which behaviour is intended — the asymmetry is deliberate and predates this PR, so I documented it rather than changing it. handle_hook_claude_code also falls back to a synthetic UUID while handle_hook_claude_prompt drops the event: losing a command from history is worse than losing prompt grouping, and a prompt cached under an id no command will ever look up is dead weight. Codex copied the convention correctly.

You were right not to fix it blind, so I validated against a live codex-cli 0.148 harness instead. That turned up something affecting 9c5054e: Codex reports no exit code at all, and success is indistinguishable from failure. tool_response is a plain string, and the key set is identical either way.

{
  "session_id": "01a01ade-c43e-76f1-963f-1202e7c394a0",
  "turn_id": "01a01ade-c524-7fe0-b7c6-41b998616b9e",
  "transcript_path": "/Users/…/.codex/sessions/2026/08/19/rollout-….jsonl",
  "cwd": "/Users/…/code/suvadu",
  "hook_event_name": "PostToolUse",
  "model": "gpt-5.6-sol",
  "permission_mode": "default",
  "tool_name": "Bash",
  "tool_input": { "command": "echo suvadu-hook-probe-42" },
  "tool_response": "suvadu-hook-probe-42\n",
  "tool_use_id": "exec-837af453-534c-47b5-9a47-fb3d9f65b912"
}
{
  "…": "same key set, `ls /nonexistent-suvadu-probe`",
  "tool_response": "ls: /nonexistent-suvadu-probe: No such file or directory\n"
}

So the structured reads in codex_exit_code — including the "error": null case you guarded — are unreachable against 0.148, and every Codex entry records exit_code = NULL. I kept them as forward-compat but labelled them as unexercised, and added a regression test pinning the real shape so the assumption fails loudly if Codex changes it. Say the word if you'd rather delete the speculative branch than carry it.

tool_name, tool_input.command, cwd and session_id are all confirmed present and usable, and prompt grouping works end to end — replaying the captured payloads through the built binary:

session_id = codex-01a01ae8-1360-77a1-b916-5f75d25049b4
   command = cargo build --release
 exit_code =
  executor = openai-codex
   context = {"agent_prompt":"Reply OK. Run no commands."}

One thing for a separate issue, not this PR: the executor rename from codex to openai-codex orphans entries written by the older shell hook from any --executor filter — 18940 codex rows vs 49 openai-codex in my local history. Needs a migration or an alias.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Correcting my last paragraph above — it was wrong, and no migration is needed.

I claimed this PR renames the executor from codex to openai-codex. It doesn't. openai-codex has been the canonical label since the initial release: src/hooks.rs has written it for CODEX_THREAD_ID-detected shells all along, and git log -S'--executor codex' --all and git log -S'suvadu-post-tool' --all both come back empty — suvadu has never emitted the bare codex label or generated that script.

The codex rows in my local history came from a hook I hand-wrote in July that calls suv add --executor codex directly. Entirely local, nothing to do with this repo. Sorry for the noise.

@MadhuAppachi

Copy link
Copy Markdown
Member

Thanks for this @benediktms — great work on the Codex integration. Reviewed and pushed a few small fixes directly to this branch (9c5054e), since "Allow edits from maintainers" was enabled:

  • codex_exit_code() null-error bug: an explicit JSON "error": null field (common when Codex serializes Option<String> without skip_serializing_if) was being treated as a real error, defaulting successful commands to exit_code = Some(1) instead of None. Added a .filter(|err| !err.is_null()) guard plus a unit test covering the null case.
  • Duplicate output: suv init codex printed "Restart Codex to activate." twice on a successful run (once in the auto_configured branch, once again at the end). Removed the redundant early print.
  • Test isolation: test_configure_codex_mcp_idempotent mutates the process-wide HOME env var, which risked permanently poisoning the cached PROJECT_DIRS LazyLock (src/util/mod.rs) if another test raced to initialize it first. Now warms project_dirs() under the real HOME before redirecting it.

Ran cargo build, full cargo test (1099 lib + 17 integration tests), and cargo clippy --all-targets — all green, no new warnings.

Left one as a review comment rather than fixing blind: handle_hook_codex() duplicates stdin-parsing logic already copy-pasted between handle_hook_claude_code()/handle_hook_claude_code_failure(), and it falls back to a random UUID on an invalid session_id while the sibling handle_hook_codex_prompt silently drops the event — worth deciding which behavior is intended before consolidating, and that needs a live Codex to validate against, which we don't have on hand.

@benediktms

Copy link
Copy Markdown
Contributor Author

254a953 fixes a destructive write in try_configure_codex_mcp that testing on a live Codex install turned up. It adds a dependency (toml_edit), so it needs a look.

The function parsed ~/.codex/config.toml into a toml::Value and wrote the reserialized document back. toml::to_string_pretty has no concept of comments, so every comment in the file was silently deleted, and tables, key order and inline arrays were all reshuffled. config.toml is hand-maintained — mine is 367 lines — so this rewrites a file the user owns on every suv init codex.

Before, running init against a real config produced a 100+ line diff with all comments gone. After:

155c155
< command = "/opt/homebrew/bin/suv"
---
> command = "/Users/…/target/release/suv"

toml_edit (0.25.13) now edits in place, touching only the command/args keys we own. indexmap and winnow were already in the lock, so the added weight is toml_edit itself plus a toml_writer patch bump. Two further details:

  • set_toml_value_keeping_decor carries the existing entry's decor across a value change, so a trailing comment on our own command = … line survives a binary-path refresh, and an already-correct args line is not touched at all.
  • The file is not written when nothing changed — verified by mtime, so a re-run is a true no-op rather than a rewrite of identical bytes.

Verified across five cases (refresh with stale path, args already correct, fresh install into an existing hand-written config, no config.toml at all, path already correct). The test asserts whole-file byte equality apart from the path substring, so a regression can't pass as "semantically equivalent" — which the old behaviour technically was.

Same class of issue, deliberately left alone as out of scope for this PR: ~/.claude.json and .claude/settings.json go through serde_json, whose default map is a BTreeMap, so suv init claude-code alphabetically reorders keys in files people commit to git. No data loss, but noisy diffs. One-line fix (features = ["preserve_order"]) that touches every JSON path in the repo, so it wants its own PR.

Ports the still-unclaimed piece of PR AppachiTech#31 (feat/codex-init) onto dev's
own Codex integration (732dd34), which already covers hook-based
command/prompt capture. Ties `suv init codex` to `suv mcp-serve` in
~/.codex/config.toml the same way Claude Code and Cursor already are,
closing the remaining gap in AppachiTech#30.

Uses toml_edit rather than a parse/reserialize round trip through
toml::Value, since config.toml is hand-maintained and a round trip
would silently strip every comment and reorder tables.

Ported from github.com/benediktms/suvadu#31 (254a953), adapted to
dev's src/integrations/codex.rs module split and CODEX_HOME-aware
path resolution.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016kVHAmojKCWepQBxe9k1bN
@MadhuAppachi

Copy link
Copy Markdown
Member

Hey Benedikt — thanks for this, and sorry for the slow turnaround.

While this was in review, we ended up independently shipping most of the same functionality on dev (hook-based command + prompt capture for Codex, plus doctor/settings/uninstall integration) — parallel work happening at the same time, not a reflection on this PR.

The piece that's not duplicated, and that we still want, is the MCP auto-registration in ~/.codex/config.toml via toml_edit — nice attention to detail preserving comments/formatting there, and it's the last unfinished part of #30.

So we're going to rebase this PR down to just that piece on top of current dev and merge it under your authorship, rather than closing it outright. You'll still show up as the author and this'll still land as a merged PR. If you'd rather do that rebase yourself, or want to look at the trimmed diff first, just say so — otherwise we'll push the update to this branch shortly.

@MadhuAppachi
MadhuAppachi merged commit 6e76211 into AppachiTech:dev Sep 7, 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.

codex does not get automatically recognized as an agent

2 participants