On Dec 1, 2026 we rebuilt this guard from the prompt below on a paper bot repo and fed it 62 hook inputs in the shapes Claude Code, Cursor, Grok Build and Codex document today. The Oct 25 version let 17 of them through; this one lets 4 through. Below are the four files, then what we found.
1. .claude/settings.json: deny rules plus the two hooks. The args form runs the script with no shell, which is what Claude Code's docs recommend when the path uses ${CLAUDE_PROJECT_DIR}.
{
"permissions": {
"deny": [
"Read(**/.env)",
"Read(**/.env.*)",
"Read(**/*.pem)",
"Read(**/*.key)",
"Bash(git push *)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Read|Edit|Write|Grep",
"hooks": [
{
"type": "command",
"command": "python3",
"args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/bot_guard.py"],
"timeout": 10,
"onFailure": "block"
}
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.venv/bin/python",
"args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/limits_tests.py"],
"timeout": 120
}
]
}
]
}
}
On Claude Code older than v2.1.295, delete the onFailure line and update. Without it a crashed guard fails open. If you also open the repo in Cursor, use the shell form instead: "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/bot_guard.py\"" with no args. Cursor's hook docs don't mention args, and if a tool drops it, python3 reads the hook JSON as a Python program. We tried that: it exits 0 or 1, and either way the call goes through.
2. .claude/hooks/bot_guard.py: the PreToolUse guard. It decides by what's in the input (a command or a file path), not by the tool's name, because each tool names the same action differently. It prints only a reason, never file contents.
#!/usr/bin/env python3
"""BotCookery PreToolUse guard (Dec 1, 2026). Claude Code format; also runs
when Cursor or Grok Build load .claude/settings.json, and as a Codex hook.
Exit 0 = no objection (normal permissions still apply).
Exit 2 = block; the one-line reason on stderr goes to the agent.
Anything it can't read also exits 2."""
import json, re, sys
# .env, .env.local, *.pem, *.key, SSH keys. .env.example is allowed.
SECRET = re.compile(r"(?<![\w.-])(\.env(?!\.example(?![\w.-]))(\.[\w.-]+)?"
r"|[\w.-]*\.pem|[\w.-]*\.key|id_(rsa|ed25519|ecdsa)\w*)(?![\w.-])",
re.I)
READ_ONLY_TOOLS = {"read", "read_file", "grep", "glob", "ls", "list_dir"}
READ_CMD = re.compile(r"\s*(cat|grep|head|tail|less|jq)\s")
def block(msg):
print(f"BotCookery guard: {msg}", file=sys.stderr)
sys.exit(2)
try:
data = json.load(sys.stdin)
if not isinstance(data, dict):
raise TypeError("not a JSON object")
# Claude, Codex and Cursor send tool_name/tool_input. Grok sends
# toolName/toolInput. Cursor names Bash "Shell"; Grok names it
# run_terminal_command. So check the input fields, not the name.
tool = data.get("tool_name") or data.get("toolName") or ""
inp = data.get("tool_input") or data.get("toolInput") or {}
if isinstance(inp, str):
inp = json.loads(inp)
if not isinstance(tool, str) or not isinstance(inp, dict):
raise TypeError("tool name or tool input has the wrong type")
cmd = inp.get("command") or ""
path = inp.get("file_path") or inp.get("path") or ""
if not isinstance(cmd, str) or not isinstance(path, str):
raise TypeError("command or path is not a string")
except Exception as exc:
block(f"could not read the hook input ({exc}).")
tool = tool.lower()
path = path.replace("\\", "/")
def check_command(c):
if re.search(r"--live\b|BOT_MODE=live\b|KALSHI_ENV=prod\b", c):
block("live trading is started by a human in their own terminal, "
"never by the agent.")
if SECRET.search(c):
block("commands that touch .env or key files are blocked. "
"The bot loads secrets from env vars itself.")
if (re.search(r"(^|[;&|(]\s*)(printenv\b|env\s*($|[|;&>)]))", c)
or re.search(r"echo\s+\$\{?\w*(KEY|SECRET|TOKEN|PASS)", c, re.I)
or re.search(r"\b(python3?|node)\b.*\s-[ce]\s.*"
r"(environ|process\.env|getenv)", c)):
block("printing environment secrets is blocked.")
if re.search(r"\bgit(\s+-[Cc]\s+\S+|\s+--?[\w-]+(=\S+)?)*\s+push\b", c):
block("git push needs a human.")
if (re.search(r"\b(rm|mv|unlink)\b[^;&|]*(^|[\s/])KILL\b", c)
or re.search(r"\*\*\* Delete File: (\S*/)?KILL\b", c)):
block("the KILL file is the human's off switch. Leave it alone.")
if "limits.json" in c and (not READ_CMD.match(c)
or re.search(r">\s*\S*limits\.json", c)
or re.search(r"[;&|]", c)):
block("limits.json is human-edited only. Ask the user to change it.")
if cmd:
check_command(cmd)
# 'cat .e''nv', --li""ve, g\it: check again with quoting removed.
check_command(re.sub(r"[\"'\\]", "", cmd))
if path:
if SECRET.search(" " + path):
block(f"access to {path} is blocked.")
if tool not in READ_ONLY_TOOLS and re.search(r"(^|/)limits\.json$", path):
block("limits.json is human-edited only. Ask the user to change it.")
sys.exit(0)
3. .claude/hooks/limits_tests.py: the PostToolUse hook. It can't undo an edit, but exit 2 puts the test failure in front of the agent so it fixes the code right away. It runs your whole tests/ folder unless you set LIMIT_TESTS to one file.
#!/usr/bin/env python3
"""BotCookery PostToolUse hook (Dec 1, 2026): after the agent edits risk,
limit or kill-switch code, run the tests. Exit 2 sends the failure to the
agent. Set LIMIT_TESTS to a test file to run just that file (default: tests/)."""
import json, os, re, subprocess, sys
def fail(msg):
print(msg, file=sys.stderr)
sys.exit(2)
try:
data = json.load(sys.stdin)
inp = data.get("tool_input") or data.get("toolInput") or {}
path = inp.get("file_path") or inp.get("path") or ""
if not path: # Codex apply_patch puts the patch text in "command"
m = re.search(r"\*\*\* (?:Update|Add) File: (\S+)", inp.get("command") or "")
path = m.group(1) if m else ""
path = str(path).replace("\\", "/")
except Exception as exc:
fail(f"limits_tests: could not read the hook input ({exc}).")
if not re.search(r"(risk|limit|kill)[\w-]*\.py$", path, re.I):
sys.exit(0)
root = os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()
target = os.environ.get("LIMIT_TESTS", "tests")
try:
r = subprocess.run([sys.executable, "-m", "pytest", "-q", target],
cwd=root, capture_output=True, text=True, timeout=110)
except subprocess.TimeoutExpired:
fail(f"Tests for {target} took over 110 s after editing {path}.")
if r.returncode in (4, 5): # path missing / no tests collected
fail(f"No tests ran for {target} after editing {path}. "
"Add a limit test or set LIMIT_TESTS.")
if r.returncode != 0:
fail(f"Tests failed after editing {path}:\n{(r.stdout + r.stderr)[-3000:]}")
sys.exit(0)
4. tests/test_hooks.py: sends every case in all three input shapes.
import json, os, subprocess, sys
import pytest
GUARD = os.path.join(os.path.dirname(__file__), "..", ".claude", "hooks",
"bot_guard.py")
def run(payload):
data = payload if isinstance(payload, str) else json.dumps(payload)
return subprocess.run([sys.executable, GUARD], input=data,
capture_output=True, text=True).returncode
def shapes(cmd=None, path=None, read=False):
"""The same call as Claude Code, Cursor and Grok Build send it."""
if cmd is not None:
return [{"tool_name": "Bash", "tool_input": {"command": cmd}},
{"tool_name": "Shell", "tool_input": {"command": cmd}},
{"toolName": "run_terminal_command", "toolInput": {"command": cmd}}]
names = ("Read", "Read", "read_file") if read else ("Edit", "Write", "search_replace")
return [{"tool_name": names[0], "tool_input": {"file_path": path}},
{"tool_name": names[1], "tool_input": {"file_path": path}},
{"toolName": names[2], "toolInput": {"path": path}}]
BLOCK = ["python bot.py --live", "BOT_MODE=live python bot.py",
"KALSHI_ENV=prod python bot.py", "cat .env", "cat .env.local",
"cat ~/.kalshi/kalshi.pem", "printenv", "env | grep KALSHI",
"echo $KALSHI_API_KEY_ID", "python -c 'import os;print(os.environ)'",
"git push origin main", "git -C . push",
"sed -i s/5/50/ limits.json", "cat x > limits.json",
"rm KILL", "mv KILL /tmp/", "cat .e''nv", 'python bot.py --li""ve']
ALLOW = ["python bot.py", "python bot.py --paper", "pytest -q",
"cat .env.example", "cat limits.json", "grep max limits.json",
"git status", 'git commit -m "push fix"', "ls KILL"]
@pytest.mark.parametrize("cmd", BLOCK)
def test_blocks_commands(cmd):
assert [run(p) for p in shapes(cmd=cmd)] == [2, 2, 2]
@pytest.mark.parametrize("cmd", ALLOW)
def test_allows_commands(cmd):
assert [run(p) for p in shapes(cmd=cmd)] == [0, 0, 0]
@pytest.mark.parametrize("path", ["/p/.env", "/p/.env.local",
"/p/keys/kalshi.pem", "C:\\bot\\.env"])
def test_blocks_secret_reads(path):
assert [run(p) for p in shapes(path=path, read=True)] == [2, 2, 2]
def test_limits_json_read_ok_edit_blocked():
assert [run(p) for p in shapes(path="/p/limits.json", read=True)] == [0, 0, 0]
assert [run(p) for p in shapes(path="/p/limits.json")] == [2, 2, 2]
assert [run(p) for p in shapes(path="C:\\bot\\limits.json")] == [2, 2, 2]
def test_risk_edit_allowed():
assert [run(p) for p in shapes(path="/p/risk.py")] == [0, 0, 0]
@pytest.mark.parametrize("raw", ["not json", "", "[]",
'{"tool_name": "Bash", "tool_input": {"command": ["git", "push"]}}'])
def test_bad_input_fails_closed(raw):
assert run(raw) == 2
What we found (Dec 1, 2026)
We ran the same 62 inputs (43 commands in four tools' shapes, 9 file paths, 3 Codex patches, 7 broken payloads) against the Oct 25 files and against a fresh build from today's prompt.
- A redirect wrote
limits.json. The old guard let any command that started with cat through, so cat x > limits.json and cat limits.json > /tmp/l; echo '{}' > limits.json both exited 0. Now a > into the file, or a second command after ;, & or |, is a write.
- Nothing protected the kill file.
rm KILL and rm -f ./KILL exited 0 in every shape. The agent could switch off the bot's off switch. Now rm, mv and unlink of KILL, and a Codex patch with *** Delete File: KILL, are blocked.
- Windows paths walked past. Claude Code's hooks page says file paths arrive with backslashes on Windows. A Read of
C:\bot\.env and an Edit of C:\bot\limits.json both got exit 0. The guard now turns \ into / first.
- Easy quoting tricks now fail. The guard checks each command twice: as sent, and with quotes and backslashes removed. That closes
cat .e''nv, --li""ve, BOT_MODE='live' and g\it push. It also blocks python -c or node -e that reads os.environ, process.env or getenv.
- A list where a string belongs crashed it.
{"command": ["git", "push"]} raised TypeError and exited 1, which lets the call through everywhere except where fail-closed is set. A clean build from the Oct 25 prompt did worse: it silently exited 0 on that and on a tool_input sent as a string. Wrong types now exit 2 with a reason.
- One false block.
grep -n max limits.json was blocked as an edit. Reads with grep are allowed now.
- The test hook in a fresh build missed Codex. The Oct 25 prompt didn't say that Codex puts the edited file inside the
apply_patch text, so a build from it exited 0 after a broken risk.py patch. The prompt now says so. The page's own limits_tests.py already caught it, but died with exit 1 on bad input. It now exits 2 with a message.
- Docs moved since Oct 25. Grok Build's hooks page now has
failClosed, and reads onFailure: "block" from a Claude settings file (we said it ignored it). Its default PreToolUse timeout is 5 seconds. Cursor's third-party hooks page now says Third-Party Imports is on by default, maps Claude's Edit to Write, and lists the product as the Grok Build Agents Window. Codex still says a PreToolUse error, timeout or malformed response can let the tool run.
- Still gets through:
$(echo git) push, echo Z2l0IHB1c2g= | base64 -d | sh, a git alias for push, and cat .en?. A pattern guard can't run the shell for you. Keep the key file outside the project, keep the deny rules, and use a sandbox for anything stronger.
What we found (Oct 25, 2026)
- The old guard did nothing outside Claude Code. It checked
tool_name == "Bash". Cursor runs Claude Code hooks but calls the tool Shell. Grok Build sends toolName: "run_terminal_command" inside a camelCase toolInput. Both shapes got exit 0 for python bot.py --live, cat .env, git push and a .pem read. Run against the new tests, the old guard failed 19 of 27.
- Crashes didn't block outside Claude Code. On input that wasn't valid JSON the old guard died with exit 1. At the time Grok Build's docs said every outcome except exit 2 or an explicit deny let the call through, and Codex's docs said the same for errors and timeouts. The guard exits 2 on any input it can't read.
- Grok Build loads this file as-is.
grok inspect in the trusted repo listed both hooks as [claude], with matcher Bash|Read|Edit|Write, and loaded all 5 deny rules. Grok maps Bash to run_terminal_command, Read to read_file, and Edit/Write to search_replace, and it sets CLAUDE_PROJECT_DIR.
- Codex edits come through as a patch. Codex reports file edits as
apply_patch with the patch text in tool_input.command. The guard blocked patches to limits.json and .env and allowed one to risk.py. The test hook now reads the file name out of the patch.
- The test hook failed on every risk edit. It ran
tests/test_limits.py, which our test bot (like most bots) doesn't have, so pytest exited 4 and the hook reported "Limit tests failed". It now runs tests/ and says clearly when no tests ran.
- Two small fixes:
git -C . push got past git\s+push, and the guard now matches git options before push while still allowing git commit -m "push fix".
Sample runs (Dec 1, 2026)
The drill script, same 62 inputs each time:
Oct 25 files: SUMMARY 45/62 as expected, 17 miss
Dec 1 files: SUMMARY 58/62 as expected, 4 miss
MISS B 'cat .en?' {'claude': 0, 'cursor': 0, 'grok': 0, 'codex': 0}
MISS B '$(echo git) push' {'claude': 0, 'cursor': 0, 'grok': 0, 'codex': 0}
MISS B 'echo Z2l0IHB1c2g= | base64 -d | sh' {'claude': 0, 'cursor': 0, 'grok': 0, 'codex': 0}
MISS B 'git p # alias p=push' {'claude': 0, 'cursor': 0, 'grok': 0, 'codex': 0}
Broken input now gets a reason instead of a traceback:
ok B raw '[]' 2 ['BotCookery guard: could not read the hook input (not a JSON object).']
ok B raw '{"tool_name":"Bash","tool_input":{"command":["git","push"]} 2 ['BotCookery guard: could not read the hook input (command or path is not a string).']
The tests, and the Oct 25 guard run against them:
$ pytest -q tests/test_hooks.py
37 passed in 1.90s
Oct 25 bot_guard.py: 10 failed, 27 passed in 1.96s
Test hook after we loosened the order-size check in risk.py (qty > max * 10):
Tests failed after editing .../risk.py:
FAILED tests/test_risk.py::test_too_big - Failed: DID NOT RAISE RiskError
1 failed, 40 passed in 2.10s
exit 2
The same broken edit as a Codex apply_patch and in Grok's toolInput.path shape also exited 2. With risk.py restored it exited 0, an edit to bot.py didn't run the tests, and LIMIT_TESTS=tests/nope.py exited 2 with "No tests ran".
Follow-up prompt
Built this before Dec 1? Paste this to patch the older guard:
Read .claude/hooks/bot_guard.py, limits_tests.py and tests/test_hooks.py.
Without changing bot.py, risk.py or limits.json, fix these and add a
test for each:
- "cat x > limits.json" must be blocked (a redirect is a write).
- "rm KILL", "mv KILL x" and an apply_patch "*** Delete File: KILL"
must be blocked.
- Windows paths: turn "\" into "/" before matching, so a Read of
C:\bot\.env and an Edit of C:\bot\limits.json are blocked.
- Also match each command with quotes and backslashes removed, so
"cat .e''nv" and "python bot.py --li""ve" are blocked.
- If tool_input, command or path has the wrong type (e.g. a list),
exit 2 with a reason. Never exit 1. limits_tests.py exits 2 on input
it can't read and finds the file in a Codex apply_patch.
- "grep max limits.json" is a read and must be allowed.
Add "Grep" to the PreToolUse matcher in .claude/settings.json.
Then run pytest -q tests/test_hooks.py and show the result.
Once the hooks are in, paste this to make the agent check its own guard:
Read .claude/settings.json and .claude/hooks/. Without running the bot,
list every way you could still start live trading, read a key or push
code that the guard would allow. Don't try any of them. For each one,
say whether a deny rule, a sandbox setting or a code change closes it.
Works in Claude Code, Cursor, Codex/ChatGPT, Grok or any agent that can write files. Paste it into an empty folder. Read what it builds before you run anything.
Endpoints and rules were checked against these pages on Dec 1, 2026. APIs change, so if something here disagrees with the official docs, trust the docs and tell us.