chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1,183 @@
|
||||
# Analytics State Detection System
|
||||
|
||||
## Overview
|
||||
This document describes how the Claude Code Analytics Dashboard determines and displays conversation states in real-time.
|
||||
|
||||
## State Detection Flow
|
||||
|
||||
### 1. Backend State Calculation (`/api/conversation-state`)
|
||||
|
||||
The conversation state endpoint processes **ALL** conversations and calculates their current state:
|
||||
|
||||
#### API Endpoint: `/api/conversation-state`
|
||||
- **Method**: GET
|
||||
- **Response Format**: `{ activeStates: {conversationId: state}, timestamp: number }`
|
||||
- **Update Frequency**: Called by frontend every 5-30 seconds
|
||||
|
||||
#### State Calculation Logic
|
||||
|
||||
For each conversation, the system:
|
||||
|
||||
1. **Checks for Running Process**:
|
||||
- If `conversation.runningProcess` exists, uses `StateCalculator.quickStateCalculation()`
|
||||
- Returns states like: "Claude Code working...", "Awaiting user input...", "User typing..."
|
||||
|
||||
2. **Falls back to Basic Heuristics** (for conversations without active processes):
|
||||
```javascript
|
||||
const timeDiff = (now - new Date(conversation.lastModified)) / (1000 * 60); // minutes
|
||||
|
||||
if (timeDiff < 5) {
|
||||
state = 'Recently active';
|
||||
} else if (timeDiff < 60) {
|
||||
state = 'Idle';
|
||||
} else if (timeDiff < 1440) { // 24 hours
|
||||
state = 'Inactive';
|
||||
} else {
|
||||
state = 'Old';
|
||||
}
|
||||
```
|
||||
|
||||
### 2. StateCalculator Logic (`src/analytics/core/StateCalculator.js`)
|
||||
|
||||
The StateCalculator determines detailed conversation states based on:
|
||||
|
||||
#### Primary Factors:
|
||||
- **Running Process**: Whether there's an active Claude Code process
|
||||
- **Last Message Role**: 'user' vs 'assistant'
|
||||
- **Message Timing**: Time since last message
|
||||
- **File Activity**: File modification time
|
||||
- **Process Activity**: Active commands in the process
|
||||
|
||||
#### State Categories:
|
||||
|
||||
**Active Process States**:
|
||||
- `"Claude Code working..."` - User just sent message or recent file activity
|
||||
- `"Awaiting user input..."` - Claude responded and waiting for user
|
||||
- `"User typing..."` - User hasn't responded for a while
|
||||
- `"Awaiting response..."` - User sent message but Claude hasn't responded
|
||||
|
||||
**Inactive Process States**:
|
||||
- `"Recently active"` - Modified within 5 minutes
|
||||
- `"Idle"` - Modified within 1 hour
|
||||
- `"Inactive"` - Modified within 24 hours
|
||||
- `"Old"` - Modified more than 24 hours ago
|
||||
|
||||
### 3. Frontend State Display (`AgentsPage.js`)
|
||||
|
||||
#### State Mapping
|
||||
The frontend maps backend states to display labels and CSS classes:
|
||||
|
||||
```javascript
|
||||
// Label mapping
|
||||
const stateLabels = {
|
||||
'Claude Code working...': 'Working',
|
||||
'Awaiting user input...': 'Awaiting input',
|
||||
'User typing...': 'Typing',
|
||||
'Awaiting response...': 'Awaiting response',
|
||||
'Recently active': 'Recent',
|
||||
'Idle': 'Idle',
|
||||
'Inactive': 'Inactive',
|
||||
'Old': 'Old',
|
||||
'unknown': 'Unknown'
|
||||
};
|
||||
|
||||
// CSS class mapping
|
||||
const stateClasses = {
|
||||
'Claude Code working...': 'status-active',
|
||||
'Awaiting user input...': 'status-waiting',
|
||||
'User typing...': 'status-typing',
|
||||
'Awaiting response...': 'status-pending',
|
||||
'Recently active': 'status-recent',
|
||||
'Idle': 'status-idle',
|
||||
'Inactive': 'status-inactive',
|
||||
'Old': 'status-old',
|
||||
'unknown': 'status-unknown'
|
||||
};
|
||||
```
|
||||
|
||||
#### Visual Indicators
|
||||
States are displayed in the conversation sidebar as:
|
||||
- **Status Dot**: Colored circle indicator
|
||||
- **Status Badge**: Text label with background color
|
||||
- **CSS Classes**: For consistent styling across components
|
||||
|
||||
## Real-time Updates
|
||||
|
||||
### WebSocket Integration
|
||||
- State changes are pushed via WebSocket when available
|
||||
- Falls back to polling every 5-30 seconds when WebSocket unavailable
|
||||
|
||||
### Update Triggers
|
||||
- File system changes (FileWatcher)
|
||||
- Process detection updates
|
||||
- Periodic refresh intervals
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **States showing as "unknown"**:
|
||||
- Check if `/api/conversation-state` is returning data
|
||||
- Verify conversation IDs match between API and frontend
|
||||
- Ensure StateCalculator is processing all conversations
|
||||
|
||||
2. **States not updating in real-time**:
|
||||
- Check WebSocket connection in browser dev tools
|
||||
- Verify FileWatcher is detecting changes
|
||||
- Check for polling fallback activation
|
||||
|
||||
3. **Incorrect state calculations**:
|
||||
- Review StateCalculator logic for edge cases
|
||||
- Check conversation file modification times
|
||||
- Verify process detection is working
|
||||
|
||||
### Debug Commands
|
||||
|
||||
```bash
|
||||
# Test state endpoint
|
||||
curl -s http://localhost:3333/api/conversation-state | jq .
|
||||
|
||||
# Check conversations count
|
||||
curl -s "http://localhost:3333/api/conversations?page=0&limit=1" | jq '.pagination.totalCount'
|
||||
|
||||
# Monitor server logs for state calculation
|
||||
# Look for: "🔍 Processing X conversations for state calculation"
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### State Update Intervals
|
||||
- **With WebSocket**: 30 seconds cache duration
|
||||
- **Without WebSocket**: 5 seconds cache duration
|
||||
- **File Watch**: Immediate updates when files change
|
||||
|
||||
### Performance Considerations
|
||||
- StateCalculator uses caching to avoid repeated calculations
|
||||
- Quick state calculation for active processes only
|
||||
- Batch processing of all conversations in single API call
|
||||
|
||||
## Future Improvements
|
||||
|
||||
1. **Enhanced Process Detection**: Better correlation between conversations and running processes
|
||||
2. **Message-Level Analysis**: Analyze message content for more accurate state detection
|
||||
3. **User Activity Tracking**: Detect actual user typing vs idle time
|
||||
4. **Custom State Rules**: Allow configuration of state calculation logic
|
||||
5. **State History**: Track state changes over time for analytics
|
||||
|
||||
## Integration Points
|
||||
|
||||
### Files Involved
|
||||
- `/src/analytics.js` - Main server and API endpoints
|
||||
- `/src/analytics/core/StateCalculator.js` - Core state logic
|
||||
- `/src/analytics-web/components/AgentsPage.js` - Frontend display
|
||||
- `/src/analytics-web/services/DataService.js` - API communication
|
||||
- `/src/analytics-web/index.html` - CSS styling
|
||||
|
||||
### Key Functions
|
||||
- `StateCalculator.determineConversationState()` - Main state detection
|
||||
- `StateCalculator.quickStateCalculation()` - Fast state for active processes
|
||||
- `AgentsPage.getStateClass()` - CSS class mapping
|
||||
- `AgentsPage.getStateLabel()` - Display label mapping
|
||||
- `DataService.getConversationStates()` - API communication
|
||||
|
||||
This system provides real-time visibility into Claude Code conversation states, helping users understand what's happening across all their active sessions.
|
||||
@@ -0,0 +1,472 @@
|
||||
# Claude Code Templates - Modular Architecture
|
||||
|
||||
This document provides detailed technical documentation for the modular architecture implementation of the Claude Code Templates analytics dashboard.
|
||||
|
||||
## Overview
|
||||
|
||||
The analytics dashboard has been refactored from a monolithic architecture to a modern, scalable modular design. This transformation occurred in 4 phases:
|
||||
|
||||
1. **Phase 1**: Backend modularization (Core modules extraction)
|
||||
2. **Phase 2**: Frontend modularization (Component-based architecture)
|
||||
3. **Phase 3**: WebSocket integration (Real-time communication)
|
||||
4. **Phase 4**: Testing & Performance monitoring
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── analytics.js # Main orchestration class
|
||||
├── analytics/
|
||||
│ ├── core/ # Core business logic modules
|
||||
│ │ ├── StateCalculator.js # Conversation state detection
|
||||
│ │ ├── ProcessDetector.js # Running process detection
|
||||
│ │ ├── ConversationAnalyzer.js # Message analysis & parsing
|
||||
│ │ └── FileWatcher.js # File system monitoring
|
||||
│ ├── data/
|
||||
│ │ └── DataCache.js # Multi-level caching system
|
||||
│ ├── notifications/
|
||||
│ │ ├── WebSocketServer.js # WebSocket communication
|
||||
│ │ └── NotificationManager.js # Event management
|
||||
│ └── utils/
|
||||
│ └── PerformanceMonitor.js # Performance tracking
|
||||
├── analytics-web/ # Frontend modular components
|
||||
│ ├── index.html # Main dashboard page
|
||||
│ ├── assets/
|
||||
│ │ ├── css/style.css # Styling
|
||||
│ │ └── js/main.js # Application entry point
|
||||
│ ├── components/
|
||||
│ │ ├── Dashboard.js # Main dashboard component
|
||||
│ │ ├── ConversationTable.js # Conversation display
|
||||
│ │ └── Charts.js # Data visualization
|
||||
│ └── services/
|
||||
│ ├── DataService.js # API communication
|
||||
│ ├── StateService.js # State management
|
||||
│ └── WebSocketService.js # Real-time communication
|
||||
└── tests/ # Comprehensive test suite
|
||||
├── unit/ # Unit tests for modules
|
||||
├── integration/ # Integration tests
|
||||
└── e2e/ # End-to-end tests
|
||||
```
|
||||
|
||||
## Backend Architecture
|
||||
|
||||
### Core Modules
|
||||
|
||||
#### StateCalculator.js
|
||||
Responsible for determining conversation states based on message analysis and process detection.
|
||||
|
||||
**Key Features:**
|
||||
- Real-time state detection: `active`, `waiting`, `idle`, `completed`
|
||||
- Message pattern analysis for tool usage and errors
|
||||
- Process-aware state calculation
|
||||
- Ultra-fast refresh for live updates
|
||||
|
||||
**API:**
|
||||
```javascript
|
||||
const stateCalculator = new StateCalculator();
|
||||
const state = stateCalculator.determineConversationState(messages, lastModified, runningProcess);
|
||||
const quickState = stateCalculator.quickStateCalculation(conversation, processes);
|
||||
```
|
||||
|
||||
#### ProcessDetector.js
|
||||
Manages detection and monitoring of running Claude Code processes.
|
||||
|
||||
**Key Features:**
|
||||
- Cross-platform process detection (macOS, Linux, Windows)
|
||||
- Process-conversation correlation
|
||||
- Orphan process identification
|
||||
- Efficient process monitoring
|
||||
|
||||
**API:**
|
||||
```javascript
|
||||
const detector = new ProcessDetector();
|
||||
const processes = await detector.getRunningClaudeProcesses();
|
||||
const enriched = await detector.enrichWithRunningProcesses(conversations, claudeDir, stateCalculator);
|
||||
```
|
||||
|
||||
#### ConversationAnalyzer.js
|
||||
Handles conversation file parsing, analysis, and data extraction.
|
||||
|
||||
**Key Features:**
|
||||
- JSONL file parsing with error handling
|
||||
- Token counting and message analysis
|
||||
- Project detection and categorization
|
||||
- Integrated caching for performance
|
||||
|
||||
**API:**
|
||||
```javascript
|
||||
const analyzer = new ConversationAnalyzer(claudeDir, dataCache);
|
||||
const data = await analyzer.loadInitialData(stateCalculator, processDetector);
|
||||
const conversations = await analyzer.analyzeConversations(files, stateCalculator);
|
||||
```
|
||||
|
||||
#### FileWatcher.js
|
||||
Provides real-time file system monitoring with efficient change detection.
|
||||
|
||||
**Key Features:**
|
||||
- Chokidar-based file watching
|
||||
- Intelligent refresh throttling
|
||||
- Multiple watcher management
|
||||
- Cache invalidation integration
|
||||
|
||||
**API:**
|
||||
```javascript
|
||||
const watcher = new FileWatcher();
|
||||
watcher.setupFileWatchers(claudeDir, dataRefreshCallback, processRefreshCallback, dataCache);
|
||||
watcher.pause(); // Pause monitoring
|
||||
watcher.resume(); // Resume monitoring
|
||||
```
|
||||
|
||||
### Data Layer
|
||||
|
||||
#### DataCache.js
|
||||
Multi-level caching system with intelligent invalidation strategies.
|
||||
|
||||
**Cache Levels:**
|
||||
1. **File Content Cache** - Raw file content with timestamp validation
|
||||
2. **Parsed Data Cache** - Processed conversation data
|
||||
3. **Computation Cache** - Expensive calculation results
|
||||
|
||||
**Key Features:**
|
||||
- TTL-based expiration
|
||||
- Dependency tracking
|
||||
- Smart invalidation
|
||||
- Memory usage optimization
|
||||
- Performance metrics
|
||||
|
||||
**API:**
|
||||
```javascript
|
||||
const cache = new DataCache();
|
||||
const content = await cache.getFileContent(filepath);
|
||||
const parsed = await cache.getParsedData(key, parser);
|
||||
const result = await cache.getComputationResult(key, computer);
|
||||
cache.invalidateFile(filepath);
|
||||
```
|
||||
|
||||
### Notification System
|
||||
|
||||
#### WebSocketServer.js
|
||||
Real-time WebSocket communication with comprehensive client management.
|
||||
|
||||
**Key Features:**
|
||||
- Client connection management
|
||||
- Subscription-based messaging
|
||||
- Heartbeat mechanism
|
||||
- Message queuing for offline clients
|
||||
- Performance monitoring integration
|
||||
|
||||
**API:**
|
||||
```javascript
|
||||
const wsServer = new WebSocketServer(httpServer, options, performanceMonitor);
|
||||
await wsServer.initialize();
|
||||
wsServer.broadcast(message, channel);
|
||||
wsServer.notifyConversationStateChange(conversationId, newState, metadata);
|
||||
```
|
||||
|
||||
#### NotificationManager.js
|
||||
Event-driven notification system with subscription management.
|
||||
|
||||
**Key Features:**
|
||||
- Event subscription management
|
||||
- WebSocket integration
|
||||
- Notification queuing
|
||||
- Client filtering
|
||||
- Error handling
|
||||
|
||||
**API:**
|
||||
```javascript
|
||||
const manager = new NotificationManager(webSocketServer);
|
||||
manager.notifyDataRefresh(data, source);
|
||||
manager.notifyConversationStateChange(id, oldState, newState, metadata);
|
||||
manager.subscribe(event, callback);
|
||||
```
|
||||
|
||||
### Performance Monitoring
|
||||
|
||||
#### PerformanceMonitor.js
|
||||
Comprehensive performance tracking and system health monitoring.
|
||||
|
||||
**Monitoring Capabilities:**
|
||||
- Memory usage tracking
|
||||
- Request performance metrics
|
||||
- Cache hit/miss ratios
|
||||
- WebSocket connection metrics
|
||||
- Error tracking and alerting
|
||||
- System health status
|
||||
|
||||
**Key Features:**
|
||||
- Express middleware integration
|
||||
- Configurable thresholds
|
||||
- Metric retention management
|
||||
- Real-time statistics
|
||||
- Export capabilities
|
||||
|
||||
**API:**
|
||||
```javascript
|
||||
const monitor = new PerformanceMonitor(options);
|
||||
monitor.startTimer('operation');
|
||||
monitor.endTimer('operation', metadata);
|
||||
monitor.recordRequest(endpoint, duration, statusCode);
|
||||
const stats = monitor.getStats(timeframe);
|
||||
const middleware = monitor.createExpressMiddleware();
|
||||
```
|
||||
|
||||
## Frontend Architecture
|
||||
|
||||
### Component-Based Design
|
||||
|
||||
#### Dashboard.js
|
||||
Main orchestration component that manages the entire dashboard interface.
|
||||
|
||||
**Responsibilities:**
|
||||
- Component initialization and lifecycle management
|
||||
- Service integration (DataService, StateService, WebSocketService)
|
||||
- Real-time data refresh coordination
|
||||
- Error handling and recovery
|
||||
- Performance optimization
|
||||
|
||||
**Key Features:**
|
||||
- Modular component loading
|
||||
- Service dependency injection
|
||||
- Automatic reconnection handling
|
||||
- Progressive enhancement
|
||||
|
||||
#### ConversationTable.js
|
||||
Interactive table component for displaying conversation data.
|
||||
|
||||
**Key Features:**
|
||||
- Real-time status updates
|
||||
- Interactive sorting and filtering
|
||||
- Responsive design
|
||||
- Performance optimization for large datasets
|
||||
- Export functionality
|
||||
|
||||
#### Charts.js
|
||||
Data visualization component using Chart.js.
|
||||
|
||||
**Key Features:**
|
||||
- Multiple chart types support
|
||||
- Real-time data updates
|
||||
- Responsive design
|
||||
- Performance optimization
|
||||
- Interactive features
|
||||
|
||||
### Service Layer
|
||||
|
||||
#### StateService.js
|
||||
Reactive state management with observer pattern implementation.
|
||||
|
||||
**Key Features:**
|
||||
- Centralized state management
|
||||
- Subscriber notification system
|
||||
- State history tracking
|
||||
- Error state handling
|
||||
- State persistence
|
||||
|
||||
**API:**
|
||||
```javascript
|
||||
const stateService = new StateService();
|
||||
stateService.subscribe(callback);
|
||||
stateService.setState(newState, action);
|
||||
stateService.updateConversations(conversations);
|
||||
const conversations = stateService.getConversationsByStatus('active');
|
||||
```
|
||||
|
||||
#### DataService.js
|
||||
API communication layer with intelligent caching and real-time integration.
|
||||
|
||||
**Key Features:**
|
||||
- HTTP request management
|
||||
- Response caching with TTL
|
||||
- WebSocket integration
|
||||
- Automatic retry logic
|
||||
- Error handling
|
||||
- Performance tracking
|
||||
|
||||
**API:**
|
||||
```javascript
|
||||
const dataService = new DataService(webSocketService);
|
||||
const conversations = await dataService.getConversations();
|
||||
const states = await dataService.getConversationStates();
|
||||
const success = await dataService.requestRefresh();
|
||||
```
|
||||
|
||||
#### WebSocketService.js
|
||||
Real-time communication service with automatic reconnection.
|
||||
|
||||
**Key Features:**
|
||||
- Connection management
|
||||
- Subscription handling
|
||||
- Automatic reconnection
|
||||
- Message queuing
|
||||
- Heartbeat monitoring
|
||||
- Error recovery
|
||||
|
||||
**API:**
|
||||
```javascript
|
||||
const wsService = new WebSocketService();
|
||||
await wsService.connect();
|
||||
wsService.subscribe('data_updates');
|
||||
wsService.on('conversation_state_change', handler);
|
||||
wsService.requestRefresh();
|
||||
```
|
||||
|
||||
## Real-time Communication
|
||||
|
||||
### WebSocket Protocol
|
||||
|
||||
The system uses WebSocket for real-time bidirectional communication between server and clients.
|
||||
|
||||
#### Message Types
|
||||
|
||||
**Client to Server:**
|
||||
- `subscribe` - Subscribe to a channel
|
||||
- `unsubscribe` - Unsubscribe from a channel
|
||||
- `refresh_request` - Request data refresh
|
||||
- `ping` - Heartbeat ping
|
||||
|
||||
**Server to Client:**
|
||||
- `connection` - Connection established
|
||||
- `data_refresh` - Data updated
|
||||
- `conversation_state_change` - State changed
|
||||
- `subscription_confirmed` - Subscription successful
|
||||
- `pong` - Heartbeat response
|
||||
|
||||
#### Channels
|
||||
- `data_updates` - General data updates
|
||||
- `conversation_updates` - Conversation state changes
|
||||
- `system_updates` - System health updates
|
||||
|
||||
### Fallback Mechanisms
|
||||
|
||||
When WebSocket connection is unavailable:
|
||||
1. Automatic fallback to polling
|
||||
2. Cache-based updates
|
||||
3. Manual refresh options
|
||||
4. Offline mode handling
|
||||
|
||||
## Performance Optimizations
|
||||
|
||||
### Caching Strategy
|
||||
|
||||
#### Multi-Level Caching
|
||||
1. **Browser Cache** - Static assets and API responses
|
||||
2. **Service Cache** - DataService request caching
|
||||
3. **Backend Cache** - File content and parsed data
|
||||
4. **Computation Cache** - Expensive calculations
|
||||
|
||||
#### Cache Invalidation
|
||||
- File-based invalidation using modification timestamps
|
||||
- WebSocket-triggered cache clearing
|
||||
- TTL-based expiration
|
||||
- Manual cache control
|
||||
|
||||
### Memory Management
|
||||
|
||||
#### Backend Optimizations
|
||||
- Automatic metric cleanup
|
||||
- Configurable memory thresholds
|
||||
- Efficient data structures
|
||||
- Process monitoring
|
||||
|
||||
#### Frontend Optimizations
|
||||
- Component cleanup on unmount
|
||||
- Event listener management
|
||||
- Memory leak prevention
|
||||
- Performance monitoring
|
||||
|
||||
### Real-time Efficiency
|
||||
|
||||
#### WebSocket Optimizations
|
||||
- Connection pooling
|
||||
- Message compression
|
||||
- Efficient serialization
|
||||
- Heartbeat optimization
|
||||
|
||||
#### Update Strategies
|
||||
- Differential updates
|
||||
- Batch processing
|
||||
- Throttling and debouncing
|
||||
- Smart refresh logic
|
||||
|
||||
## Testing Framework
|
||||
|
||||
### Test Categories
|
||||
|
||||
#### Unit Tests
|
||||
- Individual module testing
|
||||
- Mock dependencies
|
||||
- Edge case coverage
|
||||
- Performance benchmarks
|
||||
|
||||
#### Integration Tests
|
||||
- End-to-end workflows
|
||||
- Real data scenarios
|
||||
- Error condition testing
|
||||
- Performance testing
|
||||
|
||||
#### Performance Tests
|
||||
- Load testing
|
||||
- Memory usage validation
|
||||
- Response time benchmarks
|
||||
- Concurrent operation testing
|
||||
|
||||
### Test Coverage Requirements
|
||||
|
||||
- **Global Coverage**: 70% minimum
|
||||
- **Core Modules**: 80% minimum
|
||||
- **Critical Paths**: 90% minimum
|
||||
|
||||
### Testing Tools
|
||||
|
||||
- **Jest** - Test framework
|
||||
- **WebSocket Testing** - Real-time communication testing
|
||||
- **Performance Testing** - Load and stress testing
|
||||
- **Integration Testing** - Complete system validation
|
||||
|
||||
## Deployment and Operations
|
||||
|
||||
### Environment Configuration
|
||||
|
||||
#### Development
|
||||
- Hot reloading
|
||||
- Debug logging
|
||||
- Performance profiling
|
||||
- Test data generation
|
||||
|
||||
#### Production
|
||||
- Optimized builds
|
||||
- Error tracking
|
||||
- Performance monitoring
|
||||
- Health checks
|
||||
|
||||
### Monitoring and Alerting
|
||||
|
||||
#### Health Checks
|
||||
- System resource monitoring
|
||||
- WebSocket connection health
|
||||
- Cache performance metrics
|
||||
- Error rate tracking
|
||||
|
||||
#### Performance Metrics
|
||||
- Request response times
|
||||
- Memory usage patterns
|
||||
- Cache hit ratios
|
||||
- WebSocket message throughput
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
### Planned Features
|
||||
- Enhanced caching strategies
|
||||
- Advanced performance analytics
|
||||
- Multi-user support
|
||||
- API rate limiting
|
||||
- Advanced error tracking
|
||||
|
||||
### Scalability Improvements
|
||||
- Horizontal scaling support
|
||||
- Database integration
|
||||
- Advanced caching layers
|
||||
- Load balancing
|
||||
|
||||
This modular architecture provides a solid foundation for future enhancements while maintaining high performance and reliability.
|
||||
@@ -0,0 +1,438 @@
|
||||
# Blog Writing Guide - Claude Code Templates
|
||||
|
||||
This guide provides a comprehensive template for creating consistent, SEO-optimized blog articles for Claude Code Templates. Use this structure for articles about technologies, companies, or trends related to Claude Code integration.
|
||||
|
||||
## 📁 File Structure
|
||||
|
||||
```
|
||||
docs/blog/
|
||||
├── index.html # Blog homepage
|
||||
├── assets/ # Shared blog assets
|
||||
│ ├── [technology]-claude-code-templates-cover.png
|
||||
│ └── aitmpl-[technology]-search.png
|
||||
├── [technology-name]-claude-code-integration/
|
||||
│ ├── index.html # Article page
|
||||
│ └── cover.jpg # Article cover image (1200x630)
|
||||
└── code-copy.js # Copy functionality script
|
||||
```
|
||||
|
||||
## 🏗️ HTML Structure Template
|
||||
|
||||
### Basic HTML Structure
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>[Technology] and Claude Code Integration</title>
|
||||
<meta name="description" content="Learn how to integrate [Technology] with Claude Code using MCP servers, specialized agents, and automated commands for lightning-fast [domain] development.">
|
||||
|
||||
<!-- Open Graph / Facebook -->
|
||||
<meta property="og:type" content="article">
|
||||
<meta property="og:url" content="https://davila7.github.io/claude-code-templates/blog/[slug]/">
|
||||
<meta property="og:title" content="[Technology] and Claude Code Integration">
|
||||
<meta property="og:description" content="Learn how to integrate [Technology] with Claude Code...">
|
||||
<meta property="og:image" content="https://davila7.github.io/claude-code-templates/blog/[slug]/cover.jpg">
|
||||
<meta property="og:image:width" content="1200">
|
||||
<meta property="og:image:height" content="630">
|
||||
<meta property="article:published_time" content="[ISO_DATE]">
|
||||
<meta property="article:author" content="Claude Code Templates">
|
||||
<meta property="article:section" content="[Category]">
|
||||
<meta property="article:tag" content="[Technology]">
|
||||
<meta property="article:tag" content="Claude Code">
|
||||
|
||||
<!-- Twitter -->
|
||||
<meta property="twitter:card" content="summary_large_image">
|
||||
<meta property="twitter:url" content="https://davila7.github.io/claude-code-templates/blog/[slug]/">
|
||||
<meta property="twitter:title" content="[Technology] and Claude Code Integration">
|
||||
<meta property="twitter:description" content="Learn how to integrate [Technology] with Claude Code...">
|
||||
<meta property="twitter:image" content="https://davila7.github.io/claude-code-templates/blog/[slug]/cover.jpg">
|
||||
|
||||
<!-- Additional SEO -->
|
||||
<meta name="keywords" content="[Technology], Claude Code, MCP, [Domain], AI Development, Anthropic">
|
||||
<meta name="author" content="Claude Code Templates">
|
||||
<link rel="canonical" href="https://davila7.github.io/claude-code-templates/blog/[slug]/">
|
||||
|
||||
<!-- Stylesheets -->
|
||||
<link rel="stylesheet" href="../../css/styles.css">
|
||||
<link rel="stylesheet" href="../../css/blog.css">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
||||
|
||||
<!-- Structured Data -->
|
||||
<script type="application/ld+json">
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "BlogPosting",
|
||||
"headline": "[Technology] and Claude Code Integration",
|
||||
"description": "Learn how to integrate [Technology] with Claude Code...",
|
||||
"image": "https://davila7.github.io/claude-code-templates/blog/[slug]/cover.jpg",
|
||||
"author": {
|
||||
"@type": "Organization",
|
||||
"name": "Claude Code Templates"
|
||||
},
|
||||
"publisher": {
|
||||
"@type": "Organization",
|
||||
"name": "Claude Code Templates",
|
||||
"logo": {
|
||||
"@type": "ImageObject",
|
||||
"url": "https://davila7.github.io/claude-code-templates/static/img/logo.svg"
|
||||
}
|
||||
},
|
||||
"datePublished": "[ISO_DATE]",
|
||||
"dateModified": "[ISO_DATE]",
|
||||
"mainEntityOfPage": {
|
||||
"@type": "WebPage",
|
||||
"@id": "https://davila7.github.io/claude-code-templates/blog/[slug]/"
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
```
|
||||
|
||||
### Header Section
|
||||
|
||||
```html
|
||||
<header class="header">
|
||||
<div class="container">
|
||||
<div class="header-content">
|
||||
<div class="terminal-header">
|
||||
<div class="ascii-title">
|
||||
<pre class="ascii-art">
|
||||
██████╗ ██╗ ██████╗ ██████╗
|
||||
██╔══██╗██║ ██╔═══██╗██╔════╝
|
||||
██████╔╝██║ ██║ ██║██║ ███╗
|
||||
██╔══██╗██║ ██║ ██║██║ ██║
|
||||
██████╔╝███████╗╚██████╔╝╚██████╔╝
|
||||
╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝</pre>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<a href="../index.html" class="header-btn">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M10,20V14H14V20H19V12H22L12,3L2,12H5V20H10Z"/>
|
||||
</svg>
|
||||
Home
|
||||
</a>
|
||||
<a href="../index.html" class="header-btn">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
|
||||
</svg>
|
||||
Blog
|
||||
</a>
|
||||
<a href="https://github.com/davila7/claude-code-templates" target="_blank" class="header-btn">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 0c-6.626 0-12 5.373-12 12..."/>
|
||||
</svg>
|
||||
GitHub
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
```
|
||||
|
||||
### Article Header
|
||||
|
||||
```html
|
||||
<header class="article-header">
|
||||
<div class="container">
|
||||
<h1 class="article-title">How to use Claude Code with [Technology]</h1>
|
||||
<p class="article-subtitle">Learn how to integrate [Technology] with Claude Code using MCP, Agents, and Commands for faster [domain] development.</p>
|
||||
<div class="article-meta-full">
|
||||
<time datetime="[YYYY-MM-DD]">[Month DD, YYYY]</time>
|
||||
<span class="read-time">[X] min read</span>
|
||||
<div class="article-tags">
|
||||
<span class="tag">[Technology]</span>
|
||||
<span class="tag">[Category]</span>
|
||||
<span class="tag">MCP</span>
|
||||
<span class="tag">Agents</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
```
|
||||
|
||||
## 📝 Content Structure
|
||||
|
||||
### 1. Hero Image
|
||||
```html
|
||||
<img src="../assets/[technology]-claude-code-templates-cover.png" alt="[Technology] and Claude Code Integration" class="article-cover">
|
||||
```
|
||||
|
||||
### 2. Technology Stack Overview
|
||||
```html
|
||||
<h2>[Technology] Stack for Claude Code</h2>
|
||||
<p>Claude Code Templates offers [X] pre-built components for [Technology] integration:</p>
|
||||
```
|
||||
|
||||
### 3. Component Tables
|
||||
|
||||
#### Agents Table
|
||||
```html
|
||||
<h3>🤖 Agents</h3>
|
||||
<table class="components-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Component</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><strong>[Agent Name]</strong></td>
|
||||
<td>[Detailed description of agent capabilities and use cases]</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
```
|
||||
|
||||
#### Commands Table
|
||||
```html
|
||||
<h3>⚡ Commands</h3>
|
||||
<table class="components-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Command</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><strong>[command-name]</strong></td>
|
||||
<td>[Command description and functionality]</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
```
|
||||
|
||||
#### MCP Table
|
||||
```html
|
||||
<h3>🔌 MCP</h3>
|
||||
<table class="components-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Component</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>🔌 <strong>[Technology] MCP Server</strong></td>
|
||||
<td>Direct integration with [Technology] API through Model Context Protocol for seamless Claude Code interaction.</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
```
|
||||
|
||||
### 4. AITMPL.com Browse Section
|
||||
```html
|
||||
<h2>Browse all components on AITMPL.com</h2>
|
||||
<p>Before installing, you can explore all available [Technology] components on the official Claude Code Templates website:</p>
|
||||
<p>Visit <strong><a href="https://aitmpl.com" target="_blank" rel="noopener">aitmpl.com</a></strong> and search for "[technology]" to see:</p>
|
||||
<img src="../assets/aitmpl-[technology]-search.png" alt="Searching for [Technology] components on AITMPL.com" loading="lazy">
|
||||
```
|
||||
|
||||
### 5. Installation Options
|
||||
|
||||
#### Individual Components
|
||||
```html
|
||||
<h3>Install Individual Components</h3>
|
||||
<pre><code class="language-bash">
|
||||
# Install specific agent
|
||||
npx claude-code-templates@latest --agent [agent-name]
|
||||
|
||||
# Install specific command
|
||||
npx claude-code-templates@latest --command [command-name]
|
||||
|
||||
# Install MCP server
|
||||
npx claude-code-templates@latest --mcp [technology]</code></pre>
|
||||
|
||||
<p><strong>Components will be installed to:</strong></p>
|
||||
<ul>
|
||||
<li>📁 <code>.claude/commands/</code></li>
|
||||
<li>📁 <code>.claude/agents/</code></li>
|
||||
<li>📁 <code>.mcp.json</code></li>
|
||||
</ul>
|
||||
```
|
||||
|
||||
#### Global Agents
|
||||
```html
|
||||
<h3>Create Global Agents (Available Anywhere)</h3>
|
||||
<pre><code class="language-bash"># Create global agents accessible from any project
|
||||
npx claude-code-templates@latest --create-agent [agent-name]
|
||||
|
||||
# List all global agents
|
||||
npx claude-code-templates@latest --list-agents
|
||||
|
||||
# Update global agents
|
||||
npx claude-code-templates@latest --update-agent [agent-name]
|
||||
|
||||
# Remove global agents
|
||||
npx claude-code-templates@latest --remove-agent [agent-name]</code></pre>
|
||||
```
|
||||
|
||||
#### Multiple Components
|
||||
```html
|
||||
<h3>Install Multiple Components at Once</h3>
|
||||
<pre><code class="language-bash">
|
||||
# Install specific commands (comma-separated for multiple)
|
||||
npx claude-code-templates@latest --command [command1],[command2],[command3]
|
||||
</code></pre>
|
||||
|
||||
<pre><code class="language-bash">
|
||||
# Install all [Technology] components in one command
|
||||
npx claude-code-templates@latest \
|
||||
--command [all-commands-comma-separated] \
|
||||
--agent [all-agents-comma-separated] \
|
||||
--mcp [technology]</code></pre>
|
||||
|
||||
<p><strong>This will install:</strong></p>
|
||||
<ul>
|
||||
<li>✓ [X] [domain] commands</li>
|
||||
<li>✓ [X] specialized AI agents</li>
|
||||
<li>✓ 1 MCP server integration</li>
|
||||
<li>✓ Complete documentation</li>
|
||||
</ul>
|
||||
```
|
||||
|
||||
#### Execute Prompt After Installation
|
||||
```html
|
||||
<h3>Execute Prompt After Installation</h3>
|
||||
<pre><code class="language-bash"># Install components and run a prompt immediately
|
||||
npx claude-code-templates@latest \
|
||||
--command [primary-command] \
|
||||
--prompt "[Sample prompt for the technology]"</code></pre>
|
||||
```
|
||||
|
||||
### 6. File Structure
|
||||
```html
|
||||
<h2>Where Components Are Installed</h2>
|
||||
<p>The installation creates a standard Claude Code structure with components organized as follows:</p>
|
||||
|
||||
<pre><code class="language-bash">your-project/
|
||||
├── .claude/
|
||||
│ ├── commands/
|
||||
│ │ ├── [command-1].md
|
||||
│ │ ├── [command-2].md
|
||||
│ │ └── ...
|
||||
│ └── agents/
|
||||
│ ├── [agent-1].md
|
||||
│ └── [agent-2].md
|
||||
└── .mcp.json
|
||||
└── src/ # Your application code</code></pre>
|
||||
|
||||
<p>That's it! Claude Code will automatically detect all components and you can start using them immediately.</p>
|
||||
```
|
||||
|
||||
### 7. Navigation Footer
|
||||
```html
|
||||
<div class="article-nav">
|
||||
<a href="../index.html" class="back-to-blog">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M20,11V13H8L13.5,18.5L12.08,19.92L4.16,12L12.08,4.08L13.5,5.5L8,11H20Z"/>
|
||||
</svg>
|
||||
Back to Blog
|
||||
</a>
|
||||
</div>
|
||||
```
|
||||
|
||||
## 📋 Content Guidelines
|
||||
|
||||
### Writing Style
|
||||
- Use clear, technical language suitable for developers
|
||||
- Include practical examples and code snippets
|
||||
- Focus on actionable content and real-world use cases
|
||||
- Keep sentences concise and scannable
|
||||
- Use bullet points and numbered lists for clarity
|
||||
|
||||
### Technical Content
|
||||
- Always include installation commands with proper syntax
|
||||
- Provide multiple installation methods (individual, global, bulk)
|
||||
- Show file structure after installation
|
||||
- Include component descriptions that highlight practical benefits
|
||||
- Use consistent command naming patterns
|
||||
|
||||
### SEO Optimization
|
||||
- **Title**: "How to use Claude Code with [Technology]"
|
||||
- **Meta Description**: Max 160 characters, include key terms
|
||||
- **Keywords**: Technology name, Claude Code, MCP, Agents, Commands, AI Development
|
||||
- **Headers**: Use proper H2, H3 hierarchy
|
||||
- **Alt Text**: Descriptive alt text for all images
|
||||
- **Internal Links**: Link to main site and other relevant articles
|
||||
- **Structured Data**: Include JSON-LD schema for articles
|
||||
|
||||
### Visual Assets Required
|
||||
1. **Cover Image**: 1200x630 pixels for social sharing
|
||||
2. **Hero Image**: Technology + Claude Code branded image
|
||||
3. **AITMPL Search Screenshot**: Show search results for the technology
|
||||
4. **Component Icons**: Use appropriate emojis (🤖 for agents, ⚡ for commands, 🔌 for MCP)
|
||||
|
||||
## 🔧 Technical Requirements
|
||||
|
||||
### File Naming Convention
|
||||
- **Slug**: `[technology-name]-claude-code-integration`
|
||||
- **Directory**: `docs/blog/[slug]/`
|
||||
- **Main File**: `index.html`
|
||||
- **Assets**: Use descriptive names with technology prefix
|
||||
|
||||
### Code Block Standards
|
||||
- Use `language-bash` for terminal commands
|
||||
- Include copy functionality (automatic via code-copy.js)
|
||||
- Clean terminal output (remove success messages and prompts)
|
||||
- Use proper syntax highlighting
|
||||
|
||||
### Responsive Design
|
||||
- All tables must be responsive
|
||||
- Images should have loading="lazy" attribute
|
||||
- Use relative paths for internal assets
|
||||
- Test on mobile and desktop viewports
|
||||
|
||||
## 📊 Component Data Requirements
|
||||
|
||||
Before writing an article, gather:
|
||||
|
||||
1. **Available Components**
|
||||
- List all commands for the technology
|
||||
- List all agents for the technology
|
||||
- Identify MCP server if available
|
||||
|
||||
2. **Installation Information**
|
||||
- Component file names
|
||||
- Installation directory structure
|
||||
- Example prompts for testing
|
||||
|
||||
3. **Category Information**
|
||||
- Primary category (Database, Frontend, Backend, etc.)
|
||||
- Secondary tags
|
||||
- Related technologies
|
||||
|
||||
## ✅ Pre-Publication Checklist
|
||||
|
||||
- [ ] All placeholders replaced with actual content
|
||||
- [ ] SEO meta tags completed
|
||||
- [ ] Images optimized and properly sized
|
||||
- [ ] Links tested (internal and external)
|
||||
- [ ] Code blocks tested for copy functionality
|
||||
- [ ] Mobile responsiveness verified
|
||||
- [ ] Structured data validated
|
||||
- [ ] Article added to blog index page
|
||||
- [ ] Social media preview tested
|
||||
|
||||
## 📈 Analytics & Performance
|
||||
|
||||
### Tracking
|
||||
- Article views and engagement will be tracked via existing analytics
|
||||
- Monitor social media sharing performance
|
||||
- Track component installation after article publication
|
||||
|
||||
### Success Metrics
|
||||
- Time on page > 3 minutes
|
||||
- Low bounce rate < 40%
|
||||
- High component installation conversion
|
||||
- Social media shares and engagement
|
||||
|
||||
This template ensures consistency across all technology integration articles while maintaining high SEO standards and user experience.
|
||||
@@ -0,0 +1,400 @@
|
||||
# Claude Code Data Structure Documentation
|
||||
|
||||
## Overview
|
||||
This document provides comprehensive information about the data structures and formats found in the `.claude` directory, used by Claude Code and the Analytics Dashboard.
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
~/.claude/
|
||||
├── projects/ # Project-specific conversations
|
||||
│ ├── -Users-user-Project1/
|
||||
│ │ ├── conversation.jsonl # Main conversation file
|
||||
│ │ └── settings.json # Project settings
|
||||
│ └── -Users-user-Project2/
|
||||
│ └── conversation.jsonl
|
||||
├── desktop/ # Claude Desktop app data
|
||||
├── statsig/ # Analytics and feature flags
|
||||
│ ├── logs/
|
||||
│ └── user_overrides.json
|
||||
└── settings.json # Global Claude Code settings
|
||||
```
|
||||
|
||||
## JSONL Conversation Format
|
||||
|
||||
### File Structure
|
||||
Each conversation is stored in a JSONL (JSON Lines) file where each line represents a single message or event.
|
||||
|
||||
### Message Types
|
||||
|
||||
#### 1. User Messages
|
||||
```json
|
||||
{
|
||||
"parentUuid": "previous-message-uuid",
|
||||
"isSidechain": false,
|
||||
"userType": "external",
|
||||
"cwd": "/Users/user/project-path",
|
||||
"sessionId": "ae93d7b5-1c54-4578-b208-603b48a88c5e",
|
||||
"version": "1.0.35",
|
||||
"type": "user",
|
||||
"message": {
|
||||
"role": "user",
|
||||
"content": "User's message text here"
|
||||
},
|
||||
"uuid": "6a8f4604-6fdd-406f-87d6-436e6cf26bd1",
|
||||
"timestamp": "2025-07-01T19:06:05.237Z"
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. Assistant Messages
|
||||
```json
|
||||
{
|
||||
"parentUuid": "6a8f4604-6fdd-406f-87d6-436e6cf26bd1",
|
||||
"isSidechain": false,
|
||||
"userType": "external",
|
||||
"cwd": "/Users/user/project-path",
|
||||
"sessionId": "ae93d7b5-1c54-4578-b208-603b48a88c5e",
|
||||
"version": "1.0.35",
|
||||
"message": {
|
||||
"id": "msg_016xDLMzLsNRmD5PsdEjPu3N",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"model": "claude-sonnet-4-20250514",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Assistant's response text"
|
||||
}
|
||||
],
|
||||
"stop_reason": null,
|
||||
"stop_sequence": null,
|
||||
"usage": {
|
||||
"input_tokens": 4,
|
||||
"cache_creation_input_tokens": 15116,
|
||||
"cache_read_input_tokens": 0,
|
||||
"output_tokens": 1,
|
||||
"service_tier": "standard"
|
||||
}
|
||||
},
|
||||
"requestId": "req_011CQgpcgetL2WTXxNz8FxVs",
|
||||
"type": "assistant",
|
||||
"uuid": "2f7d6c65-27a6-40b4-aa52-0fb8cad8f9a6",
|
||||
"timestamp": "2025-07-01T19:06:09.724Z"
|
||||
}
|
||||
```
|
||||
|
||||
#### 3. Tool Use Messages
|
||||
```json
|
||||
{
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "I'll help you with that task."
|
||||
},
|
||||
{
|
||||
"type": "tool_use",
|
||||
"id": "toolu_01A2B3C4D5E6F7G8H9I0J1K2",
|
||||
"name": "bash",
|
||||
"input": {
|
||||
"command": "ls -la"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 4. Tool Result Messages
|
||||
```json
|
||||
{
|
||||
"message": {
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "tool_result",
|
||||
"tool_use_id": "toolu_01A2B3C4D5E6F7G8H9I0J1K2",
|
||||
"content": "drwxr-xr-x 5 user staff 160 Jul 20 10:30 .\ndrwxr-xr-x 8 user staff 256 Jul 20 10:29 .."
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Field Definitions
|
||||
|
||||
### Root Level Fields
|
||||
| Field | Type | Description | Example |
|
||||
|-------|------|-------------|---------|
|
||||
| `uuid` | String | Unique identifier for this message | `"6a8f4604-6fdd-406f-87d6-436e6cf26bd1"` |
|
||||
| `parentUuid` | String/null | UUID of the previous message in conversation | `"previous-uuid"` or `null` |
|
||||
| `timestamp` | ISO String | When the message was created | `"2025-07-01T19:06:05.237Z"` |
|
||||
| `type` | String | Message type: `"user"` or `"assistant"` | `"user"` |
|
||||
| `sessionId` | String | Session identifier for the conversation | `"ae93d7b5-1c54-4578-b208-603b48a88c5e"` |
|
||||
| `version` | String | Claude Code version that created this message | `"1.0.35"` |
|
||||
| `cwd` | String | Current working directory when message was sent | `"/Users/user/project"` |
|
||||
| `userType` | String | Type of user: `"external"` (CLI) or other | `"external"` |
|
||||
| `isSidechain` | Boolean | Whether this is a sidechain conversation | `false` |
|
||||
| `requestId` | String | API request ID (assistant messages only) | `"req_011CQgpcgetL2WTXxNz8FxVs"` |
|
||||
|
||||
### Message Object Fields
|
||||
| Field | Type | Description | Example |
|
||||
|-------|------|-------------|---------|
|
||||
| `role` | String | `"user"` or `"assistant"` | `"assistant"` |
|
||||
| `id` | String | Message ID (assistant messages only) | `"msg_016xDLMzLsNRmD5PsdEjPu3N"` |
|
||||
| `type` | String | Always `"message"` for assistant messages | `"message"` |
|
||||
| `model` | String | AI model used (assistant messages only) | `"claude-sonnet-4-20250514"` |
|
||||
| `content` | String/Array | Message content (string for user, array for assistant) | See content formats below |
|
||||
| `stop_reason` | String/null | Why the assistant stopped generating | `null`, `"end_turn"`, `"max_tokens"` |
|
||||
| `stop_sequence` | String/null | Stop sequence that triggered end | `null` |
|
||||
| `usage` | Object | Token usage information | See usage object below |
|
||||
|
||||
### Content Formats
|
||||
|
||||
#### User Content (String)
|
||||
```json
|
||||
"content": "Simple text message from user"
|
||||
```
|
||||
|
||||
#### Assistant Content (Array of Blocks)
|
||||
```json
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Text response from assistant"
|
||||
},
|
||||
{
|
||||
"type": "tool_use",
|
||||
"id": "toolu_01A2B3C4D5E6F7G8H9I0J1K2",
|
||||
"name": "bash",
|
||||
"input": {
|
||||
"command": "ls -la",
|
||||
"description": "List directory contents"
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
#### Tool Result Content (Array)
|
||||
```json
|
||||
"content": [
|
||||
{
|
||||
"type": "tool_result",
|
||||
"tool_use_id": "toolu_01A2B3C4D5E6F7G8H9I0J1K2",
|
||||
"content": "Command output here...",
|
||||
"is_error": false
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### Usage Object (Token Information)
|
||||
```json
|
||||
"usage": {
|
||||
"input_tokens": 156, // Tokens in the input
|
||||
"output_tokens": 45, // Tokens in the output
|
||||
"cache_creation_input_tokens": 2048, // Tokens used to create cache
|
||||
"cache_read_input_tokens": 1024, // Tokens read from cache
|
||||
"service_tier": "standard" // Service tier: "standard" or "premium"
|
||||
}
|
||||
```
|
||||
|
||||
## Tool Types and Input Formats
|
||||
|
||||
### Available Tools
|
||||
1. **bash** - Execute shell commands
|
||||
2. **read** - Read file contents
|
||||
3. **write** - Write/create files
|
||||
4. **edit** - Edit existing files
|
||||
5. **glob** - File pattern matching
|
||||
6. **grep** - Search within files
|
||||
7. **ls** - List directory contents
|
||||
|
||||
### Tool Input Examples
|
||||
|
||||
#### Bash Tool
|
||||
```json
|
||||
{
|
||||
"type": "tool_use",
|
||||
"name": "bash",
|
||||
"input": {
|
||||
"command": "npm install --save express",
|
||||
"description": "Install Express.js package"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Read Tool
|
||||
```json
|
||||
{
|
||||
"type": "tool_use",
|
||||
"name": "read",
|
||||
"input": {
|
||||
"file_path": "/path/to/file.js",
|
||||
"limit": 100,
|
||||
"offset": 0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Write Tool
|
||||
```json
|
||||
{
|
||||
"type": "tool_use",
|
||||
"name": "write",
|
||||
"input": {
|
||||
"file_path": "/path/to/new-file.js",
|
||||
"content": "console.log('Hello World');"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Edit Tool
|
||||
```json
|
||||
{
|
||||
"type": "tool_use",
|
||||
"name": "edit",
|
||||
"input": {
|
||||
"file_path": "/path/to/file.js",
|
||||
"old_string": "const oldCode = 'old';",
|
||||
"new_string": "const newCode = 'new';",
|
||||
"replace_all": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Settings Files
|
||||
|
||||
## Message Flow and Relationships
|
||||
|
||||
### Conversation Threading
|
||||
Messages are linked through `parentUuid` fields:
|
||||
```
|
||||
Message 1 (uuid: A, parentUuid: null) # First message
|
||||
├── Message 2 (uuid: B, parentUuid: A) # Response to Message 1
|
||||
├── Message 3 (uuid: C, parentUuid: B) # Response to Message 2
|
||||
└── Message 4 (uuid: D, parentUuid: B) # Alternative response
|
||||
```
|
||||
|
||||
### Tool Use Flow
|
||||
```
|
||||
User Message → Assistant with Tool Use → Tool Result → Assistant Response
|
||||
↓ ↓ ↓ ↓
|
||||
uuid: A uuid: B uuid: C uuid: D
|
||||
parentUuid: null parentUuid: A parentUuid: B parentUuid: C
|
||||
```
|
||||
|
||||
## Analytics Data Extraction
|
||||
|
||||
### Extractable Metrics
|
||||
1. **Conversation Metrics**
|
||||
- Total messages per conversation
|
||||
- Message frequency over time
|
||||
- User vs Assistant message ratio
|
||||
- Tool usage patterns
|
||||
|
||||
2. **Token Usage**
|
||||
- Input/Output token consumption
|
||||
- Cache hit rates
|
||||
- Model usage patterns
|
||||
- Cost analysis
|
||||
|
||||
3. **Tool Analytics**
|
||||
- Most used tools
|
||||
- Tool success/error rates
|
||||
- Tool execution time (estimated)
|
||||
- File operation patterns
|
||||
|
||||
4. **Project Analytics**
|
||||
- Active projects
|
||||
- Project-specific usage patterns
|
||||
- File types being worked on
|
||||
- Development patterns
|
||||
|
||||
## Common Patterns and Edge Cases
|
||||
|
||||
### User Confirmation Messages
|
||||
User responses to Claude's prompts often appear as simple strings:
|
||||
```json
|
||||
{
|
||||
"message": {
|
||||
"role": "user",
|
||||
"content": "[ok]" // or "yes", "1", "y", etc.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Large Tool Results
|
||||
Long command outputs are stored as complete strings:
|
||||
```json
|
||||
{
|
||||
"type": "tool_result",
|
||||
"content": "Very long output that could be thousands of characters..."
|
||||
}
|
||||
```
|
||||
|
||||
### Error Messages
|
||||
Tool errors are marked with `is_error: true`:
|
||||
```json
|
||||
{
|
||||
"type": "tool_result",
|
||||
"tool_use_id": "toolu_xxx",
|
||||
"content": "bash: command not found: invalidcommand",
|
||||
"is_error": true
|
||||
}
|
||||
```
|
||||
|
||||
## Data Processing Notes
|
||||
|
||||
### Performance Considerations
|
||||
1. **File Sizes**: JSONL files can become large (100MB+) for long conversations
|
||||
2. **Parsing**: Each line must be parsed individually as valid JSON
|
||||
3. **Memory**: Large conversations should be streamed or paginated
|
||||
4. **Caching**: Parsed conversations should be cached to avoid re-parsing
|
||||
|
||||
### Data Validation
|
||||
1. **Required Fields**: Always check for required fields before processing
|
||||
2. **Timestamps**: Parse ISO strings carefully, handle timezone differences
|
||||
3. **Content Arrays**: Assistant messages may have mixed content types
|
||||
4. **UUIDs**: Validate UUID format for consistency checks
|
||||
|
||||
## Usage in Analytics Dashboard
|
||||
|
||||
### Current Implementation
|
||||
The analytics dashboard extracts the following data:
|
||||
```javascript
|
||||
// Simplified message object after parsing
|
||||
{
|
||||
id: item.message.id || item.uuid, // Message identifier
|
||||
role: item.message.role, // "user" or "assistant"
|
||||
timestamp: new Date(item.timestamp), // Parsed timestamp
|
||||
content: item.message.content, // Raw content
|
||||
model: item.message.model || null, // AI model used
|
||||
usage: item.message.usage || null, // Token usage
|
||||
}
|
||||
```
|
||||
|
||||
### Available Extensions
|
||||
With this data structure, the dashboard could be extended to show:
|
||||
- Conversation threading/branching
|
||||
- Tool usage analytics
|
||||
- Project-specific insights
|
||||
- Cost tracking per project
|
||||
- Development velocity metrics
|
||||
- Error rate analysis
|
||||
|
||||
## File System Integration
|
||||
|
||||
### Directory Monitoring
|
||||
Watch for changes in:
|
||||
- `~/.claude/projects/*/conversation.jsonl` - New messages
|
||||
- `~/.claude/projects/` - New projects
|
||||
- `~/.claude/settings.json` - Setting changes
|
||||
|
||||
### File Reading Strategies
|
||||
1. **Tail Reading**: Read only new lines from JSONL files
|
||||
2. **Full Parse**: Parse entire file for complete analysis
|
||||
3. **Chunk Processing**: Process large files in smaller chunks
|
||||
4. **Incremental Updates**: Track file modification times
|
||||
|
||||
This documentation provides a complete reference for working with Claude Code data structures and can be updated as new formats or features are discovered.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,154 @@
|
||||
# Conversation State Detection - Improvements Implemented
|
||||
|
||||
## Overview
|
||||
|
||||
Successfully enhanced the conversation state banner (`#conversation-state-banner`) system to provide more intelligent and real-time state detection based on WebSocket messages, file changes, and content analysis.
|
||||
|
||||
## Key Improvements
|
||||
|
||||
### 1. Enhanced Frontend Message Analysis ✅
|
||||
|
||||
**File:** `src/analytics-web/components/AgentsPage.js:199-300`
|
||||
|
||||
**Improvements:**
|
||||
- **Tool Execution Detection**: Distinguishes between different tool types (bash, edit, read, grep)
|
||||
- **Content Analysis**: Analyzes message text for intent keywords (`let me`, `analyzing`, `completed`, etc.)
|
||||
- **Time-aware Logic**: Uses message timestamps for more accurate state determination
|
||||
- **Error Detection**: Identifies error states from message content
|
||||
|
||||
**New States Added:**
|
||||
- `Analyzing code...` - When Claude examines files
|
||||
- `Task completed` - When Claude indicates completion
|
||||
- `Processing request...` - For complex ongoing requests
|
||||
- `Encountered issue` - When errors are detected
|
||||
|
||||
### 2. File Activity Detection for Typing ✅
|
||||
|
||||
**File:** `src/analytics/core/FileWatcher.js:165-250`
|
||||
|
||||
**New Features:**
|
||||
- **File Size Monitoring**: Tracks file size changes to detect typing activity
|
||||
- **Timing Analysis**: Uses file modification timestamps to identify user vs Claude activity
|
||||
- **Debounced Detection**: Waits 2 seconds after file changes to confirm typing vs completed messages
|
||||
- **Smart Differentiation**: Distinguishes between user typing and Claude writing
|
||||
|
||||
**Logic:**
|
||||
```javascript
|
||||
// File changed → Track size/timestamp → Wait 2s → Check if complete message added
|
||||
// If no new message but file activity after Assistant message → "User typing..."
|
||||
```
|
||||
|
||||
### 3. WebSocket-First Approach ✅
|
||||
|
||||
**Integration Points:**
|
||||
- Real-time message analysis via `handleNewMessage()`
|
||||
- Intelligent state calculation in `analyzeMessageForState()`
|
||||
- Immediate state banner updates without polling delays
|
||||
- File activity notifications through WebSocket
|
||||
|
||||
### 4. Enhanced State Vocabulary ✅
|
||||
|
||||
**Before:** Limited to basic states (working, waiting, idle)
|
||||
|
||||
**After:** Comprehensive state detection:
|
||||
|
||||
| State | Trigger | Visual |
|
||||
|-------|---------|--------|
|
||||
| `Claude Code working...` | User sent message or Claude indicates work | 🤖 Blue pulse |
|
||||
| `Executing tools...` | Tool use without results | 🔧 Green pulse |
|
||||
| `Analyzing results...` | Tool use with results | 📊 Purple pulse |
|
||||
| `Analyzing code...` | Read/grep tools | 🔍 Purple pulse |
|
||||
| `Task completed` | Completion keywords | ✅ Green solid |
|
||||
| `Processing request...` | Complex ongoing work | ⚙️ Blue pulse |
|
||||
| `Encountered issue` | Error keywords | ⚠️ Red pulse |
|
||||
| `User typing...` | File activity after assistant message | ✍️ Yellow pulse |
|
||||
| `Awaiting user input...` | Questions or prompts | 💬 Blue solid |
|
||||
|
||||
### 5. Improved State Banner Display ✅
|
||||
|
||||
**File:** `src/analytics-web/index.html:4265-4285`
|
||||
|
||||
**New CSS Classes:**
|
||||
- `.status-completed` - Green solid for completed tasks
|
||||
- `.status-processing` - Blue pulse for ongoing work
|
||||
- `.status-error` - Red pulse for errors
|
||||
|
||||
### 6. System Integration ✅
|
||||
|
||||
**File:** `src/analytics.js:1177`
|
||||
|
||||
**Connected Components:**
|
||||
- FileWatcher ↔ NotificationManager for typing detection
|
||||
- WebSocket notifications for real-time state updates
|
||||
- Frontend analysis with backend file monitoring
|
||||
|
||||
## Technical Flow
|
||||
|
||||
### Real-time Message Detection
|
||||
```
|
||||
User/Claude adds message → File change detected → WebSocket notification sent →
|
||||
Frontend analyzes message content → Intelligent state determined → Banner updated
|
||||
```
|
||||
|
||||
### Typing Detection
|
||||
```
|
||||
User starts typing → File size changes → FileWatcher detects activity →
|
||||
Wait 2s for complete message → If no new message after assistant response →
|
||||
"User typing..." notification sent → Banner shows typing state
|
||||
```
|
||||
|
||||
### State Transition Logic
|
||||
```
|
||||
User message → "Claude Code working..." → Tool execution → "Executing tools..." →
|
||||
Tool results → "Analyzing results..." → Text response → Content analysis →
|
||||
Final state ("Task completed", "Awaiting user input...", etc.)
|
||||
```
|
||||
|
||||
## Performance Improvements
|
||||
|
||||
### Reduced Latency
|
||||
- **Before:** File-based polling every few seconds
|
||||
- **After:** WebSocket real-time updates (< 100ms)
|
||||
|
||||
### Smarter Detection
|
||||
- **Before:** Time-based assumptions (5min = typing)
|
||||
- **After:** Content and activity-based analysis
|
||||
|
||||
### Better User Experience
|
||||
- **Before:** Generic states, delayed updates
|
||||
- **After:** Specific context-aware states, instant updates
|
||||
|
||||
## Testing Results
|
||||
|
||||
✅ **WebSocket Connection**: Successfully established, subscriptions working
|
||||
✅ **File Monitoring**: Detects changes in `~/.claude/projects/*/conversation.jsonl`
|
||||
✅ **State Analysis**: New message analysis logic working
|
||||
✅ **CSS Styling**: New state classes displaying correctly
|
||||
✅ **Integration**: FileWatcher connected to NotificationManager
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
### Potential Additions
|
||||
1. **Conversation Context Memory**: Remember conversation flow for better state prediction
|
||||
2. **User Interaction Detection**: Detect Yes/No prompts and user responses
|
||||
3. **Advanced Typing Indicators**: Show typing duration and intensity
|
||||
4. **State History**: Track state transitions for debugging
|
||||
5. **Customizable States**: Allow users to configure state detection rules
|
||||
|
||||
## Implementation Status
|
||||
|
||||
🟢 **Phase 1**: Enhanced WebSocket message analysis - **COMPLETED**
|
||||
🟢 **Phase 2**: File activity detection for typing - **COMPLETED**
|
||||
🟢 **Phase 3**: Improved state vocabulary and styling - **COMPLETED**
|
||||
🟢 **Phase 4**: System integration and testing - **COMPLETED**
|
||||
|
||||
## Summary
|
||||
|
||||
The conversation state detection system has been significantly improved with:
|
||||
- **8 new intelligent states** based on content analysis
|
||||
- **Real-time file activity monitoring** for typing detection
|
||||
- **WebSocket-first approach** for instant updates
|
||||
- **Enhanced visual feedback** with appropriate animations
|
||||
- **Robust error handling** and fallback mechanisms
|
||||
|
||||
The system now provides much more accurate and responsive conversation state information, greatly improving the user experience for monitoring Claude Code sessions.
|
||||
@@ -0,0 +1,95 @@
|
||||
# Debug: "User typing..." Detection
|
||||
|
||||
## 🔍 Análisis del Problema
|
||||
|
||||
Cuando tú escribes, aparecen logs pero no se muestra "User typing..." en pantalla. Hay **3 sistemas** diferentes que pueden detectar typing:
|
||||
|
||||
### 1. **Frontend Timeout System** (AgentsPage.js)
|
||||
```javascript
|
||||
// Después de mensaje de Assistant → 30s timeout → "User typing..."
|
||||
this.checkForUserTyping(conversationId);
|
||||
```
|
||||
|
||||
### 2. **Backend File Activity** (FileWatcher.js)
|
||||
```javascript
|
||||
// Detecta cambios en ~/.claude/projects/*/conversation.jsonl
|
||||
this.checkForTypingActivity(conversationId, filePath);
|
||||
```
|
||||
|
||||
### 3. **Backend State Calculator** (StateCalculator.js)
|
||||
```javascript
|
||||
// Lógica temporal basada en tiempo transcurrido
|
||||
return 'User typing...';
|
||||
```
|
||||
|
||||
## 🧪 Test de Debug
|
||||
|
||||
### Paso 1: Verificar Logs en Consola del Navegador
|
||||
Abre DevTools (F12) → Console y busca:
|
||||
```
|
||||
🔍 Checking typing for [conversationId]: Xs since last message
|
||||
⏰ 30s timeout triggered for [conversationId]
|
||||
✍️ FRONTEND: Setting User typing state for [conversationId]
|
||||
```
|
||||
|
||||
### Paso 2: Verificar Logs del Server
|
||||
En la terminal donde corre `npm run analytics:start`, busca:
|
||||
```
|
||||
✍️ Potential typing activity detected for [conversationId]
|
||||
📨 Handling conversation change: [conversationId]
|
||||
```
|
||||
|
||||
### Paso 3: Verificar Estado Actual
|
||||
En consola del navegador, ejecuta:
|
||||
```javascript
|
||||
// Ver estado actual del conversation banner
|
||||
document.querySelector('#state-text').textContent
|
||||
|
||||
// Ver timeouts activos
|
||||
window.app.components.agents.typingTimeouts.size
|
||||
|
||||
// Ver último tiempo de mensaje
|
||||
window.app.components.agents.lastMessageTime
|
||||
```
|
||||
|
||||
## 🔧 Test Manual
|
||||
|
||||
1. **Envía un mensaje como usuario** → Banner debe mostrar "Claude Code working..."
|
||||
2. **Claude responde** → Banner debe mostrar estado basado en contenido
|
||||
3. **Espera 30 segundos SIN escribir nada** → Banner debe cambiar a "User typing..."
|
||||
4. **Empieza a escribir** → Verifica logs en ambos lados
|
||||
5. **Envía mensaje** → Banner debe cambiar inmediatamente a "Claude Code working..."
|
||||
|
||||
## 🐛 Posibles Problemas
|
||||
|
||||
### A. **Estados Sobrescritos**
|
||||
- Backend StateCalculator puede estar sobrescribiendo estado frontend
|
||||
- WebSocket `conversation_state_change` puede resetear el estado
|
||||
|
||||
### B. **Timing Conflicts**
|
||||
- Frontend timeout (30s) vs Backend file detection (2s)
|
||||
- Múltiples fuentes de verdad para el mismo estado
|
||||
|
||||
### C. **Conversation Selection**
|
||||
- Estado solo se muestra si `this.selectedConversationId === conversationId`
|
||||
- Verificar que la conversación correcta está seleccionada
|
||||
|
||||
## 🔍 Debug Steps Agregados
|
||||
|
||||
Agregué logs específicos:
|
||||
```javascript
|
||||
console.log('⏱️ Setting 30s timeout for typing detection: ${conversationId}');
|
||||
console.log('⏰ 30s timeout triggered for ${conversationId}');
|
||||
console.log('🔍 Checking typing for ${conversationId}: ${timeSinceLastMessage}s');
|
||||
console.log('✍️ FRONTEND: Setting User typing state for ${conversationId}');
|
||||
```
|
||||
|
||||
## ▶️ Próximos Pasos
|
||||
|
||||
1. **Ejecuta nuevamente** `npm run analytics:start`
|
||||
2. **Haz una conversación** con Claude
|
||||
3. **Espera 30+ segundos** después de que Claude responda
|
||||
4. **Verifica logs** tanto en navegador como en terminal
|
||||
5. **Reporta** qué logs ves y si aparece el estado
|
||||
|
||||
¿Qué logs específicos estás viendo cuando escribes?
|
||||
@@ -0,0 +1,291 @@
|
||||
# Download Tracking System
|
||||
|
||||
Sistema de seguimiento de descargas anónimo para Claude Code Templates, inspirado en npm analytics.
|
||||
|
||||
## Descripción
|
||||
|
||||
Este sistema rastrea las descargas e instalaciones de componentes de forma completamente anónima para:
|
||||
- Identificar los componentes más populares
|
||||
- Mejorar la calidad de los componentes más utilizados
|
||||
- Entender patrones de uso para desarrollo futuro
|
||||
- Proporcionar estadísticas públicas similares a npm
|
||||
|
||||
## Arquitectura
|
||||
|
||||
### Backend (Vercel + Supabase)
|
||||
|
||||
1. **API Endpoint**: `/api/track-download-supabase.js`
|
||||
- Recibe requests POST con datos de descarga
|
||||
- Valida y almacena en Supabase (PostgreSQL)
|
||||
- Maneja rate limiting y validaciones
|
||||
|
||||
2. **Base de Datos**:
|
||||
```sql
|
||||
-- Tabla principal de descargas
|
||||
component_downloads (
|
||||
id, component_type, component_name, component_path,
|
||||
category, download_timestamp, user_agent, ip_address,
|
||||
country, cli_version, created_at
|
||||
)
|
||||
|
||||
-- Tabla de estadísticas agregadas
|
||||
download_stats (
|
||||
id, component_type, component_name, total_downloads,
|
||||
last_download, created_at, updated_at
|
||||
)
|
||||
```
|
||||
|
||||
### Cliente (CLI)
|
||||
|
||||
1. **TrackingService**: Maneja el envío de datos
|
||||
- Dual endpoint: Base de datos + telemetría
|
||||
- Fire-and-forget (no bloquea al usuario)
|
||||
- Respeta opt-out del usuario
|
||||
- Timeout de 5 segundos
|
||||
|
||||
2. **Integración**: Se ejecuta automáticamente en:
|
||||
- `--agent`, `--command`, `--mcp`, `--setting`, `--hook`
|
||||
- Instalaciones de templates
|
||||
- Health checks
|
||||
- Lanzamientos de analytics dashboard
|
||||
|
||||
## Datos Recopilados
|
||||
|
||||
### Información Anónima
|
||||
- **Tipo de componente**: agent, command, mcp, setting, hook
|
||||
- **Nombre del componente**: ej. "api-security-audit"
|
||||
- **Categoría**: ej. "security", "testing", "automation"
|
||||
- **Timestamp**: Momento de instalación
|
||||
- **Plataforma**: OS (linux, darwin, win32)
|
||||
- **Versión CLI**: Para compatibilidad
|
||||
- **País**: Solo código de 2 letras (IP geolocation)
|
||||
|
||||
### NO se Recopila
|
||||
- ❌ Información personal identificable
|
||||
- ❌ Nombres de usuario
|
||||
- ❌ Rutas completas de archivos
|
||||
- ❌ Contenido de proyectos
|
||||
- ❌ Tokens o credenciales
|
||||
|
||||
## Configuración
|
||||
|
||||
### Variables de Entorno
|
||||
|
||||
```bash
|
||||
# Desactivar tracking completamente
|
||||
export CCT_NO_TRACKING=true
|
||||
export CCT_NO_ANALYTICS=true
|
||||
|
||||
# Modo debug (mostrar info de tracking)
|
||||
export CCT_DEBUG=true
|
||||
|
||||
# Base de datos (Supabase)
|
||||
export SUPABASE_URL="https://..."
|
||||
export SUPABASE_SERVICE_ROLE_KEY="..."
|
||||
```
|
||||
|
||||
### Opt-out del Usuario
|
||||
|
||||
El tracking se desactiva automáticamente si:
|
||||
- `CCT_NO_TRACKING=true`
|
||||
- `CCT_NO_ANALYTICS=true`
|
||||
- `CI=true` (entornos CI/CD)
|
||||
|
||||
## Desarrollo
|
||||
|
||||
### Setup Local
|
||||
|
||||
1. Instalar dependencias:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
2. Configurar Vercel:
|
||||
```bash
|
||||
# Instalar Vercel CLI
|
||||
npm i -g vercel
|
||||
|
||||
# Configurar proyecto
|
||||
vercel
|
||||
```
|
||||
|
||||
3. Configurar base de datos (Supabase):
|
||||
```bash
|
||||
# Crear proyecto en Supabase
|
||||
# Copiar SUPABASE_URL y SUPABASE_SERVICE_ROLE_KEY
|
||||
# Agregar variables de entorno en Vercel Dashboard
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
```bash
|
||||
# Test local con CLI
|
||||
CCT_DEBUG=true node cli-tool/bin/create-claude-config.js --agent deep-research-team/academic-researcher
|
||||
|
||||
# Test sin tracking (simula opt-out)
|
||||
CCT_NO_TRACKING=true node cli-tool/bin/create-claude-config.js --agent test-agent
|
||||
|
||||
# Test directo al API
|
||||
curl -X POST https://www.aitmpl.com/api/track-download-supabase \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"type":"agent","name":"test","path":"test","category":"test","cliVersion":"1.19.0"}'
|
||||
```
|
||||
|
||||
### Deployment
|
||||
|
||||
```bash
|
||||
# Deploy a Vercel
|
||||
vercel --prod
|
||||
|
||||
# Verificar endpoints
|
||||
curl -X POST https://tu-dominio.com/api/track-download-supabase \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"type":"agent","name":"test","path":"test","category":"test","cliVersion":"1.19.0"}'
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### POST /api/track-download-supabase
|
||||
|
||||
**Request Body:**
|
||||
```json
|
||||
{
|
||||
"type": "agent|command|mcp|setting|hook|template",
|
||||
"name": "component-name",
|
||||
"path": "optional/component/path",
|
||||
"category": "component-category",
|
||||
"cliVersion": "1.0.0"
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Download tracked successfully",
|
||||
"data": {
|
||||
"type": "agent",
|
||||
"name": "component-name",
|
||||
"timestamp": "2023-12-07T10:30:00.000Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Error Response:**
|
||||
```json
|
||||
{
|
||||
"error": "Bad Request",
|
||||
"message": "Component type and name are required"
|
||||
}
|
||||
```
|
||||
|
||||
## Monitoreo
|
||||
|
||||
### Health Check
|
||||
|
||||
```bash
|
||||
# Verificar salud del API
|
||||
curl https://tu-dominio.com/api/track-download
|
||||
```
|
||||
|
||||
### Métricas
|
||||
|
||||
El sistema proporciona métricas para:
|
||||
- Total de descargas por componente
|
||||
- Tendencias de popularidad
|
||||
- Distribución geográfica
|
||||
- Versiones de CLI más usadas
|
||||
- Patrones temporales de uso
|
||||
|
||||
### Logs
|
||||
|
||||
Los logs incluyen:
|
||||
- Requests exitosos/fallidos
|
||||
- Errores de validación
|
||||
- Problemas de conectividad a BD
|
||||
- Rate limiting activado
|
||||
|
||||
## Seguridad
|
||||
|
||||
### Protecciones Implementadas
|
||||
|
||||
1. **Rate Limiting**: Por IP y por endpoint
|
||||
2. **Validación de Input**: Sanitización de todos los campos
|
||||
3. **Timeout**: 5s máximo por request
|
||||
4. **CORS**: Headers configurados apropiadamente
|
||||
5. **SQL Injection**: Queries parametrizadas
|
||||
6. **Privacy**: No PII, solo métricas agregadas
|
||||
|
||||
### Compliance
|
||||
|
||||
- **GDPR**: No se almacenan datos personales identificables
|
||||
- **CCPA**: Sistema completamente anónimo
|
||||
- **Opt-out**: Múltiples formas de desactivar tracking
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Problemas Comunes
|
||||
|
||||
1. **Tracking no funciona**:
|
||||
- Verificar conectividad de red
|
||||
- Comprobar variables de entorno
|
||||
- Revisar logs con `CCT_DEBUG=true`
|
||||
|
||||
2. **Base de datos no responde**:
|
||||
- Verificar `POSTGRES_URL`
|
||||
- Comprobar límites de conexión
|
||||
- Revisar logs de Vercel
|
||||
|
||||
3. **Rate limiting activo**:
|
||||
- Espaciar requests
|
||||
- Implementar backoff exponencial
|
||||
- Contactar soporte si persiste
|
||||
|
||||
### Debugging
|
||||
|
||||
```bash
|
||||
# Debug completo
|
||||
CCT_DEBUG=true node cli-tool/src/index.js --agent api-security-audit
|
||||
|
||||
# Solo tracking de base de datos
|
||||
# (modificar código temporalmente)
|
||||
|
||||
# Verificar payload
|
||||
console.log(JSON.stringify(payload, null, 2))
|
||||
```
|
||||
|
||||
## Roadmap
|
||||
|
||||
### Próximas Features
|
||||
|
||||
1. **Dashboard Público**: Estadísticas en tiempo real
|
||||
2. **API Pública**: Endpoint para consultar métricas
|
||||
3. **Webhooks**: Notificaciones de descargas populares
|
||||
4. **ML Insights**: Recomendaciones basadas en patrones
|
||||
5. **Retention Analytics**: Análisis de uso continuado
|
||||
|
||||
### Mejoras Técnicas
|
||||
|
||||
1. **Caching**: Redis para requests frecuentes
|
||||
2. **CDN**: Distribución geográfica
|
||||
3. **Monitoring**: Alertas y métricas avanzadas
|
||||
4. **Backup**: Replicación de base de datos
|
||||
5. **Performance**: Optimización de queries
|
||||
|
||||
## Contribuir
|
||||
|
||||
1. Fork el repositorio
|
||||
2. Crear branch: `git checkout -b feature/tracking-improvement`
|
||||
3. Commit cambios: `git commit -m 'Add tracking feature'`
|
||||
4. Push branch: `git push origin feature/tracking-improvement`
|
||||
5. Crear Pull Request
|
||||
|
||||
## Licencia
|
||||
|
||||
MIT License - Ver [LICENSE](LICENSE) para detalles.
|
||||
|
||||
## Contacto
|
||||
|
||||
- Issues: [GitHub Issues](https://github.com/davila7/claude-code-templates/issues)
|
||||
- Discussions: [GitHub Discussions](https://github.com/davila7/claude-code-templates/discussions)
|
||||
- Email: soporte@claude-code-templates.com
|
||||
@@ -0,0 +1,122 @@
|
||||
# Enhanced Real-time State Detection - v2.0
|
||||
|
||||
## 🚀 Mejoras Implementadas
|
||||
|
||||
### 1. **Transiciones de Estado Inmediatas**
|
||||
|
||||
**Flujo Optimizado:**
|
||||
```javascript
|
||||
Mensaje del Usuario aparece en WebSocket → INMEDIATAMENTE "Claude Code working..."
|
||||
Mensaje de Claude aparece en WebSocket → Analizar contenido → Estado específico
|
||||
```
|
||||
|
||||
**Ventajas:**
|
||||
- ✅ **Latencia eliminada**: Estado cambia al mismo tiempo que aparece el mensaje
|
||||
- ✅ **Precisión total**: Basado en mensajes reales, no estimaciones temporales
|
||||
- ✅ **Experiencia fluida**: El usuario ve feedback instantáneo
|
||||
|
||||
### 2. **Detección de Herramientas Mejorada**
|
||||
|
||||
**Nuevos Estados Específicos:**
|
||||
- `🔧 Executing tools...` - bash, edit, write, multiedit
|
||||
- `🔍 Analyzing code...` - read, grep, glob, task
|
||||
- `🌐 Fetching data...` - webfetch, websearch
|
||||
- `📊 Analyzing results...` - cuando tools tienen resultados
|
||||
|
||||
### 3. **Sistema de Timing Inteligente**
|
||||
|
||||
**Features Añadidos:**
|
||||
- Tracking de tiempo entre mensajes por conversación
|
||||
- Timeouts para detectar cuando usuario podría estar escribiendo
|
||||
- Limpieza automática de timeouts al llegar nuevos mensajes
|
||||
|
||||
### 4. **Detección de Escritura Predictiva**
|
||||
|
||||
**Lógica:**
|
||||
```javascript
|
||||
Mensaje de Assistant → Esperar 30 segundos →
|
||||
Si no hay nuevo mensaje del usuario → "User typing..."
|
||||
```
|
||||
|
||||
## 🔄 Flujos de Estado Mejorados
|
||||
|
||||
### Flujo 1: Usuario Envía Mensaje
|
||||
```
|
||||
1. Usuario escribe y envía mensaje
|
||||
2. Mensaje aparece vía WebSocket → INMEDIATAMENTE "Claude Code working..."
|
||||
3. Claude responde con herramientas → "Executing tools..." / "Analyzing code..."
|
||||
4. Herramientas completan → "Analyzing results..."
|
||||
5. Claude responde con texto → Análisis de contenido → Estado final
|
||||
```
|
||||
|
||||
### Flujo 2: Detección de Escritura
|
||||
```
|
||||
1. Claude termina de responder → Estado basado en contenido
|
||||
2. Timer de 30s se activa
|
||||
3. Si no llega mensaje del usuario → "User typing..."
|
||||
4. Al llegar mensaje del usuario → Reinicia el ciclo
|
||||
```
|
||||
|
||||
### Flujo 3: Estados Contextuales
|
||||
```
|
||||
- "Task completed" cuando mensaje incluye "completed", "finished", "done"
|
||||
- "Encountered issue" cuando mensaje incluye "error", "failed", "problem"
|
||||
- "Awaiting user input..." cuando mensaje termina en "?" o incluye "should i", "would you like"
|
||||
```
|
||||
|
||||
## 💡 Beneficios Clave
|
||||
|
||||
### Para el Usuario:
|
||||
1. **Feedback Instantáneo**: Sabe inmediatamente cuando Claude empieza a trabajar
|
||||
2. **Estados Específicos**: Entiende exactamente qué está haciendo Claude
|
||||
3. **Detección de Escritura**: El sistema reconoce cuando está pensando/escribiendo
|
||||
|
||||
### Técnicos:
|
||||
1. **WebSocket-First**: Aprovecha al máximo la comunicación en tiempo real
|
||||
2. **Eliminación de Polling**: No más estimaciones temporales imprecisas
|
||||
3. **Detección Basada en Contenido**: Estados determinados por el contenido real de los mensajes
|
||||
|
||||
## 🧪 Casos de Prueba
|
||||
|
||||
### Test 1: Usuario Envía Mensaje
|
||||
- ✅ Banner cambia inmediatamente a "Claude Code working..."
|
||||
- ✅ Si Claude usa herramientas, estado cambia a "Executing tools..."
|
||||
- ✅ Al completarse, cambia a estado basado en respuesta
|
||||
|
||||
### Test 2: Herramientas Específicas
|
||||
- ✅ `bash` commands → "Executing tools..."
|
||||
- ✅ `read`, `grep` → "Analyzing code..."
|
||||
- ✅ `webfetch` → "Fetching data..."
|
||||
|
||||
### Test 3: Estados Contextuales
|
||||
- ✅ Mensajes con "let me", "i'll" → "Claude Code working..."
|
||||
- ✅ Mensajes con "completed" → "Task completed"
|
||||
- ✅ Mensajes con "?" → "Awaiting user input..."
|
||||
|
||||
### Test 4: Detección de Escritura
|
||||
- ✅ Después de respuesta de Claude, esperar 30s → "User typing..."
|
||||
- ✅ Al enviar mensaje, inmediatamente → "Claude Code working..."
|
||||
|
||||
## 🔍 Debugging y Logs
|
||||
|
||||
### Logs Añadidos:
|
||||
```javascript
|
||||
console.log('⚡ User message detected - Claude starting work immediately');
|
||||
console.log('🤖 Assistant message detected - state: ${intelligentState}');
|
||||
console.log('🔧 Tools detected: ${toolNames} - showing execution state');
|
||||
console.log('✍️ Potential user typing detected for ${conversationId}');
|
||||
```
|
||||
|
||||
### Monitoreo:
|
||||
- Tiempos de mensaje por conversación
|
||||
- Estados de timeout activos
|
||||
- Transiciones de estado en tiempo real
|
||||
|
||||
## 📈 Próximas Mejoras Posibles
|
||||
|
||||
1. **Detección de Pausa en Escritura**: Detectar cuando usuario para de escribir temporalmente
|
||||
2. **Estados Progresivos**: Mostrar progreso dentro de operaciones largas
|
||||
3. **Contexto de Conversación**: Recordar el flujo completo para mejores predicciones
|
||||
4. **Personalización**: Permitir al usuario ajustar timeouts y sensibilidad
|
||||
|
||||
El sistema ahora ofrece una experiencia mucho más responsiva y precisa para el monitoreo de estados de conversación en tiempo real.
|
||||
@@ -0,0 +1,135 @@
|
||||
# Health Check Implementation
|
||||
|
||||
## ✅ Implementation Complete
|
||||
|
||||
A comprehensive Health Check feature has been successfully implemented for the Claude Code CLI tool, exactly as specified in the requirements.
|
||||
|
||||
## 🎯 Key Features Implemented
|
||||
|
||||
### 1. Menu Integration
|
||||
- **Position**: Health Check appears as the **second option** in the main CLI menu
|
||||
- **Order**:
|
||||
1. 📊 Analytics Dashboard
|
||||
2. 🔍 **Health Check** ← NEW
|
||||
3. ⚙️ Project Setup
|
||||
|
||||
### 2. CLI Command Aliases
|
||||
All specified command aliases work correctly:
|
||||
- `claude-code-templates --health-check`
|
||||
- `claude-code-templates --health`
|
||||
- `claude-code-templates --check`
|
||||
- `claude-code-templates --verify`
|
||||
|
||||
### 3. Comprehensive System Verification
|
||||
|
||||
#### System Requirements ✅
|
||||
- **Operating System**: Validates macOS 10.15+, Ubuntu 20.04+, Windows 10+
|
||||
- **Node.js Version**: Checks for Node.js 18+ requirement
|
||||
- **Memory**: Validates 4GB+ RAM availability
|
||||
- **Network**: Tests connectivity to Anthropic API
|
||||
- **Shell Environment**: Detects Bash/Zsh/Fish compatibility
|
||||
|
||||
#### Claude Code Setup ✅
|
||||
- **Installation**: Detects local and global Claude Code installations
|
||||
- **Authentication**: Checks for authentication indicators
|
||||
- **Auto-updates**: Validates update configuration
|
||||
- **Permissions**: Verifies Claude directory permissions
|
||||
|
||||
#### Project Configuration ✅
|
||||
- **Project Structure**: Validates project indicators (package.json, .git, etc.)
|
||||
- **Configuration Files**: Checks for .claude/ directory and contents
|
||||
|
||||
#### Custom Slash Commands ✅
|
||||
- **Project Commands**: Scans `.claude/commands/` directory
|
||||
- **Personal Commands**: Scans `~/.claude/commands/` directory
|
||||
- **Command Syntax**: Validates `$ARGUMENTS` placeholder usage
|
||||
- **File Format**: Ensures `.md` file format compliance
|
||||
|
||||
#### Hooks Configuration ✅
|
||||
- **User Hooks**: Validates `~/.claude/settings.json`
|
||||
- **Project Hooks**: Validates `.claude/settings.json`
|
||||
- **Local Hooks**: Validates `.claude/settings.local.json`
|
||||
- **JSON Syntax**: Checks for valid JSON structure
|
||||
- **Hook Commands**: Validates command paths and executability
|
||||
- **MCP Hooks**: Detects MCP tool hooks patterns
|
||||
|
||||
## 🎨 Output Format
|
||||
|
||||
The health check displays results in organized, color-coded tables:
|
||||
|
||||
```
|
||||
┌───────────────────────┐
|
||||
│ SYSTEM REQUIREMENTS │
|
||||
└───────────────────────┘
|
||||
✅ Operating System │ macOS 24.4.0 (compatible)
|
||||
✅ Node.js Version │ v20.10.0 (compatible)
|
||||
✅ Memory Available │ 16.0GB total, 0.1GB free (sufficient)
|
||||
✅ Network Connection │ Connected to Anthropic API
|
||||
✅ Shell Environment │ zsh (excellent autocompletion support)
|
||||
|
||||
┌─────────────────────┐
|
||||
│ CLAUDE CODE SETUP │
|
||||
└─────────────────────┘
|
||||
✅ Installation │ 1.0.44 (Claude Code) (globally installed)
|
||||
⚠️ Authentication │ Authentication not verified (may need to login)
|
||||
✅ Auto-updates │ Auto-updates assumed enabled
|
||||
✅ Permissions │ Claude directory permissions OK
|
||||
|
||||
📊 Health Score: 10/19 checks passed (53%)
|
||||
|
||||
💡 Recommendations:
|
||||
• Consider switching to Zsh for better autocompletion and features
|
||||
• Add $ARGUMENTS placeholder to command files for proper parameter handling
|
||||
• Fix JSON syntax error in .claude/settings.local.json
|
||||
```
|
||||
|
||||
## 🔍 Status Indicators
|
||||
|
||||
- ✅ **Pass**: Feature working correctly
|
||||
- ⚠️ **Warning**: Feature present but could be improved
|
||||
- ❌ **Fail**: Feature missing or broken
|
||||
|
||||
## 📊 Health Score Calculation
|
||||
|
||||
- Displays ratio of passed checks to total checks
|
||||
- Calculates percentage score
|
||||
- Provides actionable recommendations
|
||||
- Offers to run Project Setup if score is low
|
||||
|
||||
## 🔄 Integration with Existing Flow
|
||||
|
||||
- Health Check seamlessly integrates with existing CLI structure
|
||||
- After health check, users can choose to run Project Setup
|
||||
- Maintains consistent visual style with existing CLI
|
||||
- Preserves all existing functionality
|
||||
|
||||
## 🧪 Testing Validated
|
||||
|
||||
- ✅ All individual health check functions work correctly
|
||||
- ✅ Menu positioning verified as second option
|
||||
- ✅ CLI command aliases all functional
|
||||
- ✅ Output formatting displays properly
|
||||
- ✅ Integration with existing code structure confirmed
|
||||
- ✅ Error handling works as expected
|
||||
|
||||
## 📁 Files Modified
|
||||
|
||||
1. **`src/health-check.js`** - New module with HealthChecker class
|
||||
2. **`src/index.js`** - Updated main menu and added health check handling
|
||||
3. **`bin/create-claude-config.js`** - Added CLI command aliases
|
||||
|
||||
## 🚀 Ready for Production
|
||||
|
||||
The Health Check feature is fully implemented, tested, and ready for use. It provides exactly the functionality specified in the requirements:
|
||||
|
||||
- ✅ Positioned as second menu option
|
||||
- ✅ Comprehensive system verification
|
||||
- ✅ Claude Code configuration validation
|
||||
- ✅ Project setup verification
|
||||
- ✅ Custom commands validation
|
||||
- ✅ Hooks configuration verification
|
||||
- ✅ Clear, actionable output format
|
||||
- ✅ Multiple CLI command aliases
|
||||
- ✅ Integration with existing setup flow
|
||||
|
||||
The implementation follows all technical specifications and provides the exact user experience described in the requirements.
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,566 @@
|
||||
# Complete Guide to Creating Claude Code Agents
|
||||
|
||||
This guide teaches you how to create specialized agents (subagents) for Claude Code using `.md` files with YAML frontmatter configuration.
|
||||
|
||||
## What are Claude Code Agents?
|
||||
|
||||
Agents are specialized AI assistants that Claude Code can use for specific tasks. Each agent:
|
||||
|
||||
- **Has a specific purpose** and area of expertise
|
||||
- **Uses its own context** separate from the main conversation
|
||||
- **Can be configured with specific tools** it's allowed to use
|
||||
- **Includes a custom system prompt** that guides its behavior
|
||||
|
||||
## Key Benefits
|
||||
|
||||
### 🔄 Context Preservation
|
||||
Each agent operates in its own context, avoiding contamination of the main conversation.
|
||||
|
||||
### 🧠 Specialized Expertise
|
||||
Agents can be fine-tuned with detailed instructions for specific domains.
|
||||
|
||||
### ♻️ Reusability
|
||||
Once created, they can be used across different projects and shared with the team.
|
||||
|
||||
### 🛡️ Flexible Permissions
|
||||
Each agent can have different levels of access to tools.
|
||||
|
||||
## File Locations
|
||||
|
||||
| Type | Location | Scope | Priority |
|
||||
|------|----------|-------|----------|
|
||||
| **Project Agents** | `.claude/agents/` | Available in current project | Higher |
|
||||
| **User Agents** | `~/.claude/agents/` | Available across all projects | Lower |
|
||||
|
||||
*When there are name conflicts, project agents take precedence.*
|
||||
|
||||
## File Format
|
||||
|
||||
Each agent is defined in a Markdown file with this structure:
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: agent-name
|
||||
description: Description of when this agent should be invoked
|
||||
tools: tool1, tool2, tool3 # Optional
|
||||
model: sonnet # Optional: sonnet, opus, haiku
|
||||
---
|
||||
|
||||
Your agent's system prompt goes here. This can be multiple paragraphs
|
||||
and should clearly define the agent's role, capabilities, and approach
|
||||
to solving problems.
|
||||
|
||||
Include specific instructions, best practices, and any constraints
|
||||
the agent should follow.
|
||||
```
|
||||
|
||||
## Configuration Fields
|
||||
|
||||
### `name` Field (Required)
|
||||
- **Format**: Lowercase letters and hyphens only
|
||||
- **Examples**: `code-reviewer`, `security-auditor`, `test-runner`
|
||||
- **Purpose**: Unique identifier for the agent
|
||||
|
||||
### `description` Field (Required)
|
||||
- **Format**: Natural language description
|
||||
- **Includes**: When to use the agent, what type of tasks it handles
|
||||
- **Tip**: Use phrases like "Use PROACTIVELY" to encourage automatic usage
|
||||
- **Example**: `"Expert code review specialist. Use PROACTIVELY after writing or modifying code."`
|
||||
|
||||
### `tools` Field (Optional)
|
||||
- **Default**: If omitted, inherits all available tools
|
||||
- **Format**: Comma-separated list
|
||||
- **Common tools**: `Read, Edit, Bash, Grep, Glob, Write`
|
||||
- **Example**: `tools: Read, Edit, Bash`
|
||||
|
||||
### `model` Field (Optional)
|
||||
- **Options**: `sonnet` (default), `opus`, `haiku`
|
||||
- **Usage**: For tasks requiring different capabilities
|
||||
- **Example**: `model: opus` for complex tasks
|
||||
|
||||
## Available Tools
|
||||
|
||||
### Core Tools
|
||||
- **Read**: Read files
|
||||
- **Edit**: Edit existing files
|
||||
- **Write**: Create new files
|
||||
- **Bash**: Execute terminal commands
|
||||
- **Grep**: Search text in files
|
||||
- **Glob**: Search files by patterns
|
||||
- **LS**: List directories
|
||||
|
||||
### Advanced Tools
|
||||
- **MultiEdit**: Edit multiple files
|
||||
- **NotebookEdit**: Edit Jupyter notebooks
|
||||
- **WebFetch**: Fetch web content
|
||||
- **WebSearch**: Web searches
|
||||
|
||||
## Complete Agent Examples
|
||||
|
||||
### 1. Code Reviewer
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: code-reviewer
|
||||
description: Code review specialist. Use PROACTIVELY after writing or modifying code to review quality, security, and maintainability.
|
||||
tools: Read, Grep, Glob, Bash
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are a senior code reviewer ensuring high standards of code quality and security.
|
||||
|
||||
## Review Process
|
||||
|
||||
When invoked:
|
||||
1. Run `git diff` to see recent changes
|
||||
2. Focus on modified files
|
||||
3. Begin review immediately
|
||||
|
||||
## Review Checklist
|
||||
|
||||
### Critical Issues (MUST fix)
|
||||
- Exposed secrets or API keys
|
||||
- Obvious security vulnerabilities
|
||||
- Logic errors causing failures
|
||||
|
||||
### Warnings (SHOULD fix)
|
||||
- Duplicated code
|
||||
- Missing error handling
|
||||
- Insufficient input validation
|
||||
- Performance issues
|
||||
|
||||
### Suggestions (CONSIDER improving)
|
||||
- Code readability
|
||||
- Function and variable names
|
||||
- Test coverage
|
||||
- Documentation
|
||||
|
||||
## Response Format
|
||||
|
||||
Organize feedback by priority:
|
||||
```
|
||||
🚨 CRITICAL: [specific issue]
|
||||
└── Solution: [specific code to fix]
|
||||
|
||||
⚠️ WARNING: [issue]
|
||||
└── Suggestion: [how to improve]
|
||||
|
||||
💡 SUGGESTION: [optional improvement]
|
||||
└── Benefit: [why it's useful]
|
||||
```
|
||||
|
||||
Always include specific code examples for fixes.
|
||||
```
|
||||
|
||||
### 2. Security Auditor
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: security-auditor
|
||||
description: Security audit specialist. Use PROACTIVELY to review vulnerabilities, implement secure authentication, and ensure OWASP compliance.
|
||||
tools: Read, Bash, Grep, Glob
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are a security auditor specializing in application security and secure coding practices.
|
||||
|
||||
## Focus Areas
|
||||
|
||||
### Authentication/Authorization
|
||||
- JWT, OAuth2, SAML
|
||||
- Secure session handling
|
||||
- Role-based access control
|
||||
|
||||
### OWASP Top 10 Vulnerabilities
|
||||
- SQL Injection
|
||||
- Cross-Site Scripting (XSS)
|
||||
- Cross-Site Request Forgery (CSRF)
|
||||
- Sensitive data exposure
|
||||
|
||||
### Secure Configuration
|
||||
- Security headers (CSP, HSTS, etc.)
|
||||
- CORS configuration
|
||||
- Encryption in transit and at rest
|
||||
|
||||
## Audit Process
|
||||
|
||||
1. **Initial Analysis**
|
||||
- Identify sensitive endpoints
|
||||
- Review security configurations
|
||||
- Map sensitive data flows
|
||||
|
||||
2. **Code Review**
|
||||
- Search for insecure patterns
|
||||
- Verify input validation
|
||||
- Confirm secure credential handling
|
||||
|
||||
3. **Security Testing**
|
||||
- Run static analysis tools
|
||||
- Verify configurations
|
||||
- Document findings
|
||||
|
||||
## Report Format
|
||||
|
||||
```
|
||||
🔒 SECURITY AUDIT REPORT
|
||||
|
||||
## Executive Summary
|
||||
- Risk Level: [HIGH/MEDIUM/LOW]
|
||||
- Vulnerabilities Found: X
|
||||
- Critical Recommendations: X
|
||||
|
||||
## Critical Findings
|
||||
[List of high-risk vulnerabilities]
|
||||
|
||||
## Recommendations
|
||||
[Specific remediation actions]
|
||||
|
||||
## Compliance Checklist
|
||||
- [ ] OWASP Top 10 verified
|
||||
- [ ] Security headers configured
|
||||
- [ ] Authentication implemented correctly
|
||||
```
|
||||
|
||||
Focus on practical fixes over theoretical risks. Include OWASP references.
|
||||
```
|
||||
|
||||
### 3. Performance Optimizer
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: performance-optimizer
|
||||
description: Performance optimization specialist. Use PROACTIVELY when detecting performance issues or to optimize existing code.
|
||||
tools: Read, Edit, Bash, Grep
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are a performance optimization specialist with expertise in frontend and backend.
|
||||
|
||||
## Optimization Areas
|
||||
|
||||
### Frontend
|
||||
- Bundle size and code splitting
|
||||
- Component lazy loading
|
||||
- Image optimization
|
||||
- Resource caching
|
||||
- Core Web Vitals
|
||||
|
||||
### Backend
|
||||
- Database queries
|
||||
- Algorithms and data structures
|
||||
- Strategic caching
|
||||
- Process parallelization
|
||||
- Memory management
|
||||
|
||||
## Optimization Process
|
||||
|
||||
1. **Performance Analysis**
|
||||
```bash
|
||||
# Analysis tools
|
||||
npm run build -- --analyze
|
||||
lighthouse --chrome-flags="--headless" URL
|
||||
```
|
||||
|
||||
2. **Bottleneck Identification**
|
||||
- CPU and memory profiling
|
||||
- Network request analysis
|
||||
- Database query analysis
|
||||
|
||||
3. **Implementation of Improvements**
|
||||
- Specific code changes
|
||||
- Tool configuration
|
||||
- Validation metrics
|
||||
|
||||
## Target Metrics
|
||||
|
||||
### Web Vitals
|
||||
- **LCP (Largest Contentful Paint)**: < 2.5s
|
||||
- **FID (First Input Delay)**: < 100ms
|
||||
- **CLS (Cumulative Layout Shift)**: < 0.1
|
||||
|
||||
### Backend
|
||||
- **Response Time**: < 200ms for APIs
|
||||
- **Database Queries**: < 50ms average
|
||||
- **Memory Usage**: Stable without memory leaks
|
||||
|
||||
## Report Format
|
||||
|
||||
```
|
||||
⚡ PERFORMANCE ANALYSIS
|
||||
|
||||
## Current vs Target Metrics
|
||||
| Metric | Current | Target | Status |
|
||||
|--------|---------|--------|--------|
|
||||
| LCP | Xs | 2.5s | ❌/✅ |
|
||||
|
||||
## Optimizations Implemented
|
||||
1. [Specific description]
|
||||
- Impact: X% improvement
|
||||
- Code: [link to change]
|
||||
|
||||
## Next Steps
|
||||
- [ ] Additional suggested optimization
|
||||
- [ ] Continuous monitoring
|
||||
```
|
||||
```
|
||||
|
||||
### 4. Test Runner
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: test-runner
|
||||
description: Test automation specialist. Use PROACTIVELY to run tests, create new tests, and fix testing failures.
|
||||
tools: Read, Edit, Bash, Write
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are a test automation expert and software quality specialist.
|
||||
|
||||
## Testing Types
|
||||
|
||||
### Unit Tests
|
||||
- Individual functions
|
||||
- Isolated components
|
||||
- Dependency mocking
|
||||
- Coverage target: 80%+
|
||||
|
||||
### Integration Tests
|
||||
- Module interactions
|
||||
- API endpoints
|
||||
- Database operations
|
||||
- User workflows
|
||||
|
||||
### E2E Tests
|
||||
- Complete user flows
|
||||
- Cross-browser testing
|
||||
- Performance under load
|
||||
- Regression testing
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Testing Pyramid
|
||||
```
|
||||
🔺 E2E Tests (Few, slow)
|
||||
🔺🔺 Integration Tests (Some)
|
||||
🔺🔺🔺 Unit Tests (Many, fast)
|
||||
```
|
||||
|
||||
### Automated Process
|
||||
1. **Detect code changes**
|
||||
```bash
|
||||
git diff --name-only HEAD~1
|
||||
```
|
||||
|
||||
2. **Run relevant tests**
|
||||
```bash
|
||||
npm test -- --testPathPattern="related"
|
||||
```
|
||||
|
||||
3. **Analyze failures**
|
||||
- Stack traces
|
||||
- Error logs
|
||||
- Expected vs actual state
|
||||
|
||||
4. **Auto-fix**
|
||||
- Mock updates
|
||||
- Assertion adjustments
|
||||
- Test data corrections
|
||||
|
||||
## Testing Conventions
|
||||
|
||||
### Test Structure
|
||||
```javascript
|
||||
describe('ComponentName', () => {
|
||||
describe('when condition', () => {
|
||||
it('should behavior expectation', () => {
|
||||
// Arrange
|
||||
// Act
|
||||
// Assert
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Descriptive Names
|
||||
- ✅ `should return user data when valid ID provided`
|
||||
- ❌ `test user function`
|
||||
|
||||
### Clear Assertions
|
||||
```javascript
|
||||
// ✅ Specific
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.data.user.name).toBe('John Doe');
|
||||
|
||||
// ❌ Generic
|
||||
expect(response).toBeTruthy();
|
||||
```
|
||||
|
||||
## Failure Analysis
|
||||
|
||||
For each failing test:
|
||||
1. **Identify root cause**
|
||||
2. **Reproduce failure locally**
|
||||
3. **Fix code or test**
|
||||
4. **Verify solution is robust**
|
||||
|
||||
## Testing Report
|
||||
|
||||
```
|
||||
🧪 TESTING REPORT
|
||||
|
||||
## Current Coverage
|
||||
- Lines: X% (target: 80%)
|
||||
- Branches: X% (target: 70%)
|
||||
- Functions: X% (target: 85%)
|
||||
|
||||
## Tests Executed
|
||||
- ✅ Passed: X
|
||||
- ❌ Failed: X
|
||||
- ⏭️ Skipped: X
|
||||
|
||||
## Failed Tests
|
||||
[Detail of each failure with implemented solution]
|
||||
```
|
||||
```
|
||||
|
||||
## Best Practices for Creating Agents
|
||||
|
||||
### 1. Focused Design
|
||||
- **One clear responsibility** per agent
|
||||
- **Avoid generic agents** that try to do everything
|
||||
- **Define clear boundaries** of what the agent should/shouldn't do
|
||||
|
||||
### 2. Detailed System Prompts
|
||||
```markdown
|
||||
## Recommended Structure
|
||||
|
||||
### Identification
|
||||
"You are a [specific role] specializing in [area]."
|
||||
|
||||
### Work Process
|
||||
1. Specific step with command or action
|
||||
2. Clear evaluation criteria
|
||||
3. Expected output format
|
||||
|
||||
### Standards and Metrics
|
||||
- Objective metrics when possible
|
||||
- Specific quality criteria
|
||||
- Industry benchmarks
|
||||
|
||||
### Response Format
|
||||
Consistent template with clear sections
|
||||
```
|
||||
|
||||
### 3. Tool Limitation
|
||||
```yaml
|
||||
# ✅ Specific to purpose
|
||||
tools: Read, Grep, Bash
|
||||
|
||||
# ❌ Too broad
|
||||
tools: Read, Edit, Write, Bash, Grep, Glob, WebFetch, WebSearch
|
||||
```
|
||||
|
||||
### 4. Effective Descriptions
|
||||
```yaml
|
||||
# ✅ Specific and actionable
|
||||
description: "Code security auditor. Use PROACTIVELY for security reviews, auth implementations, and OWASP compliance checks."
|
||||
|
||||
# ❌ Too generic
|
||||
description: "Helps with code stuff."
|
||||
```
|
||||
|
||||
### 5. Agent Testing
|
||||
- **Test with real cases** from your project
|
||||
- **Verify it follows instructions** consistently
|
||||
- **Adjust prompt based** on results
|
||||
- **Document edge cases** it handles well
|
||||
|
||||
## Useful Commands for Management
|
||||
|
||||
### Create Project Agent
|
||||
```bash
|
||||
mkdir -p .claude/agents
|
||||
```
|
||||
|
||||
### Create User Agent
|
||||
```bash
|
||||
mkdir -p ~/.claude/agents
|
||||
```
|
||||
|
||||
### Validate YAML Format
|
||||
```bash
|
||||
# Verify frontmatter syntax
|
||||
head -20 .claude/agents/your-agent.md
|
||||
```
|
||||
|
||||
### Agent Testing
|
||||
```bash
|
||||
# In Claude Code, use slash command
|
||||
/agents
|
||||
```
|
||||
|
||||
## Advanced Use Cases
|
||||
|
||||
### 1. Agent Chaining
|
||||
```
|
||||
> First use code-reviewer to find issues, then use security-auditor to verify vulnerabilities
|
||||
```
|
||||
|
||||
### 2. Contextual Agents
|
||||
The correct agent is automatically selected based on:
|
||||
- Task description
|
||||
- Current project context
|
||||
- Required tools
|
||||
|
||||
### 3. Specialized Workflow
|
||||
```markdown
|
||||
---
|
||||
name: deployment-orchestrator
|
||||
description: Manages complete deployment pipeline. Use when deploying to production or staging environments.
|
||||
tools: Bash, Read, Write
|
||||
---
|
||||
|
||||
Orchestrates deployment with these steps:
|
||||
1. Pre-deployment checks
|
||||
2. Build process
|
||||
3. Testing validation
|
||||
4. Environment deployment
|
||||
5. Post-deployment verification
|
||||
6. Rollback procedures if needed
|
||||
```
|
||||
|
||||
## Common Troubleshooting
|
||||
|
||||
### Issue: Agent doesn't invoke automatically
|
||||
**Solution**:
|
||||
- Improve `description` with specific keywords
|
||||
- Add "Use PROACTIVELY" in description
|
||||
- Ensure filename matches `name` field
|
||||
|
||||
### Issue: Agent doesn't have tool access
|
||||
**Solution**:
|
||||
- Verify tools are listed correctly in `tools`
|
||||
- Or omit `tools` field to inherit all tools
|
||||
|
||||
### Issue: System prompt too generic
|
||||
**Solution**:
|
||||
- Add specific examples of expected input/output
|
||||
- Define objective success metrics
|
||||
- Include specific commands it should execute
|
||||
|
||||
### Issue: Conflicts between agents
|
||||
**Solution**:
|
||||
- Use unique, descriptive names
|
||||
- Project agents (.claude/agents/) have priority
|
||||
- Remove duplicate or obsolete agents
|
||||
|
||||
## Conclusion
|
||||
|
||||
Claude Code agents are a powerful tool for automating and specializing your development workflow. With this guide, you can create effective agents that:
|
||||
|
||||
- **Automate repetitive tasks**
|
||||
- **Maintain consistent standards**
|
||||
- **Provide specialized expertise**
|
||||
- **Improve team productivity**
|
||||
|
||||
Start with simple, specific agents, then build more complex workflows as you become familiar with the system.
|
||||
@@ -0,0 +1,329 @@
|
||||
# Sub agents
|
||||
|
||||
> Create and use specialized AI sub agents in Claude Code for task-specific workflows and improved context management.
|
||||
|
||||
Custom sub agents in Claude Code are specialized AI assistants that can be invoked to handle specific types of tasks. They enable more efficient problem-solving by providing task-specific configurations with customized system prompts, tools and a separate context window.
|
||||
|
||||
## What are sub agents?
|
||||
|
||||
Sub agents are pre-configured AI personalities that Claude Code can delegate tasks to. Each sub agent:
|
||||
|
||||
* Has a specific purpose and expertise area
|
||||
* Uses its own context window separate from the main conversation
|
||||
* Can be configured with specific tools it's allowed to use
|
||||
* Includes a custom system prompt that guides its behavior
|
||||
|
||||
When Claude Code encounters a task that matches a sub agent's expertise, it can delegate that task to the specialized sub agent, which works independently and returns results.
|
||||
|
||||
## Key benefits
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Context preservation" icon="layer-group">
|
||||
Each sub agent operates in its own context, preventing pollution of the main conversation and keeping it focused on high-level objectives.
|
||||
</Card>
|
||||
|
||||
<Card title="Specialized expertise" icon="brain">
|
||||
Sub agents can be fine-tuned with detailed instructions for specific domains, leading to higher success rates on designated tasks.
|
||||
</Card>
|
||||
|
||||
<Card title="Reusability" icon="rotate">
|
||||
Once created, sub agents can be used across different projects and shared with your team for consistent workflows.
|
||||
</Card>
|
||||
|
||||
<Card title="Flexible permissions" icon="shield-check">
|
||||
Each sub agent can have different tool access levels, allowing you to limit powerful tools to specific sub agent types.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Quick start
|
||||
|
||||
To create your first sub agent:
|
||||
|
||||
<Steps>
|
||||
<Step title="Open the sub agents interface">
|
||||
Run the following command:
|
||||
|
||||
```
|
||||
/agents
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Select 'Create New Agent'">
|
||||
Choose whether to create a project-level or user-level sub agent
|
||||
</Step>
|
||||
|
||||
<Step title="Define the sub agent">
|
||||
* **Recommended**: Generate with Claude first, then customize to make it yours
|
||||
* Describe your subagent in detail and when it should be used
|
||||
* Select the tools you want to grant access to (or leave blank to inherit all tools)
|
||||
* The interface shows all available tools, making selection easy
|
||||
* If you're generating with Claude, you can also edit the system prompt in your own editor by pressing `e`
|
||||
</Step>
|
||||
|
||||
<Step title="Save and use">
|
||||
Your sub agent is now available! Claude will use it automatically when appropriate, or you can invoke it explicitly:
|
||||
|
||||
```
|
||||
> Use the code-reviewer sub agent to check my recent changes
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Sub agent configuration
|
||||
|
||||
### File locations
|
||||
|
||||
Sub agents are stored as Markdown files with YAML frontmatter in two possible locations:
|
||||
|
||||
| Type | Location | Scope | Priority |
|
||||
| :--------------------- | :------------------ | :---------------------------- | :------- |
|
||||
| **Project sub agents** | `.claude/agents/` | Available in current project | Highest |
|
||||
| **User sub agents** | `~/.claude/agents/` | Available across all projects | Lower |
|
||||
|
||||
When sub agent names conflict, project-level sub agents take precedence over user-level sub agents.
|
||||
|
||||
### File format
|
||||
|
||||
Each sub agent is defined in a Markdown file with this structure:
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: your-sub-agent-name
|
||||
description: Description of when this sub agent should be invoked
|
||||
tools: tool1, tool2, tool3 # Optional - inherits all tools if omitted
|
||||
---
|
||||
|
||||
Your sub agent's system prompt goes here. This can be multiple paragraphs
|
||||
and should clearly define the sub agent's role, capabilities, and approach
|
||||
to solving problems.
|
||||
|
||||
Include specific instructions, best practices, and any constraints
|
||||
the sub agent should follow.
|
||||
```
|
||||
|
||||
#### Configuration fields
|
||||
|
||||
| Field | Required | Description |
|
||||
| :------------ | :------- | :------------------------------------------------------------------------------------------ |
|
||||
| `name` | Yes | Unique identifier using lowercase letters and hyphens |
|
||||
| `description` | Yes | Natural language description of the sub agent's purpose |
|
||||
| `tools` | No | Comma-separated list of specific tools. If omitted, inherits all tools from the main thread |
|
||||
|
||||
### Available tools
|
||||
|
||||
Sub agents can be granted access to any of Claude Code's internal tools. See the [tools documentation](/en/docs/claude-code/settings#tools-available-to-claude) for a complete list of available tools.
|
||||
|
||||
<Tip>
|
||||
**Recommended:** Use the `/agents` command to modify tool access - it provides an interactive interface that lists all available tools, including any connected MCP server tools, making it easier to select the ones you need.
|
||||
</Tip>
|
||||
|
||||
You have two options for configuring tools:
|
||||
|
||||
* **Omit the `tools` field** to inherit all tools from the main thread (default), including MCP tools
|
||||
* **Specify individual tools** as a comma-separated list for more granular control (can be edited manually or via `/agents`)
|
||||
|
||||
**MCP Tools**: Sub agents can access MCP tools from configured MCP servers. When the `tools` field is omitted, sub agents inherit all MCP tools available to the main thread.
|
||||
|
||||
## Managing sub agents
|
||||
|
||||
### Using the /agents command (Recommended)
|
||||
|
||||
The `/agents` command provides a comprehensive interface for sub agent management:
|
||||
|
||||
```
|
||||
/agents
|
||||
```
|
||||
|
||||
This opens an interactive menu where you can:
|
||||
|
||||
* View all available sub agents (built-in, user, and project)
|
||||
* Create new sub agents with guided setup
|
||||
* Edit existing custom sub agents, including their tool access
|
||||
* Delete custom sub agents
|
||||
* See which sub agents are active when duplicates exist
|
||||
* **Easily manage tool permissions** with a complete list of available tools
|
||||
|
||||
### Direct file management
|
||||
|
||||
You can also manage sub agents by working directly with their files:
|
||||
|
||||
```bash
|
||||
# Create a project sub agent
|
||||
mkdir -p .claude/agents
|
||||
echo '---
|
||||
name: test-runner
|
||||
description: Use proactively to run tests and fix failures
|
||||
---
|
||||
|
||||
You are a test automation expert. When you see code changes, proactively run the appropriate tests. If tests fail, analyze the failures and fix them while preserving the original test intent.' > .claude/agents/test-runner.md
|
||||
|
||||
# Create a user sub agent
|
||||
mkdir -p ~/.claude/agents
|
||||
# ... create sub agent file
|
||||
```
|
||||
|
||||
## Using sub agents effectively
|
||||
|
||||
### Automatic delegation
|
||||
|
||||
Claude Code proactively delegates tasks based on:
|
||||
|
||||
* The task description in your request
|
||||
* The `description` field in sub agent configurations
|
||||
* Current context and available tools
|
||||
|
||||
<Tip>
|
||||
To encourage more proactive sub agent use, include phrases like "use PROACTIVELY" or "MUST BE USED" in your `description` field.
|
||||
</Tip>
|
||||
|
||||
### Explicit invocation
|
||||
|
||||
Request a specific sub agent by mentioning it in your command:
|
||||
|
||||
```
|
||||
> Use the test-runner sub agent to fix failing tests
|
||||
> Have the code-reviewer sub agent look at my recent changes
|
||||
> Ask the debugger sub agent to investigate this error
|
||||
```
|
||||
|
||||
## Example sub agents
|
||||
|
||||
### Code reviewer
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: code-reviewer
|
||||
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
|
||||
tools: Read, Grep, Glob, Bash
|
||||
---
|
||||
|
||||
You are a senior code reviewer ensuring high standards of code quality and security.
|
||||
|
||||
When invoked:
|
||||
1. Run git diff to see recent changes
|
||||
2. Focus on modified files
|
||||
3. Begin review immediately
|
||||
|
||||
Review checklist:
|
||||
- Code is simple and readable
|
||||
- Functions and variables are well-named
|
||||
- No duplicated code
|
||||
- Proper error handling
|
||||
- No exposed secrets or API keys
|
||||
- Input validation implemented
|
||||
- Good test coverage
|
||||
- Performance considerations addressed
|
||||
|
||||
Provide feedback organized by priority:
|
||||
- Critical issues (must fix)
|
||||
- Warnings (should fix)
|
||||
- Suggestions (consider improving)
|
||||
|
||||
Include specific examples of how to fix issues.
|
||||
```
|
||||
|
||||
### Debugger
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: debugger
|
||||
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
|
||||
tools: Read, Edit, Bash, Grep, Glob
|
||||
---
|
||||
|
||||
You are an expert debugger specializing in root cause analysis.
|
||||
|
||||
When invoked:
|
||||
1. Capture error message and stack trace
|
||||
2. Identify reproduction steps
|
||||
3. Isolate the failure location
|
||||
4. Implement minimal fix
|
||||
5. Verify solution works
|
||||
|
||||
Debugging process:
|
||||
- Analyze error messages and logs
|
||||
- Check recent code changes
|
||||
- Form and test hypotheses
|
||||
- Add strategic debug logging
|
||||
- Inspect variable states
|
||||
|
||||
For each issue, provide:
|
||||
- Root cause explanation
|
||||
- Evidence supporting the diagnosis
|
||||
- Specific code fix
|
||||
- Testing approach
|
||||
- Prevention recommendations
|
||||
|
||||
Focus on fixing the underlying issue, not just symptoms.
|
||||
```
|
||||
|
||||
### Data scientist
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: data-scientist
|
||||
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
|
||||
tools: Bash, Read, Write
|
||||
---
|
||||
|
||||
You are a data scientist specializing in SQL and BigQuery analysis.
|
||||
|
||||
When invoked:
|
||||
1. Understand the data analysis requirement
|
||||
2. Write efficient SQL queries
|
||||
3. Use BigQuery command line tools (bq) when appropriate
|
||||
4. Analyze and summarize results
|
||||
5. Present findings clearly
|
||||
|
||||
Key practices:
|
||||
- Write optimized SQL queries with proper filters
|
||||
- Use appropriate aggregations and joins
|
||||
- Include comments explaining complex logic
|
||||
- Format results for readability
|
||||
- Provide data-driven recommendations
|
||||
|
||||
For each analysis:
|
||||
- Explain the query approach
|
||||
- Document any assumptions
|
||||
- Highlight key findings
|
||||
- Suggest next steps based on data
|
||||
|
||||
Always ensure queries are efficient and cost-effective.
|
||||
```
|
||||
|
||||
## Best practices
|
||||
|
||||
* **Start with Claude-generated agents**: We highly recommend generating your initial sub agent with Claude and then iterating on it to make it personally yours. This approach gives you the best results - a solid foundation that you can customize to your specific needs.
|
||||
|
||||
* **Design focused sub agents**: Create sub agents with single, clear responsibilities rather than trying to make one sub agent do everything. This improves performance and makes sub agents more predictable.
|
||||
|
||||
* **Write detailed prompts**: Include specific instructions, examples, and constraints in your system prompts. The more guidance you provide, the better the sub agent will perform.
|
||||
|
||||
* **Limit tool access**: Only grant tools that are necessary for the sub agent's purpose. This improves security and helps the sub agent focus on relevant actions.
|
||||
|
||||
* **Version control**: Check project sub agents into version control so your team can benefit from and improve them collaboratively.
|
||||
|
||||
## Advanced usage
|
||||
|
||||
### Chaining sub agents
|
||||
|
||||
For complex workflows, you can chain multiple sub agents:
|
||||
|
||||
```
|
||||
> First use the code-analyzer sub agent to find performance issues, then use the optimizer sub agent to fix them
|
||||
```
|
||||
|
||||
### Dynamic sub agent selection
|
||||
|
||||
Claude Code intelligently selects sub agents based on context. Make your `description` fields specific and action-oriented for best results.
|
||||
|
||||
## Performance considerations
|
||||
|
||||
* **Context efficiency**: Agents help preserve main context, enabling longer overall sessions
|
||||
* **Latency**: Sub agents start off with a clean slate each time they are invoked and may add latency as they gather context that they require to do their job effectively.
|
||||
|
||||
## Related documentation
|
||||
|
||||
* [Slash commands](/en/docs/claude-code/slash-commands) - Learn about other built-in commands
|
||||
* [Settings](/en/docs/claude-code/settings) - Configure Claude Code behavior
|
||||
* [Hooks](/en/docs/claude-code/hooks) - Automate workflows with event handlers
|
||||
Reference in New Issue
Block a user