跳到正文
DEV Community· kargathara Aakash·· 42 分鐘前AI 評分70

如何將 Claude Code 的 NEVER 規則移至 settings.json,並讓 hooks 以 exit 2 阻擋操作

Move the NEVER lines out of your CLAUDE.md and into settings.json (and make your hooks exit 2)

AI 導讀

文章示範把 Claude Code 中必須強制執行的規則由 CLAUDE.md 移至 settings.json、sandbox 與 hooks,並按 hook 事件説明 exit 2 的阻擋效果。

正文

If your CLAUDE.md says "NEVER read .env" in capital letters, Anthropic has now told you twice that it's the wrong place for it. Lydia Hallie from the Claude Code team said it in her AI Engineer CODE 2026 talk, and the current Claude Code best practices page says it in writing. Emphasis doesn't help current models, and a rule that must hold doesn't belong in CLAUDE.md at all.

Below is the move, as config you can paste. The settings come from Anthropic's docs, and the talk details come from the official recording.

Thumbnail of Lydia Hallie's talk Rethinking Claude Code at the AI Engineer Code Summit

Image credit: Lydia Hallie and AI Engineer, Rethinking Claude Code Best Practices on YouTube.

The sorting question

Hallie's test for whether something becomes an enforced rule is one line: if Claude gets this wrong once, can I take it back?

Bad code? Revert it. That can stay a guideline, or be left to the model entirely. A secret read into the transcript, uncommitted work thrown away, a force push? Not reversible. Those go into configuration that Claude Code applies itself, so the outcome doesn't depend on what the model remembers.

The docs are blunter. CLAUDE.md is for guidelines, and Claude is allowed to decide a guideline doesn't apply.

A CLAUDE.md doing a settings file's job

Here's a made-up file in the style a lot of repos had earlier this year:

# Project
This is a Next.js app using TypeScript, Prisma and Postgres.
Components live in src/components, API routes in src/app/api.

IMPORTANT: NEVER read .env or .env.local!!
IMPORTANT: ALWAYS run prettier after editing a file.
Do not touch db/migrations under any circumstances.
Think hard and be thorough. Don't stop until everything works.

# Commands
- Test: npm test
- Run one file: npx vitest run path/to/file.test.ts

# Gotchas
- billing/ still calls the old invoices service through a queue, nothing in the repo imports it

Run it through the sorting question and the docs' "What you can stop doing" table:

Line Where it goes
Stack and folder layout Delete. Claude reads the repo
NEVER read .env Deny rule, plus the sandbox
ALWAYS run prettier PostToolUse hook
Don't touch migrations PreToolUse hook that exits 2
Think hard, don't stop until it works Delete. Effort setting, /goal, or a Stop hook
Commands Keep. Claude needs them to check its own work
The invoices queue gotcha Keep. It's exactly what Claude can't see from the code

What survives is short, which is the point. The memory docs target under 200 lines per file.

Deny rules in .claude/settings.json

{
  "permissions": {
    "ask": ["Bash(git push *)"],
    "deny": ["Read(./.env)", "Read(./.env.local)", "Read(./secrets/**)"]
  }
}

Deny rules hold in every permission mode, auto and bypassPermissions included. Hallie notes they're checked before the auto mode classifier, so a matching call never reaches it. The Read rule also catches cat .env, because Claude Code recognizes common file reading commands.

It won't catch a script that opens the file. That's the hole she spends the most time on.

The npm test hole

npm test is routine, auto mode runs it, and it executes your dependencies. A compromised package can open .env or ~/.ssh and send it somewhere, and permissions can't see that because they only judge the command, not what it touches at runtime.

The sandbox closes it at the OS level. Run /sandbox in a session, or set it in settings. Your Read deny rules get passed down to it, and child processes are covered too. The default read policy still allows most of your machine, including ~/.ssh and ~/.aws/credentials, so the sandboxing docs suggest declaring credentials explicitly:

{
  "sandbox": {
    "enabled": true,
    "credentials": {
      "files": [
        { "path": "~/.aws/credentials", "mode": "deny" },
        { "path": "~/.ssh", "mode": "deny" }
      ],
      "envVars": [
        { "name": "GITHUB_TOKEN", "mode": "deny" },
        { "name": "NPM_TOKEN", "mode": "deny" }
      ]
    }
  }
}

Know its edge. The sandbox wraps shell commands and whatever they start. Built-in tools like Read and WebFetch follow permission rules instead, and Hallie points out that MCP servers and hooks run outside it. You want both layers, which is what the best practices page says for anything security related.

Hooks: exit 2 or it didn't happen

This is the one I'd check in your repo today.

Hallie says it in the talk and the hooks reference spells it out. Exit code 1 from a hook, the normal Unix failure code, is a non-blocking error. The action goes ahead. On a task, it gets marked complete anyway. Exit code 2 is the blocking signal, and what your hook prints to stderr goes to Claude as the reason.

Event What exit 2 does
PreToolUse Blocks the tool call
PostToolUse Shows stderr to Claude, the tool already ran
TaskCompleted Keeps the task from being marked complete
Stop Keeps Claude working instead of ending the turn

Formatter after every edit, adapted from the docs:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\"" }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-migrations.sh" }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "npm test 1>&2 || exit 2" }
        ]
      }
    ]
  }
}

And the migrations guard:

#!/bin/bash
# .claude/hooks/protect-migrations.sh
file=$(jq -r '.tool_input.file_path // empty')
case "$file" in
  */migrations/*)
    echo "migrations/ is reviewed by a person. Write the change up instead of editing the file." >&2
    exit 2
    ;;
esac
exit 0

You can check the script before Claude ever calls it by piping fake hook input into it:

chmod +x .claude/hooks/protect-migrations.sh
echo '{"tool_input":{"file_path":"db/migrations/0042_users.sql"}}' | .claude/hooks/protect-migrations.sh; echo $?
# prints the message, then 2
echo '{"tool_input":{"file_path":"src/app.ts"}}' | .claude/hooks/protect-migrations.sh; echo $?
# prints 0

Two caveats from the docs. A Stop hook that blocks eight stops in a row with no tool call between them gets overridden and the turn ends (CLAUDE_CODE_STOP_HOOK_BLOCK_CAP raises it). And if a hook enforces something security related, add onFailure: "block" so a crashed hook blocks instead of waving the action through.

Keep the enforced set small, though. The best practices page says it straight. If you're at forty hooks and deny rules, most of them are probably preferences.

autoMode goes in your home folder

If auto mode keeps blocking something routine, like a push to your deploy repo, describe your setup in plain English rather than approving it by hand every time. Hallie's example was exactly that case, since auto mode by default only trusts the current folder and repo.

{
  "autoMode": {
    "environment": [
      "$defaults",
      "Source control: github.com/example-org and every repo under it"
    ],
    "allow": [
      "$defaults",
      "Deploying to the staging namespace is fine, it resets nightly"
    ]
  }
}

Two gotchas from the auto mode config docs. This block only works in ~/.claude/settings.json, because the classifier ignores autoMode in project settings. And keep "$defaults" in every list, or your entries can replace the built-in rules, including the blocks on force pushes and production deploys. /auto-mode-setup can draft the environment entries for you, and claude auto-mode config shows what's actually in effect.

Bar chart showing human review caught 13.6% of harmful actions and auto mode caught 89%

Image credit: Claude by Anthropic, Auto mode is now the default in Claude Code.

Anthropic leans on auto mode for a reason. In its study of 1,053 paid testers, people caught a planted dangerous command 13.6% of the time and the classifier blocked 89%. Hallie's follow up is the reason deny rules still exist. About one in ten still went through.

Then run the audit

Once the hard rules live in settings, clean up what's left:

/doctor prompt-audit

It flags instructions written for older models, references to files that don't exist anymore, and contradictions across CLAUDE.md, CLAUDE.local.md, AGENTS.md and everything under .claude/. You get proposed edits, and nothing changes until you ask. It needs Claude Code v2.1.283 or later. To audit one folder only, pass its path, like /doctor prompt-audit .claude/skills/deploy.

Where this goes next

Hallie's bigger point is that every job you used to do in the loop has to land somewhere: the model, the harness, or the environment. Anthropic's scale is why they care. Their source control post says merged changes went from about 2,500 a day in May 2026 to over 30,000 a day in September. Her suggested next step after settings is cloud sessions, where the repo is a fresh copy and your .env and SSH keys simply aren't on the machine.

You don't need that scale to use any of the above. Credit to @theprofcode and @ilexax for putting the talk in front of a lot of people this week.

The quickest win in this whole post is still the boring one. Grep your hooks for anything that can exit 1 on failure.

來源:DEV Community · dev.to