# Milestone 20: Kernel Integration

**Status**: Complete
**Goal**: Multi-app sandbox orchestrator for kernel integration.

---

## Overview

This milestone creates the LuaSandboxManager class that orchestrates multiple isolated Lua app sandboxes, providing the final integration point for the kernel.

### Key Deliverables

1. **LuaSandboxManager class** - Manages multiple concurrent app sandboxes
2. **AppSandbox struct** - Per-app container with all components
3. **Lifecycle management** - Start/stop apps with full resource cleanup
4. **Shared components** - Cross-app services (AuditLog, RateLimiter, MessageBus, TimerManager)

---

## File Structure

```
src/main/cpp/sandbox/
├── sandbox_manager.h      # NEW - Multi-app orchestrator header
├── sandbox_manager.cpp    # NEW - Orchestrator implementation
└── [all previous M1-19 files]
```

---

## Implementation Details

### 1. AppSandbox Struct

Per-app container holding all isolated components:

```cpp
struct AppSandbox {
    std::unique_ptr<LuaSandbox> lua;
    std::unique_ptr<PermissionGate> permissions;
    std::unique_ptr<VirtualFS> filesystem;
    std::unique_ptr<DatabaseManager> database;
    std::unique_ptr<NetworkManager> network;
    std::unique_ptr<WebSocketManager> websocket;
    std::unique_ptr<CameraInterface> camera;
    std::unique_ptr<MicrophoneInterface> microphone;
    std::unique_ptr<AudioOutputInterface> audio;
    std::unique_ptr<LocationInterface> location;
    std::unique_ptr<SensorInterface> sensors;
    std::unique_ptr<BluetoothInterface> bluetooth;
    std::unique_ptr<ContactsInterface> contacts;
    SandboxContext context;
    bool is_running = false;
};
```

### 2. LuaSandboxManager Class

```cpp
class LuaSandboxManager {
public:
    explicit LuaSandboxManager(const std::string& data_root = ".");
    ~LuaSandboxManager();

    // App lifecycle
    bool StartApp(const std::string& app_id, const std::string& app_path,
                  const std::vector<std::string>& permissions,
                  bool is_system_app = false);
    bool StopApp(const std::string& app_id);
    bool IsAppRunning(const std::string& app_id) const;

    // Get app sandbox for direct access
    AppSandbox* GetApp(const std::string& app_id);
    const AppSandbox* GetApp(const std::string& app_id) const;

    // Execute Lua code in app context
    bool ExecuteCode(const std::string& app_id, const std::string& code,
                     const std::string& source_name = "script");
    bool LoadFile(const std::string& app_id, const std::string& path);

    // User gesture tracking
    void RecordUserGesture(const std::string& app_id);

    // Timer management
    void UpdateTimers();

    // Get all running app IDs
    std::vector<std::string> GetRunningApps() const;
    size_t GetRunningAppCount() const;

    // Shared components
    AuditLog& GetAuditLog();
    RateLimiter& GetRateLimiter();
    MessageBus& GetMessageBus();
    TimerManager& GetTimerManager();

    // Configuration
    void SetDefaultLimits(const SandboxLimits& limits);
    const SandboxLimits& GetDefaultLimits() const;
};
```

### 3. App Lifecycle

**StartApp Flow:**
1. Create SandboxContext from parameters
2. Create AppSandbox with all components
3. Register JSON and Crypto APIs
4. Store manager/app references in Lua registry
5. Mark as running and store in map

**StopApp Flow:**
1. Clear app timers
2. Close WebSocket connections
3. Shutdown camera/microphone/audio
4. Shutdown location/sensors/bluetooth
5. Clear temp files in VirtualFS
6. Close database connections
7. Unregister from message bus
8. Remove from map

### 4. Resource Isolation

Each app gets:
- Isolated Lua state
- Isolated permissions
- Isolated filesystem (under `data_root/apps/{app_id}/`)
- Isolated database directory
- Isolated network manager
- Isolated hardware interfaces

Shared across apps:
- AuditLog (thread-safe)
- RateLimiter (app-keyed)
- MessageBus (for inter-app communication)
- TimerManager (timers keyed by app_id)

---

## Test Cases

| Test | Description |
|------|-------------|
| `Test_ManagerStartStopApp` | Start and stop app lifecycle |
| `Test_ManagerMultipleApps` | Run multiple apps concurrently |
| `Test_ManagerAppIsolation` | Verify separate Lua states |
| `Test_ManagerExecuteCode` | Execute code in app context |
| `Test_ManagerResourceCleanup` | Verify cleanup on stop |
| `Test_ManagerUserGesture` | User gesture forwarding |
| `Test_ManagerDoubleStartStop` | Idempotent start/stop |
| `Test_ManagerSharedComponents` | Access shared components |

---

## Acceptance Criteria

All tests pass (149 total):
- [x] All M1-19 tests (141 tests)
- [x] `Test_ManagerStartStopApp` - App lifecycle works
- [x] `Test_ManagerMultipleApps` - Multiple concurrent apps
- [x] `Test_ManagerAppIsolation` - Lua states are isolated
- [x] `Test_ManagerExecuteCode` - Code execution works
- [x] `Test_ManagerResourceCleanup` - Resources cleaned on stop
- [x] `Test_ManagerUserGesture` - Gesture forwarding works
- [x] `Test_ManagerDoubleStartStop` - Idempotent operations
- [x] `Test_ManagerSharedComponents` - Shared components accessible

---

## Dependencies

- All previous milestones (1-19)

---

## Notes

### Thread Safety

LuaSandboxManager is thread-safe via mutex protection on all public methods that access the app map.

### Memory Management

All components use unique_ptr for automatic cleanup. When StopApp is called:
1. CleanupApp() releases resources gracefully
2. unique_ptr destructors clean up remaining state
3. App is removed from map

### Integration with Kernel

The kernel can integrate with LuaSandboxManager by:
1. Creating a single manager instance at startup
2. Calling StartApp() for each installed app
3. Calling UpdateTimers() from the main loop
4. Calling RecordUserGesture() on UI interactions
5. Using GetApp() to access specific app components
6. Calling StopApp() when apps are closed

---

## Milestone Complete

All 149 tests pass. The sandbox system is fully integrated and ready for kernel use.
