# Local Service Migration Guide

## Overview

The VS Code extension is being migrated to use the Vreko Local Service (`vrekod`) for heavy operations, significantly reducing bundle size and improving activation time.

## Architecture Change

### Before
```
Extension Bundle (1.8MB)
  ├── Snapshot Logic
  ├── Session Management
  ├── Protection Engine
  ├── Detection Algorithms
  └── UI Components
```

### After
```
Extension Bundle (<500KB)
  └── UI Components + Thin Client

Local Service Daemon (vrekod)
  ├── Snapshot Logic
  ├── Session Management
  ├── Protection Engine
  └── Detection Algorithms
```

## Performance Targets

| Metric | Before | Target | Status |
|--------|--------|--------|--------|
| Bundle Size | 1.8MB | <500KB | 🔄 In Progress |
| Activation Time | ~500ms | <300ms | 🔄 In Progress |
| Memory Usage | ~200MB | <100MB | 🔄 In Progress |

## Migration Strategy

### Phase 1: Client Implementation ✅

- [x] Create `LocalServiceClient` - JSON-RPC 2.0 client
- [x] Create `LocalServiceBridge` - Integration layer with fallback
- [x] Add status bar indicator for connection state

### Phase 2: Service Migration 🔄

- [ ] Update `SnapshotManager` to delegate to LocalServiceBridge
- [ ] Update `SessionCoordinator` to use local service
- [ ] Update `ProtectedFileRegistry` to delegate protection checks
- [ ] Update `DetectionService` to use local service

### Phase 3: Bundle Optimization 📋

- [ ] Remove heavy snapshot logic from extension
- [ ] Remove session clustering (DBSCAN) from bundle
- [ ] Remove detection algorithms from bundle
- [ ] Verify bundle size <500KB

### Phase 4: Testing & Validation 📋

- [ ] Test snapshot creation via local service
- [ ] Test session management
- [ ] Test protection evaluation
- [ ] Test AI detection
- [ ] Verify graceful fallback when daemon offline

## Usage

### Starting the Local Service

```bash
# Start the daemon
vreko service start

# Check status
vreko service status

# Stop the daemon
vreko service stop
```

### Extension Integration

The extension will:
1. **Auto-connect** to local service on activation
2. **Show status** in status bar (connected/offline/reconnecting)
3. **Graceful fallback** to embedded mode if service unavailable
4. **Notify user** if service needed but not running

### Status Bar States

| Icon | Tooltip | Meaning |
|------|---------|---------|
| ✅ Vreko | Connected | Daemon connected, optimal performance |
| ⚠️ Vreko | Offline (embedded mode) | Using fallback, higher memory usage |
| 🔄 Vreko | Reconnecting... | Attempting to reconnect to daemon |

## API Examples

### Creating a Snapshot

```typescript
import { getLocalServiceBridge } from './services/LocalServiceBridge';

const bridge = getLocalServiceBridge(workspaceRoot);
await bridge.initialize();

// Create snapshot (tries daemon, shows notification if unavailable)
const snapshot = await bridge.createSnapshot(['file.ts'], {
  reason: 'Manual snapshot',
  trigger: 'manual'
});
```

### Checking Protection Level

```typescript
const protection = await bridge.evaluateProtection('/path/to/file.ts', content);
console.log(`Protection level: ${protection.level}`); // 'watch' | 'warn' | 'block'
```

### Session Management

```typescript
// Start session
const session = await bridge.startSession('Working on feature X');

// Get current session
const current = await bridge.getCurrentSession();

// End session (auto-creates snapshot)
await bridge.endSession(true);
```

## Troubleshooting

### Extension shows "Offline (embedded mode)"

**Solution**: Start the local service daemon
```bash
vreko service start
```

### Daemon won't start

**Checks**:
1. Verify CLI is installed: `vreko --version`
2. Check if already running: `vreko service status`
3. Check logs: `~/.vreko/service.log`

### Bundle size not reduced

**Verification**:
1. Ensure services are delegating to LocalServiceBridge
2. Check imports for heavy dependencies still bundled
3. Run: `pnpm --filter vscode build` and check dist size

## Development

### Testing Local Service Integration

```bash
# Terminal 1: Start daemon in dev mode
cd apps/local-service
pnpm dev

# Terminal 2: Run extension in debug mode
cd apps/vscode
pnpm dev
```

### Monitoring Connection State

```typescript
bridge.onStateChange((state) => {
  console.log('Local service state:', state);
  // DaemonState.Connected | Disconnected | Reconnecting | Error
});
```

## Fallback Behavior

When local service is unavailable:

| Operation | Fallback Behavior |
|-----------|------------------|
| Snapshot Creation | ❌ Error - requires daemon |
| Session Management | ❌ Error - requires daemon |
| Protection Evaluation | ✅ Default to 'watch' level |
| AI Detection | ✅ Return false (no detection) |

Users will see notifications guiding them to start the daemon.

## Benefits

### For Users
- ✨ Faster extension activation (<300ms)
- 📉 Lower memory usage (<100MB)
- 🔋 Better VS Code performance
- 🔄 Shared state across IDE instances

### For Developers
- 🎯 Cleaner separation of concerns
- 🧪 Easier to test service logic
- 🔧 Service can be upgraded independently
- 📦 Smaller extension bundle

## Next Steps

1. ✅ Implement client and bridge (DONE)
2. 🔄 Update extension services to delegate
3. 📋 Remove heavy logic from bundle
4. 🧪 Test and validate performance gains
5. 📝 Document for users

## Related Files

- `apps/vscode/src/services/LocalServiceClient.ts` - JSON-RPC client
- `apps/vscode/src/services/LocalServiceBridge.ts` - Integration layer
- `apps/local-service/src/main.ts` - Daemon entry point
- `packages/contracts/src/local-service/` - Protocol definitions
