cheat sheet

Claude Code Power-User Tips

Advanced Claude Code workflows — effective CLAUDE.md authoring, custom skills, multi-agent patterns, headless scripting, cost control, keyboard shortcuts, prompt caching, and daily workflow techniques.

Claude Code Power-User Tips

What it is

This page is a curated collection of productivity patterns for getting the most out of Claude Code — covering CLAUDE.md authoring, context management, custom skills and slash commands, multi-agent subagent workflows, headless scripting, cost control, prompt-cache hygiene, and session hygiene. These techniques reduce unnecessary token consumption, improve task accuracy, and help Claude act more like a knowledgeable teammate and less like a generic assistant. They assume you have already read Overview and Settings.

CLAUDE.md authoring

A good CLAUDE.md is the highest-leverage investment in Claude Code. It turns Claude from a generic assistant into a teammate who already knows your project's stack, conventions, and pitfalls.

What to include

markdown
# Project: <name>

## Stack (one line per component)
- Python 3.12, FastAPI, SQLAlchemy 2.0
- Postgres 16, Redis, Celery
- Deployed to AWS ECS via GitHub Actions

## Commands
- `make test` — full test suite (pytest + mypy + ruff)
- `make dev` — start dev server with hot reload
- `make migration name=<name>` — create Alembic migration

## Key conventions
- Use `structlog` for all logging — no print()
- API responses always wrap in `{"data": ..., "meta": ...}`
- All public functions need docstrings and type hints
- Test files mirror source structure: `src/users/service.py``tests/users/test_service.py`

## Do not touch
- `alembic/versions/` — only `make migration` should create files here
- `config/production.yaml` — readonly; edit `config/development.yaml` instead

## Architecture notes
- `src/core/` — shared utilities, auth, logging config
- `src/api/` — FastAPI routers only; business logic goes in `src/services/`
- Tasks run in Celery workers in `src/workers/`

What not to include

  • Long prose explanations — Claude reads the code
  • Boilerplate docs that repeat what's in README
  • File listings — Claude reads the directory tree
  • Implementation details that live in the code

Think of CLAUDE.md as "things a new teammate would need to know in the first 30 minutes that they couldn't figure out from the code alone."

Team vs personal CLAUDE.md

Commit CLAUDE.md to the repo for shared conventions. Use ~/.claude/CLAUDE.md for personal preferences (style, tone, shorthand). Subdir CLAUDE.md files are great for component-specific overrides.

text
project/
├── CLAUDE.md               # project-wide
├── frontend/
│   └── CLAUDE.md          # React conventions, component library notes
└── ml/
    └── CLAUDE.md          # Python conventions, GPU notes

Output: (none — file layout, not a command)

Lazy-loaded imports

Use the @path import syntax to split a CLAUDE.md into topic files that are inlined only when Claude is in a relevant subdirectory.

markdown
# Acme API

@./docs/conventions.md
@./docs/architecture.md
@~/.claude/snippets/python-style.md

Output: (none — files inlined at session start)

Custom slash commands

Slash commands let you encode repeatable workflows as named commands stored under .claude/commands/ (project) or ~/.claude/commands/ (personal). See Slash Commands for the full schema.

PR review command

markdown
---
description: "Security-focused diff review"
---

Review the current git diff (staged + unstaged) as if it were a pull request.

Check for:
1. **Security** — hardcoded secrets, injection vulnerabilities, unvalidated input
2. **Correctness** — edge cases, null handling, off-by-one errors
3. **Performance** — N+1 queries, unnecessary loops, missing indexes
4. **Style** — consistency with surrounding code

Format:
- One section per category
- Flag only real issues, not style preferences
- For each issue: file:line, severity (Critical/Warning/Info), one-line fix

Save as ~/.claude/commands/pr-review.md and invoke with /pr-review.

Deploy checklist

markdown
---
description: "Pre-deploy gate"
allowedTools: [Bash(make test:make lint:python scripts/validate_frontmatter.py)]
---

Run the pre-deploy checklist for this project:
1. Run `make test` — report pass/fail
2. Run `make lint` — report any violations
3. Check for TODO/FIXME/HACK comments added in this branch:
   `git diff main --unified=0 | grep -E '(TODO|FIXME|HACK)'`
4. Check that CHANGELOG.md has an entry for today's date
5. Report a final go/no-go with a one-line summary per check.

Quick refactor with arguments

markdown
# ~/.claude/commands/extract.md

Extract the function or block described by "$ARGUMENTS" into its own well-named
helper. Place the helper just above the call site. Add type hints. Do not
change behavior.

Usage: /extract the date-parsing logic in process_invoice()

Output:

text
Proposed diff in src/invoices.py:
  +  def _parse_invoice_date(raw: str) -> date: ...
  ...

Subagent workflows

Subagents (the Task tool) let you spin off isolated work in a subprocess that has its own context window. See Subagents for full details.

Parallel research + write

For large tasks, ask Claude to fan out research and merge results.

text
> Add Redis caching to the user service. Spawn one Plan agent to research the 
  existing service patterns and a second to read our Redis config. Then merge 
  findings and write the implementation.

Output:

text
[Spawns 2 Task subagents in parallel; merges into a plan; implements]

Iterative refinement

text
> Step 1: write a first draft of the migration script
> Step 2: critique it for edge cases  
> Step 3: fix the issues you found

Breaking work into explicit steps produces better results than one large prompt because Claude can revise with full context.

Verification loop

text
> Write the feature, then run `make test` and fix any failures before 
  reporting done.

This pattern — write → test → fix loop — is more reliable than asking Claude to write perfect code in one shot.

Plan mode

Plan mode runs Claude with read-only tools and a system prompt that biases toward analysis over edits. Reach for it when a task is risky or unfamiliar and you want a plan before changes happen.

text
> /plan refactor the auth module to use JWT

Output:

text
[Plan agent investigates, produces a numbered plan, asks for approval before applying]

Approve the plan and Claude implements; reject and the diff is never written.

Cost control

Model selection

TaskRecommended modelWhy
Complex refactors, architectureclaude-opus-4-7Best reasoning
Interactive coding, PR reviewclaude-sonnet-4-6Balanced quality/cost
Summarization, simple editsclaude-haiku-4-5Fastest and cheapest
Batch offline processingclaude-haiku-4-5 + batch API50% batch discount
bash
# Use Haiku for a quick summary task
claude --model claude-haiku-4-5-20251001 -p "Summarize the changes in the last 5 commits"

Output: (none — exits 0 on success)

Scope your prompts

text
# High cost — Claude reads entire codebase
> Refactor the project to use TypeScript

# Lower cost — explicit scope
> Refactor src/api/users.js to TypeScript. Keep the same exports.

Output: (none — example prompts)

Use /compact proactively

Don't wait for the context warning. Run /compact after completing a logical unit of work. This keeps the context window lean and reduces token usage on subsequent turns.

text
> /compact

Output:

text
Compacted 61,970 tokens of history into a 4,210-token summary.

Check session cost

text
> /cost

Output:

text
Session cost: $0.23
  Input tokens:  48,320
  Output tokens: 6,140
  Cache hits:    31,200 (saves ~$0.09)

Prompt caching

Claude Code automatically uses prompt caching for repeated system prompts and tool definitions within a session. To benefit:

  • Keep CLAUDE.md stable — every edit invalidates the cache.
  • Avoid randomising the system prompt mid-session.
  • For long-running headless jobs, pin the model with --model <id> so the cache key stays stable.
bash
# First call writes cache; subsequent calls hit it
claude -p "Analyze this file for security vulnerabilities" < src/auth.py
claude -p "Now check src/db.py the same way" < src/db.py

Output: (none — second call is cheaper due to cache hit)

Headless scripting patterns

Headless mode (-p / --print) is what makes Claude scriptable. The patterns below cover the most common automation surfaces.

Pre-commit hook

A git pre-commit hook that asks Claude to review staged code for critical issues, blocking the commit on failure.

bash
#!/bin/bash
# .git/hooks/pre-commit

STAGED=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(py|ts|js)$')
[ -z "$STAGED" ] && exit 0

REVIEW=$(echo "$STAGED" | xargs cat | claude --allowedTools "" -p \
  "Review for security issues and obvious bugs. 
   If any Critical issues found, output 'BLOCK: <reason>'. Otherwise output 'OK'." \
  --output-format json)

VERDICT=$(echo "$REVIEW" | jq -r '.result')
case "$VERDICT" in
  BLOCK:*) echo "$VERDICT" >&2; exit 1 ;;
  *)       echo "Pre-commit OK"; exit 0 ;;
esac

Output:

text
Pre-commit OK

CI code review

yaml
# .github/workflows/ai-review.yml
- name: AI code review
  run: |
    git diff origin/main...HEAD | claude --allowedTools "" \
      --output-format json \
      -p 'Review this diff for security vulnerabilities only.
          Output JSON: {"issues": [{"file": "", "line": 0, "desc": ""}]}' \
      > review.json
    python3 -c "
    import json
    r = json.load(open('review.json'))
    issues = json.loads(r['result']).get('issues', [])
    if issues:
        for i in issues: print(f'{i[\"file\"]}:{i[\"line\"]} {i[\"desc\"]}')
        exit(1)
    "

Output:

text
src/auth.py:42 SQL query is not parameterized

Automated documentation

bash
#!/bin/bash
for file in src/api/*.py; do
  claude --allowedTools "Read" \
    -p "Generate Markdown API documentation for this file. 
        Cover each public function: purpose, parameters, return value, example." \
    --output-format text < "$file" > "docs/api/$(basename "$file" .py).md"
done

Output:

text
(per-file generated docs/api/*.md)

Periodic refactor sweep

A nightly cron job that asks Claude to identify dead code and open a draft PR.

bash
0 3 * * * cd /home/alice/Code/myproject && \
  claude --dangerously-skip-permissions \
         -p "Find any exported function with zero imports across the repo. \
             Open a draft PR titled 'remove dead code' with the deletions."

Output: (none — exits 0 on success)

Keyboard shortcuts reference

ShortcutAction
TabAutocomplete slash commands and file paths
Up / DownNavigate input history
Shift+EnterInsert newline without submitting
Ctrl+CCancel running operation
Ctrl+DExit Claude Code
Ctrl+LClear the terminal screen
Ctrl+RReverse-search prompt history
EscapeClear current input or dismiss autocomplete
Cmd+Esc (macOS)Open Claude Code from VS Code
Ctrl+Esc (Win/Linux)Open Claude Code from VS Code

Multi-window workflows

For tasks that take a long time, Claude Code supports running multiple sessions in parallel — one for active work, others for background tasks. Combine with tmux or your terminal's split-pane feature.

bash
# Split tmux into two panes; main repo on the left, sandbox repo on the right
tmux new-session -s claude \
  'cd ~/Code/myproject && claude' \
  \; split-window -h \
  'cd ~/Code/sandbox && claude'

Output: (none — opens two tmux panes)

You can also use the EnterWorktree subagent feature to spin Claude up in an isolated git worktree, so background work cannot disturb your main checkout. See Subagents for details.

Status line and ambient context

A custom statusline turns the bottom of your REPL into a glanceable HUD — model name, branch, session cost, last hook event. See Statusline for the full scripting surface.

bash
# Snippet from ~/.claude/statusline.sh
session_id=$(jq -r '.session_id // ""')
model=$(jq -r '.model.id // ""')
branch=$(git -C "$(jq -r '.cwd')" branch --show-current 2>/dev/null)
printf "  %s  %s  %s" "$model" "$branch" "${session_id:0:8}"

Output:

text
  claude-sonnet-4-6  main  sess_01a

Daily workflow

A repeatable rhythm that pairs well with Claude Code on personal projects.

PhaseWhat you do
Pullgit pull && /init if CLAUDE.md is stale
Plan/plan <task> — read-only investigation
BuildApprove plan; let Claude iterate
VerifyAsk Claude to run tests; review diff
Compact/compact to checkpoint
Shipgit commit -am "..." (/ship if you have a skill)

Troubleshooting

Claude keeps asking for permission for the same tools

Add them to the allow list in settings.json:

json
{"permissions": {"allow": ["Bash(npm test:npm run lint)"]}}

Context fills up fast on large repos

  1. Add a .claudeignore file (same syntax as .gitignore) to exclude generated files, build outputs, and large assets.
  2. Use explicit file paths in prompts instead of broad descriptions.
  3. Run /compact more aggressively.
  4. Move detail out of CLAUDE.md into @imports that are loaded only when relevant.

Slow on first run per session

Claude Code re-reads CLAUDE.md files and does directory scanning at session start. This is normal — subsequent turns within the same session are faster because context is already loaded and cached.

Hooks not firing

  1. Check file is executable: chmod +x /path/to/hook.sh
  2. Use absolute paths in settings.json~ is not expanded in all contexts
  3. Test manually:
    bash
    echo '{"tool_input":{"command":"ls"}}' | bash /path/to/hook.sh
    echo $?
    
    Output:
    text
    0
    

MCP server keeps crashing

  1. Run the server's command manually outside Claude to see startup errors
  2. claude mcp restart <name> after fixing
  3. Check that ${ENV_VAR} placeholders in settings.json actually resolve in your shell

"Model overloaded" errors mid-session

Switch model temporarily: /model claude-sonnet-4-6. Anthropic's load-shedding sometimes hits one tier harder than others. Switch back when the burst clears.

Common pitfalls

  1. CLAUDE.md drift — old notes about removed modules confuse Claude; review CLAUDE.md whenever the architecture changes.
  2. Over-broad allow rulesBash(git *) lets Claude git push --force unless you pair it with a deny rule.
  3. Custom commands committed by accident — personal commands belong in ~/.claude/commands/, not .claude/commands/.
  4. Stale prompt cache — editing CLAUDE.md invalidates the cache; batch edits, don't dribble.
  5. /clear after a long task — destroys the conversation; use /compact if you still need the trail.
  6. Headless without --allowedTools — Claude may run prompts that need tools and ask for permission, which hangs forever in non-interactive contexts.
  7. Hook scripts that re-enter Claude — never call claude from a hook script; it deadlocks the harness.