Sub topic 10
Failing closed when the hook breaks
A pre-action hook is a safety check, and like any code it can crash, time out, or receive input it did not expect. This chapter covers what the agent does when that happens, why the default is often unsafe, and how to make the hook block the action instead.
It assumes you can read and write Python and shell scripts, you know JSON, and you have written a basic hook that reads a tool-call event on stdin and blocks with exit code 2. Exit codes and field names below follow the convention used by Claude Code and Kiro CLI. Check your agent's documentation for the exact values.
Fail open and fail closed
A check can fail in two directions when it cannot reach a verdict:
- Fail open means the action goes ahead. The check is skipped when it breaks.
- Fail closed means the action is blocked. A check that cannot decide says no.
For a safety hook, fail closed is the right default. A hook that only works when nothing goes wrong gives no protection in the cases that matter. Input you did not anticipate is exactly the input an attacker, or a confused agent, is most likely to produce.
The cost is friction. A broken hook that fails closed stops the agent from working until you fix it. That is a visible, fixable problem. A broken hook that fails open is silent.
The default is usually fail open
Most hook systems give exit codes three meanings:
| Exit code | Typical meaning |
|---|---|
| 0 | Allow. The tool call proceeds. |
| 2 | Block. The tool call is cancelled and stderr is returned to the agent. |
| Any other value | Hook error. The tool call proceeds, and stderr is shown only as a warning. |
The last row causes most failures. Python exits with code 1 on an uncaught exception, so this script fails open:
import json
import sys
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
if "rm -rf /" in command:
print("Blocked: destructive command.", file=sys.stderr)
sys.exit(2)If the event is missing tool_input, Python raises KeyError and exits with 1. The agent sees a non-blocking error, and the command runs unchecked. The same happens in these cases:
- The
python3binary is not installed, which gives exit code 127. - The script file is not executable, which gives exit code 126.
- The hook is killed for exceeding its timeout. Most agents treat this as non-blocking.
- The script has a syntax error after an edit.
Confirm the behavior for your agent version. Do not assume it.
Where a hook can break
The following diagram shows the paths that can occur on a single tool call.
There are two layers of defense. Inside the script, you handle the failures you can predict. Around the script, a wrapper handles the ones you cannot.
Layer 1: fail closed inside the script
The script has three rules:
- Treat unreadable input as a reason to block.
- Validate the type and shape of every field you depend on, not only its presence.
- Put the whole program under a catch-all handler that blocks.
#!/usr/bin/env python3
import json
import re
import sys
BLOCKED_PATTERNS = [
r"\brm\s+-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\s+/(\s|$)",
r"\bgit\s+push\b.*--force",
r"\bdrop\s+table\b",
]
def block(reason):
print(f"Blocked: {reason}", file=sys.stderr)
sys.exit(2)
def main():
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
block("hook could not read the tool call, so it was not allowed.")
if not isinstance(command, str) or not command.strip():
block("tool call has no command text to check, so it was not allowed.")
for pattern in BLOCKED_PATTERNS:
if re.search(pattern, command, re.IGNORECASE):
block(f"command matches risky pattern {pattern!r}. Use a safer alternative.")
sys.exit(0)
try:
main()
except Exception as exc:
block(f"hook crashed ({type(exc).__name__}), so the action was not allowed.")A few details matter here:
sys.exit()raisesSystemExit, which derives fromBaseException, notException. The finalexcept Exceptiontherefore does not swallow the deliberate exit 0 or exit 2.- The
isinstancecheck catches acommandthat isnull, a number, or a list. Without it,re.searchwould raiseTypeErroron a non-string. The catch-all would still block, but a specific message is easier to debug. - The catch-all reports only the exception type, not its message. Messages can contain pieces of the command, and stderr goes back to the model.
- An empty command is blocked here because this hook is scoped to a shell tool, where an empty command is anomalous. Make this choice per tool.
Decide what "unexpected" means for each field
Fail closed does not mean block every event the hook does not recognize. If a matcher scopes the hook to the shell tool, then a shell event without a command is malformed and should be blocked. An event for another tool should never reach the hook. If it does, the matcher is wrong. Fix the matcher instead of making the hook permissive.
Layer 2: fail closed around the script
The script cannot catch a missing interpreter, a syntax error, or a kill signal, because none of those run your code. A small wrapper script handles these cases by allowing only the two exit codes you intend:
#!/bin/bash
timeout 5 python3 "$(dirname "$0")/guard.py"
code=$?
if [ "$code" -eq 0 ] || [ "$code" -eq 2 ]; then
exit "$code"
fi
echo "Blocked: guard hook failed with exit code $code, so the action was not allowed." >&2
exit 2Register guard.sh as the hook command, not guard.py. The wrapper turns every unexpected result into a block:
- 1: uncaught crash.
- 124:
timeoutkilled the script. - 126: the script is not executable.
- 127: the command was not found.
- 137: the process was killed.
Two cautions apply. The timeout command is not present on every system. On macOS it comes from GNU coreutils. If it is missing, the wrapper gets 127 and blocks everything, which is safe but annoying. Test the wrapper on each machine that runs the agent. Also, the wrapper itself can fail if it is not executable or if bash is missing. Keep it small and set its permissions with chmod +x guard.sh.
Failing closed on missing protected-path data
The same principle applies to path checks. If the hook cannot resolve a path, for example because the file field is missing or realpath raises an error, treat the path as protected. The path helper from the previous chapter already follows this idea by treating anything outside the project root as protected. Extend it by blocking when a write tool's event has no path at all.
What fail closed does not fix
Fail closed covers a hook that breaks. It does not make a working hook complete. A hook with a gap in its deny patterns still allows commands that match no pattern, and a deny list cannot cover every dangerous command. Later chapters cover those limits and how to layer hooks with permissions and sandboxes.
There is also a human cost. If the hook blocks on a transient problem, such as a slow disk, the agent may retry or work around it. Keep the hook fast and free of network calls so failures stay rare. Make the block message say that the hook failed, as the examples above do, so the person reading the transcript can tell a hook fault from a policy decision.
Test the failure paths
Use the same method as in the testing chapter, but send broken input. Each of these should exit with 2:
echo 'not json' | ./guard.sh
echo "exit code: $?"
echo '{"tool_name":"shell"}' | ./guard.sh
echo "exit code: $?"
echo '{"tool_name":"shell","tool_input":{"command":null}}' | ./guard.sh
echo "exit code: $?"
echo '{"tool_name":"shell","tool_input":{"command":"ls -la"}}' | ./guard.sh
echo "exit code: $?"The first three should block, and the last should print exit code 0. To test the wrapper, temporarily break the script. Add a line containing raise SystemExit(1) at the top of guard.py, then run the last command again. The result should now be exit code 2 with the wrapper's message. Remove the line afterward.
Also run the hook inside the real agent once, with a deliberately broken script. Unit tests with echo prove the script's behavior. Only the agent run proves how the agent treats exit codes.
Exercise
A hook script has no try/except. An event arrives without a "tool_input" field, so the script raises KeyError and exits with code 1. Under the common convention, what happens to the tool call, and what two changes would make it fail closed?
Show answer
The tool call proceeds, because exit code 1 is a non-blocking error and only exit code 2 blocks. Fix it by (1) catching parse and key errors inside the script and exiting with 2, with a catch-all around main(), and (2) running the script through a wrapper that maps every exit code other than 0 and 2 to exit 2, which also covers a missing interpreter, a syntax error, and a timeout.
Exercise
Why does the catch-all in the guard script use "except Exception" and not a bare "except:" or "except BaseException"?
Show answer
sys.exit() raises SystemExit, which is a BaseException. Catching BaseException would intercept the deliberate exit 0 (allow) and exit 2 (block) calls and turn them into a crash block. With "except Exception", SystemExit passes through unchanged, so only real errors reach the catch-all.