You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Boris Cherny (the creator of Claude Code) 15 rules and the 6-step system, alongside advanced workflows, officially recommended best practices, and deep-dive strategies.
1. The Core Execution Engine (System Setup)
Parallel Workspaces: Run 5 to 15 Claude instances simultaneously across different terminal directories. Number your tabs 1-5 and use system notifications to ping you when an agent finishes a task or needs input.
Auto Mode: Use a classifier to automatically approve safe commands, allowing you to run multiple agents in parallel without constantly babysitting them.
Permission Management: Use the "fewer permission prompts" skill, which scans your history and whitelists common safe commands to reduce repetitive approvals. Seasoned users also alias Claude (e.g., alias cc='claude --dangerously-skip-permissions') to stay in a flow state.
Adaptive Effort Levels: Rely on the "extra high" default effort level. The model adaptively decides how much "thinking" a task requires, which is significantly more consistent than forcing "max" effort.
Use Opus for Everything: Default to the Opus model. Despite being larger, it requires less steering, has superior tool use, and hits the correct solution sooner, making it faster and cheaper in the long run.
Focus Mode: Keep Focus mode turned on for "builder" agents to hide intermediate steps so you only see final outputs. Keep it turned off for "reviewer" agents so you can monitor their logic.
2. Advanced Workflow & Automation
Focus on Planning: Prioritize planning over coding. Use "Plan Mode" (often toggled via Shift+Tab) to make Claude explore the codebase in read-only mode. Iterate on its proposed plan together before flipping to auto-execution.
Custom Slash Commands: Combine skills and plugins into multi-step workflows for tasks you do daily. Check these into your .claude/commands/ directory so the whole team can use commands like /commit-push-pr.
Sub-Agents for Delegation: Deploy specialized sub-agents for specific tasks, such as a code-simplifier for post-implementation cleanup or an app-verifier for testing.
The "/go" Skill: Use a short prompt style paired with a custom /go skill to automate verification, code cleanup, and pull request submissions in one seamless chain.
Automated CI & PR Loops: Build automated loops to check Pull Requests every 5 minutes and autonomously fix linting or testing errors in the background.
The "/batch" Command: Use the batch command for massive, repository-wide architectural changes that span hundreds of worktrees.
Git Worktrees: Run multiple Claude Code instances in parallel across different directories to test features without causing Git conflicts.
3. Context & State Management
Maintain the CLAUDE.md File: Treat this file like code. Keep project instructions concise, check it into Git so the team can update it with daily learnings, and delete/restart the file if it becomes bloated.
Scoped Rules Directories: Store conditional instructions in .claude/rules/ using path frontmatter (e.g., **/*.ts). This ensures TypeScript rules only load for TypeScript files, preventing unnecessary context bloat.
Monitor the "/status-line": Track your context window usage (tokens) diligently. Clear the context once it reaches 15-20% to maintain model speed and efficiency.
Thread Branching ("/branch"): Fork a conversation thread when exploring a tangent to avoid polluting your main context window.
Session Resumption ("/resume [ID]"): Jump back to a specific point in a conversation's history if a plan goes off track or an experiment fails.
Automatic Recaps: Rely on automatic recaps during long sessions to summarize agent progress, allowing you to pick up exactly where you left off.
4. Verification, Testing & QA
Self-Verification Loops: Never act as the only feedback loop. Provide Claude with test commands, linting scripts, or expected outputs in your prompt so it can run tests, see its own failures, and fix them autonomously before calling a task done.
The "--chrome" Flag: Use this flag for front-end work so Claude can open a browser, see the UI, and visually verify that components render correctly against your requirements.
The "Grill Me" Process: Instruct Claude to actively interview you about your architectural plans to eliminate ambiguity before implementation. You can also challenge Claude to act as a rigorous code reviewer on your own pull requests.
Stop Interpreting Bugs: Do not summarize issues. Paste the raw CI output, stack trace, or Slack thread directly into the terminal and simply tell Claude to "fix." It performs better with raw data than with human abstractions.
Install LSP Plugins: Utilize official Code Intelligence Plugins (like typescript-lsp or pyright-lsp) to give Claude real-time diagnostic feedback (e.g., type errors, missing imports) as it edits files.
5. Environment Flexibility & Integration
Remote Control ("remote-control"): Pick up your active terminal session directly from the Claude mobile app while you are away from your desk.
Teleportation ("teleport"): Pull a session from your mobile device or the web interface back onto your local machine.
Model Context Protocol Integration: Connect Claude to external data sources. Configure the Model Context Protocol (MCP) to securely hook your agents into Slack, Jira, Notion, or PagerDuty, enabling zero-context-switching workflows (e.g., pasting a Slack thread URL and telling Claude to fix the reported bug).
Claude Code — Practical Mastery Guide for Developers
A no-fluff, deep-dive reference synthesizing official Anthropic docs, Boris Cherny's (Claude Code creator) 15 rules,
community battle-tested patterns, and real-world production workflows.
Last updated: May 2026 · Compatible with Claude Code 2.1+
Claude Code is not a chatbot bolted onto a terminal — it is an agent framework for general computer automation. Anything achievable by typing commands into a computer can be automated through it.
The four constraints that govern everything:
Constraint
Effect
Mitigation
Context window fills fast
Performance degrades; instructions "forgotten"
Aggressive /compact and /clear discipline
No memory between sessions
Cold start on every claude invocation
CLAUDE.md + session recaps
Logic errors ~1.75× higher than human code (ACM 2025)
Every shortcut in any one of these multiplies your failure rate.
2. Installation & Shell Setup
Install & Alias
npm install -g @anthropic-ai/claude-code
# Add to ~/.zshrc or ~/.bashrcalias cc='claude --dangerously-skip-permissions'alias cr='claude --resume'# Resume last sessionalias cn='claude --no-auto-updates'# Pin version in CI
--dangerously-skip-permissions skips every approval prompt. Only use this after you understand what Claude can do to your filesystem. Never use it in shared or production environments.
Auto-permission Whitelist (Safer Alternative)
Instead of blanket --dangerously-skip-permissions, use /permissions to allowlist specific safe commands:
Run /permissions at the start of a new project to review and tune what's allowed.
Source your shell on startup
# ~/.claude/settings.json — global user settings
{
"env": {
"EDITOR": "nvim",
"NODE_ENV": "development"
}
}
Loading Context from environment
# Pipe files/errors directly — Claude receives them as stdin context
cat error.log | claude "fix the root cause"
git diff HEAD | claude "write a commit message"
cat src/auth.ts | claude "audit this for security issues"
Session Management Shortcuts
claude # New session
claude --continue # Resume most recent session
claude --resume # Interactive session picker
claude --resume <id># Jump to specific session ID
3. CLAUDE.md — Your Project Brain
CLAUDE.md is the single most impactful thing you can configure. Claude reads it at the start of every session. It gives persistent context that cannot be inferred from code alone.
Bootstrap with /init
# Inside your project directory:
claude
> /init
/init scans your project, detects build systems, test frameworks, and code patterns, then generates a starter CLAUDE.md. Refine it from there — never treat the generated file as final.
Optimal CLAUDE.md Structure
# <ProjectName>## What This Is
One-paragraph description of the system's purpose and tech stack.
## Commands- Build: `mvn clean package -DskipTests`- Test: `mvn test`- Run: `./run.sh`- Lint: `./mvnw spotless:check`- Single test: `mvn test -Dtest=AuthServiceTest`## Architecture- Entry point: `src/main/java/com/example/App.java`- Config: `src/main/resources/application.properties`- Key patterns: CDI injection throughout, no Spring
- DB: SQLite via JDBC (no ORM)
## Code Conventions- Java 21 with records and sealed interfaces
- No `var` keyword — explicit types always
- All public methods need Javadoc
- Exceptions: checked for business logic, unchecked for infra
## What Claude Gets Wrong (The Living Section)- Do NOT use `Optional.get()` without `isPresent()` check
- Do NOT add `@Transactional` to static methods
- Prefer `Path.of()` over `new File()`- Never import `com.example.legacy.*` — it is deprecated
## Testing Rules- New features require unit + integration tests
- Use `@QuarkusTest` not plain JUnit for integration
- Mock external HTTP calls with `WireMock`## Files to Read First
For auth changes: @src/main/java/com/example/auth/AuthService.java
For DB schema: @src/main/resources/db/migration/V1__init.sql
CLAUDE.md Rules
Do:
Write in declarative, factual statements: "The deployment target is production" — not "You must always..."
Keep it under 200 lines. Use @imports for overflow.
Commit it to git — it belongs to the team, not one developer.
Update it every time Claude makes a mistake that should never recur.
Use /init again after major architecture changes.
Do not:
@-file entire large docs (embeds the full file every run — burns tokens).
Write imperative system-command framing — it triggers Claude's prompt-injection defenses.
Let it grow unboundedly. Prune it quarterly.
Reference Extra Docs Without Embedding Them
## References
For complex error handling patterns, see @docs/error-catalog.md
For the API contract, see @openapi/spec.yaml
Claude reads these on demand, not on every session start.
Scoped Rules — Load Per File Type
Create .claude/rules/ with per-language or per-directory rule files:
<!-- .claude/rules/typescript.md -->---
paths:
- "**/*.ts"
- "**/*.tsx"
---# TypeScript Rules- Prefer interfaces over type aliases
- No `any` — use `unknown` + type guards
- Always return explicit types on public functions
TypeScript rules now load only when Claude edits .ts files. Go rules load only for .go files. Claude never reads conventions for languages it isn't touching.
4. Context Window Management
Context is your most constrained resource. Performance degrades predictably:
Usage Level
Behaviour
Action
0–50%
Full performance
Work freely
50–70%
Slight drift
Monitor
70–90%
Precision loss, more mistakes
Run /compact
90%+
Hallucinations, erratic responses
/clear mandatory
Commands
/usage # Shows token consumption (merged /cost + /stats)
/compact # Compress context — lossy but preserves momentum
/clear # Wipe context — fresh start, use for new tasks
/compact vs /clear — When to Use Each
Situation
Command
Mid-task, fuzzy details OK, staying on same feature
/compact
Task complete, starting genuinely new work
/clear + brief re-brief
Context is corrupted or Claude is going in circles
/clear
Approaching 90% and still mid-task
/compact immediately
Recap Before Clearing
Before wiping context on a long session:
> Summarize: what we built, what's left, and any gotchas I need to know.
Format it so the next Claude instance can pick up immediately.
Paste that summary at the top of your next session.
Thread Branching
When exploring a risky tangent, fork the conversation to avoid polluting your main context:
> /branch
> [explore risky approach here]
> /clear ← kill the branch, main thread is untouched
Automatic Recaps
For long-running agentic sessions, Claude writes periodic recaps summarising progress. Enable/disable in /config. These are invaluable when returning to a session hours later.
5. Planning Before Coding
Planning is more valuable than execution speed. Every senior developer workflow emphasises: plan first, code second.
Plan Mode (Shift+Tab)
Toggle Plan Mode before any non-trivial task:
> [Shift+Tab to activate Plan Mode]
> Analyse the codebase and create a phased plan to add OAuth2 login.
Consider: existing auth flow, DB schema, session management, security.
Do not write code yet — only explore and plan.
Claude explores read-only, proposes a plan. You iterate on the plan. Only then flip to execution.
The "Grill Me" Pattern
Before implementation, have Claude stress-test your design:
> Grill me on this architecture. Ask hard questions about edge cases,
failure modes, and scalability. Don't let me off easy.
Do not write any code until I've answered your questions satisfactorily.
This eliminates ambiguity before it becomes bugs.
Phase-Gated Plans
For large features, enforce checkpoints:
> Create a phased plan with 4 phases. Each phase must have:
- Clear acceptance criteria
- At least one unit test + one integration test
- A /rewind checkpoint before starting the next phase
Do not proceed to phase N+1 without my explicit approval.
Cross-Agent Plan Review
Run a second Claude instance to review the plan before execution:
# Terminal 1 — Architect
claude
> Design the notification system architecture
# Terminal 2 — Reviewer
claude
> Act as a staff engineer. Review this plan critically.
[paste the plan from Terminal 1]
Identify: security holes, scalability limits, missing edge cases.
This is especially effective for cross-model review (Claude + Gemini + GPT-4 on the same plan).
6. Parallel Workspaces & Git Worktrees
Running Multiple Instances
Use numbered terminal tabs (1–5 or more). Each tab runs its own claude session on a different branch/worktree.
Enable Focus Mode for builder tabs (hides intermediate steps, shows only final output). Disable it for reviewer tabs so you can follow the reasoning.
Git Worktrees Setup
# Create isolated worktrees for parallel work
git worktree add ../myapp-auth -b feature/auth main
git worktree add ../myapp-api -b feature/api main
git worktree add ../myapp-payments -b feature/payments main
# Start Claude in each worktreecd ../myapp-auth && claude
cd ../myapp-api && claude
Each Claude instance edits its own working tree. No file conflicts, no branch collisions.
Declarative Worktree Isolation for Sub-Agents
In .claude/agents/my-agent.md:
---isolation: worktree---# My Agent
This agent runs in an isolated git worktree — blast radius controlled.
Worktree isolation is a safety mechanism, not just a parallelism trick. Use it for risky refactors.
System Notifications
# macOS — notify when Claude finishesalias cc='claude && osascript -e "display notification \"Claude finished\" with title \"Claude Code\""'# Linux (notify-send)alias cc='claude; notify-send "Claude Code" "Session finished"'
7. Custom Slash Commands
Slash commands are reusable, team-shared workflows stored in .claude/commands/.
<!-- .claude/commands/commit-push-pr.md -->---
description: Commit staged changes, push branch, and open a PR
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*), Bash(git push:*), Bash(gh pr create:*)
---## Context- Current status: !`git status`- Current diff: !`git diff HEAD`- Branch: !`git branch --show-current`- Recent commits: !`git log --oneline -5`## Task1. Write a conventional commit message based on the diff
2. Stage all changes and commit
3. Push the branch to origin
4. Create a PR with a clear description of what changed and why
5. Output the PR URL
Example: /ticket
<!-- .claude/commands/ticket.md -->---
argument-hint: [ticket-id]
description: Read a JIRA ticket, implement it, and update the ticket
---1. Read ticket $1 using the JIRA MCP server
2. Understand acceptance criteria and edge cases
3. Create a feature branch named feature/$1
4. Implement the feature
5. Run tests — fix any failures before continuing
6. Commit and push
7. Create a PR linking back to $1
8. Update the ticket status to "In Review"
Example: /go (Full-Cycle Automation)
<!-- .claude/commands/go.md -->---
description: Verify, clean up, and ship the current work
---1. Run the full test suite — report any failures
2. Run the linter — fix any issues automatically
3. Simplify any code added in this session (remove dead code, extract constants)
4. Check for TODO comments left behind — resolve or file tickets
5. Run /commit-push-pr
Example: /review (Peer-Review Simulation)
<!-- .claude/commands/review.md -->---
argument-hint: [branch-or-pr-number]
description: Act as a senior engineer reviewing this code
---
Review the diff for:
1. Logic errors and off-by-one conditions
2. Security vulnerabilities (injection, auth bypass, data leaks)
3. Missing error handling
4. Performance bottlenecks
5. Test coverage gaps
Be brutally honest. Do not compliment code that has problems.
Diff: !`git diff main...$1`
Injecting Live Context into Commands
Use ! to run bash inline and embed the output:
- Current branch: !`git branch --show-current`- Failing tests: !`npm test 2>&1 | grep FAIL`- Open TODOs: !`grep -rn "TODO" src/ --include="*.ts"`- Last deploy: !`git log --oneline -1 origin/main`
8. Hooks — Event-Driven Automation
Hooks execute shell commands, HTTP requests, or LLM prompts at specific points in Claude's lifecycle automatically — no manual triggering.
Auto-formatting hooks that run after every edit can consume significant tokens (reported 160k tokens in 3 rounds). Consider running formatters manually between sessions rather than after every edit if token cost matters.
9. Sub-Agents & Delegation
Sub-agents are specialized Claude instances that handle discrete tasks, each with their own context, tools, and permissions.
Define Agents in .claude/agents/
<!-- .claude/agents/code-reviewer.md -->---
name: code-reviewer
description: Reviews code for quality, security, and correctness
model: claude-opus-4-5
tools: Read, Bash(git diff:*), Bash(git log:*)
---# Code Reviewer Agent
You are a senior engineer performing thorough code review.
For every PR or diff you review, assess:
1. Logic correctness — off-by-ones, null safety, race conditions
2. Security — injection, auth, data exposure, dependency vulnerabilities
3. Performance — N+1 queries, unnecessary allocations, blocking I/O
4. Test coverage — what scenarios are not tested
5. Architectural fit — does this code belong here
Output: numbered list of findings with severity (CRITICAL / WARN / INFO).
CRITICAL items must be fixed before merge.
<!-- .claude/agents/security-auditor.md -->---
name: security-auditor
description: OWASP-aware security analysis agent
model: claude-opus-4-5
tools: Read, Bash(grep:*)
---# Security Auditor Agent
Scan for: SQL injection, SSRF, path traversal, hardcoded secrets,
insecure deserialization, missing auth checks, OWASP Top 10.
Flag every finding with CVE reference if applicable.
Invoke Sub-Agents
> Delegate this PR diff to the code-reviewer agent
> Run the security-auditor on src/api/
Plugin Sub-Agents vs .claude/agents/
Plugin sub-agents (shipped inside a plugin package) cannot have hooks, mcpServers, or permissionMode in their frontmatter. If you need those, move the agent definition into .claude/agents/ (project-level) or ~/.claude/agents/ (user-level).
Agent Teams (Parallel Delegation)
> Create a plan for the new payments module, then delegate implementation to 3 parallel agents:
- Agent A: database schema and migrations
- Agent B: backend API endpoints
- Agent C: input validation and error handling
Do not merge until all three complete successfully.
The "Post-Implementation Cleanup" Agent
A code-simplifier sub-agent that runs after every feature:
<!-- .claude/agents/simplifier.md -->---
name: simplifier
description: Remove dead code and simplify after implementation
---
After implementation is complete:
1. Remove any code added and then unused
2. Extract magic numbers into named constants
3. Reduce method complexity — split methods over 30 lines
4. Remove leftover debug logging
5. Ensure every public method has a Javadoc/JSDoc comment
Best reasoning, best tool use, fewer steering corrections needed
Sonnet 4
Day-to-day coding, refactoring, test writing
70% of tasks, faster, cheaper
Haiku
Repetitive/batch tasks, simple edits, CI linting loops
Maximum throughput at minimum cost
Counterintuitive truth: Opus costs more per token but often finishes in fewer turns than Sonnet for complex tasks, making it cheaper end-to-end for multi-step agent workflows.
Adaptive Effort
Claude Code uses an adaptive effort system — the model decides how much "thinking" to apply based on task complexity. Rely on this default rather than forcing max-effort mode on every prompt. Forcing max-effort on trivial tasks wastes tokens and slows responses.
Switch Models Mid-Session
/model claude-opus-4-5 # For a hard architectural decision
/model claude-sonnet-4-5 # Back to day-to-day work
11. MCP Integrations
MCP (Model Context Protocol) connects Claude Code to external systems — think of it as USB-C for AI integrations.
Add MCP Servers
# Via CLI
claude mcp add github -- npx @modelcontextprotocol/server-github
claude mcp add postgres -- npx @modelcontextprotocol/server-postgres
claude mcp add jira -- npx @atlassian/mcp-server-jira
# SSE transport (remote servers)
claude mcp add --transport sse myserver https://my-mcp-server.internal/sse
# With environment variable injection
claude mcp add supabase \
--env SUPABASE_ACCESS_TOKEN=your_token \
-- npx -y @supabase/mcp-server-supabase@latest
Read/create issues, PRs, comments without leaving terminal
JIRA/Linear MCP
Full ticket lifecycle: read → implement → update status
Postgres/SQLite MCP
Query your DB, generate migrations, diagnose slow queries
Playwright MCP
Browser automation — Claude clicks, sees UI, verifies rendering
Slack MCP
Paste a Slack thread URL → Claude reads it and fixes the bug
Filesystem MCP
Enhanced cross-directory file operations
Supabase MCP
Full Supabase project management from the terminal
CLI Tools Beat MCP for Simple Cases
For tools Claude already knows (git, curl, jq, gh), CLI beats MCP — CLI tools are more context-efficient because they don't load tool schemas into the context window.
# Prefer this:
> Run `gh pr list` and summarise what needs review
# Over installing a GitHub MCP server if all you need is PR listing
MCP Security (Critical)
MCP servers can read and write your entire codebase. Before adding any MCP server:
Vet the server source code or use community-vetted lists
Use --env to inject secrets at runtime — never hardcode in .mcp.json
Restrict MCP tools via hooks: match mcp__<server>__<tool> patterns in PreToolUse
Run MCP servers as the least-privileged user possible
Known CVEs in the MCP ecosystem include path traversal and arg injection in early mcp-server-git versions. Audit before trusting.
12. LSP Plugins — Real-Time Diagnostics
LSP (Language Server Protocol) plugins give Claude live type errors, missing imports, and linting feedback as it edits files — without waiting for you to notice a problem.
Also available: C#, Java (jdtls), Kotlin, Swift, PHP, Lua, C/C++. Run /plugin → Discover tab to browse.
You need the corresponding language server binary on your system (the plugin reports if it is missing).
What LSP Plugins Do
Without LSP: Claude edits a file → you run the compiler → you paste errors back → Claude fixes them.
With LSP: Claude edits a file → diagnostics fire immediately → Claude sees errors inline → Claude fixes before moving on.
Boris Cherny attributes a 2–3× quality improvement to giving Claude a self-correction feedback loop. LSP is the most impactful version of this for typed languages.
Playwright MCP for UI Verification
claude mcp add playwright -- npx @playwright/mcp
Now for any UI work:
> Implement the login form, then open the browser and verify it renders correctly.
Check that: the form is centred, errors display below inputs, submit is disabled
when fields are empty.
Claude opens a real browser, interacts with the page, and reports back what it sees — catching visual regressions that unit tests miss.
13. Self-Verification & Testing Loops
Never be the only feedback loop. Always give Claude a way to verify its own work before it declares done.
The Rule
Every non-trivial prompt should include one of:
A test command to run
A lint/type-check command
An expected output to verify against
An explicit "verify before finishing" instruction
> Refactor the auth middleware to use JWT instead of session tokens.
After making changes:
1. Run `mvn test` — fix any failures
2. Run `mvn spotless:check` — fix any style issues
3. Run `curl -X POST /api/login -d '{"user":"test","pass":"test"}'`
and confirm a JWT is returned
Do not call this done until all three pass.
Verification Patterns
Pattern 1: Red-Green Loop
> Write the test first (it should fail).
Then implement the feature until the test passes.
Show me the test output at each step.
Pattern 2: Regression Guard
> Before touching any code, run the full test suite and save the baseline.
After your changes, run again. Report any tests that moved from
green to red — those are regressions you must fix.
Pattern 3: "Prove It Works"
> Implement the caching layer.
Prove it works by: running the benchmark before and after,
and showing me the latency numbers side by side.
Pattern 4: Diff Review
> Before creating the PR, show me the full diff between main and this branch.
Walk me through each change and explain why it is correct.
Never Summarise Bugs — Paste Raw Output
# Do this:
cat ci-output.log | claude "fix all failures"
# Not this:
claude "the tests are failing because of something with the auth module"
Claude performs significantly better on raw stack traces, compiler output, and CI logs than on human abstractions of them.
14. Debugging Techniques
Paste Raw — Never Summarise
Paste the raw CI output, stack trace, compiler error, or Sentry event directly:
# Pipe directly from terminal
kubectl logs pod/api-7d9f4b -n production | tail -100 | claude "diagnose and fix"# Or paste the raw Slack thread URL
claude "Fix the bug reported here. Read the thread: https://myteam.slack.com/archives/C123/p456"
claude --debug
claude --debug
Shows hook execution details, tool call parameters, and internal decision points. Use when a session behaves unexpectedly.
The ! Inline Command Trick
Execute shell commands mid-conversation without leaving Claude:
!git status
!npm test -- --watch
!docker ps
!curl -s http://localhost:8080/health | jq
The command runs, its output lands in context, and Claude can act on it immediately.
Systematic Debugging Pattern
> Debug this failure systematically:
Phase 1: Read the stack trace and identify the failure point
Phase 2: Trace execution backwards to find the root cause
Phase 3: Form a hypothesis
Phase 4: Prove the hypothesis with a minimal reproduction
Phase 5: Fix and verify
Do not jump to Phase 5 without completing 1-4.
After a Mediocre Fix
> Knowing everything you know now, throw away this fix and implement
the elegant solution. The current fix is too hacky to ship.
This resets Claude from patch-mode to solution-mode.
/rewind for Rollback
Esc + Esc → Open rewind menu to restore previous file states
/rewind → Interactive rollback to a past checkpoint
Use /rewind before any risky change as a manual checkpoint. Better: wrap every phase in a git commit so rollback is git reset --hard HEAD~1.
15. CI/CD & PR Automation
Automated PR Review Loop
# poll-pr.sh — runs every 5 minutes in background#!/bin/bashwhiletrue;do
STATUS=$(gh pr checks HEAD --json state -q '.[].state'| sort -u)ifecho"$STATUS"| grep -q "FAILURE";then
gh pr checks HEAD --json name,state,conclusion | \
claude "fix all failing checks. output each fix as a separate commit"fi
sleep 300
done
# Non-interactive execution — for CI and automation
claude --headless "run tests and output results as JSON"
claude --print "summarize the last 10 git commits"
The /batch Command for Repo-Wide Changes
<!-- .claude/commands/batch.md -->---
description: Execute a change across all worktrees in parallel
---
For each worktree listed:
1. Switch to that worktree
2. Apply the change: $1
3. Run tests
4. Commit if tests pass, abort if they fail
5. Report success/failure per worktree
Worktrees: !`git worktree list --porcelain | grep worktree | cut -d' ' -f2`
Use /batch "migrate all console.log to the logger utility" to execute across a monorepo in parallel.
16. Prompting Patterns That Work
Be Specific About What NOT to Do
> Add retry logic to the HTTP client.
Do not use a third-party library. Use only exponential backoff with jitter.
Do not modify the existing request method signature.
Negative constraints prevent the most common Claude drift patterns.
Give Examples
> Rename these methods to follow our naming convention.
Current: getUserById, fetchOrderData, retrieveProductInfo
Target: findUserById, getOrderData, getProductInfo
Pattern: use get* for simple lookups, find* for DB queries
Specify Output Format
> Analyse this code for performance bottlenecks.
Output format:
- Finding: [one sentence]
- Severity: HIGH / MED / LOW
- Fix: [code snippet]
Maximum 5 findings. Most severe first.
"Interview Me" for Ambiguous Requirements
> I want to add a notification system.
Before writing any code, interview me to understand the requirements.
Ask about: delivery channels, reliability guarantees, user preferences,
volume expectations, and failure handling.
Stop when you have enough to write a detailed spec.
Constraint + Verify Pattern
> Add database connection pooling.
Constraints: no new dependencies, compatible with our existing HikariCP setup.
Verify by: running `mvn test` and showing connection pool metrics
in the startup logs.
The "Knowing What You Know" Reset
After several rounds of back-and-forth that haven't resolved a bug:
> Stop. Forget the approaches we tried.
Start fresh. What is the simplest possible explanation for this bug?
Work from first principles.
17. Security Considerations
Never Use --dangerously-skip-permissions in Shared Environments
The alias is for personal dev machines where you understand the blast radius. In:
Shared developer machines: use allowlisted permissions instead
CI/CD: use a dedicated low-privilege API key with minimal filesystem scope
Containers: use --no-update and pin the version
Secrets Management
# Never hardcode in .mcp.json or CLAUDE.md# Always use environment variable references:"env": { "API_KEY": "${MY_API_KEY}" }
# Load from .env before starting claude:source .env && claude
MCP Server Threat Model
Every MCP server is a code execution vector. Before adding one:
□ Is the package published by a trusted org?
□ Is the source code auditable?
□ What file system paths can it access?
□ What network requests can it make?
□ Does it accept user-controlled input directly as shell args?
Known attack patterns: prompt injection via malicious file content, path traversal via repo_path arguments, command injection via unsanitized git refs.
CLAUDE.md Injection Defense
Write CLAUDE.md as factual statements, not imperative commands:
# Good (factual)
The deployment target is production.
This repo uses bun test for testing.
# Bad (triggers injection defenses)
You must always deploy to production.
Always run bun test, never jest.
Imperative framing can trigger Claude's prompt-injection filters, causing it to surface the text as a warning instead of following it.
Context Window Injection Awareness
Be cautious when Claude reads files from untrusted sources (user uploads, external repos, web pages). A malicious file could contain prompt injection payloads designed to override your instructions. Use PreToolUse hooks to validate file paths before reads.
18. Daily Developer Workflow
Morning Startup Ritual
cd my-project
git pull
git checkout -b feature/$(date +%Y%m%d)-my-feature
claude
> /init ← (first time only)
> [Shift+Tab] ← Plan Mode
> Here's what I'm building today: [describe the feature].
Analyse the codebase and give me a phased plan with checkpoints.
During Development
# Start each phase
> Implement Phase 1: [description]
# After each phase
> /rewind ← checkpoint
# When context hits 70%
> /compact
# When switching to a new task
> Summarise what we did and what's left.
[/clear]
> [paste summary] Now let's tackle [next task]
> Run the test suite. Fix any failures.
Summarise what was implemented today in 3 bullet points.
Create a WIP commit with message "WIP: [today's date] - [feature name]"
When Resuming After a Break
claude --continue # Resumes most recent session
Or with a recap:
claude --resume # Pick session from history> What did we accomplish in our last session? What's the next step?
Weekly: Prune CLAUDE.md
> Review our CLAUDE.md. Based on this week's work:
1. What rules proved wrong or outdated?
2. What mistakes did you make that aren't documented?
3. What should we add, remove, or reword?
Output the updated CLAUDE.md content.
19. Anti-Patterns to Avoid
❌ Vibe Coding in Production
Running Claude in auto-execute mode on production-facing code without reviewing the plan, checkpointing with git, or running tests. Works for throwaway MVPs; creates unmaintainable debt in real systems.
Fix: Always plan first, commit at checkpoints, verify with tests.
❌ Letting Context Bloat
Ignoring /usage until Claude starts hallucinating. By the time errors are obvious, 10–20 bad turns have already happened.
Fix: Check /usage every 30 minutes. Clear at 70%, mandatory at 90%.
❌ Summarising Bugs for Claude
"The login is broken because of some auth issue" gives Claude nothing to work with.
Fix:cat auth.log | claude "fix the root cause"
❌ One Giant Session for Multiple Features
Running feature A, B, and C in one continuous session with /compact holding everything together.
Fix: New feature = new session = new branch. Related tasks (e.g., write docs for what you just built) can reuse context. Unrelated tasks get fresh sessions.
❌ Treating Claude as the Author
"Claude wrote this code so it's Claude's responsibility." You own every line in a PR with your name on it, regardless of how it was produced.
Fix: Review every diff before merge. Use the /review command to have Claude peer-review its own work before you review it.
❌ CLAUDE.md Sprawl
A 500-line CLAUDE.md that Claude has to parse on every session start, most of which is irrelevant to the current task.
Fix: Main CLAUDE.md ≤ 150 lines. Overflow to @imports. Language-specific rules in .claude/rules/. Delete rules that are never triggered.
❌ Trusting All MCP Servers
Installing every MCP server that looks useful without auditing the source.
Fix: Read the source, check for known CVEs, use --env for secrets, restrict tool matchers via hooks.
❌ Over-Engineering the Agent Stack
Building a 5-agent orchestration pipeline for tasks that a simple one-shot prompt would solve.
Fix: Start with the simplest approach. Add agents and hooks only when you've proven they're needed. Simple control loops outperform complex multi-agent systems in most cases.
20. Cheatsheet — Commands, Keys & Config Paths
Essential Slash Commands
Command
Effect
/init
Generate starter CLAUDE.md from project structure
/usage
Context window usage, cost, token count
/compact
Compress context (lossy, momentum-friendly)
/clear
Wipe context entirely
/rewind
Roll back file changes to a previous state
/permissions
Manage allowed/denied tool operations
/branch
Fork conversation thread
/resume [ID]
Jump to specific session in history
/config
Edit session-level settings
/doctor
Diagnose Claude Code configuration issues
/model <name>
Switch model mid-session
/plugin
Manage plugins (install, update, discover)
/theme
Switch terminal theme
/help
List all available commands
Keyboard Shortcuts
Key
Action
Shift+Tab
Toggle Plan Mode
Esc + Esc
Open rewind menu
!<command>
Run shell command inline
@<path>
Reference file or directory
Tab
Autocomplete file paths
Config File Locations
File
Scope
Purpose
./CLAUDE.md
Project
Project memory, conventions
./.claude/settings.json
Project
Hooks, permissions, env vars
./.claude/settings.local.json
Local (gitignored)
Personal overrides
./.claude/commands/
Project
Slash commands
./.claude/rules/
Project
Scoped per-filetype rules
./.claude/agents/
Project
Sub-agent definitions
./.mcp.json
Project
MCP server config (commit to git)
~/.claude/settings.json
User global
Personal defaults
~/.claude/agents/
User global
Personal agents (available in all projects)
~/.claude/themes/
User global
Custom terminal themes
Model Identifiers (2026)
claude-opus-4-5 # Best reasoning, most capable
claude-sonnet-4-5 # Best coding, preferred for daily use
claude-haiku-4-5-20251001 # Fastest, cheapest — batch tasks
Useful CLI Flags
claude --headless # Non-interactive / scripted use
claude --print # Output only, no UI
claude --no-auto-updates # Freeze version (CI-safe)
claude --debug # Show internal hook and tool execution
claude --continue # Resume most recent session
claude --resume # Interactive session picker
claude --resume <id># Jump to specific session
claude --agent <name># Start with a named agent
claude -w <name># Start in a named git worktree