Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(codex): Match the Codex shell tool by the names Codex actually sends (#1341)
Raghav Chamadiyaac347f415f07
diff --git a/packages/cli/src/repowise/cli/agent_adapters/codex.py b/packages/cli/src/repowise/cli/agent_adapters/codex.pyindex 304626448..4e6b8a871 100644--- a/packages/cli/src/repowise/cli/agent_adapters/codex.py+++ b/packages/cli/src/repowise/cli/agent_adapters/codex.py@@ -3,9 +3,9 @@Protocol reference (Codex hooks, developers.openai.com/codex/hooks): hooksload from ``~/.codex/hooks.json`` (or a repo-local ``.codex/hooks.json``); aPreToolUse hook receives JSON on stdin with snake_case-``hook_event_name``/``tool_name``/``tool_input``/``cwd`` — the shell tool is-named ``Bash`` and ``tool_input.command`` is a string — and answers with-camelCase ``hookSpecificOutput`` JSON on stdout.+``hook_event_name``/``tool_name``/``tool_input``/``cwd`` — the shell tool+answers to several names (:data:`SHELL_TOOL_NAMES`) and ``tool_input.command``+is a string — and answers with camelCase ``hookSpecificOutput`` JSON on stdout.Two protocol limits shape this adapter's honesty posture:@@ -24,7 +24,7 @@ Two protocol limits shape this adapter's honesty posture:from __future__ import annotationsimport json-import os.path+import osfrom typing import TYPE_CHECKING, ClassVarfrom repowise.cli.agent_adapters.base import AgentAdapter, RewriteRequest, RewriteResult@@ -33,6 +33,31 @@ if TYPE_CHECKING:from pathlib import Path+#: Every name Codex has given the tool that carries a shell command *string*,+#: because it has given it more than one and the rewrite is dead for any name+#: it does not answer to.+#:+#: This started as the single literal ``"Bash"``. Measured against 18 real+#: rollouts from Codex 0.145: ``"Bash"`` does not appear once, and the shell+#: calls are ``shell_command`` (322), whose ``tool_input.command`` is a string+#: — the shape :meth:`CodexAdapter.parse_hook_payload` already reads. A rename+#: upstream is silent here (the gate stops matching and the hook never fires),+#: so this is a set and new names are added rather than swapped in.+#:+#: **``exec`` is deliberately not in it.** It looks like a shell tool in the+#: rollouts (423 calls) and is not one: it is a ``custom_tool_call`` whose+#: input is a *JavaScript program* that calls ``tools.shell_command(...)``+#: internally. There is no command string to read and nothing to rewrite, so+#: matching it would buy 423 hook subprocesses that can only decline. A name+#: belongs here once it is observed carrying ``tool_input.command``.+SHELL_TOOL_NAMES: frozenset[str] = frozenset({"Bash", "shell_command"})++#: The same set as a hooks.json matcher. Derived rather than written twice —+#: an installer whose matcher disagrees with the adapter's gate installs a+#: hook that runs and then declines every payload it is handed.+SHELL_TOOL_MATCHER: str = "|".join(sorted(SHELL_TOOL_NAMES))++class CodexAdapter(AgentAdapter):name: ClassVar[str] = "codex"@@ -51,9 +76,10 @@ class CodexAdapter(AgentAdapter):return Noneif payload.get("hook_event_name") != "PreToolUse":return None- # Codex's shell tool is named "Bash" (there is no separate- # PowerShell tool); the command is always a string.- if payload.get("tool_name") != "Bash":+ # Codex has no separate PowerShell tool, but it has renamed the shell+ # one; see SHELL_TOOL_NAMES. The command is a string on every name+ # that reaches the check below.+ if payload.get("tool_name") not in SHELL_TOOL_NAMES:return Nonetool_input = payload.get("tool_input")command = tool_input.get("command") if isinstance(tool_input, dict) else None@@ -63,7 +89,14 @@ class CodexAdapter(AgentAdapter):return RewriteRequest(command=command,cwd=cwd if isinstance(cwd, str) else "",- shell="posix",+ # Codex names its shell tool the same on every platform, so the+ # dialect has to come from the platform. It is PowerShell on+ # Windows — the real rollouts are full of `get-content`,+ # `get-childitem` and `$env:` — and calling that "posix" skips+ # `decide`'s PowerShell-alias bailout, which exists precisely to+ # stop an alias command being re-run through cmd.exe. Dead code+ # until the gate above started matching; live now.+ shell="powershell" if os.name == "nt" else "posix",)def render_response(self, result: RewriteResult) -> str:diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.pyindex a89c2351c..2b1d6d992 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py@@ -91,6 +91,8 @@ from pathlib import Pathimport click+from repowise.cli.agent_adapters.codex import SHELL_TOOL_NAMES+from ._shared import HookResult, as_resultfrom .bash_staleness import _handle_bash_postfrom .codex import _handle_codex_context_event, _handle_post_edit_use@@ -102,6 +104,13 @@ from .wrong_path import _handle_tool_failure_EDIT_TOOL_NAMES = {"apply_patch", "Edit", "Write"}+#: Shell tools, across both harnesses. ``PowerShell`` is Windows Claude Code;+#: the rest are what Codex has called its shell tool, owned by the adapter so+#: the dispatch here and the installed matcher cannot disagree. Free at module+#: scope: ``agent_adapters`` is stdlib-only by its own hot-path contract, and+#: `tests/unit/cli/test_augment_hook_perf.py` holds that.+_SHELL_TOOL_NAMES = SHELL_TOOL_NAMES | {"PowerShell"}+@click.command("augment")@click.option(@@ -340,9 +349,10 @@ def _handle_post_tool_use(# Read-after-served KPI: logged to the ledger, never spoken about._log_read_after_served(tool_input, tool_output, cwd, session_id)return _handle_read_post(tool_input, tool_output, cwd, session_id)- if tool_name in ("Bash", "PowerShell"):- # The PowerShell tool (Windows Claude Code) surfaces the same- # stdout/stderr response shape as Bash — one handler covers both.+ if tool_name in _SHELL_TOOL_NAMES:+ # The PowerShell tool (Windows Claude Code) and Codex's several names+ # for its shell all surface the same stdout/stderr response shape as+ # Bash — one handler covers them.return as_result(_handle_bash_post(tool_input, tool_output, cwd))if tool_name in ("Grep", "Glob"):# ``client`` reaches this one because the flood digest can *replace*diff --git a/packages/cli/src/repowise/cli/editor_integrations/codex_config.py b/packages/cli/src/repowise/cli/editor_integrations/codex_config.pyindex 3718b5078..183e1c330 100644--- a/packages/cli/src/repowise/cli/editor_integrations/codex_config.py+++ b/packages/cli/src/repowise/cli/editor_integrations/codex_config.py@@ -24,6 +24,12 @@ import reimport subprocessfrom pathlib import Path+# The adapter owns what Codex calls its shell tool; the installed matcher is+# derived from it so the two cannot drift. Safe at module scope: the adapter+# imports this module lazily, inside its methods, so there is no cycle, and+# its own imports are stdlib only.+from repowise.cli.agent_adapters.codex import SHELL_TOOL_MATCHER+#: First Codex release whose PreToolUse hooks honor an ``updatedInput``#: command rewrite; earlier builds report it as an unsupported hook output.CODEX_REWRITE_MIN_VERSION: tuple[int, int] = (0, 137)@@ -31,7 +37,7 @@ CODEX_REWRITE_MIN_VERSION: tuple[int, int] = (0, 137)_REWRITE_HOOK_COMMAND = "repowise-rewrite"_REWRITE_HOOK_ENTRY = {- "matcher": "Bash",+ "matcher": SHELL_TOOL_MATCHER,"hooks": [{"type": "command",@@ -43,6 +49,65 @@ _REWRITE_HOOK_ENTRY = {}+#: Matchers this entry has shipped with, current one excluded. An install+#: predating a Codex tool rename holds one of these and therefore matches+#: nothing — and because :func:`_is_rewrite_hook` keys on the *command*, a+#: reinstall would find it, call it present, and leave it dead forever. So+#: install upgrades a matcher it recognises as its own. Only these exact+#: strings are moved: a user who narrowed the matcher deliberately keeps it.+_LEGACY_REWRITE_MATCHERS = ("Bash",)+++def _migrate_rewrite_matcher(hook_list: list) -> bool:+ """Repoint an existing repowise entry at the current matcher.++ Returns True when something moved, so the caller knows to write.+ """+ changed = False+ for entry in hook_list:+ if not isinstance(entry, dict):+ continue+ if not any(_is_rewrite_hook(h) for h in entry.get("hooks", []) or []):+ continue+ if entry.get("matcher") in _LEGACY_REWRITE_MATCHERS:+ entry["matcher"] = SHELL_TOOL_MATCHER+ changed = True+ return changed+++def migrate_codex_rewrite_hook() -> bool:+ """Repoint an already-installed rewrite hook at the current matcher.++ The twin of :func:`~repowise.cli.editor_integrations.claude_config.migrate_claude_code_hooks`,+ and it exists for the same reason: a user who opted in before a Codex+ tool rename holds an entry that matches nothing, and reinstalling is a+ step nobody knows to take. Never installs — it only moves a matcher on an+ entry that is already ours, so someone who removed the hook on purpose+ stays without it. Returns True when the file was rewritten.+ """+ from repowise.cli.mcp_config import load_existing_config++ hooks_path = _codex_hooks_path()+ if not hooks_path.exists():+ return False+ try:+ existing = load_existing_config(hooks_path)+ hooks = existing.get("hooks")+ if not isinstance(hooks, dict):+ return False+ pre_hooks = hooks.get("PreToolUse")+ if not isinstance(pre_hooks, list):+ return False+ if not _migrate_rewrite_matcher(pre_hooks):+ return False+ hooks_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")+ return True+ except Exception:+ # Same posture as install: a malformed or unreadable hooks file is a+ # migration that did not happen, never an error the user sees.+ return False++def _codex_hooks_path() -> Path:"""The user-level Codex hooks file (~/.codex/hooks.json)."""return Path.home() / ".codex" / "hooks.json"@@ -108,6 +173,10 @@ def install_codex_rewrite_hook() -> Path | None:if not _has_rewrite_hook(pre_hooks):pre_hooks.append(json.loads(json.dumps(_REWRITE_HOOK_ENTRY)))hooks_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")+ elif _migrate_rewrite_matcher(pre_hooks):+ # Present but pointed at a name Codex no longer uses. Reinstalling+ # is the only repair path a user has, so it has to be one.+ hooks_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")return hooks_pathexcept Exception:# OSError on write, ClickException from load_existing_config on adiff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex e62149eca..549a34946 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -26,6 +26,18 @@ def cli(ctx: click.Context) -> None:migrate_claude_code_hooks()except Exception:pass+ # And the same for an installed Codex rewrite hook whose matcher+ # names a tool Codex has since renamed. That one cannot self-heal+ # from its own hook the way the Claude side does — a hook matching+ # nothing never runs — so the CLI is the only place it can happen.+ try:+ from repowise.cli.editor_integrations.codex_config import (+ migrate_codex_rewrite_hook,+ )++ migrate_codex_rewrite_hook()+ except Exception:+ pass_COMMANDS_PKG = "repowise.cli.commands"diff --git a/plugins/codex/hooks/hooks.json b/plugins/codex/hooks/hooks.jsonindex e0f4826d0..bde7ecd35 100644--- a/plugins/codex/hooks/hooks.json+++ b/plugins/codex/hooks/hooks.json@@ -27,7 +27,7 @@],"PostToolUse": [{- "matcher": "Bash",+ "matcher": "Bash|shell_command","hooks": [{"type": "command",diff --git a/tests/unit/cli/test_codex_plugin.py b/tests/unit/cli/test_codex_plugin.pyindex 501bb4fc4..e630f6eda 100644--- a/tests/unit/cli/test_codex_plugin.py+++ b/tests/unit/cli/test_codex_plugin.py@@ -4,6 +4,13 @@ import jsonimport refrom pathlib import Path+from repowise.cli.agent_adapters.codex import (+ SHELL_TOOL_MATCHER,+ SHELL_TOOL_NAMES,+ CodexAdapter,+)+from repowise.cli.commands.augment_cmd.command import _SHELL_TOOL_NAMES+ROOT = Path(__file__).resolve().parents[3]PLUGIN_ROOT = ROOT / "plugins" / "codex"@@ -38,7 +45,7 @@ def test_codex_plugin_hooks_match_supported_codex_events() -> None:assert set(hooks) == {"SessionStart", "UserPromptSubmit", "PostToolUse"}assert hooks["SessionStart"][0]["matcher"] == "startup|resume|clear"assert [entry["matcher"] for entry in hooks["PostToolUse"]] == [- "Bash",+ SHELL_TOOL_MATCHER,"apply_patch|Edit|Write",]@@ -57,6 +64,46 @@ def test_codex_plugin_hooks_match_supported_codex_events() -> None:] == [30] * 4+def test_codex_shell_matcher_covers_the_names_codex_actually_sends() -> None:+ """The matcher, the dispatch and the rewrite gate agree on one set.++ This is a regression test with a real defect behind it: the matcher was+ the single literal ``"Bash"``, which Codex has not called its shell tool+ in any measured release — 18 rollouts from 0.145 carry ``shell_command``+ and ``exec`` and never ``Bash``. A hook that matches nothing is silent in+ exactly the way a working one is, so nothing caught it. Pinning the three+ sites to one another is what makes the next rename a failing test rather+ than a surface that quietly stops firing.+ """+ for name in ("Bash", "shell_command"):+ assert name in SHELL_TOOL_NAMES+ assert name in SHELL_TOOL_MATCHER.split("|")+ # The augment dispatch routes it to the shell handler...+ assert name in _SHELL_TOOL_NAMES+ # ...and the rewrite hook accepts rather than declines it.+ payload = json.dumps(+ {+ "hook_event_name": "PreToolUse",+ "tool_name": name,+ "tool_input": {"command": "pytest -q"},+ "cwd": "/repo",+ }+ )+ assert CodexAdapter().parse_hook_payload(payload) is not None+++def test_codex_exec_is_excluded_because_it_carries_no_command() -> None:+ """`exec` looks like a shell tool in the rollouts and is not one.++ It is a `custom_tool_call` whose input is a JavaScript program that calls+ `tools.shell_command(...)` internally — no command string, nothing to+ rewrite. Matching it would buy a hook subprocess per call (423 of them in+ the measured corpus) that can only ever decline.+ """+ assert "exec" not in SHELL_TOOL_NAMES+ assert "exec" not in SHELL_TOOL_MATCHER.split("|")++def test_codex_plugin_skills_have_metadata_and_neutral_wording() -> None:skill_paths = sorted((PLUGIN_ROOT / "skills").glob("*/SKILL.md"))diff --git a/tests/unit/distill/test_agent_adapters.py b/tests/unit/distill/test_agent_adapters.pyindex f1a8b3bcb..fb8adbbf4 100644--- a/tests/unit/distill/test_agent_adapters.py+++ b/tests/unit/distill/test_agent_adapters.py@@ -8,12 +8,14 @@ migration-safe, and preserves user hooks and the augment PostToolUse entry.from __future__ import annotationsimport json+import osimport pytest+from repowise.cli.agent_adapters import codex as codex_modulefrom repowise.cli.agent_adapters.base import RewriteResultfrom repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter-from repowise.cli.agent_adapters.codex import CodexAdapter+from repowise.cli.agent_adapters.codex import SHELL_TOOL_MATCHER, CodexAdapterfrom repowise.cli.editor_integrations import claude_config, codex_configfrom repowise.cli.editor_integrations.claude_config import (claude_code_rewrite_hook_installed,@@ -290,13 +292,36 @@ class TestCodexParsePayload:assert req is not Noneassert req.command == "pytest -x"assert req.cwd == "/repo"- assert req.shell == "posix"+ assert req.shell == ("powershell" if os.name == "nt" else "posix")++ def test_shell_dialect_follows_the_platform(self, codex_adapter, monkeypatch) -> None:+ """Codex names its shell tool the same everywhere; the shell differs.++ The dialect was hardcoded to ``posix``, which was harmless only+ because the tool-name gate above it never matched. On Windows the+ real rollouts are PowerShell (`get-content`, `get-childitem`,+ `$env:`), and calling that posix skips `decide`'s alias bailout —+ the guard that stops an alias command being re-run through cmd.exe.+ """+ raw = json.dumps(+ {+ "hook_event_name": "PreToolUse",+ "tool_name": "shell_command",+ "tool_input": {"command": "ls -Force"},+ "cwd": "/repo",+ }+ )+ monkeypatch.setattr(codex_module.os, "name", "nt")+ assert codex_adapter.parse_hook_payload(raw).shell == "powershell"+ monkeypatch.setattr(codex_module.os, "name", "posix")+ assert codex_adapter.parse_hook_payload(raw).shell == "posix"@pytest.mark.parametrize("mutation",[{"hook_event_name": "PostToolUse"},{"tool_name": "PowerShell"}, # Codex has no PowerShell tool+ {"tool_name": "exec"}, # a JS program, not a command string{"tool_name": "apply_patch"},{"tool_input": {}},{"tool_input": {"command": " "}},@@ -385,7 +410,11 @@ class TestCodexHooksInstall:assert install_codex_rewrite_hook() == codex_hooks_pathentries = _codex_pre_hooks(codex_hooks_path)assert len(entries) == 1- assert entries[0]["matcher"] == "Bash"+ # Derived from the adapter's own gate, not a literal: an installed+ # matcher naming a tool the gate declines is a hook that runs for+ # nothing, and one missing a name the gate accepts never runs at all.+ assert entries[0]["matcher"] == SHELL_TOOL_MATCHER+ assert "shell_command" in entries[0]["matcher"]hook = entries[0]["hooks"][0]assert hook["command"] == "repowise-rewrite --agent codex"assert codex_rewrite_hook_installed() is True@@ -395,6 +424,111 @@ class TestCodexHooksInstall:install_codex_rewrite_hook()assert len(_codex_pre_hooks(codex_hooks_path)) == 1+ def test_reinstall_upgrades_a_matcher_codex_no_longer_uses(+ self, codex_hooks_path+ ) -> None:+ """An existing install must not stay dead just because it is present.++ ``_is_rewrite_hook`` keys on the command, so an entry left over from+ when the matcher was the bare literal ``Bash`` — a name Codex has not+ used for its shell tool in any measured release — is found by the+ presence check and would otherwise be skipped forever. Reinstalling+ is the only repair a user has.+ """+ codex_hooks_path.parent.mkdir(parents=True, exist_ok=True)+ stale = {+ "matcher": "Bash",+ "hooks": [{"type": "command", "command": "repowise-rewrite --agent codex"}],+ }+ codex_hooks_path.write_text(+ json.dumps({"hooks": {"PreToolUse": [stale]}}), encoding="utf-8"+ )++ install_codex_rewrite_hook()++ entries = _codex_pre_hooks(codex_hooks_path)+ assert len(entries) == 1, "upgrade in place, never a second entry"+ assert entries[0]["matcher"] == SHELL_TOOL_MATCHER++ def test_self_heal_upgrades_without_being_asked(self, codex_hooks_path) -> None:+ """`repowise <anything>` repairs a stale matcher; the hook cannot.++ A hook whose matcher matches nothing never runs, so unlike the Claude+ side it has no way to heal itself. The CLI is the only place it can+ happen, and a user who opted in months ago will not think to re-run+ install.+ """+ codex_hooks_path.parent.mkdir(parents=True, exist_ok=True)+ codex_hooks_path.write_text(+ json.dumps(+ {+ "hooks": {+ "PreToolUse": [+ {+ "matcher": "Bash",+ "hooks": [+ {+ "type": "command",+ "command": "repowise-rewrite --agent codex",+ }+ ],+ }+ ]+ }+ }+ ),+ encoding="utf-8",+ )++ assert codex_config.migrate_codex_rewrite_hook() is True+ assert _codex_pre_hooks(codex_hooks_path)[0]["matcher"] == SHELL_TOOL_MATCHER+ # Idempotent: a second pass has nothing to do and writes nothing.+ assert codex_config.migrate_codex_rewrite_hook() is False++ def test_self_heal_never_installs_for_someone_who_opted_out(+ self, codex_hooks_path+ ) -> None:+ """No hooks file, or no repowise entry, means nothing to migrate."""+ assert codex_config.migrate_codex_rewrite_hook() is False++ codex_hooks_path.parent.mkdir(parents=True, exist_ok=True)+ codex_hooks_path.write_text(+ json.dumps(+ {+ "hooks": {+ "PreToolUse": [+ {+ "matcher": "Bash",+ "hooks": [+ {"type": "command", "command": "my-validator"}+ ],+ }+ ]+ }+ }+ ),+ encoding="utf-8",+ )+ assert codex_config.migrate_codex_rewrite_hook() is False+ assert _codex_pre_hooks(codex_hooks_path)[0]["matcher"] == "Bash"++ def test_reinstall_leaves_a_deliberately_narrowed_matcher_alone(+ self, codex_hooks_path+ ) -> None:+ """Only matchers this installer shipped are moved, not the user's."""+ codex_hooks_path.parent.mkdir(parents=True, exist_ok=True)+ theirs = {+ "matcher": "shell_command",+ "hooks": [{"type": "command", "command": "repowise-rewrite --agent codex"}],+ }+ codex_hooks_path.write_text(+ json.dumps({"hooks": {"PreToolUse": [theirs]}}), encoding="utf-8"+ )++ install_codex_rewrite_hook()++ assert _codex_pre_hooks(codex_hooks_path)[0]["matcher"] == "shell_command"+def test_preserves_user_hooks(self, codex_hooks_path) -> None:codex_hooks_path.parent.mkdir(parents=True, exist_ok=True)user_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": "my-validator"}]}