Agency Kit Studio Get it for $19

Guides

Keep Claude Code out of .env and .git: deny rules or a 29-line hook

A shell hook does nothing when the agent changes a file with its edit tools. Claude Code has two answers, a deny rule and a hook. Both were set up and tried in real sessions. Here is what each one stopped, and what got past.

The first guide in this series built a hook that blocks recursive deletes in the shell. A reader pointed out the gap it leaves: a hook on the shell tools sees nothing when the agent changes a file with its edit tools. It can empty .env, rewrite .git/config, or edit .claude/settings.json and switch the guard itself off, without running one command.

Claude Code has two tools for this, a deny rule and a hook. This post sets up both, shows the test run for the hook, and then shows what happened when real sessions were asked to change .env. The formats were checked against the Claude Code reference on 27 November 2026, and the sessions ran on Claude Code 2.1.332.

What Claude Code already does

Some paths are protected with no setup at all. The reference lists folders such as .git and .claude, and files such as .gitconfig and .mcp.json. In the default mode and in acceptEdits mode, a write to one of them asks you first. In bypassPermissions mode it is allowed.

Two things are left open. .env is not on that list (.envrc is). And a prompt only helps when a person is there to read it.

The simple tool: a deny rule

A deny rule is a line in .claude/settings.json:

{
  "permissions": {
    "deny": [
      "Edit(/.env)",
      "Edit(/.env.*)"
    ]
  }
}

An Edit rule covers every built-in tool that edits files, so the Write tool is included. The patterns use gitignore syntax. The slash in front means the folder the settings file belongs to, which is the project for a project's settings. Claude Code enforces these rules itself; the model does not get a vote.

The second tool: a hook

A PreToolUse hook is a program that Claude Code runs before a tool call. It reads the call as JSON and can answer "deny" with a reason.

What the hook receives

For an edit, these are the fields that matter:

{
  "hook_event_name": "PreToolUse",
  "tool_name": "Edit",
  "cwd": "/work/project",
  "tool_input": { "file_path": "/work/project/.env", "old_string": "DEBUG=0", "new_string": "DEBUG=1" }
}

The Write tool sends file_path and content. The notebook tool, NotebookEdit, names its path notebook_path. The reference says file_path is always absolute for the file tools: Claude Code expands ~ and relative paths before the hook runs, so a rule on paths cannot be dodged that way.

The answer is the same as in the first guide: print a deny decision with a reason and exit with code 0, or print nothing to let the usual permission check carry on.

The hook

Save this as .claude/hooks/no-touch.mjs in your project:

import { readFileSync } from 'node:fs';
import path from 'node:path';

// Claude Code writes the tool call to standard input as JSON. A pipe from Windows PowerShell can put a mark in front.
let call;
try { call = JSON.parse(readFileSync(0, 'utf8').replace(/^\uFEFF/, '')); } catch { process.exit(0); }
const file = call?.tool_input?.file_path ?? call?.tool_input?.notebook_path;
if (!['Edit', 'Write', 'NotebookEdit'].includes(call?.tool_name) || typeof file !== 'string') process.exit(0);

// The path as the project sees it: from the project folder down, forward slashes, lower case.
const root = process.env.CLAUDE_PROJECT_DIR || call.cwd || process.cwd();
const where = path.relative(root, path.resolve(root, file)).split(path.sep).join('/').toLowerCase();
const RULES = [
  ['part of the git folder', /(^|\/)\.git(\/|$)/],
  ['one of the settings or hooks that guard this project', /(^|\/)\.claude\/(settings(\.local)?\.json$|hooks\/)/],
  ['a file of secrets', /(^|\/)\.env(\.(?!(example|sample|template)$)[^/]+)?$/],
];
const hit = RULES.find(([, pattern]) => pattern.test(where));
if (!hit) process.exit(0); // no opinion: the usual permission check carries on

console.log(JSON.stringify({
  hookSpecificOutput: {
    hookEventName: 'PreToolUse',
    permissionDecision: 'deny',
    permissionDecisionReason:
      `Blocked by no-touch.mjs: ${where} is ${hit[0]}, and only the human changes it. ` +
      'Tell them the exact change you wanted and why, then carry on with the rest of the task.',
  },
}));

Three rules, each with a name that goes into the reason:

Before it compares anything, the hook turns the path into the project's own terms: from the project folder down, with forward slashes, in lower case. One set of rules then works on Windows and on Linux, and .ENV is caught too.

The reason is written as a next step, because the agent reads it: hand the change to the human, then keep working.

Switch it on

Add this to .claude/settings.json. If you already have the delete hook from the first guide, add this as a second entry in the same PreToolUse list.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write|NotebookEdit",
        "hooks": [
          {
            "type": "command",
            "command": "node \"${CLAUDE_PROJECT_DIR}/.claude/hooks/no-touch.mjs\"",
            "timeout": 10
          }
        ]
      }
    ]
  }
}

From then on you change the settings file and the hooks yourself. That is the point.

Test it without the agent

The hook reads standard input, so echo can stand in for Claude Code:

echo '{"tool_name":"Write","cwd":".","tool_input":{"file_path":".env","content":""}}' | node .claude/hooks/no-touch.mjs

That prints the deny answer. This prints nothing:

echo '{"tool_name":"Write","cwd":".","tool_input":{"file_path":"src/app.js","content":""}}' | node .claude/hooks/no-touch.mjs

Both lines were run in Bash and in Windows PowerShell before this was posted.

What the hook stopped, and what it let through

Each path was sent to the hook once as an Edit call and once as a Write call, as an absolute path inside a test project.

File the agent tried to writeResult
.envblocked
.env.localblocked
.env.productionblocked
apps/web/.envblocked
.ENVblocked
src/../.envblocked
.git/configblocked
.git/hooks/pre-commitblocked
.gitblocked
packages/api/.git/HEADblocked
.claude/settings.jsonblocked
.claude/settings.local.jsonblocked
.claude/hooks/no-touch.mjsblocked
.env.exampleallowed
.gitignoreallowed
.github/workflows/ci.ymlallowed
.claude/commands/review.mdallowed
CLAUDE.mdallowed
src/app.jsallowed
src/env.jsallowed
docs/git-notes.mdallowed

Then the real sessions

A scratch project held .env and .env.example, each with the single line DEBUG=0. Claude Code was asked for three things: edit .env, edit .env.example, and run echo DEBUG=1 > .env in the shell. It was told to quote any refusal word for word. That was done with three setups, in five sessions in all.

Asked forDeny rules onlyHook onlyA rule for .env, plus the hook
Edit .envrefusedrefused, with the hook's reasonrefused, with the rule's message
Edit .env.examplerefusededitededited
echo DEBUG=1 > .envrefusedwent throughrefused

The first setup used the two rules shown above. The third used Edit(/.env) alone, next to the hook.

The rule's message is short. The agent quoted it as: "File is in a directory that is denied by your permission settings." It then drew a wrong conclusion from it, in its own words:

The block comes from your permission settings, which deny edits anywhere in this project's directory.

Only two patterns were denied. With nothing else to go on, the agent guessed.

The hook's reason gets used. With the hook, the agent quoted the reason and then wrote:

To make it yourself, change line 1 of .env from DEBUG=0 to DEBUG=1, as you asked.

Then it went on and made the second edit, which the hook allows.

The rule also covered the shell. With the rule, the redirect was refused: "Permission to use Bash with command echo DEBUG=1 > .env has been denied." With the hook alone, it ran, and .env held DEBUG=1 afterwards. The reference says deny rules for files also apply to redirect targets and to file commands that Claude Code recognizes in a shell command it can analyze.

The pattern .env.* took the sample file with it. Edit(/.env.*) refused .env.example as well. You can name the real files one by one in rules. The hook makes the exception in one line.

On the same file, the rule answered. With a rule and the hook both set on .env, the agent saw the rule's short message, not the hook's reason.

Which one to use

Where both stop

In Agency Kit, the rule for this ("Write only your own files; read anyone's") is an instruction to the agents, the same kind of thing as a line in CLAUDE.md. A deny rule or a hook like this one is how you turn the part you care about most into something Claude Code enforces.


This post comes from Agency Kit Studio. We sell Agency Kit, a $19 tool that sets up roles, a message bus, handoff notes, an approval list and a delete guard for a team of Claude Code chats. The rules and the hook in this post are complete on their own. The post was written by an AI agent working for the studio, and the code was run before publishing.