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

388
.ai/docs/ai-context.md Normal file
View File

@@ -0,0 +1,388 @@
# AI Context Management Guide
Master the art of feeding AI the right information at the right time for optimal results.
## 📚 Overview
The AI context system helps you:
- Provide consistent reference materials to your AI assistant
- Generate comprehensive project documentation
- Manage external library documentation
- Organize project-specific context
- Maintain philosophy alignment
## 🗂️ Directory Structure
```
ai_context/ # Persistent reference materials
├── README.md # Directory documentation
├── IMPLEMENTATION_PHILOSOPHY.md # Core development philosophy
├── MODULAR_DESIGN_PHILOSOPHY.md # Architecture principles
├── generated/ # Auto-generated project docs
│ └── [project-rollups] # Created by build_ai_context_files.py
└── git_collector/ # External library docs
└── [fetched-docs] # Created by build_git_collector_files.py
ai_working/ # Active AI workspace
├── README.md # Usage instructions
├── [feature-folders]/ # Feature-specific context
└── tmp/ # Temporary files (git-ignored)
└── [scratch-files] # Experiments, debug logs, etc.
```
## 🎯 Quick Start
### 1. Generate Project Context
```bash
# Generate comprehensive project documentation
make ai-context-files
# Or run directly
python tools/build_ai_context_files.py
```
This creates rollup files in `ai_context/generated/` containing:
- All source code organized by type
- Configuration files
- Documentation
- Test files
### 2. Add External Documentation
```bash
# Fetch library documentation
python tools/build_git_collector_files.py
# Configure libraries in git_collector_config.json
{
"libraries": [
{
"name": "react",
"repo": "facebook/react",
"docs_path": "docs/"
}
]
}
```
### 3. Load Philosophy
```
# In your AI assistant
/prime
# Or manually reference
Please read @ai_context/IMPLEMENTATION_PHILOSOPHY.md and follow these principles
```
## 🧠 Philosophy Documents
### IMPLEMENTATION_PHILOSOPHY.md
Core principles that guide all development:
- **Simplicity First**: Clean, maintainable code
- **Human-Centric**: AI amplifies, doesn't replace
- **Pragmatic Choices**: Real-world solutions
- **Trust in Emergence**: Let good architecture emerge
### MODULAR_DESIGN_PHILOSOPHY.md
Architecture principles for scalable systems:
- **Bricks & Studs**: Self-contained modules with clear interfaces
- **Contract-First**: Define interfaces before implementation
- **Regenerate, Don't Patch**: Rewrite modules when needed
- **AI-Ready**: Design for future automation
### Using Philosophy in Prompts
```
/ultrathink-task Build a user authentication system following our philosophy:
@ai_context/IMPLEMENTATION_PHILOSOPHY.md
@ai_context/MODULAR_DESIGN_PHILOSOPHY.md
Focus especially on simplicity and contract-first design.
```
## 📋 Context Generation Tools
### build_ai_context_files.py
Generates comprehensive project documentation:
```python
# Default configuration
FILE_GROUPS = {
"Source Code": {
"patterns": ["**/*.py", "**/*.js", "**/*.ts"],
"exclude": ["**/test_*", "**/*.test.*"]
},
"Configuration": {
"patterns": ["**/*.json", "**/*.yaml", "**/*.toml"],
"exclude": ["**/node_modules/**"]
}
}
```
**Features**:
- Groups files by type
- Respects .gitignore
- Adds helpful headers
- Creates single-file rollups
**Customization**:
```python
# In build_ai_context_files.py
FILE_GROUPS["My Custom Group"] = {
"patterns": ["**/*.custom"],
"exclude": ["**/temp/**"]
}
```
### collect_files.py
Core utility for pattern-based file collection:
```bash
# Collect all Python files
python tools/collect_files.py "**/*.py" > python_files.md
# Collect with exclusions
python tools/collect_files.py "**/*.ts" --exclude "**/node_modules/**" > typescript.md
```
### build_git_collector_files.py
Fetches external documentation:
```bash
# Configure libraries
cat > git_collector_config.json << EOF
{
"libraries": [
{
"name": "fastapi",
"repo": "tiangolo/fastapi",
"docs_path": "docs/",
"include": ["tutorial/", "advanced/"]
}
]
}
EOF
# Fetch documentation
python tools/build_git_collector_files.py
```
## 🎨 Best Practices
### 1. Layer Your Context
```
Base Layer (Philosophy)
Project Layer (Generated docs)
Feature Layer (Specific requirements)
Task Layer (Current focus)
```
### 2. Reference Strategically
```
# Good: Specific, relevant context
@ai_context/generated/api_endpoints.md
@ai_working/auth-feature/requirements.md
# Avoid: Everything at once
@ai_context/**/*
```
### 3. Keep Context Fresh
```bash
# Update before major work
make ai-context-files
# Add to git hooks
echo "make ai-context-files" >> .git/hooks/pre-commit
```
### 4. Use Working Spaces
```
ai_working/
├── feature-x/
│ ├── requirements.md # What to build
│ ├── decisions.md # Architecture choices
│ ├── progress.md # Current status
│ └── blockers.md # Issues to resolve
└── tmp/
└── debug-session-1/ # Temporary investigation
```
## 🔧 Advanced Techniques
### Dynamic Context Loading
```
# Load context based on current task
/ultrathink-task I need to work on the API layer.
Load relevant context:
@ai_context/generated/api_*.md
@ai_context/api-guidelines.md
```
### Context Templates
Create reusable context sets:
```bash
# .ai/contexts/api-work.md
# API Development Context
## Load these files:
- @ai_context/generated/api_routes.md
- @ai_context/generated/models.md
- @ai_context/api-standards.md
- @docs/api/README.md
## Key principles:
- RESTful design
- Comprehensive error handling
- OpenAPI documentation
```
### Incremental Context
Build context progressively:
```
# Start broad
Read @ai_context/IMPLEMENTATION_PHILOSOPHY.md
# Get specific
Now read @ai_context/generated/auth_module.md
# Add requirements
Also consider @ai_working/auth-v2/requirements.md
```
### Context Versioning
Track context evolution:
```bash
# Version generated docs
cd ai_context/generated
git add .
git commit -m "Context snapshot: pre-refactor"
```
## 📊 Context Optimization
### Size Management
```python
# In build_ai_context_files.py
MAX_FILE_SIZE = 100_000 # Skip large files
MAX_ROLLUP_SIZE = 500_000 # Split large rollups
```
### Relevance Filtering
```python
# Custom relevance scoring
def is_relevant(file_path: Path) -> bool:
# Skip generated files
if 'generated' in file_path.parts:
return False
# Skip vendor code
if 'vendor' in file_path.parts:
return False
# Include based on importance
important_dirs = ['src', 'api', 'core']
return any(d in file_path.parts for d in important_dirs)
```
### Context Caching
```bash
# Cache expensive context generation
CONTEXT_CACHE=".ai/context-cache"
CACHE_AGE=$(($(date +%s) - $(stat -f %m "$CONTEXT_CACHE" 2>/dev/null || echo 0)))
if [ $CACHE_AGE -gt 3600 ]; then # 1 hour
make ai-context-files
touch "$CONTEXT_CACHE"
fi
```
## 🎯 Common Patterns
### Feature Development
```
1. Create feature workspace:
mkdir -p ai_working/new-feature
2. Add requirements:
echo "..." > ai_working/new-feature/requirements.md
3. Generate fresh context:
make ai-context-files
4. Start development:
/ultrathink-task Implement @ai_working/new-feature/requirements.md
```
### Debugging Sessions
```
1. Capture context:
echo "Error details..." > ai_working/tmp/debug-notes.md
2. Add relevant code:
python tools/collect_files.py "**/auth*.py" > ai_working/tmp/auth-code.md
3. Analyze:
Help me debug using:
@ai_working/tmp/debug-notes.md
@ai_working/tmp/auth-code.md
```
### Documentation Updates
```
1. Generate current state:
make ai-context-files
2. Update docs:
Update the API documentation based on:
@ai_context/generated/api_routes.md
3. Verify consistency:
/review-code-at-path docs/
```
## 🚀 Pro Tips
1. **Front-Load Philosophy**: Always start with philosophy docs
2. **Layer Gradually**: Add context as needed, not all at once
3. **Clean Regularly**: Remove outdated context from ai_working
4. **Version Important Context**: Git commit key snapshots
5. **Automate Generation**: Add to build pipelines
## 🔗 Related Documentation
- [Command Reference](commands.md) - Commands that use context
- [Philosophy Guide](philosophy.md) - Core principles

473
.ai/docs/automation.md Normal file
View File

@@ -0,0 +1,473 @@
# Automation Guide [Claude Code only]
This guide explains how automation works for Claude Code and how to extend it for your needs.
## 🔄 How Automation Works
### The Hook System
Claude Code supports hooks that trigger actions based on events:
```json
{
"hooks": {
"EventName": [
{
"matcher": "pattern",
"hooks": [
{
"type": "command",
"command": "script-to-run.sh"
}
]
}
]
}
}
```
### Current Automations
#### 1. **Automatic Quality Checks**
- **Trigger**: After any file edit/write
- **Script**: `.claude/tools/make-check.sh`
- **What it does**:
- Finds the nearest Makefile
- Runs `make check`
- Reports results
- Works with monorepos
#### 2. **Desktop Notifications**
- **Trigger**: Any Claude Code notification event
- **Script**: `.claude/tools/notify.sh`
- **Features**:
- Native notifications on all platforms
- Shows project context
- Non-intrusive fallbacks
## 🛠️ The Make Check System
### How It Works
The `make-check.sh` script is intelligent:
```bash
# 1. Detects what file was edited
/path/to/project/src/component.tsx
# 2. Looks for Makefile in order:
/path/to/project/src/Makefile # Local directory
/path/to/project/Makefile # Project root
/path/to/Makefile # Parent directories
# 3. Runs make check from appropriate location
cd /path/to/project && make check
```
### Setting Up Your Makefile
Create a `Makefile` in your project root:
```makefile
.PHONY: check
check: format lint typecheck test
.PHONY: format
format:
@echo "Formatting code..."
# Python
black . || true
isort . || true
# JavaScript/TypeScript
prettier --write . || true
.PHONY: lint
lint:
@echo "Linting code..."
# Python
ruff check . || true
# JavaScript/TypeScript
eslint . --fix || true
.PHONY: typecheck
typecheck:
@echo "Type checking..."
# Python
mypy . || true
# TypeScript
tsc --noEmit || true
.PHONY: test
test:
@echo "Running tests..."
# Python
pytest || true
# JavaScript
npm test || true
```
### Customizing Quality Checks
For different languages/frameworks:
**Python Project**:
```makefile
check: format lint typecheck test
format:
uv run black .
uv run isort .
lint:
uv run ruff check .
typecheck:
uv run mypy .
test:
uv run pytest
```
**Node.js Project**:
```makefile
check: format lint typecheck test
format:
npm run format
lint:
npm run lint
typecheck:
npm run typecheck
test:
npm test
```
**Go Project**:
```makefile
check: format lint test
format:
go fmt ./...
lint:
golangci-lint run
test:
go test ./...
```
## 🔔 Notification System
### How Notifications Work
1. **Event Occurs**: Claude Code needs attention
2. **Hook Triggered**: Notification hook activates
3. **Context Gathered**: Project name, session ID extracted
4. **Platform Detection**: Appropriate notification method chosen
5. **Notification Sent**: Native notification appears
### Customizing Notifications
Edit `.claude/tools/notify.sh`:
```bash
# Add custom notification categories
case "$MESSAGE" in
*"error"*)
URGENCY="critical"
ICON="error.png"
;;
*"success"*)
URGENCY="normal"
ICON="success.png"
;;
*)
URGENCY="low"
ICON="info.png"
;;
esac
```
### Adding Sound Alerts
**macOS**:
```bash
# Add to notify.sh
afplay /System/Library/Sounds/Glass.aiff
```
**Linux**:
```bash
# Add to notify.sh
paplay /usr/share/sounds/freedesktop/stereo/complete.oga
```
**Windows/WSL**:
```powershell
# Add to PowerShell section
[System.Media.SystemSounds]::Exclamation.Play()
```
## 🎯 Creating Custom Automations
### Example: Auto-Format on Save
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": ".claude/tools/auto-format.sh"
}
]
}
]
}
}
```
Create `.claude/tools/auto-format.sh`:
```bash
#!/usr/bin/env bash
set -euo pipefail
# Read JSON input
JSON_INPUT=$(cat)
# Extract file path
FILE_PATH=$(echo "$JSON_INPUT" | grep -o '"file_path"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')
# Format based on file extension
case "$FILE_PATH" in
*.py)
black "$FILE_PATH"
;;
*.js|*.jsx|*.ts|*.tsx)
prettier --write "$FILE_PATH"
;;
*.go)
gofmt -w "$FILE_PATH"
;;
esac
```
### Example: Git Auto-Commit
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": ".claude/tools/auto-commit.sh"
}
]
}
]
}
}
```
Create `.claude/tools/auto-commit.sh`:
```bash
#!/usr/bin/env bash
# Auto-commit changes with descriptive messages
# ... parse JSON and get file path ...
# Generate commit message
COMMIT_MSG="Auto-update: $(basename "$FILE_PATH")"
# Stage and commit
git add "$FILE_PATH"
git commit -m "$COMMIT_MSG" --no-verify || true
```
### Example: Test Runner
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": ".claude/tools/run-tests.sh"
}
]
}
]
}
}
```
## 🏗️ Advanced Automation Patterns
### Conditional Execution
```bash
#!/usr/bin/env bash
# Only run on specific files
FILE_PATH=$(extract_file_path_from_json)
# Only check Python files
if [[ "$FILE_PATH" == *.py ]]; then
python -m py_compile "$FILE_PATH"
fi
# Only test when source files change
if [[ "$FILE_PATH" == */src/* ]]; then
npm test
fi
```
### Parallel Execution
```bash
#!/usr/bin/env bash
# Run multiple checks in parallel
{
echo "Starting parallel checks..."
# Run all checks in background
make format &
PID1=$!
make lint &
PID2=$!
make typecheck &
PID3=$!
# Wait for all to complete
wait $PID1 $PID2 $PID3
echo "All checks complete!"
}
```
### Error Handling
```bash
#!/usr/bin/env bash
# Graceful error handling
set -euo pipefail
# Trap errors
trap 'echo "Check failed at line $LINENO"' ERR
# Run with error collection
ERRORS=0
make format || ((ERRORS++))
make lint || ((ERRORS++))
make test || ((ERRORS++))
if [ $ERRORS -gt 0 ]; then
echo "⚠️ $ERRORS check(s) failed"
exit 1
else
echo "✅ All checks passed!"
fi
```
## 🔧 Debugging Automations
### Enable Debug Logging
```bash
# Add to any automation script
DEBUG_LOG="/tmp/claude-automation-debug.log"
echo "[$(date)] Script started" >> "$DEBUG_LOG"
echo "Input: $JSON_INPUT" >> "$DEBUG_LOG"
```
### Test Scripts Manually
```bash
# Test with sample input
echo '{"file_path": "/path/to/test.py", "success": true}' | .claude/tools/make-check.sh
```
### Common Issues
1. **Script Not Executing**
- Check file permissions: `chmod +x .claude/tools/*.sh`
- Verify path in settings.json
2. **No Output**
- Check if script outputs to stdout
- Look for error logs in /tmp/
3. **Platform-Specific Issues**
- Test platform detection logic
- Ensure fallbacks work
## 🚀 Best Practices
1. **Fast Execution**: Keep automations under 5 seconds
2. **Fail Gracefully**: Don't break Claude Code workflow
3. **User Feedback**: Provide clear success/failure messages
4. **Cross-Platform**: Test on Mac, Linux, Windows, WSL
5. **Configurable**: Allow users to customize behavior
## 📊 Performance Optimization
### Caching Results
```bash
# Cache expensive operations
CACHE_FILE="/tmp/claude-check-cache"
CACHE_AGE=$(($(date +%s) - $(stat -f %m "$CACHE_FILE" 2>/dev/null || echo 0)))
if [ $CACHE_AGE -lt 300 ]; then # 5 minutes
cat "$CACHE_FILE"
else
make check | tee "$CACHE_FILE"
fi
```
### Incremental Checks
```bash
# Only check changed files
CHANGED_FILES=$(git diff --name-only HEAD)
for file in $CHANGED_FILES; do
case "$file" in
*.py) pylint "$file" ;;
*.js) eslint "$file" ;;
esac
done
```
## 🔗 Related Documentation
- [Command Reference](commands.md) - Available commands
- [Notifications Guide](notifications.md) - Desktop alerts

386
.ai/docs/commands.md Normal file
View File

@@ -0,0 +1,386 @@
# Command Reference
This guide documents all custom commands available in this AI code template.
## 🧠 Core Commands
### `/prime` - Philosophy-Aligned Environment Setup
**Purpose**: Initialize your project with the right environment and philosophical grounding.
**What it does**:
1. Installs all dependencies (`make install`)
2. Activates virtual environment
3. Runs quality checks (`make check`)
4. Runs tests (`make test`)
5. Loads philosophy documents
6. Prepares AI assistant for aligned development
**Usage**:
```
/prime
```
**When to use**:
- Starting a new project
- After cloning the template
- Beginning a new AI assistant session
- When you want to ensure philosophical alignment
---
### `/ultrathink-task` - Multi-Agent Deep Analysis
**Purpose**: Solve complex problems through orchestrated AI collaboration.
**Architecture**:
```
Coordinator Agent
├── Architect Agent - Designs approach
├── Research Agent - Gathers knowledge
├── Coder Agent - Implements solution
└── Tester Agent - Validates results
```
**Usage**:
```
/ultrathink-task <detailed task description>
```
**Examples**:
```
/ultrathink-task Build a REST API with:
- User authentication using JWT
- Rate limiting
- Comprehensive error handling
- OpenAPI documentation
- Full test coverage
/ultrathink-task Debug this complex issue:
[paste error trace]
The error happens when users upload files larger than 10MB.
Check our patterns in IMPLEMENTATION_PHILOSOPHY.md
```
**When to use**:
- Complex features requiring architecture
- Problems needing research and implementation
- Tasks benefiting from multiple perspectives
- When you want systematic, thorough solutions
---
### `/test-webapp-ui` - Automated UI Testing
**Purpose**: Automatically discover and test web applications with visual validation.
**Features**:
- Auto-discovers running web apps
- Starts static servers if needed
- Tests functionality and aesthetics
- Manages server lifecycle
- Cross-browser support via MCP
**Usage**:
```
/test-webapp-ui <url_or_description> [test-focus]
```
**Examples**:
```
/test-webapp-ui http://localhost:3000
/test-webapp-ui "the React dashboard in examples/dashboard"
/test-webapp-ui http://localhost:8080 "focus on mobile responsiveness"
```
**Server Patterns Supported**:
- Running applications (auto-detected via `lsof`)
- Static HTML sites (auto-served)
- Node.js apps (`npm start`, `npm run dev`)
- Python apps (Flask, Django, FastAPI)
- Docker containers
---
## 📋 Planning Commands
### `/create-plan` - Strategic Planning
**Purpose**: Create structured implementation plans for complex features.
**Usage**:
```
/create-plan <feature description>
```
**Output**: Detailed plan with:
- Architecture decisions
- Implementation steps
- Testing strategy
- Potential challenges
- Success criteria
---
### `/execute-plan` - Plan Execution
**Purpose**: Execute a previously created plan systematically.
**Usage**:
```
/execute-plan
```
**Behavior**:
- Reads the most recent plan
- Executes steps in order
- Tracks progress
- Handles errors gracefully
- Reports completion status
---
## 🔍 Review Commands
### `/review-changes` - Comprehensive Change Review
**Purpose**: Review all recent changes for quality and consistency.
**What it reviews**:
- Code style compliance
- Philosophy alignment
- Test coverage
- Documentation updates
- Security considerations
**Usage**:
```
/review-changes
```
---
### `/review-code-at-path` - Targeted Code Review
**Purpose**: Deep review of specific files or directories.
**Usage**:
```
/review-code-at-path <file_or_directory>
```
**Examples**:
```
/review-code-at-path src/api/auth.py
/review-code-at-path components/Dashboard/
```
---
## 🛠️ Creating Custom Commands
### Claude Code
#### Command Structure
Create a new file in `.claude/commands/your-command.md`:
```markdown
## Usage
`/your-command <required-arg> [optional-arg]`
## Context
- Brief description of what the command does
- When and why to use it
- Any important notes or warnings
### Process
1. First step with clear description
2. Second step with details
3. Continue for all steps
4. Include decision points
5. Handle edge cases
## Output Format
Describe what the user will see:
- Success messages
- Error handling
- Next steps
- Any generated artifacts
```
### Gemini CLI
#### Command Structure
Create a new file in `.gemini/commands/your-command.toml`:
```toml
description = "Brief description of the command"
prompt = """## Usage
`/your-command <required-arg> [optional-arg]`
## Context
- Brief description of what the command does
- When and why to use it
- Any important notes or warnings
## Process
1. First step with clear description
2. Second step with details
3. Continue for all steps
4. Include decision points
5. Handle edge cases
## Output Format
Describe what the user will see:
- Success messages
- Error handling
- Next steps
- Any generated artifacts
"""
```
### Best Practices
1. **Clear Usage**: Show exact syntax with examples
2. **Context Section**: Explain when and why to use
3. **Detailed Process**: Step-by-step instructions
4. **Error Handling**: What to do when things go wrong
5. **Output Format**: Set clear expectations
### Advanced Features
#### Sub-Agent Orchestration
```markdown
## Process
1. **Architect Agent**: Design the approach
- Consider existing patterns
- Plan component structure
2. **Implementation Agent**: Build the solution
- Follow architecture plan
- Apply coding standards
3. **Testing Agent**: Validate everything
- Unit tests
- Integration tests
- Manual verification
```
#### Conditional Logic
```markdown
## Process
1. Check if Docker is running
- If yes: Use containerized approach
- If no: Use local development
2. Determine project type
- Node.js: Use npm/yarn commands
- Python: Use pip/poetry/uv
- Go: Use go modules
```
#### File Operations
```markdown
## Process
1. Read configuration: @config/settings.json
2. Generate based on template: @templates/component.tsx
3. Write to destination: src/components/NewComponent.tsx
4. Update index: @src/components/index.ts
```
## 🎯 Command Combinations
### Power Workflows
**Full Feature Development**:
```
/prime
/create-plan "user authentication system"
/execute-plan
/test-webapp-ui
/review-changes
```
**Rapid Prototyping**:
```
/ultrathink-task "create a dashboard mockup"
/test-webapp-ui "check the dashboard"
[iterate with natural language]
```
**Debug Session**:
```
/prime
[paste error]
/ultrathink-task "debug this error: [details]"
[test fix]
/review-code-at-path [changed files]
```
## 🚀 Tips for Effective Command Usage
1. **Start with `/prime`**: Always ensure philosophical alignment
2. **Use `/ultrathink-task` for complexity**: Let multiple agents collaborate
3. **Iterate naturally**: Commands start workflows, natural language refines
4. **Combine commands**: They're designed to work together
5. **Trust the process**: Let commands handle the details
## 📝 Command Development Guidelines
When creating new commands:
1. **Single Responsibility**: Each command does one thing well
2. **Composable**: Design to work with other commands
3. **Progressive**: Simple usage, advanced options
4. **Documented**: Clear examples and edge cases
5. **Tested**: Include validation in the process
## 🔗 Related Documentation
- [Automation Guide](automation.md) - Hooks and triggers
- [Philosophy Guide](philosophy.md) - Guiding principles

355
.ai/docs/notifications.md Normal file
View File

@@ -0,0 +1,355 @@
# Desktop Notifications Guide [Claude Code only]
Never miss important Claude Code events with native desktop notifications on all platforms.
## 🔔 Overview
The notification system keeps you in flow by alerting you when:
- Claude Code needs permission to proceed
- Tasks complete successfully
- Errors require your attention
- Long-running operations finish
- Custom events you define occur
## 🖥️ Platform Support
### macOS
- Native Notification Center
- Supports title, subtitle, and message
- Respects Do Not Disturb settings
- Sound alerts optional
### Linux
- Uses `notify-send` (libnotify)
- Full desktop environment support
- Works with GNOME, KDE, XFCE, etc.
- Custom icons supported
### Windows
- Native Windows toast notifications
- Action Center integration
- Works in PowerShell/WSL
- Supports notification grouping
### WSL (Windows Subsystem for Linux)
- Automatically detects WSL environment
- Routes to Windows notifications
- Full feature support
- No additional setup needed
## 🚀 Quick Start
Notifications work out of the box! The system automatically:
1. Detects your platform
2. Uses the best notification method
3. Falls back to console output if needed
## 🛠️ How It Works
### Notification Flow
```
Claude Code Event
Notification Hook Triggered
notify.sh Receives JSON
Platform Detection
Native Notification Sent
You Stay In Flow ✨
```
### JSON Input Format
The notification script receives:
```json
{
"session_id": "abc123",
"transcript_path": "/path/to/transcript.jsonl",
"cwd": "/path/to/project",
"hook_event_name": "Notification",
"message": "Task completed successfully"
}
```
### Smart Context Detection
Notifications include:
- **Project Name**: From git repo or directory name
- **Session ID**: Last 6 characters for multi-window users
- **Message**: The actual notification content
Example: `MyProject (abc123): Build completed successfully`
## 🎨 Customization
### Custom Messages
Edit `.claude/settings.json` to customize when notifications appear:
```json
{
"hooks": {
"Notification": [
{
"matcher": ".*error.*",
"hooks": [
{
"type": "command",
"command": ".claude/tools/notify-error.sh"
}
]
}
]
}
}
```
### Adding Sounds
**macOS** - Add to `notify.sh`:
```bash
# Play sound with notification
osascript -e 'display notification "..." sound name "Glass"'
```
**Linux** - Add to `notify.sh`:
```bash
# Play sound after notification
paplay /usr/share/sounds/freedesktop/stereo/complete.oga &
```
**Windows/WSL** - Add to PowerShell section:
```powershell
# System sounds
[System.Media.SystemSounds]::Exclamation.Play()
```
### Custom Icons
**Linux**:
```bash
notify-send -i "/path/to/icon.png" "Title" "Message"
```
**macOS** (using terminal-notifier):
```bash
terminal-notifier -title "Claude Code" -message "Done!" -appIcon "/path/to/icon.png"
```
### Notification Categories
Add urgency levels:
```bash
# In notify.sh
case "$MESSAGE" in
*"error"*|*"failed"*)
URGENCY="critical"
TIMEOUT=0 # Don't auto-dismiss
;;
*"warning"*)
URGENCY="normal"
TIMEOUT=10000
;;
*)
URGENCY="low"
TIMEOUT=5000
;;
esac
# Linux
notify-send -u "$URGENCY" -t "$TIMEOUT" "$TITLE" "$MESSAGE"
```
## 🔧 Troubleshooting
### No Notifications Appearing
1. **Check permissions**:
```bash
# Make script executable
chmod +x .claude/tools/notify.sh
```
2. **Test manually**:
```bash
echo '{"message": "Test notification", "cwd": "'$(pwd)'"}' | .claude/tools/notify.sh
```
3. **Enable debug mode**:
```bash
echo '{"message": "Test"}' | .claude/tools/notify.sh --debug
# Check /tmp/claude-code-notify-*.log
```
### Platform-Specific Issues
**macOS**:
- Check System Preferences → Notifications → Terminal/Claude Code
- Ensure notifications are allowed
- Try: `osascript -e 'display notification "Test"'`
**Linux**:
- Install libnotify: `sudo apt install libnotify-bin`
- Test: `notify-send "Test"`
- Check if notification daemon is running
**Windows/WSL**:
- Ensure Windows notifications are enabled
- Check Focus Assist settings
- Test PowerShell directly
### Silent Failures
Enable verbose logging:
```bash
# Add to notify.sh
set -x # Enable command printing
exec 2>/tmp/notify-debug.log # Redirect errors
```
## 📊 Advanced Usage
### Notification History
Track all notifications:
```bash
# Add to notify.sh
echo "$(date): $MESSAGE" >> ~/.claude-notifications.log
```
### Conditional Notifications
Only notify for important events:
```bash
# Skip trivial notifications
if [[ "$MESSAGE" =~ ^(Saved|Loaded|Reading) ]]; then
exit 0
fi
```
### Remote Notifications
Send to your phone via Pushover/Pushbullet:
```bash
# Add to notify.sh for critical errors
if [[ "$MESSAGE" =~ "critical error" ]]; then
curl -s -F "token=YOUR_APP_TOKEN" \
-F "user=YOUR_USER_KEY" \
-F "message=$MESSAGE" \
https://api.pushover.net/1/messages.json
fi
```
### Notification Groups
Group related notifications:
```bash
# macOS - Group by project
osascript -e "display notification \"$MESSAGE\" with title \"$PROJECT\" group \"$PROJECT\""
```
## 🎯 Best Practices
1. **Be Selective**: Too many notifications reduce their value
2. **Add Context**: Include project and session info
3. **Use Urgency**: Critical errors should stand out
4. **Test Regularly**: Ensure notifications work after updates
5. **Provide Fallbacks**: Always output to console too
## 🔌 Integration Examples
### Build Status
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Bash.*make.*build",
"hooks": [
{
"type": "command",
"command": ".claude/tools/notify-build.sh"
}
]
}
]
}
}
```
### Test Results
```bash
# In notify-build.sh
if grep -q "FAILED" <<< "$TOOL_OUTPUT"; then
MESSAGE="❌ Build failed! Check errors."
else
MESSAGE="✅ Build successful!"
fi
```
### Long Task Completion
```bash
# Track task duration
START_TIME=$(date +%s)
# ... task runs ...
DURATION=$(($(date +%s) - START_TIME))
MESSAGE="Task completed in ${DURATION}s"
```
## 🌟 Tips & Tricks
1. **Use Emojis**: They make notifications scannable
- ✅ Success
- ❌ Error
- ⚠️ Warning
- 🔄 In Progress
- 🎉 Major Success
2. **Keep It Short**: Notifications should be glanceable
3. **Action Words**: Start with verbs
- "Completed build"
- "Fixed 3 errors"
- "Need input for..."
4. **Session Context**: Include session ID for multiple windows
5. **Project Context**: Always show which project
## 🔗 Related Documentation
- [Automation Guide](automation.md) - Hook system
- [Command Reference](commands.md) - Triggering notifications

422
.ai/docs/philosophy.md Normal file
View File

@@ -0,0 +1,422 @@
# Philosophy Guide
Understanding the philosophy behind this template is key to achieving 10x productivity with AI assistants.
## 🧠 Core Philosophy: Human Creativity, AI Velocity
### The Fundamental Principle
> **You bring the vision and creativity. AI handles the implementation details.**
This isn't about AI replacing developers—it's about developers achieving what was previously impossible. Your unique problem-solving approach, architectural vision, and creative solutions remain entirely yours. AI simply removes the friction between idea and implementation.
## 🎯 The Three Pillars
### 1. Amplification, Not Replacement
**Traditional Approach**:
- Developer thinks of solution
- Developer implements every detail
- Developer tests and debugs
- Time: Days to weeks
**AI-Amplified Approach**:
- Developer envisions solution
- AI implements under guidance
- Developer reviews and refines
- Time: Hours to days
**Key Insight**: You still make every important decision. AI just executes faster.
### 2. Philosophy-Driven Development
**Why Philosophy Matters**:
- Consistency across all code
- Decisions aligned with principles
- AI understands your preferences
- Team shares mental model
**In Practice**:
```
/prime # Loads philosophy
# Now every AI interaction follows your principles
```
### 3. Flow State Preservation
**Flow Killers** (Eliminated):
- Context switching for formatting
- Looking up syntax details
- Writing boilerplate code
- Manual quality checks
**Flow Enhancers** (Amplified):
- Desktop notifications
- Automated quality
- Natural language interaction
- Continuous momentum
## 📋 Implementation Philosophy
### Simplicity First
**Principle**: Every line of code should have a clear purpose.
**Application**:
```python
# ❌ Over-engineered
class AbstractFactoryManagerSingleton:
def get_instance_factory_manager(self):
return self._factory_instance_manager_singleton
# ✅ Simple and clear
def get_user(user_id: str) -> User:
return database.find_user(user_id)
```
**Why It Works**: Simple code is:
- Easier to understand
- Faster to modify
- Less likely to break
- More maintainable
### Pragmatic Architecture
**Principle**: Build for today's needs, not tomorrow's possibilities.
**Application**:
- Start with monolith, split when needed
- Use boring technology that works
- Optimize when you measure, not when you guess
- Choose patterns that fit, not patterns that impress
**Example Evolution**:
```
Version 1: Simple function
Version 2: Add error handling (when errors occur)
Version 3: Add caching (when performance matters)
Version 4: Extract to service (when scale demands)
```
### Trust in Emergence
**Principle**: Good architecture emerges from good practices.
**Application**:
- Don't over-plan the system
- Let patterns reveal themselves
- Refactor when clarity emerges
- Trust the iterative process
**Real Example**:
```
Week 1: Build auth quickly
Week 2: Notice pattern, extract utilities
Week 3: See bigger pattern, create auth module
Week 4: Clear architecture has emerged naturally
```
## 🔧 Modular Design Philosophy
### Think "Bricks & Studs"
**Concept**:
- **Brick** = Self-contained module with one responsibility
- **Stud** = Clean interface others connect to
**Implementation**:
```python
# user_service.py (Brick)
"""Handles all user-related operations"""
# Public Interface (Studs)
def create_user(data: UserData) -> User: ...
def get_user(user_id: str) -> User: ...
def update_user(user_id: str, data: UserData) -> User: ...
# Internal Implementation (Hidden inside brick)
def _validate_user_data(): ...
def _hash_password(): ...
```
### Contract-First Development
**Process**:
1. Define what the module does
2. Design the interface
3. Implement the internals
4. Test the contract
**Example**:
```python
# 1. Purpose (README in module)
"""Email Service: Sends transactional emails"""
# 2. Contract (interface.py)
@dataclass
class EmailRequest:
to: str
subject: str
body: str
async def send_email(request: EmailRequest) -> bool:
"""Send email, return success status"""
# 3. Implementation (internal)
# ... whatever works, can change anytime
# 4. Contract Test
def test_email_contract():
result = await send_email(EmailRequest(...))
assert isinstance(result, bool)
```
### Regenerate, Don't Patch
**Philosophy**: When modules need significant changes, rebuild them.
**Why**:
- Clean slate avoids technical debt
- AI excels at regeneration
- Tests ensure compatibility
- Cleaner than patching patches
**Process**:
```
/ultrathink-task Regenerate the auth module with these new requirements:
- Add OAuth support
- Maintain existing API contract
- Include migration guide
```
## 🎨 Coding Principles
### Explicit Over Implicit
```python
# ❌ Implicit
def process(data):
return data * 2.5 # What is 2.5?
# ✅ Explicit
TAX_MULTIPLIER = 2.5
def calculate_with_tax(amount: float) -> float:
"""Calculate amount including tax"""
return amount * TAX_MULTIPLIER
```
### Composition Over Inheritance
```python
# ❌ Inheritance jungle
class Animal: ...
class Mammal(Animal): ...
class Dog(Mammal): ...
class FlyingDog(Dog, Bird): ... # 😱
# ✅ Composition
@dataclass
class Dog:
movement: MovementBehavior
sound: SoundBehavior
flying_dog = Dog(
movement=FlyingMovement(),
sound=BarkSound()
)
```
### Errors Are Values
```python
# ❌ Hidden exceptions
def get_user(id):
return db.query(f"SELECT * FROM users WHERE id={id}")
# SQL injection! Throws on not found!
# ✅ Explicit results
def get_user(user_id: str) -> Result[User, str]:
if not is_valid_uuid(user_id):
return Err("Invalid user ID format")
user = db.get_user(user_id)
if not user:
return Err("User not found")
return Ok(user)
```
## 🚀 AI Collaboration Principles
### Rich Context Provision
**Principle**: Give AI enough context to make good decisions.
**Application**:
```
# ❌ Minimal context
Fix the bug in auth
# ✅ Rich context
Fix the authentication bug where users get logged out after 5 minutes.
Error: "JWT token expired" even though expiry is set to 24h.
See @auth/config.py line 23 and @auth/middleware.py line 45.
Follow our error handling patterns in IMPLEMENTATION_PHILOSOPHY.md.
```
### Iterative Refinement
**Principle**: First version gets you 80%, iteration gets you to 100%.
**Process**:
1. Get something working
2. See it in action
3. Refine based on reality
4. Repeat until excellent
**Example Session**:
```
Create a data table component
[Reviews output]
Actually, add sorting to the columns
[Reviews again]
Make the sorted column show an arrow
[Perfect!]
```
### Trust but Verify
**Principle**: AI is powerful but not infallible.
**Practice**:
- Review generated code
- Run tests immediately
- Check edge cases
- Validate against requirements
**Workflow**:
```
/ultrathink-task [complex request]
# Review the plan before implementation
# Check the code before running
# Verify behavior matches intent
```
## 🌟 Philosophy in Action
### Daily Development Flow
```
Morning:
/prime # Start with philosophy alignment
Feature Development:
/create-plan "New feature based on our principles"
/execute-plan
# Automated checks maintain quality
# Notifications keep you informed
Review:
/review-changes
# Ensure philosophy compliance
```
### Problem-Solving Approach
```
1. Understand the real problem (not the symptom)
2. Consider the simplest solution
3. Check if it aligns with principles
4. Implement iteratively
5. Let architecture emerge
```
### Team Collaboration
```
# Share philosophy through configuration
git add ai_context/IMPLEMENTATION_PHILOSOPHY.md
git commit -m "Update team coding principles"
# Everyone gets same guidance
Team member: /prime
# Now coding with shared philosophy
```
## 📚 Living Philosophy
### Evolution Through Experience
This philosophy should evolve:
- Add principles that work
- Remove ones that don't
- Adjust based on team needs
- Learn from project outcomes
### Contributing Principles
When adding principles:
1. Must solve real problems
2. Should be broadly applicable
3. Include concrete examples
4. Explain the why
### Anti-Patterns to Avoid
1. **Dogmatic Adherence**: Principles guide, not dictate
2. **Premature Abstraction**: Wait for patterns to emerge
3. **Technology Over Problem**: Solve real needs
4. **Complexity Worship**: Simple is usually better
## 🎯 The Meta-Philosophy
### Why This Works
1. **Cognitive Load Reduction**: Principles make decisions easier
2. **Consistency**: Same principles = coherent codebase
3. **Speed**: No debate, follow principles
4. **Quality**: Good principles = good code
5. **Team Scaling**: Shared principles = aligned team
### The Ultimate Goal
**Create systems where:**
- Humans focus on what matters
- AI handles what's repetitive
- Quality is automatic
- Innovation is amplified
- Work remains joyful
## 🔗 Related Documentation
- [Implementation Philosophy](../../ai_context/IMPLEMENTATION_PHILOSOPHY.md)
- [Modular Design Philosophy](../../ai_context/MODULAR_DESIGN_PHILOSOPHY.md)
- [Command Reference](commands.md)
- [AI Context Guide](ai-context.md)