Sub topic 14
What Hooks Cannot Guarantee
This chapter assumes you can read the hook contract from earlier chapters: the event arrives as JSON on stdin, and the hook answers with an exit code and a stderr message. It also assumes you have written a deny-pattern check and a path check. Here you learn where those checks stop working, so you can set expectations correctly.
A hook is a filter, not a boundary
A pre-action hook inspects a proposed tool call and can stop it. It does not control what the allowed command does after it starts. A hook that blocks rm -rf / has not made deletion impossible. It has made one spelling of one request fail.
Three facts follow from this:
- The hook sees a description of the action (a command string, a file path), not the action's effects.
- The hook runs with the same operating system privileges as the agent and often the same user account.
- The hook only covers the tool calls your agent actually routes through it.
The diagram shows the gap between what the hook sees and what happens.
Pattern matching is incomplete by nature
A deny pattern matches text. The shell and the programs it launches accept many different texts that mean the same thing. The next script runs the force-push pattern from earlier chapters against several equivalent commands.
import re
PATTERN = r"\bgit\s+push\b.*--force"
commands = [
"git push --force origin main",
"git push -f origin main",
"git push origin +main",
"g=git; $g push --force origin main",
"echo Z2l0IHB1c2ggLWY= | base64 -d | sh",
]
for command in commands:
matched = bool(re.search(PATTERN, command, re.IGNORECASE))
print(f"{'BLOCKED' if matched else 'allowed'} {command}")Only the first command is blocked. The short flag -f, the +main refspec, a variable holding the program name, and a base64-encoded payload all do the same or a similar thing and pass through. You can widen the pattern to cover -f and +main. You cannot enumerate every encoding, because the shell is a programming language.
Common evasions to expect, even from an agent with no bad intent:
- Indirection: variables,
eval,sh -c "...", command substitution, and aliases. - Encoding: base64, hex escapes, or building a string from parts.
- Wrappers:
env,xargs,find -exec,sudo, andnohupput the dangerous program in the middle of a command line. - Scripts written then run: the agent writes
cleanup.shwith a file-edit tool, then runsbash cleanup.sh. The hook sees only the second command, and the dangerous text is in the file. - Other interpreters:
python -c "import shutil; shutil.rmtree('data')"contains none of the shell words you listed.
Most of these happen by accident. An agent that has been blocked once often tries a different route to finish its task, and that route may be a bypass. Treat this as a normal behavior to design for, not as an attack.
Path checks have their own gaps
Normalizing a path with realpath removes ../ tricks and resolves symlinks. That is necessary, and it is still not complete.
- Tool coverage: a matcher on the file-write tool does nothing for
sed -i,tee,cp,mv, orecho text > .envrun through the shell tool. Protecting a path means checking every tool that can write, including the shell command text, which brings back the pattern problem above. - Time-of-check, time-of-use: the hook resolves a path at one moment, and the tool opens it a moment later. If something changes a symlink in between, the checked path and the written path differ. This window is small, but it exists.
- Paths inside file contents: a build script, Makefile, or test runner can touch protected files when it runs. The hook approved
make deploy, not whatmake deploydoes. - Case and mount differences: on case-insensitive file systems,
.ENVand.envare the same file. Bind mounts and network shares can make one file appear under two paths.
Gaps in coverage
A hook only protects what reaches it. Check these before you trust one:
| Gap | Why it matters |
|---|---|
| Tools not matched | A matcher for `shell` leaves file-edit, web, and MCP tools unchecked. |
| MCP and third-party tools | Their names differ per server. A matcher written for built-in tools may never fire. |
| Subagents and other sessions | Depending on the agent, a spawned subagent may use different hook settings or none. |
| Other entry points | Commands you type yourself, IDE actions, and CI jobs do not go through the agent's hook. |
| Event field names | A field renamed in a new agent version makes `event.get("tool_input", {})` return an empty dict, and the check silently passes. |
The last row is the most common failure in practice. The fail-closed check from earlier chapters exists to catch it. Use event["tool_input"]["command"] inside a try block so that a missing field blocks instead of being treated as an empty command.
Hooks can fail open
In the usual convention, exit code 2 blocks the action and exit code 0 allows it. Other non-zero codes are typically treated as a non-blocking error: the agent shows a warning and goes ahead. Check your agent's documentation for the exact rule, because this is the most dangerous default to misunderstand.
Python makes it easy to hit. An uncaught exception ends the process with exit code 1, which is not 2. A hook that crashes on unexpected input can therefore allow the action it was meant to block. Wrap the whole hook so any failure becomes a block:
#!/usr/bin/env python3
import json
import sys
def check(event):
command = event["tool_input"]["command"]
if "drop table" in command.lower():
print("Blocked: SQL DROP TABLE needs manual review.", file=sys.stderr)
return 2
return 0
def main():
try:
event = json.load(sys.stdin)
code = check(event)
except Exception as error:
print(f"Blocked: hook failed ({type(error).__name__}).", file=sys.stderr)
code = 2
sys.exit(code)
main()Other ways a hook fails open:
- Timeout: many agents treat a hook that exceeds its time limit as a non-blocking failure. A check that makes a network call or scans a large repository can time out and let the action through.
- Missing interpreter or script: if
python3is not on the PATH in the agent's environment, the hook never runs. The shell reports exit code 127, which is not 2. - Permissions: a script that lost its execute bit fails to start with exit code 126.
Test these cases on purpose. Rename the script, break its permissions, and feed it garbage input. Then confirm what your agent does in each case.
The agent can change the rules
Hook configuration and hook scripts are files. If the agent can write to them, it can edit or delete the guard. This can happen without bad intent: an agent that sees a hook "failing" may helpfully fix the script so the failure goes away.
Reduce the risk:
- Put the hook script and its configuration in a path the agent cannot write, and add that path to your own protected list.
- Use a user-level or organization-level configuration where the agent supports it, so a project file cannot override it.
- Keep the hook files in version control and review changes to them like changes to code that handles secrets.
The same applies to the deny list. If it lives in a repository the agent edits, the agent can change it.
Hooks are not audit-proof
A hook sees an event before the action. It does not know whether the action succeeded, what a script did internally, or what happened elsewhere on the machine. Logs written by the hook show what was proposed and decided, not what occurred. Use them for review, not as evidence of what was changed.
Setting expectations
Hooks are good at several things:
- Catching common, honest mistakes such as a force-push or a write to
.env. - Giving the agent a clear reason so it can pick a safer route.
- Enforcing team conventions that are cheap to check.
- Creating a record of what was proposed.
They are poor at stopping a determined or creative path to the same result. Do not use a hook as the only control for anything where a single miss is costly: production credentials, irreversible deletes, or data you cannot restore. For those, the next chapter shows how to place hooks beside permissions and sandboxes, which enforce limits outside the agent's own process.
Exercise
A hook blocks any shell command matching \brm\s+-rf\s+/. The agent writes a file clean.sh containing rm -rf /tmp/build / using its file-edit tool, then runs bash clean.sh. Does the hook stop it, and what two changes would reduce the risk?
Show answer
No. The hook sees only the command bash clean.sh, which does not match the pattern. The dangerous text is inside the file, which was written by a different tool. Two changes: (1) add a hook on the file-write tool that scans new script content for deny patterns, or block running scripts the agent just created; (2) add a control outside the hook, such as a sandbox or permission setting that makes the target directory read-only, so the command fails even if it runs.
Exercise
Your Python hook crashes with a KeyError because the agent update renamed tool_input. The agent proceeds with the command. Why, and how do you fix it?
Show answer
An uncaught exception exits with code 1, and the agent treats any exit code other than 2 as a non-blocking error. Wrap the hook logic in a try/except that prints a message and exits with code 2 on any exception, so a failed check blocks instead of allowing. Then test it by sending an event with a missing field and confirming the exit code is 2.