Add ai-code-project-template repo files.

This commit is contained in:
2025-08-23 06:09:26 -07:00
parent 9321e54bce
commit e725ecf942
76 changed files with 17830 additions and 8 deletions

3
ai_context/.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"cSpell.enabled": false
}

View File

@@ -0,0 +1,258 @@
# Implementation Philosophy
This document outlines the core implementation philosophy and guidelines for software development projects. It serves as a central reference for decision-making and development approach throughout the project.
## Core Philosophy
Embodies a Zen-like minimalism that values simplicity and clarity above all. This approach reflects:
- **Wabi-sabi philosophy**: Embracing simplicity and the essential. Each line serves a clear purpose without unnecessary embellishment.
- **Occam's Razor thinking**: The solution should be as simple as possible, but no simpler.
- **Trust in emergence**: Complex systems work best when built from simple, well-defined components that do one thing well.
- **Present-moment focus**: The code handles what's needed now rather than anticipating every possible future scenario.
- **Pragmatic trust**: The developer trusts external systems enough to interact with them directly, handling failures as they occur rather than assuming they'll happen.
This development philosophy values clear documentation, readable code, and belief that good architecture emerges from simplicity rather than being imposed through complexity.
## Core Design Principles
### 1. Ruthless Simplicity
- **KISS principle taken to heart**: Keep everything as simple as possible, but no simpler
- **Minimize abstractions**: Every layer of abstraction must justify its existence
- **Start minimal, grow as needed**: Begin with the simplest implementation that meets current needs
- **Avoid future-proofing**: Don't build for hypothetical future requirements
- **Question everything**: Regularly challenge complexity in the codebase
### 2. Architectural Integrity with Minimal Implementation
- **Preserve key architectural patterns**: MCP for service communication, SSE for events, separate I/O channels, etc.
- **Simplify implementations**: Maintain pattern benefits with dramatically simpler code
- **Scrappy but structured**: Lightweight implementations of solid architectural foundations
- **End-to-end thinking**: Focus on complete flows rather than perfect components
### 3. Library Usage Philosophy
- **Use libraries as intended**: Minimal wrappers around external libraries
- **Direct integration**: Avoid unnecessary adapter layers
- **Selective dependency**: Add dependencies only when they provide substantial value
- **Understand what you import**: No black-box dependencies
## Technical Implementation Guidelines
### API Layer
- Implement only essential endpoints
- Minimal middleware with focused validation
- Clear error responses with useful messages
- Consistent patterns across endpoints
### Database & Storage
- Simple schema focused on current needs
- Use TEXT/JSON fields to avoid excessive normalization early
- Add indexes only when needed for performance
- Delay complex database features until required
### MCP Implementation
- Streamlined MCP client with minimal error handling
- Utilize FastMCP when possible, falling back to lower-level only when necessary
- Focus on core functionality without elaborate state management
- Simplified connection lifecycle with basic error recovery
- Implement only essential health checks
### SSE & Real-time Updates
- Basic SSE connection management
- Simple resource-based subscriptions
- Direct event delivery without complex routing
- Minimal state tracking for connections
### Event System
- Simple topic-based publisher/subscriber
- Direct event delivery without complex pattern matching
- Clear, minimal event payloads
- Basic error handling for subscribers
### LLM Integration
- Direct integration with PydanticAI
- Minimal transformation of responses
- Handle common error cases only
- Skip elaborate caching initially
### Message Routing
- Simplified queue-based processing
- Direct, focused routing logic
- Basic routing decisions without excessive action types
- Simple integration with other components
## Development Approach
### Vertical Slices
- Implement complete end-to-end functionality slices
- Start with core user journeys
- Get data flowing through all layers early
- Add features horizontally only after core flows work
### Iterative Implementation
- 80/20 principle: Focus on high-value, low-effort features first
- One working feature > multiple partial features
- Validate with real usage before enhancing
- Be willing to refactor early work as patterns emerge
### Testing Strategy
- Emphasis on integration and end-to-end tests
- Manual testability as a design goal
- Focus on critical path testing initially
- Add unit tests for complex logic and edge cases
- Testing pyramid: 60% unit, 30% integration, 10% end-to-end
### Error Handling
- Handle common errors robustly
- Log detailed information for debugging
- Provide clear error messages to users
- Fail fast and visibly during development
## Decision-Making Framework
When faced with implementation decisions, ask these questions:
1. **Necessity**: "Do we actually need this right now?"
2. **Simplicity**: "What's the simplest way to solve this problem?"
3. **Directness**: "Can we solve this more directly?"
4. **Value**: "Does the complexity add proportional value?"
5. **Maintenance**: "How easy will this be to understand and change later?"
## Areas to Embrace Complexity
Some areas justify additional complexity:
1. **Security**: Never compromise on security fundamentals
2. **Data integrity**: Ensure data consistency and reliability
3. **Core user experience**: Make the primary user flows smooth and reliable
4. **Error visibility**: Make problems obvious and diagnosable
## Areas to Aggressively Simplify
Push for extreme simplicity in these areas:
1. **Internal abstractions**: Minimize layers between components
2. **Generic "future-proof" code**: Resist solving non-existent problems
3. **Edge case handling**: Handle the common cases well first
4. **Framework usage**: Use only what you need from frameworks
5. **State management**: Keep state simple and explicit
## Practical Examples
### Good Example: Direct SSE Implementation
```python
# Simple, focused SSE manager that does exactly what's needed
class SseManager:
def __init__(self):
self.connections = {} # Simple dictionary tracking
async def add_connection(self, resource_id, user_id):
"""Add a new SSE connection"""
connection_id = str(uuid.uuid4())
queue = asyncio.Queue()
self.connections[connection_id] = {
"resource_id": resource_id,
"user_id": user_id,
"queue": queue
}
return queue, connection_id
async def send_event(self, resource_id, event_type, data):
"""Send an event to all connections for a resource"""
# Direct delivery to relevant connections only
for conn_id, conn in self.connections.items():
if conn["resource_id"] == resource_id:
await conn["queue"].put({
"event": event_type,
"data": data
})
```
### Bad Example: Over-engineered SSE Implementation
```python
# Overly complex with unnecessary abstractions and state tracking
class ConnectionRegistry:
def __init__(self, metrics_collector, cleanup_interval=60):
self.connections_by_id = {}
self.connections_by_resource = defaultdict(list)
self.connections_by_user = defaultdict(list)
self.metrics_collector = metrics_collector
self.cleanup_task = asyncio.create_task(self._cleanup_loop(cleanup_interval))
# [50+ more lines of complex indexing and state management]
```
### Good Example: Simple MCP Client
```python
# Focused MCP client with clean error handling
class McpClient:
def __init__(self, endpoint: str, service_name: str):
self.endpoint = endpoint
self.service_name = service_name
self.client = None
async def connect(self):
"""Connect to MCP server"""
if self.client is not None:
return # Already connected
try:
# Create SSE client context
async with sse_client(self.endpoint) as (read_stream, write_stream):
# Create client session
self.client = ClientSession(read_stream, write_stream)
# Initialize the client
await self.client.initialize()
except Exception as e:
self.client = None
raise RuntimeError(f"Failed to connect to {self.service_name}: {str(e)}")
async def call_tool(self, name: str, arguments: dict):
"""Call a tool on the MCP server"""
if not self.client:
await self.connect()
return await self.client.call_tool(name=name, arguments=arguments)
```
### Bad Example: Over-engineered MCP Client
```python
# Complex MCP client with excessive state management and error handling
class EnhancedMcpClient:
def __init__(self, endpoint, service_name, retry_strategy, health_check_interval):
self.endpoint = endpoint
self.service_name = service_name
self.state = ConnectionState.DISCONNECTED
self.retry_strategy = retry_strategy
self.connection_attempts = 0
self.last_error = None
self.health_check_interval = health_check_interval
self.health_check_task = None
# [50+ more lines of complex state tracking and retry logic]
```
## Remember
- It's easier to add complexity later than to remove it
- Code you don't write has no bugs
- Favor clarity over cleverness
- The best code is often the simplest
This philosophy document serves as the foundational guide for all implementation decisions in the project.

View File

@@ -0,0 +1,20 @@
# Building Software with AI: A Modular Block Approach
_By Brian Krabach_\
_3/28/2025_
Imagine you're about to build a complex construction brick spaceship. You dump out thousands of tiny bricks and open the blueprint. Step by step, the blueprint tells you which pieces to use and how to connect them. You don't need to worry about the details of each brick or whether it will fit --- the instructions guarantee that every piece snaps together correctly. **Now imagine those interlocking bricks could assemble themselves** whenever you gave them the right instructions. This is the essence of our new AI-driven software development approach: **we provide the blueprint, and AI builds the product, one modular piece at a time.**
Like a brick model, our software is built from small, clear modules. Each module is a self-contained "brick" of functionality with defined connectors (interfaces) to the rest of the system. Because these connection points are standard and stable, we can generate or regenerate any single module independently without breaking the whole. Need to improve the user login component? We can have the AI rebuild just that piece according to its spec, then snap it back into place --- all while the rest of the system continues to work seamlessly. And if we ever need to make a broad, cross-cutting change that touches many pieces, we simply hand the AI a bigger blueprint (for a larger assembly or even the entire codebase) and let it rebuild that chunk in one go. **Crucially, the external system contracts --- the equivalent of brick studs and sockets where pieces connect --- remain unchanged.** This means even a regenerated system still fits perfectly into its environment, although inside it might be built differently, with fresh optimizations and improvements.
When using LLM-powered tools today, even what looks like a tiny edit is actually the LLM generating new code based on the specifications we provide. We embrace this reality and don't treat code as something to tweak line-by-line; **we treat it as something to describe and then let the AI generate to create or assemble.** By keeping each task *small and self-contained* --- akin to one page of a blueprint --- we ensure the AI has all the context it needs to generate that piece correctly from start to finish. This makes the code generation more predictable and reliable. The system essentially always prefers regeneration of a module (or a set of modules) within a bounded context, rather than more challenging edits at the code level. The result is code that's consistently in sync with its specification, built in a clean sweep every time.
# The Human Role: From Code Mechanics to Architects
In this approach, humans step back from being code mechanics and instead take on the role of architects and quality inspectors. Much like a master builder, a human defines the vision and specifications up front --- the blueprint for what needs to be built. But once the spec (the blueprint) is handed off, the human doesn't hover over every brick placement. In fact, they don't need to read the code (just as you don't examine each brick's material for flaws). Instead, they focus on whether the assembled product meets the vision. They work at the specification level or higher: designing requirements, clarifying the intended behavior, and then evaluating the finished module or system by testing its behavior in action. If the login module is rebuilt, for example, the human reviews it by seeing if users can log in smoothly and securely --- not by poring over the source code. This elevates human involvement to where it's most valuable, letting AI handle the heavy lifting of code construction and assembly.
# Building in Parallel
The biggest leap is that we don't have to build just one solution at a time. Because our AI "builders" work so quickly and handle modular instructions so well, we can spawn multiple versions of the software in parallel --- like having several brick sets assembled simultaneously. Imagine generating and testing multiple variants of a feature at once --- the AI could try several different recommendation algorithms for a product in parallel to see which performs best. It could even build the same application for multiple platforms simultaneously (web, mobile, etc.) by following platform-specific instructions. We could have all these versions built and tested side by side in a fraction of the time it would take a traditional team to do one. Each variant teaches us something: we learn what works best, which design is most efficient, which user experience is superior. Armed with those insights, we can refine our high-level specifications and then regenerate the entire system or any module again for another iteration. This cycle of parallel experimentation and rapid regeneration means we can innovate faster and more fearlessly. It's a development playground on a scale previously unimaginable --- all enabled by trusting our AI co-builders to handle the intricate assembly while we guide the vision.
In short, this brick-inspired, AI-driven approach flips the script of software development. We break the work into well-defined pieces, let AI assemble and reassemble those pieces as needed, and keep humans focused on guiding the vision and validating results. The outcome is a process that's more flexible, faster, and surprisingly liberating: we can reshape our software as easily as snapping together (or rebuilding) a model, and even build multiple versions of it in parallel. For our stakeholders, this means delivering the right solution faster, adapting to change without fear, and continually exploring new ideas --- brick by brick, at a pace and scale that set a new standard for innovation.

6
ai_context/README.md Normal file
View File

@@ -0,0 +1,6 @@
# 🤖 AI Context
Context files for AI tools and development assistance.
- **generated/** - Project file roll-ups for LLM consumption (auto-generated)
- **git_collector/** - External library documentation for reference

View File

@@ -0,0 +1,902 @@
# Common workflows
> Learn about common workflows with Claude Code.
Each task in this document includes clear instructions, example commands, and best practices to help you get the most from Claude Code.
## Understand new codebases
### Get a quick codebase overview
Suppose you've just joined a new project and need to understand its structure quickly.
<Steps>
<Step title="Navigate to the project root directory">
```bash
cd /path/to/project
```
</Step>
<Step title="Start Claude Code">
```bash
claude
```
</Step>
<Step title="Ask for a high-level overview">
```
> give me an overview of this codebase
```
</Step>
<Step title="Dive deeper into specific components">
```
> explain the main architecture patterns used here
```
```
> what are the key data models?
```
```
> how is authentication handled?
```
</Step>
</Steps>
<Tip>
Tips:
- Start with broad questions, then narrow down to specific areas
- Ask about coding conventions and patterns used in the project
- Request a glossary of project-specific terms
</Tip>
### Find relevant code
Suppose you need to locate code related to a specific feature or functionality.
<Steps>
<Step title="Ask Claude to find relevant files">
```
> find the files that handle user authentication
```
</Step>
<Step title="Get context on how components interact">
```
> how do these authentication files work together?
```
</Step>
<Step title="Understand the execution flow">
```
> trace the login process from front-end to database
```
</Step>
</Steps>
<Tip>
Tips:
- Be specific about what you're looking for
- Use domain language from the project
</Tip>
---
## Fix bugs efficiently
Suppose you've encountered an error message and need to find and fix its source.
<Steps>
<Step title="Share the error with Claude">
```
> I'm seeing an error when I run npm test
```
</Step>
<Step title="Ask for fix recommendations">
```
> suggest a few ways to fix the @ts-ignore in user.ts
```
</Step>
<Step title="Apply the fix">
```
> update user.ts to add the null check you suggested
```
</Step>
</Steps>
<Tip>
Tips:
- Tell Claude the command to reproduce the issue and get a stack trace
- Mention any steps to reproduce the error
- Let Claude know if the error is intermittent or consistent
</Tip>
---
## Refactor code
Suppose you need to update old code to use modern patterns and practices.
<Steps>
<Step title="Identify legacy code for refactoring">
```
> find deprecated API usage in our codebase
```
</Step>
<Step title="Get refactoring recommendations">
```
> suggest how to refactor utils.js to use modern JavaScript features
```
</Step>
<Step title="Apply the changes safely">
```
> refactor utils.js to use ES2024 features while maintaining the same behavior
```
</Step>
<Step title="Verify the refactoring">
```
> run tests for the refactored code
```
</Step>
</Steps>
<Tip>
Tips:
- Ask Claude to explain the benefits of the modern approach
- Request that changes maintain backward compatibility when needed
- Do refactoring in small, testable increments
</Tip>
---
## Use specialized subagents
Suppose you want to use specialized AI subagents to handle specific tasks more effectively.
<Steps>
<Step title="View available subagents">
```
> /agents
```
This shows all available subagents and lets you create new ones.
</Step>
<Step title="Use subagents automatically">
Claude Code will automatically delegate appropriate tasks to specialized subagents:
```
> review my recent code changes for security issues
```
```
> run all tests and fix any failures
```
</Step>
<Step title="Explicitly request specific subagents">
```
> use the code-reviewer subagent to check the auth module
```
```
> have the debugger subagent investigate why users can't log in
```
</Step>
<Step title="Create custom subagents for your workflow">
```
> /agents
```
Then select "Create New subagent" and follow the prompts to define:
* Subagent type (e.g., `api-designer`, `performance-optimizer`)
* When to use it
* Which tools it can access
* Its specialized system prompt
</Step>
</Steps>
<Tip>
Tips:
- Create project-specific subagents in `.claude/agents/` for team sharing
- Use descriptive `description` fields to enable automatic delegation
- Limit tool access to what each subagent actually needs
- Check the [subagents documentation](/en/docs/claude-code/sub-agents) for detailed examples
</Tip>
---
## Work with tests
Suppose you need to add tests for uncovered code.
<Steps>
<Step title="Identify untested code">
```
> find functions in NotificationsService.swift that are not covered by tests
```
</Step>
<Step title="Generate test scaffolding">
```
> add tests for the notification service
```
</Step>
<Step title="Add meaningful test cases">
```
> add test cases for edge conditions in the notification service
```
</Step>
<Step title="Run and verify tests">
```
> run the new tests and fix any failures
```
</Step>
</Steps>
<Tip>
Tips:
- Ask for tests that cover edge cases and error conditions
- Request both unit and integration tests when appropriate
- Have Claude explain the testing strategy
</Tip>
---
## Create pull requests
Suppose you need to create a well-documented pull request for your changes.
<Steps>
<Step title="Summarize your changes">
```
> summarize the changes I've made to the authentication module
```
</Step>
<Step title="Generate a PR with Claude">
```
> create a pr
```
</Step>
<Step title="Review and refine">
```
> enhance the PR description with more context about the security improvements
```
</Step>
<Step title="Add testing details">
```
> add information about how these changes were tested
```
</Step>
</Steps>
<Tip>
Tips:
- Ask Claude directly to make a PR for you
- Review Claude's generated PR before submitting
- Ask Claude to highlight potential risks or considerations
</Tip>
## Handle documentation
Suppose you need to add or update documentation for your code.
<Steps>
<Step title="Identify undocumented code">
```
> find functions without proper JSDoc comments in the auth module
```
</Step>
<Step title="Generate documentation">
```
> add JSDoc comments to the undocumented functions in auth.js
```
</Step>
<Step title="Review and enhance">
```
> improve the generated documentation with more context and examples
```
</Step>
<Step title="Verify documentation">
```
> check if the documentation follows our project standards
```
</Step>
</Steps>
<Tip>
Tips:
- Specify the documentation style you want (JSDoc, docstrings, etc.)
- Ask for examples in the documentation
- Request documentation for public APIs, interfaces, and complex logic
</Tip>
---
## Work with images
Suppose you need to work with images in your codebase, and you want Claude's help analyzing image content.
<Steps>
<Step title="Add an image to the conversation">
You can use any of these methods:
1. Drag and drop an image into the Claude Code window
2. Copy an image and paste it into the CLI with ctrl+v (Do not use cmd+v)
3. Provide an image path to Claude. E.g., "Analyze this image: /path/to/your/image.png"
</Step>
<Step title="Ask Claude to analyze the image">
```
> What does this image show?
```
```
> Describe the UI elements in this screenshot
```
```
> Are there any problematic elements in this diagram?
```
</Step>
<Step title="Use images for context">
```
> Here's a screenshot of the error. What's causing it?
```
```
> This is our current database schema. How should we modify it for the new feature?
```
</Step>
<Step title="Get code suggestions from visual content">
```
> Generate CSS to match this design mockup
```
```
> What HTML structure would recreate this component?
```
</Step>
</Steps>
<Tip>
Tips:
- Use images when text descriptions would be unclear or cumbersome
- Include screenshots of errors, UI designs, or diagrams for better context
- You can work with multiple images in a conversation
- Image analysis works with diagrams, screenshots, mockups, and more
</Tip>
---
## Reference files and directories
Use @ to quickly include files or directories without waiting for Claude to read them.
<Steps>
<Step title="Reference a single file">
```
> Explain the logic in @src/utils/auth.js
```
This includes the full content of the file in the conversation.
</Step>
<Step title="Reference a directory">
```
> What's the structure of @src/components?
```
This provides a directory listing with file information.
</Step>
<Step title="Reference MCP resources">
```
> Show me the data from @github:repos/owner/repo/issues
```
This fetches data from connected MCP servers using the format @server:resource. See [MCP resources](/en/docs/claude-code/mcp#use-mcp-resources) for details.
</Step>
</Steps>
<Tip>
Tips:
- File paths can be relative or absolute
- @ file references add CLAUDE.md in the file's directory and parent directories to context
- Directory references show file listings, not contents
- You can reference multiple files in a single message (e.g., "@file1.js and @file2.js")
</Tip>
---
## Use extended thinking
Suppose you're working on complex architectural decisions, challenging bugs, or planning multi-step implementations that require deep reasoning.
<Steps>
<Step title="Provide context and ask Claude to think">
```
> I need to implement a new authentication system using OAuth2 for our API. Think deeply about the best approach for implementing this in our codebase.
```
Claude will gather relevant information from your codebase and
use extended thinking, which will be visible in the interface.
</Step>
<Step title="Refine the thinking with follow-up prompts">
```
> think about potential security vulnerabilities in this approach
```
```
> think harder about edge cases we should handle
```
</Step>
</Steps>
<Tip>
Tips to get the most value out of extended thinking:
Extended thinking is most valuable for complex tasks such as:
- Planning complex architectural changes
- Debugging intricate issues
- Creating implementation plans for new features
- Understanding complex codebases
- Evaluating tradeoffs between different approaches
The way you prompt for thinking results in varying levels of thinking depth:
- "think" triggers basic extended thinking
- intensifying phrases such as "think more", "think a lot", "think harder", or "think longer" triggers deeper thinking
For more extended thinking prompting tips, see [Extended thinking tips](/en/docs/build-with-claude/prompt-engineering/extended-thinking-tips).
</Tip>
<Note>
Claude will display its thinking process as italic gray text above the
response.
</Note>
---
## Resume previous conversations
Suppose you've been working on a task with Claude Code and need to continue where you left off in a later session.
Claude Code provides two options for resuming previous conversations:
- `--continue` to automatically continue the most recent conversation
- `--resume` to display a conversation picker
<Steps>
<Step title="Continue the most recent conversation">
```bash
claude --continue
```
This immediately resumes your most recent conversation without any prompts.
</Step>
<Step title="Continue in non-interactive mode">
```bash
claude --continue --print "Continue with my task"
```
Use `--print` with `--continue` to resume the most recent conversation in non-interactive mode, perfect for scripts or automation.
</Step>
<Step title="Show conversation picker">
```bash
claude --resume
```
This displays an interactive conversation selector showing:
* Conversation start time
* Initial prompt or conversation summary
* Message count
Use arrow keys to navigate and press Enter to select a conversation.
</Step>
</Steps>
<Tip>
Tips:
- Conversation history is stored locally on your machine
- Use `--continue` for quick access to your most recent conversation
- Use `--resume` when you need to select a specific past conversation
- When resuming, you'll see the entire conversation history before continuing
- The resumed conversation starts with the same model and configuration as the original
How it works:
1. **Conversation Storage**: All conversations are automatically saved locally with their full message history
2. **Message Deserialization**: When resuming, the entire message history is restored to maintain context
3. **Tool State**: Tool usage and results from the previous conversation are preserved
4. **Context Restoration**: The conversation resumes with all previous context intact
Examples:
```bash
# Continue most recent conversation
claude --continue
# Continue most recent conversation with a specific prompt
claude --continue --print "Show me our progress"
# Show conversation picker
claude --resume
# Continue most recent conversation in non-interactive mode
claude --continue --print "Run the tests again"
```
</Tip>
---
## Run parallel Claude Code sessions with Git worktrees
Suppose you need to work on multiple tasks simultaneously with complete code isolation between Claude Code instances.
<Steps>
<Step title="Understand Git worktrees">
Git worktrees allow you to check out multiple branches from the same
repository into separate directories. Each worktree has its own working
directory with isolated files, while sharing the same Git history. Learn
more in the [official Git worktree
documentation](https://git-scm.com/docs/git-worktree).
</Step>
<Step title="Create a new worktree">
```bash
# Create a new worktree with a new branch
git worktree add ../project-feature-a -b feature-a
# Or create a worktree with an existing branch
git worktree add ../project-bugfix bugfix-123
```
This creates a new directory with a separate working copy of your repository.
</Step>
<Step title="Run Claude Code in each worktree">
```bash
# Navigate to your worktree
cd ../project-feature-a
# Run Claude Code in this isolated environment
claude
```
</Step>
<Step title="Run Claude in another worktree">
```bash
cd ../project-bugfix
claude
```
</Step>
<Step title="Manage your worktrees">
```bash
# List all worktrees
git worktree list
# Remove a worktree when done
git worktree remove ../project-feature-a
```
</Step>
</Steps>
<Tip>
Tips:
- Each worktree has its own independent file state, making it perfect for parallel Claude Code sessions
- Changes made in one worktree won't affect others, preventing Claude instances from interfering with each other
- All worktrees share the same Git history and remote connections
- For long-running tasks, you can have Claude working in one worktree while you continue development in another
- Use descriptive directory names to easily identify which task each worktree is for
- Remember to initialize your development environment in each new worktree according to your project's setup. Depending on your stack, this might include:
_ JavaScript projects: Running dependency installation (`npm install`, `yarn`)
_ Python projects: Setting up virtual environments or installing with package managers \* Other languages: Following your project's standard setup process
</Tip>
---
## Use Claude as a unix-style utility
### Add Claude to your verification process
Suppose you want to use Claude Code as a linter or code reviewer.
**Add Claude to your build script:**
```json
// package.json
{
...
"scripts": {
...
"lint:claude": "claude -p 'you are a linter. please look at the changes vs. main and report any issues related to typos. report the filename and line number on one line, and a description of the issue on the second line. do not return any other text.'"
}
}
```
<Tip>
Tips:
- Use Claude for automated code review in your CI/CD pipeline
- Customize the prompt to check for specific issues relevant to your project
- Consider creating multiple scripts for different types of verification
</Tip>
### Pipe in, pipe out
Suppose you want to pipe data into Claude, and get back data in a structured format.
**Pipe data through Claude:**
```bash
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
```
<Tip>
Tips:
- Use pipes to integrate Claude into existing shell scripts
- Combine with other Unix tools for powerful workflows
- Consider using --output-format for structured output
</Tip>
### Control output format
Suppose you need Claude's output in a specific format, especially when integrating Claude Code into scripts or other tools.
<Steps>
<Step title="Use text format (default)">
```bash
cat data.txt | claude -p 'summarize this data' --output-format text > summary.txt
```
This outputs just Claude's plain text response (default behavior).
</Step>
<Step title="Use JSON format">
```bash
cat code.py | claude -p 'analyze this code for bugs' --output-format json > analysis.json
```
This outputs a JSON array of messages with metadata including cost and duration.
</Step>
<Step title="Use streaming JSON format">
```bash
cat log.txt | claude -p 'parse this log file for errors' --output-format stream-json
```
This outputs a series of JSON objects in real-time as Claude processes the request. Each message is a valid JSON object, but the entire output is not valid JSON if concatenated.
</Step>
</Steps>
<Tip>
Tips:
- Use `--output-format text` for simple integrations where you just need Claude's response
- Use `--output-format json` when you need the full conversation log
- Use `--output-format stream-json` for real-time output of each conversation turn
</Tip>
---
## Create custom slash commands
Claude Code supports custom slash commands that you can create to quickly execute specific prompts or tasks.
For more details, see the [Slash commands](/en/docs/claude-code/slash-commands) reference page.
### Create project-specific commands
Suppose you want to create reusable slash commands for your project that all team members can use.
<Steps>
<Step title="Create a commands directory in your project">
```bash
mkdir -p .claude/commands
```
</Step>
<Step title="Create a Markdown file for each command">
```bash
echo "Analyze the performance of this code and suggest three specific optimizations:" > .claude/commands/optimize.md
```
</Step>
<Step title="Use your custom command in Claude Code">
```
> /optimize
```
</Step>
</Steps>
<Tip>
Tips:
- Command names are derived from the filename (e.g., `optimize.md` becomes `/optimize`)
- You can organize commands in subdirectories (e.g., `.claude/commands/frontend/component.md` creates `/component` with "(project:frontend)" shown in the description)
- Project commands are available to everyone who clones the repository
- The Markdown file content becomes the prompt sent to Claude when the command is invoked
</Tip>
### Add command arguments with \$ARGUMENTS
Suppose you want to create flexible slash commands that can accept additional input from users.
<Steps>
<Step title="Create a command file with the $ARGUMENTS placeholder">
```bash
echo 'Find and fix issue #$ARGUMENTS. Follow these steps: 1.
Understand the issue described in the ticket 2. Locate the relevant code in
our codebase 3. Implement a solution that addresses the root cause 4. Add
appropriate tests 5. Prepare a concise PR description' >
.claude/commands/fix-issue.md
```
</Step>
<Step title="Use the command with an issue number">
In your Claude session, use the command with arguments.
```
> /fix-issue 123
```
This will replace \$ARGUMENTS with "123" in the prompt.
</Step>
</Steps>
<Tip>
Tips:
- The \$ARGUMENTS placeholder is replaced with any text that follows the command
- You can position \$ARGUMENTS anywhere in your command template
- Other useful applications: generating test cases for specific functions, creating documentation for components, reviewing code in particular files, or translating content to specified languages
</Tip>
### Create personal slash commands
Suppose you want to create personal slash commands that work across all your projects.
<Steps>
<Step title="Create a commands directory in your home folder">
```bash
mkdir -p ~/.claude/commands
```
</Step>
<Step title="Create a Markdown file for each command">
```bash
echo "Review this code for security vulnerabilities, focusing on:" >
~/.claude/commands/security-review.md
```
</Step>
<Step title="Use your personal custom command">
```
> /security-review
```
</Step>
</Steps>
<Tip>
Tips:
- Personal commands show "(user)" in their description when listed with `/help`
- Personal commands are only available to you and not shared with your team
- Personal commands work across all your projects
- You can use these for consistent workflows across different codebases
</Tip>
---
## Ask Claude about its capabilities
Claude has built-in access to its documentation and can answer questions about its own features and limitations.
### Example questions
```
> can Claude Code create pull requests?
```
```
> how does Claude Code handle permissions?
```
```
> what slash commands are available?
```
```
> how do I use MCP with Claude Code?
```
```
> how do I configure Claude Code for Amazon Bedrock?
```
```
> what are the limitations of Claude Code?
```
<Note>
Claude provides documentation-based answers to these questions. For executable examples and hands-on demonstrations, refer to the specific workflow sections above.
</Note>
<Tip>
Tips:
- Claude always has access to the latest Claude Code documentation, regardless of the version you're using
- Ask specific questions to get detailed answers
- Claude can explain complex features like MCP integration, enterprise configurations, and advanced workflows
</Tip>
---
## Next steps
<Card title="Claude Code reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">
Clone our development container reference implementation.
</Card>

View File

@@ -0,0 +1,743 @@
# Hooks reference
> This page provides reference documentation for implementing hooks in Claude Code.
<Tip>
For a quickstart guide with examples, see [Get started with Claude Code hooks](/en/docs/claude-code/hooks-guide).
</Tip>
## Configuration
Claude Code hooks are configured in your [settings files](/en/docs/claude-code/settings):
- `~/.claude/settings.json` - User settings
- `.claude/settings.json` - Project settings
- `.claude/settings.local.json` - Local project settings (not committed)
- Enterprise managed policy settings
### Structure
Hooks are organized by matchers, where each matcher can have multiple hooks:
```json
{
"hooks": {
"EventName": [
{
"matcher": "ToolPattern",
"hooks": [
{
"type": "command",
"command": "your-command-here"
}
]
}
]
}
}
```
- **matcher**: Pattern to match tool names, case-sensitive (only applicable for
`PreToolUse` and `PostToolUse`)
- Simple strings match exactly: `Write` matches only the Write tool
- Supports regex: `Edit|Write` or `Notebook.*`
- Use `*` to match all tools. You can also use empty string (`""`) or leave
`matcher` blank.
- **hooks**: Array of commands to execute when the pattern matches
- `type`: Currently only `"command"` is supported
- `command`: The bash command to execute (can use `$CLAUDE_PROJECT_DIR`
environment variable)
- `timeout`: (Optional) How long a command should run, in seconds, before
canceling that specific command.
For events like `UserPromptSubmit`, `Notification`, `Stop`, and `SubagentStop`
that don't use matchers, you can omit the matcher field:
```json
{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "/path/to/prompt-validator.py"
}
]
}
]
}
}
```
### Project-Specific Hook Scripts
You can use the environment variable `CLAUDE_PROJECT_DIR` (only available when
Claude Code spawns the hook command) to reference scripts stored in your project,
ensuring they work regardless of Claude's current directory:
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/check-style.sh"
}
]
}
]
}
}
```
## Hook Events
### PreToolUse
Runs after Claude creates tool parameters and before processing the tool call.
**Common matchers:**
- `Task` - Subagent tasks (see [subagents documentation](/en/docs/claude-code/sub-agents))
- `Bash` - Shell commands
- `Glob` - File pattern matching
- `Grep` - Content search
- `Read` - File reading
- `Edit`, `MultiEdit` - File editing
- `Write` - File writing
- `WebFetch`, `WebSearch` - Web operations
### PostToolUse
Runs immediately after a tool completes successfully.
Recognizes the same matcher values as PreToolUse.
### Notification
Runs when Claude Code sends notifications. Notifications are sent when:
1. Claude needs your permission to use a tool. Example: "Claude needs your
permission to use Bash"
2. The prompt input has been idle for at least 60 seconds. "Claude is waiting
for your input"
### UserPromptSubmit
Runs when the user submits a prompt, before Claude processes it. This allows you
to add additional context based on the prompt/conversation, validate prompts, or
block certain types of prompts.
### Stop
Runs when the main Claude Code agent has finished responding. Does not run if
the stoppage occurred due to a user interrupt.
### SubagentStop
Runs when a Claude Code subagent (Task tool call) has finished responding.
### PreCompact
Runs before Claude Code is about to run a compact operation.
**Matchers:**
- `manual` - Invoked from `/compact`
- `auto` - Invoked from auto-compact (due to full context window)
### SessionStart
Runs when Claude Code starts a new session or resumes an existing session (which
currently does start a new session under the hood). Useful for loading in
development context like existing issues or recent changes to your codebase.
**Matchers:**
- `startup` - Invoked from startup
- `resume` - Invoked from `--resume`, `--continue`, or `/resume`
- `clear` - Invoked from `/clear`
## Hook Input
Hooks receive JSON data via stdin containing session information and
event-specific data:
```typescript
{
// Common fields
session_id: string
transcript_path: string // Path to conversation JSON
cwd: string // The current working directory when the hook is invoked
// Event-specific fields
hook_event_name: string
...
}
```
### PreToolUse Input
The exact schema for `tool_input` depends on the tool.
```json
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"cwd": "/Users/...",
"hook_event_name": "PreToolUse",
"tool_name": "Write",
"tool_input": {
"file_path": "/path/to/file.txt",
"content": "file content"
}
}
```
### PostToolUse Input
The exact schema for `tool_input` and `tool_response` depends on the tool.
```json
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"cwd": "/Users/...",
"hook_event_name": "PostToolUse",
"tool_name": "Write",
"tool_input": {
"file_path": "/path/to/file.txt",
"content": "file content"
},
"tool_response": {
"filePath": "/path/to/file.txt",
"success": true
}
}
```
### Notification Input
```json
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"cwd": "/Users/...",
"hook_event_name": "Notification",
"message": "Task completed successfully"
}
```
### UserPromptSubmit Input
```json
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"cwd": "/Users/...",
"hook_event_name": "UserPromptSubmit",
"prompt": "Write a function to calculate the factorial of a number"
}
```
### Stop and SubagentStop Input
`stop_hook_active` is true when Claude Code is already continuing as a result of
a stop hook. Check this value or process the transcript to prevent Claude Code
from running indefinitely.
```json
{
"session_id": "abc123",
"transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"hook_event_name": "Stop",
"stop_hook_active": true
}
```
### PreCompact Input
For `manual`, `custom_instructions` comes from what the user passes into
`/compact`. For `auto`, `custom_instructions` is empty.
```json
{
"session_id": "abc123",
"transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"hook_event_name": "PreCompact",
"trigger": "manual",
"custom_instructions": ""
}
```
### SessionStart Input
```json
{
"session_id": "abc123",
"transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"hook_event_name": "SessionStart",
"source": "startup"
}
```
## Hook Output
There are two ways for hooks to return output back to Claude Code. The output
communicates whether to block and any feedback that should be shown to Claude
and the user.
### Simple: Exit Code
Hooks communicate status through exit codes, stdout, and stderr:
- **Exit code 0**: Success. `stdout` is shown to the user in transcript mode
(CTRL-R), except for `UserPromptSubmit` and `SessionStart`, where stdout is
added to the context.
- **Exit code 2**: Blocking error. `stderr` is fed back to Claude to process
automatically. See per-hook-event behavior below.
- **Other exit codes**: Non-blocking error. `stderr` is shown to the user and
execution continues.
<Warning>
Reminder: Claude Code does not see stdout if the exit code is 0, except for
the `UserPromptSubmit` hook where stdout is injected as context.
</Warning>
#### Exit Code 2 Behavior
| Hook Event | Behavior |
| ------------------ | ------------------------------------------------------------------ |
| `PreToolUse` | Blocks the tool call, shows stderr to Claude |
| `PostToolUse` | Shows stderr to Claude (tool already ran) |
| `Notification` | N/A, shows stderr to user only |
| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only |
| `Stop` | Blocks stoppage, shows stderr to Claude |
| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent |
| `PreCompact` | N/A, shows stderr to user only |
| `SessionStart` | N/A, shows stderr to user only |
### Advanced: JSON Output
Hooks can return structured JSON in `stdout` for more sophisticated control:
#### Common JSON Fields
All hook types can include these optional fields:
```json
{
"continue": true, // Whether Claude should continue after hook execution (default: true)
"stopReason": "string" // Message shown when continue is false
"suppressOutput": true, // Hide stdout from transcript mode (default: false)
}
```
If `continue` is false, Claude stops processing after the hooks run.
- For `PreToolUse`, this is different from `"permissionDecision": "deny"`, which
only blocks a specific tool call and provides automatic feedback to Claude.
- For `PostToolUse`, this is different from `"decision": "block"`, which
provides automated feedback to Claude.
- For `UserPromptSubmit`, this prevents the prompt from being processed.
- For `Stop` and `SubagentStop`, this takes precedence over any
`"decision": "block"` output.
- In all cases, `"continue" = false` takes precedence over any
`"decision": "block"` output.
`stopReason` accompanies `continue` with a reason shown to the user, not shown
to Claude.
#### `PreToolUse` Decision Control
`PreToolUse` hooks can control whether a tool call proceeds.
- `"allow"` bypasses the permission system. `permissionDecisionReason` is shown
to the user but not to Claude. (_Deprecated `"approve"` value + `reason` has
the same behavior._)
- `"deny"` prevents the tool call from executing. `permissionDecisionReason` is
shown to Claude. (_`"block"` value + `reason` has the same behavior._)
- `"ask"` asks the user to confirm the tool call in the UI.
`permissionDecisionReason` is shown to the user but not to Claude.
```json
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow" | "deny" | "ask",
"permissionDecisionReason": "My reason here (shown to user)"
},
"decision": "approve" | "block" | undefined, // Deprecated for PreToolUse but still supported
"reason": "Explanation for decision" // Deprecated for PreToolUse but still supported
}
```
#### `PostToolUse` Decision Control
`PostToolUse` hooks can control whether a tool call proceeds.
- `"block"` automatically prompts Claude with `reason`.
- `undefined` does nothing. `reason` is ignored.
```json
{
"decision": "block" | undefined,
"reason": "Explanation for decision"
}
```
#### `UserPromptSubmit` Decision Control
`UserPromptSubmit` hooks can control whether a user prompt is processed.
- `"block"` prevents the prompt from being processed. The submitted prompt is
erased from context. `"reason"` is shown to the user but not added to context.
- `undefined` allows the prompt to proceed normally. `"reason"` is ignored.
- `"hookSpecificOutput.additionalContext"` adds the string to the context if not
blocked.
```json
{
"decision": "block" | undefined,
"reason": "Explanation for decision",
"hookSpecificOutput": {
"hookEventName": "UserPromptSubmit",
"additionalContext": "My additional context here"
}
}
```
#### `Stop`/`SubagentStop` Decision Control
`Stop` and `SubagentStop` hooks can control whether Claude must continue.
- `"block"` prevents Claude from stopping. You must populate `reason` for Claude
to know how to proceed.
- `undefined` allows Claude to stop. `reason` is ignored.
```json
{
"decision": "block" | undefined,
"reason": "Must be provided when Claude is blocked from stopping"
}
```
#### `SessionStart` Decision Control
`SessionStart` hooks allow you to load in context at the start of a session.
- `"hookSpecificOutput.additionalContext"` adds the string to the context.
```json
{
"hookSpecificOutput": {
"hookEventName": "SessionStart",
"additionalContext": "My additional context here"
}
}
```
#### Exit Code Example: Bash Command Validation
```python
#!/usr/bin/env python3
import json
import re
import sys
# Define validation rules as a list of (regex pattern, message) tuples
VALIDATION_RULES = [
(
r"\bgrep\b(?!.*\|)",
"Use 'rg' (ripgrep) instead of 'grep' for better performance and features",
),
(
r"\bfind\s+\S+\s+-name\b",
"Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance",
),
]
def validate_command(command: str) -> list[str]:
issues = []
for pattern, message in VALIDATION_RULES:
if re.search(pattern, command):
issues.append(message)
return issues
try:
input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
sys.exit(1)
tool_name = input_data.get("tool_name", "")
tool_input = input_data.get("tool_input", {})
command = tool_input.get("command", "")
if tool_name != "Bash" or not command:
sys.exit(1)
# Validate the command
issues = validate_command(command)
if issues:
for message in issues:
print(f"• {message}", file=sys.stderr)
# Exit code 2 blocks tool call and shows stderr to Claude
sys.exit(2)
```
#### JSON Output Example: UserPromptSubmit to Add Context and Validation
<Note>
For `UserPromptSubmit` hooks, you can inject context using either method:
- Exit code 0 with stdout: Claude sees the context (special case for `UserPromptSubmit`)
- JSON output: Provides more control over the behavior
</Note>
```python
#!/usr/bin/env python3
import json
import sys
import re
import datetime
# Load input from stdin
try:
input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
sys.exit(1)
prompt = input_data.get("prompt", "")
# Check for sensitive patterns
sensitive_patterns = [
(r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"),
]
for pattern, message in sensitive_patterns:
if re.search(pattern, prompt):
# Use JSON output to block with a specific reason
output = {
"decision": "block",
"reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information."
}
print(json.dumps(output))
sys.exit(0)
# Add current time to context
context = f"Current time: {datetime.datetime.now()}"
print(context)
"""
The following is also equivalent:
print(json.dumps({
"hookSpecificOutput": {
"hookEventName": "UserPromptSubmit",
"additionalContext": context,
},
}))
"""
# Allow the prompt to proceed with the additional context
sys.exit(0)
```
#### JSON Output Example: PreToolUse with Approval
```python
#!/usr/bin/env python3
import json
import sys
# Load input from stdin
try:
input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
sys.exit(1)
tool_name = input_data.get("tool_name", "")
tool_input = input_data.get("tool_input", {})
# Example: Auto-approve file reads for documentation files
if tool_name == "Read":
file_path = tool_input.get("file_path", "")
if file_path.endswith((".md", ".mdx", ".txt", ".json")):
# Use JSON output to auto-approve the tool call
output = {
"decision": "approve",
"reason": "Documentation file auto-approved",
"suppressOutput": True # Don't show in transcript mode
}
print(json.dumps(output))
sys.exit(0)
# For other cases, let the normal permission flow proceed
sys.exit(0)
```
## Working with MCP Tools
Claude Code hooks work seamlessly with
[Model Context Protocol (MCP) tools](/en/docs/claude-code/mcp). When MCP servers
provide tools, they appear with a special naming pattern that you can match in
your hooks.
### MCP Tool Naming
MCP tools follow the pattern `mcp__<server>__<tool>`, for example:
- `mcp__memory__create_entities` - Memory server's create entities tool
- `mcp__filesystem__read_file` - Filesystem server's read file tool
- `mcp__github__search_repositories` - GitHub server's search tool
### Configuring Hooks for MCP Tools
You can target specific MCP tools or entire MCP servers:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__memory__.*",
"hooks": [
{
"type": "command",
"command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"
}
]
},
{
"matcher": "mcp__.*__write.*",
"hooks": [
{
"type": "command",
"command": "/home/user/scripts/validate-mcp-write.py"
}
]
}
]
}
}
```
## Examples
<Tip>
For practical examples including code formatting, notifications, and file protection, see [More Examples](/en/docs/claude-code/hooks-guide#more-examples) in the get started guide.
</Tip>
## Security Considerations
### Disclaimer
**USE AT YOUR OWN RISK**: Claude Code hooks execute arbitrary shell commands on
your system automatically. By using hooks, you acknowledge that:
- You are solely responsible for the commands you configure
- Hooks can modify, delete, or access any files your user account can access
- Malicious or poorly written hooks can cause data loss or system damage
- Anthropic provides no warranty and assumes no liability for any damages
resulting from hook usage
- You should thoroughly test hooks in a safe environment before production use
Always review and understand any hook commands before adding them to your
configuration.
### Security Best Practices
Here are some key practices for writing more secure hooks:
1. **Validate and sanitize inputs** - Never trust input data blindly
2. **Always quote shell variables** - Use `"$VAR"` not `$VAR`
3. **Block path traversal** - Check for `..` in file paths
4. **Use absolute paths** - Specify full paths for scripts (use
`$CLAUDE_PROJECT_DIR` for the project path)
5. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc.
### Configuration Safety
Direct edits to hooks in settings files don't take effect immediately. Claude
Code:
1. Captures a snapshot of hooks at startup
2. Uses this snapshot throughout the session
3. Warns if hooks are modified externally
4. Requires review in `/hooks` menu for changes to apply
This prevents malicious hook modifications from affecting your current session.
## Hook Execution Details
- **Timeout**: 60-second execution limit by default, configurable per command.
- A timeout for an individual command does not affect the other commands.
- **Parallelization**: All matching hooks run in parallel
- **Environment**: Runs in current directory with Claude Code's environment
- The `CLAUDE_PROJECT_DIR` environment variable is available and contains the
absolute path to the project root directory
- **Input**: JSON via stdin
- **Output**:
- PreToolUse/PostToolUse/Stop: Progress shown in transcript (Ctrl-R)
- Notification: Logged to debug only (`--debug`)
## Debugging
### Basic Troubleshooting
If your hooks aren't working:
1. **Check configuration** - Run `/hooks` to see if your hook is registered
2. **Verify syntax** - Ensure your JSON settings are valid
3. **Test commands** - Run hook commands manually first
4. **Check permissions** - Make sure scripts are executable
5. **Review logs** - Use `claude --debug` to see hook execution details
Common issues:
- **Quotes not escaped** - Use `\"` inside JSON strings
- **Wrong matcher** - Check tool names match exactly (case-sensitive)
- **Command not found** - Use full paths for scripts
### Advanced Debugging
For complex hook issues:
1. **Inspect hook execution** - Use `claude --debug` to see detailed hook
execution
2. **Validate JSON schemas** - Test hook input/output with external tools
3. **Check environment variables** - Verify Claude Code's environment is correct
4. **Test edge cases** - Try hooks with unusual file paths or inputs
5. **Monitor system resources** - Check for resource exhaustion during hook
execution
6. **Use structured logging** - Implement logging in your hook scripts
### Debug Output Example
Use `claude --debug` to see hook execution details:
```
[DEBUG] Executing hooks for PostToolUse:Write
[DEBUG] Getting matching hook commands for PostToolUse with query: Write
[DEBUG] Found 1 hook matchers in settings
[DEBUG] Matched 1 hooks for query "Write"
[DEBUG] Found 1 hook commands to execute
[DEBUG] Executing hook command: <Your command> with timeout 60000ms
[DEBUG] Hook command completed with status 0: <Your stdout>
```
Progress messages appear in transcript mode (Ctrl-R) showing:
- Which hook is running
- Command being executed
- Success/failure status
- Output or error messages

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,257 @@
# Claude Code settings
> Configure Claude Code with global and project-level settings, and environment variables.
Claude Code offers a variety of settings to configure its behavior to meet your needs. You can configure Claude Code by running the `/config` command when using the interactive REPL.
## Settings files
The `settings.json` file is our official mechanism for configuring Claude
Code through hierarchical settings:
- **User settings** are defined in `~/.claude/settings.json` and apply to all
projects.
- **Project settings** are saved in your project directory:
- `.claude/settings.json` for settings that are checked into source control and shared with your team
- `.claude/settings.local.json` for settings that are not checked in, useful for personal preferences and experimentation. Claude Code will configure git to ignore `.claude/settings.local.json` when it is created.
- For enterprise deployments of Claude Code, we also support **enterprise
managed policy settings**. These take precedence over user and project
settings. System administrators can deploy policies to:
- macOS: `/Library/Application Support/ClaudeCode/managed-settings.json`
- Linux and WSL: `/etc/claude-code/managed-settings.json`
- Windows: `C:\ProgramData\ClaudeCode\managed-settings.json`
```JSON Example settings.json
{
"permissions": {
"allow": [
"Bash(npm run lint)",
"Bash(npm run test:*)",
"Read(~/.zshrc)"
],
"deny": [
"Bash(curl:*)",
"Read(./.env)",
"Read(./.env.*)",
"Read(./secrets/**)"
]
},
"env": {
"CLAUDE_CODE_ENABLE_TELEMETRY": "1",
"OTEL_METRICS_EXPORTER": "otlp"
}
}
```
### Available settings
`settings.json` supports a number of options:
| Key | Description | Example |
| :--------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------- |
| `apiKeyHelper` | Custom script, to be executed in `/bin/sh`, to generate an auth value. This value will be sent as `X-Api-Key` and `Authorization: Bearer` headers for model requests | `/bin/generate_temp_api_key.sh` |
| `cleanupPeriodDays` | How long to locally retain chat transcripts based on last activity date (default: 30 days) | `20` |
| `env` | Environment variables that will be applied to every session | `{"FOO": "bar"}` |
| `includeCoAuthoredBy` | Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`) | `false` |
| `permissions` | See table below for structure of permissions. | |
| `hooks` | Configure custom commands to run before or after tool executions. See [hooks documentation](hooks) | `{"PreToolUse": {"Bash": "echo 'Running command...'"}}` |
| `model` | Override the default model to use for Claude Code | `"claude-3-5-sonnet-20241022"` |
| `statusLine` | Configure a custom status line to display context. See [statusLine documentation](statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` |
| `forceLoginMethod` | Use `claudeai` to restrict login to Claude.ai accounts, `console` to restrict login to Anthropic Console (API usage billing) accounts | `claudeai` |
| `enableAllProjectMcpServers` | Automatically approve all MCP servers defined in project `.mcp.json` files | `true` |
| `enabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to approve | `["memory", "github"]` |
| `disabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to reject | `["filesystem"]` |
| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/docs/claude-code/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |
| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/docs/claude-code/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |
### Permission settings
| Keys | Description | Example |
| :----------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------- |
| `allow` | Array of [permission rules](/en/docs/claude-code/iam#configuring-permissions) to allow tool use | `[ "Bash(git diff:*)" ]` |
| `ask` | Array of [permission rules](/en/docs/claude-code/iam#configuring-permissions) to ask for confirmation upon tool use. | `[ "Bash(git push:*)" ]` |
| `deny` | Array of [permission rules](/en/docs/claude-code/iam#configuring-permissions) to deny tool use. Use this to also exclude sensitive files from Claude Code access. | `[ "WebFetch", "Bash(curl:*)", "Read(./.env)", "Read(./secrets/**)" ]` |
| `additionalDirectories` | Additional [working directories](iam#working-directories) that Claude has access to | `[ "../docs/" ]` |
| `defaultMode` | Default [permission mode](iam#permission-modes) when opening Claude Code | `"acceptEdits"` |
| `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode from being activated. See [managed policy settings](iam#enterprise-managed-policy-settings) | `"disable"` |
### Settings precedence
Settings are applied in order of precedence (highest to lowest):
1. **Enterprise managed policies** (`managed-settings.json`)
- Deployed by IT/DevOps
- Cannot be overridden
2. **Command line arguments**
- Temporary overrides for a specific session
3. **Local project settings** (`.claude/settings.local.json`)
- Personal project-specific settings
4. **Shared project settings** (`.claude/settings.json`)
- Team-shared project settings in source control
5. **User settings** (`~/.claude/settings.json`)
- Personal global settings
This hierarchy ensures that enterprise security policies are always enforced while still allowing teams and individuals to customize their experience.
### Key points about the configuration system
- **Memory files (CLAUDE.md)**: Contain instructions and context that Claude loads at startup
- **Settings files (JSON)**: Configure permissions, environment variables, and tool behavior
- **Slash commands**: Custom commands that can be invoked during a session with `/command-name`
- **MCP servers**: Extend Claude Code with additional tools and integrations
- **Precedence**: Higher-level configurations (Enterprise) override lower-level ones (User/Project)
- **Inheritance**: Settings are merged, with more specific settings adding to or overriding broader ones
### System prompt availability
<Note>
Unlike for claude.ai, we do not publish Claude Code's internal system prompt on this website. Use CLAUDE.md files or `--append-system-prompt` to add custom instructions to Claude Code's behavior.
</Note>
### Excluding sensitive files
To prevent Claude Code from accessing files containing sensitive information (e.g., API keys, secrets, environment files), use the `permissions.deny` setting in your `.claude/settings.json` file:
```json
{
"permissions": {
"deny": [
"Read(./.env)",
"Read(./.env.*)",
"Read(./secrets/**)",
"Read(./config/credentials.json)",
"Read(./build)"
]
}
}
```
This replaces the deprecated `ignorePatterns` configuration. Files matching these patterns will be completely invisible to Claude Code, preventing any accidental exposure of sensitive data.
## Subagent configuration
Claude Code supports custom AI subagents that can be configured at both user and project levels. These subagents are stored as Markdown files with YAML frontmatter:
- **User subagents**: `~/.claude/agents/` - Available across all your projects
- **Project subagents**: `.claude/agents/` - Specific to your project and can be shared with your team
Subagent files define specialized AI assistants with custom prompts and tool permissions. Learn more about creating and using subagents in the [subagents documentation](/en/docs/claude-code/sub-agents).
## Environment variables
Claude Code supports the following environment variables to control its behavior:
<Note>
All environment variables can also be configured in [`settings.json`](#available-settings). This is useful as a way to automatically set environment variables for each session, or to roll out a set of environment variables for your whole team or organization.
</Note>
| Variable | Purpose |
| :----------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ANTHROPIC_API_KEY` | API key sent as `X-Api-Key` header, typically for the Claude SDK (for interactive usage, run `/login`) |
| `ANTHROPIC_AUTH_TOKEN` | Custom value for the `Authorization` header (the value you set here will be prefixed with `Bearer `) |
| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers you want to add to the request (in `Name: Value` format) |
| `ANTHROPIC_MODEL` | Name of custom model to use (see [Model Configuration](/en/docs/claude-code/bedrock-vertex-proxies#model-configuration)) |
| `ANTHROPIC_SMALL_FAST_MODEL` | Name of [Haiku-class model for background tasks](/en/docs/claude-code/costs) |
| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the small/fast model when using Bedrock |
| `AWS_BEARER_TOKEN_BEDROCK` | Bedrock API key for authentication (see [Bedrock API keys](https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/)) |
| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands |
| `BASH_MAX_TIMEOUT_MS` | Maximum timeout the model can set for long-running bash commands |
| `BASH_MAX_OUTPUT_LENGTH` | Maximum number of characters in bash outputs before they are middle-truncated |
| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command |
| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using `apiKeyHelper`) |
| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions |
| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Set the maximum number of output tokens for most requests |
| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/docs/claude-code/amazon-bedrock) |
| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/docs/claude-code/google-vertex-ai) |
| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (e.g. when using an LLM gateway) |
| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Vertex (e.g. when using an LLM gateway) |
| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_BUG_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` |
| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context |
| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates. This takes precedence over the `autoUpdates` configuration setting. |
| `DISABLE_BUG_COMMAND` | Set to `1` to disable the `/bug` command |
| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages |
| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting |
| `DISABLE_NON_ESSENTIAL_MODEL_CALLS` | Set to `1` to disable model calls for non-critical paths like flavor text |
| `DISABLE_TELEMETRY` | Set to `1` to opt out of Statsig telemetry (note that Statsig events do not include user data like code, file paths, or bash commands) |
| `HTTP_PROXY` | Specify HTTP proxy server for network connections |
| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections |
| `MAX_THINKING_TOKENS` | Force a thinking for the model budget |
| `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup |
| `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution |
| `MAX_MCP_OUTPUT_TOKENS` | Maximum number of tokens allowed in MCP tool responses (default: 25000) |
| `USE_BUILTIN_RIPGREP` | Set to `1` to ignore system-installed `rg` and use `rg` included with Claude Code |
| `VERTEX_REGION_CLAUDE_3_5_HAIKU` | Override region for Claude 3.5 Haiku when using Vertex AI |
| `VERTEX_REGION_CLAUDE_3_5_SONNET` | Override region for Claude Sonnet 3.5 when using Vertex AI |
| `VERTEX_REGION_CLAUDE_3_7_SONNET` | Override region for Claude 3.7 Sonnet when using Vertex AI |
| `VERTEX_REGION_CLAUDE_4_0_OPUS` | Override region for Claude 4.0 Opus when using Vertex AI |
| `VERTEX_REGION_CLAUDE_4_0_SONNET` | Override region for Claude 4.0 Sonnet when using Vertex AI |
| `VERTEX_REGION_CLAUDE_4_1_OPUS` | Override region for Claude 4.1 Opus when using Vertex AI |
## Configuration options
To manage your configurations, use the following commands:
- List settings: `claude config list`
- See a setting: `claude config get <key>`
- Change a setting: `claude config set <key> <value>`
- Push to a setting (for lists): `claude config add <key> <value>`
- Remove from a setting (for lists): `claude config remove <key> <value>`
By default `config` changes your project configuration. To manage your global configuration, use the `--global` (or `-g`) flag.
### Global configuration
To set a global configuration, use `claude config set -g <key> <value>`:
| Key | Description | Example |
| :---------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------- |
| `autoUpdates` | Whether to enable automatic updates (default: `true`). When enabled, Claude Code automatically downloads and installs updates in the background. Updates are applied when you restart Claude Code. | `false` |
| `preferredNotifChannel` | Where you want to receive notifications (default: `iterm2`) | `iterm2`, `iterm2_with_bell`, `terminal_bell`, or `notifications_disabled` |
| `theme` | Color theme | `dark`, `light`, `light-daltonized`, or `dark-daltonized` |
| `verbose` | Whether to show full bash and command outputs (default: `false`) | `true` |
## Tools available to Claude
Claude Code has access to a set of powerful tools that help it understand and modify your codebase:
| Tool | Description | Permission Required |
| :--------------- | :--------------------------------------------------- | :------------------ |
| **Bash** | Executes shell commands in your environment | Yes |
| **Edit** | Makes targeted edits to specific files | Yes |
| **Glob** | Finds files based on pattern matching | No |
| **Grep** | Searches for patterns in file contents | No |
| **LS** | Lists files and directories | No |
| **MultiEdit** | Performs multiple edits on a single file atomically | Yes |
| **NotebookEdit** | Modifies Jupyter notebook cells | Yes |
| **NotebookRead** | Reads and displays Jupyter notebook contents | No |
| **Read** | Reads the contents of files | No |
| **Task** | Runs a sub-agent to handle complex, multi-step tasks | No |
| **TodoWrite** | Creates and manages structured task lists | No |
| **WebFetch** | Fetches content from a specified URL | Yes |
| **WebSearch** | Performs web searches with domain filtering | Yes |
| **Write** | Creates or overwrites files | Yes |
Permission rules can be configured using `/allowed-tools` or in [permission settings](/en/docs/claude-code/settings#available-settings).
### Extending tools with hooks
You can run custom commands before or after any tool executes using
[Claude Code hooks](/en/docs/claude-code/hooks-guide).
For example, you could automatically run a Python formatter after Claude
modifies Python files, or prevent modifications to production configuration
files by blocking Write operations to certain paths.
## See also
- [Identity and Access Management](/en/docs/claude-code/iam#configuring-permissions) - Learn about Claude Code's permission system
- [IAM and access control](/en/docs/claude-code/iam#enterprise-managed-policy-settings) - Enterprise policy management
- [Troubleshooting](/en/docs/claude-code/troubleshooting#auto-updater-issues) - Solutions for common configuration issues

View File

@@ -0,0 +1,227 @@
# Slash commands
> Control Claude's behavior during an interactive session with slash commands.
## Built-in slash commands
| Command | Purpose |
| :------------------------ | :----------------------------------------------------------------------------- |
| `/add-dir` | Add additional working directories |
| `/agents` | Manage custom AI subagents for specialized tasks |
| `/bug` | Report bugs (sends conversation to Anthropic) |
| `/clear` | Clear conversation history |
| `/compact [instructions]` | Compact conversation with optional focus instructions |
| `/config` | View/modify configuration |
| `/cost` | Show token usage statistics |
| `/doctor` | Checks the health of your Claude Code installation |
| `/help` | Get usage help |
| `/init` | Initialize project with CLAUDE.md guide |
| `/login` | Switch Anthropic accounts |
| `/logout` | Sign out from your Anthropic account |
| `/mcp` | Manage MCP server connections and OAuth authentication |
| `/memory` | Edit CLAUDE.md memory files |
| `/model` | Select or change the AI model |
| `/permissions` | View or update [permissions](/en/docs/claude-code/iam#configuring-permissions) |
| `/pr_comments` | View pull request comments |
| `/review` | Request code review |
| `/status` | View account and system statuses |
| `/terminal-setup` | Install Shift+Enter key binding for newlines (iTerm2 and VSCode only) |
| `/vim` | Enter vim mode for alternating insert and command modes |
## Custom slash commands
Custom slash commands allow you to define frequently-used prompts as Markdown files that Claude Code can execute. Commands are organized by scope (project-specific or personal) and support namespacing through directory structures.
### Syntax
```
/<command-name> [arguments]
```
#### Parameters
| Parameter | Description |
| :--------------- | :---------------------------------------------------------------- |
| `<command-name>` | Name derived from the Markdown filename (without `.md` extension) |
| `[arguments]` | Optional arguments passed to the command |
### Command types
#### Project commands
Commands stored in your repository and shared with your team. When listed in `/help`, these commands show "(project)" after their description.
**Location**: `.claude/commands/`
In the following example, we create the `/optimize` command:
```bash
# Create a project command
mkdir -p .claude/commands
echo "Analyze this code for performance issues and suggest optimizations:" > .claude/commands/optimize.md
```
#### Personal commands
Commands available across all your projects. When listed in `/help`, these commands show "(user)" after their description.
**Location**: `~/.claude/commands/`
In the following example, we create the `/security-review` command:
```bash
# Create a personal command
mkdir -p ~/.claude/commands
echo "Review this code for security vulnerabilities:" > ~/.claude/commands/security-review.md
```
### Features
#### Namespacing
Organize commands in subdirectories. The subdirectories are used for organization and appear in the command description, but they do not affect the command name itself. The description will show whether the command comes from the project directory (`.claude/commands`) or the user-level directory (`~/.claude/commands`), along with the subdirectory name.
Conflicts between user and project level commands are not supported. Otherwise, multiple commands with the same base file name can coexist.
For example, a file at `.claude/commands/frontend/component.md` creates the command `/component` with description showing "(project:frontend)".
Meanwhile, a file at `~/.claude/commands/component.md` creates the command `/component` with description showing "(user)".
#### Arguments
Pass dynamic values to commands using the `$ARGUMENTS` placeholder.
For example:
```bash
# Command definition
echo 'Fix issue #$ARGUMENTS following our coding standards' > .claude/commands/fix-issue.md
# Usage
> /fix-issue 123
```
#### Bash command execution
Execute bash commands before the slash command runs using the `!` prefix. The output is included in the command context. You _must_ include `allowed-tools` with the `Bash` tool, but you can choose the specific bash commands to allow.
For example:
```markdown
---
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
description: Create a git commit
---
## Context
- Current git status: !`git status`
- Current git diff (staged and unstaged changes): !`git diff HEAD`
- Current branch: !`git branch --show-current`
- Recent commits: !`git log --oneline -10`
## Your task
Based on the above changes, create a single git commit.
```
#### File references
Include file contents in commands using the `@` prefix to [reference files](/en/docs/claude-code/common-workflows#reference-files-and-directories).
For example:
```markdown
# Reference a specific file
Review the implementation in @src/utils/helpers.js
# Reference multiple files
Compare @src/old-version.js with @src/new-version.js
```
#### Thinking mode
Slash commands can trigger extended thinking by including [extended thinking keywords](/en/docs/claude-code/common-workflows#use-extended-thinking).
### Frontmatter
Command files support frontmatter, useful for specifying metadata about the command:
| Frontmatter | Purpose | Default |
| :-------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------- |
| `allowed-tools` | List of tools the command can use | Inherits from the conversation |
| `argument-hint` | The arguments expected for the slash command. Example: `argument-hint: add [tagId] \| remove [tagId] \| list`. This hint is shown to the user when auto-completing the slash command. | None |
| `description` | Brief description of the command | Uses the first line from the prompt |
| `model` | Specific model string (see [Models overview](/en/docs/about-claude/models/overview)) | Inherits from the conversation |
For example:
```markdown
---
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
argument-hint: [message]
description: Create a git commit
model: claude-3-5-haiku-20241022
---
An example command
```
## MCP slash commands
MCP servers can expose prompts as slash commands that become available in Claude Code. These commands are dynamically discovered from connected MCP servers.
### Command format
MCP commands follow the pattern:
```
/mcp__<server-name>__<prompt-name> [arguments]
```
### Features
#### Dynamic discovery
MCP commands are automatically available when:
- An MCP server is connected and active
- The server exposes prompts through the MCP protocol
- The prompts are successfully retrieved during connection
#### Arguments
MCP prompts can accept arguments defined by the server:
```
# Without arguments
> /mcp__github__list_prs
# With arguments
> /mcp__github__pr_review 456
> /mcp__jira__create_issue "Bug title" high
```
#### Naming conventions
- Server and prompt names are normalized
- Spaces and special characters become underscores
- Names are lowercased for consistency
### Managing MCP connections
Use the `/mcp` command to:
- View all configured MCP servers
- Check connection status
- Authenticate with OAuth-enabled servers
- Clear authentication tokens
- View available tools and prompts from each server
## See also
- [Interactive mode](/en/docs/claude-code/interactive-mode) - Shortcuts, input modes, and interactive features
- [CLI reference](/en/docs/claude-code/cli-reference) - Command-line flags and options
- [Settings](/en/docs/claude-code/settings) - Configuration options
- [Memory management](/en/docs/claude-code/memory) - Managing Claude's memory across sessions

View File

@@ -0,0 +1,98 @@
# Output styles
> Adapt Claude Code for uses beyond software engineering
Output styles allow you to use Claude Code as any type of agent while keeping
its core capabilities, such as running local scripts, reading/writing files, and
tracking TODOs.
## Built-in output styles
Claude Code's **Default** output style is the existing system prompt, designed
to help you complete software engineering tasks efficiently.
There are two additional built-in output styles focused on teaching you the
codebase and how Claude operates:
- **Explanatory**: Provides educational "Insights" in between helping you
complete software engineering tasks. Helps you understand implementation
choices and codebase patterns.
- **Learning**: Collaborative, learn-by-doing mode where Claude will not only
share "Insights" while coding, but also ask you to contribute small, strategic
pieces of code yourself. Claude Code will add `TODO(human)` markers in your
code for you to implement.
## How output styles work
Output styles directly modify Claude Code's system prompt.
- Non-default output styles exclude instructions specific to code generation and
efficient output normally built into Claude Code (such as responding concisely
and verifying code with tests).
- Instead, these output styles have their own custom instructions added to the
system prompt.
## Change your output style
You can either:
- Run `/output-style` to access the menu and select your output style (this can
also be accessed from the `/config` menu)
- Run `/output-style [style]`, such as `/output-style explanatory`, to directly
switch to a style
These changes apply to the [local project level](/en/docs/claude-code/settings)
and are saved in `.claude/settings.local.json`.
## Create a custom output style
To set up a new output style with Claude's help, run
`/output-style:new I want an output style that ...`
By default, output styles created through `/output-style:new` are saved as
markdown files at the user level in `~/.claude/output-styles` and can be used
across projects. They have the following structure:
```markdown
---
name: My Custom Style
description: A brief description of what this style does, to be displayed to the user
---
# Custom Style Instructions
You are an interactive CLI tool that helps users with software engineering
tasks. [Your custom instructions here...]
## Specific Behaviors
[Define how the assistant should behave in this style...]
```
You can also create your own output style Markdown files and save them either at
the user level (`~/.claude/output-styles`) or the project level
(`.claude/output-styles`).
## Comparisons to related features
### Output Styles vs. CLAUDE.md vs. --append-system-prompt
Output styles completely “turn off” the parts of Claude Codes default system
prompt specific to software engineering. Neither CLAUDE.md nor
`--append-system-prompt` edit Claude Codes default system prompt. CLAUDE.md
adds the contents as a user message _following_ Claude Codes default system
prompt. `--append-system-prompt` appends the content to the system prompt.
### Output Styles vs. [Agents](/en/docs/claude-code/sub-agents)
Output styles directly affect the main agent loop and only affect the system
prompt. Agents are invoked to handle specific tasks and can include additional
settings like the model to use, the tools they have available, and some context
about when to use the agent.
### Output Styles vs. [Custom Slash Commands](/en/docs/claude-code/slash-commands)
You can think of output styles as “stored system prompts” and custom slash
commands as “stored prompts”.

View File

@@ -0,0 +1,340 @@
# Subagents
> Create and use specialized AI subagents in Claude Code for task-specific workflows and improved context management.
Custom subagents in Claude Code are specialized AI assistants that can be invoked to handle specific types of tasks. They enable more efficient problem-solving by providing task-specific configurations with customized system prompts, tools and a separate context window.
## What are subagents?
Subagents are pre-configured AI personalities that Claude Code can delegate tasks to. Each subagent:
- Has a specific purpose and expertise area
- Uses its own context window separate from the main conversation
- Can be configured with specific tools it's allowed to use
- Includes a custom system prompt that guides its behavior
When Claude Code encounters a task that matches a subagent's expertise, it can delegate that task to the specialized subagent, which works independently and returns results.
## Key benefits
<CardGroup cols={2}>
<Card title="Context preservation" icon="layer-group">
Each subagent operates in its own context, preventing pollution of the main conversation and keeping it focused on high-level objectives.
</Card>
<Card title="Specialized expertise" icon="brain">
Subagents can be fine-tuned with detailed instructions for specific domains, leading to higher success rates on designated tasks.
</Card>
<Card title="Reusability" icon="rotate">
Once created, subagents can be used across different projects and shared with your team for consistent workflows.
</Card>
<Card title="Flexible permissions" icon="shield-check">
Each subagent can have different tool access levels, allowing you to limit powerful tools to specific subagent types.
</Card>
</CardGroup>
## Quick start
To create your first subagent:
<Steps>
<Step title="Open the subagents interface">
Run the following command:
```
/agents
```
</Step>
<Step title="Select 'Create New Agent'">
Choose whether to create a project-level or user-level subagent
</Step>
<Step title="Define the subagent">
* **Recommended**: Generate with Claude first, then customize to make it yours
* Describe your subagent in detail and when it should be used
* Select the tools you want to grant access to (or leave blank to inherit all tools)
* The interface shows all available tools, making selection easy
* If you're generating with Claude, you can also edit the system prompt in your own editor by pressing `e`
</Step>
<Step title="Save and use">
Your subagent is now available! Claude will use it automatically when appropriate, or you can invoke it explicitly:
```
> Use the code-reviewer subagent to check my recent changes
```
</Step>
</Steps>
## Subagent configuration
### File locations
Subagents are stored as Markdown files with YAML frontmatter in two possible locations:
| Type | Location | Scope | Priority |
| :-------------------- | :------------------ | :---------------------------- | :------- |
| **Project subagents** | `.claude/agents/` | Available in current project | Highest |
| **User subagents** | `~/.claude/agents/` | Available across all projects | Lower |
When subagent names conflict, project-level subagents take precedence over user-level subagents.
### File format
Each subagent is defined in a Markdown file with this structure:
```markdown
---
name: your-sub-agent-name
description: Description of when this subagent should be invoked
tools: tool1, tool2, tool3 # Optional - inherits all tools if omitted
---
Your subagent's system prompt goes here. This can be multiple paragraphs
and should clearly define the subagent's role, capabilities, and approach
to solving problems.
Include specific instructions, best practices, and any constraints
the subagent should follow.
```
#### Configuration fields
| Field | Required | Description |
| :------------ | :------- | :------------------------------------------------------------------------------------------ |
| `name` | Yes | Unique identifier using lowercase letters and hyphens |
| `description` | Yes | Natural language description of the subagent's purpose |
| `tools` | No | Comma-separated list of specific tools. If omitted, inherits all tools from the main thread |
### Available tools
Subagents can be granted access to any of Claude Code's internal tools. See the [tools documentation](/en/docs/claude-code/settings#tools-available-to-claude) for a complete list of available tools.
<Tip>
**Recommended:** Use the `/agents` command to modify tool access - it provides an interactive interface that lists all available tools, including any connected MCP server tools, making it easier to select the ones you need.
</Tip>
You have two options for configuring tools:
- **Omit the `tools` field** to inherit all tools from the main thread (default), including MCP tools
- **Specify individual tools** as a comma-separated list for more granular control (can be edited manually or via `/agents`)
**MCP Tools**: Subagents can access MCP tools from configured MCP servers. When the `tools` field is omitted, subagents inherit all MCP tools available to the main thread.
## Managing subagents
### Using the /agents command (Recommended)
The `/agents` command provides a comprehensive interface for subagent management:
```
/agents
```
This opens an interactive menu where you can:
- View all available subagents (built-in, user, and project)
- Create new subagents with guided setup
- Edit existing custom subagents, including their tool access
- Delete custom subagents
- See which subagents are active when duplicates exist
- **Easily manage tool permissions** with a complete list of available tools
### Direct file management
You can also manage subagents by working directly with their files:
```bash
# Create a project subagent
mkdir -p .claude/agents
echo '---
name: test-runner
description: Use proactively to run tests and fix failures
---
You are a test automation expert. When you see code changes, proactively run the appropriate tests. If tests fail, analyze the failures and fix them while preserving the original test intent.' > .claude/agents/test-runner.md
# Create a user subagent
mkdir -p ~/.claude/agents
# ... create subagent file
```
## Using subagents effectively
### Automatic delegation
Claude Code proactively delegates tasks based on:
- The task description in your request
- The `description` field in subagent configurations
- Current context and available tools
<Tip>
To encourage more proactive subagent use, include phrases like "use PROACTIVELY" or "MUST BE USED" in your `description` field.
</Tip>
### Explicit invocation
Request a specific subagent by mentioning it in your command:
```
> Use the test-runner subagent to fix failing tests
> Have the code-reviewer subagent look at my recent changes
> Ask the debugger subagent to investigate this error
```
## Example subagents
### Code reviewer
```markdown
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
---
You are a senior code reviewer ensuring high standards of code quality and security.
When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
Review checklist:
- Code is simple and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed
Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)
Include specific examples of how to fix issues.
```
### Debugger
```markdown
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---
You are an expert debugger specializing in root cause analysis.
When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works
Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states
For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations
Focus on fixing the underlying issue, not just symptoms.
```
### Data scientist
```markdown
---
name: data-scientist
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
tools: Bash, Read, Write
---
You are a data scientist specializing in SQL and BigQuery analysis.
When invoked:
1. Understand the data analysis requirement
2. Write efficient SQL queries
3. Use BigQuery command line tools (bq) when appropriate
4. Analyze and summarize results
5. Present findings clearly
Key practices:
- Write optimized SQL queries with proper filters
- Use appropriate aggregations and joins
- Include comments explaining complex logic
- Format results for readability
- Provide data-driven recommendations
For each analysis:
- Explain the query approach
- Document any assumptions
- Highlight key findings
- Suggest next steps based on data
Always ensure queries are efficient and cost-effective.
```
## Best practices
- **Start with Claude-generated agents**: We highly recommend generating your initial subagent with Claude and then iterating on it to make it personally yours. This approach gives you the best results - a solid foundation that you can customize to your specific needs.
- **Design focused subagents**: Create subagents with single, clear responsibilities rather than trying to make one subagent do everything. This improves performance and makes subagents more predictable.
- **Write detailed prompts**: Include specific instructions, examples, and constraints in your system prompts. The more guidance you provide, the better the subagent will perform.
- **Limit tool access**: Only grant tools that are necessary for the subagent's purpose. This improves security and helps the subagent focus on relevant actions.
- **Version control**: Check project subagents into version control so your team can benefit from and improve them collaboratively.
## Advanced usage
### Chaining subagents
For complex workflows, you can chain multiple subagents:
```
> First use the code-analyzer subagent to find performance issues, then use the optimizer subagent to fix them
```
### Dynamic subagent selection
Claude Code intelligently selects subagents based on context. Make your `description` fields specific and action-oriented for best results.
## Performance considerations
- **Context efficiency**: Agents help preserve main context, enabling longer overall sessions
- **Latency**: Subagents start off with a clean slate each time they are invoked and may add latency as they gather context that they require to do their job effectively.
## Related documentation
- [Slash commands](/en/docs/claude-code/slash-commands) - Learn about other built-in commands
- [Settings](/en/docs/claude-code/settings) - Configure Claude Code behavior
- [Hooks](/en/docs/claude-code/hooks) - Automate workflows with event handlers

View File

@@ -0,0 +1,46 @@
# Claude Code Documentation Context
This directory contains documentation pages from [Anthropic's Claude Code documentation](https://docs.anthropic.com/) that have been downloaded for AI context and reference.
## Purpose
These files serve as authoritative documentation for Claude Code features, allowing AI assistants to provide accurate information about Claude Code capabilities, settings, and usage patterns without needing to access the web for common queries.
## File Naming Convention
Files are named based on their URL path from the docs site:
- URL: `https://docs.anthropic.com/en/docs/claude-code/settings#tools-available-to-claude`
- Filename: `CLAUDE_CODE_SETTINGS.md`
The naming follows these rules:
- Convert path segments to uppercase
- Replace `/` with `_`
- Remove language prefixes (`/en/docs/`)
- Ignore URL anchors (the `#` portion)
- Use `.md` extension
## How to Add New Documentation
1. Navigate to the desired page on https://docs.anthropic.com/
2. Click the "Copy page" button in the top right corner
3. Select "Copy page as Markdown for LLMs"
4. Create a new file in this directory following the naming convention
5. Paste the copied content into the file
## For AI Assistants
When using these files:
- Treat content as current, valid Claude Code documentation
- All relative URLs in the files are relative to `https://docs.anthropic.com/`
- If you encounter a relative link to documentation not yet downloaded:
1. First check if the file exists using the naming convention above
2. If not found, attempt to retrieve using available tools
**Note to AI:** Please update this section with the most effective method for retrieving missing documentation pages (web fetch tools vs browser-use MCP server) once you've determined which works best through testing.
## Maintenance
Periodically check for updates to the documentation on the Anthropic site, as these local copies may become outdated. The "Copy page" feature ensures we get the most LLM-friendly format of the documentation.

View File

@@ -0,0 +1,7 @@
# Generated AI Context
**NOTE: GENERATED FILES - DO NOT EDIT DIRECTLY**
Auto-generated project roll-ups for AI assistant consumption.
Regenerate with `make ai-context-files` after project changes.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,7 @@
# Git Collector Files
**NOTE: GENERATED FILES - DO NOT EDIT DIRECTLY**
External library documentation collected via git-collector tool.
Regenerate with `make ai-context-files`.