From ae208945ea2ee8ccb8a6c8d1ee2fb6618f9b4b35 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 14:02:46 -0600 Subject: [PATCH 01/51] The Codex bridge follows Claude Code's hook exit contract and honours a hook's shell scripts/codex/bridge.py dispatch would have turned any hook exit other than 0 or 2, a hook timeout, or a hook that cannot start into a blocking exit 2, and stopped running that event's remaining hooks. Claude Code treats only exit 2 as blocking; every other failure is a non-blocking error. The bridge now reports such a failure on stderr, ignores that hook's output, and runs the remaining hooks. Exit 2 still blocks and stops the event. A command-only hook now runs in the shell it names. The tracked SessionStart cloud-setup hook says shell: bash, and the bridge ran it under pwsh on Windows, where it exits 1 on a parse error. bash resolves to Git Bash beside git on Windows. A null or empty discriminator key falls through to the next one, and plain exit-0 stdout from a UserPromptSubmit hook becomes context, as Claude Code does. tests/test_codex_bridge.py now dispatches every hook in the tracked .claude/settings.json, runs its command-only hooks for real, and pins exit 1, 3 and 127, timeout and unstartable hooks as non-blocking and exit 2 as blocking. BACKLOG #5496 BACKLOG #5501 --- docs/CODEX.md | 11 ++- scripts/codex/bridge.py | 106 +++++++++++++++-------- tests/test_codex_bridge.py | 172 +++++++++++++++++++++++++++++++++---- 3 files changed, 231 insertions(+), 58 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 7a99d2674e..67713f6547 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -25,9 +25,14 @@ matches Claude's `PowerShell` name. Patch calls match `apply_patch`, `Edit`, and 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. +shells refuse the event. Exit codes follow Claude Code's hook contract: exit 2 +blocks and stops the event's remaining hooks. Any other non-zero exit, a timeout, +or a command that cannot start is a non-blocking error. The bridge reports it on +stderr, ignores that hook's output, and runs the remaining hooks. It does not +silently claim a failed hook ran. Command-only hooks use the shell they name +(`bash` is Git Bash on Windows), else PowerShell on Windows and `sh` elsewhere; +structured `command` and `args` avoid shell parsing. Hook chains have a 90-second +outer limit. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 8c8b8e1fde..484427795e 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -13,6 +13,7 @@ import json import os import re +import shutil import subprocess import sys from pathlib import Path @@ -160,6 +161,40 @@ def merge_output(result: dict, update: dict) -> None: target["permissionDecisionReason"] = source["permissionDecisionReason"] +def git_bash() -> Path: + """Git for Windows' bash, which Claude Code runs a `shell: bash` hook with on Windows.""" + git = shutil.which("git") + if git: + # git.exe sits in Git/cmd, Git/bin or Git/mingw64/bin. The real shell, usr/bin/bash.exe, goes + # before the bin/bash.exe wrapper that rewrites PATH; tests/_bash_resolver.py is the + # reference copy of this walk, which a standalone script cannot import. + for parent in Path(git).resolve().parents[:3]: + for rel in ("usr/bin/bash.exe", "bin/bash.exe"): + if (parent / rel).is_file(): + return parent / rel + raise FileNotFoundError("Git Bash not found beside git; a shell: bash hook cannot run") + + +def hook_argv(root: Path, hook: dict) -> list[str]: + command = hook["command"] + if "args" in hook: + return [ + command, + *[str(arg).replace("${CLAUDE_PROJECT_DIR}", str(root)) for arg in hook["args"]], + ] + # Command-only sources run in the shell they name, else the current platform's shell. + # Environment expansion belongs to that shell; structured args above need no shell parsing. + shell = hook.get("shell") + if shell == "powershell" or (shell is None and os.name == "nt"): + command = command.replace("${CLAUDE_PROJECT_DIR}", "$env:CLAUDE_PROJECT_DIR") + return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command] + if shell == "bash": + return [str(git_bash()) if os.name == "nt" else "bash", "-c", command] + if shell is None: + return ["sh", "-c", command] + raise ValueError(f"Unsupported Claude hook shell: {shell}") + + def dispatch(root: Path, payload: dict) -> dict: event = payload["hook_event_name"] env = child_environment(root, payload.get("session_id", "")) @@ -190,12 +225,15 @@ def dispatch(root: Path, payload: dict) -> dict: discriminator = ( aliases if event in ("PreToolUse", "PostToolUse", "PermissionRequest") + # The first key with a value: a key Codex sends as null or empty falls through to the next. else { - str( - payload.get( - "source", - payload.get("trigger", payload.get("agent_type", payload.get("reason", ""))), - ) + next( + ( + str(payload[key]) + for key in ("source", "trigger", "agent_type", "reason") + if payload.get(key) + ), + "", ) } ) @@ -210,48 +248,44 @@ def dispatch(root: Path, payload: dict) -> dict: raise ValueError( f"Unsupported Claude hook transport: {hook.get('type')}, async={hook.get('async', False)}" ) - command = hook["command"] - if "args" in hook: - argv = [ - command, - *[str(arg).replace("${CLAUDE_PROJECT_DIR}", str(root)) for arg in hook["args"]], - ] - else: - # Command-only sources use the current platform's shell. Environment expansion - # belongs to that shell; structured args above need no shell parsing. - command = command.replace( - "${CLAUDE_PROJECT_DIR}", - "$env:CLAUDE_PROJECT_DIR" if os.name == "nt" else "${CLAUDE_PROJECT_DIR}", - ) - argv = ( - ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command] - if os.name == "nt" - else ["sh", "-c", command] + # Claude Code's hook contract: exit 2 blocks; any other failure, a timeout or a command + # that cannot start included, is a non-blocking error reported on stderr, and the + # remaining hooks still run. Only a successful hook's stdout is read. + try: + completed = subprocess.run( # nosec B603 - trusted repo hook; stdin carries event data + hook_argv(root, hook), + input=json.dumps(payload), + cwd=root, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=hook.get("timeout", 30), + check=False, ) - completed = subprocess.run( # nosec B603 - trusted repo hook; event data is stdin only - argv, - input=json.dumps(payload), - cwd=root, - env=env, - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - timeout=hook.get("timeout", 30), - check=False, - ) + except (OSError, subprocess.TimeoutExpired) as exc: + print(f"Codex bridge: hook did not complete, not blocking: {exc}", file=sys.stderr) + continue if completed.stderr: print(completed.stderr, file=sys.stderr, end="") if completed.returncode == 2: raise PermissionError(completed.stderr or "Claude hook blocked this event") - completed.check_returncode() + if completed.returncode: + print( + f"Codex bridge: hook exited {completed.returncode}, not blocking: " + f"{hook['command']}", + file=sys.stderr, + ) + continue output = completed.stdout.strip() if not output: continue try: update = json.loads(output) except json.JSONDecodeError: - if event != "SessionStart": + # Claude Code adds plain exit-0 stdout as context for these two events only. + if event not in ("SessionStart", "UserPromptSubmit"): print(output, file=sys.stderr) continue output = output.replace( diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 49a8fd8e63..800c436ee1 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -7,6 +7,7 @@ import importlib.util import json import os +import re import shutil import subprocess import sys @@ -26,16 +27,36 @@ def bridge(): return module -def settings(root, handlers, event="PreToolUse"): +def settings(root, handlers, event="PreToolUse", matcher="Bash"): (root / ".claude").mkdir(exist_ok=True) (root / ".claude/settings.json").write_text( - json.dumps({"hooks": {event: [{"matcher": "Bash", "hooks": handlers}]}}), + json.dumps({"hooks": {event: [{"matcher": matcher, "hooks": handlers}]}}), encoding="utf-8", ) +def python(source, **extra): + return {"type": "command", "command": sys.executable, "args": ["-c", source], **extra} + + def handler(text): - return {"type": "command", "command": sys.executable, "args": ["-c", f"print({text!r})"]} + return python(f"print({text!r})") + + +def exits(code, stdout=""): + return python( + f"print({stdout!r}); import sys; sys.stderr.write('hook says {code}'); sys.exit({code})" + ) + + +DENIAL = { + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "deny", + "permissionDecisionReason": "later hook ran", + } +} +BASH_CALL = {"session_id": "x", "hook_event_name": "PreToolUse", "tool_name": "Bash"} def test_reads_current_source_each_time_and_preserves_denial(bridge, tmp_path): @@ -99,22 +120,135 @@ def test_new_unsupported_hook_is_reported(bridge, tmp_path): ) -def test_hook_timeout_is_reported(bridge, tmp_path): - settings( - tmp_path, - [ - { - "type": "command", - "command": sys.executable, - "args": ["-c", "import time; time.sleep(5)"], - "timeout": 0.1, - } - ], - ) - with pytest.raises(subprocess.TimeoutExpired): - bridge.dispatch( - tmp_path, {"session_id": "x", "hook_event_name": "PreToolUse", "tool_name": "Bash"} - ) +def test_hook_timeout_is_reported_without_blocking_later_hooks(bridge, tmp_path, capsys): + """Claude Code treats a timed-out hook as a non-blocking error, and so must the bridge.""" + slow = python("import time; time.sleep(5)", timeout=0.1) + settings(tmp_path, [slow, handler(json.dumps(DENIAL))]) + assert bridge.dispatch(tmp_path, BASH_CALL) == DENIAL + assert "not blocking" in capsys.readouterr().err + + +@pytest.mark.parametrize("code", [1, 3, 127]) +def test_non_blocking_exit_is_reported_and_later_hooks_still_run(bridge, tmp_path, capsys, code): + """Only exit 2 blocks. Another non-zero exit must neither block nor stop the hooks after it.""" + # The failing hook's stdout is not read, so its "continue": false must not reach the result. + settings(tmp_path, [exits(code, stdout='{"continue": false}'), handler(json.dumps(DENIAL))]) + assert bridge.dispatch(tmp_path, BASH_CALL) == DENIAL + err = capsys.readouterr().err + assert f"hook says {code}" in err + assert f"exited {code}, not blocking" in err + + +def test_unstartable_hook_is_reported_without_blocking(bridge, tmp_path, capsys): + missing = {"type": "command", "command": str(tmp_path / "no-such-hook.exe"), "args": []} + settings(tmp_path, [missing, handler(json.dumps(DENIAL))]) + assert bridge.dispatch(tmp_path, BASH_CALL) == DENIAL + assert "not blocking" in capsys.readouterr().err + + +def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path): + marker = tmp_path / "later-hook-ran" + settings(tmp_path, [exits(2), python(f"open({str(marker)!r}, 'w').close()")]) + with pytest.raises(PermissionError, match="hook says 2"): + bridge.dispatch(tmp_path, BASH_CALL) + assert not marker.exists() + + +def test_null_discriminator_key_falls_through_to_the_next(bridge, tmp_path): + settings(tmp_path, [handler(json.dumps(DENIAL))], event="SubagentStart", matcher="^worker$") + payload = { + "session_id": "x", + "hook_event_name": "SubagentStart", + "source": None, + "agent_type": "worker", + } + assert bridge.dispatch(tmp_path, payload) == DENIAL + + +def test_plain_prompt_hook_output_becomes_context(bridge, tmp_path): + settings(tmp_path, [handler("remember the brief")], event="UserPromptSubmit", matcher="") + result = bridge.dispatch(tmp_path, {"session_id": "x", "hook_event_name": "UserPromptSubmit"}) + assert result["hookSpecificOutput"]["additionalContext"] == "remember the brief" + + +# Tool names a tracked tool-event matcher is tried against. A new matcher that selects none of +# them fails the test below and names itself, rather than going undispatched. +_TOOL_NAMES = ("Bash", "PowerShell", "Agent", "Task", "Workflow", "EnterWorktree", "Edit", "Write") + + +def _tracked_settings(): + return json.loads((ROOT / ".claude/settings.json").read_text(encoding="utf-8-sig")) + + +def test_every_hook_in_the_tracked_settings_dispatches_to_a_runnable_argv( + bridge, tmp_path, monkeypatch +): + """Read the tracked .claude/settings.json, not a synthetic one, and dispatch each group. + + The subprocess is recorded, not run: the tracked hooks write the live seat registry. + """ + tracked = _tracked_settings() + (tmp_path / ".claude").mkdir() + (tmp_path / ".claude/settings.json").write_text(json.dumps(tracked), encoding="utf-8") + calls: list[list[str]] = [] + + def record(argv, **kwargs): + calls.append(argv) + return subprocess.CompletedProcess(argv, 0, "", "") + + monkeypatch.setattr(bridge.subprocess, "run", record) + monkeypatch.setattr(bridge, "git_bash", lambda: Path("git-bash/bin/bash.exe")) + assert tracked["hooks"], "the tracked settings wire no hooks; this test proves nothing" + for event, groups in tracked["hooks"].items(): + assert event in bridge.EVENTS, f"{event} has no Codex adapter" + for group in groups: + payload = {"session_id": "x", "hook_event_name": event} + matcher = group.get("matcher", "") + if matcher not in ("", "*"): + assert event in ("PreToolUse", "PostToolUse", "PermissionRequest"), event + names = [name for name in _TOOL_NAMES if re.search(matcher, name)] + assert names, f"no tool name in _TOOL_NAMES selects matcher {matcher!r}" + payload["tool_name"] = names[0] + calls.clear() + bridge.dispatch(tmp_path, payload) + for hook in group["hooks"]: + if "args" in hook: + expected = [ + hook["command"], + *(a.replace("${CLAUDE_PROJECT_DIR}", str(tmp_path)) for a in hook["args"]), + ] + assert expected in calls, (event, hook["command"]) + else: + shell = hook.get("shell") + assert shell in (None, "bash", "powershell"), shell + runs = [argv for argv in calls if hook["command"] in argv[-1]] + assert len(runs) == 1, (event, hook["command"], calls) + if shell == "bash": + assert Path(runs[0][0]).stem == "bash" + assert runs[0][1:] == ["-c", hook["command"]] + + +def test_tracked_command_only_hooks_run_cleanly_through_their_shell(bridge, tmp_path, capsys): + """Run each tracked command-only hook for real. The bridge strips CLAUDE_*, so the cloud-only + gate exits 0 before its script runs; under the wrong shell it would exit non-zero instead.""" + hooks = [ + hook + for groups in _tracked_settings()["hooks"].values() + for group in groups + for hook in group["hooks"] + if "args" not in hook + ] + if not hooks: + pytest.skip("the tracked settings carry no command-only hook") + if os.name == "nt" and any(hook.get("shell") == "bash" for hook in hooks): + try: + bridge.git_bash() + except FileNotFoundError: + pytest.skip("Git Bash is not installed") + for hook in hooks: + settings(tmp_path, [hook], event="SessionStart", matcher="") + bridge.dispatch(tmp_path, {"session_id": "x", "hook_event_name": "SessionStart"}) + assert "not blocking" not in capsys.readouterr().err, hook["command"] @pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") From 99128fac068e6c2b74324d602a3b44b1cb575ec3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 14:20:28 -0600 Subject: [PATCH 02/51] The Codex bridge keeps a PowerShell hook's exit 2 and matches Claude Code's defaults Review round 1 on the hook exit contract change. A command-only PowerShell hook whose last statement is a native program would have reported that program's exit 2 as 1, which the new contract treats as non-blocking, so the block would have failed open; the bridge now passes $LASTEXITCODE on. A hook may set onFailure to block, as in Claude Code, to make a timeout or a non-2 exit block. A command-only hook with no shell now runs in bash, Claude Code's default, Git Bash on Windows or PowerShell there when Git Bash is missing. Git Bash is the bin/bash.exe wrapper, found through CLAUDE_CODE_GIT_BASH_PATH or beside git. Each event matches its own payload field, and a matcher on an event that has none, such as UserPromptSubmit, is ignored. JSON stdout that is not an object is plain output rather than a blocking error. A non-blocking failure names its hook, and an exit 2 reason is no longer printed twice. docs/CODEX.md states where the bridge still differs from Claude Code. BACKLOG #5496 BACKLOG #5501 --- docs/CODEX.md | 23 +++--- scripts/codex/bridge.py | 143 ++++++++++++++++++++++--------------- tests/test_codex_bridge.py | 124 +++++++++++++++++++++----------- 3 files changed, 186 insertions(+), 104 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 67713f6547..e5b33f492d 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -25,14 +25,21 @@ matches Claude's `PowerShell` name. Patch calls match `apply_patch`, `Edit`, and adapter; alias matching alone cannot translate an edit payload. New event types appear as unmapped at startup. Unsupported handler types and -shells refuse the event. Exit codes follow Claude Code's hook contract: exit 2 -blocks and stops the event's remaining hooks. Any other non-zero exit, a timeout, -or a command that cannot start is a non-blocking error. The bridge reports it on -stderr, ignores that hook's output, and runs the remaining hooks. It does not -silently claim a failed hook ran. Command-only hooks use the shell they name -(`bash` is Git Bash on Windows), else PowerShell on Windows and `sh` elsewhere; -structured `command` and `args` avoid shell parsing. Hook chains have a 90-second -outer limit. +shells refuse the event. As in Claude Code, exit 2 blocks. Any other non-zero +exit, a timeout, or a command that cannot start is a non-blocking error, unless +the hook sets `"onFailure": "block"`. The bridge reports a non-blocking error on +stderr, naming the hook, ignores that hook's output, and runs the remaining hooks. +It does not silently claim a failed hook ran. + +The bridge differs from Claude Code in at least three ways. It runs an event's +hooks one after another, where Claude Code runs them in parallel. Exit 2 stops +the remaining hooks, and the bridge exits 2 on every event, including events +where Claude Code only shows the hook's stderr. Hook chains have a 90-second outer +limit, so the timeouts of a long chain add up against it. + +Command-only hooks use the shell they name. With none, they use bash, as Claude +Code does: Git Bash on Windows, else PowerShell there when Git Bash is missing. +Structured `command` and `args` avoid shell parsing. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 484427795e..c18a45c4d6 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -161,18 +161,34 @@ def merge_output(result: dict, update: dict) -> None: target["permissionDecisionReason"] = source["permissionDecisionReason"] -def git_bash() -> Path: - """Git for Windows' bash, which Claude Code runs a `shell: bash` hook with on Windows.""" +TOOL_EVENTS = ("PreToolUse", "PostToolUse", "PermissionRequest") +# The payload field a matcher is compared with. Claude Code ignores a matcher on every other event, +# UserPromptSubmit and Stop among them, so the bridge runs those groups unconditionally. +MATCHER_FIELDS = { + "SessionStart": "source", + "SessionEnd": "reason", + "PreCompact": "trigger", + "PostCompact": "trigger", + "SubagentStart": "agent_type", + "SubagentStop": "agent_type", +} +# Claude Code adds a hook's plain exit-0 stdout as context for these events only. +PLAIN_CONTEXT_EVENTS = ("SessionStart", "UserPromptSubmit") + + +def git_bash() -> str | None: + """The Git Bash that Claude Code runs a bash hook with on Windows, or None if there is none.""" + configured = os.environ.get("CLAUDE_CODE_GIT_BASH_PATH") + if configured and Path(configured).is_file(): + return configured git = shutil.which("git") if git: - # git.exe sits in Git/cmd, Git/bin or Git/mingw64/bin. The real shell, usr/bin/bash.exe, goes - # before the bin/bash.exe wrapper that rewrites PATH; tests/_bash_resolver.py is the - # reference copy of this walk, which a standalone script cannot import. - for parent in Path(git).resolve().parents[:3]: - for rel in ("usr/bin/bash.exe", "bin/bash.exe"): - if (parent / rel).is_file(): - return parent / rel - raise FileNotFoundError("Git Bash not found beside git; a shell: bash hook cannot run") + # git.exe sits in Git/cmd, Git/bin or Git/mingw64/bin. Git/bin/bash.exe is the wrapper that + # puts Git's usr/bin and mingw64/bin on PATH, so a hook's own cat or grep resolves. + for parent in Path(git).resolve().parents: + if (parent / "bin/bash.exe").is_file(): + return str(parent / "bin/bash.exe") + return None def hook_argv(root: Path, hook: dict) -> list[str]: @@ -182,19 +198,40 @@ def hook_argv(root: Path, hook: dict) -> list[str]: command, *[str(arg).replace("${CLAUDE_PROJECT_DIR}", str(root)) for arg in hook["args"]], ] - # Command-only sources run in the shell they name, else the current platform's shell. - # Environment expansion belongs to that shell; structured args above need no shell parsing. + # A command-only source runs in the shell it names. Claude Code's default is bash, and on + # Windows PowerShell when Git Bash is not installed. Environment expansion belongs to that + # shell; structured args above need no shell parsing. shell = hook.get("shell") - if shell == "powershell" or (shell is None and os.name == "nt"): + bash = git_bash() if os.name == "nt" else "bash" + if shell == "bash" or (shell is None and bash): + if not bash: + raise FileNotFoundError("Git Bash not found; a shell: bash hook cannot run") + return [bash, "-c", command] + if shell in ("powershell", None): command = command.replace("${CLAUDE_PROJECT_DIR}", "$env:CLAUDE_PROJECT_DIR") - return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command] - if shell == "bash": - return [str(git_bash()) if os.name == "nt" else "bash", "-c", command] - if shell is None: - return ["sh", "-c", command] + # -Command reports a native program's exit 2 as 1, which would turn a block into a + # non-blocking error; passing $LASTEXITCODE on keeps it. + return [ + "pwsh", + "-NoProfile", + "-NonInteractive", + "-Command", + f"{command}\nexit $LASTEXITCODE", + ] raise ValueError(f"Unsupported Claude hook shell: {shell}") +def hook_failed(hook: dict, why: str) -> None: + """Report a failure Claude Code treats as non-blocking, unless the hook opts into blocking.""" + label = hook.get("statusMessage") or " ".join( + [hook["command"], *(str(arg) for arg in hook.get("args", []))] + ) + message = f"Codex bridge: hook {why}: {label}" + if hook.get("onFailure") == "block": + raise PermissionError(f"{message} (onFailure is block)") + print(f"{message} (not blocking)", file=sys.stderr) + + def dispatch(root: Path, payload: dict) -> dict: event = payload["hook_event_name"] env = child_environment(root, payload.get("session_id", "")) @@ -217,30 +254,21 @@ def dispatch(root: Path, payload: dict) -> dict: merge_output( result, {"hookSpecificOutput": {"hookEventName": event, "additionalContext": context}} ) - aliases = {str(payload.get("tool_name", ""))} - if "Bash" in aliases: - aliases.add("PowerShell") - if "apply_patch" in aliases: - aliases.update(("Edit", "Write")) - discriminator = ( - aliases - if event in ("PreToolUse", "PostToolUse", "PermissionRequest") - # The first key with a value: a key Codex sends as null or empty falls through to the next. - else { - next( - ( - str(payload[key]) - for key in ("source", "trigger", "agent_type", "reason") - if payload.get(key) - ), - "", - ) - } - ) + discriminator: set[str] | None = None + if event in TOOL_EVENTS: + discriminator = {str(payload.get("tool_name", ""))} + if "Bash" in discriminator: + discriminator.add("PowerShell") + if "apply_patch" in discriminator: + discriminator.update(("Edit", "Write")) + elif event in MATCHER_FIELDS: + discriminator = {str(payload.get(MATCHER_FIELDS[event]) or "")} for group in config.get("hooks", {}).get(event, []): matcher = group.get("matcher", "") - if matcher not in ("", "*") and not any( - re.search(matcher, value) for value in discriminator + if ( + discriminator is not None + and matcher not in ("", "*") + and not any(re.search(matcher, value) for value in discriminator) ): continue for hook in group.get("hooks", []): @@ -248,9 +276,9 @@ def dispatch(root: Path, payload: dict) -> dict: raise ValueError( f"Unsupported Claude hook transport: {hook.get('type')}, async={hook.get('async', False)}" ) - # Claude Code's hook contract: exit 2 blocks; any other failure, a timeout or a command - # that cannot start included, is a non-blocking error reported on stderr, and the - # remaining hooks still run. Only a successful hook's stdout is read. + # Claude Code's hook contract: exit 2 blocks. Any other failure, a timeout or a command + # that cannot start included, is a non-blocking error unless the hook sets onFailure to + # block, and the remaining hooks still run. Only a successful hook's stdout is read. try: completed = subprocess.run( # nosec B603 - trusted repo hook; stdin carries event data hook_argv(root, hook), @@ -264,19 +292,23 @@ def dispatch(root: Path, payload: dict) -> dict: timeout=hook.get("timeout", 30), check=False, ) - except (OSError, subprocess.TimeoutExpired) as exc: - print(f"Codex bridge: hook did not complete, not blocking: {exc}", file=sys.stderr) + except subprocess.TimeoutExpired as exc: + if exc.stderr: + captured = exc.stderr + if isinstance(captured, bytes): + captured = captured.decode("utf-8", "replace") + print(captured, file=sys.stderr, end="") + hook_failed(hook, f"timed out after {exc.timeout} seconds") + continue + except OSError as exc: + hook_failed(hook, f"could not start ({exc})") continue + if completed.returncode == 2: + raise PermissionError(completed.stderr.strip() or "Claude hook blocked this event") if completed.stderr: print(completed.stderr, file=sys.stderr, end="") - if completed.returncode == 2: - raise PermissionError(completed.stderr or "Claude hook blocked this event") if completed.returncode: - print( - f"Codex bridge: hook exited {completed.returncode}, not blocking: " - f"{hook['command']}", - file=sys.stderr, - ) + hook_failed(hook, f"exited {completed.returncode}") continue output = completed.stdout.strip() if not output: @@ -284,8 +316,9 @@ def dispatch(root: Path, payload: dict) -> dict: try: update = json.loads(output) except json.JSONDecodeError: - # Claude Code adds plain exit-0 stdout as context for these two events only. - if event not in ("SessionStart", "UserPromptSubmit"): + update = None + if not isinstance(update, dict): + if event not in PLAIN_CONTEXT_EVENTS: print(output, file=sys.stderr) continue output = output.replace( @@ -295,8 +328,6 @@ def dispatch(root: Path, payload: dict) -> dict: update = { "hookSpecificOutput": {"hookEventName": event, "additionalContext": output} } - if not isinstance(update, dict): - raise ValueError("Hook JSON output must be an object") merge_output(result, update) return result diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 800c436ee1..08e6141f35 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -122,10 +122,10 @@ def test_new_unsupported_hook_is_reported(bridge, tmp_path): def test_hook_timeout_is_reported_without_blocking_later_hooks(bridge, tmp_path, capsys): """Claude Code treats a timed-out hook as a non-blocking error, and so must the bridge.""" - slow = python("import time; time.sleep(5)", timeout=0.1) + slow = python("import time; time.sleep(5)", timeout=0.1, statusMessage="the slow hook") settings(tmp_path, [slow, handler(json.dumps(DENIAL))]) assert bridge.dispatch(tmp_path, BASH_CALL) == DENIAL - assert "not blocking" in capsys.readouterr().err + assert "timed out after 0.1 seconds: the slow hook (not blocking)" in capsys.readouterr().err @pytest.mark.parametrize("code", [1, 3, 127]) @@ -136,44 +136,91 @@ def test_non_blocking_exit_is_reported_and_later_hooks_still_run(bridge, tmp_pat assert bridge.dispatch(tmp_path, BASH_CALL) == DENIAL err = capsys.readouterr().err assert f"hook says {code}" in err - assert f"exited {code}, not blocking" in err + assert f"exited {code}: " in err + assert "(not blocking)" in err def test_unstartable_hook_is_reported_without_blocking(bridge, tmp_path, capsys): missing = {"type": "command", "command": str(tmp_path / "no-such-hook.exe"), "args": []} settings(tmp_path, [missing, handler(json.dumps(DENIAL))]) assert bridge.dispatch(tmp_path, BASH_CALL) == DENIAL - assert "not blocking" in capsys.readouterr().err + assert "could not start" in capsys.readouterr().err -def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path): +@pytest.mark.parametrize( + "failing", + [exits(1), python("import time; time.sleep(5)", timeout=0.1)], + ids=["exit-1", "timeout"], +) +def test_on_failure_block_turns_a_non_blocking_failure_into_a_block(bridge, tmp_path, failing): + settings(tmp_path, [{**failing, "onFailure": "block"}, handler(json.dumps(DENIAL))]) + with pytest.raises(PermissionError, match="onFailure is block"): + bridge.dispatch(tmp_path, BASH_CALL) + + +def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): marker = tmp_path / "later-hook-ran" settings(tmp_path, [exits(2), python(f"open({str(marker)!r}, 'w').close()")]) with pytest.raises(PermissionError, match="hook says 2"): bridge.dispatch(tmp_path, BASH_CALL) assert not marker.exists() + # The reason travels once, in the PermissionError main() prints, not also as raw stderr. + assert "hook says 2" not in capsys.readouterr().err -def test_null_discriminator_key_falls_through_to_the_next(bridge, tmp_path): +@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") +def test_a_native_exit_2_inside_a_powershell_hook_still_blocks(bridge, tmp_path): + """pwsh -Command reports a native program's exit 2 as 1, which would fail open.""" + command = f"& '{sys.executable}' -c 'import sys; sys.exit(2)'" + settings(tmp_path, [{"type": "command", "shell": "powershell", "command": command}]) + with pytest.raises(PermissionError): + bridge.dispatch(tmp_path, BASH_CALL) + + +def test_each_event_matches_its_own_discriminator_field(bridge, tmp_path): settings(tmp_path, [handler(json.dumps(DENIAL))], event="SubagentStart", matcher="^worker$") - payload = { - "session_id": "x", - "hook_event_name": "SubagentStart", - "source": None, - "agent_type": "worker", - } - assert bridge.dispatch(tmp_path, payload) == DENIAL + payload = {"session_id": "x", "hook_event_name": "SubagentStart", "agent_type": "worker"} + # A null, or another event's field, must not stand in for SubagentStart's agent_type. + for other in (None, "", "startup"): + assert bridge.dispatch(tmp_path, {**payload, "source": other}) == DENIAL -def test_plain_prompt_hook_output_becomes_context(bridge, tmp_path): - settings(tmp_path, [handler("remember the brief")], event="UserPromptSubmit", matcher="") +def test_a_matcher_on_an_event_without_one_is_ignored(bridge, tmp_path): + """Claude Code ignores a matcher on UserPromptSubmit, so the bridge must still run the group.""" + settings(tmp_path, [handler("remember the brief")], event="UserPromptSubmit", matcher=".+") result = bridge.dispatch(tmp_path, {"session_id": "x", "hook_event_name": "UserPromptSubmit"}) assert result["hookSpecificOutput"]["additionalContext"] == "remember the brief" -# Tool names a tracked tool-event matcher is tried against. A new matcher that selects none of -# them fails the test below and names itself, rather than going undispatched. +@pytest.mark.parametrize("stdout", ["remember the brief", "3", "true", '["a list"]']) +def test_plain_or_non_object_prompt_hook_output_becomes_context(bridge, tmp_path, stdout): + settings(tmp_path, [handler(stdout)], event="UserPromptSubmit", matcher="") + result = bridge.dispatch(tmp_path, {"session_id": "x", "hook_event_name": "UserPromptSubmit"}) + assert result["hookSpecificOutput"]["additionalContext"] == stdout + + +def test_non_object_json_on_a_tool_event_is_not_a_block(bridge, tmp_path, capsys): + settings(tmp_path, [handler("3")]) + assert bridge.dispatch(tmp_path, BASH_CALL) == {} + assert "3" in capsys.readouterr().err + + +def test_a_command_only_hook_defaults_to_bash_then_powershell(bridge, tmp_path, monkeypatch): + """Claude Code's default shell is bash, or PowerShell on Windows when Git Bash is missing.""" + hook = {"type": "command", "command": "echo hi"} + monkeypatch.setattr(bridge, "git_bash", lambda: "git/bin/bash.exe") + assert Path(bridge.hook_argv(tmp_path, hook)[0]).stem == "bash" + if os.name == "nt": + monkeypatch.setattr(bridge, "git_bash", lambda: None) + assert bridge.hook_argv(tmp_path, hook)[0] == "pwsh" + with pytest.raises(FileNotFoundError): + bridge.hook_argv(tmp_path, {**hook, "shell": "bash"}) + + +# Values a tracked matcher is tried against, per event's discriminator. A new matcher that selects +# none of them fails the test below and names itself, rather than going undispatched. _TOOL_NAMES = ("Bash", "PowerShell", "Agent", "Task", "Workflow", "EnterWorktree", "Edit", "Write") +_FIELD_VALUES = ("startup", "resume", "clear", "compact", "manual", "auto", "logout", "other") def _tracked_settings(): @@ -197,7 +244,7 @@ def record(argv, **kwargs): return subprocess.CompletedProcess(argv, 0, "", "") monkeypatch.setattr(bridge.subprocess, "run", record) - monkeypatch.setattr(bridge, "git_bash", lambda: Path("git-bash/bin/bash.exe")) + monkeypatch.setattr(bridge, "git_bash", lambda: "git/bin/bash.exe") assert tracked["hooks"], "the tracked settings wire no hooks; this test proves nothing" for event, groups in tracked["hooks"].items(): assert event in bridge.EVENTS, f"{event} has no Codex adapter" @@ -205,32 +252,32 @@ def record(argv, **kwargs): payload = {"session_id": "x", "hook_event_name": event} matcher = group.get("matcher", "") if matcher not in ("", "*"): - assert event in ("PreToolUse", "PostToolUse", "PermissionRequest"), event - names = [name for name in _TOOL_NAMES if re.search(matcher, name)] - assert names, f"no tool name in _TOOL_NAMES selects matcher {matcher!r}" - payload["tool_name"] = names[0] + if event in bridge.TOOL_EVENTS: + field, values = "tool_name", _TOOL_NAMES + else: + field, values = bridge.MATCHER_FIELDS.get(event, "ignored"), _FIELD_VALUES + names = [value for value in values if re.search(matcher, value)] + assert names, f"no value in the test's lists selects {event} matcher {matcher!r}" + payload[field] = names[0] calls.clear() bridge.dispatch(tmp_path, payload) for hook in group["hooks"]: + argv = bridge.hook_argv(tmp_path, hook) + assert argv in calls, (event, hook["command"], calls) if "args" in hook: - expected = [ - hook["command"], - *(a.replace("${CLAUDE_PROJECT_DIR}", str(tmp_path)) for a in hook["args"]), - ] - assert expected in calls, (event, hook["command"]) + assert argv[0] == hook["command"] + assert not any("${CLAUDE_PROJECT_DIR}" in arg for arg in argv), argv else: - shell = hook.get("shell") - assert shell in (None, "bash", "powershell"), shell - runs = [argv for argv in calls if hook["command"] in argv[-1]] - assert len(runs) == 1, (event, hook["command"], calls) - if shell == "bash": - assert Path(runs[0][0]).stem == "bash" - assert runs[0][1:] == ["-c", hook["command"]] + assert hook.get("shell") in (None, "bash", "powershell"), hook + if hook.get("shell", "bash") == "bash": + assert Path(argv[0]).stem == "bash" + assert argv[1:] == ["-c", hook["command"]] def test_tracked_command_only_hooks_run_cleanly_through_their_shell(bridge, tmp_path, capsys): """Run each tracked command-only hook for real. The bridge strips CLAUDE_*, so the cloud-only - gate exits 0 before its script runs; under the wrong shell it would exit non-zero instead.""" + gate exits 0 before its script runs. On Windows the wrong shell, pwsh, cannot parse it and + exits 1; on POSIX sh would exit 0 too, so the argv test above is the control there.""" hooks = [ hook for groups in _tracked_settings()["hooks"].values() @@ -240,11 +287,8 @@ def test_tracked_command_only_hooks_run_cleanly_through_their_shell(bridge, tmp_ ] if not hooks: pytest.skip("the tracked settings carry no command-only hook") - if os.name == "nt" and any(hook.get("shell") == "bash" for hook in hooks): - try: - bridge.git_bash() - except FileNotFoundError: - pytest.skip("Git Bash is not installed") + if os.name == "nt" and bridge.git_bash() is None: + pytest.skip("Git Bash is not installed") for hook in hooks: settings(tmp_path, [hook], event="SessionStart", matcher="") bridge.dispatch(tmp_path, {"session_id": "x", "hook_event_name": "SessionStart"}) From a684879313d396386ea3531981d25605657045b6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 14:48:12 -0600 Subject: [PATCH 03/51] The Codex transport passes the bridge's exit 2 on, and PowerShell hooks keep only exit 2 Review round 2. Codex starts the bridge through pwsh -Command, which reports a script's exit 2 as 1, so a block the bridge raised would have reached Codex as exit 1. invoke.ps1 now ends the process with the bridge's code in hook mode, and each registered command in .codex/config.toml ends with an exit that passes the code on where PowerShell runs it. A command-only PowerShell hook passes on exit 2 only when its last statement failed with exit code 2, so a stale code from an earlier statement neither blocks nor hides a failure. A non-blocking failure also reaches the result as a systemMessage, and a hook's stderr ends its own line. ${CLAUDE_PROJECT_DIR} is substituted in a structured hook's command, and braced for PowerShell. Git Bash is looked up only for a bash hook, within Git's own layout. BACKLOG #5496 BACKLOG #5501 --- .codex/config.toml | 25 +++++----- docs/CODEX.md | 6 ++- scripts/codex/bridge.py | 67 ++++++++++++++------------- scripts/codex/invoke.ps1 | 4 ++ tests/test_codex_bridge.py | 95 ++++++++++++++++++++++++++++++++------ 5 files changed, 138 insertions(+), 59 deletions(-) diff --git a/.codex/config.toml b/.codex/config.toml index 06d58d1e21..f658c4f958 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -1,69 +1,72 @@ # Claude Code remains the source of hook policy. The bridge reads it on each event. +# pwsh -Command reports a native program's exit 2 as 1. The trailing exit passes the bridge's code +# on where PowerShell runs this line; under sh it exits with pwsh's status, and under cmd pwsh +# receives it as more of its -Command text. [features] hooks = true [[hooks.SessionStart]] [[hooks.SessionStart.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' timeout = 90 [[hooks.SessionEnd]] [[hooks.SessionEnd.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' timeout = 90 [[hooks.PreToolUse]] [[hooks.PreToolUse.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' timeout = 90 [[hooks.PostToolUse]] [[hooks.PostToolUse.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' timeout = 90 [[hooks.PermissionRequest]] [[hooks.PermissionRequest.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' timeout = 90 [[hooks.UserPromptSubmit]] [[hooks.UserPromptSubmit.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' timeout = 90 [[hooks.PreCompact]] [[hooks.PreCompact.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' timeout = 90 [[hooks.PostCompact]] [[hooks.PostCompact.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' timeout = 90 [[hooks.Stop]] [[hooks.Stop.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' timeout = 90 [[hooks.SubagentStart]] [[hooks.SubagentStart.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' timeout = 90 [[hooks.SubagentStop]] [[hooks.SubagentStop.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' timeout = 90 diff --git a/docs/CODEX.md b/docs/CODEX.md index e5b33f492d..22a42a6c01 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -28,8 +28,10 @@ New event types appear as unmapped at startup. Unsupported handler types and shells refuse the event. As in Claude Code, exit 2 blocks. Any other non-zero exit, a timeout, or a command that cannot start is a non-blocking error, unless the hook sets `"onFailure": "block"`. The bridge reports a non-blocking error on -stderr, naming the hook, ignores that hook's output, and runs the remaining hooks. -It does not silently claim a failed hook ran. +stderr and as a `systemMessage`, naming the hook, ignores that hook's output, and +runs the remaining hooks. It does not silently claim a failed hook ran. A block +leaves the bridge with exit 2, and the registered command and `invoke.ps1` pass +that code on, because `pwsh -Command` would report it as 1. The bridge differs from Claude Code in at least three ways. It runs an event's hooks one after another, where Claude Code runs them in parallel. Exit 2 stops diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index c18a45c4d6..11da045085 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -179,49 +179,49 @@ def merge_output(result: dict, update: dict) -> None: def git_bash() -> str | None: """The Git Bash that Claude Code runs a bash hook with on Windows, or None if there is none.""" configured = os.environ.get("CLAUDE_CODE_GIT_BASH_PATH") - if configured and Path(configured).is_file(): - return configured + if configured: + return configured # As set: a wrong path then fails to start and is reported. git = shutil.which("git") if git: # git.exe sits in Git/cmd, Git/bin or Git/mingw64/bin. Git/bin/bash.exe is the wrapper that # puts Git's usr/bin and mingw64/bin on PATH, so a hook's own cat or grep resolves. - for parent in Path(git).resolve().parents: + for parent in Path(git).resolve().parents[:3]: if (parent / "bin/bash.exe").is_file(): return str(parent / "bin/bash.exe") return None +# -Command reports a native program's exit 2 as 1, which would turn a block into a non-blocking +# error. This tail keeps -Command's own result, 0 or 1, except that a failed last statement which +# left exit code 2 behind exits 2. +POWERSHELL_EXIT_TAIL = "\nif (-not $?) { if ($LASTEXITCODE -eq 2) { exit 2 }; exit 1 }" + + def hook_argv(root: Path, hook: dict) -> list[str]: command = hook["command"] if "args" in hook: return [ - command, - *[str(arg).replace("${CLAUDE_PROJECT_DIR}", str(root)) for arg in hook["args"]], + str(part).replace("${CLAUDE_PROJECT_DIR}", str(root)) + for part in (command, *hook["args"]) ] # A command-only source runs in the shell it names. Claude Code's default is bash, and on # Windows PowerShell when Git Bash is not installed. Environment expansion belongs to that # shell; structured args above need no shell parsing. shell = hook.get("shell") - bash = git_bash() if os.name == "nt" else "bash" - if shell == "bash" or (shell is None and bash): - if not bash: + if shell in ("bash", None): + bash = git_bash() if os.name == "nt" else "bash" + if bash: + return [bash, "-c", command] + if shell == "bash": raise FileNotFoundError("Git Bash not found; a shell: bash hook cannot run") - return [bash, "-c", command] - if shell in ("powershell", None): - command = command.replace("${CLAUDE_PROJECT_DIR}", "$env:CLAUDE_PROJECT_DIR") - # -Command reports a native program's exit 2 as 1, which would turn a block into a - # non-blocking error; passing $LASTEXITCODE on keeps it. - return [ - "pwsh", - "-NoProfile", - "-NonInteractive", - "-Command", - f"{command}\nexit $LASTEXITCODE", - ] + shell = "powershell" + if shell == "powershell": + command = command.replace("${CLAUDE_PROJECT_DIR}", "${env:CLAUDE_PROJECT_DIR}") + return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command + POWERSHELL_EXIT_TAIL] raise ValueError(f"Unsupported Claude hook shell: {shell}") -def hook_failed(hook: dict, why: str) -> None: +def hook_failed(result: dict, hook: dict, why: str) -> None: """Report a failure Claude Code treats as non-blocking, unless the hook opts into blocking.""" label = hook.get("statusMessage") or " ".join( [hook["command"], *(str(arg) for arg in hook.get("args", []))] @@ -229,7 +229,14 @@ def hook_failed(hook: dict, why: str) -> None: message = f"Codex bridge: hook {why}: {label}" if hook.get("onFailure") == "block": raise PermissionError(f"{message} (onFailure is block)") + # On stderr and as a systemMessage, since a host may not show the stderr of an exit 0. print(f"{message} (not blocking)", file=sys.stderr) + merge_output(result, {"systemMessage": f"{message} (not blocking)"}) + + +def print_hook_stderr(text: str) -> None: + if text: + print(text, file=sys.stderr, end="" if text.endswith("\n") else "\n") def dispatch(root: Path, payload: dict) -> dict: @@ -293,22 +300,20 @@ def dispatch(root: Path, payload: dict) -> dict: check=False, ) except subprocess.TimeoutExpired as exc: - if exc.stderr: - captured = exc.stderr - if isinstance(captured, bytes): - captured = captured.decode("utf-8", "replace") - print(captured, file=sys.stderr, end="") - hook_failed(hook, f"timed out after {exc.timeout} seconds") + captured = exc.stderr or "" + if isinstance(captured, bytes): + captured = captured.decode("utf-8", "replace") + print_hook_stderr(captured) + hook_failed(result, hook, f"timed out after {exc.timeout} seconds") continue except OSError as exc: - hook_failed(hook, f"could not start ({exc})") + hook_failed(result, hook, f"could not start ({exc})") continue if completed.returncode == 2: raise PermissionError(completed.stderr.strip() or "Claude hook blocked this event") - if completed.stderr: - print(completed.stderr, file=sys.stderr, end="") + print_hook_stderr(completed.stderr) if completed.returncode: - hook_failed(hook, f"exited {completed.returncode}") + hook_failed(result, hook, f"exited {completed.returncode}") continue output = completed.stdout.strip() if not output: diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 62f59347b4..73d81076c2 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -11,4 +11,8 @@ if (-not (Test-Path -LiteralPath $python)) { throw 'Create this worktree''s .venv first; see docs/WORKTREES.md.' } & $python (Join-Path $PSScriptRoot 'bridge.py') @args +# Codex starts a hook as pwsh -Command, which reports a script's exit 2 as 1, so a block would +# reach Codex as 1. Ending the process keeps the code. Hook mode only: an interactive caller's +# window must survive `run`. +if ($args.Count -gt 0 -and $args[0] -eq 'hook') { [Environment]::Exit($LASTEXITCODE) } exit $LASTEXITCODE diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 08e6141f35..604cd62cc5 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -59,6 +59,13 @@ def exits(code, stdout=""): BASH_CALL = {"session_id": "x", "hook_event_name": "PreToolUse", "tool_name": "Bash"} +def assert_denied_with_notice(result, notice): + """The later hook's denial survived, and the failure reached the JSON Codex reads.""" + assert result["hookSpecificOutput"] == DENIAL["hookSpecificOutput"] + assert notice in result["systemMessage"] + assert "(not blocking)" in result["systemMessage"] + + def test_reads_current_source_each_time_and_preserves_denial(bridge, tmp_path): payload = {"session_id": "test", "hook_event_name": "PreToolUse", "tool_name": "Bash"} settings(tmp_path, []) @@ -124,8 +131,9 @@ def test_hook_timeout_is_reported_without_blocking_later_hooks(bridge, tmp_path, """Claude Code treats a timed-out hook as a non-blocking error, and so must the bridge.""" slow = python("import time; time.sleep(5)", timeout=0.1, statusMessage="the slow hook") settings(tmp_path, [slow, handler(json.dumps(DENIAL))]) - assert bridge.dispatch(tmp_path, BASH_CALL) == DENIAL - assert "timed out after 0.1 seconds: the slow hook (not blocking)" in capsys.readouterr().err + notice = "timed out after 0.1 seconds: the slow hook (not blocking)" + assert_denied_with_notice(bridge.dispatch(tmp_path, BASH_CALL), notice) + assert notice in capsys.readouterr().err @pytest.mark.parametrize("code", [1, 3, 127]) @@ -133,18 +141,16 @@ def test_non_blocking_exit_is_reported_and_later_hooks_still_run(bridge, tmp_pat """Only exit 2 blocks. Another non-zero exit must neither block nor stop the hooks after it.""" # The failing hook's stdout is not read, so its "continue": false must not reach the result. settings(tmp_path, [exits(code, stdout='{"continue": false}'), handler(json.dumps(DENIAL))]) - assert bridge.dispatch(tmp_path, BASH_CALL) == DENIAL + assert_denied_with_notice(bridge.dispatch(tmp_path, BASH_CALL), f"exited {code}: ") err = capsys.readouterr().err - assert f"hook says {code}" in err - assert f"exited {code}: " in err - assert "(not blocking)" in err + # The hook's own stderr ends its line, so the bridge's report starts a fresh one. + assert f"hook says {code}\nCodex bridge: hook exited {code}: " in err -def test_unstartable_hook_is_reported_without_blocking(bridge, tmp_path, capsys): +def test_unstartable_hook_is_reported_without_blocking(bridge, tmp_path): missing = {"type": "command", "command": str(tmp_path / "no-such-hook.exe"), "args": []} settings(tmp_path, [missing, handler(json.dumps(DENIAL))]) - assert bridge.dispatch(tmp_path, BASH_CALL) == DENIAL - assert "could not start" in capsys.readouterr().err + assert_denied_with_notice(bridge.dispatch(tmp_path, BASH_CALL), "could not start") @pytest.mark.parametrize( @@ -169,12 +175,35 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): @pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") -def test_a_native_exit_2_inside_a_powershell_hook_still_blocks(bridge, tmp_path): - """pwsh -Command reports a native program's exit 2 as 1, which would fail open.""" - command = f"& '{sys.executable}' -c 'import sys; sys.exit(2)'" - settings(tmp_path, [{"type": "command", "shell": "powershell", "command": command}]) - with pytest.raises(PermissionError): - bridge.dispatch(tmp_path, BASH_CALL) +@pytest.mark.parametrize( + ("command", "outcome"), + [ + # pwsh -Command reports a native program's exit 2 as 1, which would fail open. + ("& '{py}' -c 'import sys; sys.exit(2)'", "block"), + # A stale exit 2 from an earlier statement must not block a hook that went on to succeed. + ("& '{py}' -c 'import sys; sys.exit(2)'; Write-Output '{{}}'", "allow"), + # A failed cmdlet as the last statement stays -Command's own non-blocking 1. + ("Get-Item -LiteralPath 'no-such-item-b4'", "notice"), + ], + ids=["native-exit-2", "stale-exit-2", "failed-cmdlet"], +) +def test_a_powershell_hook_keeps_exit_2_and_only_exit_2(bridge, tmp_path, command, outcome): + hook = {"type": "command", "shell": "powershell", "command": command.format(py=sys.executable)} + settings(tmp_path, [hook]) + if outcome == "block": + with pytest.raises(PermissionError): + bridge.dispatch(tmp_path, BASH_CALL) + return + result = bridge.dispatch(tmp_path, BASH_CALL) + assert ("exited 1:" in result.get("systemMessage", "")) == (outcome == "notice"), result + + +def test_project_dir_is_substituted_in_every_form(bridge, tmp_path): + structured = {"type": "command", "command": "${CLAUDE_PROJECT_DIR}/guard", "args": ["a"]} + assert bridge.hook_argv(tmp_path, structured) == [f"{tmp_path}/guard", "a"] + shell = {"type": "command", "shell": "powershell", "command": "'${CLAUDE_PROJECT_DIR}_x'"} + # Braced, so a following name character cannot join the variable name. + assert "'${env:CLAUDE_PROJECT_DIR}_x'" in bridge.hook_argv(tmp_path, shell)[-1] def test_each_event_matches_its_own_discriminator_field(bridge, tmp_path): @@ -498,3 +527,39 @@ def test_registered_command_runs_from_a_subdirectory(tmp_path): timeout=20, ) assert json.loads(completed.stdout) == {"probe": True} + + +@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") +@pytest.mark.skipif(sys.prefix == sys.base_prefix, reason="invoke.ps1 needs a .venv to link") +def test_every_registered_command_passes_the_bridge_exit_2_to_codex(tmp_path): + """pwsh -Command reports a script's exit 2 as 1, so a bridge block would reach Codex as 1. + + The real invoke.ps1 runs a stub bridge, through a link to this test's own virtualenv. + """ + import tomllib + + root = tmp_path / "repo" + scripts = root / "scripts/codex" + scripts.mkdir(parents=True) + shutil.copy2(ROOT / "scripts/codex/invoke.ps1", scripts / "invoke.ps1") + (scripts / "bridge.py").write_text("import sys\nsys.exit(2)\n") + if os.name == "nt": # A junction needs no symlink privilege. + link = ["cmd", "/c", "mklink", "/J", str(root / ".venv"), sys.prefix] + subprocess.run(link, check=True, capture_output=True) + else: + (root / ".venv").symlink_to(sys.prefix, target_is_directory=True) + subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) + config = tomllib.loads((ROOT / ".codex/config.toml").read_text()) + for event, groups in config["hooks"].items(): + for group in groups: + for hook in group["hooks"]: + completed = subprocess.run( + ["pwsh", "-NoProfile", "-Command", hook["command"]], + cwd=scripts, + input="{}", + text=True, + capture_output=True, + check=False, + timeout=20, + ) + assert completed.returncode == 2, (event, completed.stderr) From 0a0107668d2651c31ec96019bc38c15783bd8c4d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 15:07:20 -0600 Subject: [PATCH 04/51] Handover for BACKLOG #5496 and #5501: proposed PR title and banners No code change. This commit carries the handover for the branch. Proposed PR title: The Codex bridge follows Claude Code's hook exit contract, and its tests dispatch the tracked hook settings (BACKLOG #5496, #5501) Proposed banners: #5496 SHIPPED: only exit 2 blocks; a non-2 exit, a timeout or an unstartable hook is non-blocking unless onFailure is block, the remaining hooks run, and item 1 (S34-14) is fixed. #5501 SHIPPED: tests/test_codex_bridge.py dispatches every hook in the tracked .claude/settings.json and pins exit 1 as non-blocking against a blocking exit 2. BACKLOG #5496 BACKLOG #5501 From baa96c7b5a67893f2426b1c8e7777ebd03e73f83 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 15:30:58 -0600 Subject: [PATCH 05/51] The Codex bridge decides its own faults, and a launcher with no decision blocks only PreToolUse Manager repair round on the hook exit contract. The bridge now exits only 0 or 2 in hook mode. A bridge fault (settings or a payload that cannot be parsed, a bad matcher, an unsupported hook type, a missing session id, any uncaught exception) blocks only on PreToolUse where a guard group could have run for the tool, or where that cannot be judged. Every other fault is reported on stderr and as a systemMessage and does not block, so a fault can no longer stop Codex from stopping. A guard group runs shell-guard-dispatch.ps1 or sets onFailure to block. Each registered command names its event. invoke.ps1 maps any outcome that is not a bridge decision (a crash, a missing .venv, no checkout) to exit 2 on PreToolUse and to a non-blocking 1 elsewhere, never 0, and the command line passes the code on under PowerShell, cmd and sh, all three tested. docs/CODEX.md states who decides a block in one place. BACKLOG #5496 BACKLOG #5501 Proposed PR title: The Codex bridge follows Claude Code's hook exit contract, and its tests dispatch the tracked hook settings (BACKLOG #5496, #5501) Proposed banners: #5496 SHIPPED: only exit 2 blocks; a non-2 exit, a timeout or an unstartable hook is non-blocking unless onFailure is block; a bridge fault blocks only a guarded PreToolUse; item 1 (S34-14) is fixed. #5501 SHIPPED: tests/test_codex_bridge.py dispatches every hook in the tracked .claude/settings.json and pins exit 1 as non-blocking against a blocking exit 2. --- .codex/config.toml | 30 ++--- docs/CODEX.md | 44 +++++-- scripts/codex/bridge.py | 119 +++++++++++++++---- scripts/codex/invoke.ps1 | 41 +++++-- tests/test_codex_bridge.py | 227 +++++++++++++++++++++++++++++++------ 5 files changed, 374 insertions(+), 87 deletions(-) diff --git a/.codex/config.toml b/.codex/config.toml index f658c4f958..108f14d385 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -1,72 +1,74 @@ # Claude Code remains the source of hook policy. The bridge reads it on each event. -# pwsh -Command reports a native program's exit 2 as 1. The trailing exit passes the bridge's code -# on where PowerShell runs this line; under sh it exits with pwsh's status, and under cmd pwsh -# receives it as more of its -Command text. +# Each command names its event, so a launcher failure that leaves no decision blocks on +# PreToolUse (the inner exit 2) and is a non-blocking 1 elsewhere. The trailing exit passes +# the code on where PowerShell runs the line, since pwsh -Command reports a native exit 2 as 1; +# under sh it exits with pwsh's status, and under cmd pwsh receives it as more -Command text. +# docs/CODEX.md, "Who decides a block", states the rule. [features] hooks = true [[hooks.SessionStart]] [[hooks.SessionStart.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SessionStart; exit 1"; exit $LASTEXITCODE''' timeout = 90 [[hooks.SessionEnd]] [[hooks.SessionEnd.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SessionEnd; exit 1"; exit $LASTEXITCODE''' timeout = 90 [[hooks.PreToolUse]] [[hooks.PreToolUse.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PreToolUse; exit 2"; exit $LASTEXITCODE''' timeout = 90 [[hooks.PostToolUse]] [[hooks.PostToolUse.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PostToolUse; exit 1"; exit $LASTEXITCODE''' timeout = 90 [[hooks.PermissionRequest]] [[hooks.PermissionRequest.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PermissionRequest; exit 1"; exit $LASTEXITCODE''' timeout = 90 [[hooks.UserPromptSubmit]] [[hooks.UserPromptSubmit.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event UserPromptSubmit; exit 1"; exit $LASTEXITCODE''' timeout = 90 [[hooks.PreCompact]] [[hooks.PreCompact.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PreCompact; exit 1"; exit $LASTEXITCODE''' timeout = 90 [[hooks.PostCompact]] [[hooks.PostCompact.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PostCompact; exit 1"; exit $LASTEXITCODE''' timeout = 90 [[hooks.Stop]] [[hooks.Stop.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event Stop; exit 1"; exit $LASTEXITCODE''' timeout = 90 [[hooks.SubagentStart]] [[hooks.SubagentStart.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SubagentStart; exit 1"; exit $LASTEXITCODE''' timeout = 90 [[hooks.SubagentStop]] [[hooks.SubagentStop.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SubagentStop; exit 1"; exit $LASTEXITCODE''' timeout = 90 diff --git a/docs/CODEX.md b/docs/CODEX.md index 22a42a6c01..981a799bdb 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -24,14 +24,42 @@ matches Claude's `PowerShell` name. Patch calls match `apply_patch`, `Edit`, and `Write`. A future hook that needs Claude-specific input fields still needs an adapter; alias matching alone cannot translate an edit payload. -New event types appear as unmapped at startup. Unsupported handler types and -shells refuse the event. As in Claude Code, exit 2 blocks. Any other non-zero -exit, a timeout, or a command that cannot start is a non-blocking error, unless -the hook sets `"onFailure": "block"`. The bridge reports a non-blocking error on -stderr and as a `systemMessage`, naming the hook, ignores that hook's output, and -runs the remaining hooks. It does not silently claim a failed hook ran. A block -leaves the bridge with exit 2, and the registered command and `invoke.ps1` pass -that code on, because `pwsh -Command` would report it as 1. +New event types appear as unmapped at startup. The bridge does not silently +claim a failed hook ran. + +### Who decides a block + +The hooks decide first. As in Claude Code, a hook's exit 2 blocks. Any other +non-zero exit, a timeout, or a command that cannot start is a non-blocking error, +unless the hook sets `"onFailure": "block"`. The bridge reports a non-blocking +error on stderr and as a `systemMessage`, naming the hook, ignores that hook's +output, and runs the remaining hooks. + +The bridge decides its own faults, and exits only 0 or 2. A fault is anything +that keeps it from running the hooks: settings that cannot be parsed, a matcher +that is not a valid regex, an unsupported handler type or shell, a missing +session id, an unreadable payload, or any other exception. A fault blocks only +on `PreToolUse`, and only where a guard group could have run for the tool, or +where that cannot be judged: settings or a payload that cannot be parsed, or a +guard group's matcher that is not a valid regex. A guard group is one that runs +`scripts/hooks/shell-guard-dispatch.ps1` or holds a hook with +`"onFailure": "block"`; today that is the `^(Bash|PowerShell)$` group. Every other +fault is reported on stderr and as a `systemMessage` and does not block, so a +fault never stops Codex from stopping, starting or taking a prompt. The advisory +`PreToolUse` hooks, such as `usage-headroom-inject.ps1` and +`enter-worktree-check.ps1`, stay non-blocking. **A future guard on any other +event must set `"onFailure": "block"`**, or its failures will not block. + +The launcher decides when the bridge returns no decision. Each command in +`.codex/config.toml` names its event to `invoke.ps1`. A bridge exit other than 0 +or 2, a missing `.venv`, or a checkout `git` cannot find maps to exit 2 on the +`PreToolUse` command and to a non-blocking exit 1 on every other event, never to +0. `invoke.ps1` ends its process with that code, and the command line passes it +on, because `pwsh -Command` would report an exit 2 as 1. This is tested with +PowerShell, `cmd` and `sh` as the outer shell. Codex's documentation does not +say which shell runs a hook command. One case is not covered: when `pwsh` +itself cannot start. Under Windows PowerShell 5.1 the line would then exit 0, +under `cmd` 9009, and under `sh` 127. This is reasoned, not measured. The bridge differs from Claude Code in at least three ways. It runs an event's hooks one after another, where Claude Code runs them in parallel. Exit 2 stops diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 11da045085..d1ec9bfd81 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -174,6 +174,13 @@ def merge_output(result: dict, update: dict) -> None: } # Claude Code adds a hook's plain exit-0 stdout as context for these events only. PLAIN_CONTEXT_EVENTS = ("SessionStart", "UserPromptSubmit") +# A guard group is one whose hooks exist to refuse a tool call. A bridge fault blocks only where a +# guard group could have run; see docs/CODEX.md, "Who decides a block". +GUARD_SCRIPTS = ("scripts/hooks/shell-guard-dispatch.ps1",) + + +class HookBlocked(Exception): + """A deliberate block: a hook exited 2, or failed with onFailure set to block.""" def git_bash() -> str | None: @@ -228,7 +235,7 @@ def hook_failed(result: dict, hook: dict, why: str) -> None: ) message = f"Codex bridge: hook {why}: {label}" if hook.get("onFailure") == "block": - raise PermissionError(f"{message} (onFailure is block)") + raise HookBlocked(f"{message} (onFailure is block)") # On stderr and as a systemMessage, since a host may not show the stderr of an exit 0. print(f"{message} (not blocking)", file=sys.stderr) merge_output(result, {"systemMessage": f"{message} (not blocking)"}) @@ -239,10 +246,92 @@ def print_hook_stderr(text: str) -> None: print(text, file=sys.stderr, end="" if text.endswith("\n") else "\n") +def read_settings(root: Path) -> dict: + config = json.loads((root / ".claude/settings.json").read_text(encoding="utf-8-sig")) + if not isinstance(config, dict): + raise ValueError(".claude/settings.json must hold a JSON object") + return config + + +def discriminator_for(event: str, payload: dict) -> set[str] | None: + """The values a matcher is compared with, or None where Claude Code ignores the matcher.""" + if event in TOOL_EVENTS: + names = {str(payload.get("tool_name", ""))} + if "Bash" in names: + names.add("PowerShell") + if "apply_patch" in names: + names.update(("Edit", "Write")) + return names + if event in MATCHER_FIELDS: + return {str(payload.get(MATCHER_FIELDS[event]) or "")} + return None + + +def group_selected(group: dict, discriminator: set[str] | None) -> bool: + matcher = group.get("matcher", "") + return ( + discriminator is None + or matcher in ("", "*") + or any(re.search(matcher, value) for value in discriminator) + ) + + +def is_guard(group: dict) -> bool: + for hook in group.get("hooks", []): + words = [str(hook.get("command", "")), *(str(arg) for arg in hook.get("args", []))] + if hook.get("onFailure") == "block" or any( + word.replace("\\", "/").endswith(script) for word in words for script in GUARD_SCRIPTS + ): + return True + return False + + +def fault_blocks(root: Path, payload: object, event: str) -> bool: + """Whether a bridge fault must block: only on PreToolUse, and only where a guard could run.""" + if isinstance(payload, dict): + event = str(payload.get("hook_event_name") or event) + if event != "PreToolUse": + return False # A fault never stops Codex from stopping, starting or prompting. + if not isinstance(payload, dict): + return True # No tool to judge, so a guard may have been skipped. + try: + discriminator = discriminator_for(event, payload) + groups = read_settings(root).get("hooks", {}).get(event, []) + return any(is_guard(group) and group_selected(group, discriminator) for group in groups) + except Exception: # noqa: BLE001 - settings or a matcher that cannot be judged may hide a guard + return True + + +def run_hook(root: Path, stdin_text: str, event: str = "") -> int: + """Decide one Codex hook event: exit 0 to proceed, or exit 2 to block, never anything else.""" + payload: object = None + try: + payload = json.loads(stdin_text) + if not isinstance(payload, dict): + raise ValueError("the hook payload must be a JSON object") + result = dispatch(root, payload) + except HookBlocked as exc: + print(str(exc), file=sys.stderr) + return 2 + except Exception as exc: # noqa: BLE001 - every bridge fault is decided here, not by a crash + message = f"Codex bridge fault: {type(exc).__name__}: {exc}" + if fault_blocks(root, payload, event): + print( + f"{message} (blocking: a guard hook could have run for this tool)", file=sys.stderr + ) + return 2 + print(f"{message} (not blocking)", file=sys.stderr) + print(json.dumps({"systemMessage": f"{message} (not blocking)"})) + return 0 + if result: + print(json.dumps(result)) + return 0 + + def dispatch(root: Path, payload: dict) -> dict: event = payload["hook_event_name"] env = child_environment(root, payload.get("session_id", "")) - config = json.loads((root / ".claude/settings.json").read_text(encoding="utf-8-sig")) + config = read_settings(root) if config.get("disableAllHooks"): return {} result: dict = {} @@ -261,22 +350,9 @@ def dispatch(root: Path, payload: dict) -> dict: merge_output( result, {"hookSpecificOutput": {"hookEventName": event, "additionalContext": context}} ) - discriminator: set[str] | None = None - if event in TOOL_EVENTS: - discriminator = {str(payload.get("tool_name", ""))} - if "Bash" in discriminator: - discriminator.add("PowerShell") - if "apply_patch" in discriminator: - discriminator.update(("Edit", "Write")) - elif event in MATCHER_FIELDS: - discriminator = {str(payload.get(MATCHER_FIELDS[event]) or "")} + discriminator = discriminator_for(event, payload) for group in config.get("hooks", {}).get(event, []): - matcher = group.get("matcher", "") - if ( - discriminator is not None - and matcher not in ("", "*") - and not any(re.search(matcher, value) for value in discriminator) - ): + if not group_selected(group, discriminator): continue for hook in group.get("hooks", []): if hook.get("type") != "command" or hook.get("async"): @@ -310,7 +386,7 @@ def dispatch(root: Path, payload: dict) -> dict: hook_failed(result, hook, f"could not start ({exc})") continue if completed.returncode == 2: - raise PermissionError(completed.stderr.strip() or "Claude hook blocked this event") + raise HookBlocked(completed.stderr.strip() or "Claude hook blocked this event") print_hook_stderr(completed.stderr) if completed.returncode: hook_failed(result, hook, f"exited {completed.returncode}") @@ -345,6 +421,7 @@ def main() -> int: 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") + parser.add_argument("--event", default="", help="hook mode: the event Codex registered") args, rest = parser.parse_known_args() if args.mode == "sync-skills": user_skills = user_skill_directory() if args.include_user_skills else None @@ -363,11 +440,7 @@ def main() -> int: print(ROOT / child_environment(ROOT, args.session_id)["KORUS_STATE_REL"]) return 0 if args.mode == "hook": - payload = json.load(sys.stdin) - result = dispatch(ROOT, payload) - if result: - print(json.dumps(result)) - return 0 + return run_hook(ROOT, sys.stdin.read(), args.event) if args.mode == "doctor": config = json.loads((ROOT / ".claude/settings.json").read_text(encoding="utf-8-sig")) for event in config.get("hooks", {}): diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 73d81076c2..d19d521729 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -3,16 +3,37 @@ # No parameter block: forward native arguments, including script-specific flags, unchanged. $ErrorActionPreference = 'Stop' $root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent -$python = Join-Path $root '.venv/Scripts/python.exe' -if (-not (Test-Path -LiteralPath $python)) { - $python = Join-Path $root '.venv/bin/python' + +function Resolve-BridgePython { + $python = Join-Path $root '.venv/Scripts/python.exe' + if (-not (Test-Path -LiteralPath $python)) { + $python = Join-Path $root '.venv/bin/python' + } + if (-not (Test-Path -LiteralPath $python)) { + throw 'Create this worktree''s .venv first; see docs/WORKTREES.md.' + } + $python } -if (-not (Test-Path -LiteralPath $python)) { - throw 'Create this worktree''s .venv first; see docs/WORKTREES.md.' + +if ($args.Count -gt 0 -and $args[0] -eq 'hook') { + # The bridge decides and exits 0 or 2. Anything else, such as a missing .venv or a bridge + # that crashed, is no decision: it blocks on the PreToolUse registration and is a + # non-blocking 1 on every other event. docs/CODEX.md, "Who decides a block", states the rule. + $noDecision = 1 + for ($i = 1; $i -lt $args.Count - 1; $i++) { + if ($args[$i] -eq '--event' -and $args[$i + 1] -eq 'PreToolUse') { $noDecision = 2 } + } + $code = $noDecision + try { + & (Resolve-BridgePython) (Join-Path $PSScriptRoot 'bridge.py') @args + if ($LASTEXITCODE -in 0, 2) { $code = $LASTEXITCODE } + } catch { + [Console]::Error.WriteLine("Codex bridge launcher: $_") + } + # Codex starts this through pwsh -Command, which reports a script's exit 2 as 1. Ending the + # process keeps the code. Hook mode only: an interactive caller's window must survive `run`. + [Environment]::Exit($code) } -& $python (Join-Path $PSScriptRoot 'bridge.py') @args -# Codex starts a hook as pwsh -Command, which reports a script's exit 2 as 1, so a block would -# reach Codex as 1. Ending the process keeps the code. Hook mode only: an interactive caller's -# window must survive `run`. -if ($args.Count -gt 0 -and $args[0] -eq 'hook') { [Environment]::Exit($LASTEXITCODE) } + +& (Resolve-BridgePython) (Join-Path $PSScriptRoot 'bridge.py') @args exit $LASTEXITCODE diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 604cd62cc5..2b592e6b16 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -160,17 +160,17 @@ def test_unstartable_hook_is_reported_without_blocking(bridge, tmp_path): ) def test_on_failure_block_turns_a_non_blocking_failure_into_a_block(bridge, tmp_path, failing): settings(tmp_path, [{**failing, "onFailure": "block"}, handler(json.dumps(DENIAL))]) - with pytest.raises(PermissionError, match="onFailure is block"): + with pytest.raises(bridge.HookBlocked, match="onFailure is block"): bridge.dispatch(tmp_path, BASH_CALL) def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): marker = tmp_path / "later-hook-ran" settings(tmp_path, [exits(2), python(f"open({str(marker)!r}, 'w').close()")]) - with pytest.raises(PermissionError, match="hook says 2"): + with pytest.raises(bridge.HookBlocked, match="hook says 2"): bridge.dispatch(tmp_path, BASH_CALL) assert not marker.exists() - # The reason travels once, in the PermissionError main() prints, not also as raw stderr. + # The reason travels once, in the HookBlocked run_hook prints, not also as raw stderr. assert "hook says 2" not in capsys.readouterr().err @@ -191,7 +191,7 @@ def test_a_powershell_hook_keeps_exit_2_and_only_exit_2(bridge, tmp_path, comman hook = {"type": "command", "shell": "powershell", "command": command.format(py=sys.executable)} settings(tmp_path, [hook]) if outcome == "block": - with pytest.raises(PermissionError): + with pytest.raises(bridge.HookBlocked): bridge.dispatch(tmp_path, BASH_CALL) return result = bridge.dispatch(tmp_path, BASH_CALL) @@ -500,7 +500,10 @@ def test_registered_command_runs_from_a_subdirectory(tmp_path): root = tmp_path / "repo with spaces" scripts = root / "scripts/codex" scripts.mkdir(parents=True) - (scripts / "invoke.ps1").write_text("[Console]::Out.Write([Console]::In.ReadToEnd())\n") + # Like the real launcher in hook mode, it ends the process with its decision. + (scripts / "invoke.ps1").write_text( + "[Console]::Out.Write([Console]::In.ReadToEnd()); [Environment]::Exit(0)\n" + ) subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) config = tomllib.loads((ROOT / ".codex/config.toml").read_text()) assert set(config["hooks"]) == { @@ -529,37 +532,197 @@ def test_registered_command_runs_from_a_subdirectory(tmp_path): assert json.loads(completed.stdout) == {"probe": True} -@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") -@pytest.mark.skipif(sys.prefix == sys.base_prefix, reason="invoke.ps1 needs a .venv to link") -def test_every_registered_command_passes_the_bridge_exit_2_to_codex(tmp_path): - """pwsh -Command reports a script's exit 2 as 1, so a bridge block would reach Codex as 1. +# --- Who decides a block: the bridge for its own faults, the launcher when there is no decision. - The real invoke.ps1 runs a stub bridge, through a link to this test's own virtualenv. - """ +GUARD_GROUP = { + "matcher": "^(Bash|PowerShell)$", + "hooks": [ + { + "type": "command", + "command": "pwsh", + "args": ["-File", "${CLAUDE_PROJECT_DIR}/scripts/hooks/shell-guard-dispatch.ps1"], + } + ], +} +ADVISORY_GROUP = {"matcher": "^(Task|Agent|Workflow)$", "hooks": [handler("{}")]} +UNSUPPORTED = {"type": "prompt", "prompt": "review"} + + +def write_settings(root, hooks): + (root / ".claude").mkdir(exist_ok=True) + (root / ".claude/settings.json").write_text(json.dumps({"hooks": hooks}), encoding="utf-8") + + +def run(bridge, root, payload, event=""): + text = payload if isinstance(payload, str) else json.dumps(payload) + return bridge.run_hook(root, text, event) + + +@pytest.mark.parametrize( + ("tool", "code"), + [("Bash", 2), ("PowerShell", 2), ("Agent", 0)], + ids=["guarded-bash", "guarded-powershell", "advisory-agent"], +) +def test_a_bridge_fault_blocks_only_where_a_guard_could_have_run( + bridge, tmp_path, capsys, tool, code +): + write_settings(tmp_path, {"PreToolUse": [ADVISORY_GROUP, GUARD_GROUP]}) + payload = {"hook_event_name": "PreToolUse", "tool_name": tool} # no session_id: a fault + assert run(bridge, tmp_path, payload) == code + captured = capsys.readouterr() + assert "Codex bridge fault: ValueError" in captured.err + if code == 0: + assert "(not blocking)" in json.loads(captured.out)["systemMessage"] + else: + assert "blocking: a guard hook could have run" in captured.err + + +@pytest.mark.parametrize("event", ["Stop", "SubagentStop", "SessionStart", "UserPromptSubmit"]) +def test_a_bridge_fault_never_blocks_another_event(bridge, tmp_path, capsys, event): + """A fault on Stop must not stop Codex from stopping.""" + write_settings(tmp_path, {event: [{"hooks": [UNSUPPORTED]}]}) + assert run(bridge, tmp_path, {"session_id": "x", "hook_event_name": event}) == 0 + assert "(not blocking)" in json.loads(capsys.readouterr().out)["systemMessage"] + + +@pytest.mark.parametrize(("event", "code"), [("PreToolUse", 2), ("Stop", 0)]) +def test_settings_that_cannot_be_parsed_block_only_pretooluse(bridge, tmp_path, event, code): + (tmp_path / ".claude").mkdir() + (tmp_path / ".claude/settings.json").write_text("{ not json", encoding="utf-8") + payload = {"session_id": "x", "hook_event_name": event, "tool_name": "Read"} + assert run(bridge, tmp_path, payload) == code + + +@pytest.mark.parametrize( + ("event", "group", "code"), + [ + ("PreToolUse", GUARD_GROUP, 2), + ("PreToolUse", ADVISORY_GROUP, 0), + ("SessionStart", GUARD_GROUP, 0), + ], + ids=["guard", "advisory", "other-event"], +) +def test_a_guard_matcher_that_cannot_be_judged_blocks_only_pretooluse( + bridge, tmp_path, event, group, code +): + write_settings(tmp_path, {event: [{**group, "matcher": "(["}]}) + payload = {"session_id": "x", "hook_event_name": event, "tool_name": "Read", "source": "x"} + assert run(bridge, tmp_path, payload) == code + + +@pytest.mark.parametrize( + ("event", "code"), [("PreToolUse", 2), ("Stop", 0), ("", 0)], ids=["pre", "stop", "unknown"] +) +def test_a_payload_that_cannot_be_parsed_uses_the_registered_event(bridge, tmp_path, event, code): + write_settings(tmp_path, {}) + assert run(bridge, tmp_path, "{ not json", event) == code + + +def test_a_deliberate_block_and_a_clean_run_exit_2_and_0(bridge, tmp_path, capsys): + settings(tmp_path, [exits(2)]) + assert run(bridge, tmp_path, BASH_CALL) == 2 + settings(tmp_path, [handler(json.dumps(DENIAL))]) + assert run(bridge, tmp_path, BASH_CALL) == 0 + assert json.loads(capsys.readouterr().out.splitlines()[-1]) == DENIAL + + +@pytest.mark.parametrize( + ("tool", "code"), + [("Bash", 2), ("PowerShell", 2), ("Agent", 0), ("EnterWorktree", 0), ("Read", 0)], +) +def test_in_the_tracked_settings_only_the_shell_guard_makes_a_fault_block( + bridge, tmp_path, tool, code +): + """Advisory PreToolUse hooks (usage-headroom-inject, enter-worktree-check) stay non-blocking.""" + tracked = _tracked_settings() + guards = [g for g in tracked["hooks"]["PreToolUse"] if bridge.is_guard(g)] + assert [g["matcher"] for g in guards] == ["^(Bash|PowerShell)$"] + (tmp_path / ".claude").mkdir() + (tmp_path / ".claude/settings.json").write_text(json.dumps(tracked), encoding="utf-8") + # A payload with no session_id is a bridge fault before any hook runs. + assert run(bridge, tmp_path, {"hook_event_name": "PreToolUse", "tool_name": tool}) == code + + +# --- The launcher and the registered commands: a missing decision blocks only on PreToolUse. + +_STUB_BRIDGE = "import os, sys\nsys.exit(int(os.environ['STUB_BRIDGE_EXIT']))\n" + + +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}" + return ["pwsh", "-NoProfile", "-Command", command] if shell == "pwsh" else ["sh", "-c", command] + + +def _link_python(root): + """Give the copied invoke.ps1 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) + + +@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") +@pytest.mark.parametrize("shell", _outer_shells()) +@pytest.mark.parametrize( + ("event", "setup", "expected"), + [ + ("PreToolUse", "0", 0), + ("PreToolUse", "2", 2), + ("PreToolUse", "1", 2), + ("PreToolUse", "3", 2), + ("PreToolUse", "no-venv", 2), + ("PreToolUse", "no-repo", 2), + ("Stop", "0", 0), + ("Stop", "2", 2), + ("Stop", "1", 1), + ("Stop", "no-venv", 1), + ("Stop", "no-repo", 1), + ], +) +def test_a_registered_command_passes_a_decision_and_maps_no_decision( + tmp_path, shell, event, setup, expected +): + """No decision (a crash, a missing .venv, no repo) blocks on PreToolUse and is a + non-blocking 1 elsewhere, never 0. The real invoke.ps1 runs a stub bridge.""" import tomllib root = tmp_path / "repo" scripts = root / "scripts/codex" scripts.mkdir(parents=True) shutil.copy2(ROOT / "scripts/codex/invoke.ps1", scripts / "invoke.ps1") - (scripts / "bridge.py").write_text("import sys\nsys.exit(2)\n") - if os.name == "nt": # A junction needs no symlink privilege. - link = ["cmd", "/c", "mklink", "/J", str(root / ".venv"), sys.prefix] - subprocess.run(link, check=True, capture_output=True) - else: - (root / ".venv").symlink_to(sys.prefix, target_is_directory=True) - subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) - config = tomllib.loads((ROOT / ".codex/config.toml").read_text()) - for event, groups in config["hooks"].items(): - for group in groups: - for hook in group["hooks"]: - completed = subprocess.run( - ["pwsh", "-NoProfile", "-Command", hook["command"]], - cwd=scripts, - input="{}", - text=True, - capture_output=True, - check=False, - timeout=20, - ) - assert completed.returncode == 2, (event, completed.stderr) + (scripts / "bridge.py").write_text(_STUB_BRIDGE) + if setup != "no-venv": + _link_python(root) + if setup != "no-repo": + subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) + hooks = tomllib.loads((ROOT / ".codex/config.toml").read_text())["hooks"][event][0]["hooks"] + env = {**os.environ, "STUB_BRIDGE_EXIT": setup if setup.isdigit() else "0"} + if setup == "no-repo": + env["GIT_CEILING_DIRECTORIES"] = str(tmp_path) + completed = subprocess.run( + _outer_argv(shell, hooks[0]["command"]), + cwd=scripts, + env=env, + input="{}", + text=True, + capture_output=True, + check=False, + timeout=60, + ) + assert completed.returncode == expected, (shell, completed.stdout, completed.stderr) From d301ba2fb7323d8fd2cb73a8cc7e430d8a3e359b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 15:56:55 -0600 Subject: [PATCH 06/51] The Codex bridge reads UTF-8 bytes, checks the registered event, and judges each hook group Final repair round on the bridge's fault rule. Hook mode reads the payload as UTF-8 bytes inside run_hook's fault handling, where the text stream would decode it with the console code page. run_hook's block now leaves hook mode as exit 10, and invoke.ps1 turns only 10 into 2, so the 2 that Python and argparse exit with is no decision and can no longer block a Stop. A payload whose hook_event_name differs from the registered --event, ignoring case, is a fault judged under the registered event. --event is parsed in hook mode only, so a run target's own --event is left alone. Each hook group is judged on its own: a defect in an advisory group is reported and the group skipped, and a defect in a guard group is still a fault. BACKLOG #5496 BACKLOG #5501 Proposed PR title: The Codex bridge follows Claude Code's hook exit contract, and its tests dispatch the tracked hook settings (BACKLOG #5496, #5501) Proposed banners: #5496 SHIPPED: only exit 2 blocks; a non-2 exit, a timeout or an unstartable hook is non-blocking unless onFailure is block; a bridge fault blocks only a guarded PreToolUse; item 1 (S34-14) is fixed. #5501 SHIPPED: tests/test_codex_bridge.py dispatches every hook in the tracked .claude/settings.json and pins exit 1 as non-blocking against a blocking exit 2. --- docs/CODEX.md | 49 ++++++----- scripts/codex/bridge.py | 171 +++++++++++++++++++++++-------------- scripts/codex/invoke.ps1 | 9 +- tests/test_codex_bridge.py | 127 +++++++++++++++++++++++++-- 4 files changed, 261 insertions(+), 95 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 981a799bdb..5082aba9cc 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -35,29 +35,36 @@ unless the hook sets `"onFailure": "block"`. The bridge reports a non-blocking error on stderr and as a `systemMessage`, naming the hook, ignores that hook's output, and runs the remaining hooks. -The bridge decides its own faults, and exits only 0 or 2. A fault is anything -that keeps it from running the hooks: settings that cannot be parsed, a matcher -that is not a valid regex, an unsupported handler type or shell, a missing -session id, an unreadable payload, or any other exception. A fault blocks only -on `PreToolUse`, and only where a guard group could have run for the tool, or -where that cannot be judged: settings or a payload that cannot be parsed, or a -guard group's matcher that is not a valid regex. A guard group is one that runs -`scripts/hooks/shell-guard-dispatch.ps1` or holds a hook with +The bridge decides its own faults. A fault is anything that keeps it from +running the hooks: settings that cannot be parsed, a missing session id, a +payload that cannot be read as UTF-8 JSON, a payload whose `hook_event_name` +differs from the registered event in more than case, or any other exception. A +fault blocks only on `PreToolUse`, judged under the registered event, and only +where a guard group could have run for the tool, or where that cannot be judged +because the settings or the payload cannot be parsed. A guard group is one that +runs `scripts/hooks/shell-guard-dispatch.ps1` or holds a hook with `"onFailure": "block"`; today that is the `^(Bash|PowerShell)$` group. Every other fault is reported on stderr and as a `systemMessage` and does not block, so a -fault never stops Codex from stopping, starting or taking a prompt. The advisory -`PreToolUse` hooks, such as `usage-headroom-inject.ps1` and -`enter-worktree-check.ps1`, stay non-blocking. **A future guard on any other -event must set `"onFailure": "block"`**, or its failures will not block. - -The launcher decides when the bridge returns no decision. Each command in -`.codex/config.toml` names its event to `invoke.ps1`. A bridge exit other than 0 -or 2, a missing `.venv`, or a checkout `git` cannot find maps to exit 2 on the -`PreToolUse` command and to a non-blocking exit 1 on every other event, never to -0. `invoke.ps1` ends its process with that code, and the command line passes it -on, because `pwsh -Command` would report an exit 2 as 1. This is tested with -PowerShell, `cmd` and `sh` as the outer shell. Codex's documentation does not -say which shell runs a hook command. One case is not covered: when `pwsh` +fault never stops Codex from stopping, starting or taking a prompt. + +Each hook group is judged on its own. A defect in a group, such as a matcher that +is not a valid regex or an unsupported handler type or shell, is a fault when the +group is a guard group. In any other group it is reported and that group is +skipped, so a guard group after it still runs. The advisory `PreToolUse` hooks, +such as `usage-headroom-inject.ps1` and `enter-worktree-check.ps1`, stay +non-blocking. **A future guard on any other event must set +`"onFailure": "block"`**, or its failures will not block. + +The launcher decides when the bridge returns no decision. In hook mode the +bridge exits 0 to proceed or 10 to block, and `invoke.ps1` turns 10 into 2. Any +other outcome is no decision: another bridge exit, including the 2 that Python +and argparse exit with, a missing `.venv`, or a checkout `git` cannot find. Each +command in `.codex/config.toml` names its event, and no decision maps to exit 2 +on the `PreToolUse` command and to a non-blocking exit 1 on every other event, +never to 0. `invoke.ps1` ends its process with that code, and the command line +passes it on, because `pwsh -Command` would report an exit 2 as 1. This is tested +with PowerShell, `cmd` and `sh` as the outer shell. Codex's documentation does +not say which shell runs a hook command. One case is not covered: when `pwsh` itself cannot start. Under Windows PowerShell 5.1 the line would then exit 0, under `cmd` 9009, and under `sh` 127. This is reasoned, not measured. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index d1ec9bfd81..f8220a5cc8 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -179,6 +179,11 @@ def merge_output(result: dict, update: dict) -> None: GUARD_SCRIPTS = ("scripts/hooks/shell-guard-dispatch.ps1",) +# Hook mode's exit code for run_hook's block. invoke.ps1 turns it into 2 and maps every other +# non-zero, the interpreter's and argparse's 2 included, to the event's no-decision code. +BLOCK_EXIT = 10 + + class HookBlocked(Exception): """A deliberate block: a hook exited 2, or failed with onFailure set to block.""" @@ -286,10 +291,17 @@ def is_guard(group: dict) -> bool: return False +def group_is_guard(group: dict) -> bool: + try: + return is_guard(group) + except (AttributeError, TypeError): + return True # A group too malformed to read may be a guard. + + def fault_blocks(root: Path, payload: object, event: str) -> bool: """Whether a bridge fault must block: only on PreToolUse, and only where a guard could run.""" - if isinstance(payload, dict): - event = str(payload.get("hook_event_name") or event) + if not event and isinstance(payload, dict): + event = str(payload.get("hook_event_name") or "") if event != "PreToolUse": return False # A fault never stops Codex from stopping, starting or prompting. if not isinstance(payload, dict): @@ -302,13 +314,24 @@ def fault_blocks(root: Path, payload: object, event: str) -> bool: return True -def run_hook(root: Path, stdin_text: str, event: str = "") -> int: - """Decide one Codex hook event: exit 0 to proceed, or exit 2 to block, never anything else.""" +def run_hook(root: Path, stdin: bytes | str | None = None, event: str = "") -> int: + """Decide one Codex hook event: 0 to proceed or 2 to block, never anything else. + + With no stdin given, the payload is read from this process's stdin as UTF-8 bytes; the text + stream would decode it with the console code page. `event` is the event Codex registered. + """ payload: object = None try: - payload = json.loads(stdin_text) + if stdin is None: + stdin = sys.stdin.buffer.read() + payload = json.loads(stdin.decode("utf-8-sig") if isinstance(stdin, bytes) else stdin) if not isinstance(payload, dict): raise ValueError("the hook payload must be a JSON object") + named = str(payload.get("hook_event_name") or "") + if event: + if named.lower() != event.lower(): + raise ValueError(f"the payload names event {named!r}, registered as {event!r}") + payload["hook_event_name"] = event # The registered spelling selects the settings. result = dispatch(root, payload) except HookBlocked as exc: print(str(exc), file=sys.stderr) @@ -328,6 +351,64 @@ def run_hook(root: Path, stdin_text: str, event: str = "") -> int: return 0 +def run_group(root: Path, payload: dict, env: dict[str, str], group: dict, result: dict) -> None: + event = payload["hook_event_name"] + for hook in group.get("hooks", []): + if hook.get("type") != "command" or hook.get("async"): + raise ValueError( + f"Unsupported Claude hook transport: {hook.get('type')}, async={hook.get('async', False)}" + ) + # Claude Code's hook contract: exit 2 blocks. Any other failure, a timeout or a command + # that cannot start included, is a non-blocking error unless the hook sets onFailure to + # block, and the remaining hooks still run. Only a successful hook's stdout is read. + try: + completed = subprocess.run( # nosec B603 - trusted repo hook; stdin carries event data + hook_argv(root, hook), + input=json.dumps(payload), + cwd=root, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=hook.get("timeout", 30), + check=False, + ) + except subprocess.TimeoutExpired as exc: + captured = exc.stderr or "" + if isinstance(captured, bytes): + captured = captured.decode("utf-8", "replace") + print_hook_stderr(captured) + hook_failed(result, hook, f"timed out after {exc.timeout} seconds") + continue + except OSError as exc: + hook_failed(result, hook, f"could not start ({exc})") + continue + if completed.returncode == 2: + raise HookBlocked(completed.stderr.strip() or "Claude hook blocked this event") + print_hook_stderr(completed.stderr) + if completed.returncode: + hook_failed(result, hook, f"exited {completed.returncode}") + continue + output = completed.stdout.strip() + if not output: + continue + try: + update = json.loads(output) + except json.JSONDecodeError: + update = None + if not isinstance(update, dict): + if event not in PLAIN_CONTEXT_EVENTS: + print(output, file=sys.stderr) + continue + output = output.replace( + "scripts\\coord\\seat.ps1", + "scripts\\codex\\invoke.ps1 run scripts/coord/seat.ps1", + ) + update = {"hookSpecificOutput": {"hookEventName": event, "additionalContext": output}} + merge_output(result, update) + + def dispatch(root: Path, payload: dict) -> dict: event = payload["hook_event_name"] env = child_environment(root, payload.get("session_id", "")) @@ -352,64 +433,22 @@ def dispatch(root: Path, payload: dict) -> dict: ) discriminator = discriminator_for(event, payload) for group in config.get("hooks", {}).get(event, []): - if not group_selected(group, discriminator): - continue - for hook in group.get("hooks", []): - if hook.get("type") != "command" or hook.get("async"): - raise ValueError( - f"Unsupported Claude hook transport: {hook.get('type')}, async={hook.get('async', False)}" - ) - # Claude Code's hook contract: exit 2 blocks. Any other failure, a timeout or a command - # that cannot start included, is a non-blocking error unless the hook sets onFailure to - # block, and the remaining hooks still run. Only a successful hook's stdout is read. - try: - completed = subprocess.run( # nosec B603 - trusted repo hook; stdin carries event data - hook_argv(root, hook), - input=json.dumps(payload), - cwd=root, - env=env, - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - timeout=hook.get("timeout", 30), - check=False, - ) - except subprocess.TimeoutExpired as exc: - captured = exc.stderr or "" - if isinstance(captured, bytes): - captured = captured.decode("utf-8", "replace") - print_hook_stderr(captured) - hook_failed(result, hook, f"timed out after {exc.timeout} seconds") - continue - except OSError as exc: - hook_failed(result, hook, f"could not start ({exc})") - continue - if completed.returncode == 2: - raise HookBlocked(completed.stderr.strip() or "Claude hook blocked this event") - print_hook_stderr(completed.stderr) - if completed.returncode: - hook_failed(result, hook, f"exited {completed.returncode}") - continue - output = completed.stdout.strip() - if not output: - continue - try: - update = json.loads(output) - except json.JSONDecodeError: - update = None - if not isinstance(update, dict): - if event not in PLAIN_CONTEXT_EVENTS: - print(output, file=sys.stderr) - continue - output = output.replace( - "scripts\\coord\\seat.ps1", - "scripts\\codex\\invoke.ps1 run scripts/coord/seat.ps1", - ) - update = { - "hookSpecificOutput": {"hookEventName": event, "additionalContext": output} - } - merge_output(result, update) + try: + if group_selected(group, discriminator): + run_group(root, payload, env, group, result) + except HookBlocked: + raise + except (AttributeError, KeyError, TypeError, ValueError, re.error) as exc: + # Each group is judged on its own. A defect in a guard group is a bridge fault, which + # run_hook decides; one in an advisory group is reported and skipped, so a guard group + # after it still runs. + if group_is_guard(group): + raise + message = ( + f"Codex bridge: skipped a hook group with a defect: {type(exc).__name__}: {exc}" + ) + print(f"{message} (not blocking)", file=sys.stderr) + merge_output(result, {"systemMessage": f"{message} (not blocking)"}) return result @@ -421,7 +460,6 @@ def main() -> int: 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") - parser.add_argument("--event", default="", help="hook mode: the event Codex registered") args, rest = parser.parse_known_args() if args.mode == "sync-skills": user_skills = user_skill_directory() if args.include_user_skills else None @@ -440,7 +478,10 @@ def main() -> int: print(ROOT / child_environment(ROOT, args.session_id)["KORUS_STATE_REL"]) return 0 if args.mode == "hook": - return run_hook(ROOT, sys.stdin.read(), args.event) + hook_parser = argparse.ArgumentParser(prog="bridge.py hook", allow_abbrev=False) + hook_parser.add_argument("--event", default="", help="the event Codex registered") + event = hook_parser.parse_args(rest).event + return BLOCK_EXIT if run_hook(ROOT, None, event) == 2 else 0 if args.mode == "doctor": config = json.loads((ROOT / ".claude/settings.json").read_text(encoding="utf-8-sig")) for event in config.get("hooks", {}): diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index d19d521729..639ee7a13b 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -16,9 +16,10 @@ function Resolve-BridgePython { } if ($args.Count -gt 0 -and $args[0] -eq 'hook') { - # The bridge decides and exits 0 or 2. Anything else, such as a missing .venv or a bridge - # that crashed, is no decision: it blocks on the PreToolUse registration and is a - # non-blocking 1 on every other event. docs/CODEX.md, "Who decides a block", states the rule. + # The bridge decides with exit 0, or with 10 (BLOCK_EXIT in bridge.py) for a block, which + # becomes 2 here. Anything else, a missing .venv, a crash, or the 2 that Python and argparse + # exit with, is no decision: it blocks on the PreToolUse registration and is a non-blocking 1 + # on every other event. docs/CODEX.md, "Who decides a block", states the rule. $noDecision = 1 for ($i = 1; $i -lt $args.Count - 1; $i++) { if ($args[$i] -eq '--event' -and $args[$i + 1] -eq 'PreToolUse') { $noDecision = 2 } @@ -26,7 +27,7 @@ if ($args.Count -gt 0 -and $args[0] -eq 'hook') { $code = $noDecision try { & (Resolve-BridgePython) (Join-Path $PSScriptRoot 'bridge.py') @args - if ($LASTEXITCODE -in 0, 2) { $code = $LASTEXITCODE } + if ($LASTEXITCODE -eq 0) { $code = 0 } elseif ($LASTEXITCODE -eq 10) { $code = 2 } } catch { [Console]::Error.WriteLine("Codex bridge launcher: $_") } diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 2b592e6b16..16544ba51b 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -5,6 +5,7 @@ from __future__ import annotations import importlib.util +import io import json import os import re @@ -120,11 +121,14 @@ def test_missing_session_is_error(bridge, tmp_path): def test_new_unsupported_hook_is_reported(bridge, tmp_path): + payload = {"session_id": "x", "hook_event_name": "PreToolUse", "tool_name": "Bash"} settings(tmp_path, [{"type": "prompt", "prompt": "review"}]) + # In an advisory group it is reported and the group skipped. + assert "prompt" in bridge.dispatch(tmp_path, payload)["systemMessage"] + # In a guard group it is a fault, which run_hook decides. + settings(tmp_path, [{"type": "prompt", "prompt": "review", "onFailure": "block"}]) with pytest.raises(ValueError, match="prompt"): - bridge.dispatch( - tmp_path, {"session_id": "x", "hook_event_name": "PreToolUse", "tool_name": "Bash"} - ) + bridge.dispatch(tmp_path, payload) def test_hook_timeout_is_reported_without_blocking_later_hooks(bridge, tmp_path, capsys): @@ -683,13 +687,15 @@ def _link_python(root): ("event", "setup", "expected"), [ ("PreToolUse", "0", 0), + ("PreToolUse", "10", 2), ("PreToolUse", "2", 2), ("PreToolUse", "1", 2), - ("PreToolUse", "3", 2), ("PreToolUse", "no-venv", 2), ("PreToolUse", "no-repo", 2), ("Stop", "0", 0), - ("Stop", "2", 2), + ("Stop", "10", 2), + # Python's "can't open file", argparse and a crash exit 2: no decision, never a block. + ("Stop", "2", 1), ("Stop", "1", 1), ("Stop", "no-venv", 1), ("Stop", "no-repo", 1), @@ -702,6 +708,8 @@ def test_a_registered_command_passes_a_decision_and_maps_no_decision( non-blocking 1 elsewhere, never 0. The real invoke.ps1 runs a stub bridge.""" import tomllib + assert bridge_block_exit() == 10, "invoke.ps1 hardcodes the bridge's BLOCK_EXIT" + root = tmp_path / "repo" scripts = root / "scripts/codex" scripts.mkdir(parents=True) @@ -726,3 +734,112 @@ def test_a_registered_command_passes_a_decision_and_maps_no_decision( timeout=60, ) assert completed.returncode == expected, (shell, completed.stdout, completed.stderr) + + +def bridge_block_exit(): + spec = importlib.util.spec_from_file_location( + "codex_bridge_c", ROOT / "scripts/codex/bridge.py" + ) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module.BLOCK_EXIT + + +def _main(bridge, monkeypatch, root, argv, stdin_bytes=b"", encoding="cp1252"): + """Run bridge.main() as Codex would, with a text stdin that does not decode as UTF-8.""" + monkeypatch.setattr(bridge, "ROOT", root) + monkeypatch.setattr(sys, "argv", ["bridge.py", *argv]) + monkeypatch.setattr(sys, "stdin", io.TextIOWrapper(io.BytesIO(stdin_bytes), encoding=encoding)) + return bridge.main() + + +def test_hook_mode_reads_the_payload_as_utf8_bytes(bridge, tmp_path, monkeypatch, capsys): + echo = "import json, sys; p = json.load(sys.stdin); print(json.dumps({'reason': p['tool_input']['command']}))" + settings(tmp_path, [python(echo)]) + payload = {**BASH_CALL, "tool_input": {"command": "cat \u2190 \u3053"}} + code = _main( + bridge, + monkeypatch, + tmp_path, + ["hook", "--event", "PreToolUse"], + json.dumps(payload, ensure_ascii=False).encode("utf-8"), + ) + assert code == 0 + assert json.loads(capsys.readouterr().out)["reason"] == "cat \u2190 \u3053" + + +def test_hook_mode_exits_the_block_code_only_for_a_decision(bridge, tmp_path, monkeypatch): + settings(tmp_path, [exits(2)]) + argv = ["hook", "--event", "PreToolUse"] + assert _main(bridge, monkeypatch, tmp_path, argv, json.dumps(BASH_CALL).encode()) == 10 + settings(tmp_path, [handler("{}")]) + assert _main(bridge, monkeypatch, tmp_path, argv, json.dumps(BASH_CALL).encode()) == 0 + # A usage error exits 2 through argparse, which the launcher reads as no decision. + with pytest.raises(SystemExit) as stopped: + _main(bridge, monkeypatch, tmp_path, ["hook", "--evnt", "Stop"], b"{}") + assert stopped.value.code == 2 + + +def test_run_mode_leaves_a_target_scripts_own_event_flag(bridge, monkeypatch): + calls: list[list[str]] = [] + + def call(argv, **kwargs): + calls.append(argv) + return 0 + + monkeypatch.setattr(bridge.subprocess, "call", call) + argv = ["run", "scripts/codex/bridge.py", "--event", "push", "--even", "x", "--limit", "3"] + assert _main(bridge, monkeypatch, ROOT, [*argv, "--session-id", "s"]) == 0 + assert calls[0][-6:] == ["--event", "push", "--even", "x", "--limit", "3"] + + +GUARD_DENY = { + "matcher": "^(Bash|PowerShell)$", + "hooks": [{**handler(json.dumps(DENIAL)), "onFailure": "block"}], +} + + +@pytest.mark.parametrize( + ("registered", "named", "code"), + [("PreToolUse", "Stop", 2), ("PreToolUse", None, 2), ("Stop", "PreToolUse", 0)], + ids=["pre-named-stop", "pre-unnamed", "stop-named-pre"], +) +def test_a_payload_naming_another_event_is_a_fault_under_the_registered_one( + bridge, tmp_path, capsys, registered, named, code +): + write_settings(tmp_path, {"PreToolUse": [GUARD_DENY], "Stop": [{"hooks": [handler("{}")]}]}) + payload = {"session_id": "x", "tool_name": "Bash"} + if named: + payload["hook_event_name"] = named + assert run(bridge, tmp_path, payload, registered) == code + assert "registered as" in capsys.readouterr().err + + +def test_an_event_name_in_another_case_still_runs_the_guard(bridge, tmp_path, capsys): + write_settings(tmp_path, {"PreToolUse": [GUARD_DENY]}) + payload = {**BASH_CALL, "hook_event_name": "pretooluse"} + assert run(bridge, tmp_path, payload, "PreToolUse") == 0 + assert json.loads(capsys.readouterr().out) == DENIAL + + +@pytest.mark.parametrize( + "defect", + [{"matcher": "^(Task|Agent|Workflow$|spawn_task"}, {"hooks": [UNSUPPORTED]}], + ids=["bad-matcher", "unsupported-hook"], +) +def test_a_defective_advisory_group_is_skipped_and_the_guard_still_runs( + bridge, tmp_path, capsys, defect +): + advisory = {"matcher": ".*", "hooks": [handler("{}")], **defect} + write_settings(tmp_path, {"PreToolUse": [advisory, GUARD_DENY]}) + assert run(bridge, tmp_path, BASH_CALL, "PreToolUse") == 0 + result = json.loads(capsys.readouterr().out) + assert result["hookSpecificOutput"] == DENIAL["hookSpecificOutput"] + assert "skipped a hook group with a defect" in result["systemMessage"] + + +def test_a_defect_in_the_guard_group_itself_still_blocks(bridge, tmp_path): + guard = {**GUARD_DENY, "hooks": [*GUARD_DENY["hooks"], UNSUPPORTED]} + write_settings(tmp_path, {"PreToolUse": [guard]}) + assert run(bridge, tmp_path, BASH_CALL, "PreToolUse") == 2 From b1e5bdf80abd828f360528ed14f37930b479de99 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 16:25:35 -0600 Subject: [PATCH 07/51] Only a hook blocks in the Codex bridge; a bridge fault or a launcher with no decision is reported Final round. The fault-block rule is removed: a bridge fault and a launcher outcome with no decision are reported on stderr and as a systemMessage and do not block, on any event. Only a hook's exit 2, carried as bridge exit 10 and turned into 2 by invoke.ps1, or a failing hook with onFailure set to block, blocks. No decision is a non-blocking 1 on every event, so the PreToolUse case is gone from invoke.ps1 and .codex/config.toml. A decision gathered before a fault, such as an earlier hook's deny, still stands. A registered event outside the known events is a reported fault. docs/CODEX.md states the rule once. BACKLOG #5496 BACKLOG #5501 Proposed PR title: The Codex bridge follows Claude Code's hook exit contract, and its tests dispatch the tracked hook settings (BACKLOG #5496, #5501) Proposed banners: #5496 SHIPPED: only a hook's exit 2, or a failing hook with onFailure block, blocks; a non-2 exit, a timeout, an unstartable hook and every bridge fault are reported and non-blocking; item 1 (S34-14) is fixed. #5501 SHIPPED: tests/test_codex_bridge.py dispatches every hook in the tracked .claude/settings.json and pins exit 1 as non-blocking against a blocking exit 2. --- .codex/config.toml | 10 +- docs/CODEX.md | 68 ++++++------ scripts/codex/bridge.py | 89 +++++----------- scripts/codex/invoke.ps1 | 19 ++-- tests/test_codex_bridge.py | 211 ++++++++++++++++++------------------- 5 files changed, 179 insertions(+), 218 deletions(-) diff --git a/.codex/config.toml b/.codex/config.toml index 108f14d385..d48f0ea5df 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -1,8 +1,8 @@ # Claude Code remains the source of hook policy. The bridge reads it on each event. -# Each command names its event, so a launcher failure that leaves no decision blocks on -# PreToolUse (the inner exit 2) and is a non-blocking 1 elsewhere. The trailing exit passes -# the code on where PowerShell runs the line, since pwsh -Command reports a native exit 2 as 1; -# under sh it exits with pwsh's status, and under cmd pwsh receives it as more -Command text. +# Only a hook's block reaches Codex as exit 2. A launcher that cannot run the bridge (the inner +# exit 1) is a non-blocking error on every event. The trailing exit passes the code on where +# PowerShell runs this line, since pwsh -Command reports a native exit 2 as 1; under sh it exits +# with pwsh's status, and under cmd pwsh receives it as more -Command text. # docs/CODEX.md, "Who decides a block", states the rule. [features] hooks = true @@ -22,7 +22,7 @@ timeout = 90 [[hooks.PreToolUse]] [[hooks.PreToolUse.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PreToolUse; exit 2"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PreToolUse; exit 1"; exit $LASTEXITCODE''' timeout = 90 [[hooks.PostToolUse]] diff --git a/docs/CODEX.md b/docs/CODEX.md index 5082aba9cc..f73af16898 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -29,44 +29,40 @@ claim a failed hook ran. ### Who decides a block -The hooks decide first. As in Claude Code, a hook's exit 2 blocks. Any other -non-zero exit, a timeout, or a command that cannot start is a non-blocking error, -unless the hook sets `"onFailure": "block"`. The bridge reports a non-blocking -error on stderr and as a `systemMessage`, naming the hook, ignores that hook's -output, and runs the remaining hooks. - -The bridge decides its own faults. A fault is anything that keeps it from -running the hooks: settings that cannot be parsed, a missing session id, a -payload that cannot be read as UTF-8 JSON, a payload whose `hook_event_name` -differs from the registered event in more than case, or any other exception. A -fault blocks only on `PreToolUse`, judged under the registered event, and only -where a guard group could have run for the tool, or where that cannot be judged -because the settings or the payload cannot be parsed. A guard group is one that -runs `scripts/hooks/shell-guard-dispatch.ps1` or holds a hook with -`"onFailure": "block"`; today that is the `^(Bash|PowerShell)$` group. Every other -fault is reported on stderr and as a `systemMessage` and does not block, so a -fault never stops Codex from stopping, starting or taking a prompt. - -Each hook group is judged on its own. A defect in a group, such as a matcher that -is not a valid regex or an unsupported handler type or shell, is a fault when the -group is a guard group. In any other group it is reported and that group is -skipped, so a guard group after it still runs. The advisory `PreToolUse` hooks, -such as `usage-headroom-inject.ps1` and `enter-worktree-check.ps1`, stay -non-blocking. **A future guard on any other event must set -`"onFailure": "block"`**, or its failures will not block. - -The launcher decides when the bridge returns no decision. In hook mode the +Only a hook blocks. As in Claude Code, a hook's exit 2 blocks. So does a hook +that sets `"onFailure": "block"` when it fails: a non-zero exit, a timeout, a +command that cannot start, or a defect in its group. Any other hook failure is a +non-blocking error. The bridge reports it on stderr and as a `systemMessage`, +naming the hook, ignores that hook's output, and runs the remaining hooks. A JSON +`permissionDecision` deny from a hook is a decision, not a failure, and is passed +on as before. + +A bridge fault never blocks, on any event. A fault is anything that keeps the +bridge from running the hooks: settings that cannot be parsed, a missing session +id, a payload that cannot be read as UTF-8 JSON, a payload whose +`hook_event_name` differs from the registered event in more than case, or any +other exception. The bridge reports it on stderr and as a `systemMessage`, and +keeps any decision already gathered, such as an earlier hook's deny. Each hook +group is judged on its own: a defect in a group, such as a matcher that is not a +valid regex or an unsupported handler type or shell, is reported and that group +skipped, so the groups after it still run. + +A launcher that cannot run the bridge never blocks either. In hook mode the bridge exits 0 to proceed or 10 to block, and `invoke.ps1` turns 10 into 2. Any other outcome is no decision: another bridge exit, including the 2 that Python -and argparse exit with, a missing `.venv`, or a checkout `git` cannot find. Each -command in `.codex/config.toml` names its event, and no decision maps to exit 2 -on the `PreToolUse` command and to a non-blocking exit 1 on every other event, -never to 0. `invoke.ps1` ends its process with that code, and the command line -passes it on, because `pwsh -Command` would report an exit 2 as 1. This is tested -with PowerShell, `cmd` and `sh` as the outer shell. Codex's documentation does -not say which shell runs a hook command. One case is not covered: when `pwsh` -itself cannot start. Under Windows PowerShell 5.1 the line would then exit 0, -under `cmd` 9009, and under `sh` 127. This is reasoned, not measured. +and argparse exit with, a missing `.venv`, or a checkout `git` cannot find. No +decision is reported and maps to a non-blocking exit 1 on every event, never to +0 or 2. `invoke.ps1` ends its process with its code, and the command line passes +it on, because `pwsh -Command` would report an exit 2 as 1. This is tested with +PowerShell, `cmd` and `sh` as the outer shell. Codex's documentation does not +say which shell runs a hook command. When `pwsh` itself cannot start, the line +would exit 0 under Windows PowerShell 5.1, 9009 under `cmd` and 127 under `sh`; +this is reasoned, not measured. + +At origin/main before this change, no exit-2 block reached Codex: `pwsh -Command` +reported the bridge's exit 2 as 1. A hook's JSON `permissionDecision` deny was +unaffected. **A future guard that must block when it fails sets +`"onFailure": "block"`.** The bridge differs from Claude Code in at least three ways. It runs an event's hooks one after another, where Claude Code runs them in parallel. Exit 2 stops diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index f8220a5cc8..c351862b07 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -174,13 +174,9 @@ def merge_output(result: dict, update: dict) -> None: } # Claude Code adds a hook's plain exit-0 stdout as context for these events only. PLAIN_CONTEXT_EVENTS = ("SessionStart", "UserPromptSubmit") -# A guard group is one whose hooks exist to refuse a tool call. A bridge fault blocks only where a -# guard group could have run; see docs/CODEX.md, "Who decides a block". -GUARD_SCRIPTS = ("scripts/hooks/shell-guard-dispatch.ps1",) - - -# Hook mode's exit code for run_hook's block. invoke.ps1 turns it into 2 and maps every other -# non-zero, the interpreter's and argparse's 2 included, to the event's no-decision code. +# Hook mode's exit code for run_hook's block. invoke.ps1 turns it into 2 and every other non-zero, +# the interpreter's and argparse's 2 included, into a non-blocking 1. See docs/CODEX.md, "Who +# decides a block". BLOCK_EXIT = 10 @@ -281,46 +277,13 @@ def group_selected(group: dict, discriminator: set[str] | None) -> bool: ) -def is_guard(group: dict) -> bool: - for hook in group.get("hooks", []): - words = [str(hook.get("command", "")), *(str(arg) for arg in hook.get("args", []))] - if hook.get("onFailure") == "block" or any( - word.replace("\\", "/").endswith(script) for word in words for script in GUARD_SCRIPTS - ): - return True - return False - - -def group_is_guard(group: dict) -> bool: - try: - return is_guard(group) - except (AttributeError, TypeError): - return True # A group too malformed to read may be a guard. - - -def fault_blocks(root: Path, payload: object, event: str) -> bool: - """Whether a bridge fault must block: only on PreToolUse, and only where a guard could run.""" - if not event and isinstance(payload, dict): - event = str(payload.get("hook_event_name") or "") - if event != "PreToolUse": - return False # A fault never stops Codex from stopping, starting or prompting. - if not isinstance(payload, dict): - return True # No tool to judge, so a guard may have been skipped. - try: - discriminator = discriminator_for(event, payload) - groups = read_settings(root).get("hooks", {}).get(event, []) - return any(is_guard(group) and group_selected(group, discriminator) for group in groups) - except Exception: # noqa: BLE001 - settings or a matcher that cannot be judged may hide a guard - return True - - def run_hook(root: Path, stdin: bytes | str | None = None, event: str = "") -> int: """Decide one Codex hook event: 0 to proceed or 2 to block, never anything else. With no stdin given, the payload is read from this process's stdin as UTF-8 bytes; the text stream would decode it with the console code page. `event` is the event Codex registered. """ - payload: object = None + result: dict = {} try: if stdin is None: stdin = sys.stdin.buffer.read() @@ -329,23 +292,20 @@ def run_hook(root: Path, stdin: bytes | str | None = None, event: str = "") -> i raise ValueError("the hook payload must be a JSON object") named = str(payload.get("hook_event_name") or "") if event: - if named.lower() != event.lower(): + canonical = next((known for known in EVENTS if known.lower() == event.lower()), None) + if canonical is None or named.lower() != event.lower(): raise ValueError(f"the payload names event {named!r}, registered as {event!r}") - payload["hook_event_name"] = event # The registered spelling selects the settings. - result = dispatch(root, payload) + payload["hook_event_name"] = canonical # The canonical spelling selects the settings. + dispatch(root, payload, result) except HookBlocked as exc: print(str(exc), file=sys.stderr) return 2 - except Exception as exc: # noqa: BLE001 - every bridge fault is decided here, not by a crash - message = f"Codex bridge fault: {type(exc).__name__}: {exc}" - if fault_blocks(root, payload, event): - print( - f"{message} (blocking: a guard hook could have run for this tool)", file=sys.stderr - ) - return 2 - print(f"{message} (not blocking)", file=sys.stderr) - print(json.dumps({"systemMessage": f"{message} (not blocking)"})) - return 0 + except Exception as exc: # noqa: BLE001 - a bridge fault is reported here, never a block + # A fault never blocks, on any event, but a decision already gathered, such as an + # earlier hook's deny, still stands. + message = f"Codex bridge fault: {type(exc).__name__}: {exc} (not blocking)" + print(message, file=sys.stderr) + merge_output(result, {"systemMessage": message}) if result: print(json.dumps(result)) return 0 @@ -409,13 +369,19 @@ def run_group(root: Path, payload: dict, env: dict[str, str], group: dict, resul merge_output(result, update) -def dispatch(root: Path, payload: dict) -> dict: +def blocks_on_failure(group: dict) -> bool: + hooks = group.get("hooks", []) if isinstance(group, dict) else [] + return any(isinstance(hook, dict) and hook.get("onFailure") == "block" for hook in hooks) + + +def dispatch(root: Path, payload: dict, result: dict | None = None) -> dict: + """Run the event's hooks, gathering their output into `result`, which a fault leaves intact.""" + result = {} if result is None else result event = payload["hook_event_name"] env = child_environment(root, payload.get("session_id", "")) config = read_settings(root) if config.get("disableAllHooks"): - return {} - result: dict = {} + return result if event == "SessionStart": unknown = set(config.get("hooks", {})) - set(EVENTS) context = ( @@ -439,14 +405,13 @@ def dispatch(root: Path, payload: dict) -> dict: except HookBlocked: raise except (AttributeError, KeyError, TypeError, ValueError, re.error) as exc: - # Each group is judged on its own. A defect in a guard group is a bridge fault, which - # run_hook decides; one in an advisory group is reported and skipped, so a guard group - # after it still runs. - if group_is_guard(group): - raise + # Each group is judged on its own: a defect is reported and that group skipped, so + # the groups after it still run. A hook in it that set onFailure to block has failed. message = ( f"Codex bridge: skipped a hook group with a defect: {type(exc).__name__}: {exc}" ) + if blocks_on_failure(group): + raise HookBlocked(f"{message} (onFailure is block)") from exc print(f"{message} (not blocking)", file=sys.stderr) merge_output(result, {"systemMessage": f"{message} (not blocking)"}) return result diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 639ee7a13b..a3d8753a06 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -18,18 +18,21 @@ function Resolve-BridgePython { if ($args.Count -gt 0 -and $args[0] -eq 'hook') { # The bridge decides with exit 0, or with 10 (BLOCK_EXIT in bridge.py) for a block, which # becomes 2 here. Anything else, a missing .venv, a crash, or the 2 that Python and argparse - # exit with, is no decision: it blocks on the PreToolUse registration and is a non-blocking 1 - # on every other event. docs/CODEX.md, "Who decides a block", states the rule. - $noDecision = 1 - for ($i = 1; $i -lt $args.Count - 1; $i++) { - if ($args[$i] -eq '--event' -and $args[$i + 1] -eq 'PreToolUse') { $noDecision = 2 } - } - $code = $noDecision + # exit with, is no decision: reported, and a non-blocking 1 on every event. + # docs/CODEX.md, "Who decides a block", states the rule. + $code = 1 + $why = '' try { & (Resolve-BridgePython) (Join-Path $PSScriptRoot 'bridge.py') @args if ($LASTEXITCODE -eq 0) { $code = 0 } elseif ($LASTEXITCODE -eq 10) { $code = 2 } + else { $why = "the bridge exited $LASTEXITCODE" } } catch { - [Console]::Error.WriteLine("Codex bridge launcher: $_") + $why = "$_" + } + if ($code -eq 1) { + $message = "Codex bridge launcher: no decision, not blocking: $why" + [Console]::Error.WriteLine($message) + [Console]::Out.WriteLine((@{ systemMessage = $message } | ConvertTo-Json -Compress)) } # Codex starts this through pwsh -Command, which reports a script's exit 2 as 1. Ending the # process keeps the code. Hook mode only: an interactive caller's window must survive `run`. diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 16544ba51b..1481d783db 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -125,9 +125,9 @@ def test_new_unsupported_hook_is_reported(bridge, tmp_path): settings(tmp_path, [{"type": "prompt", "prompt": "review"}]) # In an advisory group it is reported and the group skipped. assert "prompt" in bridge.dispatch(tmp_path, payload)["systemMessage"] - # In a guard group it is a fault, which run_hook decides. + # A hook that set onFailure to block has failed, so it blocks. settings(tmp_path, [{"type": "prompt", "prompt": "review", "onFailure": "block"}]) - with pytest.raises(ValueError, match="prompt"): + with pytest.raises(bridge.HookBlocked, match="prompt"): bridge.dispatch(tmp_path, payload) @@ -536,20 +536,10 @@ def test_registered_command_runs_from_a_subdirectory(tmp_path): assert json.loads(completed.stdout) == {"probe": True} -# --- Who decides a block: the bridge for its own faults, the launcher when there is no decision. +# --- Who decides a block: only a hook. A bridge fault or a launcher with no decision never blocks. -GUARD_GROUP = { - "matcher": "^(Bash|PowerShell)$", - "hooks": [ - { - "type": "command", - "command": "pwsh", - "args": ["-File", "${CLAUDE_PROJECT_DIR}/scripts/hooks/shell-guard-dispatch.ps1"], - } - ], -} -ADVISORY_GROUP = {"matcher": "^(Task|Agent|Workflow)$", "hooks": [handler("{}")]} UNSUPPORTED = {"type": "prompt", "prompt": "review"} +DENY_GROUP = {"matcher": "^(Bash|PowerShell)$", "hooks": [handler(json.dumps(DENIAL))]} def write_settings(root, hooks): @@ -562,64 +552,57 @@ def run(bridge, root, payload, event=""): return bridge.run_hook(root, text, event) -@pytest.mark.parametrize( - ("tool", "code"), - [("Bash", 2), ("PowerShell", 2), ("Agent", 0)], - ids=["guarded-bash", "guarded-powershell", "advisory-agent"], -) -def test_a_bridge_fault_blocks_only_where_a_guard_could_have_run( - bridge, tmp_path, capsys, tool, code -): - write_settings(tmp_path, {"PreToolUse": [ADVISORY_GROUP, GUARD_GROUP]}) - payload = {"hook_event_name": "PreToolUse", "tool_name": tool} # no session_id: a fault - assert run(bridge, tmp_path, payload) == code +def reported(capsys, text="Codex bridge fault"): + """The fault reached stderr and the systemMessage Codex reads; returns the printed result.""" captured = capsys.readouterr() - assert "Codex bridge fault: ValueError" in captured.err - if code == 0: - assert "(not blocking)" in json.loads(captured.out)["systemMessage"] - else: - assert "blocking: a guard hook could have run" in captured.err - - -@pytest.mark.parametrize("event", ["Stop", "SubagentStop", "SessionStart", "UserPromptSubmit"]) -def test_a_bridge_fault_never_blocks_another_event(bridge, tmp_path, capsys, event): - """A fault on Stop must not stop Codex from stopping.""" - write_settings(tmp_path, {event: [{"hooks": [UNSUPPORTED]}]}) - assert run(bridge, tmp_path, {"session_id": "x", "hook_event_name": event}) == 0 - assert "(not blocking)" in json.loads(capsys.readouterr().out)["systemMessage"] + assert text in captured.err + result = json.loads(captured.out.splitlines()[-1]) + assert text in result["systemMessage"] + assert "(not blocking)" in result["systemMessage"] + return result -@pytest.mark.parametrize(("event", "code"), [("PreToolUse", 2), ("Stop", 0)]) -def test_settings_that_cannot_be_parsed_block_only_pretooluse(bridge, tmp_path, event, code): +@pytest.mark.parametrize("tool", ["Bash", "PowerShell", "Agent", "EnterWorktree", "Read"]) +def test_a_fault_under_the_tracked_settings_is_reported_and_never_blocks( + bridge, tmp_path, capsys, tool +): + """A missing session id would have blocked the guarded shell call; nothing blocks now.""" + tracked = _tracked_settings() (tmp_path / ".claude").mkdir() - (tmp_path / ".claude/settings.json").write_text("{ not json", encoding="utf-8") - payload = {"session_id": "x", "hook_event_name": event, "tool_name": "Read"} - assert run(bridge, tmp_path, payload) == code + (tmp_path / ".claude/settings.json").write_text(json.dumps(tracked), encoding="utf-8") + payload = {"hook_event_name": "PreToolUse", "tool_name": tool} # no session_id: a fault + assert run(bridge, tmp_path, payload, "PreToolUse") == 0 + reported(capsys) @pytest.mark.parametrize( - ("event", "group", "code"), - [ - ("PreToolUse", GUARD_GROUP, 2), - ("PreToolUse", ADVISORY_GROUP, 0), - ("SessionStart", GUARD_GROUP, 0), - ], - ids=["guard", "advisory", "other-event"], + "event", ["PreToolUse", "PermissionRequest", "Stop", "SubagentStop", "SessionStart"] ) -def test_a_guard_matcher_that_cannot_be_judged_blocks_only_pretooluse( - bridge, tmp_path, event, group, code +def test_a_fault_on_any_event_is_reported_and_never_blocks(bridge, tmp_path, capsys, event): + write_settings(tmp_path, {event: [DENY_GROUP], "disableAllHooks": True}) + assert run(bridge, tmp_path, {"hook_event_name": event, "tool_name": "Bash"}, event) == 0 + reported(capsys) + + +@pytest.mark.parametrize("event", ["PreToolUse", "Stop"]) +def test_settings_that_cannot_be_parsed_are_reported_and_never_block( + bridge, tmp_path, capsys, event ): - write_settings(tmp_path, {event: [{**group, "matcher": "(["}]}) - payload = {"session_id": "x", "hook_event_name": event, "tool_name": "Read", "source": "x"} - assert run(bridge, tmp_path, payload) == code + (tmp_path / ".claude").mkdir() + (tmp_path / ".claude/settings.json").write_text("{ not json", encoding="utf-8") + payload = {"session_id": "x", "hook_event_name": event, "tool_name": "Bash"} + assert run(bridge, tmp_path, payload, event) == 0 + reported(capsys) -@pytest.mark.parametrize( - ("event", "code"), [("PreToolUse", 2), ("Stop", 0), ("", 0)], ids=["pre", "stop", "unknown"] -) -def test_a_payload_that_cannot_be_parsed_uses_the_registered_event(bridge, tmp_path, event, code): - write_settings(tmp_path, {}) - assert run(bridge, tmp_path, "{ not json", event) == code +@pytest.mark.parametrize("text", ["{ not json", '["a list"]', ""]) +@pytest.mark.parametrize("event", ["PreToolUse", "Stop", ""]) +def test_a_payload_that_cannot_be_parsed_is_reported_and_never_blocks( + bridge, tmp_path, capsys, event, text +): + write_settings(tmp_path, {"PreToolUse": [DENY_GROUP]}) + assert run(bridge, tmp_path, text, event) == 0 + reported(capsys) def test_a_deliberate_block_and_a_clean_run_exit_2_and_0(bridge, tmp_path, capsys): @@ -631,23 +614,35 @@ def test_a_deliberate_block_and_a_clean_run_exit_2_and_0(bridge, tmp_path, capsy @pytest.mark.parametrize( - ("tool", "code"), - [("Bash", 2), ("PowerShell", 2), ("Agent", 0), ("EnterWorktree", 0), ("Read", 0)], + ("event", "decision", "kept"), + [ + ("PreToolUse", DENIAL, ("hookSpecificOutput", DENIAL["hookSpecificOutput"])), + ("Stop", {"decision": "block", "reason": "not yet"}, ("decision", "block")), + ], + ids=["deny", "stop-block"], ) -def test_in_the_tracked_settings_only_the_shell_guard_makes_a_fault_block( - bridge, tmp_path, tool, code +def test_a_decision_gathered_before_a_fault_still_stands( + bridge, tmp_path, capsys, monkeypatch, event, decision, kept ): - """Advisory PreToolUse hooks (usage-headroom-inject, enter-worktree-check) stay non-blocking.""" - tracked = _tracked_settings() - guards = [g for g in tracked["hooks"]["PreToolUse"] if bridge.is_guard(g)] - assert [g["matcher"] for g in guards] == ["^(Bash|PowerShell)$"] - (tmp_path / ".claude").mkdir() - (tmp_path / ".claude/settings.json").write_text(json.dumps(tracked), encoding="utf-8") - # A payload with no session_id is a bridge fault before any hook runs. - assert run(bridge, tmp_path, {"hook_event_name": "PreToolUse", "tool_name": tool}) == code + first = {"matcher": "", "hooks": [handler(json.dumps(decision))]} + write_settings(tmp_path, {event: [first, {"matcher": "", "hooks": [handler("{}")]}]}) + real_run_group = bridge.run_group + calls = [] + + def fault_on_second(*args): + calls.append(args) + if len(calls) == 2: + raise RuntimeError("a fault after a decision") + real_run_group(*args) + monkeypatch.setattr(bridge, "run_group", fault_on_second) + payload = {"session_id": "x", "hook_event_name": event, "tool_name": "Bash"} + assert run(bridge, tmp_path, payload, event) == 0 + result = reported(capsys, "a fault after a decision") + assert result[kept[0]] == kept[1] -# --- The launcher and the registered commands: a missing decision blocks only on PreToolUse. + +# --- The launcher and the registered commands: no decision is a non-blocking 1 on every event. _STUB_BRIDGE = "import os, sys\nsys.exit(int(os.environ['STUB_BRIDGE_EXIT']))\n" @@ -688,10 +683,11 @@ def _link_python(root): [ ("PreToolUse", "0", 0), ("PreToolUse", "10", 2), - ("PreToolUse", "2", 2), - ("PreToolUse", "1", 2), - ("PreToolUse", "no-venv", 2), - ("PreToolUse", "no-repo", 2), + # A launcher that cannot run the bridge would lock Codex out of the fix if it blocked. + ("PreToolUse", "2", 1), + ("PreToolUse", "1", 1), + ("PreToolUse", "no-venv", 1), + ("PreToolUse", "no-repo", 1), ("Stop", "0", 0), ("Stop", "10", 2), # Python's "can't open file", argparse and a crash exit 2: no decision, never a block. @@ -704,8 +700,8 @@ def _link_python(root): def test_a_registered_command_passes_a_decision_and_maps_no_decision( tmp_path, shell, event, setup, expected ): - """No decision (a crash, a missing .venv, no repo) blocks on PreToolUse and is a - non-blocking 1 elsewhere, never 0. The real invoke.ps1 runs a stub bridge.""" + """No decision (a crash, a missing .venv, no repo) is a non-blocking 1 on every event, never 0 + and never 2. The real invoke.ps1 runs a stub bridge.""" import tomllib assert bridge_block_exit() == 10, "invoke.ps1 hardcodes the bridge's BLOCK_EXIT" @@ -734,6 +730,8 @@ def test_a_registered_command_passes_a_decision_and_maps_no_decision( timeout=60, ) assert completed.returncode == expected, (shell, completed.stdout, completed.stderr) + if expected == 1 and setup != "no-repo": # invoke.ps1 ran and reported it. + assert "no decision, not blocking" in json.loads(completed.stdout)["systemMessage"] def bridge_block_exit(): @@ -794,32 +792,28 @@ def call(argv, **kwargs): assert calls[0][-6:] == ["--event", "push", "--even", "x", "--limit", "3"] -GUARD_DENY = { - "matcher": "^(Bash|PowerShell)$", - "hooks": [{**handler(json.dumps(DENIAL)), "onFailure": "block"}], -} - - @pytest.mark.parametrize( - ("registered", "named", "code"), - [("PreToolUse", "Stop", 2), ("PreToolUse", None, 2), ("Stop", "PreToolUse", 0)], - ids=["pre-named-stop", "pre-unnamed", "stop-named-pre"], + ("registered", "named"), + [("PreToolUse", "Stop"), ("PreToolUse", None), ("Stop", "PreToolUse"), ("PreToolUze", None)], + ids=["pre-named-stop", "pre-unnamed", "stop-named-pre", "unknown-registration"], ) -def test_a_payload_naming_another_event_is_a_fault_under_the_registered_one( - bridge, tmp_path, capsys, registered, named, code +def test_a_payload_naming_another_event_is_a_reported_fault( + bridge, tmp_path, capsys, registered, named ): - write_settings(tmp_path, {"PreToolUse": [GUARD_DENY], "Stop": [{"hooks": [handler("{}")]}]}) + write_settings(tmp_path, {"PreToolUse": [DENY_GROUP], "Stop": [{"hooks": [exits(2)]}]}) payload = {"session_id": "x", "tool_name": "Bash"} if named: payload["hook_event_name"] = named - assert run(bridge, tmp_path, payload, registered) == code - assert "registered as" in capsys.readouterr().err + if registered == "PreToolUze": + payload["hook_event_name"] = "PreToolUze" + assert run(bridge, tmp_path, payload, registered) == 0 + reported(capsys, "registered as") -def test_an_event_name_in_another_case_still_runs_the_guard(bridge, tmp_path, capsys): - write_settings(tmp_path, {"PreToolUse": [GUARD_DENY]}) +def test_an_event_name_in_another_case_still_runs_the_hooks(bridge, tmp_path, capsys): + write_settings(tmp_path, {"PreToolUse": [DENY_GROUP]}) payload = {**BASH_CALL, "hook_event_name": "pretooluse"} - assert run(bridge, tmp_path, payload, "PreToolUse") == 0 + assert run(bridge, tmp_path, payload, "PRETOOLUSE") == 0 assert json.loads(capsys.readouterr().out) == DENIAL @@ -828,18 +822,21 @@ def test_an_event_name_in_another_case_still_runs_the_guard(bridge, tmp_path, ca [{"matcher": "^(Task|Agent|Workflow$|spawn_task"}, {"hooks": [UNSUPPORTED]}], ids=["bad-matcher", "unsupported-hook"], ) -def test_a_defective_advisory_group_is_skipped_and_the_guard_still_runs( - bridge, tmp_path, capsys, defect -): - advisory = {"matcher": ".*", "hooks": [handler("{}")], **defect} - write_settings(tmp_path, {"PreToolUse": [advisory, GUARD_DENY]}) +def test_a_defective_group_is_skipped_and_later_groups_still_run(bridge, tmp_path, capsys, defect): + defective = {"matcher": ".*", "hooks": [handler("{}")], **defect} + write_settings(tmp_path, {"PreToolUse": [defective, DENY_GROUP]}) assert run(bridge, tmp_path, BASH_CALL, "PreToolUse") == 0 - result = json.loads(capsys.readouterr().out) + result = reported(capsys, "skipped a hook group with a defect") assert result["hookSpecificOutput"] == DENIAL["hookSpecificOutput"] - assert "skipped a hook group with a defect" in result["systemMessage"] -def test_a_defect_in_the_guard_group_itself_still_blocks(bridge, tmp_path): - guard = {**GUARD_DENY, "hooks": [*GUARD_DENY["hooks"], UNSUPPORTED]} - write_settings(tmp_path, {"PreToolUse": [guard]}) +@pytest.mark.parametrize( + "defect", + [{"matcher": "(["}, {"hooks": [{**UNSUPPORTED, "onFailure": "block"}]}], + ids=["bad-matcher", "unsupported-hook"], +) +def test_a_defective_group_whose_hook_sets_on_failure_block_blocks(bridge, tmp_path, defect): + group = {"matcher": ".*", "hooks": [{**handler("{}"), "onFailure": "block"}], **defect} + # PreToolUse, because Stop ignores a matcher and would never read the bad one. + write_settings(tmp_path, {"PreToolUse": [group]}) assert run(bridge, tmp_path, BASH_CALL, "PreToolUse") == 2 From 98959e16f513d9d3f8f3e78906f5c23a0d1c639f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 16:49:24 -0600 Subject: [PATCH 08/51] The Codex bridge blocks on a PowerShell hook's own exit 2 and on its own onFailure hook only Four fixes from the last review round. A PowerShell hook blocks on exit 2 only when the failed last statement left it and no cmdlet error was recorded, so a stale native exit 2 followed by a failed cmdlet stays a non-blocking 1. A defect belongs to its own hook: it blocks only when that hook set onFailure to block, and an advisory hook's defect in the same group is reported and that hook skipped. invoke.ps1 pins $PSNativeCommandUseErrorActionPreference off, so a caller's preference cannot turn a block into no decision. disableAllHooks is read before the session id, so disabled hooks report nothing. BACKLOG #5496 BACKLOG #5501 Proposed PR title: The Codex bridge follows Claude Code's hook exit contract, and its tests dispatch the tracked hook settings (BACKLOG #5496, #5501) Proposed banners: #5496 SHIPPED: only a hook's exit 2, or a failing hook with onFailure block, blocks; a non-2 exit, a timeout, an unstartable hook and every bridge fault are reported and non-blocking; item 1 (S34-14) is fixed. #5501 SHIPPED: tests/test_codex_bridge.py dispatches every hook in the tracked .claude/settings.json and pins exit 1 as non-blocking against a blocking exit 2. --- docs/CODEX.md | 13 ++-- scripts/codex/bridge.py | 143 +++++++++++++++++++++---------------- scripts/codex/invoke.ps1 | 2 + tests/test_codex_bridge.py | 69 +++++++++++++++++- 4 files changed, 159 insertions(+), 68 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index f73af16898..3cf1ff1bc9 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -31,7 +31,9 @@ claim a failed hook ran. Only a hook blocks. As in Claude Code, a hook's exit 2 blocks. So does a hook that sets `"onFailure": "block"` when it fails: a non-zero exit, a timeout, a -command that cannot start, or a defect in its group. Any other hook failure is a +command that cannot start, a defect of its own such as an unsupported handler +type or shell, or a defect in its group, such as a matcher that is not a valid +regex, that keeps it from running. Any other hook failure is a non-blocking error. The bridge reports it on stderr and as a `systemMessage`, naming the hook, ignores that hook's output, and runs the remaining hooks. A JSON `permissionDecision` deny from a hook is a decision, not a failure, and is passed @@ -42,10 +44,11 @@ bridge from running the hooks: settings that cannot be parsed, a missing session id, a payload that cannot be read as UTF-8 JSON, a payload whose `hook_event_name` differs from the registered event in more than case, or any other exception. The bridge reports it on stderr and as a `systemMessage`, and -keeps any decision already gathered, such as an earlier hook's deny. Each hook -group is judged on its own: a defect in a group, such as a matcher that is not a -valid regex or an unsupported handler type or shell, is reported and that group -skipped, so the groups after it still run. +keeps any decision already gathered, such as an earlier hook's deny. A defect is +judged where it belongs. A hook's own defect is reported and that hook skipped; +the hooks before it have already run, and the hooks after it still run. A defect +in a group, such as its matcher, is reported and that group skipped, and the +groups after it still run. A launcher that cannot run the bridge never blocks either. In hook mode the bridge exits 0 to proceed or 10 to block, and `invoke.ps1` turns 10 into 2. Any diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index c351862b07..3ee7d1c92c 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -200,9 +200,15 @@ def git_bash() -> str | None: # -Command reports a native program's exit 2 as 1, which would turn a block into a non-blocking -# error. This tail keeps -Command's own result, 0 or 1, except that a failed last statement which -# left exit code 2 behind exits 2. -POWERSHELL_EXIT_TAIL = "\nif (-not $?) { if ($LASTEXITCODE -eq 2) { exit 2 }; exit 1 }" +# error. The head and tail keep -Command's own result, 0 or 1, except that a failed last statement +# exits 2 when it left exit code 2 behind and no cmdlet error was recorded. A failed cmdlet records +# one, so an earlier native exit 2 followed by a failed cmdlet stays a non-blocking 1. A cmdlet +# error anywhere before a final native exit 2 also makes it 1. The head keeps a native exit from +# recording an error where a PowerShell build defaults that preference on. +POWERSHELL_EXIT_HEAD = "$PSNativeCommandUseErrorActionPreference = $false; $Error.Clear()\n" +POWERSHELL_EXIT_TAIL = ( + "\nif (-not $?) { if ($LASTEXITCODE -eq 2 -and $Error.Count -eq 0) { exit 2 }; exit 1 }" +) def hook_argv(root: Path, hook: dict) -> list[str]: @@ -225,7 +231,8 @@ def hook_argv(root: Path, hook: dict) -> list[str]: shell = "powershell" if shell == "powershell": command = command.replace("${CLAUDE_PROJECT_DIR}", "${env:CLAUDE_PROJECT_DIR}") - return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command + POWERSHELL_EXIT_TAIL] + script = POWERSHELL_EXIT_HEAD + command + POWERSHELL_EXIT_TAIL + return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script] raise ValueError(f"Unsupported Claude hook shell: {shell}") @@ -311,62 +318,77 @@ def run_hook(root: Path, stdin: bytes | str | None = None, event: str = "") -> i return 0 -def run_group(root: Path, payload: dict, env: dict[str, str], group: dict, result: dict) -> None: +def run_one_hook(root: Path, payload: dict, env: dict[str, str], hook: dict, result: dict) -> None: event = payload["hook_event_name"] + if hook.get("type") != "command" or hook.get("async"): + raise ValueError( + f"Unsupported Claude hook transport: {hook.get('type')}, async={hook.get('async', False)}" + ) + # Claude Code's hook contract: exit 2 blocks. Any other failure, a timeout or a command + # that cannot start included, is a non-blocking error unless the hook sets onFailure to + # block, and the remaining hooks still run. Only a successful hook's stdout is read. + try: + completed = subprocess.run( # nosec B603 - trusted repo hook; stdin carries event data + hook_argv(root, hook), + input=json.dumps(payload), + cwd=root, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=hook.get("timeout", 30), + check=False, + ) + except subprocess.TimeoutExpired as exc: + captured = exc.stderr or "" + if isinstance(captured, bytes): + captured = captured.decode("utf-8", "replace") + print_hook_stderr(captured) + hook_failed(result, hook, f"timed out after {exc.timeout} seconds") + return + except OSError as exc: + hook_failed(result, hook, f"could not start ({exc})") + return + if completed.returncode == 2: + raise HookBlocked(completed.stderr.strip() or "Claude hook blocked this event") + print_hook_stderr(completed.stderr) + if completed.returncode: + hook_failed(result, hook, f"exited {completed.returncode}") + return + output = completed.stdout.strip() + if not output: + return + try: + update = json.loads(output) + except json.JSONDecodeError: + update = None + if not isinstance(update, dict): + if event not in PLAIN_CONTEXT_EVENTS: + print(output, file=sys.stderr) + return + output = output.replace( + "scripts\\coord\\seat.ps1", + "scripts\\codex\\invoke.ps1 run scripts/coord/seat.ps1", + ) + update = {"hookSpecificOutput": {"hookEventName": event, "additionalContext": output}} + merge_output(result, update) + + +def run_group(root: Path, payload: dict, env: dict[str, str], group: dict, result: dict) -> None: for hook in group.get("hooks", []): - if hook.get("type") != "command" or hook.get("async"): - raise ValueError( - f"Unsupported Claude hook transport: {hook.get('type')}, async={hook.get('async', False)}" - ) - # Claude Code's hook contract: exit 2 blocks. Any other failure, a timeout or a command - # that cannot start included, is a non-blocking error unless the hook sets onFailure to - # block, and the remaining hooks still run. Only a successful hook's stdout is read. try: - completed = subprocess.run( # nosec B603 - trusted repo hook; stdin carries event data - hook_argv(root, hook), - input=json.dumps(payload), - cwd=root, - env=env, - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - timeout=hook.get("timeout", 30), - check=False, - ) - except subprocess.TimeoutExpired as exc: - captured = exc.stderr or "" - if isinstance(captured, bytes): - captured = captured.decode("utf-8", "replace") - print_hook_stderr(captured) - hook_failed(result, hook, f"timed out after {exc.timeout} seconds") - continue - except OSError as exc: - hook_failed(result, hook, f"could not start ({exc})") - continue - if completed.returncode == 2: - raise HookBlocked(completed.stderr.strip() or "Claude hook blocked this event") - print_hook_stderr(completed.stderr) - if completed.returncode: - hook_failed(result, hook, f"exited {completed.returncode}") - continue - output = completed.stdout.strip() - if not output: - continue - try: - update = json.loads(output) - except json.JSONDecodeError: - update = None - if not isinstance(update, dict): - if event not in PLAIN_CONTEXT_EVENTS: - print(output, file=sys.stderr) - continue - output = output.replace( - "scripts\\coord\\seat.ps1", - "scripts\\codex\\invoke.ps1 run scripts/coord/seat.ps1", - ) - update = {"hookSpecificOutput": {"hookEventName": event, "additionalContext": output}} - merge_output(result, update) + run_one_hook(root, payload, env, hook, result) + except HookBlocked: + raise + except (AttributeError, KeyError, TypeError, ValueError) as exc: + # A defect belongs to its own hook: it blocks only when that hook set onFailure to + # block. Any other hook's defect is reported and that hook skipped. + message = f"Codex bridge: skipped a hook with a defect: {type(exc).__name__}: {exc}" + if isinstance(hook, dict) and hook.get("onFailure") == "block": + raise HookBlocked(f"{message} (onFailure is block)") from exc + print(f"{message} (not blocking)", file=sys.stderr) + merge_output(result, {"systemMessage": f"{message} (not blocking)"}) def blocks_on_failure(group: dict) -> bool: @@ -378,10 +400,10 @@ def dispatch(root: Path, payload: dict, result: dict | None = None) -> dict: """Run the event's hooks, gathering their output into `result`, which a fault leaves intact.""" result = {} if result is None else result event = payload["hook_event_name"] - env = child_environment(root, payload.get("session_id", "")) config = read_settings(root) if config.get("disableAllHooks"): return result + env = child_environment(root, payload.get("session_id", "")) if event == "SessionStart": unknown = set(config.get("hooks", {})) - set(EVENTS) context = ( @@ -405,8 +427,9 @@ def dispatch(root: Path, payload: dict, result: dict | None = None) -> dict: except HookBlocked: raise except (AttributeError, KeyError, TypeError, ValueError, re.error) as exc: - # Each group is judged on its own: a defect is reported and that group skipped, so - # the groups after it still run. A hook in it that set onFailure to block has failed. + # A defect in the group itself, such as its matcher, keeps all of its hooks from + # running: it is reported and the group skipped, so the groups after it still run, + # unless a hook in it set onFailure to block, which has then failed. message = ( f"Codex bridge: skipped a hook group with a defect: {type(exc).__name__}: {exc}" ) diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index a3d8753a06..4293a4ca1d 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -20,6 +20,8 @@ if ($args.Count -gt 0 -and $args[0] -eq 'hook') { # becomes 2 here. Anything else, a missing .venv, a crash, or the 2 that Python and argparse # exit with, is no decision: reported, and a non-blocking 1 on every event. # docs/CODEX.md, "Who decides a block", states the rule. + # With this preference on, the bridge's block exit 10 would throw and read as no decision. + $PSNativeCommandUseErrorActionPreference = $false $code = 1 $why = '' try { diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 1481d783db..0fc841c75f 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -188,8 +188,15 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): ("& '{py}' -c 'import sys; sys.exit(2)'; Write-Output '{{}}'", "allow"), # A failed cmdlet as the last statement stays -Command's own non-blocking 1. ("Get-Item -LiteralPath 'no-such-item-b4'", "notice"), + # A grep-style stale exit 2, then a failed cmdlet: still the cmdlet's non-blocking 1. + ( + "& '{py}' -c 'import sys; sys.exit(2)'; Get-Item -LiteralPath 'no-such-item-b4'", + "notice", + ), + # The hook's own final exit 2 still blocks, after a statement that succeeded. + ("Write-Output 'x' | Out-Null; & '{py}' -c 'import sys; sys.exit(2)'", "block"), ], - ids=["native-exit-2", "stale-exit-2", "failed-cmdlet"], + ids=["native-exit-2", "stale-exit-2", "failed-cmdlet", "stale-2-then-cmdlet", "own-final-2"], ) def test_a_powershell_hook_keeps_exit_2_and_only_exit_2(bridge, tmp_path, command, outcome): hook = {"type": "command", "shell": "powershell", "command": command.format(py=sys.executable)} @@ -579,7 +586,21 @@ def test_a_fault_under_the_tracked_settings_is_reported_and_never_blocks( "event", ["PreToolUse", "PermissionRequest", "Stop", "SubagentStop", "SessionStart"] ) def test_a_fault_on_any_event_is_reported_and_never_blocks(bridge, tmp_path, capsys, event): - write_settings(tmp_path, {event: [DENY_GROUP], "disableAllHooks": True}) + write_settings(tmp_path, {event: [DENY_GROUP]}) + assert run(bridge, tmp_path, {"hook_event_name": event, "tool_name": "Bash"}, event) == 0 + reported(capsys) + + +@pytest.mark.parametrize("event", ["PreToolUse", "Stop", "SessionStart"]) +def test_disabled_hooks_report_nothing_even_without_a_session_id(bridge, tmp_path, capsys, event): + (tmp_path / ".claude").mkdir() + settings_file = tmp_path / ".claude/settings.json" + hooks = {event: [{"matcher": "", "hooks": [exits(2)]}]} + settings_file.write_text(json.dumps({"disableAllHooks": True, "hooks": hooks})) + assert run(bridge, tmp_path, {"hook_event_name": event, "tool_name": "Bash"}, event) == 0 + assert capsys.readouterr() == ("", "") + # The twin: with hooks enabled, the same payload is a reported fault. + settings_file.write_text(json.dumps({"hooks": hooks})) assert run(bridge, tmp_path, {"hook_event_name": event, "tool_name": "Bash"}, event) == 0 reported(capsys) @@ -734,6 +755,33 @@ def test_a_registered_command_passes_a_decision_and_maps_no_decision( assert "no decision, not blocking" in json.loads(completed.stdout)["systemMessage"] +@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") +@pytest.mark.parametrize(("stub", "expected"), [("10", 2), ("0", 0), ("1", 1)]) +def test_the_launcher_ignores_a_callers_native_error_preference(tmp_path, stub, expected): + """With $PSNativeCommandUseErrorActionPreference on, exit 10 would throw and read as 1.""" + root = tmp_path / "repo" + scripts = root / "scripts/codex" + scripts.mkdir(parents=True) + shutil.copy2(ROOT / "scripts/codex/invoke.ps1", scripts / "invoke.ps1") + (scripts / "bridge.py").write_text(_STUB_BRIDGE) + _link_python(root) + command = ( + "$PSNativeCommandUseErrorActionPreference = $true; $ErrorActionPreference = 'Stop'; " + f"& '{scripts / 'invoke.ps1'}' hook --event Stop" + ) + completed = subprocess.run( + ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command], + cwd=scripts, + env={**os.environ, "STUB_BRIDGE_EXIT": stub}, + input="{}", + text=True, + capture_output=True, + check=False, + timeout=60, + ) + assert completed.returncode == expected, (completed.stdout, completed.stderr) + + def bridge_block_exit(): spec = importlib.util.spec_from_file_location( "codex_bridge_c", ROOT / "scripts/codex/bridge.py" @@ -826,10 +874,25 @@ def test_a_defective_group_is_skipped_and_later_groups_still_run(bridge, tmp_pat defective = {"matcher": ".*", "hooks": [handler("{}")], **defect} write_settings(tmp_path, {"PreToolUse": [defective, DENY_GROUP]}) assert run(bridge, tmp_path, BASH_CALL, "PreToolUse") == 0 - result = reported(capsys, "skipped a hook group with a defect") + result = reported(capsys, "with a defect") assert result["hookSpecificOutput"] == DENIAL["hookSpecificOutput"] +def test_an_advisory_hook_defect_beside_an_on_failure_hook_does_not_block(bridge, tmp_path, capsys): + """The defect is the advisory hook's own; the onFailure guard in the same group passed.""" + guard = {**handler(json.dumps(DENIAL)), "onFailure": "block"} + write_settings(tmp_path, {"PreToolUse": [{"matcher": ".*", "hooks": [guard, UNSUPPORTED]}]}) + assert run(bridge, tmp_path, BASH_CALL, "PreToolUse") == 0 + result = reported(capsys, "skipped a hook with a defect") + assert result["hookSpecificOutput"] == DENIAL["hookSpecificOutput"] + + +def test_a_defect_in_the_on_failure_hook_itself_blocks(bridge, tmp_path): + advisory_then_guard = [handler("{}"), {**UNSUPPORTED, "onFailure": "block"}] + write_settings(tmp_path, {"PreToolUse": [{"matcher": ".*", "hooks": advisory_then_guard}]}) + assert run(bridge, tmp_path, BASH_CALL, "PreToolUse") == 2 + + @pytest.mark.parametrize( "defect", [{"matcher": "(["}, {"hooks": [{**UNSUPPORTED, "onFailure": "block"}]}], From e908ec85cc0d1583dcb3d75bb7bed12341ecb5c3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 18:00:33 -0600 Subject: [PATCH 09/51] A PowerShell hook blocks on its own final exit 2, and invoke.ps1 finds hook mode after options Three fixes for the Lander's hold on PR 3003. A command-only PowerShell hook now runs every statement but its last, resets $LASTEXITCODE, then runs the last one, so a failed last statement that set exit 2 blocks whatever $Error holds, and a stale 2 from an earlier native command never blocks. The $Error heuristic is gone. invoke.ps1 reads the subcommand the way bridge.py's argparse does, so `--session-id S hook` is hook mode and cannot return the raw block code 10. docs/CODEX.md no longer says "never to 0" against its own Windows PowerShell 5.1 note, or that the bridge exits 2. BACKLOG #5496 BACKLOG #5501 Proposed PR title: The Codex bridge follows Claude Code's hook exit contract, and its tests dispatch the tracked hook settings (BACKLOG #5496, #5501) Proposed banners: #5496 SHIPPED: only a hook's exit 2, or a failing hook with onFailure block, blocks; a non-2 exit, a timeout, an unstartable hook and every bridge fault are reported and non-blocking; item 1 (S34-14) is fixed. #5501 SHIPPED: tests/test_codex_bridge.py dispatches every hook in the tracked .claude/settings.json and pins exit 1 as non-blocking against a blocking exit 2. --- docs/CODEX.md | 17 ++++----- scripts/codex/bridge.py | 30 ++++++++++------ scripts/codex/invoke.ps1 | 11 +++++- tests/test_codex_bridge.py | 71 ++++++++++++++++++++++++++++++++++++-- 4 files changed, 107 insertions(+), 22 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 3cf1ff1bc9..f9086442f2 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -55,12 +55,13 @@ bridge exits 0 to proceed or 10 to block, and `invoke.ps1` turns 10 into 2. Any other outcome is no decision: another bridge exit, including the 2 that Python and argparse exit with, a missing `.venv`, or a checkout `git` cannot find. No decision is reported and maps to a non-blocking exit 1 on every event, never to -0 or 2. `invoke.ps1` ends its process with its code, and the command line passes -it on, because `pwsh -Command` would report an exit 2 as 1. This is tested with -PowerShell, `cmd` and `sh` as the outer shell. Codex's documentation does not -say which shell runs a hook command. When `pwsh` itself cannot start, the line -would exit 0 under Windows PowerShell 5.1, 9009 under `cmd` and 127 under `sh`; -this is reasoned, not measured. +2, and never to 0 once `pwsh` has started. `invoke.ps1` ends its process with +its code, and the command line passes it on, because `pwsh -Command` would +report an exit 2 as 1. This is tested with PowerShell, `cmd` and `sh` as the +outer shell. Codex's documentation does not say which shell runs a hook command. +When `pwsh` itself cannot start, nothing reports it: the line would exit 0 under +Windows PowerShell 5.1, which proceeds as if every hook passed, 9009 under `cmd` +and 127 under `sh`; this is reasoned, not measured. At origin/main before this change, no exit-2 block reached Codex: `pwsh -Command` reported the bridge's exit 2 as 1. A hook's JSON `permissionDecision` deny was @@ -69,8 +70,8 @@ unaffected. **A future guard that must block when it fails sets The bridge differs from Claude Code in at least three ways. It runs an event's hooks one after another, where Claude Code runs them in parallel. Exit 2 stops -the remaining hooks, and the bridge exits 2 on every event, including events -where Claude Code only shows the hook's stderr. Hook chains have a 90-second outer +the remaining hooks, and the bridge exits 10 on every event, which `invoke.ps1` +turns into 2, including events where Claude Code only shows the hook's stderr. Hook chains have a 90-second outer limit, so the timeouts of a long chain add up against it. Command-only hooks use the shell they name. With none, they use bash, as Claude diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 3ee7d1c92c..71e0fb3fb0 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -200,15 +200,25 @@ def git_bash() -> str | None: # -Command reports a native program's exit 2 as 1, which would turn a block into a non-blocking -# error. The head and tail keep -Command's own result, 0 or 1, except that a failed last statement -# exits 2 when it left exit code 2 behind and no cmdlet error was recorded. A failed cmdlet records -# one, so an earlier native exit 2 followed by a failed cmdlet stays a non-blocking 1. A cmdlet -# error anywhere before a final native exit 2 also makes it 1. The head keeps a native exit from -# recording an error where a PowerShell build defaults that preference on. -POWERSHELL_EXIT_HEAD = "$PSNativeCommandUseErrorActionPreference = $false; $Error.Clear()\n" -POWERSHELL_EXIT_TAIL = ( - "\nif (-not $?) { if ($LASTEXITCODE -eq 2 -and $Error.Count -eq 0) { exit 2 }; exit 1 }" -) +# error. This wrapper passes on the hook's own final exit 2: it runs every statement but the last, +# resets $LASTEXITCODE, then runs the last one. A failed last statement that set exit code 2 exits +# 2; any other failed last statement, a failed cmdlet or a native non-zero, exits 1. So a stale 2 +# from an earlier native command never blocks, and no recorded error hides a real final 2. The +# hook text travels base64-encoded, so no quoting in it can reach the wrapper. +POWERSHELL_WRAPPER = """$PSNativeCommandUseErrorActionPreference = $false +$__mfText = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('{b64}')) +$__mfParseErrors = $null +$__mfAst = [System.Management.Automation.Language.Parser]::ParseInput($__mfText, [ref]$null, [ref]$__mfParseErrors) +$__mfStatements = @(if ($__mfAst.EndBlock) {{ $__mfAst.EndBlock.Statements }}) +if ($__mfParseErrors.Count -or $__mfAst.BeginBlock -or $__mfAst.ProcessBlock -or $__mfStatements.Count -eq 0) {{ + . ([scriptblock]::Create($__mfText)) +}} else {{ + $__mfSplit = $__mfStatements[-1].Extent.StartOffset + . ([scriptblock]::Create($__mfText.Substring(0, $__mfSplit))) + $global:LASTEXITCODE = 0 + . ([scriptblock]::Create($__mfText.Substring($__mfSplit) + "`n" + 'if (-not $?) {{ if ($LASTEXITCODE -eq 2) {{ exit 2 }}; exit 1 }}')) +}} +""" def hook_argv(root: Path, hook: dict) -> list[str]: @@ -231,7 +241,7 @@ def hook_argv(root: Path, hook: dict) -> list[str]: shell = "powershell" if shell == "powershell": command = command.replace("${CLAUDE_PROJECT_DIR}", "${env:CLAUDE_PROJECT_DIR}") - script = POWERSHELL_EXIT_HEAD + command + POWERSHELL_EXIT_TAIL + script = POWERSHELL_WRAPPER.format(b64=base64.b64encode(command.encode()).decode()) return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script] raise ValueError(f"Unsupported Claude hook shell: {shell}") diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 4293a4ca1d..b2d71129f3 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -15,7 +15,16 @@ function Resolve-BridgePython { $python } -if ($args.Count -gt 0 -and $args[0] -eq 'hook') { +# The subcommand is the first argument that is not an option, as bridge.py's argparse reads it, so +# `--session-id S hook` is hook mode too and never returns the bridge's raw block code. +$mode = $null +for ($i = 0; $i -lt $args.Count; $i++) { + $word = [string]$args[$i] + if ($word -notlike '-*') { $mode = $word; break } + # argparse takes any unambiguous prefix of --session-id, and it consumes the next argument. + if ($word -notlike '*=*' -and $word.Length -ge 3 -and '--session-id'.StartsWith($word)) { $i++ } +} +if ($mode -eq 'hook') { # The bridge decides with exit 0, or with 10 (BLOCK_EXIT in bridge.py) for a block, which # becomes 2 here. Anything else, a missing .venv, a crash, or the 2 that Python and argparse # exit with, is no decision: reported, and a non-blocking 1 on every event. diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 0fc841c75f..9bf973af0a 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -4,6 +4,7 @@ from __future__ import annotations +import base64 import importlib.util import io import json @@ -195,8 +196,35 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): ), # The hook's own final exit 2 still blocks, after a statement that succeeded. ("Write-Output 'x' | Out-Null; & '{py}' -c 'import sys; sys.exit(2)'", "block"), + # A handled or silenced earlier error does not hide the hook's own final exit 2. + ( + "try {{ Get-Item -LiteralPath 'no-such-item-b4' -EA Stop }} catch {{}}; " + "& '{py}' -c 'import sys; sys.exit(2)'", + "block", + ), + ( + "$null = Get-Command no-such-command-b4 -ErrorAction SilentlyContinue; " + "& '{py}' -c 'import sys; sys.exit(2)'", + "block", + ), + # A stale exit 2, then a cmdlet failing under -ErrorAction Ignore, records no error and + # must still not block. + ( + "& '{py}' -c 'import sys; sys.exit(2)'; " + "Remove-Item -LiteralPath 'no-such-item-b4' -ErrorAction Ignore", + "notice", + ), + ], + ids=[ + "native-exit-2", + "stale-exit-2", + "failed-cmdlet", + "stale-2-then-cmdlet", + "own-final-2", + "handled-error-then-final-2", + "silenced-error-then-final-2", + "stale-2-then-ignored-cmdlet", ], - ids=["native-exit-2", "stale-exit-2", "failed-cmdlet", "stale-2-then-cmdlet", "own-final-2"], ) def test_a_powershell_hook_keeps_exit_2_and_only_exit_2(bridge, tmp_path, command, outcome): hook = {"type": "command", "shell": "powershell", "command": command.format(py=sys.executable)} @@ -213,8 +241,11 @@ def test_project_dir_is_substituted_in_every_form(bridge, tmp_path): structured = {"type": "command", "command": "${CLAUDE_PROJECT_DIR}/guard", "args": ["a"]} assert bridge.hook_argv(tmp_path, structured) == [f"{tmp_path}/guard", "a"] shell = {"type": "command", "shell": "powershell", "command": "'${CLAUDE_PROJECT_DIR}_x'"} - # Braced, so a following name character cannot join the variable name. - assert "'${env:CLAUDE_PROJECT_DIR}_x'" in bridge.hook_argv(tmp_path, shell)[-1] + # Braced, so a following name character cannot join the variable name. The hook text + # travels base64-encoded inside the wrapper. + encoded = re.search(r"FromBase64String\('([^']+)'\)", bridge.hook_argv(tmp_path, shell)[-1]) + assert encoded + assert base64.b64decode(encoded[1]).decode() == "'${env:CLAUDE_PROJECT_DIR}_x'" def test_each_event_matches_its_own_discriminator_field(bridge, tmp_path): @@ -903,3 +934,37 @@ def test_a_defective_group_whose_hook_sets_on_failure_block_blocks(bridge, tmp_p # PreToolUse, because Stop ignores a matcher and would never read the bad one. write_settings(tmp_path, {"PreToolUse": [group]}) assert run(bridge, tmp_path, BASH_CALL, "PreToolUse") == 2 + + +@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") +@pytest.mark.parametrize( + ("args", "expected"), + [ + (["hook", "--event", "Stop"], 2), + (["--session-id", "S", "hook", "--event", "Stop"], 2), + (["--session-id=S", "hook", "--event", "Stop"], 2), + (["--sess", "S", "hook", "--event", "Stop"], 2), + # The twin: a run whose target merely takes the word hook is not hook mode. + (["run", "scripts/codex/bridge.py", "hook"], 10), + ], + ids=["first", "after-session-id", "session-id-equals", "abbreviated-option", "run-mode"], +) +def test_the_launcher_finds_hook_mode_after_options(tmp_path, args, expected): + """A block reaches Codex as 2 wherever hook is the subcommand, never as the raw 10.""" + root = tmp_path / "repo" + scripts = root / "scripts/codex" + scripts.mkdir(parents=True) + shutil.copy2(ROOT / "scripts/codex/invoke.ps1", scripts / "invoke.ps1") + (scripts / "bridge.py").write_text(_STUB_BRIDGE) + _link_python(root) + completed = subprocess.run( + ["pwsh", "-NoProfile", "-NonInteractive", "-File", str(scripts / "invoke.ps1"), *args], + cwd=scripts, + env={**os.environ, "STUB_BRIDGE_EXIT": "10"}, + input="{}", + text=True, + capture_output=True, + check=False, + timeout=60, + ) + assert completed.returncode == expected, (completed.stdout, completed.stderr) From be82fffe7d110bd3d3ca180b2e10e7775823a5fd Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 18:19:57 -0600 Subject: [PATCH 10/51] A PowerShell hook keeps its own scope, and its exit 2 is judged from its last statement Review of the hold fixes found the statement-split wrapper weakened blocks: it emptied $input, reset $LASTEXITCODE and $? before the last statement, and scoped trap and return to the first part. The hook text now runs inline and unchanged, followed by a tail that acts only when the last statement failed: it passes on exit 2 unless that statement is a pipeline ending in a cmdlet or a missing command, which cannot have set the code. invoke.ps1 compares the --session-id prefix ordinally, and docs/CODEX.md scopes its no-decision rule to calls that name hook as the subcommand. BACKLOG #5496 BACKLOG #5501 Proposed PR title: The Codex bridge follows Claude Code's hook exit contract, and its tests dispatch the tracked hook settings (BACKLOG #5496, #5501) Proposed banners: #5496 SHIPPED: only a hook's exit 2, or a failing hook with onFailure block, blocks; a non-2 exit, a timeout, an unstartable hook and every bridge fault are reported and non-blocking; item 1 (S34-14) is fixed. #5501 SHIPPED: tests/test_codex_bridge.py dispatches every hook in the tracked .claude/settings.json and pins exit 1 as non-blocking against a blocking exit 2. --- docs/CODEX.md | 3 ++- scripts/codex/bridge.py | 43 ++++++++++++++++++++---------------- scripts/codex/invoke.ps1 | 2 +- tests/test_codex_bridge.py | 45 ++++++++++++++++++++++++++++++-------- 4 files changed, 63 insertions(+), 30 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index f9086442f2..e993f5a8a5 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -53,7 +53,8 @@ groups after it still run. A launcher that cannot run the bridge never blocks either. In hook mode the bridge exits 0 to proceed or 10 to block, and `invoke.ps1` turns 10 into 2. Any other outcome is no decision: another bridge exit, including the 2 that Python -and argparse exit with, a missing `.venv`, or a checkout `git` cannot find. No +and argparse exit with, a missing `.venv`, or a checkout `git` cannot find. On a +call that names `hook` as its subcommand, as every registered command does, no decision is reported and maps to a non-blocking exit 1 on every event, never to 2, and never to 0 once `pwsh` has started. `invoke.ps1` ends its process with its code, and the command line passes it on, because `pwsh -Command` would diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 71e0fb3fb0..7e5948a778 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -200,24 +200,28 @@ def git_bash() -> str | None: # -Command reports a native program's exit 2 as 1, which would turn a block into a non-blocking -# error. This wrapper passes on the hook's own final exit 2: it runs every statement but the last, -# resets $LASTEXITCODE, then runs the last one. A failed last statement that set exit code 2 exits -# 2; any other failed last statement, a failed cmdlet or a native non-zero, exits 1. So a stale 2 -# from an earlier native command never blocks, and no recorded error hides a real final 2. The -# hook text travels base64-encoded, so no quoting in it can reach the wrapper. -POWERSHELL_WRAPPER = """$PSNativeCommandUseErrorActionPreference = $false -$__mfText = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('{b64}')) -$__mfParseErrors = $null -$__mfAst = [System.Management.Automation.Language.Parser]::ParseInput($__mfText, [ref]$null, [ref]$__mfParseErrors) -$__mfStatements = @(if ($__mfAst.EndBlock) {{ $__mfAst.EndBlock.Statements }}) -if ($__mfParseErrors.Count -or $__mfAst.BeginBlock -or $__mfAst.ProcessBlock -or $__mfStatements.Count -eq 0) {{ - . ([scriptblock]::Create($__mfText)) -}} else {{ - $__mfSplit = $__mfStatements[-1].Extent.StartOffset - . ([scriptblock]::Create($__mfText.Substring(0, $__mfSplit))) - $global:LASTEXITCODE = 0 - . ([scriptblock]::Create($__mfText.Substring($__mfSplit) + "`n" + 'if (-not $?) {{ if ($LASTEXITCODE -eq 2) {{ exit 2 }}; exit 1 }}')) -}} +# error. This tail runs after the hook text, in the hook's own scope, so the hook keeps its $input, +# $LASTEXITCODE, $?, trap and return. Only when the last statement failed does it look further: it +# passes on exit code 2 unless that statement is a pipeline ending in a cmdlet or in a command that +# does not exist, which cannot have set the code, so a stale 2 from an earlier native command +# never blocks and no recorded error hides a real final 2. Any other failure exits 1. The tail +# reparses the hook text, carried base64-encoded so no quoting in it can reach the tail. +POWERSHELL_TAIL = """ +if (-not $?) { + $__mfCmdletLast = $false + $__mfAst = [System.Management.Automation.Language.Parser]::ParseInput([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('B64')), [ref]$null, [ref]$null) + $__mfLast = if ($__mfAst.EndBlock) { $__mfAst.EndBlock.Statements | Select-Object -Last 1 } + if ($__mfLast -is [System.Management.Automation.Language.PipelineAst]) { + $__mfCall = $__mfLast.PipelineElements | Select-Object -Last 1 + if ($__mfCall -is [System.Management.Automation.Language.CommandAst] -and $__mfCall.GetCommandName()) { + $__mfFound = Get-Command -Name $__mfCall.GetCommandName() -ErrorAction Ignore | Select-Object -First 1 + if ($__mfFound -is [System.Management.Automation.AliasInfo]) { $__mfFound = $__mfFound.ResolvedCommand } + $__mfCmdletLast = $null -eq $__mfFound -or $__mfFound.CommandType -eq 'Cmdlet' + } + } + if ((Get-Variable -Name LASTEXITCODE -Scope Global -ValueOnly -ErrorAction Ignore) -eq 2 -and -not $__mfCmdletLast) { exit 2 } + exit 1 +} """ @@ -241,7 +245,8 @@ def hook_argv(root: Path, hook: dict) -> list[str]: shell = "powershell" if shell == "powershell": command = command.replace("${CLAUDE_PROJECT_DIR}", "${env:CLAUDE_PROJECT_DIR}") - script = POWERSHELL_WRAPPER.format(b64=base64.b64encode(command.encode()).decode()) + encoded = base64.b64encode(command.encode()).decode() + script = command + POWERSHELL_TAIL.replace("B64", encoded) return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script] raise ValueError(f"Unsupported Claude hook shell: {shell}") diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index b2d71129f3..3ef505abbb 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -22,7 +22,7 @@ for ($i = 0; $i -lt $args.Count; $i++) { $word = [string]$args[$i] if ($word -notlike '-*') { $mode = $word; break } # argparse takes any unambiguous prefix of --session-id, and it consumes the next argument. - if ($word -notlike '*=*' -and $word.Length -ge 3 -and '--session-id'.StartsWith($word)) { $i++ } + if ($word -notlike '*=*' -and $word.Length -ge 3 -and '--session-id'.StartsWith($word, [StringComparison]::Ordinal)) { $i++ } } if ($mode -eq 'hook') { # The bridge decides with exit 0, or with 10 (BLOCK_EXIT in bridge.py) for a block, which diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 9bf973af0a..23757f5c3e 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -214,6 +214,14 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "Remove-Item -LiteralPath 'no-such-item-b4' -ErrorAction Ignore", "notice", ), + # The hook keeps its own $input, $LASTEXITCODE, $?, trap, param() and return. + ("$p = $input | ConvertFrom-Json; if ($p.tool_name -eq 'Bash') {{ exit 2 }}", "block"), + ("& '{py}' -c 'import sys; sys.exit(2)'; exit $LASTEXITCODE", "block"), + ("& '{py}' -c 'import sys; sys.exit(3)'; if (-not $?) {{ exit 2 }}", "block"), + ("trap {{ exit 2 }}; Write-Output 'x' | Out-Null; throw 'boom'", "block"), + ("param($x = 1)\n& '{py}' -c 'import sys; sys.exit(2)'", "block"), + ("if ($true) {{ & '{py}' -c 'import sys; sys.exit(2)' }}", "block"), + ("if ($true) {{ return }}; exit 2", "allow"), ], ids=[ "native-exit-2", @@ -224,6 +232,13 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "handled-error-then-final-2", "silenced-error-then-final-2", "stale-2-then-ignored-cmdlet", + "reads-input", + "exit-lastexitcode", + "checks-status", + "trap", + "param-block", + "compound-statement", + "early-return", ], ) def test_a_powershell_hook_keeps_exit_2_and_only_exit_2(bridge, tmp_path, command, outcome): @@ -938,18 +953,30 @@ def test_a_defective_group_whose_hook_sets_on_failure_block_blocks(bridge, tmp_p @pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") @pytest.mark.parametrize( - ("args", "expected"), + ("args", "stub", "expected"), [ - (["hook", "--event", "Stop"], 2), - (["--session-id", "S", "hook", "--event", "Stop"], 2), - (["--session-id=S", "hook", "--event", "Stop"], 2), - (["--sess", "S", "hook", "--event", "Stop"], 2), + (["hook", "--event", "Stop"], "10", 2), + (["--session-id", "S", "hook", "--event", "Stop"], "10", 2), + (["--session-id=S", "hook", "--event", "Stop"], "10", 2), + (["--sess", "S", "hook", "--event", "Stop"], "10", 2), + # No decision after options stays a non-blocking 1, never a raw 2. + (["--session-id", "S", "hook", "--event", "Stop"], "2", 1), + # The value of --session-id is not the subcommand, even when it reads hook. + (["--session-id", "hook", "run", "scripts/codex/bridge.py"], "10", 10), # The twin: a run whose target merely takes the word hook is not hook mode. - (["run", "scripts/codex/bridge.py", "hook"], 10), + (["run", "scripts/codex/bridge.py", "hook"], "10", 10), + ], + ids=[ + "first", + "after-session-id", + "session-id-equals", + "abbreviated-option", + "no-decision-after-options", + "session-id-named-hook", + "run-mode", ], - ids=["first", "after-session-id", "session-id-equals", "abbreviated-option", "run-mode"], ) -def test_the_launcher_finds_hook_mode_after_options(tmp_path, args, expected): +def test_the_launcher_finds_hook_mode_after_options(tmp_path, args, stub, expected): """A block reaches Codex as 2 wherever hook is the subcommand, never as the raw 10.""" root = tmp_path / "repo" scripts = root / "scripts/codex" @@ -960,7 +987,7 @@ def test_the_launcher_finds_hook_mode_after_options(tmp_path, args, expected): completed = subprocess.run( ["pwsh", "-NoProfile", "-NonInteractive", "-File", str(scripts / "invoke.ps1"), *args], cwd=scripts, - env={**os.environ, "STUB_BRIDGE_EXIT": "10"}, + env={**os.environ, "STUB_BRIDGE_EXIT": stub}, input="{}", text=True, capture_output=True, From 002c058d530fe4c29d445012f7171ac3ee6a6144 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 18:39:04 -0600 Subject: [PATCH 11/51] A command-only PowerShell hook runs as under Claude Code, and its exit code is taken unchanged The bridge no longer infers a PowerShell hook's exit code from its last statement. The hook runs under pwsh -Command with only the line that turns $PSNativeCommandUseErrorActionPreference off before it, and the process's own exit code is used: the hook blocks by exit 2, as under Claude Code, a native 2 passed on by exit blocks, and a stale or final native 2 is -Command's own 1. Every PowerShell hook in the tracked settings is a structured -File call whose script passes its code on by exit, so none relied on native exit passthrough. docs/CODEX.md says so. BACKLOG #5496 BACKLOG #5501 Proposed PR title: The Codex bridge follows Claude Code's hook exit contract, and its tests dispatch the tracked hook settings (BACKLOG #5496, #5501) Proposed banners: #5496 SHIPPED: only a hook's exit 2, or a failing hook with onFailure block, blocks; a non-2 exit, a timeout, an unstartable hook and every bridge fault are reported and non-blocking; item 1 (S34-14) is fixed. #5501 SHIPPED: tests/test_codex_bridge.py dispatches every hook in the tracked .claude/settings.json and pins exit 1 as non-blocking against a blocking exit 2. --- docs/CODEX.md | 6 ++- scripts/codex/bridge.py | 34 ++++----------- tests/test_codex_bridge.py | 84 +++++++++++++++----------------------- 3 files changed, 45 insertions(+), 79 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index e993f5a8a5..9ceaa02362 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -77,7 +77,11 @@ limit, so the timeouts of a long chain add up against it. Command-only hooks use the shell they name. With none, they use bash, as Claude Code does: Git Bash on Windows, else PowerShell there when Git Bash is missing. -Structured `command` and `args` avoid shell parsing. +Structured `command` and `args` avoid shell parsing. A command-only PowerShell +hook blocks by `exit 2`, as under Claude Code, whose documented PowerShell hook +blocks that way. The bridge runs it under `pwsh -Command` and takes the exit code +unchanged; `-Command` reports a final native program's exit 2 as 1, so a hook +that means to pass one on ends with `exit $LASTEXITCODE`. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 7e5948a778..728c635d36 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -199,30 +199,12 @@ def git_bash() -> str | None: return None -# -Command reports a native program's exit 2 as 1, which would turn a block into a non-blocking -# error. This tail runs after the hook text, in the hook's own scope, so the hook keeps its $input, -# $LASTEXITCODE, $?, trap and return. Only when the last statement failed does it look further: it -# passes on exit code 2 unless that statement is a pipeline ending in a cmdlet or in a command that -# does not exist, which cannot have set the code, so a stale 2 from an earlier native command -# never blocks and no recorded error hides a real final 2. Any other failure exits 1. The tail -# reparses the hook text, carried base64-encoded so no quoting in it can reach the tail. -POWERSHELL_TAIL = """ -if (-not $?) { - $__mfCmdletLast = $false - $__mfAst = [System.Management.Automation.Language.Parser]::ParseInput([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('B64')), [ref]$null, [ref]$null) - $__mfLast = if ($__mfAst.EndBlock) { $__mfAst.EndBlock.Statements | Select-Object -Last 1 } - if ($__mfLast -is [System.Management.Automation.Language.PipelineAst]) { - $__mfCall = $__mfLast.PipelineElements | Select-Object -Last 1 - if ($__mfCall -is [System.Management.Automation.Language.CommandAst] -and $__mfCall.GetCommandName()) { - $__mfFound = Get-Command -Name $__mfCall.GetCommandName() -ErrorAction Ignore | Select-Object -First 1 - if ($__mfFound -is [System.Management.Automation.AliasInfo]) { $__mfFound = $__mfFound.ResolvedCommand } - $__mfCmdletLast = $null -eq $__mfFound -or $__mfFound.CommandType -eq 'Cmdlet' - } - } - if ((Get-Variable -Name LASTEXITCODE -Scope Global -ValueOnly -ErrorAction Ignore) -eq 2 -and -not $__mfCmdletLast) { exit 2 } - exit 1 -} -""" +# A command-only PowerShell hook runs as Claude Code runs it, under pwsh -Command, and its exit code +# is taken unchanged: it blocks by `exit 2`. -Command reports a final native program's exit 2 as 1, +# as it would under Claude Code. The one line put before the hook keeps a native non-zero exit from +# throwing where a PowerShell build defaults that preference on; a hook that must open with param() +# or a named block cannot take it, and fails to parse. +POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false\n" def hook_argv(root: Path, hook: dict) -> list[str]: @@ -245,9 +227,7 @@ def hook_argv(root: Path, hook: dict) -> list[str]: shell = "powershell" if shell == "powershell": command = command.replace("${CLAUDE_PROJECT_DIR}", "${env:CLAUDE_PROJECT_DIR}") - encoded = base64.b64encode(command.encode()).decode() - script = command + POWERSHELL_TAIL.replace("B64", encoded) - return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script] + return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", POWERSHELL_HEAD + command] raise ValueError(f"Unsupported Claude hook shell: {shell}") diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 23757f5c3e..d399fa9972 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -4,7 +4,6 @@ from __future__ import annotations -import base64 import importlib.util import io import json @@ -183,65 +182,48 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): @pytest.mark.parametrize( ("command", "outcome"), [ - # pwsh -Command reports a native program's exit 2 as 1, which would fail open. - ("& '{py}' -c 'import sys; sys.exit(2)'", "block"), - # A stale exit 2 from an earlier statement must not block a hook that went on to succeed. + # A command-only PowerShell hook blocks by `exit 2`, as under Claude Code. + ("Write-Output 'x' | Out-Null; exit 2", "block"), + ("try {{ Get-Item -LiteralPath 'no-such-item-b4' -EA Stop }} catch {{}}; exit 2", "block"), + ("trap {{ exit 2 }}; throw 'boom'", "block"), + ("$p = $input | ConvertFrom-Json; if ($p.tool_name -eq 'Bash') {{ exit 2 }}", "block"), + # A native 2 passed on by `exit` blocks; one left as the last statement is -Command's + # own 1, as Claude Code would see it, so it does not block. + ("& '{py}' -c 'import sys; sys.exit(2)'; exit $LASTEXITCODE", "block"), + ("& '{py}' -c 'import sys; sys.exit(2)'", "exit-1"), + # A stale 2 never blocks. ("& '{py}' -c 'import sys; sys.exit(2)'; Write-Output '{{}}'", "allow"), - # A failed cmdlet as the last statement stays -Command's own non-blocking 1. - ("Get-Item -LiteralPath 'no-such-item-b4'", "notice"), - # A grep-style stale exit 2, then a failed cmdlet: still the cmdlet's non-blocking 1. ( "& '{py}' -c 'import sys; sys.exit(2)'; Get-Item -LiteralPath 'no-such-item-b4'", - "notice", - ), - # The hook's own final exit 2 still blocks, after a statement that succeeded. - ("Write-Output 'x' | Out-Null; & '{py}' -c 'import sys; sys.exit(2)'", "block"), - # A handled or silenced earlier error does not hide the hook's own final exit 2. - ( - "try {{ Get-Item -LiteralPath 'no-such-item-b4' -EA Stop }} catch {{}}; " - "& '{py}' -c 'import sys; sys.exit(2)'", - "block", + "exit-1", ), - ( - "$null = Get-Command no-such-command-b4 -ErrorAction SilentlyContinue; " - "& '{py}' -c 'import sys; sys.exit(2)'", - "block", - ), - # A stale exit 2, then a cmdlet failing under -ErrorAction Ignore, records no error and - # must still not block. ( "& '{py}' -c 'import sys; sys.exit(2)'; " "Remove-Item -LiteralPath 'no-such-item-b4' -ErrorAction Ignore", - "notice", + "exit-1", ), - # The hook keeps its own $input, $LASTEXITCODE, $?, trap, param() and return. - ("$p = $input | ConvertFrom-Json; if ($p.tool_name -eq 'Bash') {{ exit 2 }}", "block"), - ("& '{py}' -c 'import sys; sys.exit(2)'; exit $LASTEXITCODE", "block"), - ("& '{py}' -c 'import sys; sys.exit(3)'; if (-not $?) {{ exit 2 }}", "block"), - ("trap {{ exit 2 }}; Write-Output 'x' | Out-Null; throw 'boom'", "block"), - ("param($x = 1)\n& '{py}' -c 'import sys; sys.exit(2)'", "block"), - ("if ($true) {{ & '{py}' -c 'import sys; sys.exit(2)' }}", "block"), + ("& '{py}' -c 'import sys; sys.exit(2)'; $null = Get-Item -LiteralPath 'no-b4'", "exit-1"), + ("Get-Item -LiteralPath 'no-such-item-b4'", "exit-1"), ("if ($true) {{ return }}; exit 2", "allow"), ], ids=[ - "native-exit-2", - "stale-exit-2", - "failed-cmdlet", - "stale-2-then-cmdlet", - "own-final-2", - "handled-error-then-final-2", - "silenced-error-then-final-2", - "stale-2-then-ignored-cmdlet", + "explicit-exit-2", + "handled-error-then-exit-2", + "trap-exit-2", "reads-input", - "exit-lastexitcode", - "checks-status", - "trap", - "param-block", - "compound-statement", + "native-2-passed-on", + "native-2-last", + "stale-2-then-success", + "stale-2-then-failed-cmdlet", + "stale-2-then-ignored-cmdlet", + "stale-2-then-assignment", + "failed-cmdlet", "early-return", ], ) -def test_a_powershell_hook_keeps_exit_2_and_only_exit_2(bridge, tmp_path, command, outcome): +def test_a_powershell_hook_takes_the_process_exit_code_unchanged( + bridge, tmp_path, command, outcome +): hook = {"type": "command", "shell": "powershell", "command": command.format(py=sys.executable)} settings(tmp_path, [hook]) if outcome == "block": @@ -249,18 +231,18 @@ def test_a_powershell_hook_keeps_exit_2_and_only_exit_2(bridge, tmp_path, comman bridge.dispatch(tmp_path, BASH_CALL) return result = bridge.dispatch(tmp_path, BASH_CALL) - assert ("exited 1:" in result.get("systemMessage", "")) == (outcome == "notice"), result + if outcome == "allow": + assert result == {}, result + else: + assert "hook exited 1: " in result["systemMessage"], result def test_project_dir_is_substituted_in_every_form(bridge, tmp_path): structured = {"type": "command", "command": "${CLAUDE_PROJECT_DIR}/guard", "args": ["a"]} assert bridge.hook_argv(tmp_path, structured) == [f"{tmp_path}/guard", "a"] shell = {"type": "command", "shell": "powershell", "command": "'${CLAUDE_PROJECT_DIR}_x'"} - # Braced, so a following name character cannot join the variable name. The hook text - # travels base64-encoded inside the wrapper. - encoded = re.search(r"FromBase64String\('([^']+)'\)", bridge.hook_argv(tmp_path, shell)[-1]) - assert encoded - assert base64.b64decode(encoded[1]).decode() == "'${env:CLAUDE_PROJECT_DIR}_x'" + # Braced, so a following name character cannot join the variable name. + assert bridge.hook_argv(tmp_path, shell)[-1].endswith("'${env:CLAUDE_PROJECT_DIR}_x'") def test_each_event_matches_its_own_discriminator_field(bridge, tmp_path): From bd2e9536dac45ef3ec4eb483d5ca5ff698bdc40f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 18:51:14 -0600 Subject: [PATCH 12/51] The Codex docs state what the PowerShell head line and a help flag do Review corrections to control statements only. The bridge.py comment and docs/CODEX.md no longer say Claude Code runs a PowerShell hook under pwsh -Command, which its hooks reference does not document; they say the bridge does, and that the line it puts before the hook makes a hook opening with param(), using or a named block fail to parse. The no-decision rule names the help flag that exits 0, and the onFailure advice says it holds only once the bridge runs. BACKLOG #5496 BACKLOG #5501 Proposed PR title: The Codex bridge follows Claude Code's hook exit contract, and its tests dispatch the tracked hook settings (BACKLOG #5496, #5501) Proposed banners: #5496 SHIPPED: only a hook's exit 2, or a failing hook with onFailure block, blocks; a non-2 exit, a timeout, an unstartable hook and every bridge fault are reported and non-blocking; item 1 (S34-14) is fixed. #5501 SHIPPED: tests/test_codex_bridge.py dispatches every hook in the tracked .claude/settings.json and pins exit 1 as non-blocking against a blocking exit 2. --- docs/CODEX.md | 22 ++++++++++++++-------- scripts/codex/bridge.py | 12 +++++++----- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 9ceaa02362..a69af17c8a 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -56,7 +56,8 @@ other outcome is no decision: another bridge exit, including the 2 that Python and argparse exit with, a missing `.venv`, or a checkout `git` cannot find. On a call that names `hook` as its subcommand, as every registered command does, no decision is reported and maps to a non-blocking exit 1 on every event, never to -2, and never to 0 once `pwsh` has started. `invoke.ps1` ends its process with +2, and never to 0 once `pwsh` has started, except that a help flag prints usage +and exits 0. `invoke.ps1` ends its process with its code, and the command line passes it on, because `pwsh -Command` would report an exit 2 as 1. This is tested with PowerShell, `cmd` and `sh` as the outer shell. Codex's documentation does not say which shell runs a hook command. @@ -67,21 +68,26 @@ and 127 under `sh`; this is reasoned, not measured. At origin/main before this change, no exit-2 block reached Codex: `pwsh -Command` reported the bridge's exit 2 as 1. A hook's JSON `permissionDecision` deny was unaffected. **A future guard that must block when it fails sets -`"onFailure": "block"`.** +`"onFailure": "block"`.** That holds only once the bridge runs and reads the +settings: a launcher with no decision, or a bridge fault, never blocks. The bridge differs from Claude Code in at least three ways. It runs an event's hooks one after another, where Claude Code runs them in parallel. Exit 2 stops the remaining hooks, and the bridge exits 10 on every event, which `invoke.ps1` -turns into 2, including events where Claude Code only shows the hook's stderr. Hook chains have a 90-second outer -limit, so the timeouts of a long chain add up against it. +turns into 2, including events where Claude Code only shows the hook's stderr. +Hook chains have a 90-second outer limit, so the timeouts of a long chain add up +against it. Command-only hooks use the shell they name. With none, they use bash, as Claude Code does: Git Bash on Windows, else PowerShell there when Git Bash is missing. Structured `command` and `args` avoid shell parsing. A command-only PowerShell -hook blocks by `exit 2`, as under Claude Code, whose documented PowerShell hook -blocks that way. The bridge runs it under `pwsh -Command` and takes the exit code -unchanged; `-Command` reports a final native program's exit 2 as 1, so a hook -that means to pass one on ends with `exit $LASTEXITCODE`. +hook blocks by `exit 2`, as under Claude Code, whose hooks reference blocks a +PowerShell hook with an explicit `exit 2`. The bridge runs it under +`pwsh -Command` and takes the exit code unchanged, so a final native program's +exit 2 does not block unless the hook ends with `exit $LASTEXITCODE`. The bridge +puts one line before the hook, turning `$PSNativeCommandUseErrorActionPreference` +off, so a hook that must open with `param()`, a `using` statement or a named +block fails to parse and cannot block. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 728c635d36..608c745d03 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -199,11 +199,13 @@ def git_bash() -> str | None: return None -# A command-only PowerShell hook runs as Claude Code runs it, under pwsh -Command, and its exit code -# is taken unchanged: it blocks by `exit 2`. -Command reports a final native program's exit 2 as 1, -# as it would under Claude Code. The one line put before the hook keeps a native non-zero exit from -# throwing where a PowerShell build defaults that preference on; a hook that must open with param() -# or a named block cannot take it, and fails to parse. +# A command-only PowerShell hook runs under pwsh -Command and its exit code is taken unchanged: it +# blocks by `exit 2`, the way Claude Code's hooks reference blocks a PowerShell hook. That reference +# does not say which flags Claude Code passes, or how a native exit code propagates; under -Command +# a final native program's exit 2 is reported as 1. The one line put before the hook keeps a +# native non-zero exit from throwing where a PowerShell build defaults that preference on. A hook +# that must open with at least param(), a using statement or a named block cannot take that line, +# fails to parse, and so cannot block. POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false\n" From 8b0f40c13c0ef176326e56263498ea50e77a2b2b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 19:46:51 -0600 Subject: [PATCH 13/51] Codex bridge: a PowerShell hook's guard exit 2 blocks again; four false statements corrected A command-only PowerShell hook runs under pwsh -Command, which reports a 2 from a called or dot-sourced guard script, or a native program, as 1 when it ends the hook; that exit went to hook_failed and did not block. The bridge now appends, on its own line, `if (-not $? -and $LASTEXITCODE -eq 2) { exit 2 }`. Measured on pwsh 7.6.10, it lifts only a 1 to a 2; a stale 2 still allows after a last statement that succeeds, and now blocks after one that fails. Also corrects, in docs/CODEX.md, a bridge.py comment and a test comment: a param()/using/named-block hook fails on every call with exit 1 (it is not "cannot block", and a named block fails at run time, not at parse); the "as Claude Code would see it" phrase is dropped; and the onFailure precondition now names a payload with no session id as a fault. Repair of the hold on PR 3003 at bd2e9536da. BACKLOG #5496. --- docs/CODEX.md | 14 ++++++++----- scripts/codex/bridge.py | 20 +++++++++++-------- tests/test_codex_bridge.py | 41 ++++++++++++++++++++++++++++---------- 3 files changed, 51 insertions(+), 24 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index a69af17c8a..4cc9160e79 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -68,8 +68,9 @@ and 127 under `sh`; this is reasoned, not measured. At origin/main before this change, no exit-2 block reached Codex: `pwsh -Command` reported the bridge's exit 2 as 1. A hook's JSON `permissionDecision` deny was unaffected. **A future guard that must block when it fails sets -`"onFailure": "block"`.** That holds only once the bridge runs and reads the -settings: a launcher with no decision, or a bridge fault, never blocks. +`"onFailure": "block"`.** That holds only for a hook the bridge reaches: a +launcher with no decision, or a bridge fault, such as a payload with no session +id, never blocks. The bridge differs from Claude Code in at least three ways. It runs an event's hooks one after another, where Claude Code runs them in parallel. Exit 2 stops @@ -83,11 +84,14 @@ Code does: Git Bash on Windows, else PowerShell there when Git Bash is missing. Structured `command` and `args` avoid shell parsing. A command-only PowerShell hook blocks by `exit 2`, as under Claude Code, whose hooks reference blocks a PowerShell hook with an explicit `exit 2`. The bridge runs it under -`pwsh -Command` and takes the exit code unchanged, so a final native program's -exit 2 does not block unless the hook ends with `exit $LASTEXITCODE`. The bridge +`pwsh -Command`. That reports as 1 a 2 from a native program, or from a guard +script the hook calls or dot-sources, when it ends the hook. So the bridge puts +one line after the hook: when the last statement failed and `$LASTEXITCODE` is 2, +it exits 2. That line also blocks a hook whose last statement fails while an +earlier command's 2 is still in `$LASTEXITCODE`. The bridge puts one line before the hook, turning `$PSNativeCommandUseErrorActionPreference` off, so a hook that must open with `param()`, a `using` statement or a named -block fails to parse and cannot block. +block fails on every call with exit 1. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 608c745d03..99fc4c3696 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -199,14 +199,17 @@ def git_bash() -> str | None: return None -# A command-only PowerShell hook runs under pwsh -Command and its exit code is taken unchanged: it -# blocks by `exit 2`, the way Claude Code's hooks reference blocks a PowerShell hook. That reference -# does not say which flags Claude Code passes, or how a native exit code propagates; under -Command -# a final native program's exit 2 is reported as 1. The one line put before the hook keeps a -# native non-zero exit from throwing where a PowerShell build defaults that preference on. A hook -# that must open with at least param(), a using statement or a named block cannot take that line, -# fails to parse, and so cannot block. +# A command-only PowerShell hook runs under pwsh -Command and blocks by `exit 2`, the way Claude +# Code's hooks reference blocks a PowerShell hook. That reference does not say which flags Claude +# Code passes, or how a native exit code propagates. Under -Command, a 2 from a guard script the +# hook calls or dot-sources, or from a native program, is reported as 1 when it ends the hook, so +# the line put after the hook exits 2 when the last statement failed with $LASTEXITCODE at 2, +# whichever command left that 2. The tail goes on its own line so a trailing comment cannot +# swallow it. The one line put before the hook keeps a native non-zero exit from throwing where a +# PowerShell build defaults that preference on. A hook that must open with at least param(), a +# using statement or a named block cannot take that line, and fails on every call with exit 1. POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false\n" +POWERSHELL_TAIL = "\nif (-not $? -and $LASTEXITCODE -eq 2) { exit 2 }" def hook_argv(root: Path, hook: dict) -> list[str]: @@ -229,7 +232,8 @@ def hook_argv(root: Path, hook: dict) -> list[str]: shell = "powershell" if shell == "powershell": command = command.replace("${CLAUDE_PROJECT_DIR}", "${env:CLAUDE_PROJECT_DIR}") - return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", POWERSHELL_HEAD + command] + script = POWERSHELL_HEAD + command + POWERSHELL_TAIL + return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script] raise ValueError(f"Unsupported Claude hook shell: {shell}") diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index d399fa9972..b0a3249a04 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -187,22 +187,24 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): ("try {{ Get-Item -LiteralPath 'no-such-item-b4' -EA Stop }} catch {{}}; exit 2", "block"), ("trap {{ exit 2 }}; throw 'boom'", "block"), ("$p = $input | ConvertFrom-Json; if ($p.tool_name -eq 'Bash') {{ exit 2 }}", "block"), - # A native 2 passed on by `exit` blocks; one left as the last statement is -Command's - # own 1, as Claude Code would see it, so it does not block. + # A native 2 blocks, passed on by `exit` or left as the last statement, which -Command + # alone reports as 1. ("& '{py}' -c 'import sys; sys.exit(2)'; exit $LASTEXITCODE", "block"), - ("& '{py}' -c 'import sys; sys.exit(2)'", "exit-1"), - # A stale 2 never blocks. + ("& '{py}' -c 'import sys; sys.exit(2)'", "block"), + ("& '{py}' -c 'import sys; sys.exit(3)'", "exit-1"), + # A stale 2 does not block after a last statement that succeeds, and does after one + # that fails. ("& '{py}' -c 'import sys; sys.exit(2)'; Write-Output '{{}}'", "allow"), ( "& '{py}' -c 'import sys; sys.exit(2)'; Get-Item -LiteralPath 'no-such-item-b4'", - "exit-1", + "block", ), ( "& '{py}' -c 'import sys; sys.exit(2)'; " "Remove-Item -LiteralPath 'no-such-item-b4' -ErrorAction Ignore", - "exit-1", + "block", ), - ("& '{py}' -c 'import sys; sys.exit(2)'; $null = Get-Item -LiteralPath 'no-b4'", "exit-1"), + ("& '{py}' -c 'import sys; sys.exit(2)'; $null = Get-Item -LiteralPath 'no-b4'", "block"), ("Get-Item -LiteralPath 'no-such-item-b4'", "exit-1"), ("if ($true) {{ return }}; exit 2", "allow"), ], @@ -213,6 +215,7 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "reads-input", "native-2-passed-on", "native-2-last", + "native-3-last", "stale-2-then-success", "stale-2-then-failed-cmdlet", "stale-2-then-ignored-cmdlet", @@ -221,9 +224,7 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "early-return", ], ) -def test_a_powershell_hook_takes_the_process_exit_code_unchanged( - bridge, tmp_path, command, outcome -): +def test_a_powershell_hook_blocks_on_a_2_that_ends_it(bridge, tmp_path, command, outcome): hook = {"type": "command", "shell": "powershell", "command": command.format(py=sys.executable)} settings(tmp_path, [hook]) if outcome == "block": @@ -237,12 +238,30 @@ def test_a_powershell_hook_takes_the_process_exit_code_unchanged( assert "hook exited 1: " in result["systemMessage"], result +@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") +@pytest.mark.parametrize( + "command", + ["& ./guard.ps1", ". ./guard.ps1", "& ./guard.ps1 # the guard decides"], + ids=["called", "dot-sourced", "called-before-a-comment"], +) +def test_a_powershell_hook_blocks_when_a_guard_it_runs_exits_2(bridge, tmp_path, command): + """-Command alone reports a guard script's `exit 2` as 1, which would not block.""" + (tmp_path / "guard.ps1").write_text("exit 2\n", encoding="utf-8") + settings(tmp_path, [{"type": "command", "shell": "powershell", "command": command}]) + with pytest.raises(bridge.HookBlocked): + bridge.dispatch(tmp_path, BASH_CALL) + # A later statement that succeeds is the hook's own outcome. + settings(tmp_path, [{"type": "command", "shell": "powershell", "command": command + "\n$null"}]) + assert bridge.dispatch(tmp_path, BASH_CALL) == {} + + def test_project_dir_is_substituted_in_every_form(bridge, tmp_path): structured = {"type": "command", "command": "${CLAUDE_PROJECT_DIR}/guard", "args": ["a"]} assert bridge.hook_argv(tmp_path, structured) == [f"{tmp_path}/guard", "a"] shell = {"type": "command", "shell": "powershell", "command": "'${CLAUDE_PROJECT_DIR}_x'"} # Braced, so a following name character cannot join the variable name. - assert bridge.hook_argv(tmp_path, shell)[-1].endswith("'${env:CLAUDE_PROJECT_DIR}_x'") + command = bridge.hook_argv(tmp_path, shell)[-1].removesuffix(bridge.POWERSHELL_TAIL) + assert command.endswith("'${env:CLAUDE_PROJECT_DIR}_x'") def test_each_event_matches_its_own_discriminator_field(bridge, tmp_path): From 8dd26aa5e02a6929e6808b13d1cd9345ea8428e9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 20:09:43 -0600 Subject: [PATCH 14/51] Codex bridge: the PowerShell tail survives strict mode and a trailing continuation Review round-b0d3f286 of the guard-exit fix found three defects in it. The tail read $LASTEXITCODE directly, which faults under Set-StrictMode when no native code is set, so a hook's trap turned that fault into a block; it now reads it with Get-Variable and, when the last statement failed, exits 1 itself as -Command would. It sat one newline after the hook, so a trailing backtick joined it to the hook's last command; a blank line now ends the hook first. The doc and comment said a guard's 2 is lifted however the hook calls it; they now say the hook's last statement must run it, and name the function, script block, return and break shapes the tail does not reach. BACKLOG #5496. --- docs/CODEX.md | 10 ++++++---- scripts/codex/bridge.py | 20 ++++++++++++-------- tests/test_codex_bridge.py | 10 ++++++++++ 3 files changed, 28 insertions(+), 12 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 4cc9160e79..956aa366a6 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -85,10 +85,12 @@ Structured `command` and `args` avoid shell parsing. A command-only PowerShell hook blocks by `exit 2`, as under Claude Code, whose hooks reference blocks a PowerShell hook with an explicit `exit 2`. The bridge runs it under `pwsh -Command`. That reports as 1 a 2 from a native program, or from a guard -script the hook calls or dot-sources, when it ends the hook. So the bridge puts -one line after the hook: when the last statement failed and `$LASTEXITCODE` is 2, -it exits 2. That line also blocks a hook whose last statement fails while an -earlier command's 2 is still in `$LASTEXITCODE`. The bridge +script the hook calls or dot-sources, when the hook's last statement runs it. So +the bridge puts a statement after the hook: when the last statement failed and +`$LASTEXITCODE` is 2, it exits 2. That also blocks a hook whose last statement +fails while an earlier command's 2 is still in `$LASTEXITCODE`. It does not reach +a guard called inside a function or script block, or followed by `return` or +`break`. The bridge puts one line before the hook, turning `$PSNativeCommandUseErrorActionPreference` off, so a hook that must open with `param()`, a `using` statement or a named block fails on every call with exit 1. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 99fc4c3696..7bddea532d 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -201,15 +201,19 @@ def git_bash() -> str | None: # A command-only PowerShell hook runs under pwsh -Command and blocks by `exit 2`, the way Claude # Code's hooks reference blocks a PowerShell hook. That reference does not say which flags Claude -# Code passes, or how a native exit code propagates. Under -Command, a 2 from a guard script the -# hook calls or dot-sources, or from a native program, is reported as 1 when it ends the hook, so -# the line put after the hook exits 2 when the last statement failed with $LASTEXITCODE at 2, -# whichever command left that 2. The tail goes on its own line so a trailing comment cannot -# swallow it. The one line put before the hook keeps a native non-zero exit from throwing where a -# PowerShell build defaults that preference on. A hook that must open with at least param(), a -# using statement or a named block cannot take that line, and fails on every call with exit 1. +# Code passes, or how a native exit code propagates. Under -Command, a 2 from a native program or a +# guard script that the hook's last statement runs is reported as 1, so the tail put after the hook +# exits 2 when the last statement failed with $LASTEXITCODE at 2, whichever command left that 2, +# and otherwise exits 1 when it failed, as -Command would. A blank line first ends a trailing +# comment or line continuation, and Get-Variable keeps strict mode from faulting on an unset code. +# The one line put before the hook keeps a native non-zero exit from throwing where a PowerShell +# build defaults that preference on. A hook that must open with at least param(), a using +# statement or a named block cannot take that line, and fails on every call with exit 1. POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false\n" -POWERSHELL_TAIL = "\nif (-not $? -and $LASTEXITCODE -eq 2) { exit 2 }" +POWERSHELL_TAIL = ( + "\n\nif (-not $?) { if ((Get-Variable -Name LASTEXITCODE -Scope Global -ValueOnly" + " -ErrorAction Ignore) -eq 2) { exit 2 }; exit 1 }" +) def hook_argv(root: Path, hook: dict) -> list[str]: diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index b0a3249a04..203c89d155 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -206,6 +206,14 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): ), ("& '{py}' -c 'import sys; sys.exit(2)'; $null = Get-Item -LiteralPath 'no-b4'", "block"), ("Get-Item -LiteralPath 'no-such-item-b4'", "exit-1"), + # Under strict mode, with no native code set, the bridge's own statement must not fault. + ( + "Set-StrictMode -Version Latest; trap {{ exit 2 }}; " + "Remove-Item -LiteralPath 'no-such-item-b4' -ErrorAction SilentlyContinue", + "exit-1", + ), + # A line continuation ending the hook must not swallow the bridge's own statement. + ("& '{py}' -c 'import sys; sys.exit(2)' `", "block"), ("if ($true) {{ return }}; exit 2", "allow"), ], ids=[ @@ -221,6 +229,8 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "stale-2-then-ignored-cmdlet", "stale-2-then-assignment", "failed-cmdlet", + "strict-mode-failed-cmdlet", + "trailing-continuation", "early-return", ], ) From e57e2dd097e1159614847d2fc4056185afa076cd Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 20:32:10 -0600 Subject: [PATCH 15/51] Codex bridge: state the param() and stale-2 behaviour of a PowerShell hook plainly The doc and the bridge.py comment said a hook opening with param(), a using statement or a named block fails on every call with exit 1. A non-empty param(...) runs after the head line, with its default applied, and exits as its body does. Both now name only what was measured: an empty param() fails to parse, so the hook exits 1 on every call and, under onFailure: block, blocks every call. Two test rows pin both shapes. Both also now say plainly that a hook whose last statement fails while $LASTEXITCODE is 2, including a 2 left by an earlier native command, blocks. BACKLOG #5496. --- docs/CODEX.md | 9 +++++---- scripts/codex/bridge.py | 9 +++++---- tests/test_codex_bridge.py | 9 +++++++++ 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 956aa366a6..665c964c06 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -87,13 +87,14 @@ PowerShell hook with an explicit `exit 2`. The bridge runs it under `pwsh -Command`. That reports as 1 a 2 from a native program, or from a guard script the hook calls or dot-sources, when the hook's last statement runs it. So the bridge puts a statement after the hook: when the last statement failed and -`$LASTEXITCODE` is 2, it exits 2. That also blocks a hook whose last statement -fails while an earlier command's 2 is still in `$LASTEXITCODE`. It does not reach +`$LASTEXITCODE` is 2, it exits 2. So a hook whose last statement fails while +`$LASTEXITCODE` is 2, including a 2 left by an earlier native command, blocks. +It does not reach a guard called inside a function or script block, or followed by `return` or `break`. The bridge puts one line before the hook, turning `$PSNativeCommandUseErrorActionPreference` -off, so a hook that must open with `param()`, a `using` statement or a named -block fails on every call with exit 1. +off. A hook that opens with an empty `param()` then fails to parse, so it exits +1 on every call, and under `"onFailure": "block"` it blocks every call. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 7bddea532d..8a5e8011b2 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -203,12 +203,13 @@ def git_bash() -> str | None: # Code's hooks reference blocks a PowerShell hook. That reference does not say which flags Claude # Code passes, or how a native exit code propagates. Under -Command, a 2 from a native program or a # guard script that the hook's last statement runs is reported as 1, so the tail put after the hook -# exits 2 when the last statement failed with $LASTEXITCODE at 2, whichever command left that 2, -# and otherwise exits 1 when it failed, as -Command would. A blank line first ends a trailing +# exits 2 when the last statement failed with $LASTEXITCODE at 2. So a hook whose last statement +# fails while $LASTEXITCODE is 2, including a 2 left by an earlier native command, blocks. +# Otherwise the tail exits 1 when the last statement failed, as -Command would. A blank line first ends a trailing # comment or line continuation, and Get-Variable keeps strict mode from faulting on an unset code. # The one line put before the hook keeps a native non-zero exit from throwing where a PowerShell -# build defaults that preference on. A hook that must open with at least param(), a using -# statement or a named block cannot take that line, and fails on every call with exit 1. +# build defaults that preference on. A hook that opens with an empty param() then fails to parse, +# so it exits 1 on every call, and under onFailure: block it blocks every call. POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false\n" POWERSHELL_TAIL = ( "\n\nif (-not $?) { if ((Get-Variable -Name LASTEXITCODE -Scope Global -ValueOnly" diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 203c89d155..0ff8e8cb0d 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -215,6 +215,13 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): # A line continuation ending the hook must not swallow the bridge's own statement. ("& '{py}' -c 'import sys; sys.exit(2)' `", "block"), ("if ($true) {{ return }}; exit 2", "allow"), + # After the bridge's head line, an empty param() fails to parse, but a non-empty one + # runs, with its default applied. + ("param()\nexit 2", "exit-1"), + ( + "param([string]$Mode = 'enforce')\nif ($Mode -eq 'enforce') {{ exit 0 }}; exit 2", + "allow", + ), ], ids=[ "explicit-exit-2", @@ -232,6 +239,8 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "strict-mode-failed-cmdlet", "trailing-continuation", "early-return", + "empty-param", + "non-empty-param", ], ) def test_a_powershell_hook_blocks_on_a_2_that_ends_it(bridge, tmp_path, command, outcome): From 521ae09b80b220fa9952c3321c55261f71d912e3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 20:56:29 -0600 Subject: [PATCH 16/51] Codex bridge: a dangling operator cannot absorb the PowerShell tail; the tail's test is stated as $? The tail opened with a blank line, so a hook ending in a dangling `=`, `+=` or `||` took the tail in as its operand and exited 0, where it exited 1 at bd2e9536da. The tail now opens with a lone `;` on its own line; measured on pwsh 7.6.10, those endings and a trailing `|` or `&&` are parse errors with exit 1, and a trailing comment or backtick behaves as before. The doc and the bridge.py comment now say what the tail tests: the hook ends with $? false while $LASTEXITCODE is 2, including a 2 left by an earlier native command, and a last statement that does not reset $?, such as an untaken if, keeps it false. "Any other hook failure is a non-blocking error" now names that exception. The non-empty param() test row's comment now says what was measured. Test rows pin the dangling endings and the untaken if. BACKLOG #5496. --- docs/CODEX.md | 13 +++++++------ scripts/codex/bridge.py | 20 +++++++++++--------- tests/test_codex_bridge.py | 17 ++++++++++++++--- 3 files changed, 32 insertions(+), 18 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 665c964c06..4a68c6bd03 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -34,8 +34,9 @@ that sets `"onFailure": "block"` when it fails: a non-zero exit, a timeout, a command that cannot start, a defect of its own such as an unsupported handler type or shell, or a defect in its group, such as a matcher that is not a valid regex, that keeps it from running. Any other hook failure is a -non-blocking error. The bridge reports it on stderr and as a `systemMessage`, -naming the hook, ignores that hook's output, and runs the remaining hooks. A JSON +non-blocking error, except a command-only PowerShell hook that ends with a 2 in +`$LASTEXITCODE`, as described below. The bridge reports it on stderr and as a +`systemMessage`, naming the hook, ignores that hook's output, and runs the remaining hooks. A JSON `permissionDecision` deny from a hook is a decision, not a failure, and is passed on as before. @@ -86,10 +87,10 @@ hook blocks by `exit 2`, as under Claude Code, whose hooks reference blocks a PowerShell hook with an explicit `exit 2`. The bridge runs it under `pwsh -Command`. That reports as 1 a 2 from a native program, or from a guard script the hook calls or dot-sources, when the hook's last statement runs it. So -the bridge puts a statement after the hook: when the last statement failed and -`$LASTEXITCODE` is 2, it exits 2. So a hook whose last statement fails while -`$LASTEXITCODE` is 2, including a 2 left by an earlier native command, blocks. -It does not reach +the bridge puts a statement after the hook: a hook that ends with `$?` false +while `$LASTEXITCODE` is 2, including a 2 left by an earlier native command, +exits 2 and blocks. A last statement that does not reset `$?`, such as +`if ($false) { ... }`, keeps it false. It does not reach a guard called inside a function or script block, or followed by `return` or `break`. The bridge puts one line before the hook, turning `$PSNativeCommandUseErrorActionPreference` diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 8a5e8011b2..3379e54fe0 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -202,17 +202,19 @@ def git_bash() -> str | None: # A command-only PowerShell hook runs under pwsh -Command and blocks by `exit 2`, the way Claude # Code's hooks reference blocks a PowerShell hook. That reference does not say which flags Claude # Code passes, or how a native exit code propagates. Under -Command, a 2 from a native program or a -# guard script that the hook's last statement runs is reported as 1, so the tail put after the hook -# exits 2 when the last statement failed with $LASTEXITCODE at 2. So a hook whose last statement -# fails while $LASTEXITCODE is 2, including a 2 left by an earlier native command, blocks. -# Otherwise the tail exits 1 when the last statement failed, as -Command would. A blank line first ends a trailing -# comment or line continuation, and Get-Variable keeps strict mode from faulting on an unset code. -# The one line put before the hook keeps a native non-zero exit from throwing where a PowerShell -# build defaults that preference on. A hook that opens with an empty param() then fails to parse, -# so it exits 1 on every call, and under onFailure: block it blocks every call. +# guard script that the hook's last statement runs is reported as 1. So the tail put after the +# hook exits 2 when the hook ends with $? false and $LASTEXITCODE at 2, including a 2 left by an +# earlier native command, and the hook blocks. A last statement that does not reset $?, such as +# `if ($false) {...}`, keeps it false. Otherwise the tail exits 1 when $? is false, as -Command +# would. The tail opens with a lone `;` on its own line: a trailing comment or line continuation +# ends there, and a dangling operator stays a parse error, as it is without the tail. Get-Variable +# keeps strict mode from faulting on an unset code. The one line put before the hook keeps a +# native non-zero exit from throwing where a PowerShell build defaults that preference on. A hook +# that opens with an empty param() then fails to parse, so it exits 1 on every call, and under +# onFailure: block it blocks every call. POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false\n" POWERSHELL_TAIL = ( - "\n\nif (-not $?) { if ((Get-Variable -Name LASTEXITCODE -Scope Global -ValueOnly" + "\n;\nif (-not $?) { if ((Get-Variable -Name LASTEXITCODE -Scope Global -ValueOnly" " -ErrorAction Ignore) -eq 2) { exit 2 }; exit 1 }" ) diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 0ff8e8cb0d..b9a8021d15 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -212,11 +212,18 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "Remove-Item -LiteralPath 'no-such-item-b4' -ErrorAction SilentlyContinue", "exit-1", ), - # A line continuation ending the hook must not swallow the bridge's own statement. + # A line continuation ending the hook must not swallow the bridge's own statement, and a + # dangling operator must stay a parse error rather than take it in. ("& '{py}' -c 'import sys; sys.exit(2)' `", "block"), + ("$deny =", "exit-1"), + ("Write-Output '{{}}' |", "exit-1"), + ("Write-Output '{{}}' ||", "exit-1"), + # A last statement that does not reset $? leaves an earlier native 2 to block. + ("& '{py}' -c 'import sys; sys.exit(2)'; if ($false) {{ exit 2 }}", "block"), ("if ($true) {{ return }}; exit 2", "allow"), - # After the bridge's head line, an empty param() fails to parse, but a non-empty one - # runs, with its default applied. + # After the bridge's head line, an empty param() fails to parse. A non-empty one parses + # as a call to a missing command named param, which leaves $? false; its parenthesised + # default is evaluated as an expression, so this body sees it and exits 0 by itself. ("param()\nexit 2", "exit-1"), ( "param([string]$Mode = 'enforce')\nif ($Mode -eq 'enforce') {{ exit 0 }}; exit 2", @@ -238,6 +245,10 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "failed-cmdlet", "strict-mode-failed-cmdlet", "trailing-continuation", + "dangling-assignment", + "dangling-pipe", + "dangling-or", + "stale-2-then-untaken-if", "early-return", "empty-param", "non-empty-param", From f844e926d1897e6c3b80e6efa09da29117e5baf7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 21:16:45 -0600 Subject: [PATCH 17/51] Codex bridge: the doc quotes the PowerShell tail instead of deriving when it blocks Each attempt to state in prose when the tail blocks was false for some shape, most recently a hook that ends on a terminating error. Those derivations are deleted from docs/CODEX.md, the bridge.py comment and the test comments. The doc now quotes POWERSHELL_TAIL verbatim, names the tests as the record of which shapes block, and warns that a hook that must block should end with an explicit exit 2. The bridge.py comment says only why the tail exists and points to the doc. Comments only; no code or test row changes. BACKLOG #5496. --- docs/CODEX.md | 33 +++++++++++++++++++-------------- scripts/codex/bridge.py | 17 ++++------------- tests/test_codex_bridge.py | 6 +----- 3 files changed, 24 insertions(+), 32 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 4a68c6bd03..2f978a95a4 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -34,9 +34,9 @@ that sets `"onFailure": "block"` when it fails: a non-zero exit, a timeout, a command that cannot start, a defect of its own such as an unsupported handler type or shell, or a defect in its group, such as a matcher that is not a valid regex, that keeps it from running. Any other hook failure is a -non-blocking error, except a command-only PowerShell hook that ends with a 2 in -`$LASTEXITCODE`, as described below. The bridge reports it on stderr and as a -`systemMessage`, naming the hook, ignores that hook's output, and runs the remaining hooks. A JSON +non-blocking error, except where the PowerShell tail below exits 2. The bridge +reports it on stderr and as a `systemMessage`, naming the hook, ignores that +hook's output, and runs the remaining hooks. A JSON `permissionDecision` deny from a hook is a decision, not a failure, and is passed on as before. @@ -85,17 +85,22 @@ Code does: Git Bash on Windows, else PowerShell there when Git Bash is missing. Structured `command` and `args` avoid shell parsing. A command-only PowerShell hook blocks by `exit 2`, as under Claude Code, whose hooks reference blocks a PowerShell hook with an explicit `exit 2`. The bridge runs it under -`pwsh -Command`. That reports as 1 a 2 from a native program, or from a guard -script the hook calls or dot-sources, when the hook's last statement runs it. So -the bridge puts a statement after the hook: a hook that ends with `$?` false -while `$LASTEXITCODE` is 2, including a 2 left by an earlier native command, -exits 2 and blocks. A last statement that does not reset `$?`, such as -`if ($false) { ... }`, keeps it false. It does not reach -a guard called inside a function or script block, or followed by `return` or -`break`. The bridge -puts one line before the hook, turning `$PSNativeCommandUseErrorActionPreference` -off. A hook that opens with an empty `param()` then fails to parse, so it exits -1 on every call, and under `"onFailure": "block"` it blocks every call. +`pwsh -Command`. It puts one line before the hook, turning +`$PSNativeCommandUseErrorActionPreference` off, and appends this fixed tail after +it, on new lines: + +```powershell +; +if (-not $?) { if ((Get-Variable -Name LASTEXITCODE -Scope Global -ValueOnly -ErrorAction Ignore) -eq 2) { exit 2 }; exit 1 } +``` + +The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`, and +`tests/test_codex_bridge.py` is the record of which shapes block. **A hook that +must block should end with an explicit `exit 2`.** Shapes that end on an error, +or with a stale exit code, are decided by the tail and are not listed here. + +A hook that opens with an empty `param()` fails to parse after the head line, so +it exits 1 on every call, and under `"onFailure": "block"` it blocks every call. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 3379e54fe0..4b76c0363b 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -199,19 +199,10 @@ def git_bash() -> str | None: return None -# A command-only PowerShell hook runs under pwsh -Command and blocks by `exit 2`, the way Claude -# Code's hooks reference blocks a PowerShell hook. That reference does not say which flags Claude -# Code passes, or how a native exit code propagates. Under -Command, a 2 from a native program or a -# guard script that the hook's last statement runs is reported as 1. So the tail put after the -# hook exits 2 when the hook ends with $? false and $LASTEXITCODE at 2, including a 2 left by an -# earlier native command, and the hook blocks. A last statement that does not reset $?, such as -# `if ($false) {...}`, keeps it false. Otherwise the tail exits 1 when $? is false, as -Command -# would. The tail opens with a lone `;` on its own line: a trailing comment or line continuation -# ends there, and a dangling operator stays a parse error, as it is without the tail. Get-Variable -# keeps strict mode from faulting on an unset code. The one line put before the hook keeps a -# native non-zero exit from throwing where a PowerShell build defaults that preference on. A hook -# that opens with an empty param() then fails to parse, so it exits 1 on every call, and under -# onFailure: block it blocks every call. +# A command-only PowerShell hook runs under pwsh -Command. The head line keeps a native non-zero +# exit from throwing where a PowerShell build defaults that preference on. The tail restores +# origin/main's block on a guard script's exit 2, which -Command reports as 1. See docs/CODEX.md, +# "Who decides a block", and the tests for which shapes block. POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false\n" POWERSHELL_TAIL = ( "\n;\nif (-not $?) { if ((Get-Variable -Name LASTEXITCODE -Scope Global -ValueOnly" diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index b9a8021d15..0f5dc0cf06 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -187,13 +187,10 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): ("try {{ Get-Item -LiteralPath 'no-such-item-b4' -EA Stop }} catch {{}}; exit 2", "block"), ("trap {{ exit 2 }}; throw 'boom'", "block"), ("$p = $input | ConvertFrom-Json; if ($p.tool_name -eq 'Bash') {{ exit 2 }}", "block"), - # A native 2 blocks, passed on by `exit` or left as the last statement, which -Command - # alone reports as 1. + # The rows from here on record what the bridge's tail decides, shape by shape. ("& '{py}' -c 'import sys; sys.exit(2)'; exit $LASTEXITCODE", "block"), ("& '{py}' -c 'import sys; sys.exit(2)'", "block"), ("& '{py}' -c 'import sys; sys.exit(3)'", "exit-1"), - # A stale 2 does not block after a last statement that succeeds, and does after one - # that fails. ("& '{py}' -c 'import sys; sys.exit(2)'; Write-Output '{{}}'", "allow"), ( "& '{py}' -c 'import sys; sys.exit(2)'; Get-Item -LiteralPath 'no-such-item-b4'", @@ -218,7 +215,6 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): ("$deny =", "exit-1"), ("Write-Output '{{}}' |", "exit-1"), ("Write-Output '{{}}' ||", "exit-1"), - # A last statement that does not reset $? leaves an earlier native 2 to block. ("& '{py}' -c 'import sys; sys.exit(2)'; if ($false) {{ exit 2 }}", "block"), ("if ($true) {{ return }}; exit 2", "allow"), # After the bridge's head line, an empty param() fails to parse. A non-empty one parses From 70a94ecc6ec38aa7f872e8c9b7a3c967847941d7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 21:37:50 -0600 Subject: [PATCH 18/51] Codex bridge: the PowerShell tail calls Get-Variable by its module-qualified name A hook that defined a function or alias named Get-Variable replaced the tail's call, so a guard's exit 2 came out as a non-blocking 1. The tail now calls Microsoft.PowerShell.Utility\Get-Variable; measured on pwsh 7.6.10, both shapes exit 2. Two guard test rows pin them, and the tail quoted in docs/CODEX.md matches POWERSHELL_TAIL again. The bridge.py comment now says what the tail does, with no claim about earlier code. BACKLOG #5496. --- docs/CODEX.md | 2 +- scripts/codex/bridge.py | 10 +++++----- tests/test_codex_bridge.py | 17 +++++++++++++++-- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 2f978a95a4..e8e7cb59c0 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -91,7 +91,7 @@ it, on new lines: ```powershell ; -if (-not $?) { if ((Get-Variable -Name LASTEXITCODE -Scope Global -ValueOnly -ErrorAction Ignore) -eq 2) { exit 2 }; exit 1 } +if (-not $?) { if ((Microsoft.PowerShell.Utility\Get-Variable -Name LASTEXITCODE -Scope Global -ValueOnly -ErrorAction Ignore) -eq 2) { exit 2 }; exit 1 } ``` The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`, and diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 4b76c0363b..0b5b0e44b4 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -200,13 +200,13 @@ def git_bash() -> str | None: # A command-only PowerShell hook runs under pwsh -Command. The head line keeps a native non-zero -# exit from throwing where a PowerShell build defaults that preference on. The tail restores -# origin/main's block on a guard script's exit 2, which -Command reports as 1. See docs/CODEX.md, -# "Who decides a block", and the tests for which shapes block. +# exit from throwing where a PowerShell build defaults that preference on. The tail lifts a 2 that +# -Command reports as 1, for example a guard script's exit 2, back to 2. See docs/CODEX.md, "Who +# decides a block", and the tests for which shapes block. POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false\n" POWERSHELL_TAIL = ( - "\n;\nif (-not $?) { if ((Get-Variable -Name LASTEXITCODE -Scope Global -ValueOnly" - " -ErrorAction Ignore) -eq 2) { exit 2 }; exit 1 }" + "\n;\nif (-not $?) { if ((Microsoft.PowerShell.Utility\\Get-Variable -Name LASTEXITCODE" + " -Scope Global -ValueOnly -ErrorAction Ignore) -eq 2) { exit 2 }; exit 1 }" ) diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 0f5dc0cf06..0732cdec1d 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -267,8 +267,21 @@ def test_a_powershell_hook_blocks_on_a_2_that_ends_it(bridge, tmp_path, command, @pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") @pytest.mark.parametrize( "command", - ["& ./guard.ps1", ". ./guard.ps1", "& ./guard.ps1 # the guard decides"], - ids=["called", "dot-sourced", "called-before-a-comment"], + [ + "& ./guard.ps1", + ". ./guard.ps1", + "& ./guard.ps1 # the guard decides", + # A hook's own Get-Variable must not stand in for the one the bridge's tail calls. + "function Get-Variable { 0 }\n& ./guard.ps1", + "Set-Alias Get-Variable Write-Output\n& ./guard.ps1", + ], + ids=[ + "called", + "dot-sourced", + "called-before-a-comment", + "after-a-Get-Variable-function", + "after-a-Get-Variable-alias", + ], ) def test_a_powershell_hook_blocks_when_a_guard_it_runs_exits_2(bridge, tmp_path, command): """-Command alone reports a guard script's `exit 2` as 1, which would not block.""" From 970601afafb6b76df43940022e09b00d52ad7d70 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 22:00:34 -0600 Subject: [PATCH 19/51] Codex bridge: the PowerShell tail reads the exit code without a cmdlet call A hook that set $PSDefaultParameterValues, for example '*:Exclude' or 'Get-Variable:Include', changed what the tail's Get-Variable call returned, so a guard's exit 2 came out as a non-blocking 1. The tail now reads $ExecutionContext.SessionState.PSVariable.GetValue('LASTEXITCODE'), which no default parameter, function or alias reaches. Measured on pwsh 7.6.10, both shapes exit 2, every other measured shape keeps its exit code, and strict mode does not fault with the code unset. Two guard test rows pin the shapes, and the tail quoted in docs/CODEX.md matches POWERSHELL_TAIL. BACKLOG #5496. --- docs/CODEX.md | 2 +- scripts/codex/bridge.py | 4 ++-- tests/test_codex_bridge.py | 7 ++++++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index e8e7cb59c0..74957ba67f 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -91,7 +91,7 @@ it, on new lines: ```powershell ; -if (-not $?) { if ((Microsoft.PowerShell.Utility\Get-Variable -Name LASTEXITCODE -Scope Global -ValueOnly -ErrorAction Ignore) -eq 2) { exit 2 }; exit 1 } +if (-not $?) { if ($ExecutionContext.SessionState.PSVariable.GetValue('LASTEXITCODE') -eq 2) { exit 2 }; exit 1 } ``` The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`, and diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 0b5b0e44b4..2dcd2c0649 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -205,8 +205,8 @@ def git_bash() -> str | None: # decides a block", and the tests for which shapes block. POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false\n" POWERSHELL_TAIL = ( - "\n;\nif (-not $?) { if ((Microsoft.PowerShell.Utility\\Get-Variable -Name LASTEXITCODE" - " -Scope Global -ValueOnly -ErrorAction Ignore) -eq 2) { exit 2 }; exit 1 }" + "\n;\nif (-not $?) { if ($ExecutionContext.SessionState.PSVariable.GetValue('LASTEXITCODE')" + " -eq 2) { exit 2 }; exit 1 }" ) diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 0732cdec1d..5ab12a7fa6 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -271,9 +271,12 @@ def test_a_powershell_hook_blocks_on_a_2_that_ends_it(bridge, tmp_path, command, "& ./guard.ps1", ". ./guard.ps1", "& ./guard.ps1 # the guard decides", - # A hook's own Get-Variable must not stand in for the one the bridge's tail calls. + # A hook's own commands or default parameter values must not change how the bridge's + # tail reads the exit code. "function Get-Variable { 0 }\n& ./guard.ps1", "Set-Alias Get-Variable Write-Output\n& ./guard.ps1", + "$PSDefaultParameterValues['*:Exclude'] = 'LAST*'\n& ./guard.ps1", + "$PSDefaultParameterValues['Get-Variable:Include'] = 'nothing'\n& ./guard.ps1", ], ids=[ "called", @@ -281,6 +284,8 @@ def test_a_powershell_hook_blocks_on_a_2_that_ends_it(bridge, tmp_path, command, "called-before-a-comment", "after-a-Get-Variable-function", "after-a-Get-Variable-alias", + "after-a-default-Exclude", + "after-a-default-Get-Variable-Include", ], ) def test_a_powershell_hook_blocks_when_a_guard_it_runs_exits_2(bridge, tmp_path, command): From e52437c6aa1923d16eb7c9ae3dfa5d52e6a72313 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 22:16:05 -0600 Subject: [PATCH 20/51] Codex bridge: the PowerShell tail reads LASTEXITCODE as a plain variable The GetValue method call that 970601afaf put in the tail is refused under Constrained Language Mode, so a guard's exit 2 came out as 1, and a hook's trap turned the refusal into a false block. The head line now also sets $global:LASTEXITCODE to 0, and the tail reads $global:LASTEXITCODE with no command or method call. Measured on pwsh 7.6.10: a guard blocks under CLM, after the default-parameter, Get-Variable and Update-TypeData shapes, and under strict mode; CLM with a trap and a failing cmdlet exits 1; every other measured shape keeps its exit code. CLM test rows added; the doc quotes the head line and tail as the source has them, and the test comment says only what its rows check. BACKLOG #5496. --- docs/CODEX.md | 12 ++++++++---- scripts/codex/bridge.py | 14 ++++++-------- tests/test_codex_bridge.py | 13 +++++++++++-- 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 74957ba67f..20cd23fe74 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -85,13 +85,17 @@ Code does: Git Bash on Windows, else PowerShell there when Git Bash is missing. Structured `command` and `args` avoid shell parsing. A command-only PowerShell hook blocks by `exit 2`, as under Claude Code, whose hooks reference blocks a PowerShell hook with an explicit `exit 2`. The bridge runs it under -`pwsh -Command`. It puts one line before the hook, turning -`$PSNativeCommandUseErrorActionPreference` off, and appends this fixed tail after -it, on new lines: +`pwsh -Command`. It puts this line before the hook: + +```powershell +$PSNativeCommandUseErrorActionPreference = $false; $global:LASTEXITCODE = 0 +``` + +and appends this fixed tail after it, on new lines: ```powershell ; -if (-not $?) { if ($ExecutionContext.SessionState.PSVariable.GetValue('LASTEXITCODE') -eq 2) { exit 2 }; exit 1 } +if (-not $?) { if ($global:LASTEXITCODE -eq 2) { exit 2 }; exit 1 } ``` The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`, and diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 2dcd2c0649..c00747d5ff 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -200,14 +200,12 @@ def git_bash() -> str | None: # A command-only PowerShell hook runs under pwsh -Command. The head line keeps a native non-zero -# exit from throwing where a PowerShell build defaults that preference on. The tail lifts a 2 that -# -Command reports as 1, for example a guard script's exit 2, back to 2. See docs/CODEX.md, "Who -# decides a block", and the tests for which shapes block. -POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false\n" -POWERSHELL_TAIL = ( - "\n;\nif (-not $?) { if ($ExecutionContext.SessionState.PSVariable.GetValue('LASTEXITCODE')" - " -eq 2) { exit 2 }; exit 1 }" -) +# exit from throwing where a PowerShell build defaults that preference on, and sets LASTEXITCODE so +# the tail reads it as a plain variable, with no command or method a hook can change. The tail +# lifts a 2 that -Command reports as 1, for example a guard script's exit 2, back to 2. See +# docs/CODEX.md, "Who decides a block", and the tests for which shapes block. +POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false; $global:LASTEXITCODE = 0\n" +POWERSHELL_TAIL = "\n;\nif (-not $?) { if ($global:LASTEXITCODE -eq 2) { exit 2 }; exit 1 }" def hook_argv(root: Path, hook: dict) -> list[str]: diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 5ab12a7fa6..7ec42ad057 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -209,6 +209,12 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "Remove-Item -LiteralPath 'no-such-item-b4' -ErrorAction SilentlyContinue", "exit-1", ), + # Under Constrained Language Mode the same: a failing cmdlet and a trap exit 1. + ( + "$ExecutionContext.SessionState.LanguageMode = 'ConstrainedLanguage'\n" + "trap {{ exit 2 }}; Get-Item -LiteralPath 'no-such-item-b4'", + "exit-1", + ), # A line continuation ending the hook must not swallow the bridge's own statement, and a # dangling operator must stay a parse error rather than take it in. ("& '{py}' -c 'import sys; sys.exit(2)' `", "block"), @@ -240,6 +246,7 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "stale-2-then-assignment", "failed-cmdlet", "strict-mode-failed-cmdlet", + "constrained-language-trap-failed-cmdlet", "trailing-continuation", "dangling-assignment", "dangling-pipe", @@ -271,12 +278,13 @@ def test_a_powershell_hook_blocks_on_a_2_that_ends_it(bridge, tmp_path, command, "& ./guard.ps1", ". ./guard.ps1", "& ./guard.ps1 # the guard decides", - # A hook's own commands or default parameter values must not change how the bridge's - # tail reads the exit code. + # Each still blocks after the hook defines a Get-Variable function or alias, sets these + # default parameter values, or switches to Constrained Language Mode. "function Get-Variable { 0 }\n& ./guard.ps1", "Set-Alias Get-Variable Write-Output\n& ./guard.ps1", "$PSDefaultParameterValues['*:Exclude'] = 'LAST*'\n& ./guard.ps1", "$PSDefaultParameterValues['Get-Variable:Include'] = 'nothing'\n& ./guard.ps1", + "$ExecutionContext.SessionState.LanguageMode = 'ConstrainedLanguage'\n& ./guard.ps1", ], ids=[ "called", @@ -286,6 +294,7 @@ def test_a_powershell_hook_blocks_on_a_2_that_ends_it(bridge, tmp_path, command, "after-a-Get-Variable-alias", "after-a-default-Exclude", "after-a-default-Get-Variable-Include", + "under-constrained-language", ], ) def test_a_powershell_hook_blocks_when_a_guard_it_runs_exits_2(bridge, tmp_path, command): From cc0f41c8bc05192bb9baa66e1b553ef4e13fb0dd Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 22:33:44 -0600 Subject: [PATCH 21/51] Codex bridge: the PowerShell tail reads LASTEXITCODE inside try/catch, with no preset Setting $global:LASTEXITCODE = 0 in the head line changed what a hook sees: a strict-mode hook that read the code before any native call no longer tripped its own trap, and a hook that removed the variable made the tail's read throw into its trap. The head line is back to the preference alone, and the tail's read sits in try/catch. Measured on pwsh 7.6.10 over 44 shapes, both cases now match bare pwsh -Command, a strict-mode exit $LASTEXITCODE before any native call is 1 again as it was at bd2e9536da, and every other shape keeps its exit code from e52437c6aa. Two test rows pin the cases; the doc quotes POWERSHELL_HEAD and POWERSHELL_TAIL and names both. BACKLOG #5496. --- docs/CODEX.md | 11 ++++++----- scripts/codex/bridge.py | 14 ++++++++------ tests/test_codex_bridge.py | 14 ++++++++++++++ 3 files changed, 28 insertions(+), 11 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 20cd23fe74..9146e5d481 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -88,19 +88,20 @@ PowerShell hook with an explicit `exit 2`. The bridge runs it under `pwsh -Command`. It puts this line before the hook: ```powershell -$PSNativeCommandUseErrorActionPreference = $false; $global:LASTEXITCODE = 0 +$PSNativeCommandUseErrorActionPreference = $false ``` and appends this fixed tail after it, on new lines: ```powershell ; -if (-not $?) { if ($global:LASTEXITCODE -eq 2) { exit 2 }; exit 1 } +if (-not $?) { try { if ($global:LASTEXITCODE -eq 2) { exit 2 } } catch {}; exit 1 } ``` -The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`, and -`tests/test_codex_bridge.py` is the record of which shapes block. **A hook that -must block should end with an explicit `exit 2`.** Shapes that end on an error, +The source is `POWERSHELL_HEAD` and `POWERSHELL_TAIL` in +`scripts/codex/bridge.py`, and `tests/test_codex_bridge.py` is the record of +which shapes block. **A hook that must block should end with an explicit +`exit 2`.** Shapes that end on an error, or with a stale exit code, are decided by the tail and are not listed here. A hook that opens with an empty `param()` fails to parse after the head line, so diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index c00747d5ff..3c7fec40bf 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -200,12 +200,14 @@ def git_bash() -> str | None: # A command-only PowerShell hook runs under pwsh -Command. The head line keeps a native non-zero -# exit from throwing where a PowerShell build defaults that preference on, and sets LASTEXITCODE so -# the tail reads it as a plain variable, with no command or method a hook can change. The tail -# lifts a 2 that -Command reports as 1, for example a guard script's exit 2, back to 2. See -# docs/CODEX.md, "Who decides a block", and the tests for which shapes block. -POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false; $global:LASTEXITCODE = 0\n" -POWERSHELL_TAIL = "\n;\nif (-not $?) { if ($global:LASTEXITCODE -eq 2) { exit 2 }; exit 1 }" +# exit from throwing where a PowerShell build defaults that preference on. The tail lifts a 2 that +# -Command reports as 1, for example a guard script's exit 2, back to 2. Its read sits in try/catch +# because under strict mode an unset LASTEXITCODE throws, and a hook's trap would turn that throw +# into a block. See docs/CODEX.md, "Who decides a block", and the tests for which shapes block. +POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false\n" +POWERSHELL_TAIL = ( + "\n;\nif (-not $?) { try { if ($global:LASTEXITCODE -eq 2) { exit 2 } } catch {}; exit 1 }" +) def hook_argv(root: Path, hook: dict) -> list[str]: diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 7ec42ad057..13348c5c15 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -215,6 +215,18 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "trap {{ exit 2 }}; Get-Item -LiteralPath 'no-such-item-b4'", "exit-1", ), + # The hook sees LASTEXITCODE unset, as bare pwsh starts it, so its own strict-mode read + # trips its own trap; and a hook that removes the variable gets no block from the tail. + ( + "Set-StrictMode -Version Latest; trap {{ exit 2 }}; " + "if ($LASTEXITCODE -ne 0) {{ 'native failed' }}", + "block", + ), + ( + "Remove-Variable * -ErrorAction SilentlyContinue; Set-StrictMode -Version Latest; " + "trap {{ exit 2 }}; Write-Error 'soft failure'", + "exit-1", + ), # A line continuation ending the hook must not swallow the bridge's own statement, and a # dangling operator must stay a parse error rather than take it in. ("& '{py}' -c 'import sys; sys.exit(2)' `", "block"), @@ -247,6 +259,8 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "failed-cmdlet", "strict-mode-failed-cmdlet", "constrained-language-trap-failed-cmdlet", + "strict-mode-reads-unset-code", + "strict-mode-after-removing-the-code", "trailing-continuation", "dangling-assignment", "dangling-pipe", From 54198dc3403e097b82f2367e323871261f5f0216 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 23:12:49 -0600 Subject: [PATCH 22/51] Codex bridge: no PowerShell head line, and a no-shell hook runs under pwsh on Windows The Lander's hold at cc0f41c8bc. The head line made a hook that opens with [CmdletBinding()], param(...), #Requires plus param() or a using statement fail to parse, so its exit 2 never blocked; the head is removed and the tail kept. Measured on pwsh 7.6.10, each of those now exits 2 as under bare pwsh -Command, and no shape exits worse than at cc0f41c8bc. A hook written as named blocks exits 1 at both, now as a parse error. On Windows, a command-only hook with no shell field runs under pwsh again, as on origin/main, not Git Bash. Corrects the statements the hold lists: the explicit-exit-2 advice now excludes named blocks; on origin/main a deny was lost when another hook exited non-zero; the tests record at least these shapes; and the comment and test name say the tail uses the last exit code, when it is 2. The doc's default-shell sentence and the param() comments follow the code. BACKLOG #5496. --- docs/CODEX.md | 31 +++++++++++++--------------- scripts/codex/bridge.py | 30 +++++++++++++--------------- tests/test_codex_bridge.py | 41 +++++++++++++++++++++++++++++--------- 3 files changed, 60 insertions(+), 42 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 9146e5d481..cf7499158c 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -68,7 +68,8 @@ and 127 under `sh`; this is reasoned, not measured. At origin/main before this change, no exit-2 block reached Codex: `pwsh -Command` reported the bridge's exit 2 as 1. A hook's JSON `permissionDecision` deny was -unaffected. **A future guard that must block when it fails sets +lost when another hook on the same event exited non-zero, which raised before +the merged result was printed. **A future guard that must block when it fails sets `"onFailure": "block"`.** That holds only for a hook the bridge reaches: a launcher with no decision, or a bridge fault, such as a payload with no session id, never blocks. @@ -80,32 +81,28 @@ turns into 2, including events where Claude Code only shows the hook's stderr. Hook chains have a 90-second outer limit, so the timeouts of a long chain add up against it. -Command-only hooks use the shell they name. With none, they use bash, as Claude -Code does: Git Bash on Windows, else PowerShell there when Git Bash is missing. +Command-only hooks use the shell they name. With none, they use pwsh on Windows +and bash elsewhere. Structured `command` and `args` avoid shell parsing. A command-only PowerShell hook blocks by `exit 2`, as under Claude Code, whose hooks reference blocks a PowerShell hook with an explicit `exit 2`. The bridge runs it under -`pwsh -Command`. It puts this line before the hook: - -```powershell -$PSNativeCommandUseErrorActionPreference = $false -``` - -and appends this fixed tail after it, on new lines: +`pwsh -Command` and appends this fixed tail after it, on new lines: ```powershell ; if (-not $?) { try { if ($global:LASTEXITCODE -eq 2) { exit 2 } } catch {}; exit 1 } ``` -The source is `POWERSHELL_HEAD` and `POWERSHELL_TAIL` in -`scripts/codex/bridge.py`, and `tests/test_codex_bridge.py` is the record of -which shapes block. **A hook that must block should end with an explicit -`exit 2`.** Shapes that end on an error, -or with a stale exit code, are decided by the tail and are not listed here. +The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`, and +`tests/test_codex_bridge.py` records at least these shapes and whether each +blocks. **A hook that must block should end with an explicit `exit 2`, and not +be written as named blocks (below).** Shapes +that end on an error, or with a stale exit code, are decided by the tail and are +not listed here. -A hook that opens with an empty `param()` fails to parse after the head line, so -it exits 1 on every call, and under `"onFailure": "block"` it blocks every call. +A hook written as named blocks (`begin`, `process`, `end`) fails to parse with +the tail after it, so it exits 1 on every call, and under +`"onFailure": "block"` it blocks every call. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 3c7fec40bf..0a9270ef6a 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -199,12 +199,11 @@ def git_bash() -> str | None: return None -# A command-only PowerShell hook runs under pwsh -Command. The head line keeps a native non-zero -# exit from throwing where a PowerShell build defaults that preference on. The tail lifts a 2 that -# -Command reports as 1, for example a guard script's exit 2, back to 2. Its read sits in try/catch -# because under strict mode an unset LASTEXITCODE throws, and a hook's trap would turn that throw -# into a block. See docs/CODEX.md, "Who decides a block", and the tests for which shapes block. -POWERSHELL_HEAD = "$PSNativeCommandUseErrorActionPreference = $false\n" +# A command-only PowerShell hook runs under pwsh -Command with this tail after it. When the hook +# ends with $? false, the tail exits with the last exit code, when it is 2, and with 1 otherwise; +# -Command alone reports a guard script's exit 2 as 1. Its read sits in try/catch because under +# strict mode an unset LASTEXITCODE throws, and a hook's trap would turn that throw into a block. +# See docs/CODEX.md, "Who decides a block", and the tests for which shapes block. POWERSHELL_TAIL = ( "\n;\nif (-not $?) { try { if ($global:LASTEXITCODE -eq 2) { exit 2 } } catch {}; exit 1 }" ) @@ -217,21 +216,20 @@ def hook_argv(root: Path, hook: dict) -> list[str]: str(part).replace("${CLAUDE_PROJECT_DIR}", str(root)) for part in (command, *hook["args"]) ] - # A command-only source runs in the shell it names. Claude Code's default is bash, and on - # Windows PowerShell when Git Bash is not installed. Environment expansion belongs to that - # shell; structured args above need no shell parsing. + # A command-only source runs in the shell it names; with none, pwsh on Windows and bash + # elsewhere. Environment expansion belongs to that shell; structured args above need no shell + # parsing. shell = hook.get("shell") - if shell in ("bash", None): + if shell is None: + shell = "powershell" if os.name == "nt" else "bash" + if shell == "bash": bash = git_bash() if os.name == "nt" else "bash" - if bash: - return [bash, "-c", command] - if shell == "bash": + if not bash: raise FileNotFoundError("Git Bash not found; a shell: bash hook cannot run") - shell = "powershell" + return [bash, "-c", command] if shell == "powershell": command = command.replace("${CLAUDE_PROJECT_DIR}", "${env:CLAUDE_PROJECT_DIR}") - script = POWERSHELL_HEAD + command + POWERSHELL_TAIL - return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script] + return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command + POWERSHELL_TAIL] raise ValueError(f"Unsupported Claude hook shell: {shell}") diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 13348c5c15..2d46c24388 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -235,14 +235,19 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): ("Write-Output '{{}}' ||", "exit-1"), ("& '{py}' -c 'import sys; sys.exit(2)'; if ($false) {{ exit 2 }}", "block"), ("if ($true) {{ return }}; exit 2", "allow"), - # After the bridge's head line, an empty param() fails to parse. A non-empty one parses - # as a call to a missing command named param, which leaves $? false; its parenthesised - # default is evaluated as an expression, so this body sees it and exits 0 by itself. - ("param()\nexit 2", "exit-1"), + # A hook may open with param(), [CmdletBinding()], #Requires or using, as a script can, + # and its exit 2 blocks. Named blocks cannot be followed by the tail, so they fail to + # parse. + ("param()\nexit 2", "block"), ( "param([string]$Mode = 'enforce')\nif ($Mode -eq 'enforce') {{ exit 0 }}; exit 2", "allow", ), + ("[CmdletBinding()]\nparam()\nexit 2", "block"), + ("param([string]$A = 'a', [string]$B = 'b')\nexit 2", "block"), + ("#Requires -Version 7\nparam()\nexit 2", "block"), + ("using namespace System.IO\nexit 2", "block"), + ("begin {{ }}\nend {{ exit 2 }}", "exit-1"), ], ids=[ "explicit-exit-2", @@ -269,9 +274,16 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "early-return", "empty-param", "non-empty-param", + "cmdletbinding-param", + "two-defaulted-params", + "requires-then-param", + "using-namespace", + "named-blocks", ], ) -def test_a_powershell_hook_blocks_on_a_2_that_ends_it(bridge, tmp_path, command, outcome): +def test_a_powershell_hook_blocks_on_the_last_exit_code_when_it_is_2( + bridge, tmp_path, command, outcome +): hook = {"type": "command", "shell": "powershell", "command": command.format(py=sys.executable)} settings(tmp_path, [hook]) if outcome == "block": @@ -359,16 +371,27 @@ def test_non_object_json_on_a_tool_event_is_not_a_block(bridge, tmp_path, capsys assert "3" in capsys.readouterr().err -def test_a_command_only_hook_defaults_to_bash_then_powershell(bridge, tmp_path, monkeypatch): - """Claude Code's default shell is bash, or PowerShell on Windows when Git Bash is missing.""" +def test_a_command_only_hook_defaults_to_pwsh_on_windows_else_bash(bridge, tmp_path, monkeypatch): + """With no shell named, a command-only hook runs under pwsh on Windows and bash elsewhere.""" hook = {"type": "command", "command": "echo hi"} monkeypatch.setattr(bridge, "git_bash", lambda: "git/bin/bash.exe") - assert Path(bridge.hook_argv(tmp_path, hook)[0]).stem == "bash" if os.name == "nt": - monkeypatch.setattr(bridge, "git_bash", lambda: None) assert bridge.hook_argv(tmp_path, hook)[0] == "pwsh" + assert Path(bridge.hook_argv(tmp_path, {**hook, "shell": "bash"})[0]).stem == "bash" + monkeypatch.setattr(bridge, "git_bash", lambda: None) with pytest.raises(FileNotFoundError): bridge.hook_argv(tmp_path, {**hook, "shell": "bash"}) + else: + assert Path(bridge.hook_argv(tmp_path, hook)[0]).stem == "bash" + + +@pytest.mark.skipif( + shutil.which("pwsh") is None or os.name != "nt", reason="requires PowerShell on Windows" +) +def test_a_no_shell_hook_runs_under_pwsh_on_windows(bridge, tmp_path): + settings(tmp_path, [{"type": "command", "command": 'trap { exit 2 }; throw "boom"'}]) + with pytest.raises(bridge.HookBlocked): + bridge.dispatch(tmp_path, BASH_CALL) # Values a tracked matcher is tried against, per event's discriminator. A new matcher that selects From 702559b143da6c9a9e248b763faeba009f8053ac Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 23:33:30 -0600 Subject: [PATCH 23/51] Codex bridge doc: named-block PowerShell hooks are a stated limit; three blocking statements corrected The Lander ruled named-block hooks a documented limit. docs/CODEX.md now says a command-only PowerShell hook written as named blocks, at least begin, process, end, clean and dynamicparam, cannot block by its own exit 2 under the bridge: it exits 1 on every call, which blocks every call under onFailure: block, and must use the -File exec form instead. The named-blocks test row already pins the exit 1. Also: a [CmdletBinding()] hook does not receive the payload through $input, in the doc and the row comment; the "as under Claude Code" claim is deleted, and the pwsh default on Windows is listed as a difference from Claude Code. Docs and a test comment only. BACKLOG #5496. --- docs/CODEX.md | 26 +++++++++++++++----------- tests/test_codex_bridge.py | 4 ++-- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index cf7499158c..d467e7fd7d 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -74,19 +74,19 @@ the merged result was printed. **A future guard that must block when it fails se launcher with no decision, or a bridge fault, such as a payload with no session id, never blocks. -The bridge differs from Claude Code in at least three ways. It runs an event's +The bridge differs from Claude Code in at least four ways. It runs an event's hooks one after another, where Claude Code runs them in parallel. Exit 2 stops the remaining hooks, and the bridge exits 10 on every event, which `invoke.ps1` turns into 2, including events where Claude Code only shows the hook's stderr. Hook chains have a 90-second outer limit, so the timeouts of a long chain add up -against it. +against it. On Windows, a command-only hook with no `shell` runs under pwsh, +where Claude Code runs it under Git Bash when Git Bash is installed. Command-only hooks use the shell they name. With none, they use pwsh on Windows and bash elsewhere. -Structured `command` and `args` avoid shell parsing. A command-only PowerShell -hook blocks by `exit 2`, as under Claude Code, whose hooks reference blocks a -PowerShell hook with an explicit `exit 2`. The bridge runs it under -`pwsh -Command` and appends this fixed tail after it, on new lines: +Structured `command` and `args` avoid shell parsing. The bridge runs a +command-only PowerShell hook under `pwsh -Command` and appends this fixed tail +after it, on new lines: ```powershell ; @@ -98,11 +98,15 @@ The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`, and blocks. **A hook that must block should end with an explicit `exit 2`, and not be written as named blocks (below).** Shapes that end on an error, or with a stale exit code, are decided by the tail and are -not listed here. - -A hook written as named blocks (`begin`, `process`, `end`) fails to parse with -the tail after it, so it exits 1 on every call, and under -`"onFailure": "block"` it blocks every call. +not listed here. A hook that opens with `[CmdletBinding()]` does not receive the +payload through `$input`. + +A command-only PowerShell hook written as named blocks, at least `begin`, +`process`, `end`, `clean` and `dynamicparam`, cannot block by its own `exit 2` +under the bridge: it fails to parse with the tail after it, so it exits 1 on +every call, and under `"onFailure": "block"` it blocks every call. Such a hook +must use the `-File` exec form instead, a `command` of `pwsh` with `args` that +name the script after `-File`. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 2d46c24388..82b995db81 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -236,8 +236,8 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): ("& '{py}' -c 'import sys; sys.exit(2)'; if ($false) {{ exit 2 }}", "block"), ("if ($true) {{ return }}; exit 2", "allow"), # A hook may open with param(), [CmdletBinding()], #Requires or using, as a script can, - # and its exit 2 blocks. Named blocks cannot be followed by the tail, so they fail to - # parse. + # and its exit 2 blocks; a [CmdletBinding()] hook does not receive the payload through + # $input. Named blocks cannot be followed by the tail, so they fail to parse. ("param()\nexit 2", "block"), ( "param([string]$Mode = 'enforce')\nif ($Mode -eq 'enforce') {{ exit 0 }}; exit 2", From 5c57026552b030e06ee78b159f60442072062a64 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 16 Nov 2026 23:47:40 -0600 Subject: [PATCH 24/51] Codex bridge doc: delete the -File advice for named-block hooks and a stale Claude Code claim Deletion only. The advice that a named-block hook must use the -File exec form is removed with no recipe in its place; the measured statement stays. "as under Claude Code" is removed from the test table's opening comment. BACKLOG #5496. --- docs/CODEX.md | 4 +--- tests/test_codex_bridge.py | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index d467e7fd7d..8cb91b0a9f 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -104,9 +104,7 @@ payload through `$input`. A command-only PowerShell hook written as named blocks, at least `begin`, `process`, `end`, `clean` and `dynamicparam`, cannot block by its own `exit 2` under the bridge: it fails to parse with the tail after it, so it exits 1 on -every call, and under `"onFailure": "block"` it blocks every call. Such a hook -must use the `-File` exec form instead, a `command` of `pwsh` with `args` that -name the script after `-File`. +every call, and under `"onFailure": "block"` it blocks every call. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 82b995db81..e5723c5978 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -182,7 +182,7 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): @pytest.mark.parametrize( ("command", "outcome"), [ - # A command-only PowerShell hook blocks by `exit 2`, as under Claude Code. + # A command-only PowerShell hook blocks by `exit 2`. ("Write-Output 'x' | Out-Null; exit 2", "block"), ("try {{ Get-Item -LiteralPath 'no-such-item-b4' -EA Stop }} catch {{}}; exit 2", "block"), ("trap {{ exit 2 }}; throw 'boom'", "block"), From 5901590c35d01b37fe0cb8887b7ca36f867a7a9e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 00:04:06 -0600 Subject: [PATCH 25/51] Codex bridge doc: cut the prose on which PowerShell hook shapes block; the tests record it Deletion only, with one line added as given. docs/CODEX.md drops the explicit-exit-2 advice, the named-block paragraph and the claim about what the tests record, and now says the tests in tests/test_codex_bridge.py record which PowerShell hook shapes block. The test file drops the comments and docstring that generalised about blocking; every row, id and expected exit code is unchanged. BACKLOG #5496. --- docs/CODEX.md | 10 ++-------- tests/test_codex_bridge.py | 6 ------ 2 files changed, 2 insertions(+), 14 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 8cb91b0a9f..c332d74c91 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -93,18 +93,12 @@ after it, on new lines: if (-not $?) { try { if ($global:LASTEXITCODE -eq 2) { exit 2 } } catch {}; exit 1 } ``` -The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`, and -`tests/test_codex_bridge.py` records at least these shapes and whether each -blocks. **A hook that must block should end with an explicit `exit 2`, and not -be written as named blocks (below).** Shapes +The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`. Shapes that end on an error, or with a stale exit code, are decided by the tail and are not listed here. A hook that opens with `[CmdletBinding()]` does not receive the payload through `$input`. -A command-only PowerShell hook written as named blocks, at least `begin`, -`process`, `end`, `clean` and `dynamicparam`, cannot block by its own `exit 2` -under the bridge: it fails to parse with the tail after it, so it exits 1 on -every call, and under `"onFailure": "block"` it blocks every call. +Which PowerShell hook shapes block is recorded by the tests in tests/test_codex_bridge.py; read them rather than this page. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index e5723c5978..eef68649a0 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -182,7 +182,6 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): @pytest.mark.parametrize( ("command", "outcome"), [ - # A command-only PowerShell hook blocks by `exit 2`. ("Write-Output 'x' | Out-Null; exit 2", "block"), ("try {{ Get-Item -LiteralPath 'no-such-item-b4' -EA Stop }} catch {{}}; exit 2", "block"), ("trap {{ exit 2 }}; throw 'boom'", "block"), @@ -235,9 +234,6 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): ("Write-Output '{{}}' ||", "exit-1"), ("& '{py}' -c 'import sys; sys.exit(2)'; if ($false) {{ exit 2 }}", "block"), ("if ($true) {{ return }}; exit 2", "allow"), - # A hook may open with param(), [CmdletBinding()], #Requires or using, as a script can, - # and its exit 2 blocks; a [CmdletBinding()] hook does not receive the payload through - # $input. Named blocks cannot be followed by the tail, so they fail to parse. ("param()\nexit 2", "block"), ( "param([string]$Mode = 'enforce')\nif ($Mode -eq 'enforce') {{ exit 0 }}; exit 2", @@ -324,12 +320,10 @@ def test_a_powershell_hook_blocks_on_the_last_exit_code_when_it_is_2( ], ) def test_a_powershell_hook_blocks_when_a_guard_it_runs_exits_2(bridge, tmp_path, command): - """-Command alone reports a guard script's `exit 2` as 1, which would not block.""" (tmp_path / "guard.ps1").write_text("exit 2\n", encoding="utf-8") settings(tmp_path, [{"type": "command", "shell": "powershell", "command": command}]) with pytest.raises(bridge.HookBlocked): bridge.dispatch(tmp_path, BASH_CALL) - # A later statement that succeeds is the hook's own outcome. settings(tmp_path, [{"type": "command", "shell": "powershell", "command": command + "\n$null"}]) assert bridge.dispatch(tmp_path, BASH_CALL) == {} From 2c7fbcdd19b4bbfd526d8a393cfa859465670e07 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 00:14:36 -0600 Subject: [PATCH 26/51] Codex bridge doc: restore the stale-2 sentence the Lander made a condition Restores, from docs/CODEX.md at e57e2dd097 (lines 90-91, with the leading "So" dropped and the article capitalised), "A hook whose last statement fails while $LASTEXITCODE is 2, including a 2 left by an earlier native command, blocks." and deletes the sentence it makes redundant, "Shapes that end on an error, or with a stale exit code, are decided by the tail and are not listed here." Doc only. BACKLOG #5496. --- docs/CODEX.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index c332d74c91..f1a108f519 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -93,9 +93,9 @@ after it, on new lines: if (-not $?) { try { if ($global:LASTEXITCODE -eq 2) { exit 2 } } catch {}; exit 1 } ``` -The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`. Shapes -that end on an error, or with a stale exit code, are decided by the tail and are -not listed here. A hook that opens with `[CmdletBinding()]` does not receive the +The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`. A hook whose last +statement fails while `$LASTEXITCODE` is 2, including a 2 left by an earlier +native command, blocks. A hook that opens with `[CmdletBinding()]` does not receive the payload through `$input`. Which PowerShell hook shapes block is recorded by the tests in tests/test_codex_bridge.py; read them rather than this page. From 57cece53f11121c6a5f5aee94b8e460bd251226f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 00:47:11 -0600 Subject: [PATCH 27/51] Codex bridge doc: delete the stale-2 blocking sentence Deletion only. The Lander dropped its condition, and the sentence was false for script-terminating last statements, so it is removed. BACKLOG #5496. --- docs/CODEX.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index f1a108f519..dad3d44b92 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -93,9 +93,7 @@ after it, on new lines: if (-not $?) { try { if ($global:LASTEXITCODE -eq 2) { exit 2 } } catch {}; exit 1 } ``` -The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`. A hook whose last -statement fails while `$LASTEXITCODE` is 2, including a 2 left by an earlier -native command, blocks. A hook that opens with `[CmdletBinding()]` does not receive the +The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`. A hook that opens with `[CmdletBinding()]` does not receive the payload through `$input`. Which PowerShell hook shapes block is recorded by the tests in tests/test_codex_bridge.py; read them rather than this page. From f3b2a094214e2e7869c0667931848814b58d3776 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 01:17:22 -0600 Subject: [PATCH 28/51] Codex bridge doc: cut the origin/main history and "naming the hook" Deletion only, per the Lander's hold at 2c7fbcdd19 (findings 11 and 13). The "At origin/main before this change" sentence goes, with the deny sentence that depended on it, and "naming the hook" goes from the defect-reporting sentence. The stale-2 sentence was already cut at 57cece53f1. BACKLOG #5496. --- docs/CODEX.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index dad3d44b92..8ada965e6d 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -35,7 +35,7 @@ command that cannot start, a defect of its own such as an unsupported handler type or shell, or a defect in its group, such as a matcher that is not a valid regex, that keeps it from running. Any other hook failure is a non-blocking error, except where the PowerShell tail below exits 2. The bridge -reports it on stderr and as a `systemMessage`, naming the hook, ignores that +reports it on stderr and as a `systemMessage`, ignores that hook's output, and runs the remaining hooks. A JSON `permissionDecision` deny from a hook is a decision, not a failure, and is passed on as before. @@ -66,10 +66,7 @@ When `pwsh` itself cannot start, nothing reports it: the line would exit 0 under Windows PowerShell 5.1, which proceeds as if every hook passed, 9009 under `cmd` and 127 under `sh`; this is reasoned, not measured. -At origin/main before this change, no exit-2 block reached Codex: `pwsh -Command` -reported the bridge's exit 2 as 1. A hook's JSON `permissionDecision` deny was -lost when another hook on the same event exited non-zero, which raised before -the merged result was printed. **A future guard that must block when it fails sets +**A future guard that must block when it fails sets `"onFailure": "block"`.** That holds only for a hook the bridge reaches: a launcher with no decision, or a bridge fault, such as a payload with no session id, never blocks. From 03979c5f8ec62a488e1068fa2d5c73b6fbd9804a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 02:00:02 -0600 Subject: [PATCH 29/51] Codex bridge: drop the PowerShell tail and the config's trailing exit A command-only PowerShell hook runs as plain pwsh -Command again, as on main, and .codex/config.toml no longer appends "; exit $LASTEXITCODE". Measured against origin/main: a named-block hook's JSON deny is forwarded again (the tail made it a ParserError), a missing pwsh under a PowerShell outer shell exits 1 again (the trailer made it 0), and a guard's exit 2 inside a command-only hook is a non-blocking exit 1, as on main. Exit-2 delivery is deferred to its own row. Tests: tail-only rows and the guard table are gone; a named-block deny row is added; the launcher expects 1 for a block under a pwsh outer shell. BACKLOG #5496 --- .codex/config.toml | 29 ++++---- scripts/codex/bridge.py | 12 +--- tests/test_codex_bridge.py | 135 ++++++++----------------------------- 3 files changed, 44 insertions(+), 132 deletions(-) diff --git a/.codex/config.toml b/.codex/config.toml index d48f0ea5df..a53ede7e14 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -1,8 +1,7 @@ # Claude Code remains the source of hook policy. The bridge reads it on each event. -# Only a hook's block reaches Codex as exit 2. A launcher that cannot run the bridge (the inner -# exit 1) is a non-blocking error on every event. The trailing exit passes the code on where -# PowerShell runs this line, since pwsh -Command reports a native exit 2 as 1; under sh it exits -# with pwsh's status, and under cmd pwsh receives it as more -Command text. +# A launcher that cannot run the bridge, or a missing pwsh, is a non-blocking error on every event. +# Where PowerShell runs this line, pwsh -Command reports the launcher's exit 2 as a non-blocking 1; +# a hook's JSON deny reaches Codex under every outer shell. # docs/CODEX.md, "Who decides a block", states the rule. [features] hooks = true @@ -10,65 +9,65 @@ hooks = true [[hooks.SessionStart]] [[hooks.SessionStart.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SessionStart; exit 1"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SessionStart"''' timeout = 90 [[hooks.SessionEnd]] [[hooks.SessionEnd.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SessionEnd; exit 1"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SessionEnd"''' timeout = 90 [[hooks.PreToolUse]] [[hooks.PreToolUse.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PreToolUse; exit 1"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PreToolUse"''' timeout = 90 [[hooks.PostToolUse]] [[hooks.PostToolUse.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PostToolUse; exit 1"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PostToolUse"''' timeout = 90 [[hooks.PermissionRequest]] [[hooks.PermissionRequest.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PermissionRequest; exit 1"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PermissionRequest"''' timeout = 90 [[hooks.UserPromptSubmit]] [[hooks.UserPromptSubmit.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event UserPromptSubmit; exit 1"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event UserPromptSubmit"''' timeout = 90 [[hooks.PreCompact]] [[hooks.PreCompact.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PreCompact; exit 1"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PreCompact"''' timeout = 90 [[hooks.PostCompact]] [[hooks.PostCompact.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PostCompact; exit 1"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PostCompact"''' timeout = 90 [[hooks.Stop]] [[hooks.Stop.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event Stop; exit 1"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event Stop"''' timeout = 90 [[hooks.SubagentStart]] [[hooks.SubagentStart.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SubagentStart; exit 1"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SubagentStart"''' timeout = 90 [[hooks.SubagentStop]] [[hooks.SubagentStop.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SubagentStop; exit 1"; exit $LASTEXITCODE''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SubagentStop"''' timeout = 90 diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 0a9270ef6a..a2023f1c56 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -199,16 +199,6 @@ def git_bash() -> str | None: return None -# A command-only PowerShell hook runs under pwsh -Command with this tail after it. When the hook -# ends with $? false, the tail exits with the last exit code, when it is 2, and with 1 otherwise; -# -Command alone reports a guard script's exit 2 as 1. Its read sits in try/catch because under -# strict mode an unset LASTEXITCODE throws, and a hook's trap would turn that throw into a block. -# See docs/CODEX.md, "Who decides a block", and the tests for which shapes block. -POWERSHELL_TAIL = ( - "\n;\nif (-not $?) { try { if ($global:LASTEXITCODE -eq 2) { exit 2 } } catch {}; exit 1 }" -) - - def hook_argv(root: Path, hook: dict) -> list[str]: command = hook["command"] if "args" in hook: @@ -229,7 +219,7 @@ def hook_argv(root: Path, hook: dict) -> list[str]: return [bash, "-c", command] if shell == "powershell": command = command.replace("${CLAUDE_PROJECT_DIR}", "${env:CLAUDE_PROJECT_DIR}") - return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command + POWERSHELL_TAIL] + return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command] raise ValueError(f"Unsupported Claude hook shell: {shell}") diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index eef68649a0..e40933b620 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -178,6 +178,12 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): assert "hook says 2" not in capsys.readouterr().err +DENY_JSON = ( + '{"hookSpecificOutput": {"hookEventName": "PreToolUse", ' + '"permissionDecision": "deny", "permissionDecisionReason": "no"}}' +) + + @pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") @pytest.mark.parametrize( ("command", "outcome"), @@ -186,64 +192,19 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): ("try {{ Get-Item -LiteralPath 'no-such-item-b4' -EA Stop }} catch {{}}; exit 2", "block"), ("trap {{ exit 2 }}; throw 'boom'", "block"), ("$p = $input | ConvertFrom-Json; if ($p.tool_name -eq 'Bash') {{ exit 2 }}", "block"), - # The rows from here on record what the bridge's tail decides, shape by shape. ("& '{py}' -c 'import sys; sys.exit(2)'; exit $LASTEXITCODE", "block"), - ("& '{py}' -c 'import sys; sys.exit(2)'", "block"), - ("& '{py}' -c 'import sys; sys.exit(3)'", "exit-1"), - ("& '{py}' -c 'import sys; sys.exit(2)'; Write-Output '{{}}'", "allow"), - ( - "& '{py}' -c 'import sys; sys.exit(2)'; Get-Item -LiteralPath 'no-such-item-b4'", - "block", - ), - ( - "& '{py}' -c 'import sys; sys.exit(2)'; " - "Remove-Item -LiteralPath 'no-such-item-b4' -ErrorAction Ignore", - "block", - ), - ("& '{py}' -c 'import sys; sys.exit(2)'; $null = Get-Item -LiteralPath 'no-b4'", "block"), + # pwsh -Command reports a native or script exit 2 that no explicit exit names as 1. + ("& '{py}' -c 'import sys; sys.exit(2)'", "exit-1"), + ("& ./guard.ps1", "exit-1"), ("Get-Item -LiteralPath 'no-such-item-b4'", "exit-1"), - # Under strict mode, with no native code set, the bridge's own statement must not fault. - ( - "Set-StrictMode -Version Latest; trap {{ exit 2 }}; " - "Remove-Item -LiteralPath 'no-such-item-b4' -ErrorAction SilentlyContinue", - "exit-1", - ), - # Under Constrained Language Mode the same: a failing cmdlet and a trap exit 1. - ( - "$ExecutionContext.SessionState.LanguageMode = 'ConstrainedLanguage'\n" - "trap {{ exit 2 }}; Get-Item -LiteralPath 'no-such-item-b4'", - "exit-1", - ), - # The hook sees LASTEXITCODE unset, as bare pwsh starts it, so its own strict-mode read - # trips its own trap; and a hook that removes the variable gets no block from the tail. - ( - "Set-StrictMode -Version Latest; trap {{ exit 2 }}; " - "if ($LASTEXITCODE -ne 0) {{ 'native failed' }}", - "block", - ), - ( - "Remove-Variable * -ErrorAction SilentlyContinue; Set-StrictMode -Version Latest; " - "trap {{ exit 2 }}; Write-Error 'soft failure'", - "exit-1", - ), - # A line continuation ending the hook must not swallow the bridge's own statement, and a - # dangling operator must stay a parse error rather than take it in. - ("& '{py}' -c 'import sys; sys.exit(2)' `", "block"), - ("$deny =", "exit-1"), - ("Write-Output '{{}}' |", "exit-1"), - ("Write-Output '{{}}' ||", "exit-1"), - ("& '{py}' -c 'import sys; sys.exit(2)'; if ($false) {{ exit 2 }}", "block"), ("if ($true) {{ return }}; exit 2", "allow"), - ("param()\nexit 2", "block"), + ("begin {{ }}\nend {{ exit 2 }}", "block"), ( - "param([string]$Mode = 'enforce')\nif ($Mode -eq 'enforce') {{ exit 0 }}; exit 2", - "allow", + "begin {{ }}\nend {{ Write-Output '" + + DENY_JSON.replace("{", "{{").replace("}", "}}") + + "' }}", + "deny", ), - ("[CmdletBinding()]\nparam()\nexit 2", "block"), - ("param([string]$A = 'a', [string]$B = 'b')\nexit 2", "block"), - ("#Requires -Version 7\nparam()\nexit 2", "block"), - ("using namespace System.IO\nexit 2", "block"), - ("begin {{ }}\nend {{ exit 2 }}", "exit-1"), ], ids=[ "explicit-exit-2", @@ -252,34 +213,17 @@ def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): "reads-input", "native-2-passed-on", "native-2-last", - "native-3-last", - "stale-2-then-success", - "stale-2-then-failed-cmdlet", - "stale-2-then-ignored-cmdlet", - "stale-2-then-assignment", + "guard-exits-2", "failed-cmdlet", - "strict-mode-failed-cmdlet", - "constrained-language-trap-failed-cmdlet", - "strict-mode-reads-unset-code", - "strict-mode-after-removing-the-code", - "trailing-continuation", - "dangling-assignment", - "dangling-pipe", - "dangling-or", - "stale-2-then-untaken-if", "early-return", - "empty-param", - "non-empty-param", - "cmdletbinding-param", - "two-defaulted-params", - "requires-then-param", - "using-namespace", "named-blocks", + "named-blocks-deny", ], ) -def test_a_powershell_hook_blocks_on_the_last_exit_code_when_it_is_2( +def test_a_command_only_powershell_hook_blocks_on_an_explicit_exit_2_or_a_deny( bridge, tmp_path, command, outcome ): + (tmp_path / "guard.ps1").write_text("exit 2\n", encoding="utf-8") hook = {"type": "command", "shell": "powershell", "command": command.format(py=sys.executable)} settings(tmp_path, [hook]) if outcome == "block": @@ -289,43 +233,19 @@ def test_a_powershell_hook_blocks_on_the_last_exit_code_when_it_is_2( result = bridge.dispatch(tmp_path, BASH_CALL) if outcome == "allow": assert result == {}, result + elif outcome == "deny": + assert result["hookSpecificOutput"]["permissionDecision"] == "deny", result else: assert "hook exited 1: " in result["systemMessage"], result @pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") -@pytest.mark.parametrize( - "command", - [ - "& ./guard.ps1", - ". ./guard.ps1", - "& ./guard.ps1 # the guard decides", - # Each still blocks after the hook defines a Get-Variable function or alias, sets these - # default parameter values, or switches to Constrained Language Mode. - "function Get-Variable { 0 }\n& ./guard.ps1", - "Set-Alias Get-Variable Write-Output\n& ./guard.ps1", - "$PSDefaultParameterValues['*:Exclude'] = 'LAST*'\n& ./guard.ps1", - "$PSDefaultParameterValues['Get-Variable:Include'] = 'nothing'\n& ./guard.ps1", - "$ExecutionContext.SessionState.LanguageMode = 'ConstrainedLanguage'\n& ./guard.ps1", - ], - ids=[ - "called", - "dot-sourced", - "called-before-a-comment", - "after-a-Get-Variable-function", - "after-a-Get-Variable-alias", - "after-a-default-Exclude", - "after-a-default-Get-Variable-Include", - "under-constrained-language", - ], -) -def test_a_powershell_hook_blocks_when_a_guard_it_runs_exits_2(bridge, tmp_path, command): +def test_an_args_form_hook_blocks_when_the_guard_it_runs_exits_2(bridge, tmp_path): (tmp_path / "guard.ps1").write_text("exit 2\n", encoding="utf-8") - settings(tmp_path, [{"type": "command", "shell": "powershell", "command": command}]) + hook = {"type": "command", "command": "pwsh", "args": ["-NoProfile", "-File", "guard.ps1"]} + settings(tmp_path, [hook]) with pytest.raises(bridge.HookBlocked): bridge.dispatch(tmp_path, BASH_CALL) - settings(tmp_path, [{"type": "command", "shell": "powershell", "command": command + "\n$null"}]) - assert bridge.dispatch(tmp_path, BASH_CALL) == {} def test_project_dir_is_substituted_in_every_form(bridge, tmp_path): @@ -333,7 +253,7 @@ def test_project_dir_is_substituted_in_every_form(bridge, tmp_path): assert bridge.hook_argv(tmp_path, structured) == [f"{tmp_path}/guard", "a"] shell = {"type": "command", "shell": "powershell", "command": "'${CLAUDE_PROJECT_DIR}_x'"} # Braced, so a following name character cannot join the variable name. - command = bridge.hook_argv(tmp_path, shell)[-1].removesuffix(bridge.POWERSHELL_TAIL) + command = bridge.hook_argv(tmp_path, shell)[-1] assert command.endswith("'${env:CLAUDE_PROJECT_DIR}_x'") @@ -794,7 +714,8 @@ def fault_on_second(*args): assert result[kept[0]] == kept[1] -# --- The launcher and the registered commands: no decision is a non-blocking 1 on every event. +# --- The launcher and the registered commands: no decision is a non-blocking 1 on every event, +# and so is a block under a PowerShell outer shell. _STUB_BRIDGE = "import os, sys\nsys.exit(int(os.environ['STUB_BRIDGE_EXIT']))\n" @@ -881,8 +802,10 @@ def test_a_registered_command_passes_a_decision_and_maps_no_decision( check=False, timeout=60, ) + if setup == "10" and shell == "pwsh": + expected = 1 # pwsh -Command reports the launcher's exit 2 as 1. assert completed.returncode == expected, (shell, completed.stdout, completed.stderr) - if expected == 1 and setup != "no-repo": # invoke.ps1 ran and reported it. + if expected == 1 and setup not in ("no-repo", "10"): # invoke.ps1 ran and reported it. assert "no decision, not blocking" in json.loads(completed.stdout)["systemMessage"] From 609d646d337f5b25b4bae7355056a4c4b2071c5c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 02:01:43 -0600 Subject: [PATCH 30/51] Codex bridge doc: state the outer-shell limit and cut the tail prose Under a PowerShell outer shell no exit 2 blocks; a JSON deny reaches Codex under every outer shell; a missing pwsh exits 1 there. Cut the tail, the untested shell-coverage claim, the pwsh-cannot-start reasoning, and three statements the code does not hold. BACKLOG #5496 --- docs/CODEX.md | 36 +++++++++++++----------------------- 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 8ada965e6d..e346ba4372 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -34,11 +34,8 @@ that sets `"onFailure": "block"` when it fails: a non-zero exit, a timeout, a command that cannot start, a defect of its own such as an unsupported handler type or shell, or a defect in its group, such as a matcher that is not a valid regex, that keeps it from running. Any other hook failure is a -non-blocking error, except where the PowerShell tail below exits 2. The bridge -reports it on stderr and as a `systemMessage`, ignores that -hook's output, and runs the remaining hooks. A JSON -`permissionDecision` deny from a hook is a decision, not a failure, and is passed -on as before. +non-blocking error, which the bridge reports on stderr and as a `systemMessage`. +A JSON `permissionDecision` deny from a hook is a decision, not a failure. A bridge fault never blocks, on any event. A fault is anything that keeps the bridge from running the hooks: settings that cannot be parsed, a missing session @@ -59,12 +56,13 @@ call that names `hook` as its subcommand, as every registered command does, no decision is reported and maps to a non-blocking exit 1 on every event, never to 2, and never to 0 once `pwsh` has started, except that a help flag prints usage and exits 0. `invoke.ps1` ends its process with -its code, and the command line passes it on, because `pwsh -Command` would -report an exit 2 as 1. This is tested with PowerShell, `cmd` and `sh` as the -outer shell. Codex's documentation does not say which shell runs a hook command. -When `pwsh` itself cannot start, nothing reports it: the line would exit 0 under -Windows PowerShell 5.1, which proceeds as if every hook passed, 9009 under `cmd` -and 127 under `sh`; this is reasoned, not measured. +its code. + +Codex's documentation does not say which shell runs a hook command. Under a +PowerShell outer shell, `pwsh -Command` reports the launcher's exit 2 as a +non-blocking 1, so no exit 2 blocks under it. A hook's JSON deny reaches Codex +under every outer shell. With `pwsh` missing, the line exits 1 under a +PowerShell outer shell. **A future guard that must block when it fails sets `"onFailure": "block"`.** That holds only for a hook the bridge reaches: a @@ -82,18 +80,10 @@ where Claude Code runs it under Git Bash when Git Bash is installed. Command-only hooks use the shell they name. With none, they use pwsh on Windows and bash elsewhere. Structured `command` and `args` avoid shell parsing. The bridge runs a -command-only PowerShell hook under `pwsh -Command` and appends this fixed tail -after it, on new lines: - -```powershell -; -if (-not $?) { try { if ($global:LASTEXITCODE -eq 2) { exit 2 } } catch {}; exit 1 } -``` - -The source is `POWERSHELL_TAIL` in `scripts/codex/bridge.py`. A hook that opens with `[CmdletBinding()]` does not receive the -payload through `$input`. - -Which PowerShell hook shapes block is recorded by the tests in tests/test_codex_bridge.py; read them rather than this page. +command-only PowerShell hook under `pwsh -Command`. A guard +that such a hook runs and that exits 2 is a non-blocking exit 1 there, unless the +hook itself runs `exit 2` or `exit $LASTEXITCODE`. An `args` hook +that runs the guard keeps its exit 2. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. From 1cb9b82e5a152fb44d338daa567b7cb60612ee32 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 02:26:41 -0600 Subject: [PATCH 31/51] Codex bridge doc: cut the claims a PowerShell outer shell makes false Cut only, no new prose. Deleted: a JSON deny reaches Codex under every outer shell (a deny before a later hook's exit 2 is lost there); a hook's exit 2 blocks and so does onFailure block; and the bold advice to rely on onFailure block. Under a PowerShell outer shell every block exits 1, as measured. BACKLOG #5496 --- .codex/config.toml | 3 +-- docs/CODEX.md | 14 ++------------ 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/.codex/config.toml b/.codex/config.toml index a53ede7e14..1954e2425a 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -1,7 +1,6 @@ # Claude Code remains the source of hook policy. The bridge reads it on each event. # A launcher that cannot run the bridge, or a missing pwsh, is a non-blocking error on every event. -# Where PowerShell runs this line, pwsh -Command reports the launcher's exit 2 as a non-blocking 1; -# a hook's JSON deny reaches Codex under every outer shell. +# Where PowerShell runs this line, pwsh -Command reports the launcher's exit 2 as a non-blocking 1. # docs/CODEX.md, "Who decides a block", states the rule. [features] hooks = true diff --git a/docs/CODEX.md b/docs/CODEX.md index e346ba4372..ccd54a9b31 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -29,11 +29,7 @@ claim a failed hook ran. ### Who decides a block -Only a hook blocks. As in Claude Code, a hook's exit 2 blocks. So does a hook -that sets `"onFailure": "block"` when it fails: a non-zero exit, a timeout, a -command that cannot start, a defect of its own such as an unsupported handler -type or shell, or a defect in its group, such as a matcher that is not a valid -regex, that keeps it from running. Any other hook failure is a +Only a hook blocks. Any other hook failure is a non-blocking error, which the bridge reports on stderr and as a `systemMessage`. A JSON `permissionDecision` deny from a hook is a decision, not a failure. @@ -60,15 +56,9 @@ its code. Codex's documentation does not say which shell runs a hook command. Under a PowerShell outer shell, `pwsh -Command` reports the launcher's exit 2 as a -non-blocking 1, so no exit 2 blocks under it. A hook's JSON deny reaches Codex -under every outer shell. With `pwsh` missing, the line exits 1 under a +non-blocking 1, so no exit 2 blocks under it. With `pwsh` missing, the line exits 1 under a PowerShell outer shell. -**A future guard that must block when it fails sets -`"onFailure": "block"`.** That holds only for a hook the bridge reaches: a -launcher with no decision, or a bridge fault, such as a payload with no session -id, never blocks. - The bridge differs from Claude Code in at least four ways. It runs an event's hooks one after another, where Claude Code runs them in parallel. Exit 2 stops the remaining hooks, and the bridge exits 10 on every event, which `invoke.ps1` From 66f5a1ce3b2f6e59e67fae150dd6ccdd55a5d249 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 02:39:48 -0600 Subject: [PATCH 32/51] Codex bridge doc: restore the exit-2 and onFailure sentences Restore-only, word for word from 609d646d33. Their removal made the defect-skip, "any other hook failure" and bridge-fault sentences false on every shell; they hold under sh and cmd, and the PowerShell outer-shell paragraph states the exception. The JSON-deny-under-every- shell claim stays cut. BACKLOG #5496 --- docs/CODEX.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index ccd54a9b31..63690f28ad 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -29,7 +29,11 @@ claim a failed hook ran. ### Who decides a block -Only a hook blocks. Any other hook failure is a +Only a hook blocks. As in Claude Code, a hook's exit 2 blocks. So does a hook +that sets `"onFailure": "block"` when it fails: a non-zero exit, a timeout, a +command that cannot start, a defect of its own such as an unsupported handler +type or shell, or a defect in its group, such as a matcher that is not a valid +regex, that keeps it from running. Any other hook failure is a non-blocking error, which the bridge reports on stderr and as a `systemMessage`. A JSON `permissionDecision` deny from a hook is a decision, not a failure. @@ -59,6 +63,11 @@ PowerShell outer shell, `pwsh -Command` reports the launcher's exit 2 as a non-blocking 1, so no exit 2 blocks under it. With `pwsh` missing, the line exits 1 under a PowerShell outer shell. +**A future guard that must block when it fails sets +`"onFailure": "block"`.** That holds only for a hook the bridge reaches: a +launcher with no decision, or a bridge fault, such as a payload with no session +id, never blocks. + The bridge differs from Claude Code in at least four ways. It runs an event's hooks one after another, where Claude Code runs them in parallel. Exit 2 stops the remaining hooks, and the bridge exits 10 on every event, which `invoke.ps1` From 419bc2eee2c31a430cd536974ec59a12706fb527 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 03:15:11 -0600 Subject: [PATCH 33/51] Codex bridge: restore main's SessionEnd exit and non-object JSON error Two fail-opens against origin/main, from the Lander's hold at 66f5a1ce3b. A SessionEnd hook failure or bridge fault exits non-zero again, since Codex reads no SessionEnd output. JSON that is not an object on a tool event raises "Hook JSON output must be an object" again, so it is reported and blocks under onFailure: block. The tail, the launcher line and the other paths are unchanged. BACKLOG #5496 --- scripts/codex/bridge.py | 10 ++++++++-- tests/test_codex_bridge.py | 35 +++++++++++++++++++++++++++++++---- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index a2023f1c56..18c298c321 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -272,7 +272,7 @@ def group_selected(group: dict, discriminator: set[str] | None) -> bool: def run_hook(root: Path, stdin: bytes | str | None = None, event: str = "") -> int: - """Decide one Codex hook event: 0 to proceed or 2 to block, never anything else. + """Decide one Codex hook event: 0 to proceed, 2 to block, or 1 for a reported SessionEnd failure. With no stdin given, the payload is read from this process's stdin as UTF-8 bytes; the text stream would decode it with the console code page. `event` is the event Codex registered. @@ -302,6 +302,10 @@ def run_hook(root: Path, stdin: bytes | str | None = None, event: str = "") -> i merge_output(result, {"systemMessage": message}) if result: print(json.dumps(result)) + # Codex reads no SessionEnd output, so a reported failure there exits non-zero, as on main. + reported = str(result.get("systemMessage", "")).splitlines() + if event.lower() == "sessionend" and any(m.endswith("(not blocking)") for m in reported): + return 1 return 0 @@ -352,6 +356,8 @@ def run_one_hook(root: Path, payload: dict, env: dict[str, str], hook: dict, res update = None if not isinstance(update, dict): if event not in PLAIN_CONTEXT_EVENTS: + if update is not None: # JSON that is not an object is a hook defect, as on main. + raise ValueError("Hook JSON output must be an object") print(output, file=sys.stderr) return output = output.replace( @@ -456,7 +462,7 @@ def main() -> int: hook_parser = argparse.ArgumentParser(prog="bridge.py hook", allow_abbrev=False) hook_parser.add_argument("--event", default="", help="the event Codex registered") event = hook_parser.parse_args(rest).event - return BLOCK_EXIT if run_hook(ROOT, None, event) == 2 else 0 + return {2: BLOCK_EXIT, 1: 1}.get(run_hook(ROOT, None, event), 0) if args.mode == "doctor": config = json.loads((ROOT / ".claude/settings.json").read_text(encoding="utf-8-sig")) for event in config.get("hooks", {}): diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index e40933b620..606768f901 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -279,10 +279,15 @@ def test_plain_or_non_object_prompt_hook_output_becomes_context(bridge, tmp_path assert result["hookSpecificOutput"]["additionalContext"] == stdout -def test_non_object_json_on_a_tool_event_is_not_a_block(bridge, tmp_path, capsys): - settings(tmp_path, [handler("3")]) - assert bridge.dispatch(tmp_path, BASH_CALL) == {} - assert "3" in capsys.readouterr().err +@pytest.mark.parametrize("stdout", ["3", "[1]", '"s"', "true"]) +def test_non_object_json_on_a_tool_event_is_a_reported_hook_defect(bridge, tmp_path, stdout): + """As on main: JSON that is not an object is an error, and blocks only under onFailure.""" + settings(tmp_path, [handler(stdout)]) + result = bridge.dispatch(tmp_path, BASH_CALL) + assert "Hook JSON output must be an object" in result["systemMessage"], result + settings(tmp_path, [{**handler(stdout), "onFailure": "block"}]) + with pytest.raises(bridge.HookBlocked): + bridge.dispatch(tmp_path, BASH_CALL) def test_a_command_only_hook_defaults_to_pwsh_on_windows_else_bash(bridge, tmp_path, monkeypatch): @@ -881,6 +886,28 @@ def test_hook_mode_exits_the_block_code_only_for_a_decision(bridge, tmp_path, mo assert stopped.value.code == 2 +@pytest.mark.parametrize( + ("hooks", "expected"), + [ + ([exits(1)], 1), + ([handler("[1]")], 1), + ("not a list", 1), + (None, 1), + ([handler("{}")], 0), + ], + ids=["failing-hook", "non-object-json", "defective-group", "fault", "clean"], +) +def test_a_session_end_failure_exits_non_zero(bridge, tmp_path, monkeypatch, hooks, expected): + """Codex reads no SessionEnd output, so a reported failure exits non-zero, as on main.""" + (tmp_path / ".claude").mkdir() + group = [{"matcher": "", "hooks": hooks}] if isinstance(hooks, list) else hooks + text = "{not json" if hooks is None else json.dumps({"hooks": {"SessionEnd": group}}) + (tmp_path / ".claude/settings.json").write_text(text) + payload = json.dumps({"session_id": "x", "hook_event_name": "SessionEnd", "reason": "exit"}) + argv = ["hook", "--event", "SessionEnd"] + assert _main(bridge, monkeypatch, tmp_path, argv, payload.encode()) == expected + + def test_run_mode_leaves_a_target_scripts_own_event_flag(bridge, monkeypatch): calls: list[list[str]] = [] From 6467ff99b0c85d1b661fb0fa6e6142d2c6ae2299 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 03:17:49 -0600 Subject: [PATCH 34/51] Codex bridge doc: shrink "Who decides a block" to what holds Per the Lander's hold at 66f5a1ce3b: cut the exit-2 and onFailure blocking claims, the onFailure guard advice, the timeout and "the hooks or groups after it still run" claims, and the 90-second outer limit. The section keeps a few true sentences and points to tests/test_codex_bridge.py for the exit codes. BACKLOG #5496 --- docs/CODEX.md | 49 +++++++++---------------------------------------- 1 file changed, 9 insertions(+), 40 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 63690f28ad..b43f5a91a6 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -29,51 +29,20 @@ claim a failed hook ran. ### Who decides a block -Only a hook blocks. As in Claude Code, a hook's exit 2 blocks. So does a hook -that sets `"onFailure": "block"` when it fails: a non-zero exit, a timeout, a -command that cannot start, a defect of its own such as an unsupported handler -type or shell, or a defect in its group, such as a matcher that is not a valid -regex, that keeps it from running. Any other hook failure is a -non-blocking error, which the bridge reports on stderr and as a `systemMessage`. -A JSON `permissionDecision` deny from a hook is a decision, not a failure. - -A bridge fault never blocks, on any event. A fault is anything that keeps the -bridge from running the hooks: settings that cannot be parsed, a missing session -id, a payload that cannot be read as UTF-8 JSON, a payload whose -`hook_event_name` differs from the registered event in more than case, or any -other exception. The bridge reports it on stderr and as a `systemMessage`, and -keeps any decision already gathered, such as an earlier hook's deny. A defect is -judged where it belongs. A hook's own defect is reported and that hook skipped; -the hooks before it have already run, and the hooks after it still run. A defect -in a group, such as its matcher, is reported and that group skipped, and the -groups after it still run. - -A launcher that cannot run the bridge never blocks either. In hook mode the -bridge exits 0 to proceed or 10 to block, and `invoke.ps1` turns 10 into 2. Any -other outcome is no decision: another bridge exit, including the 2 that Python -and argparse exit with, a missing `.venv`, or a checkout `git` cannot find. On a -call that names `hook` as its subcommand, as every registered command does, no -decision is reported and maps to a non-blocking exit 1 on every event, never to -2, and never to 0 once `pwsh` has started, except that a help flag prints usage -and exits 0. `invoke.ps1` ends its process with -its code. - -Codex's documentation does not say which shell runs a hook command. Under a -PowerShell outer shell, `pwsh -Command` reports the launcher's exit 2 as a -non-blocking 1, so no exit 2 blocks under it. With `pwsh` missing, the line exits 1 under a -PowerShell outer shell. - -**A future guard that must block when it fails sets -`"onFailure": "block"`.** That holds only for a hook the bridge reaches: a -launcher with no decision, or a bridge fault, such as a payload with no session -id, never blocks. +Only a hook blocks. A bridge fault, which the bridge reports on stderr and as a +`systemMessage`, never blocks. In hook mode the bridge exits 0 to proceed or 10 +to block, and `invoke.ps1` turns 10 into 2 and any other non-zero bridge exit +into a non-blocking 1. Codex's documentation does not say which shell runs a +hook command. Under a PowerShell outer shell, `pwsh -Command` reports the +launcher's exit 2 as a non-blocking 1, so no exit 2 blocks under it. With `pwsh` +missing, the line exits 1 under a PowerShell outer shell. The tests in +`tests/test_codex_bridge.py` pin the exit codes. The bridge differs from Claude Code in at least four ways. It runs an event's hooks one after another, where Claude Code runs them in parallel. Exit 2 stops the remaining hooks, and the bridge exits 10 on every event, which `invoke.ps1` turns into 2, including events where Claude Code only shows the hook's stderr. -Hook chains have a 90-second outer limit, so the timeouts of a long chain add up -against it. On Windows, a command-only hook with no `shell` runs under pwsh, +On Windows, a command-only hook with no `shell` runs under pwsh, where Claude Code runs it under Git Bash when Git Bash is installed. Command-only hooks use the shell they name. With none, they use pwsh on Windows From 2ac3c8853235c04555adb744767074d91971478c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 03:44:57 -0600 Subject: [PATCH 35/51] Codex bridge: null hook output is a non-object error; cut dangling doc pointers Per the Lander's ruling at 6467ff99b0. A "did not parse" sentinel replaces None, so a hook that prints null raises "Hook JSON output must be an object" like any other non-object, and a null row is added. In docs/CODEX.md the closed "exits 0 to proceed or 10 to block" list is cut. The config.toml and invoke.ps1 comments that pointed at "Who decides a block" now point at tests/test_codex_bridge.py. BACKLOG #5496 --- .codex/config.toml | 2 +- docs/CODEX.md | 3 +-- scripts/codex/bridge.py | 7 ++++--- scripts/codex/invoke.ps1 | 2 +- tests/test_codex_bridge.py | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.codex/config.toml b/.codex/config.toml index 1954e2425a..20bbc25a98 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -1,7 +1,7 @@ # Claude Code remains the source of hook policy. The bridge reads it on each event. # A launcher that cannot run the bridge, or a missing pwsh, is a non-blocking error on every event. # Where PowerShell runs this line, pwsh -Command reports the launcher's exit 2 as a non-blocking 1. -# docs/CODEX.md, "Who decides a block", states the rule. +# tests/test_codex_bridge.py pins the exit codes. [features] hooks = true diff --git a/docs/CODEX.md b/docs/CODEX.md index b43f5a91a6..0417ad6acc 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -30,8 +30,7 @@ claim a failed hook ran. ### Who decides a block Only a hook blocks. A bridge fault, which the bridge reports on stderr and as a -`systemMessage`, never blocks. In hook mode the bridge exits 0 to proceed or 10 -to block, and `invoke.ps1` turns 10 into 2 and any other non-zero bridge exit +`systemMessage`, never blocks. In hook mode `invoke.ps1` turns 10 into 2 and any other non-zero bridge exit into a non-blocking 1. Codex's documentation does not say which shell runs a hook command. Under a PowerShell outer shell, `pwsh -Command` reports the launcher's exit 2 as a non-blocking 1, so no exit 2 blocks under it. With `pwsh` diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 18c298c321..64285e86cb 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -350,13 +350,14 @@ def run_one_hook(root: Path, payload: dict, env: dict[str, str], hook: dict, res output = completed.stdout.strip() if not output: return + unparsed = object() # json.loads returns None for "null", so None cannot mean "not JSON". try: - update = json.loads(output) + update: object = json.loads(output) except json.JSONDecodeError: - update = None + update = unparsed if not isinstance(update, dict): if event not in PLAIN_CONTEXT_EVENTS: - if update is not None: # JSON that is not an object is a hook defect, as on main. + if update is not unparsed: # JSON that is not an object is a hook defect, as on main. raise ValueError("Hook JSON output must be an object") print(output, file=sys.stderr) return diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 3ef505abbb..1169970cf1 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -28,7 +28,7 @@ if ($mode -eq 'hook') { # The bridge decides with exit 0, or with 10 (BLOCK_EXIT in bridge.py) for a block, which # becomes 2 here. Anything else, a missing .venv, a crash, or the 2 that Python and argparse # exit with, is no decision: reported, and a non-blocking 1 on every event. - # docs/CODEX.md, "Who decides a block", states the rule. + # tests/test_codex_bridge.py pins the exit codes. # With this preference on, the bridge's block exit 10 would throw and read as no decision. $PSNativeCommandUseErrorActionPreference = $false $code = 1 diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 606768f901..5fd217a621 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -279,7 +279,7 @@ def test_plain_or_non_object_prompt_hook_output_becomes_context(bridge, tmp_path assert result["hookSpecificOutput"]["additionalContext"] == stdout -@pytest.mark.parametrize("stdout", ["3", "[1]", '"s"', "true"]) +@pytest.mark.parametrize("stdout", ["3", "[1]", '"s"', "true", "null"]) def test_non_object_json_on_a_tool_event_is_a_reported_hook_defect(bridge, tmp_path, stdout): """As on main: JSON that is not an object is an error, and blocks only under onFailure.""" settings(tmp_path, [handler(stdout)]) From 617f1262bbdc4de7e2c2ade1b59ae028c18ca41f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 04:05:09 -0600 Subject: [PATCH 36/51] Codex bridge: cut the stale exit-code pointers and closed lists Comments and prose only, per the Lander's ruling at 2ac3c88532. Cut the BLOCK_EXIT comment's pointer to "Who decides a block", the invoke.ps1 "0 to proceed / 10 to block" list with the sentence that depended on it, and the "tests pin the exit codes" claim in config.toml, invoke.ps1 and docs/CODEX.md. BACKLOG #5496 --- .codex/config.toml | 1 - docs/CODEX.md | 3 +-- scripts/codex/bridge.py | 3 +-- scripts/codex/invoke.ps1 | 5 +---- 4 files changed, 3 insertions(+), 9 deletions(-) diff --git a/.codex/config.toml b/.codex/config.toml index 20bbc25a98..7a2a93fb8c 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -1,7 +1,6 @@ # Claude Code remains the source of hook policy. The bridge reads it on each event. # A launcher that cannot run the bridge, or a missing pwsh, is a non-blocking error on every event. # Where PowerShell runs this line, pwsh -Command reports the launcher's exit 2 as a non-blocking 1. -# tests/test_codex_bridge.py pins the exit codes. [features] hooks = true diff --git a/docs/CODEX.md b/docs/CODEX.md index 0417ad6acc..760aa7538e 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -34,8 +34,7 @@ Only a hook blocks. A bridge fault, which the bridge reports on stderr and as a into a non-blocking 1. Codex's documentation does not say which shell runs a hook command. Under a PowerShell outer shell, `pwsh -Command` reports the launcher's exit 2 as a non-blocking 1, so no exit 2 blocks under it. With `pwsh` -missing, the line exits 1 under a PowerShell outer shell. The tests in -`tests/test_codex_bridge.py` pin the exit codes. +missing, the line exits 1 under a PowerShell outer shell. The bridge differs from Claude Code in at least four ways. It runs an event's hooks one after another, where Claude Code runs them in parallel. Exit 2 stops diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 64285e86cb..1669f4cc4d 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -175,8 +175,7 @@ def merge_output(result: dict, update: dict) -> None: # Claude Code adds a hook's plain exit-0 stdout as context for these events only. PLAIN_CONTEXT_EVENTS = ("SessionStart", "UserPromptSubmit") # Hook mode's exit code for run_hook's block. invoke.ps1 turns it into 2 and every other non-zero, -# the interpreter's and argparse's 2 included, into a non-blocking 1. See docs/CODEX.md, "Who -# decides a block". +# the interpreter's and argparse's 2 included, into a non-blocking 1. BLOCK_EXIT = 10 diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 1169970cf1..bf21541379 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -25,10 +25,7 @@ for ($i = 0; $i -lt $args.Count; $i++) { if ($word -notlike '*=*' -and $word.Length -ge 3 -and '--session-id'.StartsWith($word, [StringComparison]::Ordinal)) { $i++ } } if ($mode -eq 'hook') { - # The bridge decides with exit 0, or with 10 (BLOCK_EXIT in bridge.py) for a block, which - # becomes 2 here. Anything else, a missing .venv, a crash, or the 2 that Python and argparse - # exit with, is no decision: reported, and a non-blocking 1 on every event. - # tests/test_codex_bridge.py pins the exit codes. + # 10 (BLOCK_EXIT in bridge.py) becomes 2 here. # With this preference on, the bridge's block exit 10 would throw and read as no decision. $PSNativeCommandUseErrorActionPreference = $false $code = 1 From b5342951410b2a009208f6cd583ae1d4d714a593 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 04:44:37 -0600 Subject: [PATCH 37/51] Codex bridge: restore main's shell fallback, PermissionRequest exit, context JSON error Three fail-opens against origin/main, from the Lander's hold at 617f1262bb. A bash or no-shell command-only hook with no bash found runs where main ran it (sh elsewhere, pwsh on Windows), so its deny lands. A PermissionRequest hook failure, timeout or bridge fault exits non-zero, as on main. Non-object JSON, null included, raises "Hook JSON output must be an object" on SessionStart and UserPromptSubmit too. BACKLOG #5496 --- scripts/codex/bridge.py | 24 ++++++++------ tests/test_codex_bridge.py | 66 ++++++++++++++++++++++++++++++++++---- 2 files changed, 74 insertions(+), 16 deletions(-) diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 1669f4cc4d..bb8c9f107e 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -207,15 +207,17 @@ def hook_argv(root: Path, hook: dict) -> list[str]: ] # A command-only source runs in the shell it names; with none, pwsh on Windows and bash # elsewhere. Environment expansion belongs to that shell; structured args above need no shell - # parsing. + # parsing. With no bash found, it runs where main ran it: pwsh on Windows, sh elsewhere. shell = hook.get("shell") if shell is None: shell = "powershell" if os.name == "nt" else "bash" if shell == "bash": - bash = git_bash() if os.name == "nt" else "bash" - if not bash: - raise FileNotFoundError("Git Bash not found; a shell: bash hook cannot run") - return [bash, "-c", command] + bash = git_bash() if os.name == "nt" else shutil.which("bash") + if bash: + return [bash, "-c", command] + if os.name != "nt": + return ["sh", "-c", command] + shell = "powershell" if shell == "powershell": command = command.replace("${CLAUDE_PROJECT_DIR}", "${env:CLAUDE_PROJECT_DIR}") return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command] @@ -271,7 +273,7 @@ def group_selected(group: dict, discriminator: set[str] | None) -> bool: def run_hook(root: Path, stdin: bytes | str | None = None, event: str = "") -> int: - """Decide one Codex hook event: 0 to proceed, 2 to block, or 1 for a reported SessionEnd failure. + """Decide one Codex hook event: 0 to proceed, 2 to block, or 1 for a failure main exited on. With no stdin given, the payload is read from this process's stdin as UTF-8 bytes; the text stream would decode it with the console code page. `event` is the event Codex registered. @@ -301,9 +303,11 @@ def run_hook(root: Path, stdin: bytes | str | None = None, event: str = "") -> i merge_output(result, {"systemMessage": message}) if result: print(json.dumps(result)) - # Codex reads no SessionEnd output, so a reported failure there exits non-zero, as on main. + # On these events a reported failure exits non-zero, as on main: Codex reads no SessionEnd + # output, and a PermissionRequest failure must not read as a clean pass. reported = str(result.get("systemMessage", "")).splitlines() - if event.lower() == "sessionend" and any(m.endswith("(not blocking)") for m in reported): + failing_events = ("sessionend", "permissionrequest") + if event.lower() in failing_events and any(m.endswith("(not blocking)") for m in reported): return 1 return 0 @@ -355,9 +359,9 @@ def run_one_hook(root: Path, payload: dict, env: dict[str, str], hook: dict, res except json.JSONDecodeError: update = unparsed if not isinstance(update, dict): + if update is not unparsed: # JSON that is not an object is a hook defect, as on main. + raise ValueError("Hook JSON output must be an object") if event not in PLAIN_CONTEXT_EVENTS: - if update is not unparsed: # JSON that is not an object is a hook defect, as on main. - raise ValueError("Hook JSON output must be an object") print(output, file=sys.stderr) return output = output.replace( diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 5fd217a621..3f9f29e50e 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -272,11 +272,23 @@ def test_a_matcher_on_an_event_without_one_is_ignored(bridge, tmp_path): assert result["hookSpecificOutput"]["additionalContext"] == "remember the brief" -@pytest.mark.parametrize("stdout", ["remember the brief", "3", "true", '["a list"]']) -def test_plain_or_non_object_prompt_hook_output_becomes_context(bridge, tmp_path, stdout): - settings(tmp_path, [handler(stdout)], event="UserPromptSubmit", matcher="") +def test_plain_prompt_hook_output_becomes_context(bridge, tmp_path): + settings(tmp_path, [handler("remember the brief")], event="UserPromptSubmit", matcher="") result = bridge.dispatch(tmp_path, {"session_id": "x", "hook_event_name": "UserPromptSubmit"}) - assert result["hookSpecificOutput"]["additionalContext"] == stdout + assert result["hookSpecificOutput"]["additionalContext"] == "remember the brief" + + +@pytest.mark.parametrize("event", ["SessionStart", "UserPromptSubmit"]) +@pytest.mark.parametrize("stdout", ["3", "true", '["a list"]', "null"]) +def test_non_object_json_on_a_context_event_is_a_reported_hook_defect( + bridge, tmp_path, event, stdout +): + """As on main, where these events raised too: non-object JSON is not context.""" + settings(tmp_path, [handler(stdout)], event=event, matcher="") + payload = {"session_id": "x", "hook_event_name": event, "source": "startup"} + result = bridge.dispatch(tmp_path, payload) + assert "Hook JSON output must be an object" in result["systemMessage"], result + assert stdout not in result.get("hookSpecificOutput", {}).get("additionalContext", "") @pytest.mark.parametrize("stdout", ["3", "[1]", '"s"', "true", "null"]) @@ -298,12 +310,29 @@ def test_a_command_only_hook_defaults_to_pwsh_on_windows_else_bash(bridge, tmp_p assert bridge.hook_argv(tmp_path, hook)[0] == "pwsh" assert Path(bridge.hook_argv(tmp_path, {**hook, "shell": "bash"})[0]).stem == "bash" monkeypatch.setattr(bridge, "git_bash", lambda: None) - with pytest.raises(FileNotFoundError): - bridge.hook_argv(tmp_path, {**hook, "shell": "bash"}) + assert bridge.hook_argv(tmp_path, {**hook, "shell": "bash"})[0] == "pwsh" else: assert Path(bridge.hook_argv(tmp_path, hook)[0]).stem == "bash" +@pytest.mark.parametrize("shell", ["bash", None]) +def test_a_bash_hook_with_no_bash_runs_where_main_ran_it(bridge, tmp_path, monkeypatch, shell): + """With no bash found, main's shell runs it (pwsh on Windows, sh elsewhere), so a deny lands.""" + real_which = shutil.which + monkeypatch.setattr(bridge, "git_bash", lambda: None) + monkeypatch.setattr( + bridge.shutil, "which", lambda name, *a, **k: None if name == "bash" else real_which(name) + ) + if shutil.which("pwsh" if os.name == "nt" else "sh") is None: + pytest.skip("needs main's shell") + hook = {"type": "command", "command": "echo '" + json.dumps(DENIAL) + "'"} + if shell: + hook["shell"] = shell + settings(tmp_path, [hook]) + result = bridge.dispatch(tmp_path, BASH_CALL) + assert result["hookSpecificOutput"]["permissionDecision"] == "deny", result + + @pytest.mark.skipif( shutil.which("pwsh") is None or os.name != "nt", reason="requires PowerShell on Windows" ) @@ -908,6 +937,31 @@ def test_a_session_end_failure_exits_non_zero(bridge, tmp_path, monkeypatch, hoo assert _main(bridge, monkeypatch, tmp_path, argv, payload.encode()) == expected +@pytest.mark.parametrize( + ("hooks", "expected"), + [ + ([exits(1)], 1), + ([python("import time; time.sleep(5)", timeout=1)], 1), + (None, 1), + ([handler("{}")], 0), + ], + ids=["failing-hook", "timeout", "fault", "clean"], +) +def test_a_permission_request_failure_exits_non_zero( + bridge, tmp_path, monkeypatch, hooks, expected +): + """As on main: a PermissionRequest failure must not read as a clean pass.""" + (tmp_path / ".claude").mkdir() + group = [{"matcher": "Bash", "hooks": hooks}] + text = "{not json" if hooks is None else json.dumps({"hooks": {"PermissionRequest": group}}) + (tmp_path / ".claude/settings.json").write_text(text) + payload = json.dumps( + {"session_id": "x", "hook_event_name": "PermissionRequest", "tool_name": "Bash"} + ) + argv = ["hook", "--event", "PermissionRequest"] + assert _main(bridge, monkeypatch, tmp_path, argv, payload.encode()) == expected + + def test_run_mode_leaves_a_target_scripts_own_event_flag(bridge, monkeypatch): calls: list[list[str]] = [] From 87aa74b871b28182aaa13735b94d479c1050d87b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 04:50:24 -0600 Subject: [PATCH 38/51] Codex bridge doc: cut the false shell and exit-code sentences Per the Lander's hold at 617f1262bb. Cut: "exits 10 on every event"; "use the shell they name" with the sentence that depended on it; the command-only guard exit-1 sentence and the args-hook "keeps its exit 2" sentence; and invoke.ps1's "as bridge.py's argparse reads it". "At least four ways" becomes "three", the count left after the cut. BACKLOG #5496 --- docs/CODEX.md | 12 +++--------- scripts/codex/invoke.ps1 | 2 +- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 760aa7538e..4cd9b9bb2a 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -36,20 +36,14 @@ hook command. Under a PowerShell outer shell, `pwsh -Command` reports the launcher's exit 2 as a non-blocking 1, so no exit 2 blocks under it. With `pwsh` missing, the line exits 1 under a PowerShell outer shell. -The bridge differs from Claude Code in at least four ways. It runs an event's +The bridge differs from Claude Code in at least three ways. It runs an event's hooks one after another, where Claude Code runs them in parallel. Exit 2 stops -the remaining hooks, and the bridge exits 10 on every event, which `invoke.ps1` -turns into 2, including events where Claude Code only shows the hook's stderr. +the remaining hooks. On Windows, a command-only hook with no `shell` runs under pwsh, where Claude Code runs it under Git Bash when Git Bash is installed. -Command-only hooks use the shell they name. With none, they use pwsh on Windows -and bash elsewhere. Structured `command` and `args` avoid shell parsing. The bridge runs a -command-only PowerShell hook under `pwsh -Command`. A guard -that such a hook runs and that exits 2 is a non-blocking exit 1 there, unless the -hook itself runs `exit 2` or `exit $LASTEXITCODE`. An `args` hook -that runs the guard keeps its exit 2. +command-only PowerShell hook under `pwsh -Command`. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index bf21541379..0670afe952 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -15,7 +15,7 @@ function Resolve-BridgePython { $python } -# The subcommand is the first argument that is not an option, as bridge.py's argparse reads it, so +# The subcommand is the first argument that is not an option, so # `--session-id S hook` is hook mode too and never returns the bridge's raw block code. $mode = $null for ($i = 0; $i -lt $args.Count; $i++) { From 46b4e59166a6bf43647205eaaed08d0753a064a7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 05:13:50 -0600 Subject: [PATCH 39/51] Codex bridge test: a PermissionRequest fault now exits 1, never the block code The fault-on-any-event test pinned exit 0 for PermissionRequest, which the restored main behaviour changes on purpose. It still asserts the fault is reported and never blocks. BACKLOG #5496 --- tests/test_codex_bridge.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 3f9f29e50e..d64b12bcc0 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -672,7 +672,9 @@ def test_a_fault_under_the_tracked_settings_is_reported_and_never_blocks( ) def test_a_fault_on_any_event_is_reported_and_never_blocks(bridge, tmp_path, capsys, event): write_settings(tmp_path, {event: [DENY_GROUP]}) - assert run(bridge, tmp_path, {"hook_event_name": event, "tool_name": "Bash"}, event) == 0 + # A PermissionRequest fault exits non-zero, as on main, but never with the block code. + expected = 1 if event == "PermissionRequest" else 0 + assert run(bridge, tmp_path, {"hook_event_name": event, "tool_name": "Bash"}, event) == expected reported(capsys) From 783bb9f156681b86656999bcd2191883ca1a7dd0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 05:30:40 -0600 Subject: [PATCH 40/51] Revert the Codex bridge rewrite on this branch back to origin/main The Lander's re-cut at 46b4e59166: its fault posture made bridge faults, hook failures and launcher outcomes with no decision less blocking than main. This is `git revert --no-commit origin/main..HEAD` over the 41 branch commits, in one commit. scripts/codex, .codex/config.toml, docs/CODEX.md and tests/test_codex_bridge.py now match origin/main. The fault-posture redesign goes to a new row for an owner ruling. BACKLOG #5496 --- .codex/config.toml | 24 +- docs/CODEX.md | 24 +- scripts/codex/bridge.py | 349 ++++------------ scripts/codex/invoke.ps1 | 49 +-- tests/test_codex_bridge.py | 812 ++----------------------------------- 5 files changed, 134 insertions(+), 1124 deletions(-) diff --git a/.codex/config.toml b/.codex/config.toml index 7a2a93fb8c..06d58d1e21 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -1,71 +1,69 @@ # Claude Code remains the source of hook policy. The bridge reads it on each event. -# A launcher that cannot run the bridge, or a missing pwsh, is a non-blocking error on every event. -# Where PowerShell runs this line, pwsh -Command reports the launcher's exit 2 as a non-blocking 1. [features] hooks = true [[hooks.SessionStart]] [[hooks.SessionStart.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SessionStart"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' timeout = 90 [[hooks.SessionEnd]] [[hooks.SessionEnd.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SessionEnd"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' timeout = 90 [[hooks.PreToolUse]] [[hooks.PreToolUse.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PreToolUse"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' timeout = 90 [[hooks.PostToolUse]] [[hooks.PostToolUse.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PostToolUse"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' timeout = 90 [[hooks.PermissionRequest]] [[hooks.PermissionRequest.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PermissionRequest"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' timeout = 90 [[hooks.UserPromptSubmit]] [[hooks.UserPromptSubmit.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event UserPromptSubmit"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' timeout = 90 [[hooks.PreCompact]] [[hooks.PreCompact.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PreCompact"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' timeout = 90 [[hooks.PostCompact]] [[hooks.PostCompact.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event PostCompact"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' timeout = 90 [[hooks.Stop]] [[hooks.Stop.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event Stop"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' timeout = 90 [[hooks.SubagentStart]] [[hooks.SubagentStart.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SubagentStart"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' timeout = 90 [[hooks.SubagentStop]] [[hooks.SubagentStop.hooks]] type = "command" -command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook --event SubagentStop"''' +command = '''pwsh -NoProfile -NonInteractive -Command "& (Join-Path (git rev-parse --show-toplevel) 'scripts/codex/invoke.ps1') hook"''' timeout = 90 diff --git a/docs/CODEX.md b/docs/CODEX.md index 4cd9b9bb2a..7a99d2674e 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -24,26 +24,10 @@ matches Claude's `PowerShell` name. Patch calls match `apply_patch`, `Edit`, and `Write`. A future hook that needs Claude-specific input fields still needs an adapter; alias matching alone cannot translate an edit payload. -New event types appear as unmapped at startup. The bridge does not silently -claim a failed hook ran. - -### Who decides a block - -Only a hook blocks. A bridge fault, which the bridge reports on stderr and as a -`systemMessage`, never blocks. In hook mode `invoke.ps1` turns 10 into 2 and any other non-zero bridge exit -into a non-blocking 1. Codex's documentation does not say which shell runs a -hook command. Under a PowerShell outer shell, `pwsh -Command` reports the -launcher's exit 2 as a non-blocking 1, so no exit 2 blocks under it. With `pwsh` -missing, the line exits 1 under a PowerShell outer shell. - -The bridge differs from Claude Code in at least three ways. It runs an event's -hooks one after another, where Claude Code runs them in parallel. Exit 2 stops -the remaining hooks. -On Windows, a command-only hook with no `shell` runs under pwsh, -where Claude Code runs it under Git Bash when Git Bash is installed. - -Structured `command` and `args` avoid shell parsing. The bridge runs a -command-only PowerShell hook under `pwsh -Command`. +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. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index bb8c9f107e..8c8b8e1fde 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -13,7 +13,6 @@ import json import os import re -import shutil import subprocess import sys from pathlib import Path @@ -161,246 +160,13 @@ def merge_output(result: dict, update: dict) -> None: target["permissionDecisionReason"] = source["permissionDecisionReason"] -TOOL_EVENTS = ("PreToolUse", "PostToolUse", "PermissionRequest") -# The payload field a matcher is compared with. Claude Code ignores a matcher on every other event, -# UserPromptSubmit and Stop among them, so the bridge runs those groups unconditionally. -MATCHER_FIELDS = { - "SessionStart": "source", - "SessionEnd": "reason", - "PreCompact": "trigger", - "PostCompact": "trigger", - "SubagentStart": "agent_type", - "SubagentStop": "agent_type", -} -# Claude Code adds a hook's plain exit-0 stdout as context for these events only. -PLAIN_CONTEXT_EVENTS = ("SessionStart", "UserPromptSubmit") -# Hook mode's exit code for run_hook's block. invoke.ps1 turns it into 2 and every other non-zero, -# the interpreter's and argparse's 2 included, into a non-blocking 1. -BLOCK_EXIT = 10 - - -class HookBlocked(Exception): - """A deliberate block: a hook exited 2, or failed with onFailure set to block.""" - - -def git_bash() -> str | None: - """The Git Bash that Claude Code runs a bash hook with on Windows, or None if there is none.""" - configured = os.environ.get("CLAUDE_CODE_GIT_BASH_PATH") - if configured: - return configured # As set: a wrong path then fails to start and is reported. - git = shutil.which("git") - if git: - # git.exe sits in Git/cmd, Git/bin or Git/mingw64/bin. Git/bin/bash.exe is the wrapper that - # puts Git's usr/bin and mingw64/bin on PATH, so a hook's own cat or grep resolves. - for parent in Path(git).resolve().parents[:3]: - if (parent / "bin/bash.exe").is_file(): - return str(parent / "bin/bash.exe") - return None - - -def hook_argv(root: Path, hook: dict) -> list[str]: - command = hook["command"] - if "args" in hook: - return [ - str(part).replace("${CLAUDE_PROJECT_DIR}", str(root)) - for part in (command, *hook["args"]) - ] - # A command-only source runs in the shell it names; with none, pwsh on Windows and bash - # elsewhere. Environment expansion belongs to that shell; structured args above need no shell - # parsing. With no bash found, it runs where main ran it: pwsh on Windows, sh elsewhere. - shell = hook.get("shell") - if shell is None: - shell = "powershell" if os.name == "nt" else "bash" - if shell == "bash": - bash = git_bash() if os.name == "nt" else shutil.which("bash") - if bash: - return [bash, "-c", command] - if os.name != "nt": - return ["sh", "-c", command] - shell = "powershell" - if shell == "powershell": - command = command.replace("${CLAUDE_PROJECT_DIR}", "${env:CLAUDE_PROJECT_DIR}") - return ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command] - raise ValueError(f"Unsupported Claude hook shell: {shell}") - - -def hook_failed(result: dict, hook: dict, why: str) -> None: - """Report a failure Claude Code treats as non-blocking, unless the hook opts into blocking.""" - label = hook.get("statusMessage") or " ".join( - [hook["command"], *(str(arg) for arg in hook.get("args", []))] - ) - message = f"Codex bridge: hook {why}: {label}" - if hook.get("onFailure") == "block": - raise HookBlocked(f"{message} (onFailure is block)") - # On stderr and as a systemMessage, since a host may not show the stderr of an exit 0. - print(f"{message} (not blocking)", file=sys.stderr) - merge_output(result, {"systemMessage": f"{message} (not blocking)"}) - - -def print_hook_stderr(text: str) -> None: - if text: - print(text, file=sys.stderr, end="" if text.endswith("\n") else "\n") - - -def read_settings(root: Path) -> dict: - config = json.loads((root / ".claude/settings.json").read_text(encoding="utf-8-sig")) - if not isinstance(config, dict): - raise ValueError(".claude/settings.json must hold a JSON object") - return config - - -def discriminator_for(event: str, payload: dict) -> set[str] | None: - """The values a matcher is compared with, or None where Claude Code ignores the matcher.""" - if event in TOOL_EVENTS: - names = {str(payload.get("tool_name", ""))} - if "Bash" in names: - names.add("PowerShell") - if "apply_patch" in names: - names.update(("Edit", "Write")) - return names - if event in MATCHER_FIELDS: - return {str(payload.get(MATCHER_FIELDS[event]) or "")} - return None - - -def group_selected(group: dict, discriminator: set[str] | None) -> bool: - matcher = group.get("matcher", "") - return ( - discriminator is None - or matcher in ("", "*") - or any(re.search(matcher, value) for value in discriminator) - ) - - -def run_hook(root: Path, stdin: bytes | str | None = None, event: str = "") -> int: - """Decide one Codex hook event: 0 to proceed, 2 to block, or 1 for a failure main exited on. - - With no stdin given, the payload is read from this process's stdin as UTF-8 bytes; the text - stream would decode it with the console code page. `event` is the event Codex registered. - """ - result: dict = {} - try: - if stdin is None: - stdin = sys.stdin.buffer.read() - payload = json.loads(stdin.decode("utf-8-sig") if isinstance(stdin, bytes) else stdin) - if not isinstance(payload, dict): - raise ValueError("the hook payload must be a JSON object") - named = str(payload.get("hook_event_name") or "") - if event: - canonical = next((known for known in EVENTS if known.lower() == event.lower()), None) - if canonical is None or named.lower() != event.lower(): - raise ValueError(f"the payload names event {named!r}, registered as {event!r}") - payload["hook_event_name"] = canonical # The canonical spelling selects the settings. - dispatch(root, payload, result) - except HookBlocked as exc: - print(str(exc), file=sys.stderr) - return 2 - except Exception as exc: # noqa: BLE001 - a bridge fault is reported here, never a block - # A fault never blocks, on any event, but a decision already gathered, such as an - # earlier hook's deny, still stands. - message = f"Codex bridge fault: {type(exc).__name__}: {exc} (not blocking)" - print(message, file=sys.stderr) - merge_output(result, {"systemMessage": message}) - if result: - print(json.dumps(result)) - # On these events a reported failure exits non-zero, as on main: Codex reads no SessionEnd - # output, and a PermissionRequest failure must not read as a clean pass. - reported = str(result.get("systemMessage", "")).splitlines() - failing_events = ("sessionend", "permissionrequest") - if event.lower() in failing_events and any(m.endswith("(not blocking)") for m in reported): - return 1 - return 0 - - -def run_one_hook(root: Path, payload: dict, env: dict[str, str], hook: dict, result: dict) -> None: +def dispatch(root: Path, payload: dict) -> dict: event = payload["hook_event_name"] - if hook.get("type") != "command" or hook.get("async"): - raise ValueError( - f"Unsupported Claude hook transport: {hook.get('type')}, async={hook.get('async', False)}" - ) - # Claude Code's hook contract: exit 2 blocks. Any other failure, a timeout or a command - # that cannot start included, is a non-blocking error unless the hook sets onFailure to - # block, and the remaining hooks still run. Only a successful hook's stdout is read. - try: - completed = subprocess.run( # nosec B603 - trusted repo hook; stdin carries event data - hook_argv(root, hook), - input=json.dumps(payload), - cwd=root, - env=env, - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - timeout=hook.get("timeout", 30), - check=False, - ) - except subprocess.TimeoutExpired as exc: - captured = exc.stderr or "" - if isinstance(captured, bytes): - captured = captured.decode("utf-8", "replace") - print_hook_stderr(captured) - hook_failed(result, hook, f"timed out after {exc.timeout} seconds") - return - except OSError as exc: - hook_failed(result, hook, f"could not start ({exc})") - return - if completed.returncode == 2: - raise HookBlocked(completed.stderr.strip() or "Claude hook blocked this event") - print_hook_stderr(completed.stderr) - if completed.returncode: - hook_failed(result, hook, f"exited {completed.returncode}") - return - output = completed.stdout.strip() - if not output: - return - unparsed = object() # json.loads returns None for "null", so None cannot mean "not JSON". - try: - update: object = json.loads(output) - except json.JSONDecodeError: - update = unparsed - if not isinstance(update, dict): - if update is not unparsed: # JSON that is not an object is a hook defect, as on main. - raise ValueError("Hook JSON output must be an object") - if event not in PLAIN_CONTEXT_EVENTS: - print(output, file=sys.stderr) - return - output = output.replace( - "scripts\\coord\\seat.ps1", - "scripts\\codex\\invoke.ps1 run scripts/coord/seat.ps1", - ) - update = {"hookSpecificOutput": {"hookEventName": event, "additionalContext": output}} - merge_output(result, update) - - -def run_group(root: Path, payload: dict, env: dict[str, str], group: dict, result: dict) -> None: - for hook in group.get("hooks", []): - try: - run_one_hook(root, payload, env, hook, result) - except HookBlocked: - raise - except (AttributeError, KeyError, TypeError, ValueError) as exc: - # A defect belongs to its own hook: it blocks only when that hook set onFailure to - # block. Any other hook's defect is reported and that hook skipped. - message = f"Codex bridge: skipped a hook with a defect: {type(exc).__name__}: {exc}" - if isinstance(hook, dict) and hook.get("onFailure") == "block": - raise HookBlocked(f"{message} (onFailure is block)") from exc - print(f"{message} (not blocking)", file=sys.stderr) - merge_output(result, {"systemMessage": f"{message} (not blocking)"}) - - -def blocks_on_failure(group: dict) -> bool: - hooks = group.get("hooks", []) if isinstance(group, dict) else [] - return any(isinstance(hook, dict) and hook.get("onFailure") == "block" for hook in hooks) - - -def dispatch(root: Path, payload: dict, result: dict | None = None) -> dict: - """Run the event's hooks, gathering their output into `result`, which a fault leaves intact.""" - result = {} if result is None else result - event = payload["hook_event_name"] - config = read_settings(root) - if config.get("disableAllHooks"): - return result env = child_environment(root, payload.get("session_id", "")) + config = json.loads((root / ".claude/settings.json").read_text(encoding="utf-8-sig")) + if config.get("disableAllHooks"): + return {} + result: dict = {} if event == "SessionStart": unknown = set(config.get("hooks", {})) - set(EVENTS) context = ( @@ -416,24 +182,88 @@ def dispatch(root: Path, payload: dict, result: dict | None = None) -> dict: merge_output( result, {"hookSpecificOutput": {"hookEventName": event, "additionalContext": context}} ) - discriminator = discriminator_for(event, payload) + aliases = {str(payload.get("tool_name", ""))} + if "Bash" in aliases: + aliases.add("PowerShell") + if "apply_patch" in aliases: + aliases.update(("Edit", "Write")) + discriminator = ( + aliases + if event in ("PreToolUse", "PostToolUse", "PermissionRequest") + else { + str( + payload.get( + "source", + payload.get("trigger", payload.get("agent_type", payload.get("reason", ""))), + ) + ) + } + ) for group in config.get("hooks", {}).get(event, []): - try: - if group_selected(group, discriminator): - run_group(root, payload, env, group, result) - except HookBlocked: - raise - except (AttributeError, KeyError, TypeError, ValueError, re.error) as exc: - # A defect in the group itself, such as its matcher, keeps all of its hooks from - # running: it is reported and the group skipped, so the groups after it still run, - # unless a hook in it set onFailure to block, which has then failed. - message = ( - f"Codex bridge: skipped a hook group with a defect: {type(exc).__name__}: {exc}" + matcher = group.get("matcher", "") + if matcher not in ("", "*") and not any( + re.search(matcher, value) for value in discriminator + ): + continue + for hook in group.get("hooks", []): + if hook.get("type") != "command" or hook.get("async"): + raise ValueError( + f"Unsupported Claude hook transport: {hook.get('type')}, async={hook.get('async', False)}" + ) + command = hook["command"] + if "args" in hook: + argv = [ + command, + *[str(arg).replace("${CLAUDE_PROJECT_DIR}", str(root)) for arg in hook["args"]], + ] + else: + # Command-only sources use the current platform's shell. Environment expansion + # belongs to that shell; structured args above need no shell parsing. + command = command.replace( + "${CLAUDE_PROJECT_DIR}", + "$env:CLAUDE_PROJECT_DIR" if os.name == "nt" else "${CLAUDE_PROJECT_DIR}", + ) + argv = ( + ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command] + if os.name == "nt" + else ["sh", "-c", command] + ) + completed = subprocess.run( # nosec B603 - trusted repo hook; event data is stdin only + argv, + input=json.dumps(payload), + cwd=root, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=hook.get("timeout", 30), + check=False, ) - if blocks_on_failure(group): - raise HookBlocked(f"{message} (onFailure is block)") from exc - print(f"{message} (not blocking)", file=sys.stderr) - merge_output(result, {"systemMessage": f"{message} (not blocking)"}) + if completed.stderr: + print(completed.stderr, file=sys.stderr, end="") + if completed.returncode == 2: + raise PermissionError(completed.stderr or "Claude hook blocked this event") + completed.check_returncode() + output = completed.stdout.strip() + if not output: + continue + try: + update = json.loads(output) + except json.JSONDecodeError: + if event != "SessionStart": + print(output, file=sys.stderr) + continue + output = output.replace( + "scripts\\coord\\seat.ps1", + "scripts\\codex\\invoke.ps1 run scripts/coord/seat.ps1", + ) + update = { + "hookSpecificOutput": {"hookEventName": event, "additionalContext": output} + } + if not isinstance(update, dict): + raise ValueError("Hook JSON output must be an object") + merge_output(result, update) return result @@ -463,10 +293,11 @@ def main() -> int: print(ROOT / child_environment(ROOT, args.session_id)["KORUS_STATE_REL"]) return 0 if args.mode == "hook": - hook_parser = argparse.ArgumentParser(prog="bridge.py hook", allow_abbrev=False) - hook_parser.add_argument("--event", default="", help="the event Codex registered") - event = hook_parser.parse_args(rest).event - return {2: BLOCK_EXIT, 1: 1}.get(run_hook(ROOT, None, event), 0) + payload = json.load(sys.stdin) + result = dispatch(ROOT, payload) + if result: + print(json.dumps(result)) + return 0 if args.mode == "doctor": config = json.loads((ROOT / ".claude/settings.json").read_text(encoding="utf-8-sig")) for event in config.get("hooks", {}): diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 0670afe952..62f59347b4 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -3,49 +3,12 @@ # No parameter block: forward native arguments, including script-specific flags, unchanged. $ErrorActionPreference = 'Stop' $root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent - -function Resolve-BridgePython { - $python = Join-Path $root '.venv/Scripts/python.exe' - if (-not (Test-Path -LiteralPath $python)) { - $python = Join-Path $root '.venv/bin/python' - } - if (-not (Test-Path -LiteralPath $python)) { - throw 'Create this worktree''s .venv first; see docs/WORKTREES.md.' - } - $python +$python = Join-Path $root '.venv/Scripts/python.exe' +if (-not (Test-Path -LiteralPath $python)) { + $python = Join-Path $root '.venv/bin/python' } - -# The subcommand is the first argument that is not an option, so -# `--session-id S hook` is hook mode too and never returns the bridge's raw block code. -$mode = $null -for ($i = 0; $i -lt $args.Count; $i++) { - $word = [string]$args[$i] - if ($word -notlike '-*') { $mode = $word; break } - # argparse takes any unambiguous prefix of --session-id, and it consumes the next argument. - if ($word -notlike '*=*' -and $word.Length -ge 3 -and '--session-id'.StartsWith($word, [StringComparison]::Ordinal)) { $i++ } +if (-not (Test-Path -LiteralPath $python)) { + throw 'Create this worktree''s .venv first; see docs/WORKTREES.md.' } -if ($mode -eq 'hook') { - # 10 (BLOCK_EXIT in bridge.py) becomes 2 here. - # With this preference on, the bridge's block exit 10 would throw and read as no decision. - $PSNativeCommandUseErrorActionPreference = $false - $code = 1 - $why = '' - try { - & (Resolve-BridgePython) (Join-Path $PSScriptRoot 'bridge.py') @args - if ($LASTEXITCODE -eq 0) { $code = 0 } elseif ($LASTEXITCODE -eq 10) { $code = 2 } - else { $why = "the bridge exited $LASTEXITCODE" } - } catch { - $why = "$_" - } - if ($code -eq 1) { - $message = "Codex bridge launcher: no decision, not blocking: $why" - [Console]::Error.WriteLine($message) - [Console]::Out.WriteLine((@{ systemMessage = $message } | ConvertTo-Json -Compress)) - } - # Codex starts this through pwsh -Command, which reports a script's exit 2 as 1. Ending the - # process keeps the code. Hook mode only: an interactive caller's window must survive `run`. - [Environment]::Exit($code) -} - -& (Resolve-BridgePython) (Join-Path $PSScriptRoot 'bridge.py') @args +& $python (Join-Path $PSScriptRoot 'bridge.py') @args exit $LASTEXITCODE diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index d64b12bcc0..49a8fd8e63 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -5,10 +5,8 @@ from __future__ import annotations import importlib.util -import io import json import os -import re import shutil import subprocess import sys @@ -28,43 +26,16 @@ def bridge(): return module -def settings(root, handlers, event="PreToolUse", matcher="Bash"): +def settings(root, handlers, event="PreToolUse"): (root / ".claude").mkdir(exist_ok=True) (root / ".claude/settings.json").write_text( - json.dumps({"hooks": {event: [{"matcher": matcher, "hooks": handlers}]}}), + json.dumps({"hooks": {event: [{"matcher": "Bash", "hooks": handlers}]}}), encoding="utf-8", ) -def python(source, **extra): - return {"type": "command", "command": sys.executable, "args": ["-c", source], **extra} - - def handler(text): - return python(f"print({text!r})") - - -def exits(code, stdout=""): - return python( - f"print({stdout!r}); import sys; sys.stderr.write('hook says {code}'); sys.exit({code})" - ) - - -DENIAL = { - "hookSpecificOutput": { - "hookEventName": "PreToolUse", - "permissionDecision": "deny", - "permissionDecisionReason": "later hook ran", - } -} -BASH_CALL = {"session_id": "x", "hook_event_name": "PreToolUse", "tool_name": "Bash"} - - -def assert_denied_with_notice(result, notice): - """The later hook's denial survived, and the failure reached the JSON Codex reads.""" - assert result["hookSpecificOutput"] == DENIAL["hookSpecificOutput"] - assert notice in result["systemMessage"] - assert "(not blocking)" in result["systemMessage"] + return {"type": "command", "command": sys.executable, "args": ["-c", f"print({text!r})"]} def test_reads_current_source_each_time_and_preserves_denial(bridge, tmp_path): @@ -121,303 +92,29 @@ def test_missing_session_is_error(bridge, tmp_path): def test_new_unsupported_hook_is_reported(bridge, tmp_path): - payload = {"session_id": "x", "hook_event_name": "PreToolUse", "tool_name": "Bash"} settings(tmp_path, [{"type": "prompt", "prompt": "review"}]) - # In an advisory group it is reported and the group skipped. - assert "prompt" in bridge.dispatch(tmp_path, payload)["systemMessage"] - # A hook that set onFailure to block has failed, so it blocks. - settings(tmp_path, [{"type": "prompt", "prompt": "review", "onFailure": "block"}]) - with pytest.raises(bridge.HookBlocked, match="prompt"): - bridge.dispatch(tmp_path, payload) - - -def test_hook_timeout_is_reported_without_blocking_later_hooks(bridge, tmp_path, capsys): - """Claude Code treats a timed-out hook as a non-blocking error, and so must the bridge.""" - slow = python("import time; time.sleep(5)", timeout=0.1, statusMessage="the slow hook") - settings(tmp_path, [slow, handler(json.dumps(DENIAL))]) - notice = "timed out after 0.1 seconds: the slow hook (not blocking)" - assert_denied_with_notice(bridge.dispatch(tmp_path, BASH_CALL), notice) - assert notice in capsys.readouterr().err - - -@pytest.mark.parametrize("code", [1, 3, 127]) -def test_non_blocking_exit_is_reported_and_later_hooks_still_run(bridge, tmp_path, capsys, code): - """Only exit 2 blocks. Another non-zero exit must neither block nor stop the hooks after it.""" - # The failing hook's stdout is not read, so its "continue": false must not reach the result. - settings(tmp_path, [exits(code, stdout='{"continue": false}'), handler(json.dumps(DENIAL))]) - assert_denied_with_notice(bridge.dispatch(tmp_path, BASH_CALL), f"exited {code}: ") - err = capsys.readouterr().err - # The hook's own stderr ends its line, so the bridge's report starts a fresh one. - assert f"hook says {code}\nCodex bridge: hook exited {code}: " in err - - -def test_unstartable_hook_is_reported_without_blocking(bridge, tmp_path): - missing = {"type": "command", "command": str(tmp_path / "no-such-hook.exe"), "args": []} - settings(tmp_path, [missing, handler(json.dumps(DENIAL))]) - assert_denied_with_notice(bridge.dispatch(tmp_path, BASH_CALL), "could not start") - - -@pytest.mark.parametrize( - "failing", - [exits(1), python("import time; time.sleep(5)", timeout=0.1)], - ids=["exit-1", "timeout"], -) -def test_on_failure_block_turns_a_non_blocking_failure_into_a_block(bridge, tmp_path, failing): - settings(tmp_path, [{**failing, "onFailure": "block"}, handler(json.dumps(DENIAL))]) - with pytest.raises(bridge.HookBlocked, match="onFailure is block"): - bridge.dispatch(tmp_path, BASH_CALL) - - -def test_exit_2_blocks_and_stops_the_remaining_hooks(bridge, tmp_path, capsys): - marker = tmp_path / "later-hook-ran" - settings(tmp_path, [exits(2), python(f"open({str(marker)!r}, 'w').close()")]) - with pytest.raises(bridge.HookBlocked, match="hook says 2"): - bridge.dispatch(tmp_path, BASH_CALL) - assert not marker.exists() - # The reason travels once, in the HookBlocked run_hook prints, not also as raw stderr. - assert "hook says 2" not in capsys.readouterr().err - - -DENY_JSON = ( - '{"hookSpecificOutput": {"hookEventName": "PreToolUse", ' - '"permissionDecision": "deny", "permissionDecisionReason": "no"}}' -) - - -@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") -@pytest.mark.parametrize( - ("command", "outcome"), - [ - ("Write-Output 'x' | Out-Null; exit 2", "block"), - ("try {{ Get-Item -LiteralPath 'no-such-item-b4' -EA Stop }} catch {{}}; exit 2", "block"), - ("trap {{ exit 2 }}; throw 'boom'", "block"), - ("$p = $input | ConvertFrom-Json; if ($p.tool_name -eq 'Bash') {{ exit 2 }}", "block"), - ("& '{py}' -c 'import sys; sys.exit(2)'; exit $LASTEXITCODE", "block"), - # pwsh -Command reports a native or script exit 2 that no explicit exit names as 1. - ("& '{py}' -c 'import sys; sys.exit(2)'", "exit-1"), - ("& ./guard.ps1", "exit-1"), - ("Get-Item -LiteralPath 'no-such-item-b4'", "exit-1"), - ("if ($true) {{ return }}; exit 2", "allow"), - ("begin {{ }}\nend {{ exit 2 }}", "block"), - ( - "begin {{ }}\nend {{ Write-Output '" - + DENY_JSON.replace("{", "{{").replace("}", "}}") - + "' }}", - "deny", - ), - ], - ids=[ - "explicit-exit-2", - "handled-error-then-exit-2", - "trap-exit-2", - "reads-input", - "native-2-passed-on", - "native-2-last", - "guard-exits-2", - "failed-cmdlet", - "early-return", - "named-blocks", - "named-blocks-deny", - ], -) -def test_a_command_only_powershell_hook_blocks_on_an_explicit_exit_2_or_a_deny( - bridge, tmp_path, command, outcome -): - (tmp_path / "guard.ps1").write_text("exit 2\n", encoding="utf-8") - hook = {"type": "command", "shell": "powershell", "command": command.format(py=sys.executable)} - settings(tmp_path, [hook]) - if outcome == "block": - with pytest.raises(bridge.HookBlocked): - bridge.dispatch(tmp_path, BASH_CALL) - return - result = bridge.dispatch(tmp_path, BASH_CALL) - if outcome == "allow": - assert result == {}, result - elif outcome == "deny": - assert result["hookSpecificOutput"]["permissionDecision"] == "deny", result - else: - assert "hook exited 1: " in result["systemMessage"], result - - -@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") -def test_an_args_form_hook_blocks_when_the_guard_it_runs_exits_2(bridge, tmp_path): - (tmp_path / "guard.ps1").write_text("exit 2\n", encoding="utf-8") - hook = {"type": "command", "command": "pwsh", "args": ["-NoProfile", "-File", "guard.ps1"]} - settings(tmp_path, [hook]) - with pytest.raises(bridge.HookBlocked): - bridge.dispatch(tmp_path, BASH_CALL) - - -def test_project_dir_is_substituted_in_every_form(bridge, tmp_path): - structured = {"type": "command", "command": "${CLAUDE_PROJECT_DIR}/guard", "args": ["a"]} - assert bridge.hook_argv(tmp_path, structured) == [f"{tmp_path}/guard", "a"] - shell = {"type": "command", "shell": "powershell", "command": "'${CLAUDE_PROJECT_DIR}_x'"} - # Braced, so a following name character cannot join the variable name. - command = bridge.hook_argv(tmp_path, shell)[-1] - assert command.endswith("'${env:CLAUDE_PROJECT_DIR}_x'") - - -def test_each_event_matches_its_own_discriminator_field(bridge, tmp_path): - settings(tmp_path, [handler(json.dumps(DENIAL))], event="SubagentStart", matcher="^worker$") - payload = {"session_id": "x", "hook_event_name": "SubagentStart", "agent_type": "worker"} - # A null, or another event's field, must not stand in for SubagentStart's agent_type. - for other in (None, "", "startup"): - assert bridge.dispatch(tmp_path, {**payload, "source": other}) == DENIAL - - -def test_a_matcher_on_an_event_without_one_is_ignored(bridge, tmp_path): - """Claude Code ignores a matcher on UserPromptSubmit, so the bridge must still run the group.""" - settings(tmp_path, [handler("remember the brief")], event="UserPromptSubmit", matcher=".+") - result = bridge.dispatch(tmp_path, {"session_id": "x", "hook_event_name": "UserPromptSubmit"}) - assert result["hookSpecificOutput"]["additionalContext"] == "remember the brief" - - -def test_plain_prompt_hook_output_becomes_context(bridge, tmp_path): - settings(tmp_path, [handler("remember the brief")], event="UserPromptSubmit", matcher="") - result = bridge.dispatch(tmp_path, {"session_id": "x", "hook_event_name": "UserPromptSubmit"}) - assert result["hookSpecificOutput"]["additionalContext"] == "remember the brief" - - -@pytest.mark.parametrize("event", ["SessionStart", "UserPromptSubmit"]) -@pytest.mark.parametrize("stdout", ["3", "true", '["a list"]', "null"]) -def test_non_object_json_on_a_context_event_is_a_reported_hook_defect( - bridge, tmp_path, event, stdout -): - """As on main, where these events raised too: non-object JSON is not context.""" - settings(tmp_path, [handler(stdout)], event=event, matcher="") - payload = {"session_id": "x", "hook_event_name": event, "source": "startup"} - result = bridge.dispatch(tmp_path, payload) - assert "Hook JSON output must be an object" in result["systemMessage"], result - assert stdout not in result.get("hookSpecificOutput", {}).get("additionalContext", "") - - -@pytest.mark.parametrize("stdout", ["3", "[1]", '"s"', "true", "null"]) -def test_non_object_json_on_a_tool_event_is_a_reported_hook_defect(bridge, tmp_path, stdout): - """As on main: JSON that is not an object is an error, and blocks only under onFailure.""" - settings(tmp_path, [handler(stdout)]) - result = bridge.dispatch(tmp_path, BASH_CALL) - assert "Hook JSON output must be an object" in result["systemMessage"], result - settings(tmp_path, [{**handler(stdout), "onFailure": "block"}]) - with pytest.raises(bridge.HookBlocked): - bridge.dispatch(tmp_path, BASH_CALL) - - -def test_a_command_only_hook_defaults_to_pwsh_on_windows_else_bash(bridge, tmp_path, monkeypatch): - """With no shell named, a command-only hook runs under pwsh on Windows and bash elsewhere.""" - hook = {"type": "command", "command": "echo hi"} - monkeypatch.setattr(bridge, "git_bash", lambda: "git/bin/bash.exe") - if os.name == "nt": - assert bridge.hook_argv(tmp_path, hook)[0] == "pwsh" - assert Path(bridge.hook_argv(tmp_path, {**hook, "shell": "bash"})[0]).stem == "bash" - monkeypatch.setattr(bridge, "git_bash", lambda: None) - assert bridge.hook_argv(tmp_path, {**hook, "shell": "bash"})[0] == "pwsh" - else: - assert Path(bridge.hook_argv(tmp_path, hook)[0]).stem == "bash" + with pytest.raises(ValueError, match="prompt"): + bridge.dispatch( + tmp_path, {"session_id": "x", "hook_event_name": "PreToolUse", "tool_name": "Bash"} + ) -@pytest.mark.parametrize("shell", ["bash", None]) -def test_a_bash_hook_with_no_bash_runs_where_main_ran_it(bridge, tmp_path, monkeypatch, shell): - """With no bash found, main's shell runs it (pwsh on Windows, sh elsewhere), so a deny lands.""" - real_which = shutil.which - monkeypatch.setattr(bridge, "git_bash", lambda: None) - monkeypatch.setattr( - bridge.shutil, "which", lambda name, *a, **k: None if name == "bash" else real_which(name) +def test_hook_timeout_is_reported(bridge, tmp_path): + settings( + tmp_path, + [ + { + "type": "command", + "command": sys.executable, + "args": ["-c", "import time; time.sleep(5)"], + "timeout": 0.1, + } + ], ) - if shutil.which("pwsh" if os.name == "nt" else "sh") is None: - pytest.skip("needs main's shell") - hook = {"type": "command", "command": "echo '" + json.dumps(DENIAL) + "'"} - if shell: - hook["shell"] = shell - settings(tmp_path, [hook]) - result = bridge.dispatch(tmp_path, BASH_CALL) - assert result["hookSpecificOutput"]["permissionDecision"] == "deny", result - - -@pytest.mark.skipif( - shutil.which("pwsh") is None or os.name != "nt", reason="requires PowerShell on Windows" -) -def test_a_no_shell_hook_runs_under_pwsh_on_windows(bridge, tmp_path): - settings(tmp_path, [{"type": "command", "command": 'trap { exit 2 }; throw "boom"'}]) - with pytest.raises(bridge.HookBlocked): - bridge.dispatch(tmp_path, BASH_CALL) - - -# Values a tracked matcher is tried against, per event's discriminator. A new matcher that selects -# none of them fails the test below and names itself, rather than going undispatched. -_TOOL_NAMES = ("Bash", "PowerShell", "Agent", "Task", "Workflow", "EnterWorktree", "Edit", "Write") -_FIELD_VALUES = ("startup", "resume", "clear", "compact", "manual", "auto", "logout", "other") - - -def _tracked_settings(): - return json.loads((ROOT / ".claude/settings.json").read_text(encoding="utf-8-sig")) - - -def test_every_hook_in_the_tracked_settings_dispatches_to_a_runnable_argv( - bridge, tmp_path, monkeypatch -): - """Read the tracked .claude/settings.json, not a synthetic one, and dispatch each group. - - The subprocess is recorded, not run: the tracked hooks write the live seat registry. - """ - tracked = _tracked_settings() - (tmp_path / ".claude").mkdir() - (tmp_path / ".claude/settings.json").write_text(json.dumps(tracked), encoding="utf-8") - calls: list[list[str]] = [] - - def record(argv, **kwargs): - calls.append(argv) - return subprocess.CompletedProcess(argv, 0, "", "") - - monkeypatch.setattr(bridge.subprocess, "run", record) - monkeypatch.setattr(bridge, "git_bash", lambda: "git/bin/bash.exe") - assert tracked["hooks"], "the tracked settings wire no hooks; this test proves nothing" - for event, groups in tracked["hooks"].items(): - assert event in bridge.EVENTS, f"{event} has no Codex adapter" - for group in groups: - payload = {"session_id": "x", "hook_event_name": event} - matcher = group.get("matcher", "") - if matcher not in ("", "*"): - if event in bridge.TOOL_EVENTS: - field, values = "tool_name", _TOOL_NAMES - else: - field, values = bridge.MATCHER_FIELDS.get(event, "ignored"), _FIELD_VALUES - names = [value for value in values if re.search(matcher, value)] - assert names, f"no value in the test's lists selects {event} matcher {matcher!r}" - payload[field] = names[0] - calls.clear() - bridge.dispatch(tmp_path, payload) - for hook in group["hooks"]: - argv = bridge.hook_argv(tmp_path, hook) - assert argv in calls, (event, hook["command"], calls) - if "args" in hook: - assert argv[0] == hook["command"] - assert not any("${CLAUDE_PROJECT_DIR}" in arg for arg in argv), argv - else: - assert hook.get("shell") in (None, "bash", "powershell"), hook - if hook.get("shell", "bash") == "bash": - assert Path(argv[0]).stem == "bash" - assert argv[1:] == ["-c", hook["command"]] - - -def test_tracked_command_only_hooks_run_cleanly_through_their_shell(bridge, tmp_path, capsys): - """Run each tracked command-only hook for real. The bridge strips CLAUDE_*, so the cloud-only - gate exits 0 before its script runs. On Windows the wrong shell, pwsh, cannot parse it and - exits 1; on POSIX sh would exit 0 too, so the argv test above is the control there.""" - hooks = [ - hook - for groups in _tracked_settings()["hooks"].values() - for group in groups - for hook in group["hooks"] - if "args" not in hook - ] - if not hooks: - pytest.skip("the tracked settings carry no command-only hook") - if os.name == "nt" and bridge.git_bash() is None: - pytest.skip("Git Bash is not installed") - for hook in hooks: - settings(tmp_path, [hook], event="SessionStart", matcher="") - bridge.dispatch(tmp_path, {"session_id": "x", "hook_event_name": "SessionStart"}) - assert "not blocking" not in capsys.readouterr().err, hook["command"] + with pytest.raises(subprocess.TimeoutExpired): + bridge.dispatch( + tmp_path, {"session_id": "x", "hook_event_name": "PreToolUse", "tool_name": "Bash"} + ) @pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") @@ -596,10 +293,7 @@ def test_registered_command_runs_from_a_subdirectory(tmp_path): root = tmp_path / "repo with spaces" scripts = root / "scripts/codex" scripts.mkdir(parents=True) - # Like the real launcher in hook mode, it ends the process with its decision. - (scripts / "invoke.ps1").write_text( - "[Console]::Out.Write([Console]::In.ReadToEnd()); [Environment]::Exit(0)\n" - ) + (scripts / "invoke.ps1").write_text("[Console]::Out.Write([Console]::In.ReadToEnd())\n") subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) config = tomllib.loads((ROOT / ".codex/config.toml").read_text()) assert set(config["hooks"]) == { @@ -626,463 +320,3 @@ def test_registered_command_runs_from_a_subdirectory(tmp_path): timeout=20, ) assert json.loads(completed.stdout) == {"probe": True} - - -# --- Who decides a block: only a hook. A bridge fault or a launcher with no decision never blocks. - -UNSUPPORTED = {"type": "prompt", "prompt": "review"} -DENY_GROUP = {"matcher": "^(Bash|PowerShell)$", "hooks": [handler(json.dumps(DENIAL))]} - - -def write_settings(root, hooks): - (root / ".claude").mkdir(exist_ok=True) - (root / ".claude/settings.json").write_text(json.dumps({"hooks": hooks}), encoding="utf-8") - - -def run(bridge, root, payload, event=""): - text = payload if isinstance(payload, str) else json.dumps(payload) - return bridge.run_hook(root, text, event) - - -def reported(capsys, text="Codex bridge fault"): - """The fault reached stderr and the systemMessage Codex reads; returns the printed result.""" - captured = capsys.readouterr() - assert text in captured.err - result = json.loads(captured.out.splitlines()[-1]) - assert text in result["systemMessage"] - assert "(not blocking)" in result["systemMessage"] - return result - - -@pytest.mark.parametrize("tool", ["Bash", "PowerShell", "Agent", "EnterWorktree", "Read"]) -def test_a_fault_under_the_tracked_settings_is_reported_and_never_blocks( - bridge, tmp_path, capsys, tool -): - """A missing session id would have blocked the guarded shell call; nothing blocks now.""" - tracked = _tracked_settings() - (tmp_path / ".claude").mkdir() - (tmp_path / ".claude/settings.json").write_text(json.dumps(tracked), encoding="utf-8") - payload = {"hook_event_name": "PreToolUse", "tool_name": tool} # no session_id: a fault - assert run(bridge, tmp_path, payload, "PreToolUse") == 0 - reported(capsys) - - -@pytest.mark.parametrize( - "event", ["PreToolUse", "PermissionRequest", "Stop", "SubagentStop", "SessionStart"] -) -def test_a_fault_on_any_event_is_reported_and_never_blocks(bridge, tmp_path, capsys, event): - write_settings(tmp_path, {event: [DENY_GROUP]}) - # A PermissionRequest fault exits non-zero, as on main, but never with the block code. - expected = 1 if event == "PermissionRequest" else 0 - assert run(bridge, tmp_path, {"hook_event_name": event, "tool_name": "Bash"}, event) == expected - reported(capsys) - - -@pytest.mark.parametrize("event", ["PreToolUse", "Stop", "SessionStart"]) -def test_disabled_hooks_report_nothing_even_without_a_session_id(bridge, tmp_path, capsys, event): - (tmp_path / ".claude").mkdir() - settings_file = tmp_path / ".claude/settings.json" - hooks = {event: [{"matcher": "", "hooks": [exits(2)]}]} - settings_file.write_text(json.dumps({"disableAllHooks": True, "hooks": hooks})) - assert run(bridge, tmp_path, {"hook_event_name": event, "tool_name": "Bash"}, event) == 0 - assert capsys.readouterr() == ("", "") - # The twin: with hooks enabled, the same payload is a reported fault. - settings_file.write_text(json.dumps({"hooks": hooks})) - assert run(bridge, tmp_path, {"hook_event_name": event, "tool_name": "Bash"}, event) == 0 - reported(capsys) - - -@pytest.mark.parametrize("event", ["PreToolUse", "Stop"]) -def test_settings_that_cannot_be_parsed_are_reported_and_never_block( - bridge, tmp_path, capsys, event -): - (tmp_path / ".claude").mkdir() - (tmp_path / ".claude/settings.json").write_text("{ not json", encoding="utf-8") - payload = {"session_id": "x", "hook_event_name": event, "tool_name": "Bash"} - assert run(bridge, tmp_path, payload, event) == 0 - reported(capsys) - - -@pytest.mark.parametrize("text", ["{ not json", '["a list"]', ""]) -@pytest.mark.parametrize("event", ["PreToolUse", "Stop", ""]) -def test_a_payload_that_cannot_be_parsed_is_reported_and_never_blocks( - bridge, tmp_path, capsys, event, text -): - write_settings(tmp_path, {"PreToolUse": [DENY_GROUP]}) - assert run(bridge, tmp_path, text, event) == 0 - reported(capsys) - - -def test_a_deliberate_block_and_a_clean_run_exit_2_and_0(bridge, tmp_path, capsys): - settings(tmp_path, [exits(2)]) - assert run(bridge, tmp_path, BASH_CALL) == 2 - settings(tmp_path, [handler(json.dumps(DENIAL))]) - assert run(bridge, tmp_path, BASH_CALL) == 0 - assert json.loads(capsys.readouterr().out.splitlines()[-1]) == DENIAL - - -@pytest.mark.parametrize( - ("event", "decision", "kept"), - [ - ("PreToolUse", DENIAL, ("hookSpecificOutput", DENIAL["hookSpecificOutput"])), - ("Stop", {"decision": "block", "reason": "not yet"}, ("decision", "block")), - ], - ids=["deny", "stop-block"], -) -def test_a_decision_gathered_before_a_fault_still_stands( - bridge, tmp_path, capsys, monkeypatch, event, decision, kept -): - first = {"matcher": "", "hooks": [handler(json.dumps(decision))]} - write_settings(tmp_path, {event: [first, {"matcher": "", "hooks": [handler("{}")]}]}) - real_run_group = bridge.run_group - calls = [] - - def fault_on_second(*args): - calls.append(args) - if len(calls) == 2: - raise RuntimeError("a fault after a decision") - real_run_group(*args) - - monkeypatch.setattr(bridge, "run_group", fault_on_second) - payload = {"session_id": "x", "hook_event_name": event, "tool_name": "Bash"} - assert run(bridge, tmp_path, payload, event) == 0 - result = reported(capsys, "a fault after a decision") - assert result[kept[0]] == kept[1] - - -# --- The launcher and the registered commands: no decision is a non-blocking 1 on every event, -# and so is a block under a PowerShell outer shell. - -_STUB_BRIDGE = "import os, sys\nsys.exit(int(os.environ['STUB_BRIDGE_EXIT']))\n" - - -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}" - return ["pwsh", "-NoProfile", "-Command", command] if shell == "pwsh" else ["sh", "-c", command] - - -def _link_python(root): - """Give the copied invoke.ps1 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) - - -@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") -@pytest.mark.parametrize("shell", _outer_shells()) -@pytest.mark.parametrize( - ("event", "setup", "expected"), - [ - ("PreToolUse", "0", 0), - ("PreToolUse", "10", 2), - # A launcher that cannot run the bridge would lock Codex out of the fix if it blocked. - ("PreToolUse", "2", 1), - ("PreToolUse", "1", 1), - ("PreToolUse", "no-venv", 1), - ("PreToolUse", "no-repo", 1), - ("Stop", "0", 0), - ("Stop", "10", 2), - # Python's "can't open file", argparse and a crash exit 2: no decision, never a block. - ("Stop", "2", 1), - ("Stop", "1", 1), - ("Stop", "no-venv", 1), - ("Stop", "no-repo", 1), - ], -) -def test_a_registered_command_passes_a_decision_and_maps_no_decision( - tmp_path, shell, event, setup, expected -): - """No decision (a crash, a missing .venv, no repo) is a non-blocking 1 on every event, never 0 - and never 2. The real invoke.ps1 runs a stub bridge.""" - import tomllib - - assert bridge_block_exit() == 10, "invoke.ps1 hardcodes the bridge's BLOCK_EXIT" - - root = tmp_path / "repo" - scripts = root / "scripts/codex" - scripts.mkdir(parents=True) - shutil.copy2(ROOT / "scripts/codex/invoke.ps1", scripts / "invoke.ps1") - (scripts / "bridge.py").write_text(_STUB_BRIDGE) - if setup != "no-venv": - _link_python(root) - if setup != "no-repo": - subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) - hooks = tomllib.loads((ROOT / ".codex/config.toml").read_text())["hooks"][event][0]["hooks"] - env = {**os.environ, "STUB_BRIDGE_EXIT": setup if setup.isdigit() else "0"} - if setup == "no-repo": - env["GIT_CEILING_DIRECTORIES"] = str(tmp_path) - completed = subprocess.run( - _outer_argv(shell, hooks[0]["command"]), - cwd=scripts, - env=env, - input="{}", - text=True, - capture_output=True, - check=False, - timeout=60, - ) - if setup == "10" and shell == "pwsh": - expected = 1 # pwsh -Command reports the launcher's exit 2 as 1. - assert completed.returncode == expected, (shell, completed.stdout, completed.stderr) - if expected == 1 and setup not in ("no-repo", "10"): # invoke.ps1 ran and reported it. - assert "no decision, not blocking" in json.loads(completed.stdout)["systemMessage"] - - -@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") -@pytest.mark.parametrize(("stub", "expected"), [("10", 2), ("0", 0), ("1", 1)]) -def test_the_launcher_ignores_a_callers_native_error_preference(tmp_path, stub, expected): - """With $PSNativeCommandUseErrorActionPreference on, exit 10 would throw and read as 1.""" - root = tmp_path / "repo" - scripts = root / "scripts/codex" - scripts.mkdir(parents=True) - shutil.copy2(ROOT / "scripts/codex/invoke.ps1", scripts / "invoke.ps1") - (scripts / "bridge.py").write_text(_STUB_BRIDGE) - _link_python(root) - command = ( - "$PSNativeCommandUseErrorActionPreference = $true; $ErrorActionPreference = 'Stop'; " - f"& '{scripts / 'invoke.ps1'}' hook --event Stop" - ) - completed = subprocess.run( - ["pwsh", "-NoProfile", "-NonInteractive", "-Command", command], - cwd=scripts, - env={**os.environ, "STUB_BRIDGE_EXIT": stub}, - input="{}", - text=True, - capture_output=True, - check=False, - timeout=60, - ) - assert completed.returncode == expected, (completed.stdout, completed.stderr) - - -def bridge_block_exit(): - spec = importlib.util.spec_from_file_location( - "codex_bridge_c", ROOT / "scripts/codex/bridge.py" - ) - assert spec and spec.loader - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module.BLOCK_EXIT - - -def _main(bridge, monkeypatch, root, argv, stdin_bytes=b"", encoding="cp1252"): - """Run bridge.main() as Codex would, with a text stdin that does not decode as UTF-8.""" - monkeypatch.setattr(bridge, "ROOT", root) - monkeypatch.setattr(sys, "argv", ["bridge.py", *argv]) - monkeypatch.setattr(sys, "stdin", io.TextIOWrapper(io.BytesIO(stdin_bytes), encoding=encoding)) - return bridge.main() - - -def test_hook_mode_reads_the_payload_as_utf8_bytes(bridge, tmp_path, monkeypatch, capsys): - echo = "import json, sys; p = json.load(sys.stdin); print(json.dumps({'reason': p['tool_input']['command']}))" - settings(tmp_path, [python(echo)]) - payload = {**BASH_CALL, "tool_input": {"command": "cat \u2190 \u3053"}} - code = _main( - bridge, - monkeypatch, - tmp_path, - ["hook", "--event", "PreToolUse"], - json.dumps(payload, ensure_ascii=False).encode("utf-8"), - ) - assert code == 0 - assert json.loads(capsys.readouterr().out)["reason"] == "cat \u2190 \u3053" - - -def test_hook_mode_exits_the_block_code_only_for_a_decision(bridge, tmp_path, monkeypatch): - settings(tmp_path, [exits(2)]) - argv = ["hook", "--event", "PreToolUse"] - assert _main(bridge, monkeypatch, tmp_path, argv, json.dumps(BASH_CALL).encode()) == 10 - settings(tmp_path, [handler("{}")]) - assert _main(bridge, monkeypatch, tmp_path, argv, json.dumps(BASH_CALL).encode()) == 0 - # A usage error exits 2 through argparse, which the launcher reads as no decision. - with pytest.raises(SystemExit) as stopped: - _main(bridge, monkeypatch, tmp_path, ["hook", "--evnt", "Stop"], b"{}") - assert stopped.value.code == 2 - - -@pytest.mark.parametrize( - ("hooks", "expected"), - [ - ([exits(1)], 1), - ([handler("[1]")], 1), - ("not a list", 1), - (None, 1), - ([handler("{}")], 0), - ], - ids=["failing-hook", "non-object-json", "defective-group", "fault", "clean"], -) -def test_a_session_end_failure_exits_non_zero(bridge, tmp_path, monkeypatch, hooks, expected): - """Codex reads no SessionEnd output, so a reported failure exits non-zero, as on main.""" - (tmp_path / ".claude").mkdir() - group = [{"matcher": "", "hooks": hooks}] if isinstance(hooks, list) else hooks - text = "{not json" if hooks is None else json.dumps({"hooks": {"SessionEnd": group}}) - (tmp_path / ".claude/settings.json").write_text(text) - payload = json.dumps({"session_id": "x", "hook_event_name": "SessionEnd", "reason": "exit"}) - argv = ["hook", "--event", "SessionEnd"] - assert _main(bridge, monkeypatch, tmp_path, argv, payload.encode()) == expected - - -@pytest.mark.parametrize( - ("hooks", "expected"), - [ - ([exits(1)], 1), - ([python("import time; time.sleep(5)", timeout=1)], 1), - (None, 1), - ([handler("{}")], 0), - ], - ids=["failing-hook", "timeout", "fault", "clean"], -) -def test_a_permission_request_failure_exits_non_zero( - bridge, tmp_path, monkeypatch, hooks, expected -): - """As on main: a PermissionRequest failure must not read as a clean pass.""" - (tmp_path / ".claude").mkdir() - group = [{"matcher": "Bash", "hooks": hooks}] - text = "{not json" if hooks is None else json.dumps({"hooks": {"PermissionRequest": group}}) - (tmp_path / ".claude/settings.json").write_text(text) - payload = json.dumps( - {"session_id": "x", "hook_event_name": "PermissionRequest", "tool_name": "Bash"} - ) - argv = ["hook", "--event", "PermissionRequest"] - assert _main(bridge, monkeypatch, tmp_path, argv, payload.encode()) == expected - - -def test_run_mode_leaves_a_target_scripts_own_event_flag(bridge, monkeypatch): - calls: list[list[str]] = [] - - def call(argv, **kwargs): - calls.append(argv) - return 0 - - monkeypatch.setattr(bridge.subprocess, "call", call) - argv = ["run", "scripts/codex/bridge.py", "--event", "push", "--even", "x", "--limit", "3"] - assert _main(bridge, monkeypatch, ROOT, [*argv, "--session-id", "s"]) == 0 - assert calls[0][-6:] == ["--event", "push", "--even", "x", "--limit", "3"] - - -@pytest.mark.parametrize( - ("registered", "named"), - [("PreToolUse", "Stop"), ("PreToolUse", None), ("Stop", "PreToolUse"), ("PreToolUze", None)], - ids=["pre-named-stop", "pre-unnamed", "stop-named-pre", "unknown-registration"], -) -def test_a_payload_naming_another_event_is_a_reported_fault( - bridge, tmp_path, capsys, registered, named -): - write_settings(tmp_path, {"PreToolUse": [DENY_GROUP], "Stop": [{"hooks": [exits(2)]}]}) - payload = {"session_id": "x", "tool_name": "Bash"} - if named: - payload["hook_event_name"] = named - if registered == "PreToolUze": - payload["hook_event_name"] = "PreToolUze" - assert run(bridge, tmp_path, payload, registered) == 0 - reported(capsys, "registered as") - - -def test_an_event_name_in_another_case_still_runs_the_hooks(bridge, tmp_path, capsys): - write_settings(tmp_path, {"PreToolUse": [DENY_GROUP]}) - payload = {**BASH_CALL, "hook_event_name": "pretooluse"} - assert run(bridge, tmp_path, payload, "PRETOOLUSE") == 0 - assert json.loads(capsys.readouterr().out) == DENIAL - - -@pytest.mark.parametrize( - "defect", - [{"matcher": "^(Task|Agent|Workflow$|spawn_task"}, {"hooks": [UNSUPPORTED]}], - ids=["bad-matcher", "unsupported-hook"], -) -def test_a_defective_group_is_skipped_and_later_groups_still_run(bridge, tmp_path, capsys, defect): - defective = {"matcher": ".*", "hooks": [handler("{}")], **defect} - write_settings(tmp_path, {"PreToolUse": [defective, DENY_GROUP]}) - assert run(bridge, tmp_path, BASH_CALL, "PreToolUse") == 0 - result = reported(capsys, "with a defect") - assert result["hookSpecificOutput"] == DENIAL["hookSpecificOutput"] - - -def test_an_advisory_hook_defect_beside_an_on_failure_hook_does_not_block(bridge, tmp_path, capsys): - """The defect is the advisory hook's own; the onFailure guard in the same group passed.""" - guard = {**handler(json.dumps(DENIAL)), "onFailure": "block"} - write_settings(tmp_path, {"PreToolUse": [{"matcher": ".*", "hooks": [guard, UNSUPPORTED]}]}) - assert run(bridge, tmp_path, BASH_CALL, "PreToolUse") == 0 - result = reported(capsys, "skipped a hook with a defect") - assert result["hookSpecificOutput"] == DENIAL["hookSpecificOutput"] - - -def test_a_defect_in_the_on_failure_hook_itself_blocks(bridge, tmp_path): - advisory_then_guard = [handler("{}"), {**UNSUPPORTED, "onFailure": "block"}] - write_settings(tmp_path, {"PreToolUse": [{"matcher": ".*", "hooks": advisory_then_guard}]}) - assert run(bridge, tmp_path, BASH_CALL, "PreToolUse") == 2 - - -@pytest.mark.parametrize( - "defect", - [{"matcher": "(["}, {"hooks": [{**UNSUPPORTED, "onFailure": "block"}]}], - ids=["bad-matcher", "unsupported-hook"], -) -def test_a_defective_group_whose_hook_sets_on_failure_block_blocks(bridge, tmp_path, defect): - group = {"matcher": ".*", "hooks": [{**handler("{}"), "onFailure": "block"}], **defect} - # PreToolUse, because Stop ignores a matcher and would never read the bad one. - write_settings(tmp_path, {"PreToolUse": [group]}) - assert run(bridge, tmp_path, BASH_CALL, "PreToolUse") == 2 - - -@pytest.mark.skipif(shutil.which("pwsh") is None, reason="requires PowerShell") -@pytest.mark.parametrize( - ("args", "stub", "expected"), - [ - (["hook", "--event", "Stop"], "10", 2), - (["--session-id", "S", "hook", "--event", "Stop"], "10", 2), - (["--session-id=S", "hook", "--event", "Stop"], "10", 2), - (["--sess", "S", "hook", "--event", "Stop"], "10", 2), - # No decision after options stays a non-blocking 1, never a raw 2. - (["--session-id", "S", "hook", "--event", "Stop"], "2", 1), - # The value of --session-id is not the subcommand, even when it reads hook. - (["--session-id", "hook", "run", "scripts/codex/bridge.py"], "10", 10), - # The twin: a run whose target merely takes the word hook is not hook mode. - (["run", "scripts/codex/bridge.py", "hook"], "10", 10), - ], - ids=[ - "first", - "after-session-id", - "session-id-equals", - "abbreviated-option", - "no-decision-after-options", - "session-id-named-hook", - "run-mode", - ], -) -def test_the_launcher_finds_hook_mode_after_options(tmp_path, args, stub, expected): - """A block reaches Codex as 2 wherever hook is the subcommand, never as the raw 10.""" - root = tmp_path / "repo" - scripts = root / "scripts/codex" - scripts.mkdir(parents=True) - shutil.copy2(ROOT / "scripts/codex/invoke.ps1", scripts / "invoke.ps1") - (scripts / "bridge.py").write_text(_STUB_BRIDGE) - _link_python(root) - completed = subprocess.run( - ["pwsh", "-NoProfile", "-NonInteractive", "-File", str(scripts / "invoke.ps1"), *args], - cwd=scripts, - env={**os.environ, "STUB_BRIDGE_EXIT": stub}, - input="{}", - text=True, - capture_output=True, - check=False, - timeout=60, - ) - assert completed.returncode == expected, (completed.stdout, completed.stderr) From da8c2e2b8c947be1a823a1b570a37e95309bd760 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 05:38:12 -0600 Subject: [PATCH 41/51] Codex bridge: a hook's deliberate exit 2 reaches Codex as 2 The one change the re-cut keeps. On origin/main a hook's exit 2 and every fault both left bridge.py as 2, and pwsh -Command reported each as 1, so no hook could block by exit code. The bridge now exits 10 (BLOCK_EXIT) for a hook's exit 2 only, and invoke.ps1 in hook mode ends its process with 2 for it, which cmd and sh pass to Codex. Every other outcome exits exactly as on main. Tests run the registered line end to end: every fault path exits non-zero under every outer shell, as on main. BACKLOG #5496 --- scripts/codex/bridge.py | 12 +++- scripts/codex/invoke.ps1 | 4 ++ tests/test_codex_bridge.py | 119 +++++++++++++++++++++++++++++++++++++ 3 files changed, 134 insertions(+), 1 deletion(-) diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 8c8b8e1fde..9f507bc221 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -18,6 +18,9 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[2] +# Hook mode's exit code for a hook's deliberate exit 2. invoke.ps1 ends its process with 2 for it, +# since pwsh -Command reports a script's exit 2 as 1. Every other outcome exits as before. +BLOCK_EXIT = 10 EVENTS = ( "SessionStart", "SessionEnd", @@ -115,6 +118,10 @@ def sync_skills( return messages +class HookBlocked(Exception): + """A hook exited 2, which Claude Code reads as a deliberate block.""" + + 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") @@ -243,7 +250,7 @@ def dispatch(root: Path, payload: dict) -> dict: 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: @@ -331,6 +338,9 @@ def main() -> int: if __name__ == "__main__": try: sys.exit(main()) + except HookBlocked as exc: + print(f"Codex bridge: {exc}", file=sys.stderr) + sys.exit(BLOCK_EXIT) except ( OSError, ValueError, diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 62f59347b4..2e49330b1a 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -11,4 +11,8 @@ if (-not (Test-Path -LiteralPath $python)) { throw 'Create this worktree''s .venv first; see docs/WORKTREES.md.' } & $python (Join-Path $PSScriptRoot 'bridge.py') @args +# The bridge exits 10 (BLOCK_EXIT in bridge.py) for a hook's exit 2. Ending the process keeps it as +# 2, which the caller's pwsh -Command would report as 1. Hook mode only, so a caller's window +# survives `run`. +if ($LASTEXITCODE -eq 10 -and $args[0] -eq 'hook') { [Environment]::Exit(2) } exit $LASTEXITCODE diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 49a8fd8e63..35bac498b3 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -320,3 +320,122 @@ 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 stays at least as blocking as on origin/main (a non-zero exit). + +_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] + 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 _run_registered(tmp_path, shell, settings_text, payload=_PAYLOAD, venv=True): + import tomllib + + 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) + config = tomllib.loads((ROOT / ".codex/config.toml").read_text()) + command = config["hooks"]["PreToolUse"][0]["hooks"][0]["command"] + stdin = payload if isinstance(payload, str) else json.dumps(payload) + return subprocess.run( + _outer_argv(shell, command), + cwd=scripts, + input=stdin, + text=True, + capture_output=True, + check=False, + timeout=60, + ) + + +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_blocking_as_main(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 any exit 2 as 1; cmd and sh pass the launcher's 2 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 From d8edd27e4c13332170dfdccd21b56a4a85689daa Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 05:47:48 -0600 Subject: [PATCH 42/51] Codex bridge doc: state where a hook's exit 2 reaches Codex The cut head's one change: a hook's exit 2 reaches Codex as 2 except under a PowerShell outer shell, and Codex does not document which shell runs the line. Cut the 90-second outer-limit sentence, which the Lander's hold of 66f5a1ce3b found false for SessionEnd. BACKLOG #5496 --- docs/CODEX.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 7a99d2674e..82a2372894 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -27,7 +27,9 @@ 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. A hook's exit 2 reaches Codex as exit 2, +except under a PowerShell outer shell, where `pwsh -Command` reports it as 1. +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. From f971ef31e08283da798ef6054625a563e0b0da99 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 07:09:58 -0600 Subject: [PATCH 43/51] Codex bridge exits BLOCK_EXIT only where invoke.ps1 set the block sentinel Repair for the Lander hold on PR 3003 (comment 6948654821), items 1-3. - invoke.ps1 sets MEFOR_CODEX_BLOCK_SENTINEL=1 only when its first argument is `hook`, the condition its 10-to-2 mapping uses, and clears it after the call. - bridge.py pops the sentinel at startup, so no hook or run child inherits it, and exits BLOCK_EXIT on HookBlocked only where it was set; otherwise 2, as on main. A direct `python bridge.py hook` and `invoke.ps1 --session-id x hook` therefore give 2 for a hook's exit 2. - Tests, one row per contract, run red on d8edd27e4c first: the registered line gives 2; a direct bridge hook gives 2 (10 with the sentinel); invoke.ps1 --session-id x hook gives 2; a run child exiting 10 is not remapped; no hook child inherits the sentinel; every fault exits on each launch path with main's exact code. - docs/CODEX.md: cut the false sentence that a hook's exit 2 reaches Codex as 2 (on Windows the bridge's own pwsh -Command wrapper turns a command-only hook's exit 2 into 1), and the sentence that only supported it. Net prose lines: -2. --- docs/CODEX.md | 4 +- scripts/codex/bridge.py | 10 +++- scripts/codex/invoke.ps1 | 9 ++- tests/test_codex_bridge.py | 118 ++++++++++++++++++++++++++++++++++--- 4 files changed, 125 insertions(+), 16 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 82a2372894..74d5f6ee41 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -27,9 +27,7 @@ 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. A hook's exit 2 reaches Codex as exit 2, -except under a PowerShell outer shell, where `pwsh -Command` reports it as 1. -Codex's documentation does not say which shell runs a hook command. +`command` and `args` avoid shell parsing. Only repo settings are imported. Claude's user settings, local settings, account credentials, permission grants, plugins, and status line remain Claude-owned. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 9f507bc221..8337c97a2d 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -18,9 +18,11 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[2] -# Hook mode's exit code for a hook's deliberate exit 2. invoke.ps1 ends its process with 2 for it, -# since pwsh -Command reports a script's exit 2 as 1. Every other outcome exits as before. +# Hook mode's exit code for a hook's deliberate exit 2, used only where invoke.ps1 set +# BLOCK_SENTINEL. invoke.ps1 ends its process with 2 for it, since pwsh -Command reports a script's +# exit 2 as 1. Without the sentinel a hook's exit 2 exits 2, and every other outcome exits as before. BLOCK_EXIT = 10 +BLOCK_SENTINEL = "MEFOR_CODEX_BLOCK_SENTINEL" EVENTS = ( "SessionStart", "SessionEnd", @@ -336,11 +338,13 @@ def main() -> int: if __name__ == "__main__": + # Popped before any child starts, so no hook or run child inherits it. + block_exit = BLOCK_EXIT if os.environ.pop(BLOCK_SENTINEL, None) == "1" else 2 try: sys.exit(main()) except HookBlocked as exc: print(f"Codex bridge: {exc}", file=sys.stderr) - sys.exit(BLOCK_EXIT) + sys.exit(block_exit) except ( OSError, ValueError, diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 2e49330b1a..69e5022281 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -10,9 +10,12 @@ if (-not (Test-Path -LiteralPath $python)) { if (-not (Test-Path -LiteralPath $python)) { throw 'Create this worktree''s .venv first; see docs/WORKTREES.md.' } +# The bridge exits 10 (BLOCK_EXIT in bridge.py) for a hook's exit 2 only where this flag is set, +# and only under the same condition as the mapping below. It pops the flag, so no child sees it. +$env:MEFOR_CODEX_BLOCK_SENTINEL = if ($args[0] -eq 'hook') { '1' } else { $null } & $python (Join-Path $PSScriptRoot 'bridge.py') @args -# The bridge exits 10 (BLOCK_EXIT in bridge.py) for a hook's exit 2. Ending the process keeps it as -# 2, which the caller's pwsh -Command would report as 1. Hook mode only, so a caller's window -# survives `run`. +$env:MEFOR_CODEX_BLOCK_SENTINEL = $null +# 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 ($LASTEXITCODE -eq 10 -and $args[0] -eq 'hook') { [Environment]::Exit(2) } exit $LASTEXITCODE diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 35bac498b3..8121bbf403 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -7,6 +7,7 @@ import importlib.util import json import os +import shlex import shutil import subprocess import sys @@ -349,6 +350,8 @@ def _outer_argv(shell, command): 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] @@ -364,9 +367,7 @@ def _link_python(root): (root / ".venv/bin/python").symlink_to(sys.executable) -def _run_registered(tmp_path, shell, settings_text, payload=_PAYLOAD, venv=True): - import tomllib - +def _make_repo(tmp_path, settings_text, venv=True): root = tmp_path / "repo" scripts = root / "scripts/codex" scripts.mkdir(parents=True) @@ -377,20 +378,32 @@ def _run_registered(tmp_path, shell, settings_text, payload=_PAYLOAD, venv=True) if venv: _link_python(root) subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) - config = tomllib.loads((ROOT / ".codex/config.toml").read_text()) - command = config["hooks"]["PreToolUse"][0]["hooks"][0]["command"] + return root + + +def _launch(argv, cwd, payload=_PAYLOAD, env=None): stdin = payload if isinstance(payload, str) else json.dumps(payload) return subprocess.run( - _outer_argv(shell, command), - cwd=scripts, + 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)}]}}) @@ -439,3 +452,94 @@ def test_a_deny_and_a_clean_run_exit_0(tmp_path, shell): 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 sentinel. invoke.ps1 sets MEFOR_CODEX_BLOCK_SENTINEL only for `hook` as its first +# argument, the condition its 10-to-2 mapping uses; without it a hook's exit 2 exits 2, as on main. + +_SENTINEL = "MEFOR_CODEX_BLOCK_SENTINEL" +_EXIT_2 = _hooks(_py("import sys; sys.exit(2)")) +# A hook that blocks only where it inherited the sentinel, and otherwise allows. +_SEES_SENTINEL = _hooks(_py(f"import os, sys; sys.exit(2 if {_SENTINEL!r} in os.environ else 0)")) +_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 != _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): + invoke = root / "scripts/codex/invoke.ps1" + argv = ["pwsh", "-NoProfile", "-NonInteractive", "-File", str(invoke), *args] + return _launch(argv, root, payload, _env()) + + +@_needs_pwsh +def test_the_registered_line_gives_2_for_a_hooks_exit_2(tmp_path): + completed = _run_registered(tmp_path, "none", _EXIT_2) + assert completed.returncode == 2, completed.stderr + + +def test_a_direct_bridge_hook_gives_2_for_a_hooks_exit_2(tmp_path): + root = _make_repo(tmp_path, _EXIT_2, venv=False) + completed = _direct(root, "hook") + assert completed.returncode == 2, completed.stderr + blocked = _direct(root, "hook", **{_SENTINEL: "1"}) + assert blocked.returncode == 10, blocked.stderr + + +@_needs_pwsh +def test_invoke_with_a_flag_before_hook_gives_2(tmp_path): + root = _make_repo(tmp_path, _EXIT_2) + completed = _invoke_file(root, "--session-id", "x", "hook") + assert completed.returncode == 2, completed.stderr + + +@_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 + direct = _direct(root, "--session-id", "x", "run", "scripts/exit10.py", **{_SENTINEL: "1"}) + assert direct.returncode == 10, direct.stderr + + +@_needs_pwsh +def test_no_hook_child_inherits_the_sentinel(tmp_path): + registered = _run_registered(tmp_path / "registered", "none", _SEES_SENTINEL) + assert registered.returncode == 0, registered.stderr + root = _make_repo(tmp_path / "direct", _SEES_SENTINEL, venv=False) + direct = _direct(root, "hook", **{_SENTINEL: "1"}) + assert direct.returncode == 0, 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} + + +@_needs_pwsh +@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 == "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) + if path == "direct": + completed = _direct(root, "hook", payload=payload, **{_SENTINEL: "1"}) + 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) From 57b3be33b2458646dd7e1c9388c5b5e09b50a14d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 07:34:05 -0600 Subject: [PATCH 44/51] Codex bridge: review round 1 on the block-sentinel repair - invoke.ps1 computes hook mode once (case-sensitive, as argparse is) and clears the sentinel in a finally, so a terminating error cannot leave it in a caller's session. - Comments no longer say only invoke.ps1 can set the sentinel, or that every hook's exit 2 reaches the bridge as 2. - docs/CODEX.md: the cut sentence is rewritten true instead of deleted, since a guard author needs it: on Windows a command-only hook's exit 2 reaches the bridge as 1 and is treated as a failed hook; a structured hook's exit 2 reaches Codex as 2 except under a PowerShell outer shell (measured: none, cmd, pwsh). Net prose lines: +5 against the previous commit. - Tests: positive control for the sentinel probe hook; a `run`-first invoke row; direct-path fault rows no longer skip without pwsh. - Correction to the previous message: it said every test row ran red on d8edd27e4c. Only three did (direct bridge hook, invoke --session-id x hook, sentinel inheritance); the registered-line, run-child and fault rows passed there and pin behaviour the repair must keep. --- docs/CODEX.md | 6 +++++- scripts/codex/bridge.py | 7 ++++--- scripts/codex/invoke.ps1 | 17 +++++++++++------ tests/test_codex_bridge.py | 13 ++++++++++--- 4 files changed, 30 insertions(+), 13 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 74d5f6ee41..2ceb2109c2 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -27,7 +27,11 @@ 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. +`command` and `args` avoid shell parsing. On Windows a command-only hook's exit 2 +does not reach Codex as a block: its `pwsh -Command` reports it as 1, which the +bridge treats as a failed hook. A structured hook's exit 2 reaches Codex as 2, +except where Codex runs the hook line under PowerShell, which reports it as 1. +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. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 8337c97a2d..e44dc3a739 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -18,9 +18,10 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[2] -# Hook mode's exit code for a hook's deliberate exit 2, used only where invoke.ps1 set -# BLOCK_SENTINEL. invoke.ps1 ends its process with 2 for it, since pwsh -Command reports a script's -# exit 2 as 1. Without the sentinel a hook's exit 2 exits 2, and every other outcome exits as before. +# Hook mode's exit code for a hook's deliberate exit 2, used only where BLOCK_SENTINEL is "1". +# invoke.ps1 sets it in hook mode and ends its process with 2 for this code, since pwsh -Command +# reports a script's exit 2 as 1. Without the sentinel a hook's exit 2 exits 2, and every other +# outcome exits as before. BLOCK_EXIT = 10 BLOCK_SENTINEL = "MEFOR_CODEX_BLOCK_SENTINEL" EVENTS = ( diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 69e5022281..6f0a7918d6 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -10,12 +10,17 @@ if (-not (Test-Path -LiteralPath $python)) { if (-not (Test-Path -LiteralPath $python)) { throw 'Create this worktree''s .venv first; see docs/WORKTREES.md.' } -# The bridge exits 10 (BLOCK_EXIT in bridge.py) for a hook's exit 2 only where this flag is set, -# and only under the same condition as the mapping below. It pops the flag, so no child sees it. -$env:MEFOR_CODEX_BLOCK_SENTINEL = if ($args[0] -eq 'hook') { '1' } else { $null } -& $python (Join-Path $PSScriptRoot 'bridge.py') @args -$env:MEFOR_CODEX_BLOCK_SENTINEL = $null +# The bridge exits 10 (BLOCK_EXIT in bridge.py) for a hook block only where this flag is set, and +# it is set only in hook mode, where the mapping below ends the process with 2. The bridge pops it, +# so no child sees it; the finally keeps it out of a caller's session. +$hookMode = $args[0] -ceq 'hook' +$env:MEFOR_CODEX_BLOCK_SENTINEL = if ($hookMode) { '1' } else { $null } +try { + & $python (Join-Path $PSScriptRoot 'bridge.py') @args +} finally { + $env:MEFOR_CODEX_BLOCK_SENTINEL = $null +} # 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 ($LASTEXITCODE -eq 10 -and $args[0] -eq 'hook') { [Environment]::Exit(2) } +if ($hookMode -and $LASTEXITCODE -eq 10) { [Environment]::Exit(2) } exit $LASTEXITCODE diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 8121bbf403..5f156dbb26 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -475,10 +475,10 @@ def _direct(root, *args, payload=_PAYLOAD, **extra): return _launch([sys.executable, str(bridge_py), *args], root, payload, _env(**extra)) -def _invoke_file(root, *args, payload=_PAYLOAD): +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()) + return _launch(argv, root, payload, _env(**extra)) @_needs_pwsh @@ -507,12 +507,18 @@ 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", **{_SENTINEL: "1"}) assert direct.returncode == 10, direct.stderr @_needs_pwsh def test_no_hook_child_inherits_the_sentinel(tmp_path): + # Positive control: the probe hook does block where the sentinel is in its environment. + probe = json.loads(_SEES_SENTINEL)["hooks"]["PreToolUse"][0]["hooks"][0] + seen = subprocess.run([probe["command"], *probe["args"]], env=_env(**{_SENTINEL: "1"})) + assert seen.returncode == 2 registered = _run_registered(tmp_path / "registered", "none", _SEES_SENTINEL) assert registered.returncode == 0, registered.stderr root = _make_repo(tmp_path / "direct", _SEES_SENTINEL, venv=False) @@ -526,11 +532,12 @@ def test_no_hook_child_inherits_the_sentinel(tmp_path): _MAIN_FAULT_EXIT = {"registered": 1, "direct": 2, "invoke": 2} -@_needs_pwsh @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": From e21c7c5b083f400956b2163d26eb134802af7afd Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 08:00:52 -0600 Subject: [PATCH 45/51] Codex bridge: review round 2 on the block-sentinel repair - docs/CODEX.md: the previous rewrite said a Windows command-only hook's exit 2 never blocks, which is false: an `exit 2` in the command text itself reaches the bridge as 2 (measured). The paragraph now names the real split: pwsh -Command reports a child script's or program's exit 2 as 1. Net prose lines: +1 against the previous commit. - Comments in bridge.py and invoke.ps1 say the sentinel is set where `hook` is the first argument, not "in hook mode", which `--session-id x hook` also is. - Direct-path fault rows no longer build a .venv junction, so they do not skip on an interpreter outside a virtualenv. Proposed PR title: unchanged (repair on open PR 3003). Proposed ledger banner: unchanged from PR 3003's own. --- docs/CODEX.md | 11 ++++++----- scripts/codex/bridge.py | 6 +++--- scripts/codex/invoke.ps1 | 4 ++-- tests/test_codex_bridge.py | 2 +- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 2ceb2109c2..2f6dca6c5e 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -27,11 +27,12 @@ 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. On Windows a command-only hook's exit 2 -does not reach Codex as a block: its `pwsh -Command` reports it as 1, which the -bridge treats as a failed hook. A structured hook's exit 2 reaches Codex as 2, -except where Codex runs the hook line under PowerShell, which reports it as 1. -Codex's documentation does not say which shell runs a hook command. +`command` and `args` avoid shell parsing. `pwsh -Command` reports an exit 2 from +a script or program it runs as 1, which the bridge treats as a failed hook, not +a block. So on Windows a command-only hook blocks only through an `exit 2` in its +own text. A block reaches Codex as exit 2, except where Codex runs the hook line +under PowerShell, which reports it as 1. 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. diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index e44dc3a739..d4972c9f3f 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -19,9 +19,9 @@ ROOT = Path(__file__).resolve().parents[2] # Hook mode's exit code for a hook's deliberate exit 2, used only where BLOCK_SENTINEL is "1". -# invoke.ps1 sets it in hook mode and ends its process with 2 for this code, since pwsh -Command -# reports a script's exit 2 as 1. Without the sentinel a hook's exit 2 exits 2, and every other -# outcome exits as before. +# invoke.ps1 sets it where `hook` is its first argument, and ends its process with 2 for this code, +# since pwsh -Command reports a script's exit 2 as 1. Without the sentinel a hook's exit 2 exits 2, +# and every other outcome exits as before. BLOCK_EXIT = 10 BLOCK_SENTINEL = "MEFOR_CODEX_BLOCK_SENTINEL" EVENTS = ( diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 6f0a7918d6..32c6bcdb15 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -11,8 +11,8 @@ if (-not (Test-Path -LiteralPath $python)) { throw 'Create this worktree''s .venv first; see docs/WORKTREES.md.' } # The bridge exits 10 (BLOCK_EXIT in bridge.py) for a hook block only where this flag is set, and -# it is set only in hook mode, where the mapping below ends the process with 2. The bridge pops it, -# so no child sees it; the finally keeps it out of a caller's session. +# it is set only where `hook` is the first argument, where the mapping below ends the process with +# 2. The bridge pops it, so no child sees it; the finally keeps it out of a caller's session. $hookMode = $args[0] -ceq 'hook' $env:MEFOR_CODEX_BLOCK_SENTINEL = if ($hookMode) { '1' } else { $null } try { diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 5f156dbb26..6f4468d91f 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -543,7 +543,7 @@ def test_every_fault_path_exits_as_on_main(tmp_path, path, fault): elif not venv and path == "direct": pytest.skip("the direct path never reads a .venv") else: - root = _make_repo(tmp_path, settings_text, venv) + root = _make_repo(tmp_path, settings_text, venv and path != "direct") if path == "direct": completed = _direct(root, "hook", payload=payload, **{_SENTINEL: "1"}) else: From 002c6430f488b09ed42d51391cb58f12436b49dd Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 08:20:38 -0600 Subject: [PATCH 46/51] docs/CODEX.md: cut the exit-2 delivery sentences, per hold item 3 The final unrepaired review round showed the rewritten sentences were still false: a child's exit 2 under pwsh -Command can read as 0, not only 1, and an exit 2 in the command text is not the only way to block. Hold item 3 said cut, so they are cut. Net prose lines: -4. Proposed PR title: unchanged (repair on open PR 3003). Proposed ledger banner: unchanged from PR 3003's own. --- docs/CODEX.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/docs/CODEX.md b/docs/CODEX.md index 2f6dca6c5e..2defa260c3 100644 --- a/docs/CODEX.md +++ b/docs/CODEX.md @@ -27,11 +27,7 @@ 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. `pwsh -Command` reports an exit 2 from -a script or program it runs as 1, which the bridge treats as a failed hook, not -a block. So on Windows a command-only hook blocks only through an `exit 2` in its -own text. A block reaches Codex as exit 2, except where Codex runs the hook line -under PowerShell, which reports it as 1. Codex's documentation does not say +`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 From c1cb4e806fe0348daa679ab5a85cf83a36b508bd Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 09:45:20 -0600 Subject: [PATCH 47/51] Codex bridge carries the block exit as a --block-exit flag, not an env sentinel Repair for the Lander hold on PR 3003 at 002c6430 (comment 6952638497). 1. invoke.ps1 appends `--block-exit 10` only where `hook` is its first argument (-ceq). bridge.py returns that value on HookBlocked, and 2 when the flag is absent. MEFOR_CODEX_BLOCK_SENTINEL is gone: no setting, clearing, finally or pop, so an inherited variable changes nothing. The flag is bridge argv, so no hook child sees it, and outside hook mode the bridge refuses it before a run child starts. 2. The false bridge.py comment on BLOCK_SENTINEL went with the constant. 3. test_every_fault_path_is_at_least_as_blocking_as_main is renamed ..._is_at_least_as_strict_as_mains_exit_code; the header claims no block. 4. The "pwsh -Command reports any exit 2 as 1" comment now names the case it holds for: a last native program's or script's exit 2. Tests run red at 002c6430 first (3 failed, 81 passed): a direct bridge hook with MEFOR_CODEX_BLOCK_SENTINEL=1 inherited exits 2; --block-exit 10 gives 10; the flag never reaches a run child. The sentinel-inheritance test is dropped. Proposed PR title: unchanged (repair on open PR 3003). Proposed ledger banner: unchanged from PR 3003's own. --- scripts/codex/bridge.py | 23 +++++++------- scripts/codex/invoke.ps1 | 13 +++----- tests/test_codex_bridge.py | 61 ++++++++++++++++++++++---------------- 3 files changed, 51 insertions(+), 46 deletions(-) diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index d4972c9f3f..361db4c65d 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -18,12 +18,6 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[2] -# Hook mode's exit code for a hook's deliberate exit 2, used only where BLOCK_SENTINEL is "1". -# invoke.ps1 sets it where `hook` is its first argument, and ends its process with 2 for this code, -# since pwsh -Command reports a script's exit 2 as 1. Without the sentinel a hook's exit 2 exits 2, -# and every other outcome exits as before. -BLOCK_EXIT = 10 -BLOCK_SENTINEL = "MEFOR_CODEX_BLOCK_SENTINEL" EVENTS = ( "SessionStart", "SessionEnd", @@ -285,7 +279,13 @@ def main() -> int: 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") + # Hook mode's exit code for a hook's exit 2; 2 when absent. invoke.ps1 passes 10, and ends its + # process with 2 for it, since pwsh -Command reports a script's exit 2 as 1. Argv, not the + # environment, so no child or ancestor can supply it. + parser.add_argument("--block-exit", type=int, help=argparse.SUPPRESS) args, rest = parser.parse_known_args() + if args.block_exit is not None and args.mode != "hook": + parser.error("--block-exit applies only to hook mode") if args.mode == "sync-skills": user_skills = user_skill_directory() if args.include_user_skills else None print( @@ -304,7 +304,11 @@ def main() -> int: 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 2 if args.block_exit is None else args.block_exit if result: print(json.dumps(result)) return 0 @@ -339,13 +343,8 @@ def main() -> int: if __name__ == "__main__": - # Popped before any child starts, so no hook or run child inherits it. - block_exit = BLOCK_EXIT if os.environ.pop(BLOCK_SENTINEL, None) == "1" else 2 try: sys.exit(main()) - except HookBlocked as exc: - print(f"Codex bridge: {exc}", file=sys.stderr) - sys.exit(block_exit) except ( OSError, ValueError, diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 32c6bcdb15..1598a24aba 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -10,16 +10,11 @@ if (-not (Test-Path -LiteralPath $python)) { if (-not (Test-Path -LiteralPath $python)) { throw 'Create this worktree''s .venv first; see docs/WORKTREES.md.' } -# The bridge exits 10 (BLOCK_EXIT in bridge.py) for a hook block only where this flag is set, and -# it is set only where `hook` is the first argument, where the mapping below ends the process with -# 2. The bridge pops it, so no child sees it; the finally keeps it out of a caller's session. +# 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' -$env:MEFOR_CODEX_BLOCK_SENTINEL = if ($hookMode) { '1' } else { $null } -try { - & $python (Join-Path $PSScriptRoot 'bridge.py') @args -} finally { - $env:MEFOR_CODEX_BLOCK_SENTINEL = $null -} +$bridgeArgs = if ($hookMode) { @($args) + @('--block-exit', '10') } else { @($args) } +& $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 10) { [Environment]::Exit(2) } diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 6f4468d91f..be2685d8ea 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -324,7 +324,7 @@ def test_registered_command_runs_from_a_subdirectory(tmp_path): # --- 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 stays at least as blocking as on origin/main (a non-zero exit). +# 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"} @@ -429,7 +429,7 @@ def _hooks(*handlers): @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_blocking_as_main(tmp_path, shell, fault): +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) @@ -440,7 +440,7 @@ def test_every_fault_path_is_at_least_as_blocking_as_main(tmp_path, shell, fault @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 any exit 2 as 1; cmd and sh pass the launcher's 2 on. + # 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 @@ -454,18 +454,18 @@ def test_a_deny_and_a_clean_run_exit_0(tmp_path, shell): assert clean.returncode == 0, clean.stderr -# --- The block sentinel. invoke.ps1 sets MEFOR_CODEX_BLOCK_SENTINEL only for `hook` as its first -# argument, the condition its 10-to-2 mapping uses; without it a hook's exit 2 exits 2, as on main. +# --- 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. -_SENTINEL = "MEFOR_CODEX_BLOCK_SENTINEL" _EXIT_2 = _hooks(_py("import sys; sys.exit(2)")) -# A hook that blocks only where it inherited the sentinel, and otherwise allows. -_SEES_SENTINEL = _hooks(_py(f"import os, sys; sys.exit(2 if {_SENTINEL!r} in os.environ else 0)")) +# The environment variable an earlier head of this branch read in place of the flag. +_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 != _SENTINEL} + env = {k: v for k, v in os.environ.items() if k not in _OLD_SENTINEL} env.update(extra) return env @@ -491,10 +491,34 @@ def test_a_direct_bridge_hook_gives_2_for_a_hooks_exit_2(tmp_path): root = _make_repo(tmp_path, _EXIT_2, venv=False) completed = _direct(root, "hook") assert completed.returncode == 2, completed.stderr - blocked = _direct(root, "hook", **{_SENTINEL: "1"}) + blocked = _direct(root, "hook", "--block-exit", "10") assert blocked.returncode == 10, blocked.stderr +def test_an_inherited_environment_does_not_change_the_block_exit(tmp_path): + root = _make_repo(tmp_path, _EXIT_2, venv=False) + completed = _direct(root, "hook", **_OLD_SENTINEL) + assert completed.returncode == 2, completed.stderr + + +@_needs_pwsh +def test_invoke_ignores_an_inherited_environment(tmp_path): + root = _make_repo(tmp_path, _EXIT_2) + completed = _invoke_file(root, "--session-id", "x", "hook", **_OLD_SENTINEL) + assert completed.returncode == 2, completed.stderr + + +def test_the_block_exit_flag_never_reaches_the_run_path(tmp_path): + root = _make_repo(tmp_path, _hooks(), venv=False) + marker = root / "ran" + (root / "scripts/touch.py").write_text( + f"from pathlib import Path\nPath({str(marker)!r}).write_text('x')\n", encoding="utf-8" + ) + completed = _direct(root, "--session-id", "x", "run", "scripts/touch.py", "--block-exit", "10") + assert completed.returncode == 2, completed.stderr + assert not marker.exists() + + @_needs_pwsh def test_invoke_with_a_flag_before_hook_gives_2(tmp_path): root = _make_repo(tmp_path, _EXIT_2) @@ -509,23 +533,10 @@ def test_a_run_child_exiting_10_is_not_remapped(tmp_path): 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", **{_SENTINEL: "1"}) + direct = _direct(root, "--session-id", "x", "run", "scripts/exit10.py") assert direct.returncode == 10, direct.stderr -@_needs_pwsh -def test_no_hook_child_inherits_the_sentinel(tmp_path): - # Positive control: the probe hook does block where the sentinel is in its environment. - probe = json.loads(_SEES_SENTINEL)["hooks"]["PreToolUse"][0]["hooks"][0] - seen = subprocess.run([probe["command"], *probe["args"]], env=_env(**{_SENTINEL: "1"})) - assert seen.returncode == 2 - registered = _run_registered(tmp_path / "registered", "none", _SEES_SENTINEL) - assert registered.returncode == 0, registered.stderr - root = _make_repo(tmp_path / "direct", _SEES_SENTINEL, venv=False) - direct = _direct(root, "hook", **{_SENTINEL: "1"}) - assert direct.returncode == 0, 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. @@ -545,7 +556,7 @@ def test_every_fault_path_exits_as_on_main(tmp_path, path, fault): else: root = _make_repo(tmp_path, settings_text, venv and path != "direct") if path == "direct": - completed = _direct(root, "hook", payload=payload, **{_SENTINEL: "1"}) + 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] From b6a21fc6436483aee98eed4487db677d63123568 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 09:59:34 -0600 Subject: [PATCH 48/51] Codex bridge: review round 1 on the --block-exit flag - invoke.ps1 built its argument array from an if expression, which unrolled a one-element array to a string, so `invoke.ps1 doctor`, `sync-skills` and `state-dir` were splatted one character per argument. It now assigns the array and appends the flag, with the 10 named once. - bridge.py no longer registers --block-exit with argparse, whose prefix matching took `--b`, `--block` and the flag itself from a run script's own arguments. It takes the exact trailing `--block-exit 10` out of a `hook` argv before argparse, so any other value, 0 included, leaves the block at 2, and a run script's flags pass through as on main. - Comments no longer claim no ancestor can supply argv, or that invoke.ps1 forwards its arguments unchanged. - Tests, red at c1cb4e8 first (4 failed, 83 passed): a single argument forwarded whole; no flag added to a run child; a run child's own --block and --block-exit flags pass through; --block-exit 0 leaves the block at 2. Proposed PR title: unchanged (repair on open PR 3003). Proposed ledger banner: unchanged from PR 3003's own. --- scripts/codex/bridge.py | 17 ++++++++-------- scripts/codex/invoke.ps1 | 10 +++++++--- tests/test_codex_bridge.py | 41 +++++++++++++++++++++++++++++--------- 3 files changed, 48 insertions(+), 20 deletions(-) diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index 361db4c65d..a98894ad58 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -279,13 +279,14 @@ def main() -> int: 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") - # Hook mode's exit code for a hook's exit 2; 2 when absent. invoke.ps1 passes 10, and ends its - # process with 2 for it, since pwsh -Command reports a script's exit 2 as 1. Argv, not the - # environment, so no child or ancestor can supply it. - parser.add_argument("--block-exit", type=int, help=argparse.SUPPRESS) - args, rest = parser.parse_known_args() - if args.block_exit is not None and args.mode != "hook": - parser.error("--block-exit applies only to hook mode") + # A hook's exit 2 exits 2, or 10 where argv is exactly `hook ... --block-exit 10`, the form + # invoke.ps1 builds; it ends its process with 2 for 10. 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", "10"]: + argv, block_exit = argv[:-2], 10 + 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( @@ -308,7 +309,7 @@ def main() -> int: result = dispatch(ROOT, payload) except HookBlocked as exc: print(f"Codex bridge: {exc}", file=sys.stderr) - return 2 if args.block_exit is None else args.block_exit + return block_exit if result: print(json.dumps(result)) return 0 diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 1598a24aba..9f3a4001c4 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -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, unchanged, 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' @@ -13,9 +14,12 @@ if (-not (Test-Path -LiteralPath $python)) { # 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' -$bridgeArgs = if ($hookMode) { @($args) + @('--block-exit', '10') } else { @($args) } +$blockExit = 10 +# 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 10) { [Environment]::Exit(2) } +if ($hookMode -and $LASTEXITCODE -eq $blockExit) { [Environment]::Exit(2) } exit $LASTEXITCODE diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index be2685d8ea..94dfac86fa 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -459,7 +459,7 @@ def test_a_deny_and_a_clean_run_exit_0(tmp_path, shell): # main. The flag is argv, so neither a child nor an inherited environment carries it. _EXIT_2 = _hooks(_py("import sys; sys.exit(2)")) -# The environment variable an earlier head of this branch read in place of the flag. +# 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") @@ -508,15 +508,38 @@ def test_invoke_ignores_an_inherited_environment(tmp_path): assert completed.returncode == 2, completed.stderr -def test_the_block_exit_flag_never_reaches_the_run_path(tmp_path): +_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"] + + +def test_a_run_childs_own_flags_pass_through_as_on_main(tmp_path): root = _make_repo(tmp_path, _hooks(), venv=False) - marker = root / "ran" - (root / "scripts/touch.py").write_text( - f"from pathlib import Path\nPath({str(marker)!r}).write_text('x')\n", encoding="utf-8" - ) - completed = _direct(root, "--session-id", "x", "run", "scripts/touch.py", "--block-exit", "10") - assert completed.returncode == 2, completed.stderr - assert not marker.exists() + (root / "scripts/argv.py").write_text(_ARGV_CHILD, encoding="utf-8") + flags = ["--block", "1", "--block-exit", "0"] + 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 _direct(root, "hook", "--block-exit", "0").returncode == 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 From 26ff29992701ac3f8bcfc71c4f51376414d78972 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 10:20:44 -0600 Subject: [PATCH 49/51] Codex bridge: review round 2 on the --block-exit flag - The block tests assert the bridge's block line as well as the exit code, so a bridge fault, which also exits 2, cannot pass for a block. - A run argv ending in exactly `--block-exit 10` passes through to the child, which pins the strip's `hook`-first condition; the pass-through test's name now claims only block-exit flags. - bridge.py names the code BLOCK_EXIT again, and it and invoke.ps1's $blockExit each say the other must match. - invoke.ps1's header no longer says arguments pass "unchanged". Proposed PR title: unchanged (repair on open PR 3003). Proposed ledger banner: unchanged from PR 3003's own. --- scripts/codex/bridge.py | 13 ++++++++----- scripts/codex/invoke.ps1 | 4 ++-- tests/test_codex_bridge.py | 30 +++++++++++++++--------------- 3 files changed, 25 insertions(+), 22 deletions(-) diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index a98894ad58..dbd4873686 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -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", @@ -279,13 +282,13 @@ def main() -> int: 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") - # A hook's exit 2 exits 2, or 10 where argv is exactly `hook ... --block-exit 10`, the form - # invoke.ps1 builds; it ends its process with 2 for 10. It is taken out before argparse, so no - # prefix of it is captured from a run script's own flags. Nothing inherits argv. + # 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", "10"]: - argv, block_exit = argv[:-2], 10 + 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 diff --git a/scripts/codex/invoke.ps1 b/scripts/codex/invoke.ps1 index 9f3a4001c4..a17468b490 100644 --- a/scripts/codex/invoke.ps1 +++ b/scripts/codex/invoke.ps1 @@ -1,6 +1,6 @@ # 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, plus +# 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 @@ -14,7 +14,7 @@ if (-not (Test-Path -LiteralPath $python)) { # 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 +$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" } diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 94dfac86fa..280a4f6f16 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -481,31 +481,32 @@ def _invoke_file(root, *args, payload=_PAYLOAD, **extra): return _launch(argv, root, payload, _env(**extra)) +def _assert_blocked(completed, code): + """A block, told apart from a bridge fault (which also exits 2) by the bridge's block line.""" + 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): - completed = _run_registered(tmp_path, "none", _EXIT_2) - assert completed.returncode == 2, completed.stderr + _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) - completed = _direct(root, "hook") - assert completed.returncode == 2, completed.stderr - blocked = _direct(root, "hook", "--block-exit", "10") - assert blocked.returncode == 10, blocked.stderr + _assert_blocked(_direct(root, "hook"), 2) + _assert_blocked(_direct(root, "hook", "--block-exit", "10"), 10) def test_an_inherited_environment_does_not_change_the_block_exit(tmp_path): root = _make_repo(tmp_path, _EXIT_2, venv=False) - completed = _direct(root, "hook", **_OLD_SENTINEL) - assert completed.returncode == 2, completed.stderr + _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) - completed = _invoke_file(root, "--session-id", "x", "hook", **_OLD_SENTINEL) - assert completed.returncode == 2, completed.stderr + _assert_blocked(_invoke_file(root, "--session-id", "x", "hook", **_OLD_SENTINEL), 2) _ARGV_CHILD = "import json, sys\nprint(json.dumps(sys.argv[1:]))\n" @@ -520,10 +521,10 @@ def test_invoke_adds_no_flag_to_a_run_childs_argv(tmp_path): assert json.loads(completed.stdout) == ["--b", "1"] -def test_a_run_childs_own_flags_pass_through_as_on_main(tmp_path): +@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") - flags = ["--block", "1", "--block-exit", "0"] completed = _direct(root, "--session-id", "x", "run", "scripts/argv.py", *flags) assert completed.returncode == 0, completed.stderr assert json.loads(completed.stdout) == flags @@ -531,7 +532,7 @@ def test_a_run_childs_own_flags_pass_through_as_on_main(tmp_path): def test_only_the_launchers_block_exit_is_honoured(tmp_path): root = _make_repo(tmp_path, _EXIT_2, venv=False) - assert _direct(root, "hook", "--block-exit", "0").returncode == 2 + _assert_blocked(_direct(root, "hook", "--block-exit", "0"), 2) @_needs_pwsh @@ -545,8 +546,7 @@ def test_invoke_forwards_a_single_argument_whole(tmp_path): @_needs_pwsh def test_invoke_with_a_flag_before_hook_gives_2(tmp_path): root = _make_repo(tmp_path, _EXIT_2) - completed = _invoke_file(root, "--session-id", "x", "hook") - assert completed.returncode == 2, completed.stderr + _assert_blocked(_invoke_file(root, "--session-id", "x", "hook"), 2) @_needs_pwsh From 598f70f6587dc0b711dc511ad38e988ae114286a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 10:48:22 -0600 Subject: [PATCH 50/51] Codex bridge tests: cut two false claims in test prose - The _assert_blocked docstring no longer says the block line tells a block apart from a fault; it says what it asserts. - test_an_inherited_environment_does_not_change_the_block_exit is renamed test_the_retired_sentinel_variable_does_not_change_the_block_exit, since it sets only that one variable. Net prose lines: 0. Proposed PR title: unchanged (repair on open PR 3003). Proposed ledger banner: unchanged from PR 3003's own. --- tests/test_codex_bridge.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_codex_bridge.py b/tests/test_codex_bridge.py index 280a4f6f16..9ec7d908dc 100644 --- a/tests/test_codex_bridge.py +++ b/tests/test_codex_bridge.py @@ -482,7 +482,7 @@ def _invoke_file(root, *args, payload=_PAYLOAD, **extra): def _assert_blocked(completed, code): - """A block, told apart from a bridge fault (which also exits 2) by the bridge's block line.""" + """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 @@ -498,7 +498,7 @@ def test_a_direct_bridge_hook_gives_2_for_a_hooks_exit_2(tmp_path): _assert_blocked(_direct(root, "hook", "--block-exit", "10"), 10) -def test_an_inherited_environment_does_not_change_the_block_exit(tmp_path): +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) From c70ad36a5e6d837387933829f9005ff9f07c786d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 17 Nov 2026 11:45:13 -0600 Subject: [PATCH 51/51] Codex bridge: cut the HookBlocked docstring's block claim Claude Code does not read exit 2 as a block on SessionStart or SessionEnd, so the docstring now says only that a hook exited 2. Net prose lines: 0. Proposed PR title: unchanged (repair on open PR 3003). Proposed ledger banner: unchanged from PR 3003's own. --- scripts/codex/bridge.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/codex/bridge.py b/scripts/codex/bridge.py index dbd4873686..76a26c4658 100644 --- a/scripts/codex/bridge.py +++ b/scripts/codex/bridge.py @@ -119,7 +119,7 @@ def sync_skills( class HookBlocked(Exception): - """A hook exited 2, which Claude Code reads as a deliberate block.""" + """A hook exited 2.""" def child_environment(root: Path, session_id: str) -> dict[str, str]: