A comprehensive reference guide for Anthropic Claude Code, compiled from official best practices, DeepLearning.AI workshops, and engineering team experiences.
Common Terminal Bash Commands
Invoke these commands directly in your local terminal environment to manage the Claude Code CLI tool.
$ claude # Open Claude (use npx or global npm on first install)
$ claude . # Open in current directory
$ claude mcp add <servername> <command> # Add an MCP server
$ claude --loops 10 # Continue without changing (also supports "continue")
$ claude --dangerously-skip-permissions # Danger mode: skip permission confirmations
$ claude --model claude-sonnet-4-20250514 # Specify a modelPro Tip: Outline your high-level architectural plan to the agent first, then execute and confirm implementation steps iteratively.
Claude Built-in Slash Commands
Use these commands within the interactive Claude Code shell to inspect systems, clear memory, or query resources.
| Command | Description |
|---|---|
/init | Initialize a new project folder; helps Claude map the repository and prevents accidental writes |
/ide | Integrate directly with your active IDE instance to coordinate edits |
/help | List all available command resources for the active terminal session |
@documentname | Reference a static markdown file or document from your doc library |
/clear | Reset the conversation history and start fresh; excellent when /init gets bloated |
/compact | Manually trigger context compression when the history reaches active tokens limit |
/exit | Terminate the session and exit back to your standard terminal shell |
/hooks | Configure post-write automation scripts (e.g. formatters, linters, pre-commit scripts) |
/mcp | Check connection status and inspect capabilities of active Model Context Protocol servers |
/(command) | Define or call custom, shareable project-level slash commands |
Claude Keyboard Shortcuts
| Shortcut | Function |
|---|---|
Esc | Halt/cancel the active task execution and open a prompt input |
Esc + Esc | Force-trigger a brand new response generation for the current turn |
Shift + Tab | Toggle between Auto-complete mode and step-by-step confirmation mode |
Cmd + Shift + Ctrl + 4 | Capture a visual screenshot to clipboard (macOS) / Win + Shift + S (Windows) |
Ctrl + V | Paste captured clipboard screenshots directly into the terminal prompt |
Tab | Toggle internal agent Thinking mode on or off |
Codebase Familiarization Tips
a. Get a Quick Codebase Overview
Use these structured prompt templates to analyze and understand unfamiliar repositories rapidly:
Give me an overview of this codebase
Explain how the documents are processed
What is the format of the document expected by the document_processor
Trace the process of handling user's query from frontend to backend
Draw a diagram that illustrate this flow
Describe the api endpoints
How can I run the application
explain the main architecture patterns used here
what are the key data models?
how is XXX handled?b. Find Relevant Code
Locate subsystems and track transactional sequences:
find the files that handle user authentication
how do these authentication files work together
trace the login process from front-end to databaseExtended Thinking, High-Fidelity UI Design and Refactoring Tips
a. Use Extended Thinking
Trigger deep conceptual logic prior to execution to prevent design mistakes:
I need to implement a new ... system using ... . Think deeply about the best approach for implementing this in our codebase.
think about potential security vulnerabilities in this approach
think hard about edge cases we should handleb. Classic Workflow: Exploration → Planning → Coding → Commit
Strictly understand codebase constraints and dependencies before editing.
Read @src/payment/processor.py and @src/payment/gateway.py
Understand how payment processing currently works.
DO NOT write any code yet.
Use subagents if you need to verify details or investigate questions.Establish a clear implementation plan, considering edge cases and regressions.
Think hard about how to add support for Stripe webhooks.
Create a detailed plan covering:
1. New files needed
2. Changes to existing files
3. Error handling strategy
4. Testing approach
Create a GitHub issue with your plan so we can reset to this point if needed.Code step by step, validating each component's design as you progress.
Implement your plan step by step.
After each major component, verify it makes sense before moving on.
Commit logical chunks as you go.Run all unit tests and write clear, complete documentation.
Run all tests and make sure they pass.
Update the README with the new webhook feature.
Create a pull request with a clear description.c. High-Fidelity UI Design using Figma and Playwright MCP Server
# Visual Regression & UI Development
Step 1: Iterative Implementation
Using the following figma mockup (paste the link) use the figma dev MCP server to analyze the mockup and build the underlying code in this next.js application. Use the recharts library for creating charts to make this a web application. Check how this application looks using the playwright MCP server and verify it looks as close to the mock as possible.
After each change:
1. Take a screenshot of your implementation
2. Compare it with the design mock
3. List what's different
4. Fix the differences
Iterate 3-5 times until it's pixel-perfect.Step 2: Responsive Design Testing
Test the design at mobile (375px), tablet (768px), and desktop (1440px).
Take screenshots at each breakpoint and verify layout.d. Refactor Code
Safe, reliable refactoring workflows:
find XXX in our codebase
suggest how to refactor XXX to use XXXXX
Apply the change safely: refactor XXX to use XXXXX while maintaining the same behavior
verify refactor: run tests for the refactored codeEfficient and Safe Development Tips
a. Leveraging Specialized Subagents
Run the /agents command to inspect available subagents or define your own tailored subagents for design, frontend, backend, code review, or data analysis. During execution, Claude Code automatically selects the appropriate subagents based on their prompt descriptions, or you can invoke them directly:
| Subagent Type | Storage Path | Description & Priority |
|---|---|---|
| Project Subagent Project subagents | .claude/agents/ | Available only in the current repository. Highest invocation priority. |
| User Subagent User subagents | ~/.claude/agents/ | Available globally across all projects. Lower priority than project subagents. |
Example Subagent Invocations:
use the code-reviewer subagent to check XXX
have the debugger subagent investigate why users can't log in
First use the A subagent to find performance issues, then use the optimiser subagent to fix themb. Use Plan Mode for Safe Code Analysis
Toggle Plan Mode (using Shift + Tab). In this mode, Claude is strictly prohibited from modifying files or executing active command tasks immediately. Instead, it generates a comprehensive plan first, enabling you to align on design decisions and prevent accidental edits or logical drift.
c. Multi-Feature Isolation Using Git Worktrees
Run multiple isolated development and testing branches concurrently without cloning the repository multiple times. You can open sub-terminals on each worktree, start separate Claude Code instances, and build features independently.
$ git worktree add <directory>/<worktree-name>
# For example, establish three parallel worktrees under .trees:
$ git worktree add .trees/ui_feature
$ git worktree add .trees/testing_feature
$ git worktree add .trees/quality_feature
# List all active worktrees
$ git branch -a
# Dev cycle: open a terminal in each worktree directory, launch claude, commit changes:
$ git add .
$ git commit -m "feat: complete specific subsystem task"
# Merge isolated branches back into the main codebase from root:
$ git merge .trees/ui_feature
$ git merge .trees/testing_feature
$ git merge .trees/quality_feature
# Use the standard merge command to consolidate active worktrees:
# "use the git merge command to merge in all the worktrees in the .trees folder and fix conflicts"
# Clean up and remove completed worktrees:
$ git worktree remove <directory>/<worktree-name>d. Data Transfer and Context Feeding Techniques
Optimize how you present errors, performance metrics, pages, and screenshots to Claude Code for rapid resolution:
# Pattern 1: Piping Logs or Commands Directly
$ cat logs/error.log | claude -p "analyze these errors and suggest fixes"
# Pattern 2: Context reference using file symbols
Read @logs/performance.csv and create visualizations
# Pattern 3: Dynamic documentation scraping
Fetch https://api.example.com/docs and summarize the authentication flow
# Pattern 4: Direct inline log paste
Here's the error message: [paste large stacktrace logs]
Debug this issue.
# Pattern 5: Screenshot uploads for layout fixing
[Cmd + Ctrl + Shift + 4 Screenshot] → [Ctrl + V Paste]
"The UI looks broken in this screenshot. Fix the CSS."Testing and Debugging Tips
a. Test Driven Development (TDD)
Phase 1: Write Test Specifications (Zero Implementation)
Write comprehensive tests for the XXXX.
Requirements:
- Test successful XXX
- Test XXX scenario
- Test network timeout handling
- Test invalid XX data
- Test duplicate transaction prevention
Use pytest and create fixtures for common test data.
DO NOT write any implementation code yet.Phase 2: Verify Failing States
Run pytest and show me all the failing tests.
Confirm that each test fails for the RIGHT reason.Phase 3: Implement & Iterate
Now implement PaymentProcessor to make tests pass.
Run tests after each major change.
Keep iterating until all tests are green.
After passing, use a subagent to verify:
- Are we handling edge cases correctly?
- Is the code overfitting to the tests?
- Are there scenarios we haven't considered?b. Debug Workflows
Pattern 1: Supply Complete Context
I'm getting this error: [paste stacktrace / logs]
Context:
- It happens when: [describe trigger conditions]
- Expected behavior: [describe expectations]
- Relevant files: @src/api/handler.py @src/database/connection.py
- Recent changes: [describe recent commits or edits]
Please:
1. Analyze the error and identify root cause
2. Explain why it's happening
3. Provide a fix with explanation
4. Add a test to prevent regressionPattern 2: Automated Log Analysis Pipelines
cat logs/error.log | claude -p "Analyze these error logs
1. Identify patterns and common errors
2. Group related errors together
3. Suggest root cause for each group
4. Prioritize fixes by impact"Pattern 3: Performance Profiling and Bottlenecks
Profile the performance of @src/data/processor.py
Identify bottlenecks and suggest optimizations.
Run benchmarks before and after changes.c. Test Coverage and Edge Condition Testing
Pattern 1: Auto-generate Missing Tests
find functions in XXX that are not covered by tests
Run pytest --cov to check test coverage.
Identify functions with < 80% coverage.
Generate tests for those functions.
Prioritize: critical business logic > utility functions > simple getters/settersPattern 2: Boundary/Edge Conditions Tests
Review @document_name and generate tests for edge cases:
- Empty inputs
- Null/undefined values
- Maximum/minimum values
- Invalid types
- Concurrent access scenariosd. Integration and E2E Testing
Pattern 1: End-to-End Visual Flow via Puppeteer MCP
Set up end-to-end tests using Puppeteer MCP server:
Test scenario: User checkout flow
1. Navigate to homepage
2. Add product to cart
3. Proceed to checkout
4. Fill in payment details
5. Submit order
6. Verify success page
Take screenshots at each step.
Assert expected elements are present.
Verify no console errors.Pattern 2: API Integration Coverage
Create integration tests for the REST API:
- Test authentication flow
- Test CRUD operations for each resource
- Test error responses (400, 401, 403, 404, 500)
- Test rate limiting
- Test pagination
Use real database (test environment) not mocks.e. Regression Test Automation
Execute this standard pipeline after fixing a bug to block regression recurrences:
I just fixed a bug where user logout didn't clear session properly.
Please:
1. Write a regression test for this specific bug
2. Verify the test fails on the old code (checkout previous commit)
3. Verify the test passes on the fixed code
4. Add test to the CI pipeline
5. Document the bug in tests/REGRESSION_TESTS.mdAdditional Engineering Best Practices
a. Automated Documentation and Code Comment Audits
Pattern 1: OpenAPI Schema Generation
Generate OpenAPI documentation for @src/api/
Include:
- All endpoints with descriptions
- Request/response schemas
- Authentication requirements
- Example requests and responses
- Error codes and meanings
Output to docs/api_spec.yamlPattern 2: Code Comment and Docstring Compliance
Review all Python files in @src/
Check if:
- All public functions have docstrings
- Complex logic has inline comments
- Type hints are present
- Docstring format follows Google style
Generate a report of missing documentation.b. Security Reviews and Auditing
Run regular automated reviews of features and configuration modules:
Perform a security audit of @src/
Check for:
1. SQL injection vulnerabilities
2. XSS vulnerabilities
3. Hard-coded secrets/credentials
4. Insecure dependencies (check package.json)
5. Missing input validation
6. Insecure authentication/authorization
Create a report with severity levels and fixes.c. Performance Optimization and Profiling
Evaluate operational latency and resources using standard benchmarks:
Profile the application and identify performance bottlenecks:
1. Run load tests using locust
2. Analyze database query performance
3. Check for N+1 queries
4. Review API response times
5. Identify memory leaks
Generate optimization recommendations with expected impact.d. CI/CD Integration and GitHub Actions
Configure robust automation to protect branch health and coordinate releases:
Create GitHub Actions workflows:
1. .github/workflows/test.yml
- Run on every PR
- Execute all tests
- Check code coverage (>80%)
- Block merge if failing
2. .github/workflows/deploy.yml
- Run on main branch merge
- Build Docker image
- Push to registry
- Deploy to staging
3. .github/workflows/claude-triage.yml
- Trigger on new issue
- Analyze issue content
- Add appropriate labels
- Assign to relevant teamCompiled from Anthropic Claude Code official best practices and community experience.