AI Cert Prep
Type to search documentation.

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

text
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 = import

What belongs where

ContentPut it in
Org-wide security rules, banned commandsManaged 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 docsSeparate file, @import it or make a Skill
Reusable multi-step procedureSkill (.claude/skills/<name>/SKILL.md)
Parameterised one-linerSlash command (.claude/commands/<name>.md)
Delegated task needing isolated context/toolsSubagent (.claude/agents/<name>.md)
External system accessMCP server (.mcp.json)
Hard rule that must never be brokenHook (deterministic) – never just a CLAUDE.md sentence

Example CLAUDE.md

markdown
# 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.md

settings.json

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

EventFiresTypical use
SessionStartNew/resumed sessionLoad env, print status
UserPromptSubmitBefore the prompt is processedInject context, block disallowed prompts
PreToolUseBefore a tool runsBlock destructive commands, enforce policy
PostToolUseAfter a tool succeedsLint/format, run tests, log
NotificationClaude needs attentionDesktop/Slack ping
StopMain agent finishesVerify tests ran; enforce “did you run tests?”
SubagentStopA subagent finishesAggregate results
PreCompactBefore compactionPersist 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.

bash
#!/usr/bin/env bash
# .claude/hooks/guard.sh – block destructive shell
cmd=$(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 2
fi
exit 0

Skills

text
.claude/skills/release-notes/
└── SKILL.md
markdown
---
name: release-notes
description: 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

.claude/commands/review.md
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

.claude/agents/security-reviewer.md
---
name: security-reviewer
description: Reviews code changes for security vulnerabilities. Use proactively after edits to auth or payment code.
tools: Read, Grep, Glob
model: 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 whenChoose direct when
Multi-file or architectural changeSingle-file, obvious edit
Unfamiliar codebaseWell-understood area
Irreversible operations involvedRead-only or trivially reversible
You want to review before executionSpeed matters and risk is low

Toggle with Shift+Tab; plan mode is read-only until you approve.

Headless / CI

Terminal window
# JSON result for scripting
claude -p "Summarise failing tests in $(cat test.log)" --output-format json
# Streaming JSON events
claude -p "Review this PR" --output-format stream-json
# Restrict tools and permission mode
claude -p "Fix lint errors" --allowedTools "Read,Edit,Bash(pnpm lint*)" --permission-mode acceptEdits
# Resume a session
claude --resume <session-id>
--permission-modeBehaviour
defaultAsk per policy
acceptEditsAuto-accept file edits, ask for shell
planPlan only
bypassPermissionsNo prompts – sandboxed CI only

Exit codes surface failures to CI; parse --output-format json for the result and usage.

MCP configuration

Terminal window
claude mcp add github -- npx -y @modelcontextprotocol/server-github # local stdio, scope local
claude mcp add --scope project docs -- python mcp_docs_server.py # writes .mcp.json
claude mcp add --transport http linear https://mcp.linear.app/mcp # remote Streamable HTTP
claude mcp list
json
// .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" }
} }
ScopeWhereShared?
local~/.claude.json under the project pathNo
project.mcp.json in repoYes (checked in)
user~/.claude.jsonAcross your projects

Configuration decision table

You need to…MechanismNot 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 breakHook (PreToolUse, exit 2)A sentence in CLAUDE.md (prompt-as-enforcement)
Package a reusable multi-step procedureSkill (SKILL.md)Bloating CLAUDE.md
Provide a parameterised one-linerSlash command ($ARGUMENTS)A Skill (overkill)
Delegate an isolated task with its own toolsSubagent (.claude/agents)Running it in the main context
Connect an external systemMCP server (.mcp.json)A bespoke tool per app
Org-wide bans that users cannot overrideManaged policy settingsProject settings (overridable)
Personal local paths / shortcutsCLAUDE.local.md / ~/.claudeChecked-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

text
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

text
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 reason
other → non-blocking error (logged, action proceeds)
EventCan block?Typical use
SessionStartNoLoad env, print status
UserPromptSubmitYesInject context; reject disallowed prompts
PreToolUseYesBlock destructive commands, enforce policy
PostToolUseNoLint/format, run tests, log
StopYesEnforce “did tests run?” before finishing
SubagentStopYesAggregate/validate subagent output
PreCompactNoPersist critical state before summarisation
NotificationNoDesktop/Slack ping
json
// Structured stdout decision (alternative to exit code)
{ "decision": "block", "reason": "Migrations require review", "continue": false }

Settings.json full field reference

FieldPurpose
modelDefault model for the session
permissions.allow / ask / denyTool/command rules by pattern; deny in a higher scope wins
permissions.additionalDirectoriesExtra directories the session may access
envEnvironment variables injected into tool runs
hooksEvent → matcher → command handlers
enableAllProjectMcpServersAuto-approve .mcp.json servers
enabledMcpjsonServers / disabledMcpjsonServersAllow/deny specific project MCP servers
cleanupPeriodDaysTranscript retention
includeCoAuthoredByToggle the Claude co-author git trailer

Permission patterns

json
{ "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 deny and in .gitignore; never rely on the model to avoid them.
  • deny beats allow/ask; a higher-scope deny beats a lower-scope allow.

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:

json
{ "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

MisconceptionRealityWhy it matters on the exam
“CLAUDE.md can enforce a hard rule”Only a hook enforces deterministicallyPrompt-as-enforcement anti-pattern
“CLI --model always wins”Managed policy overrides CLI flagsPrecedence 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 explicitlySilent-context-loss distractor
“More tools = more capable agent”4–8 focused tools; beyond ~10 use tool searchToo-many-tools anti-pattern
“Plan mode is just slower normal mode”It is read-only until you approve the planRisk-blind distractor
“.env is safe because the model is careful”Add it to deny and .gitignoreSecret-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.

  1. Force-push / secret bans for everyone → managed policy settings.json deny list (users cannot override). Project settings are the distractor — they are overridable.
  2. Default model → managed policy model: claude-sonnet-5.
  3. Build/test conventions always known → checked-in ./CLAUDE.md (concise), not a wiki page.
  4. Security review after auth changes → a security-reviewer subagent invoked proactively, plus a /security-review in CI. A CLAUDE.md reminder is the prompt-as-enforcement distractor.
  5. Tests must have run before finishing → a Stop hook that verifies tests ran and blocks (exit 2) otherwise — deterministic, not a prompt sentence.
  6. 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

CommandPurpose
/initGenerate a starter CLAUDE.md; offers to /import Codex or Gemini CLI config if found
/memoryEdit 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
/rewindRoll 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)
/recapOne-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
/exitExit the CLI (detaches if attached to a background session). Alias /quit

Model, effort and speed

CommandPurpose
/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

CommandPurpose
/permissionsManage allow / ask / deny rules by scope, working directories, auto-mode denials. Alias /allowed-tools
/fewer-permission-promptsSkill. Scan transcripts for common read-only calls and add an allowlist to project settings
/auto-mode-setupDraft autoMode.environment entries from your project and recent sessions
/sandboxToggle sandbox mode (supported platforms)
/config [key=value …]Open Settings, or set keys directly (/config model=sonnet, /config thinking=false). Alias /settings
/hooksView hook configurations
/privacy-settingsView/update privacy settings (Pro/Max)
/keybindingsOpen the keyboard-shortcuts file
/terminal-setupInstall Shift+Enter newline binding (VS Code, Cursor, Zed, Alacritty, …)
/themeChange colour theme (auto, light/dark, daltonized, ANSI, custom)
/color [color|default]Colour the prompt bar for this session
/statuslineConfigure the status line
/tui [default|fullscreen]Switch the terminal renderer
/focusToggle focus view (fullscreen renderer only)
/scroll-speedAdjust mouse-wheel scroll speed (fullscreen renderer)
/vimRemoved in v2.1.92 – use /config → Editor mode

Skills, agents, plugins, MCP and workflows

CommandPurpose
/skillsList skills; filter, sort by token cost, cycle visibility
/skill-doctorShow what each skill costs in context and how often it is used
/reload-skillsRe-scan skill and command directories without restarting
/agentsReminder to ask Claude to create/manage subagents (edit .claude/agents/ directly)
/list-agentsList subagents, agent-team teammates and other sessions Claude can message. Alias /peers
/tasksView and manage background work in this session. Alias /bashes
/background [prompt]Detach the session to run as a background agent. Alias /bg
/stopStop 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
/workflowsWatch, pause, resume or save dynamic workflows
/workflow-authoringSkill. 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

CommandPurpose
/diffReview 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-reviewAnalyse 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)
/verifySkill. Build, run and observe the app to confirm a change works
/runSkill. Launch and drive the project’s app
/run-skill-generatorSkill. 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

CommandPurpose
/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-loginAuthorise design-system access for /design-sync
/artifactsList, attach, open or copy artifacts

Diagnostics, usage and feedback

CommandPurpose
/statusSettings → Status tab: version, model, account, connectivity, session kind
/usageSession cost, plan usage limits, activity stats. Aliases /cost, /stats
/usage-creditsConfigure or request usage credits when a limit is hit (formerly /extra-usage)
/rate-limit-optionsWays to keep working when a claude.ai limit blocks a request (hidden; type in full)
/insightsHTML report analysing your recent sessions
/doctorSkill. 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
/heapdumpWrite 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-notesBrowse the changelog by version
/helpShow help and available commands
/powerupInteractive feature lessons

Accounts, integrations and surfaces

CommandPurpose
/login / /logoutSign in / out of your Anthropic account
/upgradeOpen the plan-upgrade page
/passesShare a free week of Claude Code (eligible accounts)
/stickersOrder stickers
/radioOpen Claude FM lo-fi radio
/ideManage IDE integrations
/chromeConfigure Claude in Chrome
/desktopContinue the session in the Claude Code Desktop app. Alias /app
/mobileQR code for the mobile app. Aliases /ios, /android
/voice [hold|tap|off]Voice dictation
/remote-controlMake this session controllable from claude.ai. Alias /rc
/teleportPull a Claude Code on the web session into this terminal. Alias /tp
/remote-envChoose the default environment for cloud agents
/web-setupConnect GitHub to Claude Code on the web using local gh credentials
/install-github-appInstall the Claude GitHub App (github.com only) and optional Actions workflows
/install-slack-appInstall the Claude Slack app
/import [codex|gemini|cursor] [--dry-run] [--yes]Import instruction files, MCP servers, commands, subagents and skills from other tools
/team-onboardingGenerate a team onboarding guide from 30 days of usage
/setup-bedrock / /setup-vertexProvider 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

NeedUse
A few delegated tasks per turnSubagents / forks
Dozens–hundreds of coordinated agentsDynamic workflows (scripted)
Named roles collaborating on one taskAgent teams
Scheduled recurring jobsRoutines
Distributing commands/agents/hooks/MCPPlugins

Last updated Sep 18, 2026