Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
ae20894
The Codex bridge follows Claude Code's hook exit contract and honours…
wshallwshall Nov 16, 2026
99128fa
The Codex bridge keeps a PowerShell hook's exit 2 and matches Claude …
wshallwshall Nov 16, 2026
a684879
The Codex transport passes the bridge's exit 2 on, and PowerShell hoo…
wshallwshall Nov 16, 2026
0a01076
Handover for BACKLOG #5496 and #5501: proposed PR title and banners
wshallwshall Nov 16, 2026
baa96c7
The Codex bridge decides its own faults, and a launcher with no decis…
wshallwshall Nov 16, 2026
d301ba2
The Codex bridge reads UTF-8 bytes, checks the registered event, and …
wshallwshall Nov 16, 2026
b1e5bdf
Only a hook blocks in the Codex bridge; a bridge fault or a launcher …
wshallwshall Nov 16, 2026
98959e1
The Codex bridge blocks on a PowerShell hook's own exit 2 and on its …
wshallwshall Nov 16, 2026
e908ec8
A PowerShell hook blocks on its own final exit 2, and invoke.ps1 find…
wshallwshall Nov 17, 2026
be82fff
A PowerShell hook keeps its own scope, and its exit 2 is judged from …
wshallwshall Nov 17, 2026
002c058
A command-only PowerShell hook runs as under Claude Code, and its exi…
wshallwshall Nov 17, 2026
bd2e953
The Codex docs state what the PowerShell head line and a help flag do
wshallwshall Nov 17, 2026
8b0f40c
Codex bridge: a PowerShell hook's guard exit 2 blocks again; four fal…
wshallwshall Nov 17, 2026
8dd26aa
Codex bridge: the PowerShell tail survives strict mode and a trailing…
wshallwshall Nov 17, 2026
e57e2dd
Codex bridge: state the param() and stale-2 behaviour of a PowerShell…
wshallwshall Nov 17, 2026
521ae09
Codex bridge: a dangling operator cannot absorb the PowerShell tail; …
wshallwshall Nov 17, 2026
f844e92
Codex bridge: the doc quotes the PowerShell tail instead of deriving …
wshallwshall Nov 17, 2026
70a94ec
Codex bridge: the PowerShell tail calls Get-Variable by its module-qu…
wshallwshall Nov 17, 2026
970601a
Codex bridge: the PowerShell tail reads the exit code without a cmdle…
wshallwshall Nov 17, 2026
e52437c
Codex bridge: the PowerShell tail reads LASTEXITCODE as a plain variable
wshallwshall Nov 17, 2026
cc0f41c
Codex bridge: the PowerShell tail reads LASTEXITCODE inside try/catch…
wshallwshall Nov 17, 2026
54198dc
Codex bridge: no PowerShell head line, and a no-shell hook runs under…
wshallwshall Nov 17, 2026
702559b
Codex bridge doc: named-block PowerShell hooks are a stated limit; th…
wshallwshall Nov 17, 2026
5c57026
Codex bridge doc: delete the -File advice for named-block hooks and a…
wshallwshall Nov 17, 2026
5901590
Codex bridge doc: cut the prose on which PowerShell hook shapes block…
wshallwshall Nov 17, 2026
2c7fbcd
Codex bridge doc: restore the stale-2 sentence the Lander made a cond…
wshallwshall Nov 17, 2026
57cece5
Codex bridge doc: delete the stale-2 blocking sentence
wshallwshall Nov 17, 2026
f3b2a09
Codex bridge doc: cut the origin/main history and "naming the hook"
wshallwshall Nov 17, 2026
03979c5
Codex bridge: drop the PowerShell tail and the config's trailing exit
wshallwshall Nov 17, 2026
609d646
Codex bridge doc: state the outer-shell limit and cut the tail prose
wshallwshall Nov 17, 2026
1cb9b82
Codex bridge doc: cut the claims a PowerShell outer shell makes false
wshallwshall Nov 17, 2026
66f5a1c
Codex bridge doc: restore the exit-2 and onFailure sentences
wshallwshall Nov 17, 2026
419bc2e
Codex bridge: restore main's SessionEnd exit and non-object JSON error
wshallwshall Nov 17, 2026
6467ff9
Codex bridge doc: shrink "Who decides a block" to what holds
wshallwshall Nov 17, 2026
2ac3c88
Codex bridge: null hook output is a non-object error; cut dangling do…
wshallwshall Nov 17, 2026
617f126
Codex bridge: cut the stale exit-code pointers and closed lists
wshallwshall Nov 17, 2026
b534295
Codex bridge: restore main's shell fallback, PermissionRequest exit, …
wshallwshall Nov 17, 2026
87aa74b
Codex bridge doc: cut the false shell and exit-code sentences
wshallwshall Nov 17, 2026
46b4e59
Codex bridge test: a PermissionRequest fault now exits 1, never the b…
wshallwshall Nov 17, 2026
783bb9f
Revert the Codex bridge rewrite on this branch back to origin/main
wshallwshall Nov 17, 2026
da8c2e2
Codex bridge: a hook's deliberate exit 2 reaches Codex as 2
wshallwshall Nov 17, 2026
d8edd27
Codex bridge doc: state where a hook's exit 2 reaches Codex
wshallwshall Nov 17, 2026
f971ef3
Codex bridge exits BLOCK_EXIT only where invoke.ps1 set the block sen…
wshallwshall Nov 17, 2026
57b3be3
Codex bridge: review round 1 on the block-sentinel repair
wshallwshall Nov 17, 2026
e21c7c5
Codex bridge: review round 2 on the block-sentinel repair
wshallwshall Nov 17, 2026
002c643
docs/CODEX.md: cut the exit-2 delivery sentences, per hold item 3
wshallwshall Nov 17, 2026
c1cb4e8
Codex bridge carries the block exit as a --block-exit flag, not an en…
wshallwshall Nov 17, 2026
b6a21fc
Codex bridge: review round 1 on the --block-exit flag
wshallwshall Nov 17, 2026
26ff299
Codex bridge: review round 2 on the --block-exit flag
wshallwshall Nov 17, 2026
598f70f
Codex bridge tests: cut two false claims in test prose
wshallwshall Nov 17, 2026
c70ad36
Codex bridge: cut the HookBlocked docstring's block claim
wshallwshall Nov 17, 2026
9b5db57
Merge branch 'main' into b612-5496-5501
wshallwshall Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/CODEX.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ adapter; alias matching alone cannot translate an edit payload.
New event types appear as unmapped at startup. Unsupported handler types and
failed commands report errors. The bridge does not silently claim they ran.
Command-only hooks use PowerShell on Windows and `sh` elsewhere; structured
`command` and `args` avoid shell parsing. Hook chains have a 90-second outer limit.
`command` and `args` avoid shell parsing. Codex's documentation does not say
which shell runs a hook command.

Only repo settings are imported. Claude's user settings, local settings, account
credentials, permission grants, plugins, and status line remain Claude-owned.
Expand Down
24 changes: 21 additions & 3 deletions scripts/codex/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
# Must equal $blockExit in invoke.ps1; a mismatch leaves a block at 2, which its caller's
# pwsh -Command reports as 1.
BLOCK_EXIT = 10
EVENTS = (
"SessionStart",
"SessionEnd",
Expand Down Expand Up @@ -115,6 +118,10 @@
return messages


class HookBlocked(Exception):
"""A hook exited 2."""


def child_environment(root: Path, session_id: str) -> dict[str, str]:
if not session_id:
raise ValueError("Codex session id missing; pass --session-id or set CODEX_THREAD_ID")
Expand Down Expand Up @@ -243,7 +250,7 @@
if completed.stderr:
print(completed.stderr, file=sys.stderr, end="")
if completed.returncode == 2:
raise PermissionError(completed.stderr or "Claude hook blocked this event")
raise HookBlocked(completed.stderr or "Claude hook blocked this event")
completed.check_returncode()
output = completed.stdout.strip()
if not output:
Expand All @@ -267,7 +274,7 @@
return result


def main() -> int:

Check warning on line 277 in scripts/codex/bridge.py

View workflow job for this annotation

GitHub Actions / complexity triage (advisory)

Complexity increased

`main` complexity 15 -> 17 (mccabe threshold 10)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"mode", choices=("hook", "run", "doctor", "sync-skills", "source-skill", "state-dir")
Expand All @@ -275,7 +282,14 @@
parser.add_argument("--session-id", default=os.environ.get("CODEX_THREAD_ID", ""))
parser.add_argument("--migrate-copies", action="store_true")
parser.add_argument("--include-user-skills", action="store_true")
args, rest = parser.parse_known_args()
# A hook's exit 2 exits 2, or BLOCK_EXIT where argv is exactly `hook ... --block-exit 10`, the
# form invoke.ps1 builds; it ends its process with 2 for it. It is taken out before argparse, so
# no prefix of it is captured from a run script's own flags. Nothing inherits argv.
argv = sys.argv[1:]
block_exit = 2
if argv[:1] == ["hook"] and argv[-2:] == ["--block-exit", str(BLOCK_EXIT)]:
argv, block_exit = argv[:-2], BLOCK_EXIT
args, rest = parser.parse_known_args(argv)
if args.mode == "sync-skills":
user_skills = user_skill_directory() if args.include_user_skills else None
print(
Expand All @@ -294,7 +308,11 @@
return 0
if args.mode == "hook":
payload = json.load(sys.stdin)
result = dispatch(ROOT, payload)
try:
result = dispatch(ROOT, payload)
except HookBlocked as exc:
print(f"Codex bridge: {exc}", file=sys.stderr)
return block_exit
if result:
print(json.dumps(result))
return 0
Expand Down
15 changes: 13 additions & 2 deletions scripts/codex/invoke.ps1
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors
# No parameter block: forward native arguments, including script-specific flags, unchanged.
# No parameter block: forward native arguments, including script-specific flags, plus
# `--block-exit 10` in hook mode.
$ErrorActionPreference = 'Stop'
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$python = Join-Path $root '.venv/Scripts/python.exe'
Expand All @@ -10,5 +11,15 @@ if (-not (Test-Path -LiteralPath $python)) {
if (-not (Test-Path -LiteralPath $python)) {
throw 'Create this worktree''s .venv first; see docs/WORKTREES.md.'
}
& $python (Join-Path $PSScriptRoot 'bridge.py') @args
# Only where `hook` is the first argument, the bridge exits 10 for a hook's exit 2 (--block-exit in
# bridge.py), and the mapping below ends the process with 2 for it.
$hookMode = $args[0] -ceq 'hook'
$blockExit = 10 # Must equal BLOCK_EXIT in bridge.py.
# Assigned, never from an if expression, which would unroll a one-element array to a string.
$bridgeArgs = @($args)
if ($hookMode) { $bridgeArgs += '--block-exit', "$blockExit" }
& $python (Join-Path $PSScriptRoot 'bridge.py') @bridgeArgs
# Ending the process keeps the block as 2, which the caller's pwsh -Command would report as 1.
# Hook mode only, so a caller's window survives `run`.
if ($hookMode -and $LASTEXITCODE -eq $blockExit) { [Environment]::Exit(2) }
exit $LASTEXITCODE
264 changes: 264 additions & 0 deletions tests/test_codex_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import importlib.util
import json
import os
import shlex
import shutil
import subprocess
import sys
Expand Down Expand Up @@ -320,3 +321,266 @@ def test_registered_command_runs_from_a_subdirectory(tmp_path):
timeout=20,
)
assert json.loads(completed.stdout) == {"probe": True}


# --- The registered line, end to end: a hook's exit 2 reaches Codex as 2 where the outer shell
# keeps it, and every fault path is at least as strict as main's exit code (non-zero, as on main).

_DENY = {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny"}}
_PAYLOAD = {"session_id": "x", "hook_event_name": "PreToolUse", "tool_name": "Bash"}


def _py(source, **extra):
return {"type": "command", "command": sys.executable, "args": ["-c", source], **extra}


def _outer_shells():
shells = ["pwsh"]
if os.name == "nt":
shells.append("cmd")
if shutil.which("sh"):
shells.append("sh")
return shells


def _outer_argv(shell, command):
# cmd takes the line verbatim, as a string: Python's argv quoting escapes quotes in a way cmd
# does not read.
if shell == "cmd":
return f"cmd /d /c {command}"
if shell == "pwsh":
return ["pwsh", "-NoProfile", "-Command", command]
if shell == "none":
return shlex.split(command)
return [shutil.which("sh"), "-c", command]


def _link_python(root):
"""Give the copied launcher a .venv that reaches this test's own interpreter."""
if os.name == "nt":
if not (Path(sys.prefix) / "Scripts/python.exe").is_file():
pytest.skip("needs a virtualenv to junction on Windows")
link = ["cmd", "/c", "mklink", "/J", str(root / ".venv"), sys.prefix]
subprocess.run(link, check=True, capture_output=True)
else:
(root / ".venv/bin").mkdir(parents=True)
(root / ".venv/bin/python").symlink_to(sys.executable)


def _make_repo(tmp_path, settings_text, venv=True):
root = tmp_path / "repo"
scripts = root / "scripts/codex"
scripts.mkdir(parents=True)
for name in ("invoke.ps1", "bridge.py"):
shutil.copy2(ROOT / "scripts/codex" / name, scripts / name)
(root / ".claude").mkdir()
(root / ".claude/settings.json").write_text(settings_text, encoding="utf-8")
if venv:
_link_python(root)
subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True)
return root


def _launch(argv, cwd, payload=_PAYLOAD, env=None):
stdin = payload if isinstance(payload, str) else json.dumps(payload)
return subprocess.run(
argv,
cwd=cwd,
input=stdin,
text=True,
capture_output=True,
check=False,
timeout=60,
env=env,
)


def _run_registered(tmp_path, shell, settings_text, payload=_PAYLOAD, venv=True):
import tomllib

root = _make_repo(tmp_path, settings_text, venv)
config = tomllib.loads((ROOT / ".codex/config.toml").read_text())
command = config["hooks"]["PreToolUse"][0]["hooks"][0]["command"]
return _launch(_outer_argv(shell, command), root / "scripts/codex", payload)


def _hooks(*handlers):
return json.dumps({"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": list(handlers)}]}})


_FAULTS = {
"hook-exits-1": (_hooks(_py("import sys; sys.exit(1)")), _PAYLOAD, True),
"hook-timeout": (_hooks(_py("import time; time.sleep(5)", timeout=0.5)), _PAYLOAD, True),
"unsupported-hook": (_hooks({"type": "prompt", "prompt": "review"}), _PAYLOAD, True),
"non-object-json": (_hooks(_py("print('[1]')")), _PAYLOAD, True),
"null-json": (_hooks(_py("print('null')")), _PAYLOAD, True),
"hooks-null": (
json.dumps({"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": None}]}}),
_PAYLOAD,
True,
),
"unparseable-settings": ("{not json", _PAYLOAD, True),
"missing-session-id": (_hooks(_py("print('{}')")), {**_PAYLOAD, "session_id": ""}, True),
"unparseable-payload": (_hooks(_py("print('{}')")), "not json", True),
"no-venv": (_hooks(_py("print('{}')")), _PAYLOAD, False),
}


@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell")
@pytest.mark.parametrize("shell", _outer_shells())
@pytest.mark.parametrize("fault", list(_FAULTS))
def test_every_fault_path_is_at_least_as_strict_as_mains_exit_code(tmp_path, shell, fault):
"""On origin/main each of these exits non-zero through the registered line, never 0."""
settings_text, payload, venv = _FAULTS[fault]
completed = _run_registered(tmp_path, shell, settings_text, payload, venv)
assert completed.returncode != 0, (completed.stdout, completed.stderr)


@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell")
@pytest.mark.parametrize("shell", _outer_shells())
def test_a_hooks_exit_2_reaches_codex_where_the_outer_shell_keeps_it(tmp_path, shell):
completed = _run_registered(tmp_path, shell, _hooks(_py("import sys; sys.exit(2)")))
# pwsh -Command reports a last native program's or script's exit 2 as 1; cmd and sh pass it on.
assert completed.returncode == (1 if shell == "pwsh" else 2), completed.stderr


@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell")
@pytest.mark.parametrize("shell", _outer_shells())
def test_a_deny_and_a_clean_run_exit_0(tmp_path, shell):
deny = _run_registered(tmp_path / "deny", shell, _hooks(_py(f"print({json.dumps(_DENY)!r})")))
assert deny.returncode == 0, deny.stderr
assert json.loads(deny.stdout)["hookSpecificOutput"]["permissionDecision"] == "deny"
clean = _run_registered(tmp_path / "clean", shell, _hooks(_py("print('{}')")))
assert clean.returncode == 0, clean.stderr


# --- The block exit flag. invoke.ps1 passes `--block-exit 10` only for `hook` as its first
# argument, the condition its 10-to-2 mapping uses; without the flag a hook's exit 2 exits 2, as on
# main. The flag is argv, so neither a child nor an inherited environment carries it.

_EXIT_2 = _hooks(_py("import sys; sys.exit(2)"))
# A variable an ancestor could set; the block exit must not depend on the environment.
_OLD_SENTINEL = {"MEFOR_CODEX_BLOCK_SENTINEL": "1"}
_needs_pwsh = pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell")


def _env(**extra):
env = {k: v for k, v in os.environ.items() if k not in _OLD_SENTINEL}
env.update(extra)
return env


def _direct(root, *args, payload=_PAYLOAD, **extra):
bridge_py = root / "scripts/codex/bridge.py"
return _launch([sys.executable, str(bridge_py), *args], root, payload, _env(**extra))


def _invoke_file(root, *args, payload=_PAYLOAD, **extra):
invoke = root / "scripts/codex/invoke.ps1"
argv = ["pwsh", "-NoProfile", "-NonInteractive", "-File", str(invoke), *args]
return _launch(argv, root, payload, _env(**extra))


def _assert_blocked(completed, code):
"""Assert the exit code and the bridge's block line, which a silent blocking hook produces."""
assert completed.returncode == code, completed.stderr
assert "Claude hook blocked this event" in completed.stderr


@_needs_pwsh
def test_the_registered_line_gives_2_for_a_hooks_exit_2(tmp_path):
_assert_blocked(_run_registered(tmp_path, "none", _EXIT_2), 2)


def test_a_direct_bridge_hook_gives_2_for_a_hooks_exit_2(tmp_path):
root = _make_repo(tmp_path, _EXIT_2, venv=False)
_assert_blocked(_direct(root, "hook"), 2)
_assert_blocked(_direct(root, "hook", "--block-exit", "10"), 10)


def test_the_retired_sentinel_variable_does_not_change_the_block_exit(tmp_path):
root = _make_repo(tmp_path, _EXIT_2, venv=False)
_assert_blocked(_direct(root, "hook", **_OLD_SENTINEL), 2)


@_needs_pwsh
def test_invoke_ignores_an_inherited_environment(tmp_path):
root = _make_repo(tmp_path, _EXIT_2)
_assert_blocked(_invoke_file(root, "--session-id", "x", "hook", **_OLD_SENTINEL), 2)


_ARGV_CHILD = "import json, sys\nprint(json.dumps(sys.argv[1:]))\n"


@_needs_pwsh
def test_invoke_adds_no_flag_to_a_run_childs_argv(tmp_path):
root = _make_repo(tmp_path, _hooks())
(root / "scripts/argv.py").write_text(_ARGV_CHILD, encoding="utf-8")
completed = _invoke_file(root, "run", "scripts/argv.py", "--b", "1", CODEX_THREAD_ID="x")
assert completed.returncode == 0, completed.stderr
assert json.loads(completed.stdout) == ["--b", "1"]


@pytest.mark.parametrize("flags", [["--block", "1", "--block-exit", "0"], ["--block-exit", "10"]])
def test_a_run_childs_block_exit_flags_pass_through_as_on_main(tmp_path, flags):
root = _make_repo(tmp_path, _hooks(), venv=False)
(root / "scripts/argv.py").write_text(_ARGV_CHILD, encoding="utf-8")
completed = _direct(root, "--session-id", "x", "run", "scripts/argv.py", *flags)
assert completed.returncode == 0, completed.stderr
assert json.loads(completed.stdout) == flags


def test_only_the_launchers_block_exit_is_honoured(tmp_path):
root = _make_repo(tmp_path, _EXIT_2, venv=False)
_assert_blocked(_direct(root, "hook", "--block-exit", "0"), 2)


@_needs_pwsh
def test_invoke_forwards_a_single_argument_whole(tmp_path):
root = _make_repo(tmp_path, _hooks())
completed = _invoke_file(root, "state-dir", CODEX_THREAD_ID="x")
assert completed.returncode == 0, completed.stderr
assert ".codex" in completed.stdout


@_needs_pwsh
def test_invoke_with_a_flag_before_hook_gives_2(tmp_path):
root = _make_repo(tmp_path, _EXIT_2)
_assert_blocked(_invoke_file(root, "--session-id", "x", "hook"), 2)


@_needs_pwsh
def test_a_run_child_exiting_10_is_not_remapped(tmp_path):
root = _make_repo(tmp_path, _hooks())
(root / "scripts/exit10.py").write_text("import sys\nsys.exit(10)\n", encoding="utf-8")
assert _invoke_file(root, "--session-id", "x", "run", "scripts/exit10.py").returncode == 10
run_first = _invoke_file(root, "run", "scripts/exit10.py", CODEX_THREAD_ID="x")
assert run_first.returncode == 10, run_first.stderr
direct = _direct(root, "--session-id", "x", "run", "scripts/exit10.py")
assert direct.returncode == 10, direct.stderr


# The exit code each fault gave on origin/main, through each launch path. "registered" runs the
# .codex/config.toml line with no outer shell; its pwsh -Command reports the script's exit 2 as 1.
# With no .venv, invoke.ps1 throws before the bridge runs, which exits 1.
_MAIN_FAULT_EXIT = {"registered": 1, "direct": 2, "invoke": 2}


@pytest.mark.parametrize("path", list(_MAIN_FAULT_EXIT))
@pytest.mark.parametrize("fault", list(_FAULTS))
def test_every_fault_path_exits_as_on_main(tmp_path, path, fault):
settings_text, payload, venv = _FAULTS[fault]
if path != "direct" and shutil.which("pwsh") is None:
pytest.skip("requires PowerShell")
if path == "registered":
completed = _run_registered(tmp_path, "none", settings_text, payload, venv)
elif not venv and path == "direct":
pytest.skip("the direct path never reads a .venv")
else:
root = _make_repo(tmp_path, settings_text, venv and path != "direct")
if path == "direct":
completed = _direct(root, "hook", "--block-exit", "10", payload=payload)
else:
completed = _invoke_file(root, "hook", payload=payload)
expected = 1 if not venv else _MAIN_FAULT_EXIT[path]
assert completed.returncode == expected, (completed.stdout, completed.stderr)
Loading