Skip to content AI News: United now bars AI agents from booking its tickets: what you can still use AI for →

Claude Code Best Practices: What to Set Up, Say and Enforce

Claude Code's defaults already handle a lot. New terminal and VS Code sessions start in auto mode on recent versions, Claude hands broad searches to subagents by itself, and long conversations get compacted before the context window fills. What still needs you is what no default can know: the deploy steps in your head and the check that decides when work is done.

If you haven't run a first session yet, start with how to use Claude Code.

Sort every rule into one of two kinds

Anthropic's docs split your instructions in two. Your prompt, CLAUDE.md and skills are read by Claude, which follows them without a guarantee. Hooks, deny rules and managed settings are run by the harness whatever the model decides.

QuestionClaude decidesClaude Code enforces
What to doYour prompt, CLAUDE.md, skills Claude picks up itselfHooks
What it can touchAuto mode's classifierDeny rules, the sandbox in strict mode, managed settings
When it's doneA request for evidence, /goal, /code-reviewTests, typecheck, a Stop hook, CI
How much it spendsEffort level--max-turns or --max-budget-usd with -p, a spend limit
Who has the last wordClaude's summary of its workBranch protection, a person approving the merge

Keep most rules in the first column, since Claude can see the code and judge when a guideline doesn't fit. Move a rule to the second only when it has zero exceptions. A handy signal from the docs: if you keep adding emphasis to a CLAUDE.md line and Claude still misses it, the line belongs in a hook.

Set up the project once

Before you write anything down for Claude, ask whether it could find this by reading the repo and whether it would actually go and look. If both answers are yes, leave it out.

A CLAUDE.md that earns every line

What passes: the commands that confirm work, places where the code misleads, decisions made outside the repo, and anything you've corrected twice.

# Commands
- Install: npm ci
- One test file: npx jest path/to/file.test.ts
- Typecheck: npm run typecheck
- Lint: npm run lint

# Conventions
- Errors go through src/lib/errors.ts. Never throw raw strings.
- src/v1/ still serves traffic. Don't copy its patterns into new code.

# Gotchas
- Integration tests need REDIS_URL, see .env.example
- Run npm ci after starting in a new worktree

Check it loaded with /context. /init drafts one from your codebase, and the work after that is mostly deleting. For where each file lives, see the CLAUDE.md guide.

Folder rules and procedures

A rule for one part of the codebase goes in .claude/rules/ with a paths: filter, so it loads only when Claude touches matching files.

Procedures, like a release or a runbook, go in a skill. Claude sees only its name and description until a task calls for it. For anything with side effects, add disable-model-invocation: true so it runs only when you type its name:

---
name: deploy-staging
description: Deploy the current branch to staging and report the URL.
disable-model-invocation: true
---
1. If the working tree isn't clean, stop and ask.
2. Run npm run build and npm test. On any failure, stop and show the output.
3. Run ./scripts/deploy.sh staging and wait for it to finish.
4. Reply with the staging URL and the commit hash that went out.

Saved as .claude/skills/deploy-staging/SKILL.md, it runs on /deploy-staging. Community skills worth installing are on our Claude Code skills page.

For outside systems, start with their CLI: once gh is signed in, Claude opens pull requests without being told how. Systems without one get an MCP server, added with claude mcp add. Connected servers load their tool names into every session, so switch off the idle ones under /mcp.

Prompt with what only you know

A specific prompt hands Claude information it can't read from the code. Name the file, describe the symptom, say what fixed looks like, and state your preference when two approaches are both reasonable.

VagueSpecific
speed up the reports pagethe /reports page is slow to load. profile the query in src/reports/load.ts, fix the slowest part, and show timings from before and after
clean up the API clientsplit src/api/client.ts into one file per resource. keep every existing import path working and run the typecheck when you're done
make the signup form betterbuild the signup form from the attached mockup. be ambitious: validation messages, empty and error states, keyboard navigation
upgrade the date libraryreplace every moment import with date-fns. if a call has no direct equivalent, leave it and list it for me at the end

The third row uses a phrase the docs recommend. Claude reads a request conservatively and builds the smallest thing that satisfies it, so be ambitious tells it the scope you want.

Let Claude interview you

When you haven't worked out what you want, skip the spec and ask for an interview:

I want to add rate limiting to the public API but haven't thought it through yet. Interview me until you could write the spec, then write it to SPEC.md.

Claude asks multiple-choice questions about what you haven't pinned down. Once SPEC.md exists, build from it in a fresh session, with a clean context and a written definition of done. To keep a small fix small, paste the scope check prompt.

Plan first when the approach is unclear

In plan mode, Claude reads and explores while edits stay blocked until you approve the plan. Prefix one prompt with /plan, cycle to it with Shift+Tab, or launch with claude --permission-mode plan. Ctrl+G opens the plan in your editor before you approve it. To start a project there every time, set permissions.defaultMode to "plan" in .claude/settings.json.

Give Claude a check it can run

Claude stops when the work looks done. With nothing that comes back pass or fail, you end up as the test suite. A test file or a build's exit code lets Claude run the check and fix the failure on its own. Make it as strict as the task needs:

  • In the prompt: "run the auth tests after, and keep going until they pass." No setup; Claude decides when it's satisfied.
  • As a goal: /goal all tests in tests/auth pass and lint is clean has a separate model check the condition after every turn.
  • With a Stop hook: your script runs whenever Claude tries to finish, and a failure sends Claude back to work.
  • By a fresh reviewer: /code-review checks the diff in a subagent that never saw your conversation.

Ask for evidence either way: the command Claude ran and its output. "All tests pass" on its own tells you very little.

The Stop hook for a typecheck goes in .claude/settings.json. Exit code 2 sends Claude back to work, and stderr becomes the reason:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "npm run typecheck 1>&2 || exit 2" }
        ]
      }
    ]
  }
}

The block isn't endless: after eight blocked stops in a row with no tool call between them, Claude Code ends the turn anyway, and CLAUDE_CODE_STOP_HOOK_BLOCK_CAP raises that cap. More patterns are in our Claude Code hooks guide.

Keep sessions focused and stop drift early

Every request resends the whole conversation, so you pay for context you don't need. On a Pro, Max, Team or Enterprise plan, /usage attributes recent usage to skills, subagents, plugins and individual MCP servers.

  • /clear between unrelated tasks.
  • /compact keep the API changes and the test commands condenses a long session around what you name.
  • /btw answers a side question without adding it to the history.
  • Esc stops Claude mid-action and keeps the work so far. Watch the first minute and press it the moment Claude drifts.
  • /rewind, or Esc twice on an empty prompt, rolls code, conversation or both back. Files changed only by a Bash command aren't restored, so keep committing.

After two failed corrections on the same problem, run /clear and write one better prompt that folds in what you learned. A third correction leaves another failed attempt in the context for Claude to re-read.

Set effort on purpose

Effort is the main control for how long Claude thinks, and Opus 5.5, Sonnet 5.5 and Haiku 5.5 default to medium. Use /effort high or /effort xhigh for a bug in code you didn't write. /effort low fits fast back-and-forth where you review each step. Keep max for hard problems Claude works through alone; the docs call it prone to overthinking.

For one tricky turn, type ultrathink in the terminal prompt. Since Claude Code 2.1.311, it can raise that turn to xhigh effort without touching your session setting. "Think hard" and "be thorough" are ordinary text and raise nothing. What else changed is in our note on the late-October releases.

Use subagents where they pay for themselves

A subagent earns its cost when you want parallel work, long output kept out of your session, a reviewer that hasn't seen how the code was written, or a task with fewer tools. Each one sends its own requests and starts without your context, and it's the same model or a smaller one, so it won't produce a smarter answer.

Custom subagents are markdown files in .claude/agents/ or ~/.claude/agents/. Claude Code enforces the tools list, so this reviewer can't edit a file however it's prompted:

---
name: spec-reviewer
description: Reviews changed files against the spec they were built from. Use after a feature is implemented, before opening the PR.
tools: Read, Grep, Glob
---
You're reviewing code you didn't write. Compare the changed files with the spec you're given.
Check that every requirement is implemented and every listed edge case has a test.
Report only gaps that affect correctness, with file and line. Skip style.

Simple jobs can run on Haiku. This one keeps the test log out of your session:

---
name: test-runner
description: Runs the test suite and reports failures. Use after code changes when test results are needed.
tools: Read, Grep, Glob, Bash
model: haiku
maxTurns: 10
---
Run npm test. If everything passes, reply with the number of passing tests.
If anything fails, list each failing test with its assertion message, file and line.
Don't fix anything, and don't paste the full log.

Other fields worth knowing: permissionMode, effort, isolation: worktree for a separate checkout, and memory for notes kept between sessions.

Run parallel work in separate checkouts

Two sessions editing one folder will collide. claude -w feature-auth starts a session in a new git worktree under .claude/worktrees/feature-auth/, on the branch worktree-feature-auth. A fresh checkout has no gitignored files and no installed dependencies, so list the small files you need in .worktreeinclude at the repo root and put the install command in CLAUDE.md:

.env
.env.local
config/dev-credentials.json

For one big mechanical change, /batch migrate every handler to the v2 response helpers splits the work into 5 to 30 units and shows you the plan, then runs each unit in its own worktree and opens a pull request per unit.

Enforce the rules that can't bend

Deny rules hold in every permission mode, bypassPermissions included, which makes them the place for secrets:

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

Read deny rules also cover file commands Claude Code recognizes in Bash, so cat .env is blocked too. A script that opens the file itself gets through, and a WebFetch deny does nothing about curl. For an OS-level limit, turn on /sandbox, which confines shell commands on macOS, Linux and WSL2 and picks up your Read deny rules.

Where a rule lives decides who it binds. .claude/settings.local.json and ~/.claude/settings.json are yours alone. A committed .claude/settings.json covers the whole team, and managed settings from your organization override both. Keep the enforced set small: every hook and deny rule will occasionally fire when it shouldn't, and someone has to maintain each one.

Pick the permission mode for the job

Shift+Tab cycles modes in a session, and --permission-mode sets one at launch.

ModeRuns without askingGood for
Manual (default)Reads onlySensitive work where you review every action
acceptEditsReads, file edits, common filesystem commands like mkdir and mvIterating on code you'll review in the diff
planReads, plus classifier-approved commands when auto mode is availableExploring a codebase before changing it
autoEverything, with a classifier reviewing risky actionsLong tasks
dontAskReads and pre-approved tools; anything that would prompt is deniedCI and scripts
bypassPermissionsEverythingIsolated containers and VMs only

Auto mode's classifier watches for things like curl | bash, production deploys and force pushes over other people's work. If it keeps stopping something routine, describe your setup in ~/.claude/settings.json, since the classifier ignores autoMode in project settings:

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

Keep "$defaults" in every list, or your entries replace the built-in ones. In Manual mode, /fewer-permission-prompts allowlists the read-only commands you keep approving.

Before you leave a run unattended

A run nobody watches needs the right-hand column of the first table filled in for that specific task, down to the turn limit and the person who approves the merge. To pin down the goal and the check in one prompt, paste the long-run task brief.

For scripts, claude -p runs once and exits. --bare skips hooks, skills, plugins, MCP servers and CLAUDE.md, so the run does the same thing on every machine. It doesn't use your subscription login, so it needs ANTHROPIC_API_KEY or your cloud provider's credentials:

for file in $(cat files.txt); do
  claude --bare -p "Migrate $file to the new logger API and commit. Reply OK or FAIL." \
    --allowedTools "Read,Edit,Bash(git add *),Bash(git commit *)" \
    --permission-mode dontAsk \
    --max-turns 20
done

Try it on three files, fix the prompt, then run the rest. For recurring work, /loop 15m repeats a prompt inside a session, and /schedule sets up a cloud task that runs while your laptop is closed. Protect main with a branch rule first.

For ready-made requests, see our Claude Code prompts, and for every command on one page, the Claude Code cheat sheet. Plans and pricing are in our Claude Code review.

Sources

Weekly

New prompts in your inbox

One email a week: the best new prompts and one short guide. Confirm by email and get the free Prompt Cheat Sheet (PDF). Unsubscribe any time. Privacy policy