Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

docs: add API reference, architecture overview, and troubleshooting guide

Adam Eivy39d4c8eb9c83
diff --git a/PLAN.md b/PLAN.md
index c21b30b337..7b03e1275a 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -48,10 +48,20 @@ pm2 logs
- [x] M19: CoS Agent Runner (isolated PM2 process for agent spawning, prevents orphaned processes)
- [x] M20: AI Provider Error Handling (error extraction, categorization, CoS investigation tasks)
- [x] M21: Usage Metrics Integration (usage tracking for all AI runs, mobile responsive design)
+- [x] M22: Orphan Auto-Retry (automatic retry for orphaned agents, investigation task on max retries)
+- [x] M23: Self-Improvement System (automated UI/security/code quality analysis with Playwright and Opus)
+- [x] M24: Goal-Driven Proactive Mode (COS-GOALS.md mission file, always-working behavior, expanded task types)
+- [x] M25: Task Learning System (completion tracking, success rate analysis, model effectiveness, recommendations)
### Documentation
+- [Architecture Overview](./docs/ARCHITECTURE.md) - System design, data flow
+- [API Reference](./docs/API.md) - REST endpoints, WebSocket events
- [Contributing Guide](./docs/CONTRIBUTING.md) - Code guidelines, git workflow
+- [PM2 Configuration](./docs/PM2.md) - PM2 patterns and best practices
+- [Port Allocation](./docs/PORTS.md) - Port conventions and allocation
- [Versioning & Releases](./docs/VERSIONING.md) - Version format, release process
+- [GitHub Actions](./docs/GITHUB_ACTIONS.md) - CI/CD workflow patterns
+- [Troubleshooting](./docs/TROUBLESHOOTING.md) - Common issues and solutions
### Error Handling
The server implements comprehensive error handling:
@@ -587,13 +597,22 @@ Semantic memory system for the Chief of Staff that stores facts, learnings, obse
| cos:memory:extracted | Memories extracted from agent |
| cos:memory:approval-needed | Medium-confidence memories pending approval |
+### Setup Requirements
+
+**LM Studio** must be running with an embedding model loaded for the memory system to work:
+
+1. Download and install [LM Studio](https://lmstudio.ai/)
+2. Load an embedding model: `text-embedding-nomic-embed-text-v2-moe` (recommended) or `text-embedding-nomic-embed-text-v1.5`
+3. Start the local server on port 1234 (default)
+4. The memory system will automatically connect
+
### LM Studio Configuration
```javascript
memory: {
enabled: true,
embeddingProvider: 'lmstudio',
embeddingEndpoint: 'http://localhost:1234/v1/embeddings',
- embeddingModel: 'nomic-embed-text-v1.5',
+ embeddingModel: 'text-embedding-nomic-embed-text-v2-moe',
embeddingDimension: 768,
maxContextTokens: 2000,
minRelevanceThreshold: 0.7,
@@ -926,3 +945,289 @@ executeCliRun() / executeApiRun() / completeAgentRun()
└─► recordMessages(providerId, model, 1, estimatedTokens)
└─► updates totalMessages, byProvider, byModel tokens
```
+
+---
+
+## M22: Orphan Auto-Retry
+
+Automatic retry for orphaned agents with investigation task creation after repeated failures.
+
+### Problem
+When agents become orphaned (server restart, runner crash, etc.), the task remained stuck and the system didn't automatically retry or investigate the issue.
+
+### Solution
+1. **Auto-Retry**: Reset orphaned tasks to pending for automatic retry (up to 3 attempts)
+2. **Retry Tracking**: Track retry count in task metadata (orphanRetryCount)
+3. **Investigation Task**: After max retries, create auto-approved investigation task
+4. **Evaluation Trigger**: Trigger task evaluation immediately after orphan cleanup
+
+### Retry Flow
+```
+Agent Orphaned
+ └─► cleanupOrphanedAgents() marks agent as completed
+ └─► handleOrphanedTask() checks retry count
+ ├─► retryCount < 3: Reset task to pending, trigger evaluation
+ └─► retryCount >= 3: Mark task blocked, create investigation task
+```
+
+### Task Metadata
+```javascript
+metadata: {
+ orphanRetryCount: number, // Incremented each orphan
+ lastOrphanedAt: string, // ISO timestamp
+ lastOrphanedAgentId: string, // Agent that was orphaned
+ blockedReason: string // Only if max retries exceeded
+}
+```
+
+### Investigation Task (Auto-Approved)
+When max retries (3) are exceeded, an investigation task is created:
+- Priority: HIGH
+- approvalRequired: false (auto-approved, will run immediately)
+- Contains: original task description, retry count, last agent ID
+- Instructions: Check logs, verify spawning, look for resource constraints
+
+### Implementation Files
+| File | Changes |
+|------|---------|
+| `server/services/subAgentSpawner.js` | Added `handleOrphanedTask()`, updated `cleanupOrphanedAgents()` to reset tasks and trigger evaluation |
+| `server/services/cos.js` | Added `getTaskById()` export, updated `updateTask()` to merge metadata properly |
+
+### Configuration
+| Setting | Value | Description |
+|---------|-------|-------------|
+| MAX_ORPHAN_RETRIES | 3 | Retries before creating investigation task |
+
+---
+
+## M23: Self-Improvement System
+
+Automated self-analysis and improvement system that uses Playwright and Opus to continuously improve PortOS.
+
+### Problem
+CoS idle reviews only checked managed apps for simple fixes. The system wasn't proactively improving itself - checking its own UI for bugs, mobile responsiveness issues, security vulnerabilities, or code quality.
+
+### Solution
+A comprehensive self-improvement system that rotates through 7 analysis types:
+
+1. **ui-bugs**: Navigate to all routes with Playwright, check console errors, fix bugs
+2. **mobile-responsive**: Test at mobile/tablet/desktop viewports, fix layout issues
+3. **security**: Audit server/client code for XSS, injection, path traversal
+4. **code-quality**: Find DRY violations, large functions, dead code
+5. **accessibility**: Check ARIA labels, color contrast, keyboard navigation
+6. **console-errors**: Capture and fix all JavaScript errors
+7. **performance**: Analyze re-renders, N+1 queries, bundle size
+
+### Key Features
+- **Automatic rotation**: Cycles through analysis types when CoS is idle
+- **Opus model**: All self-improvement tasks use claude-opus-4-5-20251101 for thorough analysis
+- **Playwright integration**: Uses MCP browser tools to analyze live UI
+- **Auto-approved**: Tasks run without requiring manual approval
+- **Alternates with app reviews**: Balances self-improvement with managed app maintenance
+
+### Task Flow
+```
+CoS Idle (no user/system tasks)
+ └─► Check lastSelfImprovement vs lastIdleReview
+ ├─► Self-improvement older: Generate self-improvement task
+ │ └─► Rotate to next analysis type
+ │ └─► Spawn Opus agent with Playwright instructions
+ └─► App review older: Generate idle app review (existing behavior)
+```
+
+### Implementation Files
+| File | Purpose |
+|------|---------|
+| `server/services/cos.js` | Added `generateSelfImprovementTask()`, updated `generateIdleReviewTask()` |
+| `server/services/selfImprovement.js` | Constants, prompt templates, utility functions |
+
+### State Tracking
+```javascript
+stats: {
+ lastSelfImprovement: ISO timestamp,
+ lastSelfImprovementType: 'ui-bugs' | 'mobile-responsive' | ... ,
+ lastIdleReview: ISO timestamp
+}
+```
+
+### Example Task
+```
+[Self-Improvement] UI Bug Analysis
+
+Use Playwright MCP to analyze PortOS UI at http://localhost:5555/
+- Navigate to each route
+- Capture browser snapshots and console messages
+- Fix any bugs found
+- Commit changes
+
+Use model: claude-opus-4-5-20251101
+```
+
+---
+
+## M24: Goal-Driven Proactive Mode
+
+Makes CoS proactive and goal-driven, spending more time working and less time idle.
+
+### Problem
+CoS was too passive - it would sit idle when apps were on cooldown instead of finding other productive work. The system lacked clear goals and mission guidance.
+
+### Solution
+
+#### 1. COS-GOALS.md Mission File
+Created `data/COS-GOALS.md` with:
+- Mission statement and core principles
+- 5 active goals (codebase quality, self-improvement, documentation, user engagement, system health)
+- Task generation priorities
+- Behavior guidelines
+- Metrics to track
+
+#### 2. Always-Working Behavior
+Updated `generateIdleReviewTask()` to ALWAYS return work:
+- First tries self-improvement if it's been longer since last run
+- Then tries app reviews if any apps are off cooldown
+- **Falls back to self-improvement** if apps are on cooldown (instead of returning null)
+
+#### 3. Expanded Task Types
+Added 4 new self-improvement task types:
+- `cos-enhancement`: Improve CoS capabilities and prompts
+- `test-coverage`: Add missing tests
+- `documentation`: Update PLAN.md, docs/, code comments
+- `feature-ideas`: Brainstorm and implement small features
+
+Now 11 task types total, rotating through all goals.
+
+#### 4. Configuration Changes
+| Setting | Old | New |
+|---------|-----|-----|
+| `evaluationIntervalMs` | 300000 (5m) | 60000 (1m) |
+| `appReviewCooldownMs` | 3600000 (1h) | 1800000 (30m) |
+| `idleReviewPriority` | LOW | MEDIUM |
+| `proactiveMode` | (new) | true |
+| `goalsFile` | (new) | data/COS-GOALS.md |
+
+### Task Rotation
+```
+1. ui-bugs → Check UI for errors
+2. mobile-responsive → Test viewport sizes
+3. security → Audit for vulnerabilities
+4. code-quality → Find DRY violations, dead code
+5. console-errors → Fix JS errors
+6. performance → Optimize re-renders, queries
+7. cos-enhancement → Improve CoS itself
+8. test-coverage → Add tests
+9. documentation → Update docs
+10. feature-ideas → Implement new features
+11. accessibility → Check a11y issues
+```
+
+### Key Behavior Change
+```
+Before: Apps on cooldown → Return null → Idle
+After: Apps on cooldown → Run self-improvement → Always working
+```
+
+### Implementation Files
+| File | Changes |
+|------|---------|
+| `data/COS-GOALS.md` | New mission and goals file |
+| `server/services/cos.js` | Updated config defaults, expanded task types, always-working logic |
+
+---
+
+## Security Audit (2026-01-08)
+
+Comprehensive security audit performed by CoS Self-Improvement agent.
+
+### Vulnerabilities Found and Fixed
+
+#### 1. Command Injection in Git Service (CRITICAL - FIXED)
+**File**: `server/services/git.js`
+
+**Problem**: The service used `exec()` with string concatenation for shell commands, allowing command injection attacks:
+```javascript
+// VULNERABLE - user input directly in shell command
+await execAsync(`git add ${paths}`, { cwd: dir });
+await execAsync(`git commit -m "${message}"`, { cwd: dir });
+```
+
+An attacker could inject shell commands via file paths like `; rm -rf /` or commit messages containing shell metacharacters.
+
+**Fix Applied**:
+- Replaced `exec()` with `spawn()` and `shell: false` to prevent shell interpretation
+- Created `execGit()` helper that uses argument arrays instead of string concatenation
+- Added `validateFilePaths()` to reject paths with:
+ - Null bytes (`\0`)
+ - Shell metacharacters (`;`, `|`, `&`, `` ` ``, `$`)
+ - Path traversal (`..`)
+ - Absolute paths (`/`)
+
+#### 2. Path Traversal in Screenshots Route (HIGH - FIXED)
+**File**: `server/routes/screenshots.js`
+
+**Problem**: User-provided filenames were used directly without sanitization:
+```javascript
+// VULNERABLE - path traversal possible
+const filepath = join(SCREENSHOTS_DIR, filename);
+```
+
+An attacker could access arbitrary files via paths like `../../../etc/passwd`.
+
+**Fix Applied**:
+- Added `sanitizeFilename()` to strip path components and special characters
+- Use `resolve()` to normalize paths, then verify result stays within `SCREENSHOTS_DIR`
+- Defense in depth: check both upload and retrieval endpoints
+
+### No Issues Found (Secure Patterns in Use)
+
+#### Command Execution
+- **`server/services/commands.js`**: Uses allowlist (`ALLOWED_COMMANDS`) to restrict which commands can be executed. Only the base command is checked, but it uses `spawn('sh', ['-c', command])` which allows pipes and redirects for allowed commands only.
+
+#### PM2 Operations
+- **`server/services/pm2.js`**: Uses `spawn('pm2', args, { shell: false })` correctly.
+
+#### Input Validation
+- **Zod schemas**: Routes use Zod validation for structured input (`lib/validation.js`, `lib/memoryValidation.js`)
+- **Type coercion**: Query parameters properly parsed with `parseInt()` with fallback defaults
+
+#### React XSS Protection
+- No `dangerouslySetInnerHTML` usage found
+- React's JSX escapes content by default
+- API client properly uses `JSON.stringify()` for request bodies
+
+#### No Sensitive Data in Client
+- API keys stored server-side only in `data/providers.json`
+- No localStorage usage for sensitive data
+- Client uses relative API paths, no hardcoded secrets
+
+#### CSRF Protection
+- Same-origin deployment (client and server on same domain)
+- JSON content type required for all POST/PUT requests
+
+### Command Allowlist Review
+**File**: `server/services/commands.js`
+
+The allowlist is comprehensive for the intended use case:
+```javascript
+const ALLOWED_COMMANDS = new Set([
+ 'npm', 'npx', 'pnpm', 'yarn', 'bun', // Package managers
+ 'node', 'deno', // Runtimes
+ 'git', 'gh', // Git operations
+ 'pm2', // Process manager
+ 'ls', 'cat', 'head', 'tail', 'grep', 'find', 'wc', // File inspection
+ 'pwd', 'which', 'echo', 'env', // System info
+ 'curl', 'wget', // Network
+ 'docker', 'docker-compose', // Containers
+ 'make', 'cargo', 'go', 'python', 'python3', 'pip', 'pip3', // Build tools
+ 'brew' // macOS package manager
+]);
+```
+
+**Note**: While this prevents arbitrary command execution, the system allows shell pipes/redirects within allowed commands because it uses `spawn('sh', ['-c', command])`. This is intentional for DevTools functionality but could theoretically be abused (e.g., `npm run "$(malicious)"`).
+
+### Recommendations for Future
+
+1. **Rate Limiting**: Consider adding rate limiting to prevent DoS
+2. **Audit Logging**: Log all command executions for forensic analysis
+3. **Content Security Policy**: Add CSP headers to client responses
+4. **Command Argument Validation**: Consider validating arguments to allowed commands, not just base commands
diff --git a/README.md b/README.md
index b50dddd287..b16f5c697a 100644
--- a/README.md
+++ b/README.md
@@ -124,10 +124,15 @@ Configure AI providers for the runner:
## Documentation
+- [Architecture Overview](./docs/ARCHITECTURE.md) — System design and data flow
+- [API Reference](./docs/API.md) — REST endpoints and WebSocket events
- [Contributing Guide](./docs/CONTRIBUTING.md) — Development setup and code guidelines
+- [PM2 Configuration](./docs/PM2.md) — PM2 patterns and best practices
- [Port Allocation](./docs/PORTS.md) — Port conventions and allocation guide
- [Versioning & Releases](./docs/VERSIONING.md) — Version format and release process
-- [Implementation Plan](./PLAN.md) — Detailed feature roadmap and API reference
+- [GitHub Actions](./docs/GITHUB_ACTIONS.md) — CI/CD workflow patterns
+- [Troubleshooting](./docs/TROUBLESHOOTING.md) — Common issues and solutions
+- [Implementation Plan](./PLAN.md) — Detailed feature roadmap
## License
diff --git a/docs/API.md b/docs/API.md
new file mode 100644
index 0000000000..c852cbaef3
--- /dev/null
+++ b/docs/API.md
@@ -0,0 +1,314 @@
+# API Reference
+
+PortOS exposes a REST API on port 5554 and WebSocket events via Socket.IO.
+
+## Base URL
+
+```
+http://localhost:5554/api
+```
+
+## Authentication
+
+No authentication is required. PortOS relies on network-level security (Tailscale) for access control.
+
+## REST Endpoints
+
+### Apps
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/apps` | List all registered apps |
+| POST | `/apps` | Register a new app |
+| GET | `/apps/:id` | Get app details |
+| PUT | `/apps/:id` | Update app |
+| DELETE | `/apps/:id` | Unregister app |
+| POST | `/apps/:id/start` | Start app via PM2 |
+| POST | `/apps/:id/stop` | Stop app via PM2 |
+| POST | `/apps/:id/restart` | Restart app via PM2 |
+| GET | `/apps/:id/status` | Get PM2 status |
+| GET | `/apps/:id/logs` | Get recent logs |
+| POST | `/apps/:id/refresh-config` | Re-parse ecosystem config |
+
+### Processes & Logs
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/logs/processes` | List all PM2 processes |
+| GET | `/logs/:name` | Get logs for process |
+| GET | `/ports/scan` | Scan for active ports |
+
+### AI Providers
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/providers` | List all AI providers |
+| POST | `/providers` | Add new provider |
+| PUT | `/providers/:id` | Update provider |
+| DELETE | `/providers/:id` | Delete provider |
+| POST | `/providers/:id/test` | Test provider connectivity |
+| PUT | `/providers/active` | Set active provider |
+
+### AI Runs (DevTools)
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/runs` | List run history |
+| POST | `/runs` | Execute new AI run |
+| GET | `/runs/:id` | Get run details |
+| GET | `/runs/:id/output` | Get run output |
+| POST | `/runs/:id/stop` | Stop active run |
+| DELETE | `/runs/:id` | Delete run |
+
+### AI Agents
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/agents` | List running AI agent processes |
+| GET | `/agents/:pid` | Get agent process details |
+| DELETE | `/agents/:pid` | Kill agent process |
+
+### Command Execution
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| POST | `/commands/execute` | Execute shell command |
+| POST | `/commands/:id/stop` | Stop running command |
+| GET | `/commands/allowed` | List allowed commands |
+| GET | `/commands/processes` | List PM2 processes |
+
+### History
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/history` | List action history |
+| GET | `/history/stats` | Get history statistics |
+| DELETE | `/history` | Clear history |
+
+### Detection & Import
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| POST | `/detect/ports` | Detect process on port |
+| POST | `/detect/repo` | Validate repo path |
+| POST | `/detect/ai` | AI-powered app detection |
+
+### Templates
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/templates` | List available templates |
+| POST | `/templates` | Add custom template |
+| POST | `/templates/create` | Create app from template |
+| DELETE | `/templates/:id` | Delete custom template |
+
+### Prompts
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/prompts` | List all prompt stages |
+| GET | `/prompts/:stage` | Get stage template |
+| PUT | `/prompts/:stage` | Update stage/template |
+| POST | `/prompts/:stage/preview` | Preview compiled prompt |
+| GET | `/prompts/variables` | List all variables |
+| PUT | `/prompts/variables/:key` | Update variable |
+| POST | `/prompts/variables` | Create variable |
+| DELETE | `/prompts/variables/:key` | Delete variable |
+
+### Chief of Staff
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/cos` | Get CoS status |
+| POST | `/cos/start` | Start daemon |
+| POST | `/cos/stop` | Stop daemon |
+| GET | `/cos/config` | Get configuration |
+| PUT | `/cos/config` | Update configuration |
+| GET | `/cos/tasks` | Get all tasks |
+| POST | `/cos/evaluate` | Force task evaluation |
+| GET | `/cos/health` | Get health status |
+| POST | `/cos/health/check` | Run health check |
+| GET | `/cos/agents` | List active agents |
+| POST | `/cos/agents/:id/terminate` | Terminate agent |
+| GET | `/cos/reports` | List reports |
+
+### Memory System
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/memory` | List memories with filters |
+| GET | `/memory/:id` | Get single memory |
+| POST | `/memory` | Create memory |
+| PUT | `/memory/:id` | Update memory |
+| DELETE | `/memory/:id` | Delete (soft) memory |
+| POST | `/memory/search` | Semantic search |
+| GET | `/memory/categories` | List categories |
+| GET | `/memory/tags` | List tags |
+| GET | `/memory/timeline` | Timeline view data |
+| GET | `/memory/graph` | Graph visualization data |
+| GET | `/memory/stats` | Memory statistics |
+| POST | `/memory/link` | Link two memories |
+| POST | `/memory/consolidate` | Merge similar memories |
+| POST | `/memory/decay` | Apply importance decay |
+| DELETE | `/memory/expired` | Clear expired memories |
+| GET | `/memory/embeddings/status` | LM Studio connection status |
+
+### PM2 Standardization
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| POST | `/standardize/analyze` | Analyze app for standardization |
+| POST | `/standardize/apply` | Apply standardization changes |
+| GET | `/standardize/template` | Get PM2 template reference |
+| POST | `/standardize/backup` | Create git backup |
+
+### Usage Metrics
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/usage` | Get usage statistics |
+| GET | `/usage/daily` | Get daily activity |
+| GET | `/usage/hourly` | Get hourly activity |
+
+## WebSocket Events
+
+Connect to Socket.IO at `http://localhost:5554`.
+
+### Log Streaming
+
+```javascript
+// Subscribe to process logs
+socket.emit('logs:subscribe', { processName: 'portos-server', lines: 100 });
+
+// Receive log lines
+socket.on('logs:line', ({ processName, line }) => {
+ console.log(`[${processName}] ${line}`);
+});
+
+// Unsubscribe
+socket.emit('logs:unsubscribe', { processName: 'portos-server' });
+```
+
+### Error Notifications
+
+```javascript
+// Subscribe to errors
+socket.emit('errors:subscribe');
+
+// Receive error events
+socket.on('error:occurred', (error) => {
+ console.error('Server error:', error.message, error.code);
+});
+
+// Unsubscribe
+socket.emit('errors:unsubscribe');
+```
+
+### Chief of Staff Events
+
+```javascript
+// CoS status updates
+socket.on('cos:status', (status) => {
+ console.log('CoS running:', status.running);
+});
+
+// Agent activity
+socket.on('cos:agent:started', (agent) => {
+ console.log('Agent started:', agent.id, agent.task);
+});
+
+socket.on('cos:agent:completed', (agent) => {
+ console.log('Agent completed:', agent.id, agent.success);
+});
+
+// Task updates
+socket.on('cos:task:updated', (task) => {
+ console.log('Task updated:', task.id, task.status);
+});
+
+// Logs from CoS
+socket.on('cos:log', (entry) => {
+ console.log(`[CoS] ${entry.level}: ${entry.message}`);
+});
+```
+
+### Memory Events
+
+```javascript
+socket.on('cos:memory:created', (memory) => {
+ console.log('Memory created:', memory.id);
+});
+
+socket.on('cos:memory:updated', (memory) => {
+ console.log('Memory updated:', memory.id);
+});
+```
+
+### App Detection (Streaming)
+
+```javascript
+// Start streaming detection
+socket.emit('detect:stream', { path: '/path/to/repo' });
+
+// Receive discovery steps
+socket.on('detect:step', (step) => {
+ console.log('Discovered:', step.field, step.value);
+});
+
+// Detection complete
+socket.on('detect:complete', (appData) => {
+ console.log('Detection complete:', appData);
+});
+```
+
+## Request Examples
+
+### Register an App
+
+```bash
+curl -X POST http://localhost:5554/api/apps \
+ -H "Content-Type: application/json" \
+ -d '{
+ "name": "My App",
+ "repoPath": "/path/to/repo",
+ "uiPort": 3000,
+ "apiPort": 3001,
+ "pm2ProcessNames": ["myapp-server", "myapp-client"]
+ }'
+```
+
+### Execute AI Run
+
+```bash
+curl -X POST http://localhost:5554/api/runs \
+ -H "Content-Type: application/json" \
+ -d '{
+ "prompt": "List all files in the current directory",
+ "workspacePath": "/path/to/workspace"
+ }'
+```
+
+### Get PM2 Process Logs
+
+```bash
+curl http://localhost:5554/api/logs/portos-server?lines=50
+```
+
+## Error Responses
+
+All errors return JSON with consistent structure:
+
+```json
+{
+ "error": "Error message",
+ "code": "ERROR_CODE",
+ "timestamp": 1704067200000,
+ "context": {}
+}
+```
+
+Common error codes:
+- `NOT_FOUND` - Resource not found
+- `VALIDATION_ERROR` - Invalid request data
+- `COMMAND_NOT_ALLOWED` - Shell command not in allowlist
+- `INTERNAL_ERROR` - Server error
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
new file mode 100644
index 0000000000..e2a79ee980
--- /dev/null
+++ b/docs/ARCHITECTURE.md
@@ -0,0 +1,215 @@
+# Architecture Overview
+
+PortOS is a monorepo application with a React frontend and Express.js backend, managed by PM2.
+
+## System Diagram
+
+```
+┌─────────────────────────────────────────────────────────────────────────┐
+│ PortOS │
+├─────────────────────────────────────────────────────────────────────────┤
+│ │
+│ ┌──────────────────┐ ┌──────────────────────────────────────┐ │
+│ │ React Client │ │ Express Server │ │
+│ │ (port 5555) │ │ (port 5554) │ │
+│ │ │ │ │ │
+│ │ ┌────────────┐ │ HTTP │ ┌──────────┐ ┌────────────────┐ │ │
+│ │ │ Pages │◄─┼────────┼──┤ Routes │───│ Services │ │ │
+│ │ └────────────┘ │ │ └──────────┘ └────────────────┘ │ │
+│ │ │ │ │ │ │ │ │
+│ │ ┌────────────┐ │Socket.IO│ │ ┌─────▼─────┐ │ │
+│ │ │ Components │◄─┼────────┼────────┘ │ PM2 API │ │ │
+│ │ └────────────┘ │ │ └───────────┘ │ │
+│ │ │ │ │ │ │ │
+│ │ ┌────────────┐ │ │ ┌─────▼─────┐ │ │
+│ │ │ Services │ │ │ │ JSON Files│ │ │
+│ │ │ (api.js) │ │ │ │ (data/) │ │ │
+│ │ └────────────┘ │ │ └───────────┘ │ │
+│ └──────────────────┘ └──────────────────────────────────────┘ │
+│ │
+│ ┌──────────────────────────────────────────────────────────────────┐ │
+│ │ Chief of Staff (CoS) │ │
+│ │ │ │
+│ │ ┌─────────────┐ ┌──────────────┐ ┌────────────────────────┐ │ │
+│ │ │ Task Watcher│ │ CoS Service │ │ Sub-Agent Spawner │ │ │
+│ │ │(TASKS.md) │──│ (evaluation) │──│ (Claude CLI) │ │ │
+│ │ └─────────────┘ └──────────────┘ └────────────────────────┘ │ │
+│ │ │ │ │ │ │
+│ │ ┌──────▼──────────────▼─────────────────────▼───────────────┐ │ │
+│ │ │ portos-cos (Runner - port 5558) │ │ │
+│ │ │ Isolated process for agent management │ │ │
+│ │ └────────────────────────────────────────────────────────────┘ │ │
+│ └──────────────────────────────────────────────────────────────────┘ │
+│ │
+└─────────────────────────────────────────────────────────────────────────┘
+```
+
+## Directory Structure
+
+```
+PortOS/
+├── client/ # React + Vite frontend
+│ └── src/
+│ ├── components/ # Reusable UI components
+│ │ ├── cos/ # Chief of Staff components
+│ │ └── Layout.jsx # Main app layout
+│ ├── hooks/ # Custom React hooks
+│ ├── pages/ # Route-based page components
+│ └── services/ # API client (api.js, socket.js)
+│
+├── server/ # Express.js backend
+│ ├── routes/ # HTTP endpoint handlers
+│ ├── services/ # Business logic
+│ │ ├── cos.js # Chief of Staff core
+│ │ ├── subAgentSpawner.js # Claude CLI integration
+│ │ ├── pm2.js # PM2 process management
+│ │ ├── runner.js # AI execution engine
+│ │ └── memory.js # Memory system
+│ ├── lib/ # Shared utilities
+│ │ ├── errorHandler.js # Error normalization
+│ │ ├── validation.js # Zod schemas
+│ │ └── taskParser.js # TASKS.md parser
+│ └── cos-runner/ # Isolated agent runner
+│ └── index.js # Standalone Express server
+│
+├── data/ # Runtime data (gitignored)
+│ ├── apps.json # Registered apps
+│ ├── providers.json # AI provider configs
+│ ├── history.json # Action history
+│ ├── TASKS.md # User task file
+│ ├── COS-TASKS.md # System task file
+│ ├── COS-GOALS.md # Mission and goals
+│ └── cos/ # CoS state and agents
+│ ├── state.json # Daemon state
+│ ├── agents/ # Agent outputs
+│ └── memory/ # Memory storage
+│
+├── docs/ # Documentation
+├── .github/workflows/ # CI/CD
+└── ecosystem.config.cjs # PM2 configuration
+```
+
+## Data Flow
+
+### HTTP Request Flow
+
+```
+Browser → React Page → api.js → Express Route → Service → Response
+ │
+ ├── Zod Validation
+ ├── Service Logic
+ └── JSON File / PM2 API
+```
+
+### WebSocket Event Flow
+
+```
+Server Event → Socket.IO → socket.js → React Component State Update
+ │
+ └── Real-time: logs, CoS status, errors, memory changes
+```
+
+### Chief of Staff Flow
+
+```
+1. Task Watcher monitors TASKS.md for changes
+2. CoS Service evaluates tasks on interval
+3. For each pending task:
+ a. Select appropriate AI model based on task complexity
+ b. Build prompt with context and memory injection
+ c. Spawn Claude CLI via Sub-Agent Spawner
+4. Agent executes task, output captured
+5. On completion:
+ a. Mark task as completed
+ b. Extract memories from output
+ c. Update usage metrics
+```
+
+## Key Services
+
+### Apps Service (`server/services/apps.js`)
+- CRUD operations for registered apps
+- Persists to `data/apps.json`
+
+### PM2 Service (`server/services/pm2.js`)
+- Start/stop/restart processes
+- Status monitoring
+- Log retrieval
+
+### Runner Service (`server/services/runner.js`)
+- AI provider execution
+- CLI and API-based providers
+- Output streaming and capture
+
+### CoS Service (`server/services/cos.js`)
+- Task evaluation and prioritization
+- Agent orchestration
+- Health monitoring
+- Self-improvement task generation
+
+### Sub-Agent Spawner (`server/services/subAgentSpawner.js`)
+- Claude CLI process spawning
+- Model selection based on task complexity
+- MCP server integration
+- Usage tracking
+
+### Memory Service (`server/services/memory.js`)
+- Semantic memory storage
+- Vector embeddings via LM Studio
+- Memory retrieval for context injection
+
+## Error Handling
+
+All routes use `asyncHandler` wrapper from `server/lib/errorHandler.js`:
+
+```javascript
+// Routes automatically catch errors and:
+// 1. Log to console with emoji prefix
+// 2. Emit Socket.IO event for UI notification
+// 3. Return structured JSON error response
+```
+
+Error severity levels:
+- **warning**: Non-critical, logged only
+- **error**: Server error, shown to user
+- **critical**: System-threatening, triggers auto-fix
+
+## Security Model
+
+1. **Network Security**: Relies on Tailscale for access control
+2. **Command Allowlist**: Shell execution restricted to approved commands
+3. **No Shell Interpolation**: Uses `spawn()` with argument arrays
+4. **Zod Validation**: All API inputs validated
+5. **Path Traversal Prevention**: Filename sanitization on uploads
+
+## PM2 Process Map
+
+| Process | Port | Purpose |
+|---------|------|---------|
+| portos-server | 5554 | Main API server |
+| portos-client | 5555 | Vite dev server |
+| portos-browser | 5556-5557 | Playwright browser (optional) |
+| portos-cos | 5558 | Isolated agent runner |
+| portos-autofixer | 5559 | Crash detection daemon |
+| portos-autofixer-ui | 5560 | Autofixer web UI |
+
+## Extension Points
+
+### Adding a New Page
+1. Create component in `client/src/pages/`
+2. Add route in `client/src/App.jsx`
+3. Add navigation link in `client/src/components/Layout.jsx`
+
+### Adding an API Endpoint
+1. Create route file in `server/routes/`
+2. Register in `server/index.js`
+3. Add Zod schema if needed in `server/lib/validation.js`
+
+### Adding a Service
+1. Create service file in `server/services/`
+2. Export functions (not classes)
+3. Import in routes as needed
+
+### Adding CoS Task Types
+1. Update `SELF_IMPROVEMENT_TYPES` in `server/services/cos.js`
+2. Add prompt template in `generateSelfImprovementTask()`
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
new file mode 100644
index 0000000000..604d16bd9c
--- /dev/null
+++ b/docs/TROUBLESHOOTING.md
@@ -0,0 +1,286 @@
+# Troubleshooting Guide
+
+Common issues and solutions when running PortOS.
+
+## Startup Issues
+
+### Port Already in Use
+
+**Symptom**: Server fails to start with `EADDRINUSE` error.
+
+**Solution**:
+```bash
+# Find what's using the port
+lsof -i :5554
+lsof -i :5555
+
+# Kill the process or choose different ports in ecosystem.config.cjs
+```
+
+### PM2 Process Not Starting
+
+**Symptom**: `pm2 start ecosystem.config.cjs` shows process but status is `errored`.
+
+**Solution**:
+```bash
+# Check PM2 logs for errors
+pm2 logs portos-server --lines 100
+
+# Common causes:
+# - Missing dependencies: npm run install:all
+# - Missing data directory: mkdir -p data
+# - Port conflict: check EADDRINUSE errors
+```
+
+### Missing Data Directory
+
+**Symptom**: Server crashes with `ENOENT` errors about files in `data/`.
+
+**Solution**:
+```bash
+# Copy sample data files
+cp -r data.sample/* data/
+```
+
+## Connection Issues
+
+### Cannot Access from Other Devices
+
+**Symptom**: PortOS works on localhost but not from phone/tablet.
+
+**Causes and Solutions**:
+
+1. **Tailscale not connected**: Ensure both devices are on same Tailscale network
+2. **Firewall blocking**: Check local firewall allows ports 5554-5555
+3. **Server bound to localhost**: PortOS should bind to 0.0.0.0 (default)
+
+```bash
+# Verify server is listening on all interfaces
+netstat -an | grep 5554
+# Should show: *.5554 or 0.0.0.0:5554
+```
+
+### WebSocket Disconnections
+
+**Symptom**: Real-time features (logs, CoS updates) stop working.
+
+**Solution**:
+- Check browser console for WebSocket errors
+- Verify server is running: `pm2 status`
+- Restart server: `pm2 restart ecosystem.config.cjs`
+
+## AI Provider Issues
+
+### Claude Code CLI Not Found
+
+**Symptom**: DevTools runs fail with "command not found".
+
+**Solution**:
+```bash
+# Install Claude Code globally
+npm install -g @anthropic-ai/claude-code
+
+# Verify installation
+which claude
+claude --version
+```
+
+### API Key Errors
+
+**Symptom**: AI runs fail with authentication errors.
+
+**Solution**:
+1. Check provider configuration in PortOS Settings
+2. Verify API key is valid and has credits
+3. For Claude: ensure `ANTHROPIC_API_KEY` is set
+
+### Model Not Found
+
+**Symptom**: Error "model: xyz not found" or similar.
+
+**Solution**:
+- Verify model name matches provider's available models
+- Check provider documentation for correct model identifiers
+- Common models:
+ - Claude: `claude-sonnet-4-20250514`, `claude-opus-4-5-20251101`
+ - OpenAI: `gpt-4`, `gpt-4-turbo`
+ - Ollama: Model must be pulled first (`ollama pull llama3`)
+
+## Chief of Staff Issues
+
+### CoS Not Running
+
+**Symptom**: CoS page shows "Stopped" status.
+
+**Solution**:
+1. Click "Start" button in CoS UI
+2. Or enable `alwaysOn: true` in CoS config
+3. Check server logs for startup errors
+
+### Agents Not Spawning
+
+**Symptom**: Tasks stay in "pending" status, no agents start.
+
+**Solution**:
+```bash
+# Check CoS runner is running
+pm2 status | grep portos-cos
+
+# Check runner logs
+pm2 logs portos-cos --lines 100
+
+# Verify Claude CLI is available
+which claude
+```
+
+### Tasks Not Being Picked Up
+
+**Symptom**: Added tasks to TASKS.md but CoS ignores them.
+
+**Solution**:
+1. Verify task format matches expected syntax:
+ ```markdown
+ ## Pending
+ - [ ] #task-001 | HIGH | Task description
+ ```
+2. Check file path in CoS config matches your TASKS.md location
+3. Trigger manual evaluation via UI
+
+### Memory System Not Working
+
+**Symptom**: Memory search returns no results, embeddings fail.
+
+**Solution**:
+1. Ensure LM Studio is running on port 1234
+2. Load an embedding model in LM Studio (e.g., `nomic-embed-text`)
+3. Check memory embeddings status: `GET /api/memory/embeddings/status`
+
+## PM2 Issues
+
+### Process Keeps Restarting
+
+**Symptom**: PM2 shows high restart count, app unstable.
+
+**Solution**:
+```bash
+# Check for crash reason
+pm2 logs portos-server --lines 200
+
+# Common causes:
+# - Unhandled exceptions (check error handling)
+# - Memory limit exceeded (increase max_memory_restart)
+# - Missing environment variables
+```
+
+### Cannot Stop Processes
+
+**Symptom**: `pm2 stop` doesn't work or processes restart.
+
+**Solution**:
+```bash
+# Stop specific ecosystem
+pm2 stop ecosystem.config.cjs
+
+# Never use these (affects all PM2 apps):
+# pm2 kill ← Don't use
+# pm2 delete all ← Don't use
+```
+
+### Old Code Running After Changes
+
+**Symptom**: Code changes don't take effect.
+
+**Solution**:
+```bash
+# Restart to pick up changes
+pm2 restart ecosystem.config.cjs
+
+# For frontend changes, Vite hot-reload should work
+# For server changes, PM2 watch mode can help (if enabled)
+```
+
+## Database/Data Issues
+
+### Lost App Registrations
+
+**Symptom**: Apps disappear after restart.
+
+**Causes**:
+- `data/apps.json` was deleted or corrupted
+- File permissions prevent writing
+
+**Solution**:
+```bash
+# Check file exists and is valid JSON
+cat data/apps.json | jq .
+
+# If corrupted, restore from backup or recreate
+```
+
+### History Not Persisting
+
+**Symptom**: Action history clears on restart.
+
+**Solution**:
+- Check `data/history.json` exists and is writable
+- Verify disk space available
+
+## Performance Issues
+
+### Slow UI Loading
+
+**Causes and Solutions**:
+1. **Large log files**: Clear old logs with `pm2 flush`
+2. **Many apps**: Pagination added in recent versions
+3. **Network latency**: Use local access when possible
+
+### High Memory Usage
+
+**Solution**:
+```bash
+# Check PM2 memory usage
+pm2 monit
+
+# Set memory limits in ecosystem.config.cjs
+max_memory_restart: '500M'
+```
+
+### Agent Runs Timeout
+
+**Symptom**: AI runs hit timeout before completing.
+
+**Solution**:
+- Increase timeout in provider settings
+- Break large tasks into smaller chunks
+- Check network connectivity to AI provider
+
+## Development Issues
+
+### Hot Reload Not Working
+
+**Symptom**: Frontend changes require manual refresh.
+
+**Solution**:
+- Check Vite is running: `pm2 logs portos-client`
+- Ensure file watchers aren't exhausted: `fs.inotify.max_user_watches`
+
+### Tests Failing
+
+**Solution**:
+```bash
+cd server
+npm test
+
+# For specific test file
+npm test -- taskParser.test.js
+
+# Watch mode for development
+npm run test:watch
+```
+
+## Getting Help
+
+1. **Check logs**: `pm2 logs` shows all process output
+2. **Browser console**: F12 → Console for frontend errors
+3. **Server logs**: Look for emoji prefixes (❌ errors, ⚠️ warnings)
+4. **GitHub Issues**: Report bugs at https://github.com/atomantic/PortOS/issues
diff --git a/server/services/subAgentSpawner.test.js b/server/services/subAgentSpawner.test.js
new file mode 100644
index 0000000000..ee227b19e4
--- /dev/null
+++ b/server/services/subAgentSpawner.test.js
@@ -0,0 +1,474 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+/**
+ * Tests for the subAgentSpawner service
+ *
+ * Note: We test the pure functions directly by extracting their logic.
+ * The spawner has complex dependencies (process spawning, file system, etc.)
+ * so we focus on the decision-making logic that can be unit tested.
+ */
+
+// Test model selection logic
+describe('Model Selection Logic', () => {
+ // Simulate selectModelForTask function logic
+ function selectModelForTask(task, provider) {
+ const desc = (task.description || '').toLowerCase();
+ const context = task.metadata?.context || '';
+ const contextLen = context.length;
+ const priority = task.priority || 'MEDIUM';
+
+ // Check for user-specified model preference
+ const userModel = task.metadata?.model;
+ const userProvider = task.metadata?.provider;
+
+ if (userModel) {
+ return {
+ model: userModel,
+ tier: 'user-specified',
+ reason: 'user-preference',
+ userProvider: userProvider || null
+ };
+ }
+
+ // Image/visual analysis
+ if (/image|screenshot|visual|photo|picture/.test(desc)) {
+ return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'visual-analysis' };
+ }
+
+ // Critical priority
+ if (priority === 'CRITICAL') {
+ return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'critical-priority' };
+ }
+
+ // Complex reasoning tasks
+ if (/architect|refactor|design|complex|optimize|security|audit|review.*code|performance/.test(desc)) {
+ return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'complex-task' };
+ }
+
+ // Long context
+ if (contextLen > 500) {
+ return { model: provider.heavyModel || provider.mediumModel || provider.defaultModel, tier: 'heavy', reason: 'long-context' };
+ }
+
+ // Detect coding/development tasks
+ const isCodingTask = /\b(fix|bug|implement|develop|code|refactor|test|feature|function|class|module|api|endpoint|component|service|route|schema|migration|script|build|deploy|debug|error|exception|crash|issue|patch)\b/.test(desc);
+
+ // Simple/quick tasks (non-coding)
+ if (!isCodingTask && /fix typo|update text|update docs|edit readme|update readme|write docs|documentation only|format text/.test(desc)) {
+ return { model: provider.lightModel || provider.defaultModel, tier: 'light', reason: 'documentation-task' };
+ }
+
+ // Standard tasks
+ return { model: provider.mediumModel || provider.defaultModel, tier: 'medium', reason: 'standard-task' };
+ }
+
+ const mockProvider = {
+ id: 'anthropic',
+ name: 'Anthropic',
+ defaultModel: 'claude-3-sonnet',
+ lightModel: 'claude-3-haiku',
+ mediumModel: 'claude-3-sonnet',
+ heavyModel: 'claude-3-opus'
+ };
+
+ describe('User-specified model', () => {
+ it('should use user-specified model when provided', () => {
+ const task = {
+ description: 'Simple task',
+ metadata: { model: 'custom-model' }
+ };
+
+ const result = selectModelForTask(task, mockProvider);
+
+ expect(result.model).toBe('custom-model');
+ expect(result.tier).toBe('user-specified');
+ expect(result.reason).toBe('user-preference');
+ });
+
+ it('should include user provider if specified', () => {
+ const task = {
+ description: 'Simple task',
+ metadata: { model: 'gpt-4', provider: 'openai' }
+ };
+
+ const result = selectModelForTask(task, mockProvider);
+
+ expect(result.userProvider).toBe('openai');
+ });
+ });
+
+ describe('Visual analysis tasks', () => {
+ it('should select heavy model for image analysis', () => {
+ const task = { description: 'Analyze this image for errors' };
+ const result = selectModelForTask(task, mockProvider);
+
+ expect(result.model).toBe('claude-3-opus');
+ expect(result.tier).toBe('heavy');
+ expect(result.reason).toBe('visual-analysis');
+ });
+
+ it('should select heavy model for screenshot review', () => {
+ const task = { description: 'Review the screenshot' };
+ const result = selectModelForTask(task, mockProvider);
+
+ expect(result.reason).toBe('visual-analysis');
+ });
+ });
+
+ describe('Priority-based selection', () => {
+ it('should select heavy model for CRITICAL priority', () => {
+ const task = { description: 'Fix something', priority: 'CRITICAL' };
+ const result = selectModelForTask(task, mockProvider);
+
+ expect(result.model).toBe('claude-3-opus');
+ expect(result.reason).toBe('critical-priority');
+ });
+
+ it('should not use heavy for HIGH priority alone', () => {
+ const task = { description: 'Update a setting', priority: 'HIGH' };
+ const result = selectModelForTask(task, mockProvider);
+
+ expect(result.reason).not.toBe('critical-priority');
+ });
+ });
+
+ describe('Complex task detection', () => {
+ it.each([
+ ['architect the new module', 'complex-task'],
+ ['refactor the auth system', 'complex-task'],
+ ['design a new API', 'complex-task'],
+ ['optimize performance', 'complex-task'],
+ ['security audit', 'complex-task'],
+ ['review code for issues', 'complex-task']
+ ])('should select heavy model for: %s', (description, expectedReason) => {
+ const task = { description };
+ const result = selectModelForTask(task, mockProvider);
+
+ expect(result.tier).toBe('heavy');
+ expect(result.reason).toBe(expectedReason);
+ });
+ });
+
+ describe('Context length handling', () => {
+ it('should select heavy model for long context', () => {
+ const task = {
+ description: 'Simple task',
+ metadata: { context: 'x'.repeat(501) }
+ };
+
+ const result = selectModelForTask(task, mockProvider);
+
+ expect(result.tier).toBe('heavy');
+ expect(result.reason).toBe('long-context');
+ });
+
+ it('should not use heavy model for short context', () => {
+ const task = {
+ description: 'Simple update',
+ metadata: { context: 'Short context' }
+ };
+
+ const result = selectModelForTask(task, mockProvider);
+
+ expect(result.reason).not.toBe('long-context');
+ });
+ });
+
+ describe('Documentation tasks', () => {
+ // Note: The model selection logic checks for coding keywords first,
+ // so we use phrases that don't contain words like 'fix', 'bug', etc.
+ // which would be detected as coding tasks
+ it.each([
+ 'update text in guide',
+ 'edit readme with new info',
+ 'format text only'
+ ])('should select light model for: %s', (description) => {
+ const task = { description };
+ const result = selectModelForTask(task, mockProvider);
+
+ expect(result.model).toBe('claude-3-haiku');
+ expect(result.tier).toBe('light');
+ expect(result.reason).toBe('documentation-task');
+ });
+
+ // These phrases contain coding keywords so they get medium model
+ // Note: 'fix' is a coding keyword so 'fix typo' routes to medium tier
+ it.each([
+ 'fix typo in manual',
+ 'fix typo in README',
+ 'update docs for feature',
+ 'write docs for API'
+ ])('should NOT select light model when coding keyword present: %s', (description) => {
+ const task = { description };
+ const result = selectModelForTask(task, mockProvider);
+
+ // These contain words like 'fix', 'docs', 'API' which are coding keywords
+ expect(result.tier).not.toBe('light');
+ });
+ });
+
+ describe('Coding tasks detection', () => {
+ it.each([
+ 'fix bug in login',
+ 'implement new feature',
+ 'develop API endpoint',
+ 'refactor the component',
+ 'test the function',
+ 'debug the error',
+ 'patch the issue'
+ ])('should NOT select light model for coding task: %s', (description) => {
+ const task = { description };
+ const result = selectModelForTask(task, mockProvider);
+
+ expect(result.tier).not.toBe('light');
+ });
+
+ it('should use medium model for standard coding tasks', () => {
+ const task = { description: 'Add a new helper function' };
+ const result = selectModelForTask(task, mockProvider);
+
+ expect(result.model).toBe('claude-3-sonnet');
+ expect(result.tier).toBe('medium');
+ expect(result.reason).toBe('standard-task');
+ });
+ });
+
+ describe('Default fallbacks', () => {
+ it('should fall back to defaultModel if lightModel not available', () => {
+ const providerNoLight = { ...mockProvider, lightModel: null };
+ const task = { description: 'update readme' };
+
+ const result = selectModelForTask(task, providerNoLight);
+
+ expect(result.model).toBe('claude-3-sonnet');
+ });
+
+ it('should fall back to defaultModel if heavyModel not available', () => {
+ const providerNoHeavy = { ...mockProvider, heavyModel: null };
+ const task = { description: 'analyze this image' };
+
+ const result = selectModelForTask(task, providerNoHeavy);
+
+ expect(result.model).toBe('claude-3-sonnet');
+ });
+ });
+});
+
+// Test error pattern analysis
+describe('Error Analysis Logic', () => {
+ const ERROR_PATTERNS = [
+ {
+ pattern: /API Error: 404.*model:\s*(\S+)/i,
+ category: 'model-not-found',
+ actionable: true
+ },
+ {
+ pattern: /API Error: 401|authentication|unauthorized/i,
+ category: 'auth-error',
+ actionable: true
+ },
+ {
+ pattern: /API Error: 429|rate.?limit|too many requests/i,
+ category: 'rate-limit',
+ actionable: false
+ },
+ {
+ pattern: /API Error: 5\d{2}|server error|internal error/i,
+ category: 'server-error',
+ actionable: false
+ },
+ {
+ pattern: /ECONNREFUSED|ETIMEDOUT|network error/i,
+ category: 'network-error',
+ actionable: false
+ },
+ {
+ pattern: /not_found_error.*model/i,
+ category: 'model-not-found',
+ actionable: true
+ }
+ ];
+
+ function categorizeError(output) {
+ for (const errorDef of ERROR_PATTERNS) {
+ if (errorDef.pattern.test(output)) {
+ return {
+ category: errorDef.category,
+ actionable: errorDef.actionable
+ };
+ }
+ }
+ return { category: 'unknown', actionable: false };
+ }
+
+ describe('Model not found errors', () => {
+ it('should detect 404 model error', () => {
+ const output = 'API Error: 404 - model: claude-4-ultra not found';
+ const result = categorizeError(output);
+
+ expect(result.category).toBe('model-not-found');
+ expect(result.actionable).toBe(true);
+ });
+
+ it('should detect not_found_error for model', () => {
+ const output = 'Response: not_found_error - The specified model does not exist';
+ const result = categorizeError(output);
+
+ expect(result.category).toBe('model-not-found');
+ expect(result.actionable).toBe(true);
+ });
+ });
+
+ describe('Authentication errors', () => {
+ it('should detect 401 error', () => {
+ const output = 'API Error: 401 Unauthorized';
+ const result = categorizeError(output);
+
+ expect(result.category).toBe('auth-error');
+ expect(result.actionable).toBe(true);
+ });
+
+ it('should detect authentication failure', () => {
+ const output = 'Authentication failed: invalid API key';
+ const result = categorizeError(output);
+
+ expect(result.category).toBe('auth-error');
+ expect(result.actionable).toBe(true);
+ });
+ });
+
+ describe('Rate limit errors', () => {
+ it('should detect 429 error', () => {
+ const output = 'API Error: 429 Too Many Requests';
+ const result = categorizeError(output);
+
+ expect(result.category).toBe('rate-limit');
+ expect(result.actionable).toBe(false);
+ });
+
+ it('should detect rate limit message', () => {
+ const output = 'Error: Rate limit exceeded, please try again later';
+ const result = categorizeError(output);
+
+ expect(result.category).toBe('rate-limit');
+ expect(result.actionable).toBe(false);
+ });
+ });
+
+ describe('Server errors', () => {
+ it('should detect 500 error', () => {
+ const output = 'API Error: 500 Internal Server Error';
+ const result = categorizeError(output);
+
+ expect(result.category).toBe('server-error');
+ expect(result.actionable).toBe(false);
+ });
+
+ it('should detect 502 error', () => {
+ const output = 'API Error: 502 Bad Gateway';
+ const result = categorizeError(output);
+
+ expect(result.category).toBe('server-error');
+ expect(result.actionable).toBe(false);
+ });
+ });
+
+ describe('Network errors', () => {
+ it('should detect connection refused', () => {
+ const output = 'Error: connect ECONNREFUSED 127.0.0.1:443';
+ const result = categorizeError(output);
+
+ expect(result.category).toBe('network-error');
+ expect(result.actionable).toBe(false);
+ });
+
+ it('should detect timeout', () => {
+ const output = 'Error: ETIMEDOUT - connection timed out';
+ const result = categorizeError(output);
+
+ expect(result.category).toBe('network-error');
+ expect(result.actionable).toBe(false);
+ });
+ });
+
+ describe('Unknown errors', () => {
+ it('should return unknown for unmatched patterns', () => {
+ const output = 'Some random error message';
+ const result = categorizeError(output);
+
+ expect(result.category).toBe('unknown');
+ expect(result.actionable).toBe(false);
+ });
+ });
+});
+
+// Test exit code message mapping
+describe('Exit Code Analysis', () => {
+ const exitCodeMessages = {
+ 1: 'General error',
+ 2: 'Misuse of shell command',
+ 126: 'Command invoked cannot execute (permission or not executable)',
+ 127: 'Command not found',
+ 128: 'Invalid exit argument',
+ 130: 'Script terminated by Ctrl+C',
+ 137: 'Process killed (SIGKILL)',
+ 143: 'Process terminated (SIGTERM - likely timeout)',
+ 255: 'Exit status out of range'
+ };
+
+ function getExitCodeMessage(exitCode) {
+ return exitCodeMessages[exitCode] || 'Unknown error';
+ }
+
+ it.each([
+ [1, 'General error'],
+ [2, 'Misuse of shell command'],
+ [126, 'Command invoked cannot execute (permission or not executable)'],
+ [127, 'Command not found'],
+ [130, 'Script terminated by Ctrl+C'],
+ [137, 'Process killed (SIGKILL)'],
+ [143, 'Process terminated (SIGTERM - likely timeout)']
+ ])('exit code %i should map to: %s', (code, message) => {
+ expect(getExitCodeMessage(code)).toBe(message);
+ });
+
+ it('should return Unknown error for unmapped codes', () => {
+ expect(getExitCodeMessage(99)).toBe('Unknown error');
+ });
+});
+
+// Test spawn args building
+describe('Spawn Arguments Building', () => {
+ function buildSpawnArgs(config, model) {
+ const args = [
+ '--dangerously-skip-permissions',
+ '--print',
+ ];
+
+ if (model) {
+ args.push('--model', model);
+ }
+
+ return args;
+ }
+
+ it('should include base flags', () => {
+ const args = buildSpawnArgs({}, null);
+
+ expect(args).toContain('--dangerously-skip-permissions');
+ expect(args).toContain('--print');
+ });
+
+ it('should include model when specified', () => {
+ const args = buildSpawnArgs({}, 'claude-3-sonnet');
+
+ expect(args).toContain('--model');
+ expect(args).toContain('claude-3-sonnet');
+ });
+
+ it('should not include model flag when model is null', () => {
+ const args = buildSpawnArgs({}, null);
+
+ expect(args).not.toContain('--model');
+ });
+});