diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index a06a445..0000000 --- a/.dockerignore +++ /dev/null @@ -1,87 +0,0 @@ -# Python cache and build artifacts -__pycache__/ -*.py[cod] -*$py.class -*.so -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -*.egg-info/ -.installed.cfg -*.egg - -# Virtual environments -.venv/ -venv/ -ENV/ -env/ - -# IDE and editor files -.vscode/ -.idea/ -*.swp -*.swo -*~ - -# OS generated files -.DS_Store -.DS_Store? -._* -.Spotlight-V100 -.Trashes -ehthumbs.db -Thumbs.db - -# Git -.git/ -.gitignore - -# Docker -Dockerfile* -docker-compose* -.dockerignore - -# Database files (will be created in volume) -*.db -*.sqlite -*.sqlite3 - -# Logs -*.log -logs/ - -# Environment files (handled separately) -.env* - -# Temporary files -tmp/ -temp/ -.tmp/ - -# Hook configuration files (generated) -claude-hooks-*.json - -# Cache -.cache/ -.pytest_cache/ - -# Coverage reports -htmlcov/ -.coverage -.coverage.* - -# Node modules (if any) -node_modules/ - -# Documentation build -docs/_build/ \ No newline at end of file diff --git a/.env.example b/.env.example index db16268..5a8aa25 100644 --- a/.env.example +++ b/.env.example @@ -1,18 +1,10 @@ -# Claude Code Tracker Configuration +# Database +DATABASE_URL=sqlite+aiosqlite:///./data/tracker.db -# Domain configuration for Caddy reverse proxy -DOMAIN=claude.l.supported.systems - -# Database configuration -DATABASE_URL=sqlite+aiosqlite:///app/data/tracker.db - -# Application settings -DEBUG=false +# API Configuration API_HOST=0.0.0.0 API_PORT=8000 - -# Data storage path (host directory to bind mount) -DATA_PATH=./data +DEBUG=true # Security (generate with: openssl rand -hex 32) SECRET_KEY=your-secret-key-here @@ -24,20 +16,4 @@ ANALYTICS_BATCH_SIZE=1000 # Logging LOG_LEVEL=INFO -LOG_FILE=tracker.log - -# Optional: Rate limiting settings -# RATE_LIMIT_ENABLED=true -# RATE_LIMIT_PER_MINUTE=100 - -# Optional: Performance settings -# MAX_WORKERS=4 -# TIMEOUT_SECONDS=60 - -# Optional: Hook settings -# DEFAULT_HOOK_TIMEOUT=10 -# MAX_HOOK_RETRIES=3 - -# Optional: Analytics retention -# ANALYTICS_RETENTION_DAYS=365 -# ENABLE_ANONYMOUS_ANALYTICS=false \ No newline at end of file +LOG_FILE=tracker.log \ No newline at end of file diff --git a/DOCKER.md b/DOCKER.md deleted file mode 100644 index 6fd0b4b..0000000 --- a/DOCKER.md +++ /dev/null @@ -1,345 +0,0 @@ -# Claude Code Tracker - Docker Deployment - -This guide covers deploying Claude Code Tracker using Docker with Caddy reverse proxy integration. - -## Quick Start - -1. **Clone and configure:** - ```bash - git clone - cd claude-tracker - cp .env.example .env - # Edit .env file to set your domain - ``` - -2. **Deploy with one command:** - ```bash - ./docker-deploy.sh - ``` - -3. **Access your instance:** - - Dashboard: `https://claude.l.supported.systems/dashboard` - - API Docs: `https://claude.l.supported.systems/docs` - -## Prerequisites - -### Required -- Docker Engine 20.10+ -- Docker Compose 2.0+ -- Caddy server with docker-proxy plugin running - -### Caddy Network Setup -The deployment expects an external Docker network named `caddy`: - -```bash -# Create the network if it doesn't exist -docker network create caddy -``` - -### Caddy Server -Ensure Caddy is running with the docker-proxy plugin: - -```bash -# Example Caddy docker-compose.yml -version: '3.8' -services: - caddy: - image: lucaslorentz/caddy-docker-proxy:ci-alpine - ports: - - "80:80" - - "443:443" - environment: - - CADDY_INGRESS_NETWORKS=caddy - networks: - - caddy - volumes: - - /var/run/docker.sock:/var/run/docker.sock - - caddy_data:/data - restart: unless-stopped -``` - -## Configuration - -### Environment Variables - -The `.env` file configures the deployment: - -```bash -# Domain for Caddy reverse proxy -DOMAIN=claude.l.supported.systems - -# Database path (inside container) -DATABASE_URL=sqlite+aiosqlite:///app/data/tracker.db - -# Application settings -DEBUG=false -API_HOST=0.0.0.0 -API_PORT=8000 - -# Data directory path (host) -DATA_PATH=./data -``` - -### Caddy Labels - -The `docker-compose.yml` includes comprehensive Caddy configuration: - -- **Reverse Proxy:** Automatic routing to the container -- **SSL/TLS:** Automatic certificate management -- **Security Headers:** XSS protection, content type sniffing prevention -- **CORS Headers:** API cross-origin support -- **Compression:** Gzip encoding for better performance -- **Caching:** Static asset caching - -## Deployment Options - -### Option 1: Automated Deployment (Recommended) -```bash -./docker-deploy.sh -``` - -### Option 2: Manual Deployment -```bash -# Create network if needed -docker network create caddy - -# Build and start -docker-compose up -d --build - -# Check status -docker-compose ps -``` - -### Option 3: Development Mode -```bash -# Start with logs -docker-compose up --build - -# Rebuild after changes -docker-compose up --build --force-recreate -``` - -## Data Persistence - -### Database Storage -- **Host Path:** `./data/` (configurable via `DATA_PATH`) -- **Container Path:** `/app/data/` -- **Database File:** `tracker.db` - -### Volume Management -```bash -# Backup database -cp ./data/tracker.db ./backups/tracker-$(date +%Y%m%d).db - -# Restore database -cp ./backups/tracker-20240115.db ./data/tracker.db -docker-compose restart claude-tracker -``` - -## Management Commands - -### Service Management -```bash -# View logs -docker-compose logs -f claude-tracker - -# Restart service -docker-compose restart claude-tracker - -# Stop service -docker-compose down - -# Update and restart -docker-compose pull && docker-compose up -d -``` - -### Container Access -```bash -# Shell access -docker-compose exec claude-tracker /bin/bash - -# Run commands in container -docker-compose exec claude-tracker uv run python recalculate_project_stats.py - -# View container stats -docker stats claude-tracker-api -``` - -### Health Monitoring -```bash -# Check health -curl http://localhost:8000/health - -# Container status -docker-compose ps - -# Resource usage -docker-compose exec claude-tracker cat /proc/meminfo -``` - -## Troubleshooting - -### Common Issues - -#### 1. Container Won't Start -```bash -# Check logs -docker-compose logs claude-tracker - -# Common causes: -# - Port 8000 already in use -# - Database permission issues -# - Missing environment variables -``` - -#### 2. Database Errors -```bash -# Check database permissions -ls -la ./data/ - -# Recreate database -rm ./data/tracker.db -docker-compose restart claude-tracker -``` - -#### 3. Caddy Connection Issues -```bash -# Verify Caddy network -docker network ls | grep caddy - -# Check Caddy logs -docker logs caddy - -# Verify labels -docker inspect claude-tracker-api | grep -A 10 Labels -``` - -#### 4. Performance Issues -```bash -# Monitor resources -docker stats claude-tracker-api - -# Increase memory limits in docker-compose.yml -``` - -### Health Checks - -The container includes built-in health checks: - -```bash -# Container health status -docker-compose ps - -# Manual health check -curl -f http://localhost:8000/health - -# Detailed health info -docker inspect --format='{{json .State.Health}}' claude-tracker-api -``` - -## Security Considerations - -### Network Security -- Container only exposes port 8000 internally to Docker network -- External access only through Caddy reverse proxy -- Automatic HTTPS with Let's Encrypt - -### Data Security -- Database stored in dedicated Docker volume -- No sensitive data in container images -- Environment variables for configuration - -### Resource Limits -- Memory limit: 512MB (configurable) -- CPU limit: 1.0 core (configurable) -- Automatic restart on failure - -## Production Recommendations - -### Performance -1. **Use bind mounts for data persistence** -2. **Configure resource limits appropriately** -3. **Monitor container health and logs** -4. **Regular database backups** - -### Security -1. **Use specific image tags (not `latest`)** -2. **Regular security updates** -3. **Network isolation** -4. **Secret management for sensitive data** - -### Monitoring -1. **Set up log aggregation** -2. **Configure health check alerts** -3. **Monitor resource usage** -4. **Database backup automation** - -## Advanced Configuration - -### Custom Caddy Labels -Add additional Caddy configuration in `docker-compose.yml`: - -```yaml -labels: - # Rate limiting - caddy.rate_limit: "100r/m" - - # Basic auth for admin endpoints - caddy.basicauth./admin/*: "admin $2a$14$..." - - # IP restrictions - caddy.@internal: "remote_ip 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16" - caddy.authorize.@internal: "" -``` - -### Multi-Environment Setup -Create environment-specific compose files: - -```bash -# Production -docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d - -# Development -docker-compose -f docker-compose.yml -f docker-compose.dev.yml up -d -``` - -## Updating - -### Application Updates -```bash -# Pull latest changes -git pull - -# Rebuild and restart -docker-compose up -d --build - -# Check health -curl https://claude.l.supported.systems/health -``` - -### Database Migrations -```bash -# Backup first -cp ./data/tracker.db ./data/tracker.backup.db - -# Run migration (if needed) -docker-compose exec claude-tracker uv run python migrate.py - -# Verify -docker-compose logs claude-tracker -``` - -## Support - -For issues related to: -- **Docker deployment:** Check this documentation -- **Caddy configuration:** Refer to Caddy documentation -- **Application features:** See main README.md -- **API usage:** Visit `/docs` endpoint - -## Links - -- **Dashboard:** `https://your-domain/dashboard` -- **API Documentation:** `https://your-domain/docs` -- **Hook Reference:** `https://your-domain/dashboard/docs/hook-reference` -- **Health Check:** `https://your-domain/health` \ No newline at end of file diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index d39e618..0000000 --- a/Dockerfile +++ /dev/null @@ -1,53 +0,0 @@ -# Use Python 3.12 slim image -FROM python:3.12-slim - -# Set environment variables -ENV PYTHONDONTWRITEBYTECODE=1 \ - PYTHONUNBUFFERED=1 \ - UV_CACHE_DIR=/tmp/uv-cache - -# Install system dependencies -RUN apt-get update && apt-get install -y \ - curl \ - git \ - build-essential \ - && rm -rf /var/lib/apt/lists/* - -# Install uv -COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv - -# Create app directory -WORKDIR /app - -# Copy dependency files and README first for better caching -COPY pyproject.toml uv.lock README.md ./ - -# Install dependencies -RUN uv sync --frozen --no-cache --no-dev - -# Copy application code -COPY . . - -# Create data directory for SQLite database with proper permissions -RUN mkdir -p /app/data && chmod 777 /app/data - -# Expose port -EXPOSE 8000 - -# Health check -HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \ - CMD curl -f http://localhost:8000/health || exit 1 - -# Copy initialization script -COPY init_db.py ./ - -# Create startup script -RUN echo '#!/bin/bash\n\ -echo "Ensuring database is initialized..."\n\ -/app/.venv/bin/python init_db.py\n\ -echo "Starting application..."\n\ -exec /app/.venv/bin/python -m uvicorn main:app --host 0.0.0.0 --port 8000' > start.sh && \ -chmod +x start.sh - -# Run the application -CMD ["./start.sh"] \ No newline at end of file diff --git a/README.md b/README.md index 3678d07..891e496 100644 --- a/README.md +++ b/README.md @@ -1,116 +1,146 @@ -# Claude Code Hook Configurations +# Claude Code Project Tracker -This directory contains various pre-configured hook setups for different use cases: +A comprehensive development intelligence system that tracks your Claude Code sessions, providing insights into your coding patterns, productivity, and learning journey. -## Available Configurations +## Overview -### basic.json -Essential hooks for basic session and tool tracking. -- Session management -- Tool calls -- File modifications -- Conversations +The Claude Code Project Tracker automatically captures your development workflow through Claude Code's hook system, creating a detailed record of: -### comprehensive.json -Complete hook setup with all available hook types. -- All performance monitoring -- Code quality tracking -- Learning analytics -- Collaboration insights -- Project intelligence +- **Development Sessions** - When you start/stop working, what projects you focus on +- **Conversations** - Full dialogue history with Claude for context and learning analysis +- **Code Changes** - File modifications, tool usage, and command executions +- **Thinking Patterns** - Wait times between interactions to understand your workflow +- **Git Activity** - Repository changes, commits, and branch operations +- **Productivity Metrics** - Engagement levels, output quality, and learning velocity -### essential.json -Minimal setup for core functionality. +## Architecture -### developer.json -Focused on development workflow and code quality. -- Essential hooks -- Performance monitoring -- Code quality checks +``` +┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ +│ Claude Code │───▶│ Hook System │───▶│ FastAPI Server │ +│ (your IDE) │ │ │ │ │ +└─────────────────┘ └─────────────────┘ └─────────────────┘ + │ + ▼ +┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ +│ Web Dashboard │◀───│ Analytics │◀───│ SQLite Database │ +│ │ │ Engine │ │ │ +└─────────────────┘ └─────────────────┘ └─────────────────┘ +``` -### power_user.json -Advanced setup for productivity optimization. -- Essential hooks -- Performance tracking -- Workflow analysis -- Project intelligence +### Components -### research.json -Optimized for learning and exploration. -- Essential hooks -- Learning tracking -- External resource usage -- Knowledge gap analysis +- **FastAPI Server**: REST API that receives hook data and serves analytics +- **SQLite Database**: Local storage for all tracking data +- **Hook Integration**: Claude Code hooks that capture development events +- **Analytics Engine**: Processes raw data into meaningful insights +- **Web Dashboard**: Interactive interface for exploring your development patterns -### team.json -Team-focused configuration for collaboration. -- Essential hooks -- Collaboration tracking -- Testing workflows -- Project intelligence +## Key Features -## Installation +### 🎯 Session Tracking +- Automatic project detection and session management +- Working directory and git branch context +- Session duration and engagement analysis -1. Choose the configuration that matches your needs -2. Copy the JSON content to your Claude Code settings file: - - macOS/Linux: `~/.config/claude/settings.json` - - Windows: `%APPDATA%\claude\settings.json` -3. Ensure Claude Code Tracker is running on port 8000 -4. Start using Claude Code - hooks will automatically track your activity! +### 💬 Conversation Intelligence +- Full dialogue history with semantic search +- Problem-solving pattern recognition +- Learning topic identification and progress tracking -## Available Hook Variables +### 📊 Development Analytics +- Productivity metrics and engagement scoring +- Tool usage patterns and optimization insights +- Cross-project learning and code reuse analysis -Each hook can use these variables that Claude Code provides: +### 🔍 Advanced Insights +- Think time analysis and flow state detection +- Git activity correlation with conversations +- Skill development velocity tracking +- Workflow optimization recommendations -### Session Variables -- `$SESSION_ID` - Current session identifier -- `$TIMESTAMP` - Current timestamp (ISO format) -- `$PWD` - Current working directory -- `$USER` - System username +## Data Privacy -### Tool Variables -- `$TOOL_NAME` - Name of tool being called -- `$TOOL_PARAMS` - Tool parameters (JSON) -- `$RESULT_STATUS` - Success/error status -- `$EXECUTION_TIME` - Tool execution time (ms) -- `$ERROR_TYPE` - Type of error -- `$ERROR_MESSAGE` - Error message -- `$STACK_TRACE` - Error stack trace +- **Local-First**: All data stays on your machine +- **No External Services**: No data transmission to third parties +- **Full Control**: Complete ownership of your development history +- **Selective Tracking**: Configurable hook activation per project -### File Variables -- `$FILE_PATH` - Path to modified file -- `$ACTION` - File action (created/modified/deleted) -- `$FILE_SIZE_MB` - File size in megabytes +## Quick Start -### Context Variables -- `$CONTENT` - Conversation content -- `$CONTEXT` - Current context description -- `$SEARCH_QUERY` - What you're searching for -- `$NEW_PROJECT` - Project being switched to -- `$OLD_PROJECT` - Project being switched from +1. **Install Dependencies** + ```bash + pip install -r requirements.txt + ``` -### Performance Variables -- `$MEMORY_MB` - Memory usage in MB -- `$DURATION_MS` - Duration in milliseconds -- `$THRESHOLD_EXCEEDED` - Boolean for threshold alerts +2. **Start the Tracking Server** + ```bash + python main.py + ``` -And many more! Each hook type has specific variables available. +3. **Configure Claude Code Hooks** + ```bash + # Add hooks to your Claude Code settings + cp config/claude-hooks.json ~/.config/claude-code/ + ``` -## Customization +4. **Access Dashboard** + ``` + Open http://localhost:8000 in your browser + ``` -You can modify any configuration by: -1. Adding/removing specific hooks -2. Changing API endpoints or ports -3. Adjusting timeout and retry settings -4. Adding custom metadata to hook calls +## Project Structure -## Troubleshooting +``` +claude-tracker/ +├── README.md # This file +├── requirements.txt # Python dependencies +├── main.py # FastAPI application entry point +├── config/ # Configuration files +│ └── claude-hooks.json # Hook setup for Claude Code +├── app/ # Application code +│ ├── models/ # Database models +│ ├── api/ # API endpoints +│ ├── analytics/ # Insights engine +│ └── dashboard/ # Web interface +├── tests/ # Test suite +├── docs/ # Detailed documentation +└── data/ # SQLite database location +``` -If hooks aren't working: -1. Ensure Claude Code Tracker server is running -2. Check that curl is installed -3. Verify the API endpoints are accessible -4. Check Claude Code logs for hook execution errors -5. Test individual hooks manually with curl +## Documentation -For more help, see the documentation at `/dashboard/docs/hook-setup`. +- [API Specification](docs/api-spec.yaml) - Complete endpoint documentation +- [Database Schema](docs/database-schema.md) - Data model details +- [Hook Setup Guide](docs/hook-setup.md) - Claude Code integration +- [Development Guide](docs/development.md) - Local setup and contribution +- [Analytics Guide](docs/analytics.md) - Understanding insights and metrics + +## Development + +See [Development Guide](docs/development.md) for detailed setup instructions. + +```bash +# Install development dependencies +pip install -r requirements-dev.txt + +# Run tests +pytest + +# Start development server with hot reload +uvicorn main:app --reload + +# Generate API documentation +python -m app.generate_docs +``` + +## Contributing + +This project follows test-driven development. Please ensure: +1. All new features have comprehensive tests +2. Documentation is updated for API changes +3. Analytics insights are validated with test data + +## License + +MIT License - See LICENSE file for details \ No newline at end of file diff --git a/app/api/conversations.py b/app/api/conversations.py index a11c496..0df3168 100644 --- a/app/api/conversations.py +++ b/app/api/conversations.py @@ -83,54 +83,6 @@ async def log_conversation( ) -@router.get("/conversations", response_model=List[ConversationSearchResult]) -async def get_conversations( - project_id: Optional[int] = Query(None, description="Filter by project ID"), - limit: int = Query(50, description="Maximum number of results"), - offset: int = Query(0, description="Number of results to skip"), - db: AsyncSession = Depends(get_db) -): - """ - Get recent conversations with optional project filtering. - """ - try: - # Build query - query = select(Conversation).options( - selectinload(Conversation.session).selectinload(Session.project) - ) - - # Add project filter if specified - if project_id: - query = query.join(Session).where(Session.project_id == project_id) - - # Order by timestamp descending, add pagination - query = query.order_by(Conversation.timestamp.desc()).offset(offset).limit(limit) - - result = await db.execute(query) - conversations = result.scalars().all() - - # Convert to response format - results = [] - for conversation in conversations: - results.append(ConversationSearchResult( - id=conversation.id, - project_name=conversation.session.project.name, - timestamp=conversation.timestamp, - user_prompt=conversation.user_prompt, - claude_response=conversation.claude_response, - relevance_score=1.0, # All results are equally relevant when just listing - context=[] # No context snippets needed for listing - )) - - return results - - except Exception as e: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to get conversations: {str(e)}" - ) - - @router.get("/conversations/search", response_model=List[ConversationSearchResult]) async def search_conversations( query: str = Query(..., description="Search query"), diff --git a/app/api/hooks.py b/app/api/hooks.py deleted file mode 100644 index 7018e39..0000000 --- a/app/api/hooks.py +++ /dev/null @@ -1,619 +0,0 @@ -""" -Comprehensive hook tracking API endpoints. -""" - -import json -from datetime import datetime -from typing import List, Optional, Dict, Any -from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy import select, func, desc, and_ -from sqlalchemy.orm import selectinload -from pydantic import BaseModel, Field - -from app.database.connection import get_db -from app.models.session import Session -from app.models.hooks import ( - HookEvent, ToolError, WaitingPeriodNew, PerformanceMetric, - CodeQualityEvent, WorkflowEvent, LearningEvent, - EnvironmentEvent, CollaborationEvent, ProjectIntelligence -) - -router = APIRouter() - - -# Request/Response Models -class BaseHookRequest(BaseModel): - """Base request schema for hook events.""" - session_id: Optional[str] = Field(None, description="Session ID (auto-detected if not provided)") - timestamp: Optional[datetime] = Field(None, description="Event timestamp") - - -class ToolErrorRequest(BaseHookRequest): - """Request schema for tool error events.""" - tool_name: str - error_type: str - error_message: str - stack_trace: Optional[str] = None - parameters: Optional[dict] = None - - -class WaitingPeriodRequest(BaseHookRequest): - """Request schema for waiting period events.""" - reason: Optional[str] = Field("thinking", description="Reason for waiting") - context: Optional[str] = None - duration_ms: Optional[int] = None - end_time: Optional[datetime] = None - - -class PerformanceMetricRequest(BaseHookRequest): - """Request schema for performance metrics.""" - metric_type: str = Field(..., description="Type of metric: memory, cpu, disk") - value: float - unit: str = Field(..., description="Unit: MB, %, seconds, etc.") - threshold_exceeded: bool = False - - -class CodeQualityRequest(BaseHookRequest): - """Request schema for code quality events.""" - event_type: str = Field(..., description="lint, format, test, build, analysis") - file_path: Optional[str] = None - tool_name: Optional[str] = None - status: str = Field(..., description="success, warning, error") - issues_count: int = 0 - details: Optional[dict] = None - duration_ms: Optional[int] = None - - -class WorkflowRequest(BaseHookRequest): - """Request schema for workflow events.""" - event_type: str = Field(..., description="context_switch, search_query, browser_tab, etc.") - description: Optional[str] = None - metadata: Optional[dict] = None - source: Optional[str] = None - duration_ms: Optional[int] = None - - -class LearningRequest(BaseHookRequest): - """Request schema for learning events.""" - event_type: str = Field(..., description="tutorial, documentation, experimentation") - topic: Optional[str] = None - resource_url: Optional[str] = None - confidence_before: Optional[int] = Field(None, ge=1, le=10) - confidence_after: Optional[int] = Field(None, ge=1, le=10) - notes: Optional[str] = None - duration_ms: Optional[int] = None - - -class EnvironmentRequest(BaseHookRequest): - """Request schema for environment events.""" - event_type: str = Field(..., description="env_change, config_update, security_scan") - environment: Optional[str] = None - config_file: Optional[str] = None - changes: Optional[dict] = None - impact_level: Optional[str] = Field(None, description="low, medium, high, critical") - - -class CollaborationRequest(BaseHookRequest): - """Request schema for collaboration events.""" - event_type: str = Field(..., description="external_resource, ai_question, review_request") - interaction_type: Optional[str] = None - query_or_topic: Optional[str] = None - resource_url: Optional[str] = None - response_quality: Optional[int] = Field(None, ge=1, le=5) - time_to_resolution: Optional[int] = None - metadata: Optional[dict] = None - - -class ProjectIntelligenceRequest(BaseHookRequest): - """Request schema for project intelligence events.""" - event_type: str = Field(..., description="refactor, feature_flag, debugging_session") - scope: Optional[str] = Field(None, description="small, medium, large") - complexity: Optional[str] = Field(None, description="low, medium, high") - end_time: Optional[datetime] = None - duration_minutes: Optional[int] = None - files_affected: Optional[List[str]] = None - outcome: Optional[str] = Field(None, description="success, partial, failed, abandoned") - notes: Optional[str] = None - - -class HookResponse(BaseModel): - """Response schema for hook operations.""" - id: int - hook_type: str - session_id: str - timestamp: datetime - message: str - - -async def get_current_session_id() -> Optional[str]: - """Get the current session ID from the temporary file.""" - try: - with open("/tmp/claude-session-id", "r") as f: - return f.read().strip() - except (OSError, FileNotFoundError): - return None - - -async def validate_session(session_id: str, db: AsyncSession) -> Session: - """Validate that the session exists.""" - result = await db.execute( - select(Session).where(Session.id == int(session_id)) - ) - session = result.scalars().first() - - if not session: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Session {session_id} not found" - ) - - return session - - -# Tool Error Endpoints -@router.post("/hooks/tool-error", response_model=HookResponse, status_code=status.HTTP_201_CREATED) -async def record_tool_error( - request: ToolErrorRequest, - db: AsyncSession = Depends(get_db) -): - """Record a tool error event.""" - try: - session_id = request.session_id or await get_current_session_id() - if not session_id: - raise HTTPException(status_code=400, detail="No active session found") - - await validate_session(session_id, db) - - tool_error = ToolError( - session_id=session_id, - tool_name=request.tool_name, - error_type=request.error_type, - error_message=request.error_message, - stack_trace=request.stack_trace, - parameters=request.parameters, - timestamp=request.timestamp or datetime.utcnow() - ) - - db.add(tool_error) - await db.commit() - await db.refresh(tool_error) - - return HookResponse( - id=tool_error.id, - hook_type="tool_error", - session_id=session_id, - timestamp=tool_error.timestamp, - message=f"Tool error recorded for {request.tool_name}" - ) - - except HTTPException: - raise - except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to record tool error: {str(e)}") - - -# Waiting Period Endpoints -@router.post("/hooks/waiting-period", response_model=HookResponse, status_code=status.HTTP_201_CREATED) -async def record_waiting_period( - request: WaitingPeriodRequest, - db: AsyncSession = Depends(get_db) -): - """Record a waiting period event.""" - try: - session_id = request.session_id or await get_current_session_id() - if not session_id: - raise HTTPException(status_code=400, detail="No active session found") - - await validate_session(session_id, db) - - waiting_period = WaitingPeriodNew( - session_id=session_id, - reason=request.reason, - context=request.context, - duration_ms=request.duration_ms, - end_time=request.end_time, - timestamp=request.timestamp or datetime.utcnow() - ) - - db.add(waiting_period) - await db.commit() - await db.refresh(waiting_period) - - return HookResponse( - id=waiting_period.id, - hook_type="waiting_period", - session_id=session_id, - timestamp=waiting_period.start_time, - message=f"Waiting period recorded: {request.reason}" - ) - - except HTTPException: - raise - except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to record waiting period: {str(e)}") - - -# Performance Metric Endpoints -@router.post("/hooks/performance", response_model=HookResponse, status_code=status.HTTP_201_CREATED) -async def record_performance_metric( - request: PerformanceMetricRequest, - db: AsyncSession = Depends(get_db) -): - """Record a performance metric.""" - try: - session_id = request.session_id or await get_current_session_id() - if not session_id: - raise HTTPException(status_code=400, detail="No active session found") - - await validate_session(session_id, db) - - metric = PerformanceMetric( - session_id=session_id, - metric_type=request.metric_type, - value=request.value, - unit=request.unit, - threshold_exceeded=request.threshold_exceeded, - timestamp=request.timestamp or datetime.utcnow() - ) - - db.add(metric) - await db.commit() - await db.refresh(metric) - - return HookResponse( - id=metric.id, - hook_type="performance_metric", - session_id=session_id, - timestamp=metric.timestamp, - message=f"Performance metric recorded: {request.metric_type} = {request.value}{request.unit}" - ) - - except HTTPException: - raise - except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to record performance metric: {str(e)}") - - -# Code Quality Endpoints -@router.post("/hooks/code-quality", response_model=HookResponse, status_code=status.HTTP_201_CREATED) -async def record_code_quality_event( - request: CodeQualityRequest, - db: AsyncSession = Depends(get_db) -): - """Record a code quality event.""" - try: - session_id = request.session_id or await get_current_session_id() - if not session_id: - raise HTTPException(status_code=400, detail="No active session found") - - await validate_session(session_id, db) - - event = CodeQualityEvent( - session_id=session_id, - event_type=request.event_type, - file_path=request.file_path, - tool_name=request.tool_name, - status=request.status, - issues_count=request.issues_count, - details=request.details, - duration_ms=request.duration_ms, - timestamp=request.timestamp or datetime.utcnow() - ) - - db.add(event) - await db.commit() - await db.refresh(event) - - return HookResponse( - id=event.id, - hook_type="code_quality", - session_id=session_id, - timestamp=event.timestamp, - message=f"Code quality event recorded: {request.event_type} - {request.status}" - ) - - except HTTPException: - raise - except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to record code quality event: {str(e)}") - - -# Workflow Endpoints -@router.post("/hooks/workflow", response_model=HookResponse, status_code=status.HTTP_201_CREATED) -async def record_workflow_event( - request: WorkflowRequest, - db: AsyncSession = Depends(get_db) -): - """Record a workflow event.""" - try: - session_id = request.session_id or await get_current_session_id() - if not session_id: - raise HTTPException(status_code=400, detail="No active session found") - - await validate_session(session_id, db) - - event = WorkflowEvent( - session_id=session_id, - event_type=request.event_type, - description=request.description, - event_metadata=request.metadata, - source=request.source, - duration_ms=request.duration_ms, - timestamp=request.timestamp or datetime.utcnow() - ) - - db.add(event) - await db.commit() - await db.refresh(event) - - return HookResponse( - id=event.id, - hook_type="workflow", - session_id=session_id, - timestamp=event.timestamp, - message=f"Workflow event recorded: {request.event_type}" - ) - - except HTTPException: - raise - except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to record workflow event: {str(e)}") - - -# Learning Endpoints -@router.post("/hooks/learning", response_model=HookResponse, status_code=status.HTTP_201_CREATED) -async def record_learning_event( - request: LearningRequest, - db: AsyncSession = Depends(get_db) -): - """Record a learning event.""" - try: - session_id = request.session_id or await get_current_session_id() - if not session_id: - raise HTTPException(status_code=400, detail="No active session found") - - await validate_session(session_id, db) - - event = LearningEvent( - session_id=session_id, - event_type=request.event_type, - topic=request.topic, - resource_url=request.resource_url, - confidence_before=request.confidence_before, - confidence_after=request.confidence_after, - notes=request.notes, - duration_ms=request.duration_ms, - timestamp=request.timestamp or datetime.utcnow() - ) - - db.add(event) - await db.commit() - await db.refresh(event) - - return HookResponse( - id=event.id, - hook_type="learning", - session_id=session_id, - timestamp=event.timestamp, - message=f"Learning event recorded: {request.event_type} - {request.topic or 'General'}" - ) - - except HTTPException: - raise - except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to record learning event: {str(e)}") - - -# Environment Endpoints -@router.post("/hooks/environment", response_model=HookResponse, status_code=status.HTTP_201_CREATED) -async def record_environment_event( - request: EnvironmentRequest, - db: AsyncSession = Depends(get_db) -): - """Record an environment event.""" - try: - session_id = request.session_id or await get_current_session_id() - if not session_id: - raise HTTPException(status_code=400, detail="No active session found") - - await validate_session(session_id, db) - - event = EnvironmentEvent( - session_id=session_id, - event_type=request.event_type, - environment=request.environment, - config_file=request.config_file, - changes=request.changes, - impact_level=request.impact_level, - timestamp=request.timestamp or datetime.utcnow() - ) - - db.add(event) - await db.commit() - await db.refresh(event) - - return HookResponse( - id=event.id, - hook_type="environment", - session_id=session_id, - timestamp=event.timestamp, - message=f"Environment event recorded: {request.event_type}" - ) - - except HTTPException: - raise - except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to record environment event: {str(e)}") - - -# Collaboration Endpoints -@router.post("/hooks/collaboration", response_model=HookResponse, status_code=status.HTTP_201_CREATED) -async def record_collaboration_event( - request: CollaborationRequest, - db: AsyncSession = Depends(get_db) -): - """Record a collaboration event.""" - try: - session_id = request.session_id or await get_current_session_id() - if not session_id: - raise HTTPException(status_code=400, detail="No active session found") - - await validate_session(session_id, db) - - event = CollaborationEvent( - session_id=session_id, - event_type=request.event_type, - interaction_type=request.interaction_type, - query_or_topic=request.query_or_topic, - resource_url=request.resource_url, - response_quality=request.response_quality, - time_to_resolution=request.time_to_resolution, - event_metadata=request.metadata, - timestamp=request.timestamp or datetime.utcnow() - ) - - db.add(event) - await db.commit() - await db.refresh(event) - - return HookResponse( - id=event.id, - hook_type="collaboration", - session_id=session_id, - timestamp=event.timestamp, - message=f"Collaboration event recorded: {request.event_type}" - ) - - except HTTPException: - raise - except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to record collaboration event: {str(e)}") - - -# Project Intelligence Endpoints -@router.post("/hooks/project-intelligence", response_model=HookResponse, status_code=status.HTTP_201_CREATED) -async def record_project_intelligence( - request: ProjectIntelligenceRequest, - db: AsyncSession = Depends(get_db) -): - """Record a project intelligence event.""" - try: - session_id = request.session_id or await get_current_session_id() - if not session_id: - raise HTTPException(status_code=400, detail="No active session found") - - await validate_session(session_id, db) - - event = ProjectIntelligence( - session_id=session_id, - event_type=request.event_type, - scope=request.scope, - complexity=request.complexity, - end_time=request.end_time, - duration_minutes=request.duration_minutes, - files_affected=request.files_affected, - outcome=request.outcome, - notes=request.notes, - timestamp=request.timestamp or datetime.utcnow() - ) - - db.add(event) - await db.commit() - await db.refresh(event) - - return HookResponse( - id=event.id, - hook_type="project_intelligence", - session_id=session_id, - timestamp=event.timestamp, - message=f"Project intelligence recorded: {request.event_type}" - ) - - except HTTPException: - raise - except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to record project intelligence: {str(e)}") - - -# Analytics Endpoints -@router.get("/hooks/analytics/summary", response_model=Dict[str, Any]) -async def get_hook_analytics_summary( - project_id: Optional[int] = None, - start_date: Optional[datetime] = None, - end_date: Optional[datetime] = None, - db: AsyncSession = Depends(get_db) -): - """Get comprehensive analytics summary across all hook types.""" - try: - # Base filters - filters = [] - if start_date: - filters.append(ToolError.timestamp >= start_date) - if end_date: - filters.append(ToolError.timestamp <= end_date) - - if project_id: - filters.append(Session.project_id == project_id) - - # Get counts for each hook type - summary = {} - - # Tool errors - query = select(func.count(ToolError.id)) - if project_id: - query = query.join(Session) - if filters: - query = query.where(and_(*filters)) - - result = await db.execute(query) - summary["tool_errors"] = result.scalar() - - # Add similar queries for other hook types... - # (Similar pattern for each hook type) - - return summary - - except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to get analytics summary: {str(e)}") - - -@router.get("/hooks/session/{session_id}/timeline", response_model=List[Dict[str, Any]]) -async def get_session_timeline( - session_id: str, - db: AsyncSession = Depends(get_db) -): - """Get a comprehensive timeline of all events in a session.""" - try: - await validate_session(session_id, db) - - # Collect all events from different tables - timeline = [] - - # Tool errors - result = await db.execute( - select(ToolError).where(ToolError.session_id == session_id) - ) - for event in result.scalars().all(): - timeline.append({ - "type": "tool_error", - "timestamp": event.timestamp, - "data": { - "tool_name": event.tool_name, - "error_type": event.error_type, - "error_message": event.error_message - } - }) - - # Add other event types to timeline... - # (Similar pattern for each event type) - - # Sort by timestamp - timeline.sort(key=lambda x: x["timestamp"]) - - return timeline - - except HTTPException: - raise - except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to get session timeline: {str(e)}") \ No newline at end of file diff --git a/app/api/importer.py b/app/api/importer.py deleted file mode 100644 index 5ddd48c..0000000 --- a/app/api/importer.py +++ /dev/null @@ -1,528 +0,0 @@ -""" -Data importer for Claude Code .claude.json file. - -This module provides functionality to import historical data from the -.claude.json configuration file into the project tracker. -""" - -import json -import os -from datetime import datetime, timedelta -from pathlib import Path -from typing import Dict, List, Optional, Any - -from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File -from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy import select - -from app.database.connection import get_db -from app.models.project import Project -from app.models.session import Session -from app.models.conversation import Conversation - -router = APIRouter() - - -class ClaudeJsonImporter: - """Importer for .claude.json data.""" - - def __init__(self, db: AsyncSession): - self.db = db - - async def import_from_file(self, file_path: str) -> Dict[str, Any]: - """Import data from .claude.json file.""" - if not os.path.exists(file_path): - raise FileNotFoundError(f"Claude configuration file not found: {file_path}") - - try: - with open(file_path, 'r', encoding='utf-8') as f: - claude_data = json.load(f) - except json.JSONDecodeError as e: - raise ValueError(f"Invalid JSON in Claude configuration file: {e}") - - return await self._import_claude_data(claude_data) - - async def import_from_content(self, content: str) -> Dict[str, Any]: - """Import data from .claude.json file content.""" - try: - claude_data = json.loads(content) - except json.JSONDecodeError as e: - raise ValueError(f"Invalid JSON in Claude configuration file: {e}") - - return await self._import_claude_data(claude_data) - - async def _import_claude_data(self, claude_data: Dict[str, Any]) -> Dict[str, Any]: - """Common import logic for both file and content imports.""" - results = { - "projects_imported": 0, - "sessions_estimated": 0, - "conversations_imported": 0, - "errors": [] - } - - # Import basic usage statistics - await self._import_usage_stats(claude_data, results) - - # Import projects and their history - if "projects" in claude_data: - await self._import_projects(claude_data["projects"], results) - - return results - - async def _import_usage_stats(self, claude_data: Dict[str, Any], results: Dict[str, Any]): - """Import basic usage statistics.""" - # We could create a synthetic "Claude Code Usage" project to track overall stats - if claude_data.get("numStartups") and claude_data.get("firstStartTime"): - try: - first_start = datetime.fromisoformat( - claude_data["firstStartTime"].replace('Z', '+00:00') - ) - - # Create a synthetic project for overall Claude Code usage - usage_project = await self._get_or_create_project( - name="Claude Code Usage Statistics", - path="", - description="Imported usage statistics from .claude.json" - ) - - # Estimate session distribution over time - num_startups = claude_data["numStartups"] - days_since_first = (datetime.now() - first_start.replace(tzinfo=None)).days - - if days_since_first > 0: - # Create estimated sessions spread over the usage period - await self._create_estimated_sessions( - usage_project, - first_start.replace(tzinfo=None), - num_startups, - days_since_first - ) - results["sessions_estimated"] = num_startups - - except Exception as e: - results["errors"].append(f"Failed to import usage stats: {e}") - - async def _import_projects(self, projects_data: Dict[str, Any], results: Dict[str, Any]): - """Import project data from .claude.json.""" - for project_path, project_info in projects_data.items(): - try: - # Skip system paths or non-meaningful paths - if project_path in ["", "/", "/tmp"]: - continue - - # Extract project name from path - project_name = Path(project_path).name or "Unknown Project" - - # Create or get existing project - project = await self._get_or_create_project( - name=project_name, - path=project_path - ) - - results["projects_imported"] += 1 - - # Import conversation history if available - if "history" in project_info and isinstance(project_info["history"], list): - conversation_count = await self._import_project_history( - project, - project_info["history"] - ) - results["conversations_imported"] += conversation_count - - except Exception as e: - results["errors"].append(f"Failed to import project {project_path}: {e}") - - async def _get_or_create_project( - self, - name: str, - path: str, - description: Optional[str] = None - ) -> Project: - """Get existing project or create new one.""" - # Check if project already exists - result = await self.db.execute( - select(Project).where(Project.path == path) - ) - existing_project = result.scalars().first() - - if existing_project: - return existing_project - - # Try to detect languages from path - languages = self._detect_languages(path) - - # Create new project - project = Project( - name=name, - path=path, - languages=languages - ) - - self.db.add(project) - await self.db.commit() - await self.db.refresh(project) - - return project - - def _detect_languages(self, project_path: str) -> Optional[List[str]]: - """Attempt to detect programming languages from project directory.""" - languages = [] - - try: - if os.path.exists(project_path) and os.path.isdir(project_path): - # Look for common files to infer languages - files = os.listdir(project_path) - - # Python - if any(f.endswith(('.py', '.pyx', '.pyi')) for f in files) or 'requirements.txt' in files: - languages.append('python') - - # JavaScript/TypeScript - if any(f.endswith(('.js', '.jsx', '.ts', '.tsx')) for f in files) or 'package.json' in files: - if any(f.endswith(('.ts', '.tsx')) for f in files): - languages.append('typescript') - else: - languages.append('javascript') - - # Go - if any(f.endswith('.go') for f in files) or 'go.mod' in files: - languages.append('go') - - # Rust - if any(f.endswith('.rs') for f in files) or 'Cargo.toml' in files: - languages.append('rust') - - # Java - if any(f.endswith('.java') for f in files) or 'pom.xml' in files: - languages.append('java') - - except (OSError, PermissionError): - # If we can't read the directory, that's okay - pass - - return languages if languages else None - - async def _create_estimated_sessions( - self, - project: Project, - first_start: datetime, - num_startups: int, - days_since_first: int - ): - """Create estimated sessions based on startup count.""" - # Check if we already have sessions for this project - existing_sessions = await self.db.execute( - select(Session).where( - Session.project_id == project.id, - Session.session_type == "startup" - ) - ) - if existing_sessions.scalars().first(): - return # Sessions already exist, skip creation - - # Don't create too many sessions - limit to reasonable estimates - max_sessions = min(num_startups, 50) # Cap at 50 sessions - - # Distribute sessions over the time period - if days_since_first > 0: - sessions_per_day = max_sessions / days_since_first - - for i in range(max_sessions): - # Spread sessions over the time period - days_offset = int(i / sessions_per_day) if sessions_per_day > 0 else i - session_time = first_start + timedelta(days=days_offset) - - # Estimate session duration (30-180 minutes) - import random - duration = random.randint(30, 180) - - session = Session( - project_id=project.id, - start_time=session_time, - end_time=session_time + timedelta(minutes=duration), - session_type="startup", - working_directory=project.path, - duration_minutes=duration, - activity_count=random.randint(5, 25), # Estimated activity - conversation_count=random.randint(2, 8) # Estimated conversations - ) - - self.db.add(session) - - await self.db.commit() - - async def _import_project_history( - self, - project: Project, - history: List[Dict[str, Any]] - ) -> int: - """Import conversation history for a project.""" - # Check if we already have history conversations for this project - existing_conversations = await self.db.execute( - select(Conversation).where( - Conversation.context.like('%"imported_from": ".claude.json"%'), - Conversation.session.has(Session.project_id == project.id) - ) - ) - if existing_conversations.scalars().first(): - return 0 # History already imported, skip - - conversation_count = 0 - - # Create a synthetic session for imported history - history_session = Session( - project_id=project.id, - start_time=datetime.now() - timedelta(days=30), # Assume recent - session_type="history_import", # Different type to avoid conflicts - working_directory=project.path, - activity_count=len(history), - conversation_count=len(history) - ) - - self.db.add(history_session) - await self.db.commit() - await self.db.refresh(history_session) - - # Import each history entry as a conversation - for i, entry in enumerate(history[:20]): # Limit to 20 entries - try: - display_text = entry.get("display", "") - if display_text: - conversation = Conversation( - session_id=history_session.id, - timestamp=history_session.start_time + timedelta(minutes=i * 5), - user_prompt=display_text, - exchange_type="user_prompt", - context={"imported_from": ".claude.json"} - ) - - self.db.add(conversation) - conversation_count += 1 - except Exception as e: - # Skip problematic entries - continue - - if conversation_count > 0: - await self.db.commit() - - return conversation_count - - -@router.post("/import/claude-json") -async def import_claude_json( - file_path: Optional[str] = None, - db: AsyncSession = Depends(get_db) -): - """ - Import data from .claude.json file. - - If no file_path is provided, tries to find .claude.json in the user's home directory. - """ - if not file_path: - # Try default location - home_path = Path.home() / ".claude.json" - file_path = str(home_path) - - try: - importer = ClaudeJsonImporter(db) - results = await importer.import_from_file(file_path) - - return { - "success": True, - "message": "Import completed successfully", - "results": results - } - - except FileNotFoundError as e: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Claude configuration file not found: {e}" - ) - except ValueError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid file format: {e}" - ) - except Exception as e: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Import failed: {e}" - ) - - -@router.post("/import/claude-json/upload") -async def import_claude_json_upload( - file: UploadFile = File(...), - db: AsyncSession = Depends(get_db) -): - """ - Import data from uploaded .claude.json file. - """ - # Validate file type - if file.filename and not file.filename.endswith('.json'): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="File must be a JSON file (.json)" - ) - - # Check file size (limit to 10MB) - MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB - content = await file.read() - - if len(content) > MAX_FILE_SIZE: - raise HTTPException( - status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, - detail="File too large. Maximum size is 10MB." - ) - - try: - # Decode file content - file_content = content.decode('utf-8') - - # Import data - importer = ClaudeJsonImporter(db) - results = await importer.import_from_content(file_content) - - return { - "success": True, - "message": "Import completed successfully", - "file_name": file.filename, - "file_size_kb": round(len(content) / 1024, 2), - "results": results - } - - except UnicodeDecodeError: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="File must be UTF-8 encoded" - ) - except ValueError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid file format: {e}" - ) - except Exception as e: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Import failed: {e}" - ) - - -@router.get("/import/claude-json/preview") -async def preview_claude_json_import( - file_path: Optional[str] = None -): - """ - Preview what would be imported from .claude.json file without actually importing. - """ - if not file_path: - home_path = Path.home() / ".claude.json" - file_path = str(home_path) - - if not os.path.exists(file_path): - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Claude configuration file not found" - ) - - try: - with open(file_path, 'r', encoding='utf-8') as f: - claude_data = json.load(f) - except json.JSONDecodeError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid JSON in Claude configuration file: {e}" - ) - - preview = { - "file_path": file_path, - "file_size_mb": round(os.path.getsize(file_path) / (1024 * 1024), 2), - "claude_usage": { - "num_startups": claude_data.get("numStartups", 0), - "first_start_time": claude_data.get("firstStartTime"), - "prompt_queue_use_count": claude_data.get("promptQueueUseCount", 0) - }, - "projects": { - "total_count": len(claude_data.get("projects", {})), - "paths": list(claude_data.get("projects", {}).keys())[:10], # Show first 10 - "has_more": len(claude_data.get("projects", {})) > 10 - }, - "history_entries": 0 - } - - # Count total history entries across all projects - if "projects" in claude_data: - total_history = sum( - len(proj.get("history", [])) - for proj in claude_data["projects"].values() - ) - preview["history_entries"] = total_history - - return preview - - -@router.post("/import/claude-json/preview-upload") -async def preview_claude_json_upload( - file: UploadFile = File(...) -): - """ - Preview what would be imported from uploaded .claude.json file without actually importing. - """ - # Validate file type - if file.filename and not file.filename.endswith('.json'): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="File must be a JSON file (.json)" - ) - - # Check file size (limit to 10MB) - MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB - content = await file.read() - - if len(content) > MAX_FILE_SIZE: - raise HTTPException( - status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, - detail="File too large. Maximum size is 10MB." - ) - - try: - # Decode and parse file content - file_content = content.decode('utf-8') - claude_data = json.loads(file_content) - except UnicodeDecodeError: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="File must be UTF-8 encoded" - ) - except json.JSONDecodeError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid JSON in Claude configuration file: {e}" - ) - - preview = { - "file_name": file.filename, - "file_size_mb": round(len(content) / (1024 * 1024), 2), - "file_size_kb": round(len(content) / 1024, 2), - "claude_usage": { - "num_startups": claude_data.get("numStartups", 0), - "first_start_time": claude_data.get("firstStartTime"), - "prompt_queue_use_count": claude_data.get("promptQueueUseCount", 0) - }, - "projects": { - "total_count": len(claude_data.get("projects", {})), - "paths": list(claude_data.get("projects", {}).keys())[:10], # Show first 10 - "has_more": len(claude_data.get("projects", {})) > 10 - }, - "history_entries": 0 - } - - # Count total history entries across all projects - if "projects" in claude_data: - total_history = sum( - len(proj.get("history", [])) - for proj in claude_data["projects"].values() - ) - preview["history_entries"] = total_history - - return preview \ No newline at end of file diff --git a/app/api/tool_calls.py b/app/api/tool_calls.py deleted file mode 100644 index 5b8aa02..0000000 --- a/app/api/tool_calls.py +++ /dev/null @@ -1,254 +0,0 @@ -""" -Tool call tracking API endpoints. -""" - -import json -from datetime import datetime -from typing import List, Optional -from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy import select, func, desc -from sqlalchemy.orm import selectinload -from pydantic import BaseModel, Field - -from app.database.connection import get_db -from app.models.session import Session -from app.models.tool_call import ToolCall - -router = APIRouter() - - -class ToolCallRequest(BaseModel): - """Request schema for recording a tool call.""" - session_id: Optional[str] = Field(None, description="Session ID (auto-detected if not provided)") - tool_name: str = Field(..., description="Name of the tool being called") - parameters: Optional[dict] = Field(None, description="Tool parameters as JSON object") - result_status: Optional[str] = Field("success", description="Result status: success, error, timeout") - error_message: Optional[str] = Field(None, description="Error message if failed") - execution_time_ms: Optional[int] = Field(None, description="Execution time in milliseconds") - timestamp: Optional[datetime] = Field(None, description="Timestamp of the tool call") - - -class ToolCallResponse(BaseModel): - """Response schema for tool call operations.""" - id: int - session_id: str - tool_name: str - result_status: str - timestamp: datetime - message: str - - -class ToolUsageStats(BaseModel): - """Statistics about tool usage.""" - tool_name: str - total_calls: int - success_calls: int - error_calls: int - avg_execution_time_ms: Optional[float] - success_rate: float - - -async def get_current_session_id() -> Optional[str]: - """Get the current session ID from the temporary file.""" - try: - with open("/tmp/claude-session-id", "r") as f: - return f.read().strip() - except (OSError, FileNotFoundError): - return None - - -@router.post("/tool-calls", response_model=ToolCallResponse, status_code=status.HTTP_201_CREATED) -async def record_tool_call( - request: ToolCallRequest, - db: AsyncSession = Depends(get_db) -): - """ - Record a tool call made during a Claude Code session. - - This endpoint is called by Claude Code hooks when tools are used. - It automatically detects the current session if not provided. - """ - try: - # Get session ID - session_id = request.session_id - if not session_id: - session_id = await get_current_session_id() - - if not session_id: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="No active session found. Please provide session_id or ensure a session is running." - ) - - # Verify session exists - result = await db.execute( - select(Session).where(Session.id == int(session_id)) - ) - session = result.scalars().first() - - if not session: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Session {session_id} not found" - ) - - # Create tool call record - tool_call = ToolCall( - session_id=str(session_id), - tool_name=request.tool_name, - parameters=json.dumps(request.parameters) if request.parameters else None, - result_status=request.result_status or "success", - error_message=request.error_message, - execution_time_ms=request.execution_time_ms, - timestamp=request.timestamp or datetime.utcnow() - ) - - db.add(tool_call) - await db.commit() - await db.refresh(tool_call) - - return ToolCallResponse( - id=tool_call.id, - session_id=tool_call.session_id, - tool_name=tool_call.tool_name, - result_status=tool_call.result_status, - timestamp=tool_call.timestamp, - message=f"Tool call '{request.tool_name}' recorded successfully" - ) - - except HTTPException: - raise - except Exception as e: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to record tool call: {str(e)}" - ) - - -@router.get("/tool-calls/session/{session_id}", response_model=List[dict]) -async def get_session_tool_calls( - session_id: str, - db: AsyncSession = Depends(get_db) -): - """Get all tool calls for a specific session.""" - try: - result = await db.execute( - select(ToolCall) - .where(ToolCall.session_id == session_id) - .order_by(desc(ToolCall.timestamp)) - ) - tool_calls = result.scalars().all() - - return [ - { - "id": tc.id, - "tool_name": tc.tool_name, - "parameters": json.loads(tc.parameters) if tc.parameters else None, - "result_status": tc.result_status, - "error_message": tc.error_message, - "execution_time_ms": tc.execution_time_ms, - "timestamp": tc.timestamp - } - for tc in tool_calls - ] - - except Exception as e: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to get tool calls: {str(e)}" - ) - - -@router.get("/tool-calls/stats", response_model=List[ToolUsageStats]) -async def get_tool_usage_stats( - project_id: Optional[int] = None, - start_date: Optional[datetime] = None, - end_date: Optional[datetime] = None, - db: AsyncSession = Depends(get_db) -): - """Get tool usage statistics with optional filtering.""" - try: - # Base query - query = select( - ToolCall.tool_name, - func.count(ToolCall.id).label("total_calls"), - func.sum(func.case([(ToolCall.result_status == "success", 1)], else_=0)).label("success_calls"), - func.sum(func.case([(ToolCall.result_status == "error", 1)], else_=0)).label("error_calls"), - func.avg(ToolCall.execution_time_ms).label("avg_execution_time_ms") - ) - - # Apply filters - if project_id: - query = query.join(Session).where(Session.project_id == project_id) - - if start_date: - query = query.where(ToolCall.timestamp >= start_date) - - if end_date: - query = query.where(ToolCall.timestamp <= end_date) - - # Group by tool name - query = query.group_by(ToolCall.tool_name).order_by(desc("total_calls")) - - result = await db.execute(query) - rows = result.all() - - stats = [] - for row in rows: - success_rate = (row.success_calls / row.total_calls * 100) if row.total_calls > 0 else 0 - - stats.append(ToolUsageStats( - tool_name=row.tool_name, - total_calls=row.total_calls, - success_calls=row.success_calls, - error_calls=row.error_calls, - avg_execution_time_ms=float(row.avg_execution_time_ms) if row.avg_execution_time_ms else None, - success_rate=round(success_rate, 2) - )) - - return stats - - except Exception as e: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to get tool usage stats: {str(e)}" - ) - - -@router.get("/tool-calls/popular", response_model=List[dict]) -async def get_popular_tools( - limit: int = 10, - project_id: Optional[int] = None, - db: AsyncSession = Depends(get_db) -): - """Get the most frequently used tools.""" - try: - query = select( - ToolCall.tool_name, - func.count(ToolCall.id).label("usage_count"), - func.max(ToolCall.timestamp).label("last_used") - ) - - if project_id: - query = query.join(Session).where(Session.project_id == project_id) - - query = query.group_by(ToolCall.tool_name).order_by(desc("usage_count")).limit(limit) - - result = await db.execute(query) - rows = result.all() - - return [ - { - "tool_name": row.tool_name, - "usage_count": row.usage_count, - "last_used": row.last_used - } - for row in rows - ] - - except Exception as e: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to get popular tools: {str(e)}" - ) \ No newline at end of file diff --git a/app/dashboard/routes.py b/app/dashboard/routes.py index 215a34d..1364495 100644 --- a/app/dashboard/routes.py +++ b/app/dashboard/routes.py @@ -46,89 +46,4 @@ async def dashboard_conversations(request: Request, db: AsyncSession = Depends(g return templates.TemplateResponse("conversations.html", { "request": request, "title": "Conversations - Claude Code Tracker" - }) - - -@dashboard_router.get("/dashboard/import", response_class=HTMLResponse) -async def dashboard_import(request: Request, db: AsyncSession = Depends(get_db)): - """Data import page.""" - return templates.TemplateResponse("import.html", { - "request": request, - "title": "Import Data - Claude Code Tracker" - }) - - -@dashboard_router.get("/dashboard/projects/{project_id}/timeline", response_class=HTMLResponse) -async def dashboard_project_timeline(request: Request, project_id: int, db: AsyncSession = Depends(get_db)): - """Project timeline page.""" - return templates.TemplateResponse("project_timeline.html", { - "request": request, - "title": f"Timeline - Project {project_id}", - "project_id": project_id - }) - - -@dashboard_router.get("/dashboard/projects/{project_id}/stats", response_class=HTMLResponse) -async def dashboard_project_stats(request: Request, project_id: int, db: AsyncSession = Depends(get_db)): - """Project statistics page.""" - return templates.TemplateResponse("project_stats.html", { - "request": request, - "title": f"Statistics - Project {project_id}", - "project_id": project_id - }) - - -@dashboard_router.get("/dashboard/docs", response_class=HTMLResponse) -async def dashboard_docs(request: Request, db: AsyncSession = Depends(get_db)): - """Documentation overview page.""" - return templates.TemplateResponse("docs/index.html", { - "request": request, - "title": "Documentation - Claude Code Tracker" - }) - - -@dashboard_router.get("/dashboard/docs/{section}", response_class=HTMLResponse) -async def dashboard_docs_section(request: Request, section: str, db: AsyncSession = Depends(get_db)): - """Documentation section pages.""" - # Map section names to templates and titles - sections = { - "getting-started": { - "template": "docs/getting-started.html", - "title": "Getting Started - Claude Code Tracker" - }, - "data-import": { - "template": "docs/data-import.html", - "title": "Data Import Guide - Claude Code Tracker" - }, - "docker-deployment": { - "template": "docs/docker-deployment.html", - "title": "Docker Deployment Guide - Claude Code Tracker" - }, - "hook-setup": { - "template": "docs/hook-setup.html", - "title": "Hook Setup Guide - Claude Code Tracker" - }, - "hook-reference": { - "template": "docs/hook-reference.html", - "title": "Complete Hook Reference - Claude Code Tracker" - }, - "api-reference": { - "template": "docs/api-reference.html", - "title": "API Reference - Claude Code Tracker" - }, - "faq": { - "template": "docs/faq.html", - "title": "FAQ - Claude Code Tracker" - } - } - - if section not in sections: - from fastapi import HTTPException - raise HTTPException(status_code=404, detail=f"Documentation section '{section}' not found") - - section_info = sections[section] - return templates.TemplateResponse(section_info["template"], { - "request": request, - "title": section_info["title"], - "section": section }) \ No newline at end of file diff --git a/app/dashboard/static/claude-hooks-basic.json b/app/dashboard/static/claude-hooks-basic.json deleted file mode 100644 index 456f6b6..0000000 --- a/app/dashboard/static/claude-hooks-basic.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "hooks": { - "session_start": "curl -X POST http://localhost:8000/api/sessions/start -H \"Content-Type: application/json\" -d '{\"project_path\": \"$PWD\", \"start_time\": \"$TIMESTAMP\"}'", - "session_end": "curl -X POST http://localhost:8000/api/sessions/end -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"end_time\": \"$TIMESTAMP\"}'", - "conversation_update": "curl -X POST http://localhost:8000/api/conversations -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"content\": \"$CONTENT\"}'", - "tool_call": "curl -X POST http://localhost:8000/api/tool-calls -H \"Content-Type: application/json\" -d '{\"tool_name\": \"$TOOL_NAME\", \"parameters\": $TOOL_PARAMS, \"result_status\": \"$RESULT_STATUS\", \"execution_time_ms\": $EXECUTION_TIME}'", - "file_modified": "curl -X POST http://localhost:8000/api/activities -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"file_path\": \"$FILE_PATH\", \"action\": \"$ACTION\"}'" - } -} \ No newline at end of file diff --git a/app/dashboard/static/claude-hooks-comprehensive.json b/app/dashboard/static/claude-hooks-comprehensive.json deleted file mode 100644 index fdc0196..0000000 --- a/app/dashboard/static/claude-hooks-comprehensive.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "hooks": { - "session_start": "curl -X POST http://localhost:8000/api/sessions/start -H \"Content-Type: application/json\" -d '{\"project_path\": \"$PWD\", \"start_time\": \"$TIMESTAMP\", \"user\": \"$USER\"}'", - "session_end": "curl -X POST http://localhost:8000/api/sessions/end -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"end_time\": \"$TIMESTAMP\"}'", - "conversation_update": "curl -X POST http://localhost:8000/api/conversations -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"content\": \"$CONTENT\", \"timestamp\": \"$TIMESTAMP\"}'", - "tool_call": "curl -X POST http://localhost:8000/api/tool-calls -H \"Content-Type: application/json\" -d '{\"tool_name\": \"$TOOL_NAME\", \"parameters\": $TOOL_PARAMS, \"result_status\": \"$RESULT_STATUS\", \"execution_time_ms\": $EXECUTION_TIME, \"timestamp\": \"$TIMESTAMP\"}'", - "file_modified": "curl -X POST http://localhost:8000/api/activities -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"file_path\": \"$FILE_PATH\", \"action\": \"$ACTION\", \"timestamp\": \"$TIMESTAMP\"}'", - "tool_error": "curl -X POST http://localhost:8000/api/hooks/tool-error -H \"Content-Type: application/json\" -d '{\"tool_name\": \"$TOOL_NAME\", \"error_type\": \"$ERROR_TYPE\", \"error_message\": \"$ERROR_MESSAGE\", \"stack_trace\": \"$STACK_TRACE\", \"parameters\": $TOOL_PARAMS}'", - "waiting_period_start": "curl -X POST http://localhost:8000/api/hooks/waiting-period -H \"Content-Type: application/json\" -d '{\"reason\": \"thinking\", \"context\": \"$CONTEXT\"}'", - "waiting_period_end": "curl -X POST http://localhost:8000/api/hooks/waiting-period -H \"Content-Type: application/json\" -d '{\"reason\": \"thinking\", \"duration_ms\": $DURATION_MS, \"end_time\": \"$TIMESTAMP\"}'", - "memory_usage": "curl -X POST http://localhost:8000/api/hooks/performance -H \"Content-Type: application/json\" -d '{\"metric_type\": \"memory\", \"value\": $MEMORY_MB, \"unit\": \"MB\", \"threshold_exceeded\": $THRESHOLD_EXCEEDED}'", - "large_file_warning": "curl -X POST http://localhost:8000/api/hooks/performance -H \"Content-Type: application/json\" -d '{\"metric_type\": \"file_size\", \"value\": $FILE_SIZE_MB, \"unit\": \"MB\", \"threshold_exceeded\": true}'", - "code_analysis": "curl -X POST http://localhost:8000/api/hooks/code-quality -H \"Content-Type: application/json\" -d '{\"event_type\": \"analysis\", \"file_path\": \"$FILE_PATH\", \"tool_name\": \"$ANALYSIS_TOOL\", \"status\": \"$STATUS\", \"issues_count\": $ISSUES_COUNT, \"details\": $DETAILS}'", - "test_execution": "curl -X POST http://localhost:8000/api/hooks/code-quality -H \"Content-Type: application/json\" -d '{\"event_type\": \"test\", \"tool_name\": \"$TEST_FRAMEWORK\", \"status\": \"$STATUS\", \"details\": {\"passed\": $PASSED_COUNT, \"failed\": $FAILED_COUNT}, \"duration_ms\": $DURATION_MS}'", - "build_process": "curl -X POST http://localhost:8000/api/hooks/code-quality -H \"Content-Type: application/json\" -d '{\"event_type\": \"build\", \"tool_name\": \"$BUILD_TOOL\", \"status\": \"$STATUS\", \"duration_ms\": $DURATION_MS}'", - "dependency_change": "curl -X POST http://localhost:8000/api/hooks/environment -H \"Content-Type: application/json\" -d '{\"event_type\": \"dependency_change\", \"config_file\": \"$PACKAGE_FILE\", \"changes\": {\"action\": \"$ACTION\", \"package\": \"$PACKAGE_NAME\", \"version\": \"$VERSION\"}}'", - "context_switch": "curl -X POST http://localhost:8000/api/hooks/workflow -H \"Content-Type: application/json\" -d '{\"event_type\": \"context_switch\", \"description\": \"Switched to $NEW_PROJECT\", \"metadata\": {\"from\": \"$OLD_PROJECT\", \"to\": \"$NEW_PROJECT\"}}'", - "search_query": "curl -X POST http://localhost:8000/api/hooks/workflow -H \"Content-Type: application/json\" -d '{\"event_type\": \"search_query\", \"description\": \"$SEARCH_QUERY\", \"metadata\": {\"search_type\": \"$SEARCH_TYPE\", \"context\": \"$CONTEXT\"}}'", - "browser_tab": "curl -X POST http://localhost:8000/api/hooks/workflow -H \"Content-Type: application/json\" -d '{\"event_type\": \"browser_tab\", \"description\": \"$TAB_TITLE\", \"metadata\": {\"url\": \"$TAB_URL\", \"category\": \"$TAB_CATEGORY\"}}'", - "copy_paste": "curl -X POST http://localhost:8000/api/hooks/workflow -H \"Content-Type: application/json\" -d '{\"event_type\": \"copy_paste\", \"description\": \"Code copied/pasted\", \"metadata\": {\"action\": \"$ACTION\", \"source\": \"$SOURCE\", \"lines\": $LINE_COUNT}}'", - "external_resource": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"external_resource\", \"interaction_type\": \"$RESOURCE_TYPE\", \"resource_url\": \"$URL\", \"query_or_topic\": \"$TOPIC\"}'", - "ai_question": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"ai_question\", \"query_or_topic\": \"$QUESTION\", \"metadata\": {\"question_type\": \"$QUESTION_TYPE\", \"complexity\": \"$COMPLEXITY\"}}'", - "code_explanation": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"code_explanation\", \"query_or_topic\": \"$CODE_CONTEXT\", \"metadata\": {\"explanation_type\": \"$TYPE\", \"code_lines\": $CODE_LINES}}'", - "review_request": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"review_request\", \"query_or_topic\": \"$REVIEW_SCOPE\", \"metadata\": {\"files_count\": $FILES_COUNT, \"review_type\": \"$REVIEW_TYPE\"}}'", - "refactor_start": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"refactor\", \"scope\": \"$SCOPE\", \"complexity\": \"$COMPLEXITY\", \"files_affected\": $FILES_LIST}'", - "refactor_end": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"refactor\", \"end_time\": \"$TIMESTAMP\", \"duration_minutes\": $DURATION_MIN, \"outcome\": \"$OUTCOME\", \"notes\": \"$NOTES\"}'", - "feature_flag": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"feature_flag\", \"scope\": \"$SCOPE\", \"notes\": \"Feature flag: $FLAG_NAME - $ACTION\"}'", - "debugging_session": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"debugging_session\", \"complexity\": \"$COMPLEXITY\", \"files_affected\": $FILES_LIST, \"notes\": \"$DEBUG_CONTEXT\"}'", - "documentation_update": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"documentation_update\", \"scope\": \"small\", \"files_affected\": [\"$DOC_FILE\"], \"notes\": \"$UPDATE_DESCRIPTION\"}'", - "environment_change": "curl -X POST http://localhost:8000/api/hooks/environment -H \"Content-Type: application/json\" -d '{\"event_type\": \"env_change\", \"environment\": \"$NEW_ENV\", \"impact_level\": \"$IMPACT_LEVEL\"}'", - "config_update": "curl -X POST http://localhost:8000/api/hooks/environment -H \"Content-Type: application/json\" -d '{\"event_type\": \"config_update\", \"config_file\": \"$CONFIG_FILE\", \"changes\": $CONFIG_CHANGES, \"impact_level\": \"$IMPACT_LEVEL\"}'", - "security_scan": "curl -X POST http://localhost:8000/api/hooks/environment -H \"Content-Type: application/json\" -d '{\"event_type\": \"security_scan\", \"changes\": {\"tool\": \"$SCAN_TOOL\", \"vulnerabilities\": $VULN_COUNT, \"severity\": \"$MAX_SEVERITY\"}}'", - "performance_benchmark": "curl -X POST http://localhost:8000/api/hooks/environment -H \"Content-Type: application/json\" -d '{\"event_type\": \"performance_benchmark\", \"changes\": {\"benchmark_type\": \"$BENCHMARK_TYPE\", \"results\": $BENCHMARK_RESULTS}}'", - "learning_session": "curl -X POST http://localhost:8000/api/hooks/learning -H \"Content-Type: application/json\" -d '{\"event_type\": \"learning_session\", \"topic\": \"$LEARNING_TOPIC\", \"confidence_before\": $CONFIDENCE_BEFORE, \"confidence_after\": $CONFIDENCE_AFTER, \"duration_ms\": $DURATION_MS}'", - "tutorial_follow": "curl -X POST http://localhost:8000/api/hooks/learning -H \"Content-Type: application/json\" -d '{\"event_type\": \"tutorial\", \"topic\": \"$TUTORIAL_TOPIC\", \"resource_url\": \"$TUTORIAL_URL\", \"notes\": \"$TUTORIAL_NOTES\"}'", - "experimentation": "curl -X POST http://localhost:8000/api/hooks/learning -H \"Content-Type: application/json\" -d '{\"event_type\": \"experimentation\", \"topic\": \"$EXPERIMENT_TYPE\", \"notes\": \"$EXPERIMENT_DESCRIPTION\"}'", - "knowledge_gap": "curl -X POST http://localhost:8000/api/hooks/learning -H \"Content-Type: application/json\" -d '{\"event_type\": \"knowledge_gap\", \"topic\": \"$UNKNOWN_CONCEPT\", \"notes\": \"$GAP_DESCRIPTION\"}'", - "manual_testing": "curl -X POST http://localhost:8000/api/hooks/code-quality -H \"Content-Type: application/json\" -d '{\"event_type\": \"manual_test\", \"status\": \"$TEST_RESULT\", \"details\": {\"test_type\": \"$TEST_TYPE\", \"scenarios\": $SCENARIO_COUNT}, \"duration_ms\": $DURATION_MS}'", - "bug_reproduction": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"bug_reproduction\", \"complexity\": \"$BUG_COMPLEXITY\", \"notes\": \"$BUG_DESCRIPTION\", \"outcome\": \"$REPRODUCTION_RESULT\"}'", - "edge_case_testing": "curl -X POST http://localhost:8000/api/hooks/code-quality -H \"Content-Type: application/json\" -d '{\"event_type\": \"edge_case_test\", \"status\": \"$TEST_RESULT\", \"details\": {\"edge_cases\": $EDGE_CASE_COUNT, \"findings\": \"$FINDINGS\"}}'", - "user_feedback": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"user_feedback\", \"query_or_topic\": \"$FEEDBACK_TOPIC\", \"response_quality\": $FEEDBACK_RATING, \"metadata\": {\"feedback_type\": \"$FEEDBACK_TYPE\", \"urgency\": \"$URGENCY\"}}'" - }, - "hook_settings": { - "timeout": 10, - "retry_count": 3, - "async": true, - "log_errors": true, - "log_file": "~/.claude-hooks.log" - } -} \ No newline at end of file diff --git a/app/dashboard/static/claude-hooks-developer.json b/app/dashboard/static/claude-hooks-developer.json deleted file mode 100644 index 68b42c1..0000000 --- a/app/dashboard/static/claude-hooks-developer.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "hooks": { - "conversation_update": "curl -X POST http://localhost:8000/api/conversations -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"content\": \"$CONTENT\", \"timestamp\": \"$TIMESTAMP\"}'", - "waiting_period_start": "curl -X POST http://localhost:8000/api/hooks/waiting-period -H \"Content-Type: application/json\" -d '{\"reason\": \"thinking\", \"context\": \"$CONTEXT\"}'", - "tool_error": "curl -X POST http://localhost:8000/api/hooks/tool-error -H \"Content-Type: application/json\" -d '{\"tool_name\": \"$TOOL_NAME\", \"error_type\": \"$ERROR_TYPE\", \"error_message\": \"$ERROR_MESSAGE\", \"stack_trace\": \"$STACK_TRACE\", \"parameters\": $TOOL_PARAMS}'", - "tool_call": "curl -X POST http://localhost:8000/api/tool-calls -H \"Content-Type: application/json\" -d '{\"tool_name\": \"$TOOL_NAME\", \"parameters\": $TOOL_PARAMS, \"result_status\": \"$RESULT_STATUS\", \"execution_time_ms\": $EXECUTION_TIME, \"timestamp\": \"$TIMESTAMP\"}'", - "test_execution": "curl -X POST http://localhost:8000/api/hooks/code-quality -H \"Content-Type: application/json\" -d '{\"event_type\": \"test\", \"tool_name\": \"$TEST_FRAMEWORK\", \"status\": \"$STATUS\", \"details\": {\"passed\": $PASSED_COUNT, \"failed\": $FAILED_COUNT}, \"duration_ms\": $DURATION_MS}'", - "session_start": "curl -X POST http://localhost:8000/api/sessions/start -H \"Content-Type: application/json\" -d '{\"project_path\": \"$PWD\", \"start_time\": \"$TIMESTAMP\", \"user\": \"$USER\"}'", - "waiting_period_end": "curl -X POST http://localhost:8000/api/hooks/waiting-period -H \"Content-Type: application/json\" -d '{\"reason\": \"thinking\", \"duration_ms\": $DURATION_MS, \"end_time\": \"$TIMESTAMP\"}'", - "large_file_warning": "curl -X POST http://localhost:8000/api/hooks/performance -H \"Content-Type: application/json\" -d '{\"metric_type\": \"file_size\", \"value\": $FILE_SIZE_MB, \"unit\": \"MB\", \"threshold_exceeded\": true}'", - "session_end": "curl -X POST http://localhost:8000/api/sessions/end -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"end_time\": \"$TIMESTAMP\"}'", - "memory_usage": "curl -X POST http://localhost:8000/api/hooks/performance -H \"Content-Type: application/json\" -d '{\"metric_type\": \"memory\", \"value\": $MEMORY_MB, \"unit\": \"MB\", \"threshold_exceeded\": $THRESHOLD_EXCEEDED}'", - "code_analysis": "curl -X POST http://localhost:8000/api/hooks/code-quality -H \"Content-Type: application/json\" -d '{\"event_type\": \"analysis\", \"file_path\": \"$FILE_PATH\", \"tool_name\": \"$ANALYSIS_TOOL\", \"status\": \"$STATUS\", \"issues_count\": $ISSUES_COUNT, \"details\": $DETAILS}'", - "dependency_change": "curl -X POST http://localhost:8000/api/hooks/environment -H \"Content-Type: application/json\" -d '{\"event_type\": \"dependency_change\", \"config_file\": \"$PACKAGE_FILE\", \"changes\": {\"action\": \"$ACTION\", \"package\": \"$PACKAGE_NAME\", \"version\": \"$VERSION\"}}'", - "file_modified": "curl -X POST http://localhost:8000/api/activities -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"file_path\": \"$FILE_PATH\", \"action\": \"$ACTION\", \"timestamp\": \"$TIMESTAMP\"}'", - "build_process": "curl -X POST http://localhost:8000/api/hooks/code-quality -H \"Content-Type: application/json\" -d '{\"event_type\": \"build\", \"tool_name\": \"$BUILD_TOOL\", \"status\": \"$STATUS\", \"duration_ms\": $DURATION_MS}'" - }, - "hook_settings": { - "timeout": 10, - "retry_count": 3, - "async": true, - "log_errors": true, - "log_file": "~/.claude-hooks.log" - } -} \ No newline at end of file diff --git a/app/dashboard/static/claude-hooks-essential.json b/app/dashboard/static/claude-hooks-essential.json deleted file mode 100644 index 109d422..0000000 --- a/app/dashboard/static/claude-hooks-essential.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "hooks": { - "conversation_update": "curl -X POST http://localhost:8000/api/conversations -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"content\": \"$CONTENT\", \"timestamp\": \"$TIMESTAMP\"}'", - "tool_call": "curl -X POST http://localhost:8000/api/tool-calls -H \"Content-Type: application/json\" -d '{\"tool_name\": \"$TOOL_NAME\", \"parameters\": $TOOL_PARAMS, \"result_status\": \"$RESULT_STATUS\", \"execution_time_ms\": $EXECUTION_TIME, \"timestamp\": \"$TIMESTAMP\"}'", - "session_start": "curl -X POST http://localhost:8000/api/sessions/start -H \"Content-Type: application/json\" -d '{\"project_path\": \"$PWD\", \"start_time\": \"$TIMESTAMP\", \"user\": \"$USER\"}'", - "session_end": "curl -X POST http://localhost:8000/api/sessions/end -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"end_time\": \"$TIMESTAMP\"}'", - "file_modified": "curl -X POST http://localhost:8000/api/activities -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"file_path\": \"$FILE_PATH\", \"action\": \"$ACTION\", \"timestamp\": \"$TIMESTAMP\"}'" - }, - "hook_settings": { - "timeout": 10, - "retry_count": 3, - "async": true, - "log_errors": true, - "log_file": "~/.claude-hooks.log" - } -} \ No newline at end of file diff --git a/app/dashboard/static/claude-hooks-power_user.json b/app/dashboard/static/claude-hooks-power_user.json deleted file mode 100644 index 8c12cc7..0000000 --- a/app/dashboard/static/claude-hooks-power_user.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "hooks": { - "refactor_end": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"refactor\", \"end_time\": \"$TIMESTAMP\", \"duration_minutes\": $DURATION_MIN, \"outcome\": \"$OUTCOME\", \"notes\": \"$NOTES\"}'", - "browser_tab": "curl -X POST http://localhost:8000/api/hooks/workflow -H \"Content-Type: application/json\" -d '{\"event_type\": \"browser_tab\", \"description\": \"$TAB_TITLE\", \"metadata\": {\"url\": \"$TAB_URL\", \"category\": \"$TAB_CATEGORY\"}}'", - "search_query": "curl -X POST http://localhost:8000/api/hooks/workflow -H \"Content-Type: application/json\" -d '{\"event_type\": \"search_query\", \"description\": \"$SEARCH_QUERY\", \"metadata\": {\"search_type\": \"$SEARCH_TYPE\", \"context\": \"$CONTEXT\"}}'", - "conversation_update": "curl -X POST http://localhost:8000/api/conversations -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"content\": \"$CONTENT\", \"timestamp\": \"$TIMESTAMP\"}'", - "tool_call": "curl -X POST http://localhost:8000/api/tool-calls -H \"Content-Type: application/json\" -d '{\"tool_name\": \"$TOOL_NAME\", \"parameters\": $TOOL_PARAMS, \"result_status\": \"$RESULT_STATUS\", \"execution_time_ms\": $EXECUTION_TIME, \"timestamp\": \"$TIMESTAMP\"}'", - "session_start": "curl -X POST http://localhost:8000/api/sessions/start -H \"Content-Type: application/json\" -d '{\"project_path\": \"$PWD\", \"start_time\": \"$TIMESTAMP\", \"user\": \"$USER\"}'", - "waiting_period_end": "curl -X POST http://localhost:8000/api/hooks/waiting-period -H \"Content-Type: application/json\" -d '{\"reason\": \"thinking\", \"duration_ms\": $DURATION_MS, \"end_time\": \"$TIMESTAMP\"}'", - "debugging_session": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"debugging_session\", \"complexity\": \"$COMPLEXITY\", \"files_affected\": $FILES_LIST, \"notes\": \"$DEBUG_CONTEXT\"}'", - "session_end": "curl -X POST http://localhost:8000/api/sessions/end -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"end_time\": \"$TIMESTAMP\"}'", - "memory_usage": "curl -X POST http://localhost:8000/api/hooks/performance -H \"Content-Type: application/json\" -d '{\"metric_type\": \"memory\", \"value\": $MEMORY_MB, \"unit\": \"MB\", \"threshold_exceeded\": $THRESHOLD_EXCEEDED}'", - "documentation_update": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"documentation_update\", \"scope\": \"small\", \"files_affected\": [\"$DOC_FILE\"], \"notes\": \"$UPDATE_DESCRIPTION\"}'", - "tool_error": "curl -X POST http://localhost:8000/api/hooks/tool-error -H \"Content-Type: application/json\" -d '{\"tool_name\": \"$TOOL_NAME\", \"error_type\": \"$ERROR_TYPE\", \"error_message\": \"$ERROR_MESSAGE\", \"stack_trace\": \"$STACK_TRACE\", \"parameters\": $TOOL_PARAMS}'", - "refactor_start": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"refactor\", \"scope\": \"$SCOPE\", \"complexity\": \"$COMPLEXITY\", \"files_affected\": $FILES_LIST}'", - "copy_paste": "curl -X POST http://localhost:8000/api/hooks/workflow -H \"Content-Type: application/json\" -d '{\"event_type\": \"copy_paste\", \"description\": \"Code copied/pasted\", \"metadata\": {\"action\": \"$ACTION\", \"source\": \"$SOURCE\", \"lines\": $LINE_COUNT}}'", - "file_modified": "curl -X POST http://localhost:8000/api/activities -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"file_path\": \"$FILE_PATH\", \"action\": \"$ACTION\", \"timestamp\": \"$TIMESTAMP\"}'", - "waiting_period_start": "curl -X POST http://localhost:8000/api/hooks/waiting-period -H \"Content-Type: application/json\" -d '{\"reason\": \"thinking\", \"context\": \"$CONTEXT\"}'", - "feature_flag": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"feature_flag\", \"scope\": \"$SCOPE\", \"notes\": \"Feature flag: $FLAG_NAME - $ACTION\"}'", - "large_file_warning": "curl -X POST http://localhost:8000/api/hooks/performance -H \"Content-Type: application/json\" -d '{\"metric_type\": \"file_size\", \"value\": $FILE_SIZE_MB, \"unit\": \"MB\", \"threshold_exceeded\": true}'", - "context_switch": "curl -X POST http://localhost:8000/api/hooks/workflow -H \"Content-Type: application/json\" -d '{\"event_type\": \"context_switch\", \"description\": \"Switched to $NEW_PROJECT\", \"metadata\": {\"from\": \"$OLD_PROJECT\", \"to\": \"$NEW_PROJECT\"}}'" - }, - "hook_settings": { - "timeout": 10, - "retry_count": 3, - "async": true, - "log_errors": true, - "log_file": "~/.claude-hooks.log" - } -} \ No newline at end of file diff --git a/app/dashboard/static/claude-hooks-research.json b/app/dashboard/static/claude-hooks-research.json deleted file mode 100644 index d561354..0000000 --- a/app/dashboard/static/claude-hooks-research.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "hooks": { - "conversation_update": "curl -X POST http://localhost:8000/api/conversations -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"content\": \"$CONTENT\", \"timestamp\": \"$TIMESTAMP\"}'", - "refactor_end": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"refactor\", \"end_time\": \"$TIMESTAMP\", \"duration_minutes\": $DURATION_MIN, \"outcome\": \"$OUTCOME\", \"notes\": \"$NOTES\"}'", - "code_explanation": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"code_explanation\", \"query_or_topic\": \"$CODE_CONTEXT\", \"metadata\": {\"explanation_type\": \"$TYPE\", \"code_lines\": $CODE_LINES}}'", - "feature_flag": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"feature_flag\", \"scope\": \"$SCOPE\", \"notes\": \"Feature flag: $FLAG_NAME - $ACTION\"}'", - "tool_call": "curl -X POST http://localhost:8000/api/tool-calls -H \"Content-Type: application/json\" -d '{\"tool_name\": \"$TOOL_NAME\", \"parameters\": $TOOL_PARAMS, \"result_status\": \"$RESULT_STATUS\", \"execution_time_ms\": $EXECUTION_TIME, \"timestamp\": \"$TIMESTAMP\"}'", - "learning_session": "curl -X POST http://localhost:8000/api/hooks/learning -H \"Content-Type: application/json\" -d '{\"event_type\": \"learning_session\", \"topic\": \"$LEARNING_TOPIC\", \"confidence_before\": $CONFIDENCE_BEFORE, \"confidence_after\": $CONFIDENCE_AFTER, \"duration_ms\": $DURATION_MS}'", - "tutorial_follow": "curl -X POST http://localhost:8000/api/hooks/learning -H \"Content-Type: application/json\" -d '{\"event_type\": \"tutorial\", \"topic\": \"$TUTORIAL_TOPIC\", \"resource_url\": \"$TUTORIAL_URL\", \"notes\": \"$TUTORIAL_NOTES\"}'", - "session_start": "curl -X POST http://localhost:8000/api/sessions/start -H \"Content-Type: application/json\" -d '{\"project_path\": \"$PWD\", \"start_time\": \"$TIMESTAMP\", \"user\": \"$USER\"}'", - "ai_question": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"ai_question\", \"query_or_topic\": \"$QUESTION\", \"metadata\": {\"question_type\": \"$QUESTION_TYPE\", \"complexity\": \"$COMPLEXITY\"}}'", - "external_resource": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"external_resource\", \"interaction_type\": \"$RESOURCE_TYPE\", \"resource_url\": \"$URL\", \"query_or_topic\": \"$TOPIC\"}'", - "debugging_session": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"debugging_session\", \"complexity\": \"$COMPLEXITY\", \"files_affected\": $FILES_LIST, \"notes\": \"$DEBUG_CONTEXT\"}'", - "session_end": "curl -X POST http://localhost:8000/api/sessions/end -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"end_time\": \"$TIMESTAMP\"}'", - "experimentation": "curl -X POST http://localhost:8000/api/hooks/learning -H \"Content-Type: application/json\" -d '{\"event_type\": \"experimentation\", \"topic\": \"$EXPERIMENT_TYPE\", \"notes\": \"$EXPERIMENT_DESCRIPTION\"}'", - "knowledge_gap": "curl -X POST http://localhost:8000/api/hooks/learning -H \"Content-Type: application/json\" -d '{\"event_type\": \"knowledge_gap\", \"topic\": \"$UNKNOWN_CONCEPT\", \"notes\": \"$GAP_DESCRIPTION\"}'", - "refactor_start": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"refactor\", \"scope\": \"$SCOPE\", \"complexity\": \"$COMPLEXITY\", \"files_affected\": $FILES_LIST}'", - "review_request": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"review_request\", \"query_or_topic\": \"$REVIEW_SCOPE\", \"metadata\": {\"files_count\": $FILES_COUNT, \"review_type\": \"$REVIEW_TYPE\"}}'", - "file_modified": "curl -X POST http://localhost:8000/api/activities -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"file_path\": \"$FILE_PATH\", \"action\": \"$ACTION\", \"timestamp\": \"$TIMESTAMP\"}'", - "documentation_update": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"documentation_update\", \"scope\": \"small\", \"files_affected\": [\"$DOC_FILE\"], \"notes\": \"$UPDATE_DESCRIPTION\"}'" - }, - "hook_settings": { - "timeout": 10, - "retry_count": 3, - "async": true, - "log_errors": true, - "log_file": "~/.claude-hooks.log" - } -} \ No newline at end of file diff --git a/app/dashboard/static/claude-hooks-team.json b/app/dashboard/static/claude-hooks-team.json deleted file mode 100644 index 7a33626..0000000 --- a/app/dashboard/static/claude-hooks-team.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "hooks": { - "conversation_update": "curl -X POST http://localhost:8000/api/conversations -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"content\": \"$CONTENT\", \"timestamp\": \"$TIMESTAMP\"}'", - "refactor_end": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"refactor\", \"end_time\": \"$TIMESTAMP\", \"duration_minutes\": $DURATION_MIN, \"outcome\": \"$OUTCOME\", \"notes\": \"$NOTES\"}'", - "code_explanation": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"code_explanation\", \"query_or_topic\": \"$CODE_CONTEXT\", \"metadata\": {\"explanation_type\": \"$TYPE\", \"code_lines\": $CODE_LINES}}'", - "edge_case_testing": "curl -X POST http://localhost:8000/api/hooks/code-quality -H \"Content-Type: application/json\" -d '{\"event_type\": \"edge_case_test\", \"status\": \"$TEST_RESULT\", \"details\": {\"edge_cases\": $EDGE_CASE_COUNT, \"findings\": \"$FINDINGS\"}}'", - "feature_flag": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"feature_flag\", \"scope\": \"$SCOPE\", \"notes\": \"Feature flag: $FLAG_NAME - $ACTION\"}'", - "tool_call": "curl -X POST http://localhost:8000/api/tool-calls -H \"Content-Type: application/json\" -d '{\"tool_name\": \"$TOOL_NAME\", \"parameters\": $TOOL_PARAMS, \"result_status\": \"$RESULT_STATUS\", \"execution_time_ms\": $EXECUTION_TIME, \"timestamp\": \"$TIMESTAMP\"}'", - "session_start": "curl -X POST http://localhost:8000/api/sessions/start -H \"Content-Type: application/json\" -d '{\"project_path\": \"$PWD\", \"start_time\": \"$TIMESTAMP\", \"user\": \"$USER\"}'", - "ai_question": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"ai_question\", \"query_or_topic\": \"$QUESTION\", \"metadata\": {\"question_type\": \"$QUESTION_TYPE\", \"complexity\": \"$COMPLEXITY\"}}'", - "external_resource": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"external_resource\", \"interaction_type\": \"$RESOURCE_TYPE\", \"resource_url\": \"$URL\", \"query_or_topic\": \"$TOPIC\"}'", - "debugging_session": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"debugging_session\", \"complexity\": \"$COMPLEXITY\", \"files_affected\": $FILES_LIST, \"notes\": \"$DEBUG_CONTEXT\"}'", - "session_end": "curl -X POST http://localhost:8000/api/sessions/end -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"end_time\": \"$TIMESTAMP\"}'", - "manual_testing": "curl -X POST http://localhost:8000/api/hooks/code-quality -H \"Content-Type: application/json\" -d '{\"event_type\": \"manual_test\", \"status\": \"$TEST_RESULT\", \"details\": {\"test_type\": \"$TEST_TYPE\", \"scenarios\": $SCENARIO_COUNT}, \"duration_ms\": $DURATION_MS}'", - "bug_reproduction": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"bug_reproduction\", \"complexity\": \"$BUG_COMPLEXITY\", \"notes\": \"$BUG_DESCRIPTION\", \"outcome\": \"$REPRODUCTION_RESULT\"}'", - "user_feedback": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"user_feedback\", \"query_or_topic\": \"$FEEDBACK_TOPIC\", \"response_quality\": $FEEDBACK_RATING, \"metadata\": {\"feedback_type\": \"$FEEDBACK_TYPE\", \"urgency\": \"$URGENCY\"}}'", - "review_request": "curl -X POST http://localhost:8000/api/hooks/collaboration -H \"Content-Type: application/json\" -d '{\"event_type\": \"review_request\", \"query_or_topic\": \"$REVIEW_SCOPE\", \"metadata\": {\"files_count\": $FILES_COUNT, \"review_type\": \"$REVIEW_TYPE\"}}'", - "file_modified": "curl -X POST http://localhost:8000/api/activities -H \"Content-Type: application/json\" -d '{\"session_id\": \"$SESSION_ID\", \"file_path\": \"$FILE_PATH\", \"action\": \"$ACTION\", \"timestamp\": \"$TIMESTAMP\"}'", - "refactor_start": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"refactor\", \"scope\": \"$SCOPE\", \"complexity\": \"$COMPLEXITY\", \"files_affected\": $FILES_LIST}'", - "documentation_update": "curl -X POST http://localhost:8000/api/hooks/project-intelligence -H \"Content-Type: application/json\" -d '{\"event_type\": \"documentation_update\", \"scope\": \"small\", \"files_affected\": [\"$DOC_FILE\"], \"notes\": \"$UPDATE_DESCRIPTION\"}'" - }, - "hook_settings": { - "timeout": 10, - "retry_count": 3, - "async": true, - "log_errors": true, - "log_file": "~/.claude-hooks.log" - } -} \ No newline at end of file diff --git a/app/dashboard/static/js/api-client.js b/app/dashboard/static/js/api-client.js index 24fef0e..24ec8d2 100644 --- a/app/dashboard/static/js/api-client.js +++ b/app/dashboard/static/js/api-client.js @@ -92,14 +92,6 @@ class ApiClient { } // Conversations API - async getConversations(projectId = null, limit = 50, offset = 0) { - let url = `/conversations?limit=${limit}&offset=${offset}`; - if (projectId) { - url += `&project_id=${projectId}`; - } - return this.request(url); - } - async searchConversations(query, projectId = null, limit = 20) { let url = `/conversations/search?query=${encodeURIComponent(query)}&limit=${limit}`; if (projectId) { diff --git a/app/dashboard/templates/base.html b/app/dashboard/templates/base.html index 91846fa..54c9471 100644 --- a/app/dashboard/templates/base.html +++ b/app/dashboard/templates/base.html @@ -47,24 +47,12 @@ Conversations - -