Contents

Claude Code Best Practices

Once Claude Code is installed in a real repository, the gap between frustrating sessions and dependable daily leverage has very little to do with clever prompting. It comes down to wiring up the surrounding engineering harness properly: permission rules that eliminate prompt fatigue without opening security holes, a lean CLAUDE.md, deterministic Hooks, clean rollback habits, and isolated headless runs.

This guide skips abstract framing and goes straight into the exact configs, commands, syntax pitfalls, and boundaries that hold up in production repositories.

Configure settings.json Permissions First

Out of the box, read-only inspection commands (like git status or git diff) are typically covered by built-in defaults, while running project test and build scripts (pnpm test, pnpm lint) still prompts for approval. Within thirty minutes you either lose focus or start blindly approving prompts—the worst possible failure mode. Put a project-level .claude/settings.json in your repo root (and personal defaults in ~/.claude/settings.json) to allow safe, frequent project scripts while hard-blocking secrets and destructive operations:

{
  "permissions": {
    "allow": [
      "Read",
      "Bash(git status)",
      "Bash(git diff *)",
      "Bash(pnpm test *)",
      "Bash(pnpm vitest run *)",
      "Bash(pnpm typecheck)",
      "Bash(pnpm lint)"
    ],
    "ask": [
      "Bash(git push *)",
      "Bash(git commit *)"
    ],
    "deny": [
      "Bash(sudo *)",
      "Bash(rm -rf /*)",
      "Bash(git push --force *)",
      "Read(**/.env)",
      "Read(**/.env.*)",
      "Read(**/secrets/**)",
      "Read(~/.ssh/*)"
    ]
  }
}

Three rules in the permission engine trip people up constantly:

  1. Evaluation order is strictly deny → ask → allow, first match wins. A matching deny rule can never be overridden by a narrower allow entry.
  2. Whitespace inside Bash(...) matters: Bash(ls *) requires a space after ls and matches directory listings; omitting the space (Bash(ls*)) unintentionally matches commands like lsof.
  3. Read(...) uses gitignore-style globs: Read(./.env) only blocks the root .env file. In a monorepo, use Read(**/.env) and Read(**/.env.*) so nested package secrets are blocked recursively.

Keep CLAUDE.md Under ~80 Lines of Non-Obvious Facts

Root CLAUDE.md is injected into every session. Once it swells past 150 lines with prose explanations, style guides, and stale debugging notes, signal drops fast. Keep it strictly to what cannot be inferred cleanly from the code: targeted test commands, non-negotiable contracts, internal helpers to reuse, and hard prohibitions:

# Stack & Entry Points
- TypeScript (strict), Next.js App Router, Prisma + PostgreSQL, pnpm
- `src/app/api/`: HTTP routes only (keep business logic in `src/services/`)
- `src/schemas/`: shared Zod schemas

# Verification
- Single test file: `pnpm vitest run <path>`
- Static checks: `pnpm typecheck && pnpm lint`
- Schema change: always run `pnpm prisma generate` afterward

# Hard Constraints
- Do not change response shapes under `src/app/api/` without explicit approval
- Use `src/lib/http.ts` for outbound requests; do not add raw `fetch` wrappers
- Never edit or delete existing files under `prisma/migrations/`

In monorepos, push module-specific conventions into subdirectory CLAUDE.md files (such as apps/mobile/CLAUDE.md) or modular markdown files under .claude/rules/. They load on demand without bloating the root file.

Give Verification Up Front and Split Reading from Editing

Most bad diffs happen when Claude starts editing before understanding existing invariants—and has no objective check to prove its fix works. Make two habits automatic:

  • Attach an explicit test command or reproducible failure to every task.
  • Split multi-file work into two turns: read and propose a plan first, edit only after you sign off on the file list.

Compare how differently the same 500 bug plays out:

# Invites band-aid patches
/api/orders/export occasionally throws 500—please find and fix it.

# Repro-driven and bounded
/api/orders/export returns 500 when exporting >1,000 rows (stack trace below).
Read `src/app/api/orders/export/route.ts` and `src/services/export.ts` first without changing
production code. Write a failing test in `src/services/export.test.ts` that reproduces the 500.
Once it fails reliably, propose the fix without changing CSV column order.

The same applies to UI changes: attach a screenshot, explicitly freeze existing API calls and form validation, restrict edits to existing components in src/components/ui/, and require pnpm build at the end.

Enforce Hard Rules with Hooks (and Watch the Exit Code)

Anything written in CLAUDE.md or .claude/rules/ is still advisory—long sessions can drift past it. For zero-tolerance rules like automatic formatting or blocking destructive shell commands, use Hooks across Claude Code’s 25 lifecycle events (PreToolUse, PostToolUse, Stop, etc.).

One subtle detail in PreToolUse scripts catches almost everyone:

  • exit 0: allows the tool call to proceed through normal permission checks.
  • exit 2: blocks the tool call deterministically, and anything printed to stderr is fed directly back to Claude as reasoning so it can self-correct.
  • Any other non-zero exit code (including exit 1): treated as a non-blocking script error—the command still runs.

Drop this into .claude/settings.json to wire up automatic Prettier formatting after edits plus a hard bash guard before execution:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path // empty' | xargs -r npx prettier --write"
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/guard-bash.sh"
          }
        ]
      }
    ]
  }
}

Pair it with an executable .claude/hooks/guard-bash.sh:

#!/usr/bin/env bash
set -euo pipefail

cmd=$(jq -r '.tool_input.command // empty')

if echo "$cmd" | grep -qE '(rm\s+-rf\s+/|git\s+push\s+--force|git\s+reset\s+--hard|chmod\s+777)'; then
  echo "Blocked by project hook: dangerous command '$cmd'. Use a safer alternative or ask the user." >&2
  exit 2
fi

Roll Back Fast with /rewind—and Know Its Blind Spot

When a turn goes sideways, run /rewind (or press Esc twice on an empty prompt) to open the checkpoint menu. You can roll back code only (keeping your investigation context), conversation only, or both.

Critical limitation: /rewind only tracks edits made through Claude’s native file tools (Edit, Write). Anything mutated via Bash—database migrations, sed -i, rm, or mv—cannot be undone by /rewind. Commit clean git checkpoints before running shell-heavy operations.

Offload Runbooks to Skills and Reviews to Subagents

Skills (.claude/skills/<name>/SKILL.md)

Move repeatable multi-step procedures out of CLAUDE.md into Skills. At startup Claude reads only metadata (name, description, when_to_use) and loads the body on demand:

---
name: new-api-route
description: Create a REST API route with Zod schema, service handler, and Vitest tests, then verify typecheck and tests pass.
when_to_use: Use when adding a new backend endpoint under src/app/api/.
allowed-tools: Read, Write, Edit, Bash
model: sonnet
context: fork
---

1. Read an adjacent route in `src/app/api/` to match auth middleware and error codes.
2. Put request/response Zod schemas in `src/schemas/`.
3. Put business logic in `src/services/`, keeping the route handler thin.
4. Write unit tests covering 200, 400 validation failure, and 401 unauthorized.
5. Run `pnpm vitest run <test-file>` and `pnpm typecheck` until both pass.

Setting context: fork runs the skill in an isolated subcontext so intermediate file reads never clutter your main session.

Subagents (.claude/agents/<name>.md)

Reviewing your own diff in the same thread invites confirmation bias. Keep a read-only reviewer subagent with tools locked down so it cannot edit files while auditing:

---
name: pr-reviewer
description: Audit uncommitted git diff for bugs, race conditions, security flaws, and broken contracts.
tools: Read, Glob, Grep, Bash
model: sonnet
---

Run `git diff` and review strictly like a staff engineer:
- Flag real logic bugs, missing edge cases, auth/security issues, and API contract breaks.
- Skip formatting nits already handled by Prettier/ESLint.
- Cite exact file paths and line ranges for every issue.
- Do not modify any files.

Prevent Context Rot: /clear and /compact

  1. /clear between unrelated tasks: Never carry stale diffs from a finished bug fix into a new feature.
  2. Compact proactively at milestones: Once a plan is locked or a phase passes tests, run /compact keep the agreed scope, modified file list, and open edge cases instead of waiting for auto-compaction.
  3. Interrupt early: Hit Esc and /rewind at the first sign of drift rather than debating across five polluted turns.

Wiring MCP Cleanly Across Scopes

When registering MCP servers with claude mcp add, match --transport (http for remote servers, stdio -- <cmd> for local processes) with the right --scope:

  • local (default): saved privately under the current project path in ~/.claude.json.
  • project: saved to .mcp.json in the repo root and committed for the team—never hardcode secrets here; teammates get an approval prompt on first use.
  • user: saved globally across all your local repositories.
# Team-shared remote HTTP MCP (writes .mcp.json)
claude mcp add --transport http --scope project sentry https://mcp.sentry.dev/mcp

# Personal global remote MCP
claude mcp add --transport http --scope user context7 https://mcp.context7.com/mcp

# Local stdio MCP (note the -- separator)
claude mcp add --transport stdio filesystem -- npx -y @modelcontextprotocol/server-filesystem ./docs

Keep active MCP servers minimal—every attached server injects its full tool schemas into your context window.

Headless Automation with claude -p and Git Worktrees

For scripts, CI triage, and batch fixes, run headless mode with claude -p (--print). It accepts piped stdin and exits automatically:

git diff main...HEAD | claude -p "Summarize key behavioral impacts and risks in <=5 bullets"

When automating code edits unattended, never run directly in your active working tree and keep four boundaries distinct: --tools restricts the available tool set, --allowedTools adds auto-approval rules, --permission-mode dontAsk auto-denies unapproved actions (while still inheriting existing settings.json rules), and OS-level isolation requires a container or sandbox (git worktree isolates the branch/working tree, not the OS). Combine them cleanly:

# 1. Create an isolated branch and worktree (keeps your main working tree clean)
git fetch origin
git worktree add ../wt-fix-auth -b fix/auth-tests origin/main
cd ../wt-fix-auth

# 2. Run headlessly: cap available tools with --tools, auto-approve a narrow subset with --allowedTools
claude -p "Fix the failing unit tests under src/auth/ without changing public API signatures." \
  --output-format json \
  --tools "Read,Edit,Bash" \
  --allowedTools "Read,Edit,Bash(pnpm test *)" \
  --permission-mode dontAsk > ../wt-fix-auth-result.json

# 3. Inspect outcome, denials, and diff
jq '{is_error, num_turns, permission_denials, result}' ../wt-fix-auth-result.json
git diff

The JSON payload surfaces result, is_error, num_turns, session_id, and permission_denials, making CI debugging immediate. Use --output-format stream-json when you need live streaming logs.

If your team also runs Codex or GitHub Copilot CLI, this same worktree + verification-first + least-privilege skeleton carries straight across tools.

References