moai-foundation-claude
Imported from https://github.com/junseokandylee/ClaudeAutomate.
Packaged view
This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.
Install command
npx @skill-hub/cli install junseokandylee-claudeautomate-moai-foundation-claude
Repository
Skill path: .claude/skills/moai-foundation-claude
Imported from https://github.com/junseokandylee/ClaudeAutomate.
Open repositoryBest for
Primary workflow: Ship Full Stack.
Technical facets: Full Stack.
Target audience: everyone.
License: Unknown.
Original source
Catalog source: SkillHub Club.
Repository owner: junseokandylee.
This is still a mirrored public skill entry. Review the repository before installing into production workflows.
What it helps with
- Install moai-foundation-claude into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
- Review https://github.com/junseokandylee/ClaudeAutomate before adding moai-foundation-claude to shared team environments
- Use moai-foundation-claude for development workflows
Works across
Favorites: 0.
Sub-skills: 0.
Aggregator: No.
Original source / Raw SKILL.md
---
name: moai-foundation-claude
aliases: [moai-foundation-claude]
category: foundation
description: Canonical Claude Code skill authoring kit covering agent Skills, sub-agent templates, custom slash commands, orchestration patterns, hooks, memory, settings, and IAM permission rules aligned with official documentation.
version: 2.0.0
modularized: false
allowed-tools: Read, Write, Edit, Grep, Glob
tags:
- foundation
- claude-code
- skills
- sub-agents
- slash-commands
- orchestration
- hooks
- memory
- settings
- iam
- best-practices
# Claude Code Authoring Kit
Comprehensive reference for Claude Code Skills, sub-agents, custom slash commands, hooks, memory, settings, and IAM permissions with official standards compliance.
Official Documentation References:
- [Skills Guide](reference/claude-code-skills-official.md) - Agent Skills creation and management
- [Sub-agents Guide](reference/claude-code-sub-agents-official.md) - Sub-agent development and delegation
- [Custom Slash Commands](reference/claude-code-custom-slash-commands-official.md) - Command creation and orchestration
- [Hooks System](reference/claude-code-hooks-official.md) - Event-driven automation
- [Memory Management](reference/claude-code-memory-official.md) - Context and knowledge persistence
- [Settings Configuration](reference/claude-code-settings-official.md) - Configuration hierarchy and management
- [IAM & Permissions](reference/claude-code-iam-official.md) - Access control and security
- [Complete Configuration](reference/complete-configuration-guide.md) - Comprehensive setup guide
## Quick Reference (30 seconds)
Skills: `~/.claude/skills/` (personal) or `.claude/skills/` (project), ≤500 lines, progressive disclosure
Sub-agents: `Task(subagent_type="...")` delegation only, no nested spawning
Commands: `$ARGUMENTS`/`$1`/`$2` parameters, `@file` references, stored in `.claude/commands/`
Hooks: Event-driven automation in `settings.json`, PreToolUse/PostToolUse events
Memory: Enterprise → Project → User hierarchy, `@import.md` syntax
Settings: 4-tier hierarchy (Enterprise → User → Project → Local)
IAM: Tiered permissions (Read→Bash→Write→Admin), tool-specific rules
## Implementation Guide (5 minutes)
### Features
- Comprehensive Claude Code authoring reference
- Skills, sub-agents, commands, hooks, and settings
- IAM permissions and security best practices
- Progressive disclosure documentation architecture
- MCP integration patterns and examples
### When to Use
- Creating new Claude Code skills following official standards
- Developing custom sub-agents with proper delegation patterns
- Implementing custom slash commands with parameter handling
- Setting up hooks for event-driven automation
- Configuring IAM permissions and access control
### Core Patterns
Pattern 1: Skill Creation (≤500 lines)
```yaml
---
name: skill-name
description: One-line description (max 200 chars)
version: 1.0.0
updated: 2025-11-26
status: active
---
## Quick Reference (30 seconds)
## Implementation Guide (5 minutes)
## Advanced Implementation (10+ minutes)
```
Pattern 2: Sub-agent Delegation
```python
# Sequential delegation
result1 = Task(subagent_type="workflow-spec", prompt="Analyze")
result2 = Task(subagent_type="code-backend", prompt="Implement", context=result1)
# Parallel delegation
results = await Promise.all([
Task(subagent_type="code-backend", prompt="Backend"),
Task(subagent_type="code-frontend", prompt="Frontend")
])
```
Pattern 3: Custom Command with Hooks
```json
{
"hooks": {
"PreToolUse": [{
"matcher": "Write",
"hooks": [{"type": "command", "command": "validate-write"}]
}]
}
}
```
## MoAI-ADK Skills & Sub-agents Directory
### Quick Access Patterns
Core Skills: `Skill("moai-foundation-claude")` - This comprehensive authoring kit
Agent Creation: `Task(subagent_type="agent-factory")` - Create standardized sub-agents
Skill Creation: `Task(subagent_type="skill-factory")` - Create compliant skills
Quality Gates: `Task(subagent_type="quality-gate")` - TRUST 5 validation
Documentation: `Task(subagent_type="docs-manager")` - Generate technical docs
Key Specialized Skills:
- `moai-lang-python` - Python 3.13+ with FastAPI, async patterns
- `moai-lang-typescript` - TypeScript 5.9+ with React 19, Next.js 16
- `moai-domain-backend` - Modern backend architecture patterns
- `moai-domain-frontend` - React 19, Next.js 15, Vue 3.5 frameworks
- `moai-quality-security` - OWASP Top 10, threat modeling
- `moai-essentials-debug` - AI-powered debugging with Context7
Essential Sub-agents:
- `spec-builder` - EARS format specification generation
- `tdd-implementer` - RED-GREEN-REFACTOR TDD execution
- `security-expert` - Security analysis and validation
- `backend-expert` - Backend architecture and API development
- `frontend-expert` - Frontend UI implementation
- `performance-engineer` - Performance optimization and analysis
## Essential Implementation Patterns
### Command→Agent→Skill Orchestration
Sequential Workflow:
```python
# Phase 1: Analysis → spec-builder → analysis
analysis = Task(subagent_type="spec-builder", prompt="Analyze: $ARGUMENTS")
# Phase 2: Implementation → tdd-implementer → code + tests
implementation = Task(subagent_type="tdd-implementer", prompt="Implement: $analysis.spec_id")
# Phase 3: Validation → quality-gate → approval
validation = Task(subagent_type="quality-gate", prompt="Validate: $implementation")
```
Parallel Development:
```python
# Execute independent tasks simultaneously
results = await Promise.all([
Task(subagent_type="backend-expert", prompt="Backend: $1"),
Task(subagent_type="frontend-expert", prompt="Frontend: $1"),
Task(subagent_type="docs-manager", prompt="Docs: $1")
])
# Integrate all results
Task(subagent_type="quality-gate", prompt="Integrate", context={"results": results})
```
### Token Session Management
Independent 200K Sessions: Each `Task()` creates a new 200K token context
```python
Task(subagent_type="backend-expert", prompt="Complex task") # 200K session
Task(subagent_type="frontend-expert", prompt="UI task") # New 200K session
```
### File Reference Patterns
Parameter Handling:
- Positional: `$1`, `$2`, `$3`
- All arguments: `$ARGUMENTS`
- File references: `@config.yaml`, `@path/to/file.md`
### Hook Integration
Pre/Post Tool Execution (see [Hooks Guide](reference/claude-code-hooks-official.md)):
```json
{
"hooks": {
"PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "validate-command"}]}],
"PostToolUse": [{"matcher": "Write", "hooks": [{"type": "command", "command": "backup-file"}]}]
}
}
```
## Key Reference Guides
Comprehensive Documentation:
- [Commands Guide](reference/claude-code-custom-slash-commands-official.md) - Complete command creation
- [Hooks System](reference/claude-code-hooks-official.md) - Event-driven automation
- [Memory Management](reference/claude-code-memory-official.md) - Context persistence
- [Settings Config](reference/claude-code-settings-official.md) - Configuration hierarchy
- [IAM Permissions](reference/claude-code-iam-official.md) - Access control
- [Complete Setup](reference/complete-configuration-guide.md) - Full configuration
## Works Well With
- moai-core-agent-factory - For creating new sub-agents with proper standards
- moai-cc-commands - For creating custom slash commands
- moai-cc-hooks - For implementing Claude Code hooks
- moai-cc-configuration - For managing Claude Code settings
- moai-quality-gate - For validating code quality standards
- moai-essentials-debug - For debugging skill loading issues
---
## Referenced Files
> The following files are referenced in this skill and included for context.
### reference/claude-code-skills-official.md
```markdown
# Claude Code Skills - Official Documentation Reference
Source: https://code.claude.com/docs/en/skills
## Key Concepts
### What are Claude Code Skills?
Skills are reusable pieces of functionality that extend Claude Code's capabilities. They can be automatically loaded based on context or manually invoked by users.
### Skill Types
1. Automatic Skills: Load automatically based on conversation context
2. Manual Skills: User must explicitly invoke using `/skill <skill-name>`
3. Plugin Skills: Bundled with installed packages
### Storage Locations (Priority Order)
1. Personal Skills: `~/.claude/skills/` (highest priority)
2. Project Skills: `.claude/skills/` (team-shared)
3. Plugin Skills: Bundled with installed packages (lowest priority)
### Required Frontmatter Fields
```yaml
---
name: my-skill # Required: kebab-case, max 64 chars
description: Brief description of what the skill does and when to trigger it
allowed-tools: Read, Write, Bash # Required: comma-separated tool list
---
```
### Optional Frontmatter Fields
```yaml
---
name: my-skill
description: What the skill does and when to trigger it
version: 1.0.0 # Semantic versioning
modularized: false # Whether skill can be split into modules
tags: [tag1, tag2] # For categorization
updated: 2025-11-25 # Last update date
status: active # active, deprecated, experimental
---
```
### Skill Discovery and Loading
- Automatic Loading: Skills load when Claude detects relevant context
- Progressive Loading: Supporting files load on-demand
- Tool Restrictions: Skills only have access to declared tools
### Best Practices
1. Single Responsibility: Each skill should have one clear purpose
2. Specific Descriptions: Include trigger scenarios in description
3. Minimal Tools: Declare only necessary tools using least privilege
4. Progressive Disclosure: Keep main SKILL.md concise; expand with supporting files
5. Working Examples: Include practical, tested examples
### File Structure Standards
```
skill-name/
SKILL.md # Always create (main file, ≤ 500 lines)
reference.md # Optional: Extended documentation
examples.md # Optional: Code examples
scripts/ # Optional: Utility scripts
helper.sh
templates/ # Optional: File templates
template.md
```
### Skill Naming Conventions
- Format: kebab-case (lowercase with hyphens)
- Length: Maximum 64 characters
- Uniqueness: Must be unique across all storage locations
- Descriptive: Name should indicate skill purpose
### Tool Permissions
Skills only have access to tools declared in `allowed-tools`. Common tool categories:
- Information: `Read`, `Grep`, `Glob` (no user approval needed)
- Modification: `Write`, `Edit`, `Bash` (user approval required)
- External: `WebFetch`, `WebSearch` (user approval required)
### Integration Patterns
Skill Dependencies:
```yaml
skills: moai-foundation-claude, other-skill-name
```
MCP Server Integration:
```yaml
mcpServers:
- context7
- figma-dev-mode-mcp-server
```
### Validation and Debugging
Common Issues:
- Skill not loading: Check YAML syntax and file path
- Tool prompts unexpected: Review `allowed-tools` declaration
- Duplicate triggers: Rename skill or tighten description
Debug Commands:
- `claude --debug`: Check skill loading and configuration
- Validate YAML: Use online YAML validators or local tools
- Test skills: Create test cases for skill functionality
```
### reference/claude-code-sub-agents-official.md
```markdown
# Claude Code Sub-agents - Official Documentation Reference
Source: https://code.claude.com/docs/en/sub-agents
## Key Concepts
### What are Claude Code Sub-agents?
Sub-agents are specialized AI assistants that can be invoked to handle specific tasks or domains. They extend Claude Code's capabilities through delegation patterns.
### Sub-agent Limitations
Critical Constraint: Sub-agents cannot spawn other sub-agents. This is a fundamental limitation to prevent infinite recursion.
Required Pattern: All sub-agent delegation must use the `Task()` function:
```python
# CORRECT - Required delegation pattern
Task(subagent_type="specialized-agent", prompt="Handle specific task")
```
### Sub-agent Configuration
Required Fields:
```yaml
---
name: agent-name
description: Clear description of agent's purpose and domain
tools: Read, Write, Bash, Grep # Required: Available tools
model: sonnet # Model choice: sonnet, opus, haiku, inherit
permissionMode: default # Permission handling strategy
skills: skill1, skill2 # Available skills for agent
---
```
### Model Selection
- sonnet: Balanced performance and quality (default)
- opus: Highest quality, higher cost
- haiku: Fastest, most cost-effective
- inherit: Use same model as calling agent
### Permission Modes
Official Claude Code permissionMode values (verified from official documentation):
- default: Standard permission prompts. Each tool usage requires user approval on first use in the session. This is the default value if permissionMode is omitted. Recommended for most agents requiring user oversight.
- acceptEdits: Automatically accepts file edit operations (Write, Edit, MultiEdit) without prompting. Other tool operations (like Bash) still require approval. Use for trusted development environments where file modifications are expected and safe.
- dontAsk: Suppresses all permission dialog prompts for this agent. All tool operations proceed without user confirmation. Use with caution - recommended ONLY for automated environments, CI/CD pipelines, or fully sandboxed contexts.
Important Notes:
- If `permissionMode` is omitted, the default value is `default`
- The values `bypassPermissions`, `plan`, and `ignore` are NOT official permissionMode values
- For maximum security, use `default` and explicitly approve each operation
- For automation workflows in safe environments, `acceptEdits` or `dontAsk` may be appropriate
### Tool Permissions
Security Principle: Apply least privilege - only grant tools necessary for agent's domain.
Common Tool Categories:
- Read Tools: `Read`, `Grep`, `Glob` (file system access)
- Write Tools: `Write`, `Edit`, `MultiEdit` (file modification)
- System Tools: `Bash` (command execution)
- Communication Tools: `AskUserQuestion`, `WebFetch` (interaction)
### Sub-agent Creation Patterns
Domain-Specific Specialization:
```yaml
---
name: security-expert
description: OWASP security analysis and vulnerability assessment
tools: Read, Grep, Bash, WebFetch
model: sonnet
skills: moai-quality-security
---
```
Task-Oriented Specialization:
```yaml
---
name: spec-builder
description: Generate EARS format specifications from requirements
tools: Read, Write, Bash
model: sonnet
skills: moai-foundation-specs
---
```
### Best Practices
1. Clear Scope Definition: Single domain or responsibility
2. Specific System Prompts: Clear instructions about agent boundaries
3. Security Boundaries: Explicit limitations on agent behavior
4. Error Handling: Robust error recovery and fallback strategies
5. Performance Considerations: Appropriate model selection and context management
### Integration Patterns
Sequential Delegation:
```python
# Phase 1: Analysis
analysis = Task(
subagent_type="spec-builder",
prompt="Analyze requirements for user authentication"
)
# Phase 2: Implementation (passes analysis results)
implementation = Task(
subagent_type="backend-expert",
prompt="Implement authentication API based on analysis",
context={"analysis": analysis}
)
```
Parallel Delegation:
```python
# Independent execution
results = await Promise.all([
Task(subagent_type="backend-expert", prompt="Backend implementation"),
Task(subagent_type="frontend-expert", prompt="Frontend implementation"),
Task(subagent_type="test-engineer", prompt="Test strategy")
])
```
Conditional Delegation:
```python
# Route based on analysis results
if analysis.has_database_issues:
result = Task(subagent_type="database-expert", prompt="Optimize database")
elif analysis.has_api_issues:
result = Task(subagent_type="backend-expert", prompt="Fix API issues")
```
### Context Management
Efficient Data Passing:
- Pass only essential information between agents
- Use structured data formats for complex information
- Minimize context size for performance optimization
- Include validation metadata when appropriate
Context Size Limits:
- Each Task() creates independent context window
- Recommended context size: 20K-50K tokens maximum
- Large datasets should be referenced rather than embedded
### File Storage Standards
Agent Definition Location:
```
.claude/agents/
domain/
agent-name.md # Agent definition
examples.md # Usage examples
integration.md # Integration patterns
validation.md # Quality checks
agent-factory.md # Agent creation utilities
```
### Naming Conventions
- Format: lowercase with hyphens (domain-function)
- Length: Maximum 64 characters
- Descriptive: Name should clearly indicate agent's domain
- Unique: Must be unique across all agents
### Testing and Validation
Test Categories:
1. Functionality Testing: Agent performs expected tasks correctly
2. Integration Testing: Agent works properly with other agents
3. Security Testing: Agent respects security boundaries
4. Performance Testing: Agent operates efficiently within token limits
Validation Steps:
1. Test agent behavior with various inputs
2. Verify tool usage respects permissions
3. Validate error handling and recovery
4. Check integration with other agents or skills
### Error Handling
Common Error Types:
- Agent Not Found: Incorrect agent name or file not found
- Permission Denied: Insufficient tool permissions
- Context Overflow: Too much context passed between agents
- Infinite Recursion: Agent tries to spawn another sub-agent
Recovery Strategies:
- Fallback to basic functionality
- User notification with clear error messages
- Graceful degradation of complex features
- Context optimization for retry attempts
### Performance Optimization
Model Selection Guidelines:
- Simple Tasks: Use `haiku` for speed and cost efficiency
- Complex Analysis: Use `sonnet` for quality and reliability
- Creative Tasks: Use `opus` for highest quality output
- Cost-Sensitive: Use `haiku` with careful prompt optimization
Context Optimization:
- Minimize passed context between agents
- Use efficient data structures
- Cache reusable results
- Avoid circular references
### Security Considerations
Access Control:
- Apply principle of least privilege
- Validate all external inputs
- Restrict file system access where appropriate
- Audit tool usage regularly
Data Protection:
- Never pass sensitive credentials
- Sanitize inputs before processing
- Use secure communication channels
- Log agent activities appropriately
### Monitoring and Observability
Activity Logging:
- Track all agent invocations
- Monitor token usage and performance
- Log error conditions and recovery attempts
- Record integration patterns and dependencies
Quality Metrics:
- Agent success rates and error frequencies
- Average response times per task type
- Token efficiency and optimization opportunities
- User satisfaction and feedback collection
```
### reference/claude-code-custom-slash-commands-official.md
```markdown
# Claude Code Custom Slash Commands - Official Documentation Reference
Source: https://code.claude.com/docs/en/slash-commands#custom-slash-commands
## Key Concepts
### What are Custom Slash Commands?
Custom slash commands are user-defined commands that extend Claude Code's functionality with specialized workflows, automations, and integrations. They follow a specific file structure and syntax, enabling powerful command→agent→skill orchestration patterns.
### Command Architecture
Command Execution Flow:
```
User Input → Command File → Parameter Parsing → Agent Delegation → Skill Execution
```
Command Components:
1. Command File: Markdown file with frontmatter and implementation
2. Parameter System: Argument parsing and validation
3. Agent Orchestration: Multi-agent workflow coordination
4. Skill Integration: Specialized knowledge and capabilities
5. Result Processing: Output formatting and user feedback
## Command File Structure
### Storage Locations
Command Directory Priority:
1. Personal Commands: `~/.claude/commands/` (highest priority)
2. Project Commands: `.claude/commands/` (team-shared)
3. Plugin Commands: Bundled with installed packages (lowest priority)
Directory Structure:
```
.claude/commands/
category1/
my-command.md
related-command.md
category2/
specialized-command.md
README.md # Command index and documentation
```
### Command File Format
Complete Command Template:
```markdown
---
name: my-command
description: Brief description of what the command does and when to use it
usage: |
/my-command [argument] [options]
Examples:
/my-command create user --name="John Doe"
/my-command validate @config.yaml
parameters:
- name: action
description: Action to perform (create, update, delete, validate)
required: true
type: string
values: [create, update, delete, validate]
- name: target
description: Target entity or file to operate on
required: false
type: string
allowFileReference: true
- name: options
description: Additional command options
required: false
type: object
default: {}
---
# Command Implementation
## Quick Reference
Purpose: One-line summary of command purpose
Usage: `/my-command <action> <target> [options]`
Examples: 2-3 common usage patterns
## Implementation
### Phase 1: Input Validation
```bash
# Validate required parameters
if [ -z "$1" ]; then
echo "Error: Action parameter is required"
echo "Usage: /my-command <action> <target> [options]"
exit 1
fi
```
### Phase 2: Agent Delegation
```python
# Delegate to appropriate agents
action="$1"
target="$2"
case "$action" in
"create")
Task(
subagent_type="spec-builder",
prompt="Create specification for $target",
context={"user_input": "$ARGUMENTS"}
)
;;
"validate")
Task(
subagent_type="quality-gate",
prompt="Validate configuration in $target",
context={"config_file": "$target"}
)
;;
esac
```
### Phase 3: Result Processing
```python
# Process agent results and format output
results = await Promise.all(agent_tasks)
# Format results for user
formatted_output = format_command_output(results, action)
# Provide user feedback
echo "Command completed successfully"
echo "Results: $formatted_output"
```
```
## Parameter System
### Parameter Types
String Parameters:
```yaml
parameters:
- name: feature_name
description: Name of the feature to implement
required: true
type: string
validation:
pattern: "^[a-z][a-z0-9-]*$"
minLength: 3
maxLength: 50
```
File Reference Parameters:
```yaml
parameters:
- name: config_file
description: Configuration file to process
required: false
type: string
allowFileReference: true
validation:
fileExists: true
fileExtensions: [".yaml", ".json", ".toml"]
```
Boolean Parameters:
```yaml
parameters:
- name: verbose
description: Enable verbose output
required: false
type: boolean
default: false
shortFlag: "-v"
longFlag: "--verbose"
```
Choice Parameters:
```yaml
parameters:
- name: environment
description: Target environment
required: false
type: string
values: [development, staging, production]
default: development
```
Object Parameters:
```yaml
parameters:
- name: options
description: Additional options object
required: false
type: object
properties:
timeout:
type: number
default: 300
retries:
type: number
default: 3
additionalProperties: true
```
### Parameter Access Patterns
Positional Arguments:
```bash
# $1, $2, $3... for positional arguments
action="$1" # First argument
target="$2" # Second argument
options="$3" # Third argument
# All arguments as single string
all_args="$ARGUMENTS"
```
Named Arguments:
```bash
# Parse named arguments using getopts
while getopts ":f:t:v" opt; do
case $opt in
f) file="$OPTARG" ;;
t) timeout="$OPTARG" ;;
v) verbose=true ;;
esac
done
```
File References:
```bash
# File reference handling with @ prefix
if [[ "$target" == @* ]]; then
file_path="${target#@}"
if [ -f "$file_path" ]; then
file_content=$(cat "$file_path")
else
echo "Error: File not found: $file_path"
exit 1
fi
fi
```
## Agent Orchestration Patterns
### Sequential Agent Workflow
Linear Execution Pattern:
```python
# Phase 1: Analysis
analysis = Task(
subagent_type="spec-builder",
prompt="Analyze requirements for $ARGUMENTS",
context={"user_input": "$ARGUMENTS"}
)
# Phase 2: Implementation (passes analysis results)
implementation = Task(
subagent_type="tdd-implementer",
prompt="Implement based on analysis",
context={"analysis": analysis, "spec_id": analysis.spec_id}
)
# Phase 3: Quality Validation
validation = Task(
subagent_type="quality-gate",
prompt="Validate implementation",
context={"implementation": implementation}
)
```
### Parallel Agent Workflow
Concurrent Execution Pattern:
```python
# Independent parallel execution
results = await Promise.all([
Task(
subagent_type="backend-expert",
prompt="Backend implementation for $1"
),
Task(
subagent_type="frontend-expert",
prompt="Frontend implementation for $1"
),
Task(
subagent_type="docs-manager",
prompt="Documentation for $1"
)
])
# Integration phase
integration = Task(
subagent_type="quality-gate",
prompt="Integrate all components",
context={"components": results}
)
```
### Conditional Agent Workflow
Dynamic Agent Selection:
```python
# Route based on analysis results
if analysis.has_database_issues:
result = Task(
subagent_type="database-expert",
prompt="Optimize database",
context={"issues": analysis.database_issues}
)
elif analysis.has_api_issues:
result = Task(
subagent_type="backend-expert",
prompt="Fix API issues",
context={"issues": analysis.api_issues}
)
else:
result = Task(
subagent_type="quality-gate",
prompt="General quality check",
context={"analysis": analysis}
)
```
## Command Examples
### Simple Validation Command
Configuration Validator:
```markdown
---
name: validate-config
description: Validate configuration files against schema and best practices
usage: |
/validate-config <file> [options]
Examples:
/validate-config app.yaml
/validate-config @production-config.json --strict
parameters:
- name: file
description: Configuration file to validate
required: true
type: string
allowFileReference: true
- name: strict
description: Enable strict validation mode
required: false
type: boolean
default: false
---
# Configuration Validator
## Quick Reference
Validates YAML/JSON configuration files against schemas and best practices.
## Implementation
### Input Processing
```bash
config_file="$1"
strict_mode="$2"
# Handle file reference
if [[ "$config_file" == @* ]]; then
config_file="${config_file#@}"
fi
# Validate file exists
if [ ! -f "$config_file" ]; then
echo "Error: Configuration file not found: $config_file"
exit 1
fi
```
### Validation Execution
```python
# Determine validation strategy
if [[ "$config_file" == *.yaml ]] || [[ "$config_file" == *.yml ]]; then
validator = "yaml-validator"
elif [[ "$config_file" == *.json ]]; then
validator = "json-validator"
else
echo "Error: Unsupported file format"
exit 1
fi
# Execute validation
Task(
subagent_type="quality-gate",
prompt="Validate $config_file using $validator" +
(" --strict" if strict_mode else ""),
context={
"file_path": config_file,
"validator": validator,
"strict_mode": strict_mode == "--strict"
}
)
```
```
### Complex Multi-Phase Command
Feature Implementation Workflow:
```markdown
---
name: implement-feature
description: Complete feature implementation workflow from spec to deployment
usage: |
/implement-feature "Feature description" [options]
Examples:
/implement-feature "Add user authentication with JWT"
/implement-feature "Create API endpoints" --skip-tests
parameters:
- name: description
description: Feature description to implement
required: true
type: string
- name: skip_tests
description: Skip test implementation phase
required: false
type: boolean
default: false
- name: environment
description: Target environment
required: false
type: string
values: [development, staging, production]
default: development
---
# Feature Implementation Workflow
## Quick Reference
Complete TDD-based feature implementation from specification to deployment.
## Implementation
### Phase 1: Specification Generation
```python
# Generate comprehensive specification
spec_result = Task(
subagent_type="spec-builder",
prompt="Create detailed specification for: $1",
context={
"feature_description": "$1",
"environment": "$3"
}
)
spec_id = spec_result.spec_id
echo "Specification created: $spec_id"
```
### Phase 2: Implementation Planning
```python
# Plan implementation approach
plan_result = Task(
subagent_type="plan",
prompt="Create implementation plan for $spec_id",
context={
"spec_id": spec_id,
"skip_tests": "$2"
}
)
```
### Phase 3: Test Implementation (if not skipped)
```python
if [ "$2" != "--skip-tests" ]; then
# RED phase: Write failing tests
test_result = Task(
subagent_type="test-engineer",
prompt="Write comprehensive tests for $spec_id",
context={"spec_id": spec_id}
)
fi
```
### Phase 4: Feature Implementation
```python
# GREEN phase: Implement feature
implementation_result = Task(
subagent_type="tdd-implementer",
prompt="Implement feature for $spec_id",
context={
"spec_id": spec_id,
"tests_available": "$2" != "--skip-tests"
}
)
```
### Phase 5: Quality Assurance
```python
# REFACTOR and validation
quality_result = Task(
subagent_type="quality-gate",
prompt="Validate implementation for $spec_id",
context={
"implementation": implementation_result,
"test_coverage": "90%" if "$2" != "--skip-tests" else "0%"
}
)
```
### Phase 6: Documentation
```python
# Generate documentation
docs_result = Task(
subagent_type="docs-manager",
prompt="Create documentation for $spec_id",
context={"spec_id": spec_id}
)
```
### Results Summary
```python
echo "Feature implementation completed!"
echo "Specification: $spec_id"
echo "Implementation: $(echo $implementation_result | jq .status)"
echo "Quality Score: $(echo $quality_result | jq .score)"
echo "Documentation: $(echo $docs_result | jq .generated_files)"
```
```
### Integration Command
CI/CD Pipeline Integration:
```markdown
---
name: deploy
description: Deploy application with comprehensive validation and rollback capability
usage: |
/deploy [environment] [options]
Examples:
/deploy staging
/deploy production --skip-tests --dry-run
parameters:
- name: environment
description: Target deployment environment
required: false
type: string
values: [staging, production]
default: staging
- name: skip_tests
description: Skip pre-deployment tests
required: false
type: boolean
default: false
- name: dry_run
description: Perform dry-run deployment
required: false
type: boolean
default: false
---
# Deployment Pipeline
## Quick Reference
Safe deployment with validation, testing, and rollback capabilities.
## Implementation
### Pre-Deployment Validation
```python
# Environment validation
env_result = Task(
subagent_type="devops-expert",
prompt="Validate $1 environment configuration",
context={"environment": "$1"}
)
# Security validation
security_result = Task(
subagent_type="security-expert",
prompt="Perform security pre-deployment check",
context={"environment": "$1"}
)
```
### Testing Phase
```python
if [ "$2" != "--skip-tests" ]; then
# Run comprehensive test suite
test_result = Task(
subagent_type="test-engineer",
prompt="Execute deployment test suite",
context={"environment": "$1"}
)
fi
```
### Deployment Execution
```python
if [ "$3" != "--dry-run" ]; then
# Actual deployment
deploy_result = Task(
subagent_type="devops-expert",
prompt="Deploy to $1 environment",
context={
"environment": "$1",
"rollback_plan": true
}
)
else
echo "Dry-run mode: Deployment simulated"
deploy_result = {"status": "simulated", "environment": "$1"}
fi
```
### Post-Deployment Validation
```python
# Health check and validation
health_result = Task(
subagent_type="monitoring-expert",
prompt="Validate deployment health in $1",
context={"environment": "$1"}
)
# Generate deployment report
report_result = Task(
subagent_type="docs-manager",
prompt="Generate deployment report",
context={
"environment": "$1",
"deployment": deploy_result,
"health": health_result
}
)
```
```
## Command Distribution and Sharing
### Team Command Distribution
Git-Based Distribution:
```bash
# Store commands in version control
git add .claude/commands/
git commit -m "Add custom commands for team workflow"
# Team members clone and update
git pull origin main
claude commands reload
```
Package Distribution:
```bash
# Create command package
claude commands package --name "team-workflows" --version "1.0.0"
# Install command package
claude commands install [email protected]
```
### Command Documentation
Command Index Generation:
```markdown
# .claude/commands/README.md
## Team Command Library
### Development Commands
- `/implement-feature` - Complete feature implementation workflow
- `/validate-config` - Configuration file validation
- `/create-component` - Component scaffolding and setup
### Deployment Commands
- `/deploy` - Safe deployment with rollback
- `/rollback` - Emergency rollback procedure
- `/health-check` - System health validation
### Analysis Commands
- `/analyze-performance` - Performance bottleneck analysis
- `/security-audit` - Security vulnerability assessment
- `/code-review` - Automated code review
```
## Best Practices
### Command Design
Naming Conventions:
- Use kebab-case for command names: `implement-feature`, `validate-config`
- Keep names descriptive and action-oriented
- Avoid abbreviations and jargon
- Use consistent prefixes for related commands
Parameter Design:
- Required parameters come first
- Use descriptive parameter names
- Provide clear validation and error messages
- Support common patterns (file references, boolean flags)
Error Handling:
- Validate all inputs before processing
- Provide helpful error messages with suggestions
- Implement graceful degradation
- Support dry-run modes for destructive operations
### Performance Optimization
Efficient Agent Usage:
- Batch related operations in single agent calls
- Use parallel execution for independent tasks
- Cache results when appropriate
- Minimize context passing between agents
User Experience:
- Provide progress feedback for long-running commands
- Use clear, consistent output formatting
- Support interactive confirmation for critical operations
- Include usage examples and help text
### Security Considerations
Security Best Practices:
- Validate all file paths and inputs
- Implement principle of least privilege
- Never expose sensitive credentials in command output
- Use secure parameter handling for passwords and tokens
Audit and Logging:
- Log all command executions with parameters
- Track success/failure rates
- Monitor for unusual usage patterns
- Provide audit trails for compliance
This comprehensive reference provides all the information needed to create powerful, secure, and user-friendly custom slash commands for Claude Code.
```
### reference/claude-code-hooks-official.md
```markdown
# Claude Code Hooks - Official Documentation Reference
Source: https://code.claude.com/docs/en/hooks
## Key Concepts
### What are Claude Code Hooks?
Hooks are powerful automation tools that extend Claude Code functionality by executing commands or prompts in response to specific events. They provide deterministic control over Claude Code's behavior through event-driven automation.
Security Warning: Hooks execute arbitrary shell commands with system credentials. Use with extreme caution.
### Hook System Architecture
Event Flow:
```
User Action → Event Trigger → Hook Execution → Result Processing
```
Hook Types:
- Command Hooks: Execute shell commands
- Prompt Hooks: Generate and execute prompts
- Validation Hooks: Validate inputs and outputs
- Notification Hooks: Send notifications or logs
## Core Hook Events
### Tool-Related Events
PreToolUse: Before tool execution
- Can block tool execution
- Perfect for validation and security checks
- Receives tool name and parameters
PostToolUse: After successful tool use
- Cannot block (post-execution)
- Ideal for logging and cleanup
- Receives execution results
PermissionRequest: When permission dialogs appear
- Can auto-approve or deny
- Useful for automation workflows
- Receives permission details
### Session-Related Events
SessionStart: When new session begins
- Initialize session state
- Set up environment variables
- Configure session-specific settings
SessionEnd: When session terminates
- Cleanup temporary files
- Save session state
- Generate session reports
SubagentStop: When sub-agent tasks complete
- Process sub-agent results
- Trigger follow-up actions
- Log completion status
Stop: When main agent finishes
- Final cleanup operations
- Generate completion reports
- Prepare for next session
### User Interaction Events
UserPromptSubmit: When user submits prompts
- Validate user input
- Modify prompts programmatically
- Add contextual information
## Hook Configuration Structure
### Basic Configuration
Configure hooks in `settings.json`:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "echo 'Executing bash command:' >> ~/.claude/hooks.log"
}
]
}
]
}
}
```
### Advanced Configuration
Multiple Event Handlers:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "validate-bash-command \"$COMMAND\"",
"blocking": true
},
{
"type": "prompt",
"prompt": "Review bash command for security: $COMMAND"
}
]
},
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "backup-file \"$TARGET_PATH\""
}
]
}
]
}
}
```
### Complex Hook Patterns
Conditional Execution:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "if [[ \"$COMMAND\" == *\"rm -rf\"* ]]; then exit 1; fi",
"blocking": true
}
]
}
]
}
}
```
## Hook Types and Usage
### Command Hooks
Shell Command Execution:
```json
{
"type": "command",
"command": "echo \"Tool: $TOOL_NAME, Args: $ARGUMENTS\" >> ~/claude-hooks.log",
"env": {
"HOOK_LOG_LEVEL": "debug"
}
}
```
Available Variables:
- `$TOOL_NAME`: Name of the tool being executed
- `$ARGUMENTS`: Tool arguments as JSON string
- `$SESSION_ID`: Current session identifier
- `$USER_INPUT`: User's original input
### Prompt Hooks
Prompt Generation and Execution:
```json
{
"type": "prompt",
"prompt": "Review this command for security risks: $COMMAND\n\nProvide a risk assessment and recommendations.",
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 500
}
```
Prompt Variables:
- All command hook variables available
- `$HOOK_CONTEXT`: Current hook execution context
- `$PREVIOUS_RESULTS`: Results from previous hooks
### Validation Hooks
Input/Output Validation:
```json
{
"type": "validation",
"pattern": "^[a-zA-Z0-9_\\-\\.]+$",
"message": "File name contains invalid characters",
"blocking": true
}
```
## Security Considerations
### Security Best Practices
Principle of Least Privilege:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "allowed_commands=(npm python git make)",
"command": "if [[ ! \" ${allowed_commands[@]} \" =~ \" ${COMMAND%% *} \" ]]; then exit 1; fi",
"blocking": true
}
]
}
]
}
}
```
Input Sanitization:
```json
{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "echo \"$USER_INPUT\" | sanitize-input",
"blocking": true
}
]
}
]
}
}
```
### Dangerous Pattern Detection
Prevent Dangerous Commands:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "dangerous_patterns=(\"rm -rf\" \"sudo\" \"chmod 777\" \"dd\" \"mkfs\")",
"command": "for pattern in \"${dangerous_patterns[@]}\"; do if [[ \"$COMMAND\" == *\"$pattern\"* ]]; then echo \"Dangerous command detected: $pattern\" >&2; exit 1; fi; done",
"blocking": true
}
]
}
]
}
}
```
## Hook Management
### Configuration Management
Using /hooks Command:
```bash
# Open hooks configuration editor
/hooks
# View current hooks configuration
/hooks --list
# Test hook functionality
/hooks --test
```
Settings File Locations:
- Global: `~/.claude/settings.json` (user-wide hooks)
- Project: `.claude/settings.json` (project-specific hooks)
- Local: `.claude/settings.local.json` (local overrides)
### Hook Lifecycle Management
Installation:
```bash
# Add hook to configuration
claude config set hooks.PreToolUse[0].matcher "Bash"
claude config set hooks.PreToolUse[0].hooks[0].type "command"
claude config set hooks.PreToolUse[0].hooks[0].command "echo 'Bash executed' >> hooks.log"
# Validate configuration
claude config validate
```
Testing and Debugging:
```bash
# Test individual hook
claude hooks test --event PreToolUse --tool Bash
# Debug hook execution
claude hooks debug --verbose
# View hook logs
claude hooks logs
```
## Common Hook Patterns
### Pre-Commit Validation
Code Quality Checks:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "if [[ \"$COMMAND\" == \"git commit\"* ]]; then npm run lint && npm test; fi",
"blocking": true
}
]
}
]
}
}
```
### Auto-Backup System
File Modification Backup:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "cp \"$TARGET_PATH\" \"$TARGET_PATH.backup.$(date +%s)\""
}
]
},
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "cp \"$TARGET_PATH\" \"$TARGET_PATH.backup.$(date +%s)\""
}
]
}
]
}
}
```
### Session Logging
Comprehensive Activity Logging:
```json
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "echo \"$(date '+%Y-%m-%d %H:%M:%S') - Tool: $TOOL_NAME, Duration: $DURATION_MS ms, Success: $SUCCESS\" >> ~/.claude/session-logs/$SESSION_ID.log"
}
]
},
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "echo \"$(date '+%Y-%m-%d %H:%M:%S') - Session: $SESSION_ID, Event: $EVENT_TYPE\" >> ~/.claude/activity.log"
}
]
}
]
}
}
```
## Error Handling and Recovery
### Error Handling Strategies
Graceful Degradation:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "if ! validate-command \"$COMMAND\"; then echo \"Command validation failed, proceeding with caution\"; exit 0; fi",
"blocking": false
}
]
}
]
}
}
```
Fallback Mechanisms:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "primary-command \"$ARGUMENTS\" || fallback-command \"$ARGUMENTS\"",
"fallback": {
"type": "command",
"command": "echo \"Primary hook failed, using fallback\""
}
}
]
}
]
}
}
```
## Performance Optimization
### Hook Performance
Asynchronous Execution:
```json
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "background-process \"$ARGUMENTS\" &",
"async": true
}
]
}
]
}
}
```
Conditional Hook Execution:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"condition": "$COMMAND != 'git status'",
"hooks": [
{
"type": "command",
"command": "complex-validation \"$COMMAND\""
}
]
}
]
}
}
```
## Integration with Other Systems
### External Service Integration
Webhook Integration:
```json
{
"hooks": {
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "curl -X POST https://api.example.com/webhook -d '{\"session_id\": \"$SESSION_ID\", \"events\": \"$EVENT_COUNT\"}'"
}
]
}
]
}
}
```
Database Logging:
```json
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "psql -h localhost -u claude -d hooks -c \"INSERT INTO tool_usage (session_id, tool_name, timestamp) VALUES ('$SESSION_ID', '$TOOL_NAME', NOW())\""
}
]
}
]
}
}
```
## Best Practices
### Development Guidelines
Hook Development Checklist:
- [ ] Test hooks in isolation before deployment
- [ ] Implement proper error handling and logging
- [ ] Use non-blocking hooks for non-critical operations
- [ ] Validate all inputs and sanitize outputs
- [ ] Document hook dependencies and requirements
- [ ] Implement graceful fallbacks for critical operations
- [ ] Monitor hook performance and resource usage
- [ ] Regular security audits and permission reviews
Performance Guidelines:
- Keep hook execution time under 100ms for critical paths
- Use asynchronous execution for non-blocking operations
- Minimize file I/O operations in hot paths
- Cache frequently used data and configuration
- Implement rate limiting for external API calls
Security Guidelines:
- Never expose sensitive credentials in hook commands
- Validate and sanitize all user inputs
- Use principle of least privilege for file system access
- Implement proper access controls for external integrations
- Regular security reviews and penetration testing
This comprehensive reference provides all the information needed to create, configure, and manage Claude Code Hooks effectively and securely.
```
### reference/claude-code-memory-official.md
```markdown
# Claude Code Memory System - Official Documentation Reference
Source: https://code.claude.com/docs/en/memory
## Key Concepts
### What is Claude Code Memory?
Claude Code Memory provides a hierarchical context management system that allows agents to maintain persistent information across sessions, projects, and organizations. It enables consistent behavior, knowledge retention, and context-aware interactions.
### Memory Architecture
Three-Tier Hierarchy:
1. Enterprise Policy: Organization-wide policies and standards
2. Project Memory: Project-specific knowledge and context
3. User Memory: Personal preferences and individual knowledge
Memory Flow:
```
Enterprise Policy → Project Memory → User Memory
(Highest) (Project) (Personal)
↓ ↓ ↓
Overrides Overrides Overrides
```
## Memory Storage and Access
### File-Based Memory System
Memory File Locations:
- Enterprise: `/etc/claude/policies/` (system-wide)
- Project: `./CLAUDE.md` (project-specific)
- User: `~/.claude/CLAUDE.md` (personal preferences)
- Local: `.claude/memory/` (project metadata)
File Types and Purpose:
```
Project Root/
CLAUDE.md # Main project memory (highest priority in project)
.claude/memory/ # Structured project metadata
execution-rules.md # Execution constraints and rules
agents.md # Agent catalog and capabilities
commands.md # Command references and patterns
delegation-patterns.md # Agent delegation strategies
token-optimization.md # Token budget management
.moai/
config/ # Configuration management
config.json # Project settings
cache/ # Memory cache and optimization
```
### Memory Import Syntax
Direct Import Pattern:
```markdown
# In CLAUDE.md files
@path/to/import.md # Import external memory file
@.claude/memory/agents.md # Import agent reference
@.claude/memory/commands.md # Import command reference
@memory/delegation-patterns.md # Relative import from memory directory
```
Conditional Import:
```markdown
# Import based on environment or configuration
<!-- @if environment == "production" -->
@memory/production-rules.md
<!-- @endif -->
<!-- @if features.security == "enabled" -->
@memory/security-policies.md
<!-- @endif -->
```
## Memory Content Types
### Policy and Rules Memory
Execution Rules (`memory/execution-rules.md`):
```markdown
# Execution Rules and Constraints
## Core Principles
- Agent-first mandate: Always delegate to specialized agents
- Security sandbox: All operations in controlled environment
- Token budget management: Phase-based allocation strategy
## Agent Delegation Rules
- Required tools: Task(), AskUserQuestion(), Skill()
- Forbidden tools: Read(), Write(), Edit(), Bash(), Grep(), Glob()
- Delegation pattern: Sequential → Parallel → Conditional
## Security Constraints
- Forbidden paths: .env*, .vercel/, .github/workflows/secrets
- Forbidden commands: rm -rf, sudo, chmod 777, dd, mkfs
- Input validation: Required before all processing
```
Agent Catalog (`memory/agents.md`):
```markdown
# Agent Reference Catalog
## Planning & Specification
- spec-builder: SPEC generation in EARS format
- plan: Decompose complex tasks step-by-step
## Implementation
- tdd-implementer: Execute TDD cycle (RED-GREEN-REFACTOR)
- backend-expert: Backend architecture and API development
- frontend-expert: Frontend UI component development
## Usage Patterns
- Simple tasks (1-2 files): Sequential execution
- Medium tasks (3-5 files): Mixed sequential/parallel
- Complex tasks (10+ files): Parallel with integration phase
```
### Configuration Memory
Settings Management (`config/config.json`):
```json
{
"user": {
"name": "Developer Name",
"preferences": {
"language": "en",
"timezone": "UTC"
}
},
"project": {
"name": "Project Name",
"type": "web-application",
"documentation_mode": "comprehensive"
},
"constitution": {
"test_coverage_target": 90,
"enforce_tdd": true,
"quality_gates": ["test-first", "readable", "unified", "secured", "trackable"]
},
"git_strategy": {
"mode": "team",
"workflow": "github-flow",
"auto_pr": true
}
}
```
### Process Memory
Command References (`memory/commands.md`):
```markdown
# Command Reference Guide
## Core MoAI Commands
- /moai:0-project: Initialize project structure
- /moai:1-plan: Generate SPEC document
- /moai:2-run: Execute TDD implementation
- /moai:3-sync: Generate documentation
- /moai:9-feedback: Collect improvement feedback
## Command Execution Rules
- After /moai:1-plan: Execute /clear (mandatory)
- Token threshold: Execute /clear at >150K tokens
- Error handling: Use /moai:9-feedback for all issues
```
## Memory Management Strategies
### Memory Initialization
Project Bootstrap:
```bash
# Initialize project memory structure
/moai:0-project
# Creates:
# - .moai/config/config.yaml
# - .moai/memory/ directory
# - CLAUDE.md template
# - Memory structure files
```
Manual Memory Setup:
```bash
# Create memory directory structure
mkdir -p .claude/memory
mkdir -p .moai/config
mkdir -p .moai/cache
# Create initial memory files
touch .claude/memory/agents.md
touch .claude/memory/commands.md
touch .claude/memory/execution-rules.md
touch CLAUDE.md
```
### Memory Synchronization
Import Resolution:
```python
# Memory import resolution order
def resolve_memory_import(import_path, base_path):
"""
Resolve @import paths in memory files
1. Check relative to current file
2. Check in .claude/memory/ directory
3. Check in project root
4. Check in user memory directory
"""
candidates = [
os.path.join(base_path, import_path),
os.path.join(".claude/memory", import_path),
os.path.join(".", import_path),
os.path.expanduser(os.path.join("~/.claude", import_path))
]
for candidate in candidates:
if os.path.exists(candidate):
return candidate
return None
```
Memory Cache Management:
```bash
# Memory cache operations
claude memory cache clear # Clear all memory cache
claude memory cache list # List cached memory files
claude memory cache refresh # Refresh memory from files
claude memory cache status # Show cache statistics
```
### Memory Optimization
Token Efficiency Strategies:
```markdown
# Memory optimization techniques
## Progressive Loading
- Load core memory first (2000 tokens)
- Load detailed memory on-demand (5000 tokens each)
- Cache frequently accessed memory files
## Content Prioritization
- Priority 1: Execution rules and agent catalog (must load)
- Priority 2: Project-specific configurations (conditional)
- Priority 3: Historical data and examples (on-demand)
## Memory Compression
- Use concise bullet points over paragraphs
- Implement cross-references instead of duplication
- Group related information in structured sections
```
## Memory Access Patterns
### Agent Memory Access
Agent Memory Loading:
```python
# Agent memory access pattern
class AgentMemory:
def __init__(self, session_id):
self.session_id = session_id
self.memory_cache = {}
self.load_base_memory()
def load_base_memory(self):
"""Load essential memory for agent operation"""
essential_files = [
".claude/memory/execution-rules.md",
".claude/memory/agents.md",
".moai/config/config.yaml"
]
for file_path in essential_files:
self.memory_cache[file_path] = self.load_memory_file(file_path)
def get_memory(self, key):
"""Get memory value with fallback hierarchy"""
# 1. Check session cache
if key in self.memory_cache:
return self.memory_cache[key]
# 2. Load from file system
memory_value = self.load_memory_file(key)
if memory_value:
self.memory_cache[key] = memory_value
return memory_value
# 3. Return default or None
return None
```
Context-Aware Memory:
```python
# Context-aware memory selection
def select_relevant_memory(context, available_memory):
"""
Select memory files relevant to current context
"""
relevant_memory = []
# Analyze context keywords
context_keywords = extract_keywords(context)
# Match memory files by content relevance
for memory_file in available_memory:
relevance_score = calculate_relevance(memory_file, context_keywords)
if relevance_score > 0.7: # Threshold
relevant_memory.append((memory_file, relevance_score))
# Sort by relevance and return top N
relevant_memory.sort(key=lambda x: x[1], reverse=True)
return [memory[0] for memory in relevant_memory[:5]]
```
## Memory Configuration
### Environment-Specific Memory
Development Environment:
```json
{
"memory": {
"mode": "development",
"cache_size": "100MB",
"auto_refresh": true,
"debug_memory": true,
"memory_files": [
".claude/memory/execution-rules.md",
".claude/memory/agents.md",
".claude/memory/commands.md"
]
}
}
```
Production Environment:
```json
{
"memory": {
"mode": "production",
"cache_size": "50MB",
"auto_refresh": false,
"debug_memory": false,
"memory_files": [
".claude/memory/execution-rules.md",
".claude/memory/production-policies.md"
],
"memory_restrictions": {
"max_file_size": "1MB",
"allowed_extensions": [".md", ".json"],
"forbidden_patterns": ["password", "secret", "key"]
}
}
}
```
### User Preference Memory
Personal Memory Structure (`~/.claude/CLAUDE.md`):
```markdown
# Personal Claude Code Preferences
## User Information
- Name: John Developer
- Role: Senior Software Engineer
- Expertise: Backend Development, DevOps
## Development Preferences
- Language: Python, TypeScript
- Frameworks: FastAPI, React
- Testing: pytest, Jest
- Documentation: Markdown, OpenAPI
## Workflow Preferences
- Git strategy: feature branches
- Code review: required for PRs
- Testing coverage: >90%
- Documentation: comprehensive
## Tool Preferences
- Editor: VS Code
- Shell: bash
- Package manager: npm, pip
- Container: Docker
```
## Memory Maintenance
### Memory Updates and Synchronization
Automatic Memory Updates:
```bash
# Update memory from templates
claude memory update --from-templates
# Synchronize memory across team
claude memory sync --team
# Validate memory structure
claude memory validate --strict
```
Memory Version Control:
```bash
# Track memory changes in Git
git add .claude/memory/ CLAUDE.md
git commit -m "docs: Update project memory and agent catalog"
# Tag memory versions
git tag -a "memory-v1.2.0" -m "Memory version 1.2.0"
```
### Memory Cleanup
Cache Cleanup:
```bash
# Clear expired cache entries
claude memory cache cleanup --older-than 7d
# Remove unused memory files
claude memory cleanup --unused
# Optimize memory file size
claude memory optimize --compress
```
Memory Audit:
```bash
# Audit memory usage
claude memory audit --detailed
# Check for duplicate memory
claude memory audit --duplicates
# Validate memory references
claude memory audit --references
```
## Advanced Memory Features
### Memory Templates
Template-Based Memory Initialization:
```markdown
<!-- memory/project-template.md -->
# Project Memory Template
## Project Structure
- Name: {{project.name}}
- Type: {{project.type}}
- Language: {{project.language}}
## Team Configuration
- Team size: {{team.size}}
- Workflow: {{team.workflow}}
- Review policy: {{team.review_policy}}
## Quality Standards
- Test coverage: {{quality.test_coverage}}%
- Documentation: {{quality.documentation_level}}
- Security: {{quality.security_level}}
```
Template Instantiation:
```bash
# Create memory from template
claude memory init --template web-app --config project.json
# Variables in project.json:
# {
# "project": {"name": "MyApp", "type": "web-app", "language": "TypeScript"},
# "team": {"size": 5, "workflow": "github-flow", "review_policy": "required"},
# "quality": {"test_coverage": 90, "documentation_level": "comprehensive", "security_level": "high"}
# }
```
### Memory Sharing and Distribution
Team Memory Distribution:
```bash
# Export memory for team sharing
claude memory export --team --format archive
# Import shared memory
claude memory import --team --file team-memory.tar.gz
# Merge memory updates
claude memory merge --base current --update team-updates
```
Memory Distribution Channels:
- Git Repository: Version-controlled memory files
- Package Distribution: Memory bundled with tools/libraries
- Network Share: Centralized memory server
- Cloud Storage: Distributed memory storage
## Best Practices
### Memory Organization
Structural Guidelines:
- Keep memory files focused on single topics
- Use consistent naming conventions
- Implement clear hierarchy and relationships
- Maintain cross-references and links
Content Guidelines:
- Write memory content in clear, concise language
- Use structured formats (markdown, JSON, YAML)
- Include examples and use cases
- Provide context and usage instructions
### Performance Optimization
Memory Loading Optimization:
- Load memory files on-demand when possible
- Implement caching for frequently accessed memory
- Use compression for large memory files
- Preload critical memory files
Memory Access Patterns:
- Group related memory access operations
- Minimize memory file loading frequency
- Use memory references instead of duplication
- Implement lazy loading for optional memory
### Security and Privacy
Memory Security:
- Never store sensitive credentials in memory files
- Implement access controls for memory files
- Use encryption for confidential memory content
- Regular security audits of memory content
Privacy Considerations:
- Separate personal and project memory appropriately
- Use anonymization for sensitive data in shared memory
- Implement data retention policies for memory content
- Respect user privacy preferences in memory usage
This comprehensive reference provides all the information needed to effectively implement, manage, and optimize Claude Code Memory systems for projects of any scale and complexity.
```
### reference/claude-code-settings-official.md
```markdown
# Claude Code Settings - Official Documentation Reference
Source: https://code.claude.com/docs/en/settings
## Key Concepts
### What are Claude Code Settings?
Claude Code Settings provide a hierarchical configuration system that controls Claude Code's behavior, tool permissions, model selection, and integration preferences. Settings are managed through JSON configuration files with clear inheritance and override patterns.
### Settings Hierarchy
Configuration Priority (highest to lowest):
1. Enterprise Settings: Organization-wide policies and restrictions
2. User Settings: `~/.claude/settings.json` (personal preferences)
3. Project Settings: `.claude/settings.json` (team-shared)
4. Local Settings: `.claude/settings.local.json` (local overrides)
Inheritance Flow:
```
Enterprise Policy → User Settings → Project Settings → Local Settings
(Applied) (Personal) (Team) (Local)
↓ ↓ ↓ ↓
Overrides Overrides Overrides Overrides
```
## Core Settings Structure
### Complete Configuration Schema
Base Settings Framework:
```json
{
"model": "claude-3-5-sonnet-20241022",
"permissionMode": "default",
"maxFileSize": 10000000,
"maxTokens": 200000,
"temperature": 1.0,
"environment": {},
"hooks": {},
"plugins": {},
"subagents": {},
"mcpServers": {},
"allowedTools": [],
"toolRestrictions": {},
"memory": {},
"logging": {},
"security": {}
}
```
### Essential Configuration Fields
Model Configuration:
```json
{
"model": "claude-3-5-sonnet-20241022",
"maxTokens": 200000,
"temperature": 1.0,
"topP": 1.0,
"topK": 0
}
```
Permission Management:
```json
{
"permissionMode": "default",
"allowedTools": [
"Read",
"Write",
"Edit",
"Bash",
"Grep",
"Glob",
"WebFetch",
"AskUserQuestion"
],
"toolRestrictions": {
"Bash": "prompt",
"Write": "prompt",
"Edit": "prompt"
}
}
```
## Detailed Configuration Sections
### Model Settings
Available Models:
- `claude-3-5-sonnet-20241022`: Balanced performance (default)
- `claude-3-5-haiku-20241022`: Fast and cost-effective
- `claude-3-opus-20240229`: Highest quality, higher cost
Model Configuration Examples:
```json
{
"model": "claude-3-5-sonnet-20241022",
"maxTokens": 200000,
"temperature": 0.7,
"topP": 0.9,
"topK": 40,
"stopSequences": ["---", "##"],
"timeout": 300000
}
```
Model Selection Guidelines:
```json
{
"modelProfiles": {
"development": {
"model": "claude-3-5-haiku-20241022",
"temperature": 0.3,
"maxTokens": 50000
},
"testing": {
"model": "claude-3-5-sonnet-20241022",
"temperature": 0.1,
"maxTokens": 100000
},
"production": {
"model": "claude-3-5-sonnet-20241022",
"temperature": 0.0,
"maxTokens": 200000
}
}
}
```
### Permission System
Permission Modes:
- `default`: Standard permission prompts for sensitive operations
- `acceptEdits`: Automatically accept file edits without prompts
- `dontAsk`: Suppress all permission dialogs
Tool-Specific Permissions:
```json
{
"allowedTools": [
"Read",
"Write",
"Edit",
"Bash",
"Grep",
"Glob",
"WebFetch",
"WebSearch",
"AskUserQuestion",
"TodoWrite",
"Task",
"Skill",
"SlashCommand"
],
"toolRestrictions": {
"Read": {
"allowedPaths": ["./", "~/.claude/"],
"blockedPaths": [".env*", "*.key", "*.pem"]
},
"Bash": {
"allowedCommands": ["git", "npm", "python", "make", "docker"],
"blockedCommands": ["rm -rf", "sudo", "chmod 777", "dd", "mkfs"],
"requireConfirmation": true
},
"Write": {
"allowedExtensions": [".md", ".py", ".js", ".ts", ".json", ".yaml"],
"blockedExtensions": [".exe", ".bat", ".sh", ".key"],
"maxFileSize": 10000000
},
"WebFetch": {
"allowedDomains": ["*.github.com", "*.npmjs.com", "docs.python.org"],
"blockedDomains": ["*.malicious-site.com"],
"requireConfirmation": false
}
}
}
```
### Environment Variables
Environment Configuration:
```json
{
"environment": {
"NODE_ENV": "development",
"PYTHONPATH": "./src",
"API_KEY": "$ENV_VAR", // Environment variable reference
"PROJECT_ROOT": ".", // Static value
"DEBUG": "true",
"LOG_LEVEL": "$DEFAULT_LOG_LEVEL"
}
}
```
Variable Resolution:
```json
{
"environmentResolution": {
"precedence": [
"runtime_environment",
"settings_json",
"default_values"
],
"validation": {
"required": ["PROJECT_ROOT"],
"optional": ["DEBUG", "LOG_LEVEL"],
"typeChecking": true
}
}
}
```
### MCP Server Configuration
MCP Server Setup:
```json
{
"mcpServers": {
"context7": {
"command": "npx",
"args": ["@upstash/context7-mcp"],
"env": {
"CONTEXT7_API_KEY": "$CONTEXT7_KEY"
},
"timeout": 30000
},
"sequential-thinking": {
"command": "npx",
"args": ["@modelcontextprotocol/server-sequential-thinking"],
"env": {},
"timeout": 60000
},
"figma": {
"command": "npx",
"args": ["@figma/mcp-server"],
"env": {
"FIGMA_API_KEY": "$FIGMA_KEY"
}
}
}
}
```
MCP Permission Management:
```json
{
"mcpPermissions": {
"context7": {
"allowed": ["resolve-library-id", "get-library-docs"],
"rateLimit": {
"requestsPerMinute": 60,
"burstSize": 10
}
},
"sequential-thinking": {
"allowed": ["*"], // All permissions
"maxContextSize": 100000
}
}
}
```
### Hooks Configuration
Hooks Setup:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "echo 'Bash command: $COMMAND' >> ~/.claude/hooks.log"
}
]
}
],
"PostToolUse": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "echo 'Tool executed: $TOOL_NAME' >> ~/.claude/activity.log"
}
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{
"type": "validation",
"pattern": "^[\\w\\s\\.\\?!]+$",
"message": "Invalid characters in prompt"
}
]
}
]
}
}
```
### Sub-agent Configuration
Sub-agent Settings:
```json
{
"subagents": {
"defaultModel": "claude-3-5-sonnet-20241022",
"defaultPermissionMode": "default",
"maxConcurrentTasks": 5,
"taskTimeout": 300000,
"allowedSubagents": [
"spec-builder",
"tdd-implementer",
"security-expert",
"backend-expert",
"frontend-expert"
],
"customSubagents": {
"custom-analyzer": {
"description": "Custom code analysis agent",
"tools": ["Read", "Grep", "Bash"],
"model": "claude-3-5-sonnet-20241022"
}
}
}
}
```
### Plugin System
Plugin Configuration:
```json
{
"plugins": {
"enabled": true,
"pluginPaths": ["./plugins", "~/.claude/plugins"],
"loadedPlugins": [
"git-integration",
"docker-helper",
"database-tools"
],
"pluginSettings": {
"git-integration": {
"autoCommit": false,
"branchStrategy": "feature-branch"
},
"docker-helper": {
"defaultRegistry": "docker.io",
"buildTimeout": 300000
}
}
}
}
```
## File Locations and Management
### Settings File Paths
Standard Locations:
```bash
# Enterprise settings (system-wide)
/etc/claude/settings.json
# User settings (personal preferences)
~/.claude/settings.json
# Project settings (team-shared)
./.claude/settings.json
# Local overrides (development)
./.claude/settings.local.json
# Environment-specific overrides
./.claude/settings.${ENVIRONMENT}.json
```
### Settings Management Commands
Configuration Commands:
```bash
# View current settings
claude settings show
claude settings show --model
claude settings show --permissions
# Set individual settings
claude config set model "claude-3-5-sonnet-20241022"
claude config set maxTokens 200000
claude config set permissionMode "default"
# Edit settings file
claude config edit
claude config edit --local
claude config edit --user
# Reset settings
claude config reset
claude config reset --local
claude config reset --user
# Validate settings
claude config validate
claude config validate --strict
```
Environment-Specific Settings:
```bash
# Set environment-specific settings
claude config set --environment development model "claude-3-5-haiku-20241022"
claude config set --environment production maxTokens 200000
# Switch between environments
claude config use-environment development
claude config use-environment production
# List available environments
claude config list-environments
```
## Advanced Configuration
### Context Management
Context Window Settings:
```json
{
"context": {
"maxTokens": 200000,
"compressionThreshold": 150000,
"compressionStrategy": "importance-based",
"memoryIntegration": true,
"cacheStrategy": {
"enabled": true,
"maxSize": "100MB",
"ttl": 3600
}
}
}
```
### Logging and Debugging
Logging Configuration:
```json
{
"logging": {
"level": "info",
"file": "~/.claude/logs/claude.log",
"maxFileSize": "10MB",
"maxFiles": 5,
"format": "json",
"include": [
"tool_usage",
"agent_delegation",
"errors",
"performance"
],
"exclude": [
"sensitive_data"
]
}
}
```
Debug Settings:
```json
{
"debug": {
"enabled": false,
"verboseOutput": false,
"timingInfo": false,
"tokenUsage": true,
"stackTraces": false,
"apiCalls": false
}
}
```
### Performance Optimization
Performance Settings:
```json
{
"performance": {
"parallelExecution": true,
"maxConcurrency": 5,
"caching": {
"enabled": true,
"strategy": "lru",
"maxSize": "500MB"
},
"optimization": {
"contextCompression": true,
"responseStreaming": false,
"batchProcessing": true
}
}
}
```
## Integration Settings
### Git Integration
Git Configuration:
```json
{
"git": {
"autoCommit": false,
"autoPush": false,
"branchStrategy": "feature-branch",
"commitTemplate": {
"prefix": "feat:",
"includeScope": true,
"includeBody": true
},
"hooks": {
"preCommit": "lint && test",
"prePush": "security-scan"
}
}
}
```
### CI/CD Integration
CI/CD Settings:
```json
{
"cicd": {
"platform": "github-actions",
"configPath": ".github/workflows/",
"autoGenerate": false,
"pipelines": {
"test": {
"trigger": ["push", "pull_request"],
"steps": ["lint", "test", "security-scan"]
},
"deploy": {
"trigger": ["release"],
"steps": ["build", "deploy"]
}
}
}
}
```
## Security Configuration
### Security Settings
Security Configuration:
```json
{
"security": {
"level": "standard",
"encryption": {
"enabled": true,
"algorithm": "AES-256-GCM"
},
"accessControl": {
"authentication": "required",
"authorization": "role-based"
},
"audit": {
"enabled": true,
"logLevel": "detailed",
"retention": "90d"
}
}
}
```
### Privacy Settings
Privacy Configuration:
```json
{
"privacy": {
"dataCollection": "minimal",
"analytics": false,
"crashReporting": true,
"usageStatistics": false,
"dataRetention": {
"logs": "30d",
"cache": "7d",
"temp": "1d"
}
}
}
```
## Best Practices
### Configuration Management
Development Practices:
- Use version control for project settings
- Keep local overrides in `.gitignore`
- Document all custom settings
- Validate settings before deployment
Security Practices:
- Never commit sensitive credentials
- Use environment variables for secrets
- Implement principle of least privilege
- Regular security audits
Performance Practices:
- Optimize context window usage
- Enable caching where appropriate
- Monitor token usage
- Use appropriate models for tasks
### Organization Standards
Team Configuration:
```json
{
"team": {
"standards": {
"model": "claude-3-5-sonnet-20241022",
"testCoverage": 90,
"codeStyle": "prettier",
"documentation": "required"
},
"workflow": {
"branching": "gitflow",
"reviews": "required",
"ciCd": "automated"
}
}
}
```
Enterprise Policies:
```json
{
"enterprise": {
"policies": {
"allowedModels": ["claude-3-5-sonnet-20241022"],
"maxTokens": 100000,
"restrictedTools": ["Bash", "WebFetch"],
"auditRequired": true
},
"compliance": {
"standards": ["SOC2", "ISO27001"],
"dataResidency": "us-east-1",
"retentionPolicy": "7y"
}
}
}
```
This comprehensive reference provides all the information needed to configure Claude Code effectively for any use case, from personal development to enterprise deployment.
```
### reference/claude-code-iam-official.md
```markdown
# Claude Code IAM & Permissions - Official Documentation Reference
Source: https://code.claude.com/docs/en/iam
## Key Concepts
### What is Claude Code IAM?
Identity and Access Management (IAM) in Claude Code provides a comprehensive permission system that controls access to tools, files, and external services. IAM implements tiered approval levels, role-based access control, and security boundaries to ensure safe and compliant operations.
### IAM Architecture
Tiered Permission System:
```
Level 1: Read-only Access (No Approval)
Read, Grep, Glob
Information gathering tools
Level 2: Bash Commands (User Approval Required)
Bash, WebFetch, WebSearch
System operations and external access
Level 3: File Modification (User Approval Required)
Write, Edit, MultiEdit
File system modifications
Level 4: Administrative (Enterprise Approval)
Settings management
User administration
System configuration
```
## Tool-Specific Permission Rules
### Permission Rule Format
Basic Permission Structure:
```json
{
"allowedTools": [
"Read", // Read-only access (no approval)
"Bash", // Commands with approval
"Write", // File modification with approval
"WebFetch(domain:*.example.com)" // Domain-specific web access
]
}
```
### Permission Levels and Tools
Level 1: Read-Only Tools (No Approval Required)
```json
{
"readLevel": {
"tools": ["Read", "Grep", "Glob"],
"approval": "none",
"description": "Information gathering and file exploration",
"useCases": [
"Code analysis and review",
"File system exploration",
"Pattern searching and analysis",
"Documentation reading"
]
}
}
```
Level 2: System Operations (User Approval Required)
```json
{
"systemLevel": {
"tools": ["Bash", "WebFetch", "WebSearch"],
"approval": "user",
"description": "System operations and external resource access",
"useCases": [
"Build and deployment operations",
"External API integration",
"System configuration changes",
"Network operations"
]
}
}
```
Level 3: File Modifications (User Approval Required)
```json
{
"modificationLevel": {
"tools": ["Write", "Edit", "MultiEdit", "NotebookEdit"],
"approval": "user",
"description": "File system modifications and content creation",
"useCases": [
"Code implementation and changes",
"Documentation updates",
"Configuration file modifications",
"Content generation"
]
}
}
```
Level 4: Administrative (Enterprise Approval Required)
```json
{
"adminLevel": {
"tools": ["Settings", "UserManagement", "SystemConfig"],
"approval": "enterprise",
"description": "System administration and user management",
"useCases": [
"System configuration changes",
"User permission management",
"Enterprise policy updates",
"Security configuration"
]
}
}
```
## Role-Based Access Control (RBAC)
### Predefined Roles
Developer Role:
```json
{
"developer": {
"allowedTools": [
"Read", "Grep", "Glob",
"Bash", "Write", "Edit",
"WebFetch", "WebSearch",
"AskUserQuestion", "Task", "Skill"
],
"toolRestrictions": {
"Bash": {
"allowedCommands": ["git", "npm", "python", "make", "docker"],
"blockedCommands": ["sudo", "chmod 777", "rm -rf /"],
"requireConfirmation": true
},
"WebFetch": {
"allowedDomains": ["*.github.com", "*.npmjs.com", "docs.python.org"],
"blockedDomains": ["*.malicious-site.com"],
"maxRequestsPerMinute": 60
},
"Write": {
"allowedPaths": ["./src/", "./tests/", "./docs/"],
"blockedPaths": ["./.env*", "./config/secrets"],
"maxFileSize": 10000000
}
},
"permissions": {
"canCreateFiles": true,
"canModifyFiles": true,
"canExecuteCommands": true,
"canAccessExternal": true
}
}
}
```
Security Reviewer Role:
```json
{
"securityReviewer": {
"allowedTools": [
"Read", "Grep", "Glob",
"Bash", "WebFetch",
"AskUserQuestion", "Task"
],
"toolRestrictions": {
"Read": {
"allowedPaths": ["./"],
"blockedPatterns": ["*.key", "*.pem", ".env*"]
},
"Bash": {
"allowedCommands": ["git", "grep", "find", "openssl"],
"requireConfirmation": true
}
},
"specialPermissions": {
"canAccessSecurityLogs": true,
"canRunSecurityScans": true,
"canReviewPermissions": true,
"cannotModifyProduction": true
}
}
}
```
DevOps Engineer Role:
```json
{
"devopsEngineer": {
"allowedTools": [
"Read", "Grep", "Glob",
"Bash", "Write", "Edit",
"WebFetch", "WebSearch",
"Task", "Skill"
],
"toolRestrictions": {
"Bash": {
"allowedCommands": [
"git", "docker", "kubectl", "helm", "terraform",
"npm", "pip", "make", "curl", "wget"
],
"blockedCommands": ["sudo", "chmod 777"],
"requireConfirmation": false
},
"WebFetch": {
"allowedDomains": ["*"],
"requireConfirmation": false
}
},
"permissions": {
"canDeployToStaging": true,
"canManageInfrastructure": true,
"canAccessProduction": false,
"canManageCI/CD": true
}
}
}
```
### Custom Role Definition
Role Template:
```json
{
"customRole": {
"name": "CustomRoleName",
"description": "Role description and purpose",
"allowedTools": ["Read", "Bash", "Write"],
"toolRestrictions": {
"Read": {
"allowedPaths": ["./"],
"blockedPaths": [".env*", "secrets/"]
},
"Bash": {
"allowedCommands": ["git", "npm"],
"blockedCommands": ["rm", "sudo"],
"requireConfirmation": true
}
},
"permissions": {
"customPermission": "value"
},
"inherits": ["developer"]
}
}
```
## Enterprise Policy Overrides
### Enterprise IAM Structure
Enterprise Policy Framework:
```json
{
"enterprise": {
"policies": {
"tools": {
"Bash": "never",
"WebFetch": ["domain:*.company.com", "domain:*.partner.com"],
"Write": ["path:./workspace/", "path:./temp/"]
},
"mcpServers": {
"allowed": ["context7", "figma", "company-internal-mcp"],
"blocked": ["custom-unverified-mcp", "external-scanner"]
},
"roles": {
"default": "readonly-developer",
"overrides": {
"senior-developer": "developer",
"devops": "devops-engineer"
}
},
"compliance": {
"auditRequired": true,
"dataRetention": "7y",
"encryptionRequired": true,
"mfaRequired": true
}
}
}
}
```
Policy Enforcement Mechanisms:
```json
{
"policyEnforcement": {
"validation": {
"strict": true,
"failOnViolation": true,
"auditFrequency": "daily"
},
"overrides": {
"allowUserOverrides": false,
"requireManagerApproval": true,
"emergencyOverrides": {
"enabled": true,
"duration": "24h",
"approvalRequired": ["cto", "security-team"]
}
},
"monitoring": {
"realTimeAlerts": true,
"anomalyDetection": true,
"complianceReporting": true
}
}
}
```
## MCP Server Permissions
### MCP Access Control
MCP Server Configuration:
```json
{
"allowedMcpServers": [
"context7",
"figma-dev-mode-mcp-server",
"playwright",
"company-internal-mcp"
],
"blockedMcpServers": [
"custom-unverified-mcp",
"experimental-ai-mcp",
"external-scanner-mcp"
],
"mcpServerPermissions": {
"context7": {
"allowed": ["resolve-library-id", "get-library-docs"],
"rateLimit": {
"requestsPerMinute": 60,
"burstSize": 10
},
"dataUsage": {
"allowedDataTypes": ["documentation", "api-reference"],
"blockedDataTypes": ["credentials", "private-keys"]
}
},
"figma-dev-mode-mcp-server": {
"allowed": ["get-design-context", "get-variable-defs", "get-screenshot"],
"accessControl": {
"allowedProjects": ["company-design-system"],
"blockedProjects": ["competitor-designs"]
}
}
}
}
```
MCP Security Validation:
```json
{
"mcpSecurity": {
"validationRules": {
"requireSignature": true,
"requireVersionCheck": true,
"requirePermissionsReview": true
},
"sandbox": {
"enabled": true,
"isolatedNetwork": true,
"fileSystemAccess": "restricted"
},
"monitoring": {
"logAllCalls": true,
"auditSensitiveOperations": true,
"rateLimitViolations": "block"
}
}
}
```
## Domain-Specific Permissions
### Web Access Control
Domain-Based Web Permissions:
```json
{
"webPermissions": {
"allowedDomains": [
"*.github.com",
"*.npmjs.com",
"docs.python.org",
"*.company.com",
"*.partner-site.com"
],
"blockedDomains": [
"*.malicious-site.com",
"*.competitor.com",
"*.social-media.com"
],
"domainRestrictions": {
"github.com": {
"allowedPaths": ["/api/v3/", "/raw/"],
"blockedPaths": ["/settings/", "/admin/"]
},
"npmjs.com": {
"allowedPaths": ["/package/"],
"blockedPaths": ["/settings/", "/account/"]
}
}
}
}
```
### File System Access Control
Path-Based Permissions:
```json
{
"fileSystemPermissions": {
"allowedPaths": [
"./src/",
"./tests/",
"./docs/",
"./.claude/",
"./.moai/"
],
"blockedPaths": [
"./.env*",
"./secrets/",
"./.ssh/",
"./config/private/",
"./node_modules/.cache/"
],
"pathRestrictions": {
"./src/": {
"allowedExtensions": [".py", ".js", ".ts", ".md", ".json"],
"blockedExtensions": [".exe", ".key", ".pem"]
},
"./config/": {
"readOnly": true,
"requireApproval": true
}
}
}
}
```
## Permission Validation and Enforcement
### Pre-Execution Validation
Permission Check Workflow:
```python
def validate_tool_usage(tool_name, parameters, user_role):
"""
Validate tool usage against IAM policies
"""
# 1. Check if tool is allowed for user role
if tool_name not in get_allowed_tools(user_role):
return {"allowed": False, "reason": "Tool not permitted for role"}
# 2. Check tool-specific restrictions
restrictions = get_tool_restrictions(tool_name, user_role)
if not validate_tool_restrictions(tool_name, parameters, restrictions):
return {"allowed": False, "reason": "Tool restriction violation"}
# 3. Check enterprise policy overrides
if violates_enterprise_policy(tool_name, parameters):
return {"allowed": False, "reason": "Enterprise policy violation"}
# 4. Determine approval requirement
approval_level = get_approval_level(tool_name, user_role)
return {
"allowed": True,
"approvalRequired": approval_level != "none",
"approvalLevel": approval_level
}
```
### Real-Time Permission Monitoring
Permission Monitoring System:
```json
{
"monitoring": {
"realTimeValidation": {
"enabled": true,
"checkFrequency": "per-execution",
"blockOnViolation": true
},
"auditLogging": {
"enabled": true,
"logLevel": "detailed",
"retention": "90d",
"format": "structured-json"
},
"alerts": {
"permissionViolations": {
"enabled": true,
"channels": ["email", "slack"],
"escalation": ["security-team", "management"]
},
"suspiciousActivity": {
"enabled": true,
"threshold": "5 violations in 1h",
"action": "temporary-ban"
}
}
}
}
```
## Security Compliance
### Compliance Framework Integration
SOC 2 Compliance:
```json
{
"compliance": {
"SOC2": {
"security": {
"accessControl": true,
"encryptionRequired": true,
"auditLogging": true,
"incidentResponse": true
},
"availability": {
"backupRequired": true,
"disasterRecovery": true,
"uptimeMonitoring": true
},
"processing": {
"dataIntegrity": true,
"accuracyValidation": true,
"errorHandling": true
},
"confidentiality": {
"dataEncryption": true,
"accessControls": true,
"dataMinimization": true
}
}
}
}
```
ISO 27001 Compliance:
```json
{
"compliance": {
"ISO27001": {
"accessControl": {
"policyDocumented": true,
"accessReview": "quarterly",
"leastPrivilege": true,
"segregationOfDuties": true
},
"informationSecurity": {
"riskAssessment": "annual",
"securityTraining": "mandatory",
"incidentManagement": true,
"businessContinuity": true
}
}
}
}
```
## Best Practices
### Permission Management
Principle of Least Privilege:
```json
{
"leastPrivilege": {
"grantOnlyNecessary": true,
"regularReview": "quarterly",
"automaticRevocation": {
"enabled": true,
"inactivityPeriod": "90d"
},
"roleBasedAssignment": true
}
}
```
Security Best Practices:
- Implement multi-factor authentication for administrative access
- Regular security audits and permission reviews
- Encrypted storage of sensitive configuration data
- Real-time monitoring and alerting for security events
- Incident response procedures for security violations
Compliance Best Practices:
- Document all permission policies and procedures
- Maintain comprehensive audit logs
- Regular compliance assessments and reporting
- Employee security training and awareness programs
- Automated compliance checking and validation
### Implementation Guidelines
Development Environment:
```json
{
"development": {
"permissionMode": "default",
"allowedTools": ["Read", "Write", "Edit", "Bash"],
"toolRestrictions": {
"Bash": {"allowedCommands": ["git", "npm", "python"]},
"Write": {"allowedPaths": ["./src/", "./tests/"]}
}
}
}
```
Production Environment:
```json
{
"production": {
"permissionMode": "restricted",
"allowedTools": ["Read", "Grep"],
"toolRestrictions": {
"Read": {"allowedPaths": ["./logs/", "./config/readonly/"]}
},
"monitoring": {
"realTimeAlerts": true,
"auditAllAccess": true
}
}
}
```
This comprehensive IAM reference provides all the information needed to implement secure, compliant, and effective access control for Claude Code deployments at any scale.
```
### reference/complete-configuration-guide.md
```markdown
# Claude Code Complete Configuration Guide
## IAM & Permission Rules
### Tool-Specific Permission Rules
Tiered Permission System:
1. Read-only: No approval required
2. Bash Commands: User approval required
3. File Modification: User approval required
Permission Rule Format:
```json
{
"allowedTools": [
"Read", // Read-only access
"Bash", // Commands with approval
"Write", // File modification with approval
"WebFetch(domain:*.example.com)" // Domain-specific web access
]
}
```
### Enterprise Policy Overrides
Enterprise IAM Structure:
```json
{
"enterprise": {
"policies": {
"tools": {
"Bash": "never", // Enterprise-wide restriction
"WebFetch": ["domain:*.company.com"] // Approved domains only
},
"mcpServers": {
"allowed": ["context7", "figma"], // Approved MCP servers
"blocked": ["custom-mcp"] // Blocked servers
}
}
}
}
```
### Permission Configuration Examples
Development Environment:
```json
{
"allowedTools": [
"Read",
"Write",
"Edit",
"Bash",
"WebFetch",
"Grep",
"Glob"
],
"toolRestrictions": {
"Bash": {
"allowedCommands": ["npm", "python", "git", "make"],
"blockedCommands": ["rm -rf", "sudo", "chmod 777"]
},
"WebFetch": {
"allowedDomains": ["*.github.com", "*.npmjs.com", "docs.python.org"],
"blockedDomains": ["*.malicious-site.com"]
}
}
}
```
Production Environment:
```json
{
"allowedTools": [
"Read",
"Grep",
"Glob"
],
"toolRestrictions": {
"Write": "never",
"Edit": "never",
"Bash": "never"
}
}
```
### MCP Permission Management
MCP servers do not support wildcards - specific server names required:
```json
{
"allowedMcpServers": [
"context7",
"figma-dev-mode-mcp-server",
"playwright"
],
"blockedMcpServers": [
"custom-unverified-mcp"
]
}
```
## Claude Code Settings
### Settings Hierarchy
Configuration Priority (highest to lowest):
1. Enterprise Settings: Organization-wide policies
2. User Settings: `~/.claude/settings.json` (personal)
3. Project Settings: `.claude/settings.json` (shared)
4. Local Settings: `.claude/settings.local.json` (local overrides)
### Core Settings Structure
```json
{
"model": "claude-3-5-sonnet-20241022",
"permissionMode": "default",
"maxFileSize": 10000000,
"maxTokens": 200000,
"environment": {},
"hooks": {},
"plugins": {},
"subagents": {},
"mcpServers": {}
}
```
### Key Configuration Options
Model Settings:
```json
{
"model": "claude-3-5-sonnet-20241022", // or haiku, opus
"maxTokens": 200000, // Context window limit
"temperature": 1.0 // Creativity level (0.0-1.0)
}
```
Permission Management:
```json
{
"permissionMode": "default", // default, acceptEdits, dontAsk
"tools": {
"Bash": "prompt", // always, prompt, never
"Write": "prompt",
"Edit": "prompt"
}
}
```
Environment Variables:
```json
{
"environment": {
"NODE_ENV": "development",
"API_KEY": "$ENV_VAR", // Environment variable reference
"PROJECT_ROOT": "." // Static value
}
}
```
MCP Server Configuration:
```json
{
"mcpServers": {
"context7": {
"command": "npx",
"args": ["@upstash/context7-mcp"],
"env": {"CONTEXT7_API_KEY": "$CONTEXT7_KEY"}
}
}
}
```
```