{"slug": "our-claude-code-hook-guard-got-17-of-62-drill-inputs-wrong", "title": "Our Claude Code hook guard got 17 of 62 drill inputs wrong", "summary": "A developer publishing Claude Code hooks for Kalshi and Polymarket trading-bot repos ran a 62-input drill on Dec 1, 2026 and found the originally published PreToolUse guard passed only 45 of 62 cases, while a rebuilt v2 version reached 58 of 62. The failures included shell-quoting bypasses like `cat .e''nv` and `g\\it push`, Windows paths, `rm KILL` deleting the bot's off switch, and a `TypeError` on array-form commands that exited 1 and failed open. The v2 guard now decides by input content rather than tool name, since Cursor, Grok Build and Codex send shell and patch calls under different tool names and field shapes.", "body_md": "*Originally published on [BotCookery](https://botcookery.com/recipes/claude-code-hooks-trading-bots/), free build recipes for AI-built trading and prediction-market bots. Written with AI assistance. Every count and output below is from a mock drill on Dec 1, 2026: the hook scripts were fed sample JSON in each tool's documented format, plus real pytest runs on a paper bot. They were not run inside a live agent session. Nothing here is financial advice.*\n\nWe publish a set of Claude Code hooks for Kalshi and Polymarket US bot repos. A `PreToolUse` guard stops the agent from reading `.env` or key files, starting the bot with `--live`, running `git push` or editing `limits.json`. A `PostToolUse` hook re-runs the limit tests whenever the agent touches risk code.\n\nOn Dec 1 we wrote a drill: 62 hook inputs (43 commands sent in the Claude Code, Cursor, Grok Build and Codex shapes, 9 file paths, 3 Codex patches, 7 broken payloads). Each one has an expected exit code. The files we'd published on Oct 25 got **45 of 62** right. A fresh build from the Oct 25 prompt got **49 of 62**. The rebuilt v2 files get **58 of 62**, and the 4 still open are listed at the end.\n\nThese came back with exit 0 (no objection) from the Oct 25 guard:\n\n`limits.json`.` cat` through as a read. So `cat x > limits.json` and `cat limits.json > /tmp/l; echo '{}' > limits.json` both passed.`rm KILL` and `rm -f ./KILL` passed in every shape. The agent never touched a limit, but it could remove the bot's off switch.`C:\\bot\\.env` and an Edit of `C:\\bot\\limits.json` both passed.`cat .e''nv`, `python bot.py --li\"\"ve`, `BOT_MODE='live'` and `g\\it push` all run the same as the plain versions in a shell, but none of them matched the guard's patterns.`python -c 'import os;print(os.environ)'` passed.`{\"command\": [\"git\", \"push\"]}` raised a `TypeError`, so the guard exited 1. Exit 1 is a non-blocking error, so the call goes ahead unless fail-closed is configured. The fresh build from the Oct 25 prompt did worse: it silently exited 0 on that, and on a `tool_input` sent as a string.\nThere was also a false block: `grep -n max limits.json` was treated as an edit.\n\nThe test hook had its own gap. The Oct 25 prompt didn't say that Codex puts the edited file name inside the `apply_patch` text, so a fresh build exited 0 after a broken `risk.py` patch. The published `limits_tests.py` caught that one, but died with exit 1 on bad input.\n\nThe main change is that it decides by what's in the input, not by the tool's name. Cursor calls the shell tool `Shell`, Grok Build sends `toolName: \"run_terminal_command\"` in camelCase fields, and Codex sends edits as `apply_patch`. A guard that checks `tool_name == \"Bash\"` allows everything in the other tools. Ours did, back in October.\n\n`.claude/settings.json`: deny rules plus the two hooks.\n\n```\n{\n  \"permissions\": {\n    \"deny\": [\n      \"Read(**/.env)\",\n      \"Read(**/.env.*)\",\n      \"Read(**/*.pem)\",\n      \"Read(**/*.key)\",\n      \"Bash(git push *)\"\n    ]\n  },\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash|Read|Edit|Write|Grep\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"python3\",\n            \"args\": [\"${CLAUDE_PROJECT_DIR}/.claude/hooks/bot_guard.py\"],\n            \"timeout\": 10,\n            \"onFailure\": \"block\"\n          }\n        ]\n      }\n    ],\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Edit|Write\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"${CLAUDE_PROJECT_DIR}/.venv/bin/python\",\n            \"args\": [\"${CLAUDE_PROJECT_DIR}/.claude/hooks/limits_tests.py\"],\n            \"timeout\": 120\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n`onFailure: \"block\"` needs Claude Code v2.1.295 or later; without it a guard that crashes or times out fails open. If you also open the repo in Cursor, use the shell form, `\"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.\n\n`.claude/hooks/bot_guard.py`:\n\n``` bash\n#!/usr/bin/env python3\n\"\"\"BotCookery PreToolUse guard (Dec 1, 2026). Claude Code format; also runs\nwhen Cursor or Grok Build load .claude/settings.json, and as a Codex hook.\nExit 0 = no objection (normal permissions still apply).\nExit 2 = block; the one-line reason on stderr goes to the agent.\nAnything it can't read also exits 2.\"\"\"\nimport json, re, sys\n\n# .env, .env.local, *.pem, *.key, SSH keys. .env.example is allowed.\nSECRET = re.compile(r\"(?<![\\w.-])(\\.env(?!\\.example(?![\\w.-]))(\\.[\\w.-]+)?\"\n                    r\"|[\\w.-]*\\.pem|[\\w.-]*\\.key|id_(rsa|ed25519|ecdsa)\\w*)(?![\\w.-])\",\n                    re.I)\nREAD_ONLY_TOOLS = {\"read\", \"read_file\", \"grep\", \"glob\", \"ls\", \"list_dir\"}\nREAD_CMD = re.compile(r\"\\s*(cat|grep|head|tail|less|jq)\\s\")\n\ndef block(msg):\n    print(f\"BotCookery guard: {msg}\", file=sys.stderr)\n    sys.exit(2)\n\ntry:\n    data = json.load(sys.stdin)\n    if not isinstance(data, dict):\n        raise TypeError(\"not a JSON object\")\n    # Claude, Codex and Cursor send tool_name/tool_input. Grok sends\n    # toolName/toolInput. Cursor names Bash \"Shell\"; Grok names it\n    # run_terminal_command. So check the input fields, not the name.\n    tool = data.get(\"tool_name\") or data.get(\"toolName\") or \"\"\n    inp = data.get(\"tool_input\") or data.get(\"toolInput\") or {}\n    if isinstance(inp, str):\n        inp = json.loads(inp)\n    if not isinstance(tool, str) or not isinstance(inp, dict):\n        raise TypeError(\"tool name or tool input has the wrong type\")\n    cmd = inp.get(\"command\") or \"\"\n    path = inp.get(\"file_path\") or inp.get(\"path\") or \"\"\n    if not isinstance(cmd, str) or not isinstance(path, str):\n        raise TypeError(\"command or path is not a string\")\nexcept Exception as exc:\n    block(f\"could not read the hook input ({exc}).\")\n\ntool = tool.lower()\npath = path.replace(\"\\\\\", \"/\")\n\ndef check_command(c):\n    if re.search(r\"--live\\b|BOT_MODE=live\\b|KALSHI_ENV=prod\\b\", c):\n        block(\"live trading is started by a human in their own terminal, \"\n              \"never by the agent.\")\n    if SECRET.search(c):\n        block(\"commands that touch .env or key files are blocked. \"\n              \"The bot loads secrets from env vars itself.\")\n    if (re.search(r\"(^|[;&|(]\\s*)(printenv\\b|env\\s*($|[|;&>)]))\", c)\n            or re.search(r\"echo\\s+\\$\\{?\\w*(KEY|SECRET|TOKEN|PASS)\", c, re.I)\n            or re.search(r\"\\b(python3?|node)\\b.*\\s-[ce]\\s.*\"\n                         r\"(environ|process\\.env|getenv)\", c)):\n        block(\"printing environment secrets is blocked.\")\n    if re.search(r\"\\bgit(\\s+-[Cc]\\s+\\S+|\\s+--?[\\w-]+(=\\S+)?)*\\s+push\\b\", c):\n        block(\"git push needs a human.\")\n    if (re.search(r\"\\b(rm|mv|unlink)\\b[^;&|]*(^|[\\s/])KILL\\b\", c)\n            or re.search(r\"\\*\\*\\* Delete File: (\\S*/)?KILL\\b\", c)):\n        block(\"the KILL file is the human's off switch. Leave it alone.\")\n    if \"limits.json\" in c and (not READ_CMD.match(c)\n                               or re.search(r\">\\s*\\S*limits\\.json\", c)\n                               or re.search(r\"[;&|]\", c)):\n        block(\"limits.json is human-edited only. Ask the user to change it.\")\n\nif cmd:\n    check_command(cmd)\n    # 'cat .e''nv', --li\"\"ve, g\\it: check again with quoting removed.\n    check_command(re.sub(r\"[\\\"'\\\\]\", \"\", cmd))\nif path:\n    if SECRET.search(\" \" + path):\n        block(f\"access to {path} is blocked.\")\n    if tool not in READ_ONLY_TOOLS and re.search(r\"(^|/)limits\\.json$\", path):\n        block(\"limits.json is human-edited only. Ask the user to change it.\")\nsys.exit(0)\n```\n\nFour details do most of the work:\n\n`--li\"\"ve`, `\\` to `/``>`, `;`, `&` and `|` near `grep`, `head`, `tail`, `less` and `jq` reads stay allowed.\nBroken input now gets a reason instead of a traceback:\n\n```\nok   B raw '[]' 2 ['BotCookery guard: could not read the hook input (not a JSON object).']\nok   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).']\n```\n\n`PostToolUse` can't undo an edit, but exit 2 puts the failure in front of the agent so it fixes the code right away. v2 also finds the file name in a Codex `apply_patch`:\n\n```\ntry:\n    data = json.load(sys.stdin)\n    inp = data.get(\"tool_input\") or data.get(\"toolInput\") or {}\n    path = inp.get(\"file_path\") or inp.get(\"path\") or \"\"\n    if not path:  # Codex apply_patch puts the patch text in \"command\"\n        m = re.search(r\"\\*\\*\\* (?:Update|Add) File: (\\S+)\", inp.get(\"command\") or \"\")\n        path = m.group(1) if m else \"\"\n    path = str(path).replace(\"\\\\\", \"/\")\nexcept Exception as exc:\n    fail(f\"limits_tests: could not read the hook input ({exc}).\")\n\nif not re.search(r\"(risk|limit|kill)[\\w-]*\\.py$\", path, re.I):\n    sys.exit(0)\n```\n\nThe rest runs `pytest -q tests/` (or `$LIMIT_TESTS`) from `$CLAUDE_PROJECT_DIR`, and exits 2 on a failure, a timeout, or when no tests ran. The full file is on the recipe page. Here's what it did after we loosened the order-size check in `risk.py` (`qty > max * 10`):\n\n```\nTests failed after editing .../risk.py:\nFAILED tests/test_risk.py::test_too_big - Failed: DID NOT RAISE RiskError\n1 failed, 40 passed in 2.10s\nexit 2\n```\n\nThe same broken edit also exited 2 as a Codex `apply_patch` and in Grok's `toolInput.path` shape. 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\".\n\nBetween Oct 25 and Dec 1:\n\n`failClosed`, and reads `onFailure: \"block\"` from a Claude settings file. We had written that it ignored it. Its default `PreToolUse` timeout is 5 seconds.`Edit` to `Write`, and lists the product as the Grok Build Agents Window.` Bash(git push *)` doesn't match `git -C . push` or `git -c push.default=current push`. The hook catches both, so keep the rule and the hook.\n\n```\nDec 1 files:    SUMMARY 58/62 as expected, 4 miss\nMISS B 'cat .en?' {'claude': 0, 'cursor': 0, 'grok': 0, 'codex': 0}\nMISS B '$(echo git) push' {'claude': 0, 'cursor': 0, 'grok': 0, 'codex': 0}\nMISS B 'echo Z2l0IHB1c2g= | base64 -d | sh' {'claude': 0, 'cursor': 0, 'grok': 0, 'codex': 0}\nMISS B 'git p  # alias p=push' {'claude': 0, 'cursor': 0, 'grok': 0, 'codex': 0}\n```\n\nA glob, command substitution, base64 piped into `sh`, and a git alias. A pattern guard can't run the shell to see what a command expands to. Keep the key file outside the project, keep the deny rules, and use a sandbox if you need something stronger.\n\n`.claude/settings.json`, `.claude/hooks/bot_guard.py`, `.claude/hooks/limits_tests.py` and `tests/test_hooks.py` from the recipe page, or paste its prompt into your coding agent.`/hooks` in Claude Code; `grok inspect` in a trusted folder in Grok Build (both hooks show as `[claude]`); Third-Party Imports on in Cursor.` pytest -q tests/test_hooks.py`. The tests pipe sample JSON into the guard in the Claude Code, Cursor and Grok Build shapes. We got 37 passed. The Oct 25 guard against the same tests: 10 failed, 27 passed.`.claude/hooks/` so the guard travels with the repo.\nBuilt the October version? The recipe page has a follow-up prompt that patches each of these gaps and adds a test for each one.\n\nThe page's verified line, word for word: *Verified working in mock mode, Dec 1, 2026. Both hook scripts run with sample inputs in each tool's documented format, plus real pytest runs on a paper bot; not run inside a live agent session. Command substitution, base64 piped into sh, git aliases and globs like .en? still get past the guard.*\n\nHooks only control what the AI coding agent does. They don't control what your running bot does. Position limits, the kill switch and venue cancel-all endpoints in the bot's own code are what protect the money. Keep the bot on Kalshi demo or local paper mode, and have a human type `--live`.\n\nThe full recipe (all four files, the prompt, the follow-up prompt, the Oct 25 findings and every doc we checked) is at **[botcookery.com/recipes/claude-code-hooks-trading-bots](https://botcookery.com/recipes/claude-code-hooks-trading-bots/)**.\n\nAPI changes and new field notes: [@botcookery](https://dev.to/botcookery) on X ([https://x.com/botcookery](https://x.com/botcookery))", "url": "https://wpnews.pro/news/our-claude-code-hook-guard-got-17-of-62-drill-inputs-wrong", "canonical_source": "https://dev.to/botcookery/our-claude-code-hook-guard-got-17-of-62-drill-inputs-wrong-bf4", "published_at": "2026-12-01 15:12:07+00:00", "updated_at": "2026-12-01 15:13:52.007361+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "ai-safety", "developer-tools"], "entities": ["Claude Code", "Cursor", "Grok Build", "Codex", "Kalshi", "Polymarket", "BotCookery"], "also_reported_by": [], "takeaway": "A PreToolUse guard that matches on `tool_name == \"Bash\"` misses Cursor's `Shell`, Grok Build's `run_terminal_command` and Codex's `apply_patch`, and pattern matching alone is bypassed by shell quoting like `cat .e''nv` or `g\\it push`; deciding on input content plus `onFailure: \"block\"` (Claude Code ", "recommendation": {"advice": "Match guard rules on the content of tool inputs rather than tool names, cover shell-quoting and Windows-path variants, and set `onFailure: \"block\"` so a crashing or timing-out hook fails closed instead of allowing the call.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/our-claude-code-hook-guard-got-17-of-62-drill-inputs-wrong", "markdown": "https://wpnews.pro/news/our-claude-code-hook-guard-got-17-of-62-drill-inputs-wrong.md", "text": "https://wpnews.pro/news/our-claude-code-hook-guard-got-17-of-62-drill-inputs-wrong.txt", "jsonld": "https://wpnews.pro/news/our-claude-code-hook-guard-got-17-of-62-drill-inputs-wrong.jsonld"}}