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: map existing codebase

Adam Eivya91bc7d46f92
diff --git a/.planning/codebase/ARCHITECTURE.md b/.planning/codebase/ARCHITECTURE.md
new file mode 100644
index 0000000000..947ed17e25
--- /dev/null
+++ b/.planning/codebase/ARCHITECTURE.md
@@ -0,0 +1,172 @@
+# Architecture
+
+**Analysis Date:** 2026-02-26
+
+## Pattern Overview
+
+**Overall:** Monorepo with centralized Express.js backend serving multiple PM2-managed processes and a Vite/React frontend
+
+**Key Characteristics:**
+- Multi-process orchestration via PM2 (server, UI, CoS agent runner, autofixer, browser automation)
+- Layered backend (routes → services → lib utilities)
+- Validation-first approach with Zod schemas
+- Centralized error handling with Socket.IO event broadcasting
+- JSON file persistence in `/data/` directory
+- Functional React components with custom hooks for state management
+
+## Layers
+
+**Presentation (Client):**
+- Purpose: User interface for monitoring, controlling, and configuring PortOS and managed apps
+- Location: `client/src/`
+- Contains: React pages, reusable components, service clients, hooks, utilities
+- Depends on: HTTP API via `api.js`, WebSocket via `socket.js`
+- Used by: End users via Vite dev server (port 5555) or production build
+
+**API Layer (Routes):**
+- Purpose: HTTP request handlers that validate input and delegate to services
+- Location: `server/routes/`
+- Contains: Route handlers for apps, agents, CoS, brain, digital-twin, providers, etc.
+- Depends on: Services (business logic), lib/validation.js (Zod schemas)
+- Used by: Express app, consumed by client via HTTP
+
+**Business Logic (Services):**
+- Purpose: Core application logic, PM2 management, file I/O, event publishing
+- Location: `server/services/`
+- Contains: ~100+ service files managing apps, agents, CoS runner, brain, digital-twin, providers, etc.
+- Depends on: lib/ (validation, error handling, file utils), PM2, Socket.IO
+- Used by: Routes, other services, scheduled tasks
+
+**Validation & Utilities (Lib):**
+- Purpose: Shared schemas, error handling, file operations, platform detection
+- Location: `server/lib/`
+- Contains: Zod validation schemas, error handler, file utilities, vector math, task parsing
+- Depends on: Zod, fs/promises
+- Used by: Routes, services, Socket.IO validation
+
+**Data Persistence:**
+- Purpose: Store application state in JSON files
+- Location: `data/` directory (runtime), `data.sample/` (template)
+- Contains: apps.json, providers.json, runs/, prompts/, cos/, agents/, brain/, digital-twin/, meatspace/
+- Accessed by: Services via fileUtils and custom loaders
+
+**External Integration (portos-ai-toolkit):**
+- Purpose: AI provider management, run tracking, prompt templating
+- Location: External npm module at `../portos-ai-toolkit`
+- Contains: Provider drivers, CLI runner, hooks system
+- Integrated at: `server/index.js` creates toolkit instance, routes extend it
+
+**Process Management (PM2):**
+- Purpose: Orchestrate multi-process lifecycle
+- Location: `ecosystem.config.cjs` (configuration), `server/cos-runner/index.js` (isolated CoS runner)
+- Contains: Process definitions for server, UI, CoS runner, autofixer, browser service
+- Managed by: PM2 CLI, PortOS routes use pm2Service for control
+
+## Data Flow
+
+**Typical Request Flow:**
+
+1. Client initiates HTTP request via `services/api.js`
+2. Express route handler (`server/routes/*.js`) receives request
+3. Route validates input using Zod schema from `lib/validation.js`
+4. Route calls service(s) via `server/services/`
+5. Service executes business logic (file I/O, PM2 commands, external APIs)
+6. Route responds with JSON result or throws ServerError
+7. ErrorMiddleware catches errors, emits Socket.IO event, returns error response
+8. Client displays response or error toast notification
+
+**WebSocket Flow (Real-time Updates):**
+
+1. Client subscribes via socket event (e.g., `detect:start`, `logs:subscribe`)
+2. `services/socket.js` handles event with validation
+3. Socket handler spawns long-running operation (detection, streaming logs)
+4. Handler emits progress updates back via `socket.emit()`
+5. Service publishes state change events (e.g., `apps:changed`)
+6. All connected clients receive broadcast update
+
+**State Management:**
+- Server: JSON files + in-memory caches (e.g., `appsCache` in `services/apps.js`)
+- Client: React state via hooks + Socket.IO subscriptions + API fetches
+- Cache invalidation: File watchers, event emitters, TTL-based caching
+
+## Key Abstractions
+
+**App Registry:**
+- Purpose: Track managed applications (PortOS itself, user projects)
+- Examples: `server/services/apps.js`, routes/apps.js
+- Pattern: In-memory cache (2s TTL) backed by `data/apps.json`, EventEmitter for subscriptions
+
+**PM2 Service Layer:**
+- Purpose: Abstract PM2 CLI commands behind consistent interface
+- Examples: `server/services/pm2.js`, `pm2Standardizer.js`
+- Pattern: Spawn child processes, parse output, return typed results
+
+**Zod Validation:**
+- Purpose: Runtime schema validation at API boundary
+- Examples: `lib/validation.js`, `lib/digitalTwinValidation.js`, `lib/brainValidation.js`
+- Pattern: Define schemas once, validate in routes and Socket.IO handlers
+
+**Error Broadcasting:**
+- Purpose: Propagate server errors to all UI clients in real-time
+- Examples: `lib/errorHandler.js`, `services/autoFixer.js`
+- Pattern: ServerError with metadata → errorMiddleware → Socket.IO `error:occurred` event → Toast UI
+
+**AI Toolkit Integration:**
+- Purpose: Centralize AI provider configuration and execution tracking
+- Examples: `server/services/providers.js`, `runner.js`, routes/providers.js
+- Pattern: Import toolkit, extend routes, set hooks for PortOS lifecycle tracking
+
+## Entry Points
+
+**Server Initialization:**
+- Location: `server/index.js`
+- Triggers: `npm run dev` or `pm2 start ecosystem.config.cjs`
+- Responsibilities: Create Express app, initialize Socket.IO, load routes, set middleware, start HTTP server on port 5554
+
+**Client Initialization:**
+- Location: `client/src/main.jsx` → `App.jsx`
+- Triggers: Vite dev server (port 5555) or production build
+- Responsibilities: Set up React Router, initialize hooks, load Layout component with nested routes
+
+**PM2 CoS Runner Process:**
+- Location: `server/cos-runner/index.js`
+- Triggers: Spawned by PM2 (separate process, not watched)
+- Responsibilities: Run isolated Claude CLI agent instances, prevent orphaned processes
+
+**Autofixer Service:**
+- Location: `autofixer/server.js`
+- Triggers: PM2 spawned process (port 5559)
+- Responsibilities: Listen for error events, execute recovery scripts, report status
+
+## Error Handling
+
+**Strategy:** Catch errors at route level, emit Socket.IO events, let client display toast
+
+**Patterns:**
+- Routes use `asyncHandler` wrapper to catch Promise rejections
+- Services throw `ServerError` with status, code, context
+- `errorMiddleware` catches uncaught errors and emits via Socket.IO
+- Client hook `useErrorNotifications` subscribes to `error:occurred` events
+- Platform errors (PLATFORM_UNAVAILABLE) emit as warnings, not errors
+
+## Cross-Cutting Concerns
+
+**Logging:** Single-line format with emoji prefixes, string interpolation
+- Example: `console.log('🚀 Server started on port ${PORT}')`
+- Used in: All services and routes
+
+**Validation:** Zod schemas defined in `lib/validation.js` and domain-specific files
+- Routes call `validateRequest(schema, data, next)`
+- Socket.IO calls `validateSocketData(schema, rawData, socket, eventName)`
+
+**Authentication:** Not applicable (single-user, internal tool behind Tailscale VPN)
+
+**File I/O:** Centralized through `lib/fileUtils.js` with consistent PATHS constants
+- Services use `readJSONFile()`, `writeFile()`, `ensureDir()`
+
+**Process Management:** PM2 commands abstracted via `services/pm2.js`
+- All process lifecycle operations go through pm2Service
+
+---
+
+*Architecture analysis: 2026-02-26*
diff --git a/.planning/codebase/CONCERNS.md b/.planning/codebase/CONCERNS.md
new file mode 100644
index 0000000000..77f1dd3e26
--- /dev/null
+++ b/.planning/codebase/CONCERNS.md
@@ -0,0 +1,259 @@
+# Codebase Concerns
+
+**Analysis Date:** 2026-02-26
+
+## Tech Debt
+
+**Large Service Files (>3000 LOC):**
+- Issue: Core services have grown monolithic with mixed responsibilities
+- Files: `server/services/cos.js` (3763 LOC), `server/services/subAgentSpawner.js` (3145 LOC), `server/services/digital-twin.js` (2823 LOC)
+- Impact: Harder to test, refactor, and reason about code flow; increased cognitive load for maintainers
+- Fix approach: Extract services into focused modules (e.g., agent indexing, state management, spawning logic into separate files); consider facade pattern to reduce coupling
+
+**Race Conditions in File State Management:**
+- Issue: Multiple services write to shared JSON state files without coordinated locking
+- Files: `server/services/cos.js`, `server/services/memory.js`, `server/services/taskSchedule.js`
+- Current mitigation: Mutex locks exist in `memory.js` (line 48: `createMutex()`) but not consistently applied to cos.js state mutations
+- Impact: Risk of corrupted state.json, index.json, or embeddings.json on concurrent writes; loss of agent metadata
+- Fix approach: Wrap all state mutations in `withLock()` in cos.js; implement atomic write-via-temp-file pattern consistently across all state files
+
+**Unprotected Atomic Write Operations:**
+- Issue: `writeFile` → `rename` sequences in `cos.js` (lines 429-430, 108-112) attempt atomicity but catch handlers swallow errors
+- Files: `server/services/cos.js` (lines 108-112: agent index save), `server/lib/fileUtils.js` (no fallback for atomic writes)
+- Impact: On rename failure, temp files accumulate in data/cos; corrupt writes if process crashes between writeFile and rename
+- Fix approach: Implement guaranteed atomic writes with rollback; add cleanup for orphaned temp files on startup; log critical failures
+
+**Missing Mutex in CoS State Mutations:**
+- Issue: CoS daemon writes state without mutex protection while sub-agents read/update agents
+- Files: `server/services/cos.js` (state writes at lines 429-430)
+- Impact: Sub-agent updates to agent metadata can collide with CoS state persistence; lost updates
+- Fix approach: Create dedicated state manager with `withLock()` wrapper for all state.json mutations
+
+## Known Bugs
+
+**Agent Index Migration Incomplete:**
+- Symptoms: Agents created before date-bucket migration may not be found on subsequent runs
+- Files: `server/services/cos.js` (lines 96-98, 160-228)
+- Trigger: Migration runs once on first access to `loadAgentIndex()`; if migration fails silently, old flat agents are orphaned
+- Workaround: Manually move agent directories from `data/cos/agents/` to `data/cos/agents/YYYY-MM-DD/` buckets
+- Fix approach: Add recovery log for failed migrations; implement rollback mechanism; add startup validation
+
+**Challenge Solver AI Timeout Vulnerability:**
+- Symptoms: Moltbook posts get stuck in "verification_required" state indefinitely
+- Files: `server/integrations/moltbook/challengeSolver.js` (lines 52-84)
+- Trigger: AI provider timeout (specified as `provider.timeout || 300000` = 5min) exceeds verification window (Moltbook requires answer within ~5 minutes)
+- Impact: Post never publishes; no retry mechanism; user must manually re-attempt
+- Workaround: Lower challenge solving timeout or ensure LM Studio is responsive
+- Fix approach: Add exponential backoff with per-attempt timeout reduction; implement verification retry with new challenge; cache solved challenges
+
+**Memory Embeddings Out-of-Sync:**
+- Symptoms: Memory search returns low-quality results; embeddings vector dimension mismatches
+- Files: `server/services/memory.js` (lines 88-95), `server/services/memoryEmbeddings.js`
+- Trigger: Provider changed without regenerating all embeddings; embedding config updated mid-operation
+- Impact: New memories use correct dimension, old ones don't; BM25 fallback masks the issue
+- Fix approach: Add migration tool to regenerate embeddings on provider change; validate dimension consistency on load; batch re-embed on startup
+
+**Moltbook API Verification State Not Persisted:**
+- Symptoms: Successfully verified posts lose verification state on restart
+- Files: `server/integrations/moltbook/api.js` (line 59: `data.verification_solved = true`)
+- Trigger: State held in-memory only; not written to persistent queue file
+- Impact: Post verification succeeds but isn't recorded; re-attempts verification on next run
+- Fix approach: Persist verification_solved flag in post queue; check flag before re-verifying
+
+## Security Considerations
+
+**Challenge Solver AI Injection Risk:**
+- Risk: User-controlled task descriptions flow into LLM prompt for challenge solving
+- Files: `server/integrations/moltbook/challengeSolver.js` (lines 35-40)
+- Current mitigation: None; prompt is user-controlled via task.metadata.context
+- Recommendations: Sanitize challenge text before passing to LLM; add prompt injection detection; use structured format (JSON) instead of free-form text
+
+**Command Security Allowlist Not Enforced in All Paths:**
+- Risk: Some services may bypass `server/lib/commandSecurity.js` validation
+- Files: `server/lib/commandSecurity.js`, various services executing shell commands
+- Current mitigation: Primary routes validated; integrations (Moltbook/world APIs) may spawn processes without checks
+- Recommendations: Audit all `exec`, `execFile`, `spawn` calls; centralize command execution with mandatory allowlist check
+
+**Plaintext Credential Storage in Provider Configuration:**
+- Risk: API keys, tokens, and credentials stored in `data/providers.json` as plaintext
+- Files: `server/data/providers.json`
+- Current mitigation: File permissions (644 by default); deployed behind Tailscale but accessible if machine compromised
+- Recommendations: Implement encryption-at-rest for sensitive provider fields; use environment variables for critical credentials; rotate provider secrets regularly
+
+**WebSocket Events Broadcast Without Sanitization on All Paths:**
+- Risk: Error context emitted via Socket.IO may contain sensitive data
+- Files: `server/lib/errorHandler.js` (lines 110-130 implements sanitization)
+- Current mitigation: Context sanitization exists in errorHandler
+- Recommendations: Audit all `cosEvents.emit()` and `io.emit()` calls to ensure no PII/credentials escape; add audit logging for security-relevant events
+
+## Performance Bottlenecks
+
+**Agent Index Loaded Into Memory:**
+- Problem: Agent index (Map of agentId → date-bucket) requires full file read/parse on each access
+- Files: `server/services/cos.js` (lines 83-100)
+- Cause: Lazy-load pattern reads entire INDEX_FILE on first access; no caching invalidation on new agents
+- Current state: Index is ~50KB (described as avoiding 16MB full cache), cached in-memory after load
+- Improvement path: Use persistent cache with file-watch invalidation; consider LRU cache for large deployments; implement background index updates
+
+**Memory Search with Dual-Path Fallback:**
+- Problem: Every memory search tries vector embedding first, then falls back to BM25 if embeddings unavailable
+- Files: `server/services/memory.js` (multiple search functions with fallback logic)
+- Cause: Embedding provider availability is external dependency; BM25 adds latency
+- Improvement path: Cache search index to disk; pre-compute BM25 on memory upsert; parallelize embedding availability check
+
+**CoS State Loaded Synchronously on Every Daemon Cycle:**
+- Problem: Full state.json read on each task cycle without incremental updates
+- Files: `server/services/cos.js` (state loading in main loop)
+- Cause: No state subscription/change tracking; daemon re-reads full file repeatedly
+- Improvement path: Implement state change stream; use file watch or atomic updates-only; consider in-memory state with periodic flush
+
+**History File Grows Unbounded:**
+- Problem: `data/history.json` accumulates all-time execution history
+- Files: Various services append to history without truncation
+- Current state: Unknown size; no pruning mechanism observed
+- Improvement path: Implement rolling window (keep last N entries or last 30 days); archive old history; use JSONL with streaming reads
+
+**DevTools Page Re-renders All Components on State Change:**
+- Problem: Large tabbed interface in DevTools.jsx (2758 LOC) may cause full re-renders
+- Files: `client/src/pages/DevTools.jsx`
+- Cause: Centralized state management; no component-level memoization observed
+- Improvement path: Split tabs into separate components; implement React.memo; use context selectors; lazy-load inactive tabs
+
+## Fragile Areas
+
+**SubAgent Spawner Task Classification:**
+- Files: `server/services/subAgentSpawner.js` (lines 49-62: extractTaskTypeKey, 72-112: detectSkillTemplate)
+- Why fragile: Task type detection relies on string matching in description; brittle pattern matching for skill templates (e.g., "[self-improvement]" marker must be exact)
+- Safe modification: Add regression tests for new task types before changing matchers; implement fuzzy matching for skill detection; add logging for unmatched tasks
+- Test coverage: `subAgentSpawner.test.js` exists; coverage gaps on skill detection and edge cases
+
+**Moltbook Integration Rate Limiting:**
+- Files: `server/integrations/moltbook/rateLimits.js`, `server/integrations/moltbook/api.js`
+- Why fragile: External rate limits (unknown specs for Moltbook API) not enforced; API responses may contain throttle headers not currently parsed
+- Safe modification: Add response header parsing for `Retry-After`, `X-RateLimit-*`; log actual rate limit responses; implement adaptive backoff
+- Test coverage: No tests for rate limit edge cases
+
+**Task Watcher File Monitoring:**
+- Files: `server/services/taskWatcher.js`
+- Why fragile: Depends on reliable file system watch events; TASKS.md changes may be missed if fs.watch is unreliable on the system
+- Safe modification: Add poll-based fallback; implement CRC hash validation; test on target OS
+- Test coverage: Unknown; watch behavior is notoriously platform-dependent
+
+**Provider Status Fallback Chain:**
+- Files: `server/services/providerStatus.js` (line 20: defaultFallbackPriority)
+- Why fragile: Hard-coded fallback list may not match available providers; if all providers in chain fail, no fallback defined
+- Safe modification: Generate fallback chain dynamically based on available providers; add sentinel provider (console-based); test with single provider available
+- Test coverage: No tests for fallback chain exhaustion
+
+## Scaling Limits
+
+**Single State Machine for All Agent Executions:**
+- Current capacity: Unknown; depends on PM2 process limits and concurrent CoS runner instances
+- Limit: Event-driven architecture may bottleneck if many agents spawn simultaneously
+- Scaling path: Implement execution lanes/queues with configurable concurrency; separate spawner process; use work queue (Redis-like) for agent scheduling
+
+**Date-Bucket Directory Structure for Agents:**
+- Current capacity: One directory per day; subdirectories per agent
+- Limit: File system readdir() scales linearly with directory size; millions of agents across months will be slow
+- Scaling path: Implement multi-level bucketing (YYYY/MM/DD or by agent hash); consider flat file database (SQLite) for agent metadata
+
+**In-Memory Index for All Memories:**
+- Current capacity: Unknown; embeddings cache can grow to MB for large memory databases
+- Limit: 10,000 max memories configured; embeddings vector (768 dimension) = ~3KB per memory ≈ 30MB max
+- Scaling path: Implement lazy-loading per category; use disk-backed vector DB (Milvus, Qdrant); implement memory consolidation/pruning
+
+**WebSocket Event Broadcasting to All Clients:**
+- Current capacity: Unknown; `io.emit()` broadcasts to all connected clients
+- Limit: Many clients + large log events = saturated network
+- Scaling path: Implement rooms/namespaces per dashboard view; filter events client-side; add event sampling for high-frequency logs
+
+## Dependencies at Risk
+
+**portos-ai-toolkit ^0.5.0:**
+- Risk: Non-breaking version; if toolkit API changes (e.g., provider field structure), PortOS may break without major version bump
+- Impact: Provider configuration could become incompatible; sub-agent spawning could fail if toolkit's model selection changes
+- Migration plan: Pin to specific version (0.5.0) until ready to test 0.6.x; implement compatibility layer for provider config; test with toolkit updates before deploying
+
+**PM2 ^5.4.3:**
+- Risk: Node-based process manager; process spawning reliability depends on PM2 internals; ECMAScript module support was recently added
+- Impact: If PM2 has bugs with ESM modules, app lifecycle management breaks; agent processes may not restart correctly
+- Migration plan: Monitor PM2 changelog; test process recovery scenarios regularly; have fallback (systemd/Docker) ready
+
+**Node-PTY ^1.2.0-beta.10:**
+- Risk: Beta version with ongoing development; PTY handling is low-level and platform-specific
+- Impact: Shell command execution may fail or hang; character encoding issues in CLI output; terminal resize events may be lost
+- Migration plan: Monitor for stable release; implement timeout/cancellation for PTY commands; test on target OS before updating
+
+**Zod ^3.24.1:**
+- Risk: While stable, no major concerns; however, validation schemas scattered across `server/lib/validation.js` and route files
+- Impact: Schema changes require updates in multiple places; potential inconsistency
+- Migration plan: Consider centralized schema registry; implement schema versioning
+
+## Missing Critical Features
+
+**No Persistent Queue for Failed Tasks:**
+- Problem: If CoS daemon crashes mid-task, in-progress agents may be lost or orphaned
+- Blocks: Reliable autonomous job execution; task recovery after outages
+- Fix approach: Implement persistent task queue (file-based or Redis); implement checkpoint/resume for agents; track agent lineage
+
+**No Data Validation on Load (JSON Files):**
+- Problem: Corrupted state.json, embeddings.json, or index.json can crash services
+- Blocks: Reliable startup after unclean shutdown
+- Fix approach: Implement Zod schema validation on all file loads; add recovery/rollback for corrupted files; implement backup rotation
+
+**No Audit Logging for Critical Operations:**
+- Problem: No record of who triggered what, when, or why (important for autonomous system)
+- Blocks: Debugging issues; security investigation; accountability
+- Fix approach: Implement audit log to `data/cos/audit.jsonl`; log all task creations, agent spawns, provider changes, memory mutations; implement retention policy
+
+**No Graceful Degradation for Missing Providers:**
+- Problem: If embedding provider (LM Studio) is offline, all memory operations hang or fail
+- Blocks: Resilience to infrastructure changes; usability during provider maintenance
+- Fix approach: Add provider health checks; implement memory-only mode without embeddings; queue embeddings until provider recovers
+
+**No Rate Limiting on Sub-Agent Spawning:**
+- Problem: Rapid task creation could spawn unbounded agents, exhausting system resources
+- Blocks: Resource safety; preventing runaway CoS daemon
+- Fix approach: Implement execution lanes with configurable limits; add task queue with backpressure; expose limits in settings
+
+## Test Coverage Gaps
+
+**Critical Services Without Tests:**
+- Files: `server/services/cos.js` (no dedicated test file; core daemon logic untested)
+- What's not tested: Daemon startup/shutdown cycles, state persistence, agent spawning coordination, error recovery
+- Risk: Daemon bugs can cause data loss or orphaned processes; hard to refactor safely
+- Priority: High
+
+**File System Operations Not Tested:**
+- Files: `server/services/cos.js`, `server/lib/fileUtils.js`
+- What's not tested: Atomic write failures, concurrent file access, corruption recovery, migration edge cases
+- Risk: State corruption under load or after crashes
+- Priority: High
+
+**External Integration Failures:**
+- Files: `server/integrations/moltbook/` and `server/integrations/moltworld/`
+- What's not tested: Rate limit exhaustion, network timeouts, malformed API responses, challenge solving edge cases
+- Risk: Silent failures in autonomous posting; posts get stuck in unknown states
+- Priority: Medium
+
+**Provider Fallback Chain:**
+- Files: `server/services/providerStatus.js`, `server/services/subAgentSpawner.js`
+- What's not tested: All providers in fallback chain unavailable, provider switching mid-execution, model availability edge cases
+- Risk: Sub-agents fail with unclear errors; no model available to escalate to
+- Priority: Medium
+
+**Memory Search Path with Embeddings Unavailable:**
+- Files: `server/services/memory.js`, `server/services/memoryBM25.js`
+- What's not tested: Embedding provider offline, partial embeddings available (some memories have vectors, some don't), vector dimension mismatch
+- Risk: Memory search returns inconsistent results or crashes
+- Priority: Medium
+
+**Client WebSocket Reconnection:**
+- Files: `client/src/services/socket.js`
+- What's not tested: Rapid reconnect/disconnect cycles, message loss during disconnection, stale state after reconnect
+- Risk: UI out of sync with server; lost notifications
+- Priority: Low
+
+---
+
+*Concerns audit: 2026-02-26*
diff --git a/.planning/codebase/CONVENTIONS.md b/.planning/codebase/CONVENTIONS.md
new file mode 100644
index 0000000000..23b12a5920
--- /dev/null
+++ b/.planning/codebase/CONVENTIONS.md
@@ -0,0 +1,249 @@
+# Coding Conventions
+
+**Analysis Date:** 2026-02-26
+
+## Naming Patterns
+
+**Files:**
+- Kebab-case for all files: `apps.js`, `errorHandler.js`, `asyncMutex.js`
+- Test files: `{name}.test.js` or `{name}.spec.js` (e.g., `validation.test.js`, `apps.test.js`)
+- Integration tests: `{name}.integration.test.js` (e.g., `visionTest.integration.test.js`)
+- Route files grouped by domain: `routes/apps.js`, `routes/health.js`, `routes/cos.js`
+- Service files grouped by domain: `services/apps.js`, `services/pm2.js`, `services/history.js`
+- Library/utility files in `lib/`: `lib/validation.js`, `lib/errorHandler.js`, `lib/logger.js`
+- React components: PascalCase with `.jsx` extension: `Layout.jsx`, `Logo.jsx`, `NotificationDropdown.jsx`
+
+**Functions:**
+- camelCase for all functions: `asyncHandler`, `validateRequest`, `normalizeError`, `getAppById`, `createApp`
+- Prefix boolean functions with `is` or `has` where applicable: `existsSync`, `hasLength`
+- Event handlers prefixed with appropriate verb: `handleError`, `handleRecoveryRequested`, `handleCriticalError`
+
+**Variables:**
+- camelCase for all variables: `pm2Home`, `statusValues`, `overallStatus`, `mockApps`, `mockPm2Processes`
+- Constant-like data structures in camelCase (not SCREAMING_SNAKE_CASE): `PORTOS_APP_ID`, `APPS_FILE`, `DATA_DIR`, `API_BASE`
+- Private/internal variables can use underscore prefix: `_internal`
+- Event emitter instances: `appsEvents`, `errorEvents`, `cosEvents`
+
+**Types:**
+- Zod schemas use descriptive names ending with `Schema`: `appSchema`, `processSchema`, `providerSchema`, `agentPersonalitySchema`, `platformAccountSchema`
+- Partial update schemas use naming pattern: `{type}UpdateSchema` (e.g., `appUpdateSchema`)
+- Enum schemas follow pattern: `{type}TypeSchema` (e.g., `personalityStyleSchema`, `platformTypeSchema`)
+
+## Code Style
+
+**Formatting:**
+- No explicit ESLint or Prettier config found
+- ES Module syntax (`import`/`export`) required in all files (`"type": "module"` in package.json)
+- 2-space indentation (observed in codebase)
+- No semicolons suppressed (semicolons present throughout)
+
+**Linting:**
+- No ESLint configuration detected
+- Code relies on natural JavaScript conventions
+
+## Import Organization
+
+**Order:**
+1. Node.js built-in modules: `import { Router } from 'express'`, `import { spawn } from 'child_process'`, `import { EventEmitter } from 'events'`
+2. Third-party packages: `import express from 'express'`, `import { z } from 'zod'`, `import toast from 'react-hot-toast'`
+3. Local modules (relative imports): `import * as appsService from '../services/apps.js'`, `import { validateRequest } from '../lib/validation.js'`
+4. Local specific imports after wildcard imports
+
+**Path Aliases:**
+- No path aliases configured (uses relative paths: `../services/`, `../lib/`, `./components/`)
+- Server-side: Uses consistent relative path depth from routes/services to lib
+- Client-side: Uses relative imports from services, hooks, components directories
+
+## Error Handling
+
+**Patterns:**
+- No try/catch blocks (per CLAUDE.md conventions) — errors bubble to centralized middleware
+- Async route handlers wrapped with `asyncHandler()` middleware defined in `errorHandler.js`
+- `ServerError` class used for structured error creation with metadata
+- `normalizeError()` function converts any error type to `ServerError` for consistency
+- HTTP status codes map to error codes: `404 → NOT_FOUND`, `400 → BAD_REQUEST`, `422 → VALIDATION_ERROR`
+- Error context object attached to errors for additional debugging info: `{ context: { resource: 'user' } }`
+- Errors emit Socket.IO events for client notification (see `emitErrorEvent()`)
+- `PLATFORM_UNAVAILABLE` errors treated as warnings rather than critical errors
+
+Example from `server/routes/apps.js`:
+```javascript
+const loadApp = asyncHandler(async (req, res, next) => {
+ const app = await appsService.getAppById(req.params.id);
+ if (!app) {
+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ req.loadedApp = app;
+ next();
+});
+```
+
+## Logging
+
+**Framework:** `console` (no external logging library)
+
+**Patterns:**
+- Single-line logging with emoji prefixes (per CLAUDE.md conventions)
+- Never log full JSON blobs or arrays
+- Use string interpolation for values
+- Logger utility functions in `server/lib/logger.js`:
+ - `startup()` → 🚀 (initialization messages)
+ - `process()` → 📜 (operation progress)
+ - `error()` → ❌ (errors to console.error)
+ - `success()` → ✅ (successful operations)
+ - `config()` → 🔧 (configuration changes)
+ - `feature()` → 🎉 (new features)
+ - `bug()` → 🐛 (bug detection)
+ - `info()` → ℹ️ (informational messages)
+ - `warning()` → ⚠️ (deprecations, warnings to console.warn)
+ - `debug()` → 🔍 (debug traces)
+
+Example patterns:
+```javascript
+console.log(`🚀 Server started on port ${PORT}`);
+console.log(`📜 Processing ${items.length} items`);
+console.error(`❌ Failed to connect: ${err.message}`);
+```
+
+## Comments
+
+**When to Comment:**
+- JSDoc/TSDoc comments on exported functions: `/** * Utility description * @param {type} name - description */`
+- Explain "why" not "what" for complex logic
+- Comments above sections: `// =============================================================================`
+- Inline comments for non-obvious logic, but sparingly
+
+Example from `server/lib/validation.js`:
+```javascript
+// =============================================================================
+// AGENT PERSONALITY SCHEMAS
+// =============================================================================
+
+// Agent personality style
+export const personalityStyleSchema = z.enum([
+ 'professional',
+ 'casual',
+ 'witty',
+ 'academic',
+ 'creative'
+]);
+```
+
+## Function Design
+
+**Size:** Functions are generally focused on single responsibility, ranging 5-40 lines
+
+**Parameters:**
+- Destructured parameters for objects: `asyncHandler(async (req, res, next) => { ... })`
+- Optional options objects as last parameter: `readJSONFile(APPS_FILE, { apps: {} })`
+- Middleware pattern for Express routes: `(req, res, next) => { ... }`
+
+**Return Values:**
+- Handlers return void (Express middleware)
+- Services return Promises (async functions)
+- Utility functions return data or Promise<data>
+- Schema validation returns result object: `{ success: boolean, data?: T, errors?: Array }`
+
+Example from `server/routes/apps.js`:
+```javascript
+router.get('/', asyncHandler(async (req, res) => {
+ const apps = await appsService.getAllApps();
+ // ... enrichment logic ...
+ res.json(enriched);
+}));
+```
+
+## Module Design
+
+**Exports:**
+- Named exports for most utilities and services: `export const getAppById = async (id) => { ... }`
+- Default exports rarely used
+- Service modules export both data and functions: `export const PORTOS_APP_ID = 'portos-default'`, `export async function getAllApps() { ... }`
+
+**Barrel Files:**
+- Minimal use of barrel files; prefer specific imports
+- Routes/services imported with wildcard: `import * as appsService from '../services/apps.js'`
+
+## Async Patterns
+
+**Promise handling:**
+- Async/await preferred over .then() chains
+- Error handling via asyncHandler wrapper, not try/catch
+- Promise.all() for concurrent operations with settled promises when appropriate
+
+Example from `server/routes/apps.js`:
+```javascript
+const enriched = await Promise.all(apps.map(async (app) => {
+ const pm2Home = app.pm2Home || null;
+ const pm2Map = pm2Maps.get(pm2Home) || new Map();
+ // ... processing logic ...
+ return { ...app, pm2Status: statuses, overallStatus };
+}));
+```
+
+## React/Client Conventions
+
+**Hooks:**
+- Functional components with hooks only (no classes)
+- Custom hooks file naming: `use{Purpose}.js` (e.g., `useErrorNotifications.js`, `useNotifications.js`)
+- Hooks return object with methods: `return { requestAutoFix }`
+
+**Component Organization:**
+- Components in `client/src/components/`
+- Pages in `client/src/pages/` (route-based)
+- Services in `client/src/services/` (API and WebSocket)
+- Custom hooks in `client/src/hooks/`
+- Utilities in `client/src/utils/`
+
+**Navigation:**
+- Sidebar nav items in `Layout.jsx` organized alphabetically (after Dashboard + CyberCity section and separator)
+- URL params for tabbed pages instead of local state: `/devtools/history` not `/devtools` with internal state
+- All views must be linkable routes
+
+**UI Patterns:**
+- No `window.alert()` or `window.confirm()` — use toast notifications via `react-hot-toast`
+- Toast notifications with emoji icons: `toast()`, `toast.error()`, `toast.success()`
+- Example: `toast('Recovery agent dispatched', { icon: '🔧' })`
+
+Example hook from `client/src/hooks/useErrorNotifications.js`:
+```javascript
+export function useErrorNotifications() {
+ const requestAutoFix = useCallback((errorCode, context) => {
+ socket.emit('error:recover', { code: errorCode, context });
+ toast('Recovery agent dispatched', { icon: '🔧' });
+ }, []);
+
+ useEffect(() => {
+ socket.emit('errors:subscribe');
+ // ... handlers setup ...
+ return () => {
+ socket.off('error:occurred', handleError);
+ };
+ }, []);
+
+ return { requestAutoFix };
+}
+```
+
+## Data Validation
+
+**Zod Schemas:**
+- All route inputs validated via Zod schemas in `server/lib/validation.js`
+- `validateRequest(schema, data)` wrapper function normalizes validation results
+- Validation result format: `{ success: boolean, data?: T, errors?: Array<{ path: string, message: string }> }`
+- Schemas define defaults, optional fields, and constraints
+
+Example:
+```javascript
+export const appSchema = z.object({
+ name: z.string().min(1).max(100),
+ repoPath: z.string().min(1),
+ type: z.string().default('express'),
+ uiPort: z.number().int().min(1).max(65535).nullable().optional(),
+ processes: z.array(processSchema).optional()
+});
+```
+
+---
+
+*Convention analysis: 2026-02-26*
diff --git a/.planning/codebase/INTEGRATIONS.md b/.planning/codebase/INTEGRATIONS.md
new file mode 100644
index 0000000000..3b73ce9b3f
--- /dev/null
+++ b/.planning/codebase/INTEGRATIONS.md
@@ -0,0 +1,243 @@
+# External Integrations
+
+**Analysis Date:** 2026-02-26
+
+## APIs & External Services
+
+**Moltworld (Voxel World):**
+- Purpose: AI agent movement, building, communication, and SIM token earning
+- Integration: `server/integrations/moltworld/`
+- SDK/Client: Custom client class `MoltworldClient` with stateful wrapper
+- API Base: https://moltworld.io
+- Auth: API key stored in platform accounts config
+- Methods:
+ - `joinWorld()` - Agent entry point
+ - `think()` - Agent thoughts/communication
+ - `build()` - Structure creation
+ - `getProfile()`, `updateProfile()` - Agent identity
+ - `getBalance()` - SIM token balance
+- Rate Limits: Enforced per agent (checked before requests)
+- Reference: `server/integrations/moltworld/rateLimits.js`
+
+**Moltbook (AI Agent Social Platform):**
+- Purpose: AI agent social networking, posts, comments, voting, following
+- Integration: `server/integrations/moltbook/`
+- SDK/Client: Custom client class `MoltbookClient` with stateful wrapper
+- API Base: https://www.moltbook.com/api/v1
+- Auth: API key required for all requests
+- Methods:
+ - Posts: `createPost()`, `getFeed()`, `getPost()`, `deletePost()`
+ - Comments: `createComment()`, `replyToComment()`, `getComments()`
+ - Voting: `upvote()`, `downvote()`, `upvoteComment()`
+ - Social: `follow()`, `unfollow()`, `getFollowers()`, `getFollowing()`
+ - Account: `getStatus()`, `getProfile()`, `updateProfile()`, `heartbeat()`
+ - Submolts: `getSubmolts()`, `getSubmolt()`
+- Rate Limits: Enforced per API key (checked before requests)
+- Reference: `server/integrations/moltbook/rateLimits.js`
+- Account Suspension Detection: `isAccountSuspended()` checks for locked accounts
+
+**JIRA:**
+- Purpose: Task/issue tracking, multi-instance support
+- Service: `server/services/jira.js`
+- HTTP Client: axios with HTTPS certificate handling
+- Auth: Personal Access Token (PAT) per instance
+ - Configured in: `data/jira.json`
+ - Env var for token: Per-instance basis (no global var)
+- Multi-Instance: Each JIRA instance has:
+ - `id`, `name`, `baseUrl`, `email`, `apiToken`
+ - `createdAt`, `updatedAt`, `tokenUpdatedAt` timestamps
+- Route: `server/routes/jira.js` handles HTTP requests
+- Features: Create/read/update issues, search, custom fields support
+
+**LMStudio (Local LLM):**
+- Purpose: Local AI inference server alternative
+- Configuration: Accessible via localhost endpoints
+- Route: `server/routes/lmstudio.js`
+- Protocol: HTTP API (similar to OpenAI-compatible)
+- Default: `http://localhost:1234/v1` (for scaffolding templates)
+
+**Ollama (Local LLM):**
+- Purpose: Local AI model runner
+- Default Endpoint: `http://localhost:11434/v1` (in scaffolding templates)
+- Used as fallback local provider option
+
+## Data Storage
+
+**Databases:**
+- Not used; all data persists to JSON files in `./data/`
+
+**File Storage:**
+- Local filesystem only
+- Key directories:
+ - `data/screenshots/` - Screenshots captured by browser or agents
+ - `data/uploads/` - User uploads and attachments
+ - `data/browser-profile/` - Chrome user data directory for persistent sessions
+- Routes:
+ - `server/routes/screenshots.js` - Screenshot management
+ - `server/routes/uploads.js` - Upload handling
+ - `server/routes/attachments.js` - Attachment linking
+
+**Caching:**
+- None detected; minimal in-memory caching for browser config and AI toolkit
+
+## Authentication & Identity
+
+**Auth Provider:**
+- Custom/None for external - PortOS is single-user internal tool
+- Per-provider credentials stored in `data/providers.json` (from AI Toolkit)
+- Per-Moltbook account: API keys in platform accounts
+- Per-Moltworld account: API keys in platform accounts
+- Per-JIRA instance: Personal Access Tokens in `data/jira.json`
+
+**Platform Accounts:**
+- Route: `server/routes/platformAccounts.js`
+- Stores credentials for third-party platforms (Moltbook, Moltworld, etc.)
+- Example: `data/agents/{agentId}/accounts.json`
+
+## Monitoring & Observability
+
+**Error Tracking:**
+- None detected (no external service)
+- Local error events via `server/lib/errorHandler.js`
+- Error broadcast via Socket.IO to client: `errorEvents.emit('error', {...})`
+
+**Logs:**
+- Console.log with emoji prefixes (e.g., `🚀`, `❌`, `📜`)
+- Single-line logging pattern (no JSON blobs)
+- PM2 manages log persistence:
+ - Log file format: `YYYY-MM-DDTHH:mm:ss.SSS[Z]` (UTC)
+ - Output via `pm2 logs` command
+ - Configured in `ecosystem.config.cjs`
+
+## CI/CD & Deployment
+
+**Hosting:**
+- Local machine (dev) / Private network behind Tailscale VPN
+- Not exposed to public internet
+- Deployment: PM2 process manager (`ecosystem.config.cjs`)
+
+**CI Pipeline:**
+- GitHub Actions workflows in `.github/workflows/`
+- Release process: Merge `dev` → `main` triggers:
+ - Version bump via `npm version` (manual in commit message)
+ - Changelog substitution (v0.10.x → actual version)
+ - GitHub release creation
+ - Archive changelog with version number
+
+**Process Management:**
+- PM2 orchestrates 6 processes:
+ - `portos-server` (5554) - Express API
+ - `portos-cos` (5558) - Chief of Staff agent runner
+ - `portos-ui` (5555) - Vite dev server
+ - `portos-autofixer` (5559) - Error recovery
+ - `portos-autofixer-ui` (5560) - Autofixer UI
+ - `portos-browser` (5556/5557) - Chrome CDP
+
+## AI Provider Integration
+
+**Framework:**
+- portos-ai-toolkit (separate npm module `^0.5.0`)
+- Imported: `import { createAIToolkit } from 'portos-ai-toolkit/server'`
+
+**Provider Management:**
+- Route: `server/routes/providers.js` - Lists/tests/creates providers
+- Service: `server/services/providers.js` - Toolkit wrapper
+- Config: `data/providers.json` - Provider definitions
+ - Fields: id, name, type, baseUrl, apiKey, model, tier, fallbackProvider, lightModel, etc.
+ - Managed by toolkit's `createProvider()` and `updateProvider()`
+
+**Run Execution:**
+- Route: `server/routes/runs.js` - Run history and execution
+- Service: `server/services/runner.js` - Toolkit wrapper with CLI execution fix
+ - Fixed DEP0190 security warning by removing `shell: true`
+- Data: `data/runs/` - Run results and metadata
+- Lifecycle hooks:
+ - `onRunCreated` - Records session usage
+ - `onRunCompleted` - Tracks token usage
+ - `onRunFailed` - Emits error event with context
+
+**Prompt Templates:**
+- Route: `server/routes/prompts.js` - Prompt management
+- Service: `server/services/promptService.js` - Toolkit wrapper
+- Data: `data/prompts/` - Saved templates
+- Features: Template versioning, variable substitution
+
+**Provider Status Monitoring:**
+- Service: `server/services/providerStatus.js`
+- Health checks for configured providers
+- Emits status events via `providerStatusEvents`
+
+## Browser & Automation
+
+**Chrome DevTools Protocol (CDP):**
+- Service: `server/services/browserService.js`
+- Process: `browser/server.js` (separate PM2 process)
+- Config: `data/browser-config.json`
+- Settings:
+ - CDP Port: 5556 (default)
+ - CDP Host: 127.0.0.1 (localhost only, security)
+ - Health Port: 5557
+ - Headless: true (default)
+ - User Data: `data/browser-profile/` (persistent cookies/sessions)
+- HTTP health check: GET `/json/version` on health port
+- Feature: Persistent Chrome profile for session maintenance
+
+**Terminal Emulation:**
+- node-pty for shell/terminal integration
+- Routes: `server/routes/history.js` - Command history
+- Real-time terminal via Socket.IO
+
+## Webhooks & Callbacks
+
+**Incoming:**
+- Socket.IO subscriptions (client subscribes to server events)
+- Webhook channels: detect, logs, errors, notifications, agents, cosmos, instances, brain
+
+**Outgoing:**
+- Socket.IO emissions to subscribed clients
+- No webhook API for external services detected
+- Browser events emitted locally: `browserEvents.emit()`
+
+## Automation & Scheduling
+
+**Automation Scheduler:**
+- Service: `server/services/automationScheduler.js`
+- Route: `server/routes/automationSchedules.js`
+- Triggers: Time-based schedules for agent actions
+- Agent Action Execution: `server/services/agentActionExecutor.js`
+
+**Brain Scheduler:**
+- Service: `server/services/brainScheduler.js`
+- Features: Daily digests, weekly reviews
+- Started via `startBrainScheduler()`
+
+**Task Learning:**
+- Service: `server/services/taskLearning.js`
+- Tracks agent task completions for learning
+
+## Environment Configuration
+
+**Required Environment Variables:**
+- `NODE_ENV`: development/production
+- `PORT`: 5554 (API server), configurable
+- `HOST`: 0.0.0.0 (default) or specific IP
+- `TZ`: UTC (forced in ecosystem.config.cjs)
+- `CDP_PORT`, `CDP_HOST`: Browser CDP settings
+- `VITE_API_HOST`: Client Vite config for API proxy (localhost default)
+
+**Secrets Location:**
+- AI Provider API keys: `data/providers.json` (managed by toolkit)
+- JIRA PATs: `data/jira.json`
+- Moltbook/Moltworld API keys: Per-platform-account config
+- Browser config: `data/browser-config.json`
+- No `.env` files used; all config via JSON files in `data/`
+
+**Note on Security Model:**
+- PortOS is intentionally designed for single-user, internal use on private network
+- No authentication, CORS restrictions, rate limiting, or HTTPS
+- Deployment context: Behind Tailscale VPN, not internet-exposed
+- Security handled at network level, not application level
+
+---
+
+*Integration audit: 2026-02-26*
diff --git a/.planning/codebase/STACK.md b/.planning/codebase/STACK.md
new file mode 100644
index 0000000000..fa51fcbe45
--- /dev/null
+++ b/.planning/codebase/STACK.md
@@ -0,0 +1,156 @@
+# Technology Stack
+
+**Analysis Date:** 2026-02-26
+
+## Languages
+
+**Primary:**
+- JavaScript (ES6 modules) - Across all server/client code
+- JSX - React components in client code (`client/src/**/*.jsx`)
+
+## Runtime
+
+**Environment:**
+- Node.js v22.21.1 (development; actual runtime flexible)
+- npm v10.9.4
+
+**Package Manager:**
+- npm 10.9.4
+- Lockfiles: `package-lock.json`, `server/package-lock.json`, `client/package-lock.json` (committed)
+
+## Frameworks
+
+**Backend:**
+- Express.js ^4.21.2 - HTTP server and routing
+- Socket.IO ^4.8.3 - Real-time bidirectional communication
+- node-pty ^1.2.0-beta.10 - Terminal emulation and shell integration
+- axios ^1.7.9 - HTTP client for external APIs
+- ws ^8.18.0 - WebSocket library
+- Zod ^3.24.1 - TypeScript-first schema validation
+
+**Frontend:**
+- React ^18.3.1 - UI framework
+- React Router DOM ^7.1.1 - Client-side routing
+- Vite ^6.0.6 - Build tool and dev server
+- Tailwind CSS ^3.4.17 - Utility-first CSS framework
+- PostCSS ^8.4.49 - CSS transformation
+- Autoprefixer ^10.4.20 - CSS vendor prefixes
+
+**3D Graphics & Terminal:**
+- Three.js ^0.182.0 - WebGL 3D graphics
+- @react-three/fiber ^8.18.0 - React renderer for Three.js
+- @react-three/drei ^9.122.0 - Useful helpers for React Three
+- @xterm/xterm ^6.0.0 - Terminal emulator (web)
+- @xterm/addon-fit ^0.11.0 - XTerm fit addon
+- @xterm/addon-web-links ^0.12.0 - XTerm web links addon
+
+**UI Components & Interaction:**
+- react-hot-toast ^2.6.0 - Toast notification system
+- lucide-react ^0.562.0 - Icon library
+- react-markdown ^10.1.0 - Markdown rendering
+- recharts ^3.7.0 - React charting library
+- geist ^1.7.0 - UI component library
+- @dnd-kit/core ^6.3.1 - Drag-and-drop primitives
+- @dnd-kit/sortable ^10.0.0 - Sortable drag-and-drop
+- @dnd-kit/utilities ^3.2.2 - Drag-and-drop utilities
+- fflate ^0.8.2 - JavaScript deflate compression
+- socket.io-client ^4.8.3 - WebSocket client
+
+**Development & Build:**
+- Vite ^6.0.6 - Module bundler and dev server
+- @vitejs/plugin-react ^4.3.4 - React plugin for Vite
+- vitest ^4.0.16 - Unit test framework
+- @vitest/coverage-v8 ^4.0.16 - Test coverage reporting
+- supertest ^7.1.4 - HTTP assertion library
+
+**Process Management:**
+- PM2 ^5.4.3 - Application process manager (root and server deps)
+
+**Utilities:**
+- uuid ^11.0.3 - UUID generation
+- cors ^2.8.5 - CORS middleware
+
+## Key Dependencies
+
+**Critical for AI Integration:**
+- portos-ai-toolkit ^0.5.0 - Separate npm module for AI provider management, run tracking, and prompt templates
+ - Located at `../portos-ai-toolkit` in development
+ - Manages provider configuration (models, tiers, fallbacks)
+ - Handles provider lifecycle and CLI execution
+
+**External Service Integration:**
+- axios - HTTP client for Jira, Moltbook, Moltworld APIs
+- node-pty - Terminal spawning for shell commands and script execution
+- ws - WebSocket connections for real-time features
+
+**Validation & Error Handling:**
+- Zod - Input validation for all Express routes
+- Centralized error middleware in `server/lib/errorHandler.js`
+
+## Configuration
+
+**Environment:**
+- Process environment variables via `ecosystem.config.cjs`:
+ - `NODE_ENV`: 'development' (base)
+ - `TZ`: 'UTC' (all timestamps in UTC)
+ - `PORT`: 5554 (API), configurable per process
+ - `HOST`: '0.0.0.0' (server), '127.0.0.1' (CDP/CoS)
+
+**Build Configuration:**
+- Vite config: `client/vite.config.js` (port 5555, API proxy to 5554)
+- Tailwind config: `client/tailwind.config.js` (custom design tokens)
+- PostCSS: `client/postcss.config.js` (Tailwind + Autoprefixer)
+- Server test: `server/vitest.config.js` (30% coverage threshold)
+
+**Asset Bundling:**
+- Manual Vite chunks for vendor libraries:
+ - `vendor-react`: React, React DOM, React Router
+ - `vendor-realtime`: Socket.IO, React Hot Toast
+ - `vendor-dnd`: @dnd-kit libraries
+ - `vendor-icons`: lucide-react (largest)
+
+## Platform Requirements
+
+**Development:**
+- Node.js v22.x (tested v22.21.1)
+- npm v10.x
+- Chrome/Chromium (for browser automation via CDP)
+- Shell environment (bash/sh for command execution)
+
+**Production:**
+- Node.js runtime (same as development)
+- PM2 for process orchestration (`ecosystem.config.cjs`)
+- Chrome/Chromium (optional, for browser features)
+- File system access for JSON data persistence
+
+## Data Persistence
+
+**Storage Method:**
+- JSON files in `./data/` directory (not database)
+- Key files:
+ - `data/providers.json` - AI provider configurations
+ - `data/runs/` - AI provider runs and results
+ - `data/prompts/` - Prompt templates
+ - `data/agents/` - Agent configurations
+ - `data/jira.json` - JIRA instance configurations
+ - `data/browser-config.json` - Browser CDP settings
+ - `data/screenshots/` - Screenshots captured by agents
+ - `data/apps.json` - Detected/monitored applications
+ - `data/history.json` - Command history
+ - `data/brain/` - Memory and learning data
+ - `data/digital-twin/` - Identity and autobiography data
+
+## Port Allocation
+
+Defined in `ecosystem.config.cjs`:
+- **5554**: Express API server (core PortOS backend)
+- **5555**: Vite client dev server (React UI)
+- **5556**: Chrome CDP (browser remote debugging)
+- **5557**: Browser health check endpoint
+- **5558**: Chief of Staff (CoS) agent runner
+- **5559**: Autofixer API
+- **5560**: Autofixer UI
+
+---
+
+*Stack analysis: 2026-02-26*
diff --git a/.planning/codebase/STRUCTURE.md b/.planning/codebase/STRUCTURE.md
new file mode 100644
index 0000000000..c8ace6332b
--- /dev/null
+++ b/.planning/codebase/STRUCTURE.md
@@ -0,0 +1,280 @@
+# Codebase Structure
+
+**Analysis Date:** 2026-02-26
+
+## Directory Layout
+
+```
+PortOS/
+├── .planning/
+│ ├── codebase/ # Generated codebase analysis documents
+│ └── ...
+├── .changelog/ # Release changelogs (v0.10.x.md, etc)
+├── .github/
+│ └── workflows/ # GitHub Actions CI/CD
+├── .claude/
+│ └── commands/ # Claude Code custom commands
+├── autofixer/ # Autofixer standalone service
+│ ├── server.js # Autofixer API server
+│ └── ui.js # Autofixer UI server
+├── browser/ # Browser automation service (Playwright CDP)
+│ └── server.js # CDP proxy and health check server
+├── client/ # React/Vite frontend
+│ ├── src/
+│ │ ├── main.jsx # Vite entry point
+│ │ ├── App.jsx # Router setup and main layout
+│ │ ├── index.css # Tailwind imports
+│ │ ├── pages/ # Route pages (~20 main pages)
+│ │ ├── components/ # Reusable UI components (~140 files)
+│ │ ├── hooks/ # Custom React hooks
+│ │ ├── services/
+│ │ │ ├── api.js # HTTP client wrapper
+│ │ │ └── socket.js # Socket.IO connection singleton
+│ │ └── utils/ # Utility functions
+│ ├── public/ # Static assets (fonts, favicon)
+│ └── dist/ # Production build output
+├── data/ # Runtime JSON storage (gitignored)
+│ ├── apps.json # Registry of managed applications
+│ ├── providers.json # AI provider configurations
+│ ├── runs/ # AI run history
+│ ├── prompts/ # Prompt templates
+│ ├── cos/ # Chief of Staff agent data
+│ │ ├── memory/ # CoS memory/context
+│ │ ├── agents/ # Sub-agent instances
+│ │ ├── scripts/ # CoS script library
+│ │ ├── missions/ # CoS mission definitions
+│ │ └── reports/ # CoS execution reports
+│ ├── brain/ # Brain state (thoughts, digests, reviews)
+│ ├── digital-twin/ # Digital twin profile data
+│ ├── agents/ # Agent personalities and state
+│ ├── meatspace/ # Meatspace (IRL) tracking data
+│ └── screenshots/ # Captured screenshots
+├── data.sample/ # Sample data templates (checked in)
+│ ├── providers.json # Sample provider config
+│ ├── prompts/ # Default prompt templates
+│ ├── cos/ # Sample CoS structure
+│ └── ...
+├── docs/ # Documentation
+│ ├── PORTS.md # Port allocation guide
+│ ├── VERSIONING.md # Version management
+│ ├── features/ # Feature documentation
+│ └── media/ # Images and diagrams
+├── scripts/ # Utility scripts for setup and development
+│ ├── dev-start.js # Start PM2 with dev-specific config
+│ ├── setup-data.js # Initialize data directory
+│ ├── setup-browser.js # Configure browser environment
+│ └── setup-ghostty.js # Configure terminal
+├── server/ # Express.js backend
+│ ├── index.js # Server entry point, middleware, route mounting
+│ ├── routes/ # HTTP route handlers (~50 route files)
+│ │ ├── apps.js # App registry CRUD
+│ │ ├── agents.js # Agent process management
+│ │ ├── cos.js # Chief of Staff routes
+│ │ ├── brain.js # Brain state management
+│ │ ├── digital-twin.js # Digital twin profile
+│ │ ├── providers.js # AI provider config extension
+│ │ ├── runs.js # AI run history
+│ │ ├── prompts.js # Prompt management
+│ │ ├── health.js # System health checks
+│ │ ├── logs.js # App log streaming
+│ │ ├── git.js # Git operations
+│ │ ├── history.js # Activity history
+│ │ ├── commands.js # Shell command execution
+│ │ └── ... (30+ more)
+│ ├── services/ # Business logic (~130 files)
+│ │ ├── apps.js # App registry persistence and caching
+│ │ ├── pm2.js # PM2 CLI wrapper
+│ │ ├── agents.js # Agent lifecycle management
+│ │ ├── cos.js # Chief of Staff orchestration
+│ │ ├── brain.js # Brain state management
+│ │ ├── digital-twin.js # Digital twin operations
+│ │ ├── socket.js # Socket.IO event handlers
+│ │ ├── errorHandler.js # Socket.IO error broadcasting
+│ │ ├── autoFixer.js # Error recovery automation
+│ │ ├── providers.js # AI provider management (toolkit wrapper)
+│ │ ├── runner.js # AI CLI execution (toolkit wrapper)
+│ │ ├── history.js # Activity logging
+│ │ ├── usage.js # Usage tracking
+│ │ ├── pm2Standardizer.js # Auto-configure PM2 ecosystem files
+│ │ ├── streamingDetect.js # Detect app config from repo
+│ │ └── ... (100+ more)
+│ ├── lib/ # Shared utilities (~30 files)
+│ │ ├── validation.js # Zod schemas for all entities
+│ │ ├── errorHandler.js # ServerError class and middleware
+│ │ ├── fileUtils.js # File I/O and path constants
+│ │ ├── logger.js # Logging utilities
+│ │ ├── taskParser.js # Parse task descriptions
+│ │ ├── brainValidation.js # Brain schema validation
+│ │ ├── digitalTwinValidation.js # Digital twin schema validation
+│ │ ├── memoryValidation.js # Memory schema validation
+│ │ ├── bm25.js # BM25 search algorithm
+│ │ ├── vectorMath.js # Vector operations
+│ │ └── ... (more)
+│ ├── cos-runner/ # CoS isolated process
+│ │ └── index.js # Spawn Claude CLI agents
+│ ├── integrations/ # External platform integrations
+│ │ ├── moltworld/ # Moltworld integration
+│ │ └── moltbook/ # Moltbook integration
+│ ├── scripts/ # Standalone utility scripts
+│ │ └── ... (various data prep scripts)
+│ ├── data/ # Symlink to ../data for local references
+│ └── node_modules/
+├── shell/ # Terminal/shell customization
+│ ├── themes/ # Terminal color themes
+│ └── shaders/ # Terminal shader configs
+├── ecosystem.config.cjs # PM2 process configuration
+├── package.json # Root workspace package
+├── package-lock.json
+├── vite.config.js # Vite build config (if at root)
+└── CLAUDE.md # Developer instructions
+```
+
+## Directory Purposes
+
+**`.planning/codebase/`:**
+- Purpose: Generated analysis documents for GSD orchestrator
+- Contains: ARCHITECTURE.md, STRUCTURE.md, CONVENTIONS.md, TESTING.md, CONCERNS.md
+- Key files: None (auto-generated)
+
+**`client/src/pages/`:**
+- Purpose: Route-level page components (one per major feature)
+- Contains: Dashboard, Apps, ChiefOfStaff, Brain, DigitalTwin, DevTools, etc.
+- Key files: `Dashboard.jsx` (homepage), `Apps.jsx` (app management)
+
+**`client/src/components/`:**
+- Purpose: Reusable UI components organized by feature
+- Contains: Base components (Layout, AppTile, BrailleSpinner) + feature-specific subdirs (city/, cos/, brain/, digital-twin/, etc.)
+- Key files: `Layout.jsx` (main shell with sidebar), `AppIcon.jsx` (app icon renderer)
+
+**`client/src/hooks/`:**
+- Purpose: Custom React hooks for reusable logic
+- Contains: useErrorNotifications (toast subscription), useSocket (singleton access), useTheme, useCityData, etc.
+- Key files: `useErrorNotifications.js` (subscribes to Socket.IO error events)
+
+**`server/routes/`:**
+- Purpose: HTTP route handlers for specific features
+- Contains: CRUD operations with Zod validation, delegates to services
+- Key files: `apps.js` (150+ lines), `cos.js` (45K+ lines), `brain.js`, `agents.js`
+
+**`server/services/`:**
+- Purpose: Business logic and state management
+- Contains: File I/O, PM2 management, event publishing, domain-specific workflows
+- Key files: `apps.js` (registry + caching), `cos.js` (129K+ CoS orchestration), `pm2.js` (process control)
+
+**`server/lib/`:**
+- Purpose: Shared infrastructure and utilities
+- Contains: Zod schemas, error handling, file operations, validation logic
+- Key files: `validation.js` (14K+ agent/account/brain schemas), `errorHandler.js`, `fileUtils.js`
+
+**`server/cos-runner/`:**
+- Purpose: Isolated process for spawning long-running Claude CLI agents
+- Contains: CoS agent spawner, process lifecycle management
+- Key files: `index.js` (must not auto-restart with main server)
+
+**`data/`:**
+- Purpose: Runtime JSON storage (all app state, user data)
+- Contains: JSON files for apps, providers, runs, prompts, agents, CoS memory, brain state, etc.
+- Generated by: Services via fileUtils, AI toolkit
+
+**`data.sample/`:**
+- Purpose: Template data checked into git for bootstrapping new instances
+- Contains: Sample provider configs, prompt templates, CoS mission examples
+- Key files: `providers.json` (template AI providers)
+
+## Key File Locations
+
+**Entry Points:**
+- Server: `server/index.js` (Express setup, route mounting, Socket.IO init)
+- Client: `client/src/main.jsx` → `App.jsx` (Router setup)
+- CoS Runner: `server/cos-runner/index.js` (Isolated agent spawner)
+- PM2 Config: `ecosystem.config.cjs` (Process definitions)
+
+**Configuration:**
+- PM2: `ecosystem.config.cjs` (port allocation, env setup)
+- Vite: `client/vite.config.js` (build config)
+- Tailwind: `client/tailwind.config.js` (design tokens)
+- AI Toolkit: `server/services/providers.js` (extends toolkit config)
+
+**Core Logic:**
+- App Management: `server/services/apps.js` (registry), `server/routes/apps.js` (API)
+- PM2 Control: `server/services/pm2.js` (CLI wrapper), `routes/apps.js` (process endpoints)
+- AI Execution: `server/services/runner.js` (toolkit wrapper), `routes/runs.js` (history)
+- Error Handling: `server/lib/errorHandler.js` (ServerError + middleware), `services/socket.js` (broadcasting)
+
+**Testing:**
+- Unit Tests: Co-located with services, e.g., `services/apps.test.js`
+- Test Config: `server/package.json` defines vitest/jest commands
+- Key test files: `services/autobiography.test.js`, `services/brain.test.js`
+
+## Naming Conventions
+
+**Files:**
+- Services: camelCase, descriptive (e.g., `agentActionExecutor.js`, `automationScheduler.js`)
+- Routes: Match resource name (e.g., `apps.js`, `cos.js`)
+- Components: PascalCase, descriptive (e.g., `SystemHealthWidget.jsx`)
+- Pages: PascalCase, match route (e.g., `ChiefOfStaff.jsx`, `DigitalTwin.jsx`)
+- Utilities: camelCase (e.g., `taskParser.js`, `vectorMath.js`)
+
+**Directories:**
+- Feature directories: kebab-case (e.g., `digital-twin/`, `cos-runner/`)
+- Component categories: lowercase plural (e.g., `components/city/`, `hooks/`)
+- Data domains: kebab-case (e.g., `data/digital-twin/`, `data/brain/`)
+
+## Where to Add New Code
+
+**New Feature:**
+- Primary code: `server/services/{feature}.js` (business logic)
+- Route handler: `server/routes/{feature}.js` (API endpoints)
+- Tests: `server/services/{feature}.test.js`
+- Schemas: Add to `server/lib/validation.js` or create `server/lib/{feature}Validation.js`
+- Client: Create `client/src/pages/{Feature}.jsx` for new page
+
+**New Component/Module:**
+- Reusable components: `client/src/components/{Component}.jsx`
+- Feature-specific components: `client/src/components/{feature}/`
+- Hooks: `client/src/hooks/use{Hook}.js`
+- Services: `server/services/{service}.js` (follow existing patterns)
+
+**Utilities:**
+- Shared server utilities: `server/lib/{utility}.js`
+- Validation schemas: `server/lib/{domain}Validation.js`
+- Client utilities: `client/src/utils/{utility}.js`
+- API methods: Add to `client/src/services/api.js`
+
+## Special Directories
+
+**`data/`:**
+- Purpose: All runtime application state
+- Generated: Yes (by services at runtime)
+- Committed: No (gitignored)
+- Persistence: JSON files, watched by services for changes
+
+**`data.sample/`:**
+- Purpose: Bootstrap templates for new instances
+- Generated: No (checked in manually)
+- Committed: Yes (part of repo)
+- Usage: Copied or referenced during setup
+
+**`docs/`:**
+- Purpose: User and developer documentation
+- Key files: `PORTS.md` (port allocation), `VERSIONING.md` (release process)
+- Maintenance: Update when architecture changes
+
+**`shell/`:**
+- Purpose: Terminal environment customization
+- Contains: Theme files, shader configs
+- Used by: `setup-ghostty.js` during initialization
+
+**`autofixer/`:**
+- Purpose: Standalone microservice for error recovery
+- Contains: `server.js` (API), `ui.js` (UI server)
+- Managed by: PM2 process (separate from main server)
+
+**`browser/`:**
+- Purpose: Browser automation via Playwright CDP
+- Contains: CDP proxy server with health checks
+- Managed by: PM2 process (separate, bound to localhost only)
+
+---
+
+*Structure analysis: 2026-02-26*
diff --git a/.planning/codebase/TESTING.md b/.planning/codebase/TESTING.md
new file mode 100644
index 0000000000..b30b8dcec6
--- /dev/null
+++ b/.planning/codebase/TESTING.md
@@ -0,0 +1,522 @@
+# Testing Patterns
+
+**Analysis Date:** 2026-02-26
+
+## Test Framework
+
+**Runner:**
+- Vitest v4.0.16
+- Config: `server/vitest.config.js`
+- ES modules support (native)
+
+**Assertion Library:**
+- Vitest built-in: `expect()` from vitest
+
+**Run Commands:**
+```bash
+cd server && npm test # Run all tests (vitest run)
+cd server && npm run test:watch # Watch mode (vitest)
+cd server && npm run test:coverage # Coverage report (vitest run --coverage)
+```
+
+## Test File Organization
+
+**Location:**
+- Co-located with source code in same directory
+- Not in separate `__tests__` directory
+
+**Naming:**
+- `.test.js` suffix: `validation.test.js`, `errorHandler.test.js`, `logger.test.js`
+- Integration tests: `.integration.test.js` suffix (e.g., `visionTest.integration.test.js`)
+
+**Structure:**
+```
+server/
+├── lib/
+│ ├── validation.js
+│ └── validation.test.js # Co-located test
+├── routes/
+│ ├── apps.js
+│ └── apps.test.js # Co-located test
+└── services/
+ ├── apps.js
+ └── apps.test.js # Co-located test
+```
+
+## Test Structure
+
+**Suite Organization:**
+```javascript
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+describe('Module Name', () => {
+ describe('FeatureName', () => {
+ it('should do something specific', () => {
+ // Test implementation
+ });
+
+ it('should handle edge case', () => {
+ // Test implementation
+ });
+ });
+
+ describe('AnotherFeature', () => {
+ // More tests
+ });
+});
+```
+
+**Test Patterns:**
+- `describe()` blocks group related tests (domain or function-level)
+- Nested `describe()` blocks for feature-specific tests
+- `it()` for individual test cases with clear, descriptive names starting with "should"
+- Tests are independent and can run in any order
+
+Example from `server/lib/validation.test.js`:
+```javascript
+describe('validation.js', () => {
+ describe('processSchema', () => {
+ it('should validate a complete process object', () => {
+ const process = {
+ name: 'test-process',
+ port: 3000,
+ description: 'A test process'
+ };
+ const result = processSchema.safeParse(process);
+ expect(result.success).toBe(true);
+ expect(result.data).toEqual(process);
+ });
+
+ it('should reject empty name', () => {
+ const process = { name: '' };
+ const result = processSchema.safeParse(process);
+ expect(result.success).toBe(false);
+ });
+ });
+});
+```
+
+## Test Setup/Teardown
+
+**Patterns:**
+```javascript
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+describe('Module', () => {
+ let mockData;
+
+ beforeEach(() => {
+ // Fresh setup for each test
+ mockData = { id: '123', value: 'test' };
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ // Cleanup after each test
+ vi.clearAllMocks();
+ mockData = null;
+ });
+
+ it('should test something', () => {
+ // Test body
+ });
+});
+```
+
+Example from `server/routes/apps.test.js`:
+```javascript
+describe('Apps Routes', () => {
+ let app;
+
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/apps', appsRoutes);
+
+ // Reset all mocks
+ vi.clearAllMocks();
+ });
+
+ it('should return list of apps with PM2 status', async () => {
+ // Test implementation
+ });
+});
+```
+
+Example from `server/lib/logger.test.js`:
+```javascript
+describe('logger', () => {
+ let consoleLogSpy;
+ let consoleErrorSpy;
+ let consoleWarnSpy;
+
+ beforeEach(() => {
+ consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ consoleLogSpy.mockRestore();
+ consoleErrorSpy.mockRestore();
+ consoleWarnSpy.mockRestore();
+ });
+
+ test('startup logs with rocket emoji', () => {
+ logger.startup('Server started');
+ expect(consoleLogSpy).toHaveBeenCalledWith('🚀 Server started');
+ });
+});
+```
+
+## Mocking
+
+**Framework:** Vitest built-in `vi` from 'vitest'
+
+**Patterns:**
+
+### Module Mocking:
+```javascript
+vi.mock('../services/apps.js', () => ({
+ getAllApps: vi.fn(),
+ getAppById: vi.fn(),
+ createApp: vi.fn(),
+ updateApp: vi.fn(),
+ deleteApp: vi.fn(),
+ PORTOS_APP_ID: 'portos-default'
+}));
+
+// Then import the mocked module
+import * as appsService from '../services/apps.js';
+
+// Usage in tests
+appsService.getAllApps.mockResolvedValue(mockApps);
+```
+
+### Function Mocking with vi.fn():
+```javascript
+const mockSocket = {
+ id: 'socket-123',
+ emit: vi.fn(),
+ on: vi.fn()
+};
+
+// Assertions on calls
+expect(mockSocket.emit).toHaveBeenCalledWith('cos:subscribed');
+```
+
+### Spy Mocking:
+```javascript
+const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+expect(consoleLogSpy).toHaveBeenCalledWith('🚀 Server started');
+consoleLogSpy.mockRestore();
+```
+
+### Return Value Mocking:
+```javascript
+appsService.getAllApps.mockResolvedValue([
+ { id: 'app-001', name: 'Test App', pm2ProcessNames: ['test-app'] }
+]);
+
+pm2Service.listProcesses.mockResolvedValue([
+ { name: 'test-app', status: 'online' }
+]);
+```
+
+Example from `server/routes/apps.test.js`:
+```javascript
+vi.mock('../services/apps.js', () => ({
+ getAllApps: vi.fn(),
+ getAppById: vi.fn(),
+ createApp: vi.fn(),
+ updateApp: vi.fn(),
+ deleteApp: vi.fn(),
+ archiveApp: vi.fn(),
+ notifyAppsChanged: vi.fn(),
+ PORTOS_APP_ID: 'portos-default'
+}));
+
+vi.mock('../services/pm2.js', () => ({
+ listProcesses: vi.fn(),
+ getAppStatus: vi.fn(),
+ startWithCommand: vi.fn(),
+ stopApp: vi.fn(),
+ restartApp: vi.fn(),
+ getLogs: vi.fn()
+}));
+
+// Later in test
+appsService.getAllApps.mockResolvedValue(mockApps);
+pm2Service.listProcesses.mockResolvedValue(mockPm2Processes);
+```
+
+**What to Mock:**
+- External service dependencies (apps service, pm2 service, history service)
+- HTTP/Socket.IO calls
+- File system operations (when testing business logic, not I/O)
+- Console methods when testing log output
+- EventEmitter instances
+
+**What NOT to Mock:**
+- Validation schemas (test real Zod validation)
+- Error handler logic (test with real ServerError)
+- Core utility functions (test real implementations)
+- Internal module logic you're testing
+
+## Fixtures and Factories
+
+**Test Data:**
+- Inline mock data in test files (no separate fixtures directory)
+- Reusable data objects defined at top of describe blocks or in beforeEach
+
+Example pattern from `server/routes/apps.test.js`:
+```javascript
+const mockApps = [
+ { id: 'app-001', name: 'Test App', pm2ProcessNames: ['test-app'], repoPath: '/tmp/test' }
+];
+
+const mockPm2Processes = [
+ { name: 'test-app', status: 'online' }
+];
+
+// Reuse in multiple tests
+appsService.getAllApps.mockResolvedValue(mockApps);
+```
+
+Example from `server/lib/errorHandler.test.js`:
+```javascript
+const testCases = [
+ { status: 400, code: 'BAD_REQUEST' },
+ { status: 401, code: 'UNAUTHORIZED' },
+ { status: 403, code: 'FORBIDDEN' },
+ { status: 404, code: 'NOT_FOUND' },
+ // ... more cases
+];
+
+for (const tc of testCases) {
+ const error = new Error('Test');
+ error.status = tc.status;
+ const normalized = normalizeError(error);
+ expect(normalized.code).toBe(tc.code);
+}
+```
+
+**Location:**
+- Test data lives inline in test files
+- No separate fixtures directory
+- Shared data reused via variables/functions in beforeEach
+
+## Coverage
+
+**Requirements:** 30% threshold for lines, functions, branches, and statements
+
+**Configuration** (in `server/vitest.config.js`):
+```javascript
+coverage: {
+ provider: 'v8',
+ reporter: ['text', 'text-summary', 'html'],
+ reportsDirectory: './coverage',
+ include: ['lib/**/*.js', 'routes/**/*.js', 'services/**/*.js'],
+ exclude: [
+ '**/*.test.js',
+ '**/index.js',
+ '**/cos-runner/**'
+ ],
+ thresholds: {
+ lines: 30,
+ functions: 30,
+ branches: 30,
+ statements: 30
+ }
+}
+```
+
+**View Coverage:**
+```bash
+npm run test:coverage
+# Generates HTML report in ./coverage/index.html
+```
+
+**Included:**
+- `lib/**/*.js` - All utility/library code
+- `routes/**/*.js` - All route handlers
+- `services/**/*.js` - All service code
+
+**Excluded:**
+- `*.test.js` - Test files themselves
+- `index.js` - Entry points
+- `cos-runner/**` - External agent runner code
+
+## Test Types
+
+**Unit Tests:**
+- Scope: Single function or small module
+- Approach: Test business logic in isolation with mocked dependencies
+- No external I/O (unless testing I/O specifically)
+- Fast execution (< 100ms per test)
+
+Example from `server/lib/validation.test.js`:
+```javascript
+it('should validate a complete process object', () => {
+ const process = {
+ name: 'test-process',
+ port: 3000,
+ description: 'A test process'
+ };
+ const result = processSchema.safeParse(process);
+ expect(result.success).toBe(true);
+ expect(result.data).toEqual(process);
+});
+```
+
+**Integration Tests:**
+- Scope: Multiple modules working together, typically route + service
+- Approach: Mock external services, test request/response cycle
+- Uses `supertest` for HTTP testing with Express
+- May use real validation and error handling
+
+Example from `server/routes/apps.test.js`:
+```javascript
+it('should return list of apps with PM2 status', async () => {
+ const mockApps = [
+ { id: 'app-001', name: 'Test App', pm2ProcessNames: ['test-app'], repoPath: '/tmp/test' }
+ ];
+ const mockPm2Processes = [
+ { name: 'test-app', status: 'online' }
+ ];
+
+ appsService.getAllApps.mockResolvedValue(mockApps);
+ pm2Service.listProcesses.mockResolvedValue(mockPm2Processes);
+
+ const response = await request(app).get('/api/apps');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toHaveLength(1);
+ expect(response.body[0].overallStatus).toBe('online');
+});
+```
+
+**E2E Tests:**
+- Framework: Not currently in use
+- Vision testing only (integration test with `.integration.test.js` suffix)
+
+## Common Patterns
+
+**Async Testing:**
+```javascript
+it('should serialize concurrent operations', async () => {
+ const withLock = createMutex();
+ const results = [];
+
+ const p1 = withLock(async () => {
+ await new Promise(r => setTimeout(r, 20));
+ results.push('first');
+ return 'first';
+ });
+
+ const p2 = withLock(async () => {
+ results.push('second');
+ return 'second';
+ });
+
+ const p3 = withLock(async () => {
+ results.push('third');
+ return 'third';
+ });
+
+ await Promise.all([p1, p2, p3]);
+
+ expect(results).toEqual(['first', 'second', 'third']);
+});
+```
+
+**Error Testing:**
+```javascript
+it('should propagate errors from the wrapped function', async () => {
+ const withLock = createMutex();
+
+ await expect(
+ withLock(async () => {
+ throw new Error('test error');
+ })
+ ).rejects.toThrow('test error');
+});
+```
+
+**HTTP Route Testing with supertest:**
+```javascript
+import request from 'supertest';
+import express from 'express';
+import routes from './routes.js';
+
+const app = express();
+app.use(express.json());
+app.use('/api', routes);
+
+it('should return 200 with correct data', async () => {
+ const response = await request(app)
+ .get('/api/health');
+
+ expect(response.status).toBe(200);
+ expect(response.body.status).toBe('ok');
+ expect(response.body.version).toBeDefined();
+});
+```
+
+**Zod Schema Validation Testing:**
+```javascript
+it('should validate with safeParse', () => {
+ const data = { name: 'Test', repoPath: '/path' };
+ const result = appSchema.safeParse(data);
+ expect(result.success).toBe(true);
+ expect(result.data.type).toBe('express'); // default value
+});
+
+it('should reject invalid data', () => {
+ const data = { name: '', repoPath: '' };
+ const result = appSchema.safeParse(data);
+ expect(result.success).toBe(false);
+ expect(result.errors).toBeDefined();
+ expect(result.errors.length).toBeGreaterThan(0);
+});
+```
+
+**Mock Callback Testing:**
+```javascript
+it('should emit error event to errorEvents', () => {
+ const listener = vi.fn();
+ errorEvents.on('error', listener);
+
+ const error = new ServerError('Test error');
+ emitErrorEvent(mockIo, error);
+
+ expect(listener).toHaveBeenCalledWith(error);
+ errorEvents.off('error', listener);
+});
+```
+
+## Test File Examples
+
+**Unit Test:** `server/lib/errorHandler.test.js`
+- Tests ServerError class creation with options
+- Tests normalizeError() conversion logic
+- Tests error code mapping from HTTP status
+- Tests emitErrorEvent() with mocked io and event listeners
+
+**Integration Test:** `server/routes/apps.test.js`
+- Mocks all services (apps, pm2, history, streamingDetect)
+- Tests HTTP GET/POST/PUT/DELETE endpoints
+- Uses supertest for request/response testing
+- Verifies request validation and response shape
+- Tests multiple scenarios: success, empty results, error handling
+
+**Utility Test:** `server/lib/validation.test.js`
+- Tests multiple schemas: processSchema, appSchema, providerSchema, runSchema
+- Tests valid data with all fields and defaults
+- Tests invalid data rejection (empty strings, out-of-range values)
+- Tests optional fields (null, omitted)
+- Tests validate() wrapper function error formatting
+
+---
+
+*Testing analysis: 2026-02-26*