DEV Community

mibii
mibii

Posted on

Claude Code Cheatsheet: The Terminal AI Agent That Actually Codes

TL;DR — Claude Code is Anthropic's terminal-based agentic coding tool. It reads your codebase, edits files, runs commands, and manages git — all through natural language. This is your practical reference from setup to advanced workflows.


🧠 The Mental Model: Why Not Just Use Chat?

In chat you are the middleman:

You → copy file → paste to Claude → get answer → paste back → run → error → repeat
Enter fullscreen mode Exit fullscreen mode

Claude Code removes you from the loop for the mechanical parts:

You: "Add rate limiting to the auth endpoints"
Claude Code: reads files → understands architecture → edits code → runs tests → commits
Enter fullscreen mode Exit fullscreen mode

The difference: Claude Code has direct access to your filesystem, terminal, and git. It acts, not just talks. You review diffs and approve — the thinking stays yours, the typing goes away.


📁 Project Structure

my-project/
├── CLAUDE.md                  ← project memory, auto-loaded every session
├── .claude/
│   ├── settings.json          ← hooks config (commit to git)
│   ├── settings.local.json    ← permissions (gitignore this)
│   ├── commands/              ← custom slash commands (.md files)
│   │   ├── review.md
│   │   └── fix-issue.md
│   ├── skills/                ← auto-activated workflow modules
│   │   ├── code-review/
│   │   │   └── SKILL.md
│   │   └── test-writer/
│   │       └── SKILL.md
│   └── agents/                ← subagent definitions (.yml files)
│       └── code-reviewer.yml
├── .mcp.json                  ← MCP server definitions
└── src/
Enter fullscreen mode Exit fullscreen mode

Personal (cross-project):

~/.claude/
├── CLAUDE.md        ← global preferences, always loaded
├── commands/        ← personal slash commands
└── skills/          ← personal skills
Enter fullscreen mode Exit fullscreen mode

⚙️ Installation

# macOS
brew install --cask claude-code

# Windows
winget install Anthropic.ClaudeCode

# Linux / native binary (recommended)
curl -fsSL https://claude.ai/install.sh | bash

# Verify
claude doctor

# Authenticate
claude auth login
Enter fullscreen mode Exit fullscreen mode

⚠️ npm install -g @anthropic-ai/claude-code is deprecated. Use the native installer.

Requirements: Claude Pro ($20/mo) or Max subscription, or API key from Anthropic Console.


🚀 First Run In Any Project

cd your-project
claude          # starts interactive session

> /init         # generates starter CLAUDE.md from your codebase
> /status       # see loaded context and model
> /plan         # map project before touching anything
Enter fullscreen mode Exit fullscreen mode

Start with: "What does this project do and how is it structured?" — let Claude orient itself first.


📝 CLAUDE.md — Project Memory

Claude reads this every session. The single most impactful thing to set up.

# Project: E-commerce API

## Build & Test Commands
- `npm run dev` — start dev server on port 3000
- `npm test` — run Jest test suite
- `npm run lint` — ESLint + Prettier check
- `npm run build` — production build

## Architecture
- Next.js 15 with App Router
- PostgreSQL with Prisma ORM
- Authentication via JWT (see src/auth/)
- All API routes in src/app/api/

## Code Conventions
- TypeScript strict mode — no `any`
- Server components by default; `"use client"` only when needed
- Write tests for all new utility functions
- Conventional commits: feat:, fix:, chore:, docs:

## What NOT to Do
- Never modify db/migrations/ manually
- Never commit .env files
- Don't use `console.log` — use logger.ts
Enter fullscreen mode Exit fullscreen mode

Rules for a good CLAUDE.md:

  • Target 50–100 lines. Every line should earn its place.
  • Ask: "Would removing this cause Claude to make a mistake?" If no → cut it.
  • 500+ lines = context bloat = Claude ignores rules buried inside.
  • Use # text shortcut inside a session to instantly append a note.
  • Run /memory to open and edit it mid-session.

⌨️ CLI Flags

Flag What it does
claude "prompt" Start with a prompt
claude -p "prompt" One-shot, non-interactive
claude -c Continue last session
claude --resume Resume by ID or name
claude -n "name" Name the session
claude --worktree Run in isolated git worktree
claude --effort high Max reasoning effort
claude --model opus Override model
claude --add-dir ../lib Grant access to additional directory
claude --debug Enable debug logging
claude --allowedTools "Bash(git:*)" Restrict tool access

⚡ Slash Commands

Session

Command What it does
/clear Delete all conversation history
/compact Compress context into summary (keeps thread)
/context View token usage
/rewind Undo last turn
/cost Show token costs

Model & Config

Command What it does
/model Switch model (sonnet / opus / haiku)
/model opusplan Plan with Opus, execute with Sonnet
`/effort low\ med\
{% raw %}"ultrathink" keyword Trigger deep reasoning on next turn
/config Open settings UI

Workflow

Command What it does
/plan Toggle plan mode — propose before acting
/review Multi-agent code review pipeline
/simplify 3-agent architecture review before PR
/batch Parallel changes across isolated worktrees
/loop Schedule recurring tasks (cron-like)
/debug Automatic debugging workflow
/voice Voice input mode

Memory

Command What it does
/memory Edit CLAUDE.md files
/init Generate CLAUDE.md from codebase
# text Quick-add note to memory
@path File autocomplete in prompt
!command Run shell command inline

⌨️ Keyboard Shortcuts

Shortcut Action
Shift+Tab Cycle permission modes (normal → auto-accept → plan)
Shift+Tab × 2 Enter plan mode directly
Option+T Toggle extended thinking
Option+P Open model picker
Ctrl+G Open current file/diff in editor
Esc+Esc Open rewind/undo
Ctrl+C Cancel current operation
Tab Toggle thinking

🧩 Skills — Auto-Activated Workflows

Skills are Markdown modules Claude loads on demand when context matches — not stuffed into every prompt.

.claude/skills/my-skill/
├── SKILL.md       ← instructions + YAML frontmatter
├── scripts/       ← executable automation
└── references/    ← docs loaded on demand
Enter fullscreen mode Exit fullscreen mode

Example skill:

---
name: generate-commit-messages
description: Generates clear commit messages from git diffs. Use when
  writing commit messages or reviewing staged changes.
---

# Generating Commit Messages

1. Run `git diff --staged` to see staged changes
2. Write a commit message:
   - Summary under 50 chars, imperative mood
   - Blank line, then detailed description
3. Follow conventional commits: feat:, fix:, docs:, chore:
Enter fullscreen mode Exit fullscreen mode

Skills vs Commands:

  • Skills = comprehensive workflows, auto-invoked by context match
  • Commands = quick prompts, invoked explicitly with /

🪝 Hooks — Deterministic Event Scripts

Hooks run shell scripts at lifecycle points. Use for behavior Claude can't reliably self-enforce.

In .claude/settings.json:

{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Write(*.py)",
      "hooks": [{ "type": "command", "command": "python -m black \"$file\"" }]
    }],
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{ "type": "command", "command": "echo 'Running: $TOOL_INPUT'" }]
    }],
    "Stop": [{ "command": "notify-send 'Claude finished'" }]
  }
}
Enter fullscreen mode Exit fullscreen mode

Key hook events:

Event Blockable When
PreToolUse Yes Before any tool executes
PostToolUse No After tool completes
PreCompact No Before context compaction
PermissionRequest Yes Permission dialog shown
WorktreeCreate Yes Before new worktree
TaskCompleted No Task marked complete
Stop No Claude finished turn

Common patterns: auto-format on write, block dangerous commands, secret detection pre-commit, notify on completion.


🤖 Subagents — Parallel Isolated Workers

Subagents are specialized Claude instances with their own context windows.

Define in .claude/agents/:

---
name: code-reviewer
description: Use for thorough code reviews. Focus on security, performance, maintainability.
model: claude-sonnet-4-6
color: orange
---
You are an expert code reviewer.
Structure all feedback as: Summary → Critical Issues → Suggestions → Positives.
Enter fullscreen mode Exit fullscreen mode

Agent team patterns:

Pattern When to use
Orchestrator Central dispatcher routes tasks to specialists
Pipeline Sequential handoff (research → draft → review)
Map-Reduce Parallel then merge (review 10 files at once)
Supervisor Monitor and retry failed agents
Swarm Dynamic peer delegation

Boris Cherny (Claude Code creator) runs 10–15 sessions simultaneously with separate git worktrees. Each session gets its own plan. Competing implementations are then compared.


🔌 MCP Servers — External Tool Connections

# Add via CLI
claude mcp add github -- npx -y @modelcontextprotocol/server-github
claude mcp add playwright -- npx -y @playwright/mcp

# Or in .mcp.json (committed, shared with team)
Enter fullscreen mode Exit fullscreen mode
{
  "mcpServers": {
    "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"] },
    "postgres": { "command": "npx", "args": ["-y", "@mcp/postgres"],
      "env": { "DB_URL": "${DATABASE_URL}" } }
  }
}
Enter fullscreen mode Exit fullscreen mode

Popular MCP servers:

Server What it unlocks
GitHub PRs, issues, repos, actions
JIRA / Linear Ticket workflows
Slack Notifications, search
Postgres / Supabase Direct DB queries
Playwright Browser automation
Notion Knowledge base

📊 Context Management

Usage Status Action
0–50% 🟢 Work freely
50–70% 🟡 Monitor with /context
70–90% 🟠 Run /compact
90%+ 🔴 /clear — mandatory

/clear vs /compact:

  • /compact — summarizes history, preserves thread. Use between sub-tasks.
  • /clear — deletes all history. Use when switching to a different task entirely.

File edits persist after both. Only the conversation is affected.


💸 Cost Tips

  • /effort low for quick iteration — saves thinking tokens
  • /model haiku for mechanical repetitive tasks (renaming, formatting)
  • /compact proactively — larger context = higher cost per token
  • Batch API: 60% off for non-urgent async work
  • Prompt Caching: 30% savings on repetitive sessions with same CLAUDE.md
  • Per-skill effort: add effort: low to commit/scaffold skills, effort: high to security-audit skills

⚡ The Core Workflow

1. cd project && claude

2. "What does this project do?"    ← orient Claude first

3. Shift+Tab → Plan Mode
   "Implement OAuth2 with PKCE"    ← Claude proposes, you review

4. Approve the plan

5. Shift+Tab → Normal Mode         ← Claude executes
   (review diffs, accept/reject)

6. /review                         ← multi-agent review

7. git diff                        ← your final check

8. /compact (if context > 70%)

9. Repeat
Enter fullscreen mode Exit fullscreen mode

Rule of thumb: Plan Mode for anything touching 3+ files. Direct ask for obvious single-line fixes.


🧭 Who Is This For

Use Claude Code if:

  • You work in the terminal and are comfortable reading diffs
  • Your tasks involve multiple files or whole-codebase understanding
  • You want to keep your existing tools and just add AI to the loop
  • You have repetitive mechanical work (tests, docs, refactoring) eating time

Skip Claude Code if:

  • You want inline autocomplete in an IDE → use Cursor or Copilot
  • You're doing a quick one-off question → chat is faster and free
  • You need enterprise audit trails and compliance → look at Amp
  • You don't yet read diffs comfortably → build that skill first

🆚 Claude Code vs Other Tools

Tool Best for
Claude Code Terminal-native, agentic, whole-codebase tasks
Cursor IDE-integrated autocomplete + chat panel
GitHub Copilot Inline autocomplete, tight GitHub integration
Aider Lightweight CLI alternative, supports local models
Gemini CLI Visual assets, free tier to experiment
Claude chat One-off questions, no file access needed

📚 Key Resources

Resource Where
Official docs code.claude.com/docs
Skills docs code.claude.com/docs/en/skills
Hooks docs code.claude.com/docs/en/hooks
MCP servers code.claude.com/docs/en/mcp
Awesome Claude Code github.com/hesreallyhim/awesome-claude-code
Community skills skillsplayground.com
Ultimate guide github.com/FlorianBruniaux/claude-code-ultimate-guide

Based on official Claude Code documentation (code.claude.com), shipyard.build/blog, blakecrosley.com, FlorianBruniaux/claude-code-ultimate-guide, mindwiredai.com. April 2026.

Top comments (0)