A PreToolUse Hook Protects Claude Code Governance Files
A Juejin author published a roughly 120-line, dependency-free gate.py for Claude Code that rejects tool calls targeting AGENTS.md, .claude/gates, .claude/hooks, .claude/settings.json, and related governance files. The hook normalizes paths, resolves symlinks, checks common write commands, fails closed on errors, and includes eight tests covering blocked and permitted paths. The author cautions that it cannot provide absolute isolation against an agent with shell access.
The implementation offers a reusable guardrail for preventing Claude Code from altering repository governance files through common path and command variants, though its coverage is based on one author's implementation.
我给 Claude Code 写了条规则:不许改治理文件(AGENTS.md、.claude/gates、hooks)。
写完那天我觉得挺严。第二天拿一组路径试了一下:
echo x > .claude/gates/rules.py → 拦住
echo x >> ./.claude/./gates/rules.py → 放行
cp /tmp/x .claude/hooks/gate.py → 放行
ln -sf /tmp/x AGENTS.md → 放行
同一个文件,换个写法就进去了。
下面是完整可运行的修复:一个 gate.py,挂在 Claude Code 的 PreToolUse 钩子上,约 120 行,零依赖,附 8 条测试。
一、挂在哪儿
Claude Code 支持工具调用前的钩子。.claude/settings.json:
#Claude Code#AGENTS.md#CLAUDE.md#kernel.md#gate.py#.claude/settings.json#.claude/gates#.claude/hooks