# Hephaestus Agent Instructions

This document provides technical guidance for AI coding agents working with Hephaestus MCP server. It contains specifications for Anvil development patterns, tool implementations, and code generation standards using a minimal, focused toolchain.

**Related Documentation:**
- `anvil_yaml_reference.md` - Complete Anvil YAML component configuration specification

## Development Toolchain

Hephaestus uses a minimal, modern toolchain:

### Core Infrastructure
- **Python**: `>=3.13` (modern Python features)
- **Build System**: `hatchling` (minimal, fast builds)
- **MCP Framework**: `fastmcp>=0.11.0` (lightweight MCP server)
- **Dependencies**: Minimal core set (`attrs`, `mcp`, `pyyaml`, `typer`)

### Development Tools
- **Package Manager**: `uv` (fast Python package management)
- **Task Runner**: `just` (command recipes)
- **Linting**: `ruff` (fast Python linting and formatting)
- **Type Checking**: `basedpyright` (minimal type checking)
- **Testing**: `pytest` (minimal testing framework)

### Project Structure
```
hephaestus/
├── src/
│   ├── __init__.py
│   └── server.py          # Main MCP server entry point
├── pyproject.toml         # Hatchling-based configuration
├── justfile              # Development commands
└── Documentation/
```

### Development Commands
- `just run` - Run MCP server
- `just test` - Run tests
- `just lint` - Lint code
- `just format` - Format code
- `just typecheck` - Type check code
- `just build` - Build package

## Development Philosophy

Hephaestus follows a **minimal, focused approach**:

- **Core Functionality First**: Essential Anvil development tools without unnecessary complexity
- **Modern Toolchain**: Python 3.13+, FastMCP, hatchling, and minimal dependencies
- **Developer Experience**: Fast, reliable tooling that stays out of your way
- **Incremental Growth**: Start with core functionality, expand as needed

This contrasts with enterprise-grade comprehensive tooling - we prioritize speed, simplicity, and reliability over extensive feature sets.

## Complete Anvil Development Ecosystem

Hephaestus provides comprehensive tooling for all Anvil development needs, specialising in modern technologies for world-class applications:

### Core Technologies
1. **[Material 3 Theme](https://anvil.works/dependencies/4UK6WHQ6UX7AKELK)** - Modern Material Design 3 components and layouts
2. **[Official Routing](https://anvil.works/dependencies/3PIDO5P3H4VPEMPL)** - Modern routing with data loading and caching
3. **[Reactive Library](https://anvil.works/dependencies/N7KFE4YBWMGWJ5OX)** - Signals-based state management for automatic UI updates
4. **Model Classes** - Type-safe, validated data models with automatic serialisation and relationships
5. **Layouts System** - Slot-based layout architecture replacing traditional panels
6. **Tabulator Integration** - High-performance reactive data tables with model integration

### Intelligent Context System

Every tool execution begins with project analysis to determine the optimal generation approach:

```python
@dataclass
class ProjectContext:
    anvil_version: str
    theme_type: str  # "material-3", "classic", "custom"
    routing_system: str  # "official", "anvil-extras", "none" 
    has_reactive: bool
    data_layer: str  # "model-classes", "anvil-extras-orm", "raw-tables"
    layout_system: str  # "layouts", "traditional", "mixed"
    modernisation_score: float  # 0.0-1.0
    generation_mode: str  # "modern", "hybrid", "legacy-compatible"
    performance_opportunities: List[str]
    breaking_change_risks: List[str]
```

### Smart Tool Routing
- **Modern Apps** (Score 0.8+): Full M3 + Reactive + Routing + Layouts + Model Classes + Enterprise features
- **Transitioning Apps** (Score 0.4-0.8): Enhanced patterns respecting existing architecture + strategic modernisation
- **Legacy Apps** (Score 0-0.4): Compatible patterns + comprehensive support + modernisation suggestions
- **All Apps**: Complete coverage of fundamental operations regardless of architecture

## Tool Categories & Specifications

### Essential Anvil Development (Universal Coverage)

**Foundation Development**
- Data table operations (CRUD, search, relationships, validation)
- User authentication and management (login, signup, permissions, MFA)
- Client-server communication (callable functions, error handling, security)
- Form creation and navigation (basic forms, complex workflows, data binding)
- File and media management (upload, download, processing, storage)

**Advanced UI/UX Development**
- Custom component creation (HTML components, JavaScript integration, event handling)
- Theme and CSS manipulation (custom themes, Material Design, responsive design)
- Interactive interfaces (drag-and-drop, animations, dynamic layouts)
- Cross-platform compatibility (mobile web, PWA features, touch interfaces)
- Accessibility and internationalisation (screen readers, multi-language support)

**Business Logic & Integration**
- Email services (transactional emails, templates, incoming message handling)
- Payment processing (Stripe integration, subscriptions, financial workflows)
- External API integration (REST clients, webhook handlers, data synchronisation)
- Background task processing (long-running jobs, queues, progress tracking)
- Third-party service connectors (Google services, Microsoft, social platforms)

**Production Operations**
- Testing and quality assurance (unit tests, UI automation, performance testing)
- Monitoring and analytics (performance tracking, user behaviour, error reporting)
- Security and compliance (vulnerability scanning, GDPR tools, audit logging)
- Deployment and DevOps (CI/CD pipelines, environment management, scaling)
- Enterprise features (on-premises deployment, high availability, governance)

### Modern Architecture Specialisation

**Project Scaffolding**
- `create_modern_anvil_app` - Complete M3 + Reactive + Routing + Layouts + Models stack
- `analyse_project_context` - Intelligent pattern detection and scoring
- `validate_modern_architecture` - Performance and best practice compliance

**Data Layer Generation**
- `create_model_classes` - Type-safe data models with validation and relationships
- `generate_model_schemas` - Database schema from model definitions
- `create_model_services` - CRUD operations with proper error handling
- `migrate_to_models` - Convert raw table access to model-based patterns

**Component Generation**
- `create_reactive_page` - Route class + reactive form + M3 layout + model integration
- `create_reactive_store` - Application state management with signals and models
- `add_m3_navigation` - NavigationDrawer/NavigationRail layouts
- `create_reactive_data_table` - Tabulator with reactive model integration
- `create_optimised_form` - Reactive patterns with model binding and validation

### Legacy Support & Migration

**Pattern Recognition**
- `detect_anvil_patterns` - Comprehensive pattern recognition (v1.0+)
- `analyse_migration_impact` - Breaking change risk assessment
- `create_capability_matrix` - Component/pattern compatibility mapping

**Guided Migration**
- `create_migration_plan` - Interactive step-by-step modernisation
- `migrate_form_to_reactive` - Add reactive patterns to existing forms
- `upgrade_to_m3_components` - Replace classic components systematically  
- `migrate_routing_system` - Anvil Extras → Official routing conversion
- `modernise_layout_architecture` - ColumnPanel → Layout migration
- `migrate_data_layer` - Raw tables/anvil-extras → Model classes conversion

### Performance Optimisation

**Analysis Tools**
- `analyse_reactive_dependencies` - Signal dependency visualisation
- `optimise_render_effects` - Performance bottleneck identification
- `create_performance_report` - Comprehensive app performance audit
- `optimise_component_tree` - Component hierarchy analysis

## Code Generation Standards

### Anvil YAML Form Generation

Hephaestus generates Anvil form YAML files programmatically. All generated forms must follow the specification in `anvil_yaml_reference.md`. Key patterns include:

**Form Structure:**
```yaml
container:
  type: ColumnPanel
  event_bindings: 
    refreshing_data_bindings: form_refreshing_data_bindings
components:
  - name: component_name
    type: ComponentType
    properties:
      text: "Submit"
      role: outlined-button
    layout_properties:
      grid_position: 'X,Y'
    data_bindings:
      - property: enabled
        code: self.some_condition
    event_bindings:
      click: click_handler
```

**Component Generation Rules:**
- Use snake_case IDs with component type prefixes (`button_submit`, `textbox_email`)
- Include required properties: `type` for all components, `id` for non-containers
- Validate component types against Anvil API
- Preserve existing component order when updating forms
- Use proper 2-space YAML indentation

**Modern vs Legacy Component Patterns:**
- Prefer Material 3 components (`role: outlined-card`, `role: primary-color`)
- Use reactive data bindings with `writeback: true` for model integration
- Implement proper event handler mapping to existing form methods
- Support custom components with `form:DEPENDENCY_ID:MODULE_PATH.COMPONENT_NAME` format

Refer to `anvil_yaml_reference.md` for complete component specifications, property lists, and advanced patterns.

### Modern Model Classes
```python
@anvil.server.model_class
class User:
    name = field(String)
    email = field(String, unique=True)
    created_at = field(DateTime, default=lambda: datetime.now())
    is_active = field(Boolean, default=True)
    profile = field(Link("UserProfile", optional=True))
    
    def get_display_name(self):
        return self.name or self.email.split('@')[0]
    
    @classmethod 
    def find_active_users(cls):
        return cls.search(is_active=True).order_by("created_at", ascending=False)

@anvil.server.model_class  
class UserProfile:
    user = field(Link("User"))
    bio = field(String, optional=True)
    avatar_url = field(String, optional=True)
    preferences = field(Object, default=lambda: {})
```

### Modern Reactive Component with Models
```python
@reactive_class
class UserDashboard(UserDashboardTemplate):
    def __init__(self, routing_context, **properties):
        # Load user model from routing context
        user_id = routing_context.data.get('user_id')
        self.user = reactive_instance(User.get_by_id(user_id))
        self.notifications = signal([])
        self.layout.app_bar_title = f"Dashboard - {self.user.get_display_name()}" 
        self.init_components(**properties)
    
    @render_effect
    def sync_user_display(self):
        bind(self.user_name, "text", lambda: self.user.name)
        bind(self.user_email, "text", lambda: self.user.email)
        bind(self.status_indicator, "visible", lambda: self.user.is_active)
        bind(self.profile_image, "source", lambda: self.user.profile.avatar_url if self.user.profile else None)
    
    def save_user_changes_click(self, **event_args):
        self.user.save()
        self.notifications.append("User profile updated successfully")
```

### Modern vs Legacy Data Patterns

**❌ Legacy Raw Table Access**
```python
# Fragile, no validation, prone to errors
user_row = app_tables.users.get(email=email)
user_row['name'] = new_name
user_row.update()
```

**❌ Legacy anvil-extras ORM**
```python  
# Better than raw tables, but still outdated
user = User.get(email=email)
user.name = new_name
user.save()
```

**✅ Modern Model Classes**
```python
# Type-safe, validated, with relationships
user = User.get(email=email)
user.name = new_name  # Automatic validation
user.save()  # Automatic serialisation and error handling
```

### Modern Project Structure
```
modern_anvil_app/
├── client_code/
│   ├── layouts/
│   │   ├── MainLayout/      # NavigationDrawerLayout
│   │   └── DetailLayout/    # NavigationRailLayout
│   ├── pages/
│   │   ├── dashboard/
│   │   ├── settings/
│   │   └── profile/
│   ├── stores/
│   │   ├── app_store.py     # Reactive global state
│   │   └── user_store.py
│   └── components/
│       └── shared/
├── server_code/
│   ├── models/
│   │   ├── __init__.py      # Model class definitions
│   │   ├── user.py         # User and UserProfile models
│   │   └── content.py      # Content-related models
│   ├── services/
│   │   ├── user_service.py  # Business logic using models
│   │   └── auth_service.py
│   └── routes/             # API endpoints with model validation
└── theme/
    └── m3_customisations/
```

### Hephaestus Server Structure
```
hephaestus/
├── src/
│   ├── __init__.py
│   └── server.py          # Main MCP server entry point
├── pyproject.toml         # Hatchling-based configuration
├── justfile              # Development commands
└── Documentation/
```

## Architecture Guidelines

### Context-Aware Design
Hephaestus uses intelligent project analysis to determine the optimal code generation strategy for each situation:

```python
class ContextAwareTool:
    def execute(self, context: ProjectContext, **params):
        if context.generation_mode == "modern":
            return self._generate_optimal(**params)
        elif context.generation_mode == "hybrid":
            return self._generate_enhanced(context, **params)  
        else:
            return self._generate_compatible(context, **params)
```

### Performance-First Validation
Every generated pattern is optimised for performance:
- Minimal re-renders with reactive patterns
- Optimal component hierarchies
- Efficient state management
- Modern layout architectures

### Legacy Compatibility
Comprehensive support for all Anvil development patterns:
- **Data Layer**: Raw data tables, anvil-extras ORM, custom database access
- **Routing**: anvil-extras, custom navigation, hash routing
- **State**: Global modules, form properties, manual updates
- **Components**: All classic components, custom components, anvil-extras
- **Layouts**: ColumnPanel, FlowPanel, GridPanel, XYPanel hierarchies
- **Themes**: Classic, Material Design, Shoelace, custom CSS

## Quality Standards

### Code Generation Excellence
- Follow latest Anvil best practices and conventions
- Generate clean, self-documenting code without unnecessary comments
- Include comprehensive error handling in generated server functions
- Use meaningful variable names and optimal structure
- Performance-first patterns by default

### Validation & Safety
- Strict validation of component types against Anvil API (see `anvil_yaml_reference.md`)
- YAML syntax validation with meaningful error messages using component specification
- Python code syntax checking
- Prevention of naming conflicts
- Breaking change risk assessment

### Modern Architecture Compliance
- Always prefer M3 components over classic equivalents
- Use reactive patterns for all state management
- Implement Model classes for type-safe, validated data access
- Implement proper layout-based architecture
- Generate optimal routing with data loading patterns
- Ensure responsive design and accessibility

## Migration Philosophy

Hephaestus embraces both innovation and compatibility:

- **New Projects**: Always use the latest modern stack for optimal performance and maintainability
- **Existing Projects**: Respectful enhancement with clear upgrade paths and risk assessment
- **Developer Education**: Guided migration with clear explanations of benefits and trade-offs
- **Performance Focus**: Every suggestion prioritises speed, efficiency, and user experience

## Toolchain Implications

### Minimal vs Comprehensive Approach

The minimal toolchain approach has several implications:

**Benefits:**
- **Fast Development**: Minimal setup, quick iteration
- **Reliable Builds**: Fewer dependencies, fewer points of failure
- **Modern Python**: Latest language features and best practices
- **Developer Experience**: Fast tooling that stays out of the way

**Trade-offs:**
- **Limited Tooling**: No extensive IDE integration, coverage reporting, or documentation generation
- **Manual Processes**: Some tasks require manual intervention vs automated tooling
- **Focused Scope**: Core functionality prioritized over enterprise features

**When to Extend:**
- Add tooling only when specific pain points emerge
- Prefer external tools over complex internal tooling
- Maintain minimal approach for core development workflow

### Development Workflow

1. **Setup**: `uv sync` to install dependencies
2. **Development**: `just run` to start MCP server
3. **Quality**: `just lint && just format && just typecheck` for code quality
4. **Testing**: `just test` for basic test coverage
5. **Building**: `just build` to create distributable package

This minimal approach ensures fast, reliable development while maintaining the ability to extend tooling as needed.