# Story 3.3: Module Loader and Initialization

## Metadata
- **Story ID**: 3.3
- **Title**: Module Loader and Initialization
- **Epic**: 3 - Module Framework
- **Status**: Pending
- **Priority**: High
- **Estimated Time**: 6-8 hours
- **Dependencies**: 3.1, 1.2

## Goal
Implement module loading (static and dynamic) with dependency resolution and automatic initialization.

## Description
This story implements the complete module loading system that discovers modules, resolves dependencies, initializes them in the correct order, and runs their migrations. It supports both static registration (preferred) and dynamic plugin loading.

## Deliverables

### 1. Module Loader (`internal/pluginloader/loader.go`)
- Support static registration (preferred method)
- Optional: Go plugin loading (`.so` files)
- Module discovery from `modules/*/module.yaml`
- Loader interface for extensibility

### 2. Static Loader (`internal/pluginloader/static_loader.go`)
- Import modules via side-effect imports
- Collect all registered modules
- Module discovery and registration

### 3. Optional Plugin Loader (`internal/pluginloader/plugin_loader.go`)
- Scan `./plugins/*.so` files
- Load via `plugin.Open()`
- Extract and validate module symbols
- Version compatibility checking

### 4. Module Initializer (`internal/module/initializer.go`)
- Collect all registered modules
- Resolve dependency order (topological sort)
- Initialize each module's `Init()` fx.Option
- Merge all options into main fx container
- Run migrations in dependency order
- Handle errors gracefully

### 5. FX Lifecycle Integration
- Call `OnStart()` during app startup
- Call `OnStop()` during graceful shutdown
- Proper error handling

## Implementation Steps

1. **Create Module Loader**
   - Create `internal/pluginloader/loader.go`
   - Define loader interface

2. **Implement Static Loader**
   - Create `internal/pluginloader/static_loader.go`
   - Implement static module loading

3. **Implement Module Initializer**
   - Create `internal/module/initializer.go`
   - Implement dependency resolution
   - Implement initialization

4. **Integrate with FX**
   - Add lifecycle hooks
   - Test initialization

## Acceptance Criteria
- [ ] Modules load in correct dependency order
- [ ] Module migrations run automatically
- [ ] Module initialization integrates with FX
- [ ] Lifecycle hooks work correctly
- [ ] Dependency resolution handles cycles
- [ ] Errors are handled gracefully

## Files to Create/Modify
- `internal/pluginloader/loader.go` - Loader interface
- `internal/pluginloader/static_loader.go` - Static loader
- `internal/pluginloader/plugin_loader.go` - Plugin loader (optional)
- `internal/module/initializer.go` - Module initializer
- `internal/di/container.go` - Integrate module initialization

