Claude Code · CLI Mastery

Claude Code Deep Dive

Claude Code is your terminal-native agentic engineering partner. This guide covers everything from getting started in 5 minutes to the advanced configurations that engineering teams build their entire workflows around.

📦 Installation 📄 CLAUDE.md ⚡ Slash Commands 📐 Plan Mode 🔧 Power Workflows

Installation & First Run

Claude Code requires Node.js 18+ and an Anthropic API key. Installation takes under 2 minutes:

bash
# Install globally
npm install -g @anthropic-ai/claude-code

# Set your API key (or add to .bashrc/.zshrc)
export ANTHROPIC_API_KEY="sk-ant-..."

# Navigate to your project
cd my-project/

# Start an interactive session
claude

# Or give a one-shot task
claude "Add input validation to all API endpoints and write tests"
💡 Pro Tip

Always start Claude Code from your project root directory. This ensures Claude's Glob and Read tools have access to your full project structure and CLAUDE.md is automatically loaded.

The Claude Code Interface

Once Claude Code is running, you're in an interactive REPL. Here's what you can do:

InputWhat it does
Natural language taskGive Claude a goal to accomplish autonomously
/helpShow available built-in slash commands
/plan "task"Get an implementation plan before Claude starts coding
/edit filepathOpen a specific file for Claude to work on
/run "command"Execute a shell command and show Claude the output
/clearClear conversation context (starts fresh awareness)
/costShow current session token usage and cost estimate
Ctrl+CCancel current Claude operation
exit / quitEnd the Claude Code session

Built-in Tools Reference

Claude Code ships with a suite of built-in tools that allow it to interact with your filesystem, execute commands, and search your codebase. Understanding these helps you write better tasks:

ToolWhat Claude uses it forWhen it activates
ReadReads file contents into contextUnderstanding existing code before editing
WriteCreates new files from scratchGenerating new components, configs, tests
EditMakes targeted edits to existing filesModifying specific functions, adding imports
BashRuns shell commands, sees outputRunning tests, installing deps, building
GrepSearches codebase for patternsFinding all usages of a function, error patterns
GlobLists files matching patternsDiscovering project structure, finding related files
WebSearchSearches the web for docs/solutionsUnfamiliar library APIs, error message research
🔍 How Claude combines these tools

On a task like "add error handling to the payment module", Claude will: Glob to find all payment-related files → Read each file to understand current implementation → Grep to find all function calls → Edit targeted changes → Bash to run tests → Read failure output → iterate. This tool orchestration happens automatically.

CLAUDE.md Mastery

CLAUDE.md is the single most impactful thing you can configure for Claude Code. It's loaded automatically at session start and gives Claude the context it needs to work like a team member who knows your codebase — not a stranger dropped into an unfamiliar repo.

CLAUDE.md Hierarchy

CLAUDE.md files cascade: global (~/.claude/CLAUDE.md) → project root (./CLAUDE.md) → subdirectory (./src/CLAUDE.md). More specific files override more general ones. This lets you set global preferences while having project-specific overrides.

markdown — CLAUDE.md template
# Project: E-Commerce Platform API

## Architecture Overview
- Node.js/Express REST API, PostgreSQL database
- Monorepo: /api (backend), /web (React frontend), /shared (types)
- Authentication: JWT stored in httpOnly cookies
- ORM: Prisma with migrations in /prisma/migrations/

## Coding Conventions
- All functions must have JSDoc comments with @param and @returns
- Error handling: wrap async route handlers with asyncHandler middleware
- Validation: use Zod schemas defined in /src/schemas/
- Tests: Vitest, files named *.test.ts, coverage target 80%
- Imports: always use path aliases (@/utils, @/models, etc.)

## What NOT to do
- Never modify /prisma/schema.prisma — migrations require review
- Do not install new dependencies without noting them in CLAUDE.md
- Do not use any, always use proper TypeScript types

## Common Commands
- Run tests: npm test
- Start dev server: npm run dev  
- Run Prisma migrations: npx prisma migrate dev

## Team Preferences
- Prefer functional components over class components in React
- Always handle loading and error states in UI components
- API responses: { data, error, meta } shape

What Makes a Great CLAUDE.md

🗺️

Architecture Map

Directory structure, technology stack, key files Claude should know about. Claude reads thousands of projects — yours needs a clear map.

📏

Conventions That Aren't Obvious

ESLint caught naming issues. But "we never put business logic in route handlers" isn't lintable — that goes in CLAUDE.md as an explicit rule.

🚫

Explicit Forbidden Actions

"Never modify the migrations folder" or "don't touch auth flows without running the security test suite" — guardrails that prevent costly mistakes.

Quick Run Commands

How to run tests, build the project, start the dev server. Claude can then run these autonomously to verify its own work.

🧪 Exercise 1: Write Your First CLAUDE.md

1
Navigate to any project you're working on: cd your-project
2
Create CLAUDE.md: touch CLAUDE.md
3
Write sections: Project overview, tech stack, directory structure, 3+ conventions, 2+ forbidden actions, and run commands
4
Start Claude: claude and ask "Read my CLAUDE.md and tell me what's missing that would help you work on this project"
5
Iterate based on Claude's feedback — treat it as a conversation about how to onboard yourself as an AI engineer

Custom Slash Commands

Custom slash commands are reusable prompt templates stored as Markdown files. They turn common Claude Code tasks into one-keystroke operations — your team's shared vocabulary for recurring engineering workflows.

Command Storage Locations

Project commands: .claude/commands/ — shared via git with your team
Personal commands: ~/.claude/commands/ — your personal library across all projects

markdown — .claude/commands/review.md
# Code Review

Review the staged git changes as a senior engineer would.
Check for:
- Security vulnerabilities (injection, auth bypass, data exposure)
- Performance issues (N+1 queries, missing indexes, sync where async needed)  
- Missing error handling and edge cases
- Violations of our coding conventions from CLAUDE.md
- Missing or inadequate tests

Output a structured review with:
1. CRITICAL issues (must fix before merge)
2. IMPORTANT issues (should fix, explain why if not)
3. SUGGESTIONS (optional improvements)

End with an overall APPROVE / REQUEST_CHANGES recommendation and one sentence summary.
markdown — .claude/commands/add-tests.md
# Generate Tests for $ARGUMENTS

Add comprehensive tests for the file or function: $ARGUMENTS

Requirements:
- Use Vitest (our test framework per CLAUDE.md)
- Cover: happy path, edge cases, error states, boundary conditions
- Mock external dependencies (don't hit real APIs in tests)
- Follow our pattern in existing test files as reference style
- Target 90%+ branch coverage for this unit
- Include a brief comment explaining what each test group verifies

Run the tests after writing them and fix any failures before finishing.

Use them by typing /review or /add-tests src/auth/login.ts in your Claude Code session. $ARGUMENTS captures whatever you type after the command name.

🧪 Exercise 2: Build Your Command Library

1
Create mkdir -p .claude/commands in your project
2
Create /review command for PR review (use the template above, adapt to your stack)
3
Create /document $ARGUMENTS command that adds JSDoc/docstring to a specified file
4
Create /security-check that audits a module for OWASP Top-10 vulnerabilities
5
Run /review on your latest git diff. Evaluate: does it catch real issues in your code?

Plan Mode — When & How

Plan mode is Claude Code's "show your work" setting. Instead of starting implementation immediately, Claude first proposes a detailed plan for your review and approval. This is critical for:

🏗️

Large Features

Any task spanning multiple files or requiring architectural decisions. Review the plan to catch misunderstandings before hours of implementation.

⚠️

High-Risk Areas

Authentication flows, payment processing, database schema changes — places where an incorrect implementation has serious consequences.

🆕

Unfamiliar Codebases

When Claude is working in a part of the codebase it hasn't touched yet. The plan reveals whether it understood the architecture correctly.

👥

Team Alignment

Share the plan with teammates before Claude implements. Catch disagreements at the planning stage, not in code review.

bash — activating plan mode
# In a Claude Code session, prefix task with /plan
/plan "Refactor the notification system to support multiple channels (email, SMS, push) using the Strategy pattern"

# Or via CLI flag
claude --plan "Add OAuth2 authentication with Google and GitHub providers"

# Claude responds with a structured plan like:
# 1. Analysis of current notification code
# 2. Files I'll create: NotificationStrategy.ts, EmailStrategy.ts, SMSStrategy.ts, PushStrategy.ts
# 3. Files I'll modify: NotificationService.ts, user controller
# 4. Tests I'll write: strategy unit tests, integration tests
# 5. Estimated changes: +280 lines, -45 lines
# Shall I proceed? (y/n/redirect)

Context Management

Claude's 200K context window is large — but long sessions accumulate context that can degrade performance. Here's how to manage it effectively:

⚠️ Context Window Reality

200K tokens ≈ ~150,000 words ≈ a large novel. More than enough for a full session. But as context fills with intermediate outputs, Claude's focus on your original instructions can dilute. Watch for this sign: Claude starts repeating things it already did, or misses constraints from earlier in the session. Time to /clear.

SituationWhat to do
Starting a new unrelated taskUse /clear to reset context. Reload CLAUDE.md context is automatic.
Session getting long, Claude seems confusedSummarize progress manually, then /clear and restart with the summary
Need Claude to focus on one areaExplicitly tell Claude which files to ignore: "Focus only on /src/api — don't read the frontend files"
Multi-day work on same featureAdd a "Current Status" section to CLAUDE.md that you update daily — persistent context across sessions

Hands-on Exercises

These exercises are designed to build real proficiency, not just theoretical knowledge. Complete them in order on a real project:

🧪 Exercise 3: Agentic Feature Implementation

Goal: Experience the full agentic loop on a real feature

1
Pick a small-to-medium feature for a real project (something that would normally take 2-3 hours)
2
Write a clear task description focused on the goal, not the steps. Include: what it should do, who uses it, success criteria
3
Run /plan "your task" first. Review and give Claude any corrections before it starts
4
Let Claude implement without interrupting. Watch what tools it uses in the output
5
Review the output: does it pass tests? Match your standards? Use /review command to run a code review
6
Iterate with natural language corrections until it's ship-ready. Track: how many rounds? What was the final quality?

🧪 Exercise 4: Legacy Code Modernization

Goal: Use Claude Code for a real-world modernization task

1
Find a module in your codebase with no tests, outdated syntax, or technical debt
2
Task: "Analyze [module], identify all technical debt, propose a modernization plan, and implement it with full test coverage"
3
Evaluate Claude's debt analysis — does it catch issues a junior developer would miss?
4
Let it implement. Compare before/after test coverage and code complexity metrics

Power-User Workflows

These workflows are used by engineering teams that have deeply integrated Claude Code into their development process:

The Morning Standup Workflow

At start of day: claude "Review yesterday's commits (git log --since=yesterday), summarize what changed, identify any technical debt created, and suggest what needs attention today". Turns commit history into actionable daily priorities in 60 seconds.

The PR-Ready Workflow

bash
# Before creating a PR, run this custom command:
/pr-prep

# Which does: tests → lint → /review → generate PR description → check for security issues
# Defined in .claude/commands/pr-prep.md:
markdown — .claude/commands/pr-prep.md
Prepare this branch for a pull request: 1. Run the full test suite. Fix any failures before continuing. 2. Run linting. Fix all lint errors. 3. Review staged changes for security and quality issues. 4. Generate a PR description with: Summary, Changes Made, Testing Done, Breaking Changes (if any). 5. Verify all new code has adequate test coverage. Report final status: READY TO MERGE or what needs attention.

The "Explain This" Onboarding Workflow

For new team members: claude "Walk me through the authentication flow in this codebase — from the HTTP request hitting the router, through middleware, to the database query, and back. Explain each step and why it works the way it does." A 3-hour code walkthrough compressed to a focused session.

5min
Time to first agentic task with a good CLAUDE.md
10×
Improvement when CLAUDE.md is well-maintained vs. absent
200K
Context tokens — fits an entire mid-size codebase
<$1
Typical cost per complex agentic task with Claude Sonnet