How to stop a Claude Code agent writing outside a directory
When you're sitting in front of an agent, "don't touch anything outside src/ " is enforced by you noticing. Unattended, it has to be enforced by something that runs whether or not anyone is watching. Claude Code gives you two mechanisms for that, and they are not interchangeable. One is declarative and can't express what you probably want. The other can, but is structurally blind to a whole…
Claude Code agents need restrictions when left unattended, and two mechanisms provide this: declarative rules and a code-based solution. The declarative rules, defined in settings.json, use deny and allow lists with gitignore-style paths. However, deny rules block everything, making it hard to specify exceptions. The code-based solution introduces a PreToolUse hook that denies writes outside the project directory.
This hook runs before file-writing tool calls, analyzing the tool name, input, and working directory. If the file path is outside the project, the hook returns a JSON response denying permission, providing a clear instruction to the model. This approach enables fine-grained control over which directories are writable, addressing the key concern of agents writing beyond their intended scope.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — it may contain errors, so check the original before relying on it.