# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

@docs/claude/mcp-integration.md
@docs/claude/development-commands.md
@docs/claude/architecture.md
@docs/claude/framework-personas.md
@docs/claude/scheduler-queue-pipeline.md
@docs/claude/scheduler-queue-pipeline-persona.md
@docs/claude/magiclinks-system.md
@docs/claude/guidelines.md
@docs/claude/common-workflows.md
@docs/claude/error-handling.md
@docs/claude/security-patterns.md
@docs/claude/queue-system.md
@docs/claude/event-system.md
@docs/claude/async-components.md
@docs/claude/console-commands.md
@docs/claude/database-patterns.md
@docs/claude/performance-monitoring.md
@docs/claude/troubleshooting.md

## MCP Server Integration 🤖

**IMPORTANT**: This project has a fully functional MCP (Model Context Protocol) server that provides direct access to framework internals.

### Quick Access Commands:
```bash
# Start MCP server
docker exec -i php php console.php mcp:server

# Test MCP server
echo '{"jsonrpc": "2.0", "method": "initialize", "params": {}}' | docker exec -i php php console.php mcp:server
```

### Available MCP Tools:
- `analyze_routes`: Get all registered routes in the framework
- `analyze_container_bindings`: Analyze DI container bindings
- `discover_attributes`: Discover attributes by type
- `framework_health_check`: Health check of framework components
- `list_framework_modules`: List all framework modules
- `list_directory`: List directory contents (project-scoped)
- `read_file`: Read file contents with line limits
- `find_files`: Find files by pattern

### MCP Resources:
- `framework://config`: Framework configuration and environment

### Configuration for Claude Desktop:
```json
{
  "mcpServers": {
    "custom-php-framework": {
      "command": "docker",
      "args": ["exec", "-i", "php", "php", "console.php", "mcp:server"],
      "cwd": "/home/michael/dev/michaelschiemer"
    }
  }
}
```

## Development Commands

### PHP Development
- `composer install` - Install PHP dependencies
- `composer cs` - Run code style checks (dry-run)
- `composer cs-fix` - Fix code style issues
- `composer reload` - Dump autoloader with optimization
- `./vendor/bin/pest` - Run PHP tests (using Pest testing framework)
- Run phpstan always with the make command

### Frontend Development
- `npm install` - Install Node.js dependencies
- `npm run dev` - Start Vite development server with HTTPS
- `npm run build` - Build production assets and copy to public/
- `npm run preview` - Preview production build
- `npm run test` - Run Jest tests
- `npm run deploy` - Build and deploy assets to public/

### Local Development Access
- **Framework URL**: https://localhost
- **HTTPS Required**: HTTPS is mandatory - HTTP requests will be rejected
- **SSL Certificates**: Automatically configured for local development
- **User Agent Required**: Always use a browser User-Agent header to avoid triggering firewall rules

### HTTP Client Configuration
When making HTTP requests to the framework, always include a browser User-Agent:

```bash
# cURL with browser User-Agent
curl -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" \
     https://localhost/api/endpoint

# Testing API endpoints
curl -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36" \
     -H "Content-Type: application/json" \
     -d '{"key": "value"}' \
     https://localhost/api/test
```

### Docker & Environment
- `make up` - Start all Docker containers
- `make down` - Stop all containers
- `make build` - Build Docker images
- `make logs` - View Docker logs
- `make reload` - Dump autoloader and restart PHP container
- `make console` - Run console commands in Docker PHP container
- `make cs` - Run code style checks in Docker
- `make cs-fix` - Fix code style in Docker
- `make cs-fix-file FILE=path/to/file.php` - Fix code style for specific file
- `make fix-perms` - Fix file permissions
- `make doctor` - Check prerequisites and project health

### Console Commands
- `php console.php` - Run console application
- `docker exec php php console.php` - Run console in Docker
- `php console.php mcp:server` - Start MCP server for AI integration

### Database & Migration Commands
- `php console.php make:migration CreateUsersTable [Domain]` - Generate new migration file
- `php console.php db:migrate` - Apply all pending migrations
- `php console.php db:rollback [steps]` - Rollback migrations (default: 1 step)
- `php console.php db:status` - Show migration status across all domains

### Testing
- **All test files** must be placed in `tests/` directory
- **PHP test scripts** (including non-Pest tests) belong in `tests/` directory
- **Debug scripts**: Place debug PHP scripts in `tests/debug/` directory
- **Pest preferred**: Always prefer Pest over PHPUnit for new tests
- **No mocking**: Avoid mocking - use real implementations and test data
- **Directory structure**: Tests should mirror source directory structure
- **PHPUnit configuration** in `phpunit.xml` (supports both Pest and PHPUnit)

**Test Directory Structure:**
```
tests/
├── debug/           # Debug and development scripts
│   └── test-*.php   # Debug scripts for testing functionality
├── Unit/            # Unit tests mirroring src/ structure
├── Feature/         # Feature/integration tests
├── tmp/             # Temporary test files (gitignored)
└── pest.php         # Pest configuration
```

**Important Test Rules:**
- **Temporary files**: All test temporary files must be created in `tests/tmp/` or `tests/` directory
- **Never create files** in the project root directory during tests
- **Clean up**: Tests should clean up their temporary files after execution
- **Isolation**: Each test should use unique filenames to avoid conflicts

## Architecture Overview

This is a custom PHP framework with the following key architectural patterns:

### Core Components

**Application Bootstrap**
- `src/Framework/Core/Application.php` - Main application class that orchestrates the request lifecycle
- `src/Framework/Core/AppBootstrapper.php` - Bootstraps the application and DI container
- Uses event system for application lifecycle (ApplicationBooted, BeforeHandleRequest, etc.)

**Dependency Injection**
- `src/Framework/DI/Container.php` - DI container interface
- `src/Framework/DI/DefaultContainer.php` - Default container implementation
- Supports binding, singletons, and instance registration
- Automatic dependency resolution and method invocation

**HTTP & Routing**
- Attribute-based routing using `#[Route]` attributes
- `src/Framework/Http/Middlewares/RoutingMiddleware.php` - Core routing middleware
- Middleware chain pattern for request processing
- Support for different result types (JsonResult, ViewResult, Redirect, etc.)
- `HttpRequest` - Standard implementation of the Request interface

**MCP Integration**
- `src/Framework/Mcp/` - Full MCP server implementation
- `#[McpTool]` and `#[McpResource]` attributes for AI integration
- Automatic discovery via framework's attribute system
- Safe, project-scoped file system access for AI

**Framework Principles**
- **No inheritance**: Composition over inheritance - avoid `extends` completely
- **Immutable by design**: Objects should be immutable whenever possible
- **Readonly everywhere**: Classes and properties `readonly` where possible
- **Final by default**: Classes are `final` unless specifically designed for extension
- **Explicit dependency injection**: No global state or service locators
- **Modular architecture**: Minimal external dependencies, clear boundaries
- **Event-driven architecture**: Loose coupling through domain events
- **Automatic discovery**: Convention over configuration with attribute scanning

[Rest of the file remains unchanged]

## Exception Handling

### Core Exception Handling Principles
- Detailed error context
- Centralized error logging
- Custom exception hierarchy
- Contextual error responses
- Security-focused error masking

### Exception Types
- `FrameworkException`: Base framework exception
- `ConfigurationException`: Configuration-related errors
- `DatabaseException`: Database connection and query errors
- `ValidationException`: Input validation failures
- `AuthorizationException`: Access control violations
- `ResourceNotFoundException`: Missing resources
- `DependencyInjectionException`: DI container errors
- `SerializationException`: Serialization/deserialization issues

### Logging and Monitoring
- Automatically log all unhandled exceptions
- Include request context in error logs
- Capture stack traces for debugging
- Support for error reporting services
- Performance-aware error tracking

### Error Response Handling
- Detailed errors in development
- Sanitized errors in production
- JSON and HTML error formats
- Localized error messages
- Error code mapping

### Example Exception Handling
```php
final readonly class ExceptionHandler
{
    public function handle(Throwable $exception): HttpResponse
    {
        // Log the exception
        $this->logger->error('Unhandled exception', [
            'message' => $exception->getMessage(),
            'type' => get_class($exception),
            'trace' => $exception->getTraceAsString()
        ]);

        // Determine appropriate response based on exception type
        return match(true) {
            $exception instanceof ValidationException => 
                new JsonErrorResponse(
                    errors: $exception->getValidationErrors(),
                    statusCode: 422
                ),
            $exception instanceof AuthorizationException => 
                new JsonErrorResponse(
                    message: 'Unauthorized access',
                    statusCode: 403
                ),
            $exception instanceof ResourceNotFoundException => 
                new JsonErrorResponse(
                    message: 'Resource not found',
                    statusCode: 404
                ),
            default => new JsonErrorResponse(
                message: 'Internal server error',
                statusCode: 500
            )
        };
    }
}
```

### Security Considerations
- Never expose sensitive error details in production
- Mask internal system information
- Use generic error messages for security-sensitive scenarios
- Log detailed errors server-side
- Implement rate limiting for repeated error conditions

## Value Objects

### CountryCode Value Object
- Represents a standardized country code (ISO 3166-1 alpha-2 and alpha-3)
- Validates and normalizes country code formats
- Ensures type safety for country code representations
```

## Collections and Interfaces

### PHP Collection Interfaces
- Collections implementieren IteratorAggregate + Countable

## Parameter Design 

### Variadic Parameters
- Nutze variadic parameters statt arrays wo immer möglich

## Template System

- Das Templatesystem verwendet kein php sondern Html Template Komponenten und platzhalter in geschwungenen Klammern