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
# 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.
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.
# 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
---
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
---
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
# ~/.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:
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.
> 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:
[Spawns 2 Task subagents in parallel; merges into a plan; implements]
Iterative refinement
> 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
> 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.
> /plan refactor the auth module to use JWT
Output:
[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
| Task | Recommended model | Why |
|---|---|---|
| Complex refactors, architecture | claude-opus-4-7 | Best reasoning |
| Interactive coding, PR review | claude-sonnet-4-6 | Balanced quality/cost |
| Summarization, simple edits | claude-haiku-4-5 | Fastest and cheapest |
| Batch offline processing | claude-haiku-4-5 + batch API | 50% batch discount |
# 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
# 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.
> /compact
Output:
Compacted 61,970 tokens of history into a 4,210-token summary.
Check session cost
> /cost
Output:
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.
# 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.
#!/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:
Pre-commit OK
CI code review
# .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:
src/auth.py:42 SQL query is not parameterized
Automated documentation
#!/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:
(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.
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
| Shortcut | Action |
|---|---|
Tab | Autocomplete slash commands and file paths |
Up / Down | Navigate input history |
Shift+Enter | Insert newline without submitting |
Ctrl+C | Cancel running operation |
Ctrl+D | Exit Claude Code |
Ctrl+L | Clear the terminal screen |
Ctrl+R | Reverse-search prompt history |
Escape | Clear 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.
# 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.
# 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:
claude-sonnet-4-6 main sess_01a
Daily workflow
A repeatable rhythm that pairs well with Claude Code on personal projects.
| Phase | What you do |
|---|---|
| Pull | git pull && /init if CLAUDE.md is stale |
| Plan | /plan <task> — read-only investigation |
| Build | Approve plan; let Claude iterate |
| Verify | Ask Claude to run tests; review diff |
| Compact | /compact to checkpoint |
| Ship | git 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:
{"permissions": {"allow": ["Bash(npm test:npm run lint)"]}}
Context fills up fast on large repos
- Add a
.claudeignorefile (same syntax as.gitignore) to exclude generated files, build outputs, and large assets. - Use explicit file paths in prompts instead of broad descriptions.
- Run
/compactmore aggressively. - Move detail out of CLAUDE.md into
@importsthat 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
- Check file is executable:
chmod +x /path/to/hook.sh - Use absolute paths in
settings.json—~is not expanded in all contexts - Test manually:
Output:
echo '{"tool_input":{"command":"ls"}}' | bash /path/to/hook.sh echo $?0
MCP server keeps crashing
- Run the server's command manually outside Claude to see startup errors
claude mcp restart <name>after fixing- Check that
${ENV_VAR}placeholders insettings.jsonactually 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
- CLAUDE.md drift — old notes about removed modules confuse Claude; review CLAUDE.md whenever the architecture changes.
- Over-broad allow rules —
Bash(git *)lets Claudegit push --forceunless you pair it with a deny rule. - Custom commands committed by accident — personal commands belong in
~/.claude/commands/, not.claude/commands/. - Stale prompt cache — editing CLAUDE.md invalidates the cache; batch edits, don't dribble.
/clearafter a long task — destroys the conversation; use/compactif you still need the trail.- Headless without
--allowedTools— Claude may run prompts that need tools and ask for permission, which hangs forever in non-interactive contexts. - Hook scripts that re-enter Claude — never call
claudefrom a hook script; it deadlocks the harness.