Appendix · Claude
Claude Code Cheat Sheet
CLAUDE.md hierarchy, settings.json, permissions, hooks, Skills, commands, subagents, plan mode, headless mode, MCP config and session commands.
Configuration hierarchy
Precedence (highest → lowest)┌──────────────────────────────────────────────────────────┐│ Managed / enterprise policy (IT-controlled, cannot be ││ overridden by users) │├──────────────────────────────────────────────────────────┤│ Command-line flags (--model, --allowedTools…) │├──────────────────────────────────────────────────────────┤│ .claude/settings.local.json (project, git-ignored) │├──────────────────────────────────────────────────────────┤│ .claude/settings.json (project, checked in) │├──────────────────────────────────────────────────────────┤│ ~/.claude/settings.json (user) │└──────────────────────────────────────────────────────────┘
CLAUDE.md memory (all loaded, most specific wins on conflict) managed policy CLAUDE.md → ~/.claude/CLAUDE.md → ./CLAUDE.md → ./sub/dir/CLAUDE.md CLAUDE.local.md = personal, git-ignored @path/to/file = importWhat belongs where
| Content | Put it in |
|---|---|
| Org-wide security rules, banned commands | Managed policy settings.json |
| Repo conventions: build/test commands, architecture, style | ./CLAUDE.md (checked in, concise) |
| Module-specific guidance | ./module/CLAUDE.md |
| Personal shortcuts, local paths | ~/.claude/CLAUDE.md or CLAUDE.local.md |
| Long reference docs | Separate file, @import it or make a Skill |
| Reusable multi-step procedure | Skill (.claude/skills/<name>/SKILL.md) |
| Parameterised one-liner | Slash command (.claude/commands/<name>.md) |
| Delegated task needing isolated context/tools | Subagent (.claude/agents/<name>.md) |
| External system access | MCP server (.mcp.json) |
| Hard rule that must never be broken | Hook (deterministic) – never just a CLAUDE.md sentence |
Example CLAUDE.md
# Project: payments-api
## Commands- Install: `pnpm install` · Test: `pnpm test` · Lint: `pnpm lint` · Typecheck: `pnpm tsc --noEmit`
## Architecture- Hexagonal: `src/domain` (pure), `src/adapters` (IO). Never import adapters from domain.- All money values are integer minor units (cents). Never floats.
## Workflow- Run `pnpm test` before proposing a commit. Use conventional commits.- Prefer plan mode for changes touching more than 3 files.
@docs/api-conventions.mdsettings.json
{ "model": "claude-opus-5", "permissions": { "allow": ["Read", "Edit", "Bash(pnpm test*)", "Bash(pnpm lint*)", "Bash(git status*)", "Bash(git diff*)"], "ask": ["Bash(git commit*)", "Bash(git push*)", "WebFetch"], "deny": ["Bash(rm -rf*)", "Bash(git push --force*)", "Read(.env*)", "Read(**/secrets/**)"] }, "env": { "NODE_ENV": "test" }, "hooks": { "PreToolUse": [{ "matcher": "Bash", "hooks": [{ "type": "command", "command": ".claude/hooks/guard.sh" }] }], "PostToolUse": [{ "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "pnpm lint --fix $CLAUDE_FILE_PATHS" }] }] }}Hooks
| Event | Fires | Typical use |
|---|---|---|
SessionStart | New/resumed session | Load env, print status |
UserPromptSubmit | Before the prompt is processed | Inject context, block disallowed prompts |
PreToolUse | Before a tool runs | Block destructive commands, enforce policy |
PostToolUse | After a tool succeeds | Lint/format, run tests, log |
Notification | Claude needs attention | Desktop/Slack ping |
Stop | Main agent finishes | Verify tests ran; enforce “did you run tests?” |
SubagentStop | A subagent finishes | Aggregate results |
PreCompact | Before compaction | Persist critical state to files/memory |
Hook contract: receives JSON on stdin (tool name, input, session id); exit 0 = allow, exit 2 = block and feed stderr back to Claude; other non-zero = non-blocking error. May also emit JSON on stdout for structured decisions.
#!/usr/bin/env bash# .claude/hooks/guard.sh – block destructive shellcmd=$(jq -r '.tool_input.command // empty')if echo "$cmd" | grep -Eq 'rm -rf|git push --force|drop table|mkfs|dd if='; then echo "Blocked by policy: destructive command" >&2 exit 2fiexit 0Skills
.claude/skills/release-notes/└── SKILL.md---name: release-notesdescription: Generate release notes from merged PRs since the last tag. Use when asked for a changelog or release summary.---1. Run `git describe --tags --abbrev=0` to find the last tag.2. List merged PRs since then with `gh pr list --state merged --search "merged:>$TAG_DATE"`.3. Group by label (feat, fix, chore) and write Markdown under `## vNEXT`.Skills load progressively: only the name/description are in context until Claude decides the skill is relevant. Prefer Skills over bloating CLAUDE.md.
Custom slash commands
Review the diff in $ARGUMENTS for security issues (injection, secrets, authz), then correctness, then style.Output a table: severity | file:line | issue | fix.Invoke: /review src/payments/.
Subagents
---name: security-reviewerdescription: Reviews code changes for security vulnerabilities. Use proactively after edits to auth or payment code.tools: Read, Grep, Globmodel: claude-sonnet-5---You are a security reviewer. Report only findings with file:line, severity and fix. Do not edit files.- Isolated context window; receives only what the parent passes explicitly.
- Own tool allowlist and model (cheaper model for mechanical tasks).
- Manage with
/agents.
Plan mode vs direct
| Choose plan mode when | Choose direct when |
|---|---|
| Multi-file or architectural change | Single-file, obvious edit |
| Unfamiliar codebase | Well-understood area |
| Irreversible operations involved | Read-only or trivially reversible |
| You want to review before execution | Speed matters and risk is low |
Toggle with Shift+Tab; plan mode is read-only until you approve.
Headless / CI
# JSON result for scriptingclaude -p "Summarise failing tests in $(cat test.log)" --output-format json
# Streaming JSON eventsclaude -p "Review this PR" --output-format stream-json
# Restrict tools and permission modeclaude -p "Fix lint errors" --allowedTools "Read,Edit,Bash(pnpm lint*)" --permission-mode acceptEdits
# Resume a sessionclaude --resume <session-id>--permission-mode | Behaviour |
|---|---|
default | Ask per policy |
acceptEdits | Auto-accept file edits, ask for shell |
plan | Plan only |
bypassPermissions | No prompts – sandboxed CI only |
Exit codes surface failures to CI; parse --output-format json for the result and usage.
MCP configuration
claude mcp add github -- npx -y @modelcontextprotocol/server-github # local stdio, scope localclaude mcp add --scope project docs -- python mcp_docs_server.py # writes .mcp.jsonclaude mcp add --transport http linear https://mcp.linear.app/mcp # remote Streamable HTTPclaude mcp list// .mcp.json (project scope, checked in){ "mcpServers": { "docs": { "command": "python", "args": ["mcp_docs_server.py"], "env": { "DOCS_ROOT": "./docs" } }, "linear": { "type": "http", "url": "https://mcp.linear.app/mcp" }} }| Scope | Where | Shared? |
|---|---|---|
local | ~/.claude.json under the project path | No |
project | .mcp.json in repo | Yes (checked in) |
user | ~/.claude.json | Across your projects |
Configuration decision table
| You need to… | Mechanism | Not this |
|---|---|---|
| State repo conventions (build/test/style) | ./CLAUDE.md (concise, checked in) | A long README the model must re-read |
| Enforce a rule that must never break | Hook (PreToolUse, exit 2) | A sentence in CLAUDE.md (prompt-as-enforcement) |
| Package a reusable multi-step procedure | Skill (SKILL.md) | Bloating CLAUDE.md |
| Provide a parameterised one-liner | Slash command ($ARGUMENTS) | A Skill (overkill) |
| Delegate an isolated task with its own tools | Subagent (.claude/agents) | Running it in the main context |
| Connect an external system | MCP server (.mcp.json) | A bespoke tool per app |
| Org-wide bans that users cannot override | Managed policy settings | Project settings (overridable) |
| Personal local paths / shortcuts | CLAUDE.local.md / ~/.claude | Checked-in project files |
Exam signal
“The team keeps running a banned command even though CLAUDE.md says not to” → the fix is a PreToolUse hook (deterministic, exit 2), not a stronger sentence. Prompt-as-enforcement is anti-pattern 3.
Precedence worked examples
Scenario A – model conflict managed policy: model = claude-sonnet-5 (locked) ~/.claude/settings.json: model = claude-opus-5 --model claude-haiku-4-5 on the CLI → Effective: claude-sonnet-5 (managed policy wins over everything)
Scenario B – permission conflict project .claude/settings.json allow: Bash(git push*) managed policy deny: Bash(git push --force*) → git push allowed; git push --force denied (deny in a higher scope wins)
Scenario C – CLAUDE.md conflict ./CLAUDE.md: "use tabs" ./frontend/CLAUDE.md: "use 2-space indent" → In frontend/, 2-space wins (most specific file wins on conflict; both are loaded)Hook exit codes and payload
stdin (JSON): { "tool_name": "Bash", "tool_input": { "command": "…" }, "session_id": "…", "cwd": "…" }
exit 0 → allow (stdout may carry structured JSON decision)exit 2 → BLOCK; stderr is fed back to Claude as the reasonother → non-blocking error (logged, action proceeds)| Event | Can block? | Typical use |
|---|---|---|
SessionStart | No | Load env, print status |
UserPromptSubmit | Yes | Inject context; reject disallowed prompts |
PreToolUse | Yes | Block destructive commands, enforce policy |
PostToolUse | No | Lint/format, run tests, log |
Stop | Yes | Enforce “did tests run?” before finishing |
SubagentStop | Yes | Aggregate/validate subagent output |
PreCompact | No | Persist critical state before summarisation |
Notification | No | Desktop/Slack ping |
// Structured stdout decision (alternative to exit code){ "decision": "block", "reason": "Migrations require review", "continue": false }Settings.json full field reference
| Field | Purpose |
|---|---|
model | Default model for the session |
permissions.allow / ask / deny | Tool/command rules by pattern; deny in a higher scope wins |
permissions.additionalDirectories | Extra directories the session may access |
env | Environment variables injected into tool runs |
hooks | Event → matcher → command handlers |
enableAllProjectMcpServers | Auto-approve .mcp.json servers |
enabledMcpjsonServers / disabledMcpjsonServers | Allow/deny specific project MCP servers |
cleanupPeriodDays | Transcript retention |
includeCoAuthoredBy | Toggle the Claude co-author git trailer |
Permission patterns
{ "permissions": { "allow": ["Read", "Edit", "Bash(pnpm test:*)", "Bash(git status)", "Bash(git diff:*)"], "ask": ["Bash(git commit:*)", "Bash(git push:*)", "WebFetch(domain:docs.internal)"], "deny": ["Bash(rm -rf:*)", "Bash(curl:*)", "Read(./.env)", "Read(./**/*.pem)", "Read(**/secrets/**)"]} }- Patterns are prefix + glob;
:*matches arguments. Be specific —Bash(git:*)is broader than you think. - Secret files belong in
denyand in.gitignore; never rely on the model to avoid them. denybeatsallow/ask; a higher-scopedenybeats a lower-scopeallow.
Managed policy for teams
IT ships a managed settings.json (macOS /Library/Application Support/ClaudeCode/managed-settings.json; Linux /etc/claude-code/) that users cannot override:
{ "permissions": { "deny": ["Bash(rm -rf:*)", "Bash(git push --force:*)", "Read(**/*.pem)", "WebFetch"] }, "model": "claude-sonnet-5", "disabledMcpjsonServers": ["*"] }Use it for org-wide bans, an approved default model, and disabling untrusted project MCP servers by default. This is the exam-correct place for “must apply to everyone regardless of local config”.
Common misconceptions
| Misconception | Reality | Why it matters on the exam |
|---|---|---|
| “CLAUDE.md can enforce a hard rule” | Only a hook enforces deterministically | Prompt-as-enforcement anti-pattern |
“CLI --model always wins” | Managed policy overrides CLI flags | Precedence distractor |
“/compact and /clear are the same” | /compact shrinks the same conversation; /clear starts fresh (keeps memory) | Confusing the two loses context |
| “Subagents inherit the parent’s context” | They get only what the parent passes explicitly | Silent-context-loss distractor |
| “More tools = more capable agent” | 4–8 focused tools; beyond ~10 use tool search | Too-many-tools anti-pattern |
| “Plan mode is just slower normal mode” | It is read-only until you approve the plan | Risk-blind distractor |
“.env is safe because the model is careful” | Add it to deny and .gitignore | Secret-leak distractor |
Scenario walkthrough
A 30-engineer team wants Claude Code standardised: nobody may force-push or read secrets, everyone defaults to Sonnet 5, the repo’s build/test conventions are always known, a security review must run after auth changes, and tests must have run before Claude claims it is done.
- Force-push / secret bans for everyone → managed policy
settings.jsondenylist (users cannot override). Project settings are the distractor — they are overridable. - Default model → managed policy
model: claude-sonnet-5. - Build/test conventions always known → checked-in
./CLAUDE.md(concise), not a wiki page. - Security review after auth changes → a
security-reviewersubagent invoked proactively, plus a/security-reviewin CI. A CLAUDE.md reminder is the prompt-as-enforcement distractor. - Tests must have run before finishing → a Stop hook that verifies tests ran and blocks (exit 2) otherwise — deterministic, not a prompt sentence.
- Team rollout → distribute commands/agents/hooks/MCP as a plugin; onboard with a generated guide.
Rejected alternatives: putting bans in project settings (overridable), enforcing “run tests” via CLAUDE.md prose (prompt-as-enforcement), and loading a dozen MCP tools upfront (too-many-tools).
Complete command reference
Every built-in command, bundled skill and bundled workflow available inside a Claude Code session (type / to filter). <arg> = required, [arg] = optional. Availability varies by platform, plan and provider – for example /design, /artifacts, /import and /design-sync are unavailable on Bedrock / Vertex / Foundry, and /upgrade does not appear on Enterprise plans. Skill = a bundled prompt handed to Claude; Workflow = a bundled dynamic workflow that fans out across subagents.
Session, context and memory
| Command | Purpose |
|---|---|
/init | Generate a starter CLAUDE.md; offers to /import Codex or Gemini CLI config if found |
/memory | Edit CLAUDE.md files, toggle auto memory, view auto-memory entries |
/context [all] | Visualise context usage as a grid with optimisation suggestions; all expands the per-item breakdown |
/compact [instructions] | Summarise the conversation to free context; optional focus instructions |
/autocompact [auto|<tokens>] | Set how full the window gets before automatic compaction (e.g. 500k) |
/clear [name] | Start a fresh conversation (keeps project memory); optional label for the /resume picker. Aliases /reset, /new |
/resume [session] | Resume a conversation by ID or name, or open the picker. Alias /continue |
/branch [name] | Branch the current conversation to try a different direction; return with /resume |
/fork [prompt] | Copy the conversation into a new background session and keep working here |
/subtask <task> | Spawn a forked subagent that inherits the conversation; result returns here |
/rewind | Roll conversation and/or code back to a checkpoint, or summarise from a message. Aliases /checkpoint, /undo |
/rename [name] | Name the session (auto-generates from history if omitted) |
/recap | One-line summary of the current session |
/btw [question] | Side question that does not enter the conversation history |
/export [filename] | Export the conversation as plain text |
/copy [N] | Copy the last (or Nth-latest) assistant response; picker for code blocks |
/cd <path> | Move the session to another working directory, keeping the conversation |
/add-dir <path> | Grant file access to an additional directory for this session |
/goal [condition|clear] | Set a goal Claude keeps working toward across turns until met |
/exit | Exit the CLI (detaches if attached to a background session). Alias /quit |
Model, effort and speed
| Command | Purpose |
|---|---|
/model [model] | Switch model (and save as default); s in the picker switches for this session only |
/effort [level|auto|status] | Set effort low … xhigh, max, ultracode, or auto |
/fast [on|off] | Toggle fast mode |
/advisor [model|off] | Consult a second model (fable, opus, sonnet, or an ID) at key moments |
/plan [description] | Enter plan mode, optionally starting on a task |
Permissions, safety and configuration
| Command | Purpose |
|---|---|
/permissions | Manage allow / ask / deny rules by scope, working directories, auto-mode denials. Alias /allowed-tools |
/fewer-permission-prompts | Skill. Scan transcripts for common read-only calls and add an allowlist to project settings |
/auto-mode-setup | Draft autoMode.environment entries from your project and recent sessions |
/sandbox | Toggle sandbox mode (supported platforms) |
/config [key=value …] | Open Settings, or set keys directly (/config model=sonnet, /config thinking=false). Alias /settings |
/hooks | View hook configurations |
/privacy-settings | View/update privacy settings (Pro/Max) |
/keybindings | Open the keyboard-shortcuts file |
/terminal-setup | Install Shift+Enter newline binding (VS Code, Cursor, Zed, Alacritty, …) |
/theme | Change colour theme (auto, light/dark, daltonized, ANSI, custom) |
/color [color|default] | Colour the prompt bar for this session |
/statusline | Configure the status line |
/tui [default|fullscreen] | Switch the terminal renderer |
/focus | Toggle focus view (fullscreen renderer only) |
/scroll-speed | Adjust mouse-wheel scroll speed (fullscreen renderer) |
/vim | Removed in v2.1.92 – use /config → Editor mode |
Skills, agents, plugins, MCP and workflows
| Command | Purpose |
|---|---|
/skills | List skills; filter, sort by token cost, cycle visibility |
/skill-doctor | Show what each skill costs in context and how often it is used |
/reload-skills | Re-scan skill and command directories without restarting |
/agents | Reminder to ask Claude to create/manage subagents (edit .claude/agents/ directly) |
/list-agents | List subagents, agent-team teammates and other sessions Claude can message. Alias /peers |
/tasks | View and manage background work in this session. Alias /bashes |
/background [prompt] | Detach the session to run as a background agent. Alias /bg |
/stop | Stop the attached background session (transcript kept) |
/plugin [subcommand] | Manage plugins (list, install, enable, disable) |
/reload-plugins [--force] | Reload active plugins without restarting |
/mcp [reconnect <server>|enable|disable [<server>|all]] | Manage MCP connections and OAuth |
/workflows | Watch, pause, resume or save dynamic workflows |
/workflow-authoring | Skill. Load the reference for writing dynamic-workflow scripts |
/schedule [description] | Create/update/list/run cloud routines. Alias /routines |
/loop [interval] [prompt] | Skill. Run a prompt repeatedly while the session is open (/loop 5m check the deploy). Alias /proactive |
/batch <instruction> | Skill. Decompose a large change into 5–30 units, one background subagent per unit in its own worktree, each opening a PR |
/deep-research <question> | Workflow. Fan out web searches, cross-check sources, synthesise a cited report |
Code review, verification and shipping
| Command | Purpose |
|---|---|
/diff | Review working-tree changes including Claude’s edits |
/code-review [low|medium|high|xhigh|max|ultra] [--fix] [--comment] [pr#|branch|path] | Skill. Review the diff or a PR for correctness bugs; --fix applies, --comment posts, ultra runs a cloud multi-agent review. Alias /review |
/security-review | Analyse the branch diff for security vulnerabilities (injection, auth, data exposure) |
/simplify [target] | Skill. Four parallel agents propose and apply cleanups (reuse, simplification, efficiency, abstraction level) |
/ultrareview [PR or branch] | Deep multi-agent cloud review (alias of /code-review ultra) |
/verify | Skill. Build, run and observe the app to confirm a change works |
/run | Skill. Launch and drive the project’s app |
/run-skill-generator | Skill. Teach /run and /verify how to build and launch your app |
/autofix-pr [prompt] | Spawn a cloud session that watches the branch’s PR and pushes fixes on CI failure or review comments |
/pr-comments [PR] | Removed in v2.1.91 – ask Claude directly |
Claude API and design skills
| Command | Purpose |
|---|---|
/claude-api [migrate|upgrade|managed-agents-onboard|prompt-audit|cost-optimize|build-eval|hillclimb] | Skill. Load Claude API / Managed Agents reference; migrate to a newer model, upgrade the SDK major, prompt-audit legacy instructions, cost-optimize spend, build-eval an eval set, hillclimb against it |
/dataviz [request] | Skill. Chart/dashboard design guidance with colour-blind-safe palettes |
/design [brief] | Skill. Draft UI mockups as artboards published as an artifact (Anthropic API only) |
/design-sync [hint] | Skill. Upload your repo’s React design system to Claude Design |
/design-login | Authorise design-system access for /design-sync |
/artifacts | List, attach, open or copy artifacts |
Diagnostics, usage and feedback
| Command | Purpose |
|---|---|
/status | Settings → Status tab: version, model, account, connectivity, session kind |
/usage | Session cost, plan usage limits, activity stats. Aliases /cost, /stats |
/usage-credits | Configure or request usage credits when a limit is hit (formerly /extra-usage) |
/rate-limit-options | Ways to keep working when a claude.ai limit blocks a request (hidden; type in full) |
/insights | HTML report analysing your recent sessions |
/doctor | Skill. Setup checkup: installs, PATH, unparseable settings, unused skills/MCP/plugins, slow hooks, CLAUDE.md trimming. Alias /checkup |
/debug [description] | Skill. Enable debug logging and troubleshoot from the session log |
/heapdump | Write a heap snapshot for memory issues (hidden; type in full) |
/bug [report] | Report a bug / share the conversation with consent. Alias /share |
/feedback [report] | Send product feedback (drafts queue when Claude-drafted feedback is on) |
/release-notes | Browse the changelog by version |
/help | Show help and available commands |
/powerup | Interactive feature lessons |
Accounts, integrations and surfaces
| Command | Purpose |
|---|---|
/login / /logout | Sign in / out of your Anthropic account |
/upgrade | Open the plan-upgrade page |
/passes | Share a free week of Claude Code (eligible accounts) |
/stickers | Order stickers |
/radio | Open Claude FM lo-fi radio |
/ide | Manage IDE integrations |
/chrome | Configure Claude in Chrome |
/desktop | Continue the session in the Claude Code Desktop app. Alias /app |
/mobile | QR code for the mobile app. Aliases /ios, /android |
/voice [hold|tap|off] | Voice dictation |
/remote-control | Make this session controllable from claude.ai. Alias /rc |
/teleport | Pull a Claude Code on the web session into this terminal. Alias /tp |
/remote-env | Choose the default environment for cloud agents |
/web-setup | Connect GitHub to Claude Code on the web using local gh credentials |
/install-github-app | Install the Claude GitHub App (github.com only) and optional Actions workflows |
/install-slack-app | Install the Claude Slack app |
/import [codex|gemini|cursor] [--dry-run] [--yes] | Import instruction files, MCP servers, commands, subagents and skills from other tools |
/team-onboarding | Generate a team onboarding guide from 30 days of usage |
/setup-bedrock / /setup-vertex | Provider setup wizards (hidden until CLAUDE_CODE_USE_BEDROCK=1 / CLAUDE_CODE_USE_VERTEX=1) |
/ultraplan <prompt> | Removed – use plan mode |
Exam signal
Commands most likely to appear in exam stems: /init, /memory, /compact vs /clear, /context, /plan, /model, /effort, /permissions, /hooks, /mcp, /agents, /skills, /cost, /rewind, /code-review, /security-review, /doctor. Know the difference between /compact (keep the conversation, shrink it) and /clear (fresh conversation, keep memory), and between /branch (switch into a copy), /fork (copy runs in the background) and /subtask (forked subagent whose result returns).
Scaling patterns
| Need | Use |
|---|---|
| A few delegated tasks per turn | Subagents / forks |
| Dozens–hundreds of coordinated agents | Dynamic workflows (scripted) |
| Named roles collaborating on one task | Agent teams |
| Scheduled recurring jobs | Routines |
| Distributing commands/agents/hooks/MCP | Plugins |
Last updated Sep 18, 2026