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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add Chief of Staff autonomous task manager
Adam Eivy9b4c4ba63837
diff --git a/.gitignore b/.gitignoreindex af059b5e9c..dab5dc55f8 100644--- a/.gitignore+++ b/.gitignore@@ -30,3 +30,5 @@ Thumbs.db# PM2.pm2/++.playwright-mcpdiff --git a/CLAUDE.md b/CLAUDE.mdindex 961576c1aa..daffe15b29 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -33,6 +33,7 @@ PortOS is a monorepo with Express.js server (port 5554) and React/Vite client (p- **Pages**: Route-based components- **Components**: Reusable UI elements- **Services**: `api.js` (HTTP) and `socket.js` (WebSocket)+- **Hooks**: `useErrorNotifications.js` subscribes to server errors, shows toast notifications### Data FlowClient → HTTP/WebSocket → Routes (validate) → Services (logic) → JSON files/PM2diff --git a/HEALTH_REPORT.md b/HEALTH_REPORT.mddeleted file mode 100644index 45787c5ed5..0000000000--- a/HEALTH_REPORT.md+++ /dev/null@@ -1,210 +0,0 @@-# PortOS System Health Check Report--**Generated**: 2026-01-03 01:35 UTC-**Task ID**: sys-health-001-**Priority**: HIGH-**Status**: ✅ OPERATIONAL - All systems nominal-------## Executive Summary--✅ **Overall Status**: OPERATIONAL-The PortOS system is fully operational with all critical processes online, excellent resource utilization, and zero blocking errors. System is stable and ready for production use.-------## PM2 Process Status--### Critical Processes-| Process | ID | Status | PID | Memory | CPU | Restarts |-|---------|----|---------|----|--------|-----|----------|-| **portos-server** | 16 | ✅ online | 22961 | 69.6 MB | 0% | 29 |-| **portos-client** | 17 | ✅ online | 36152 | 54.5 MB | 0% | 2 |--### Application Ecosystem (24 total processes)-- **All 24 processes**: ✅ ONLINE- - Browser instances (8): Running normally, 121-366 MB range- - Support services: autofixer, autofixer-ui, pages-server, template-watcher all online- - 3rd party apps: escapemint, fableloom, void all running--**Status**: ✅ All processes healthy, zero failures-------## Health Check Results--### API Health Endpoint-```-GET /api/cos/health - ✅ Responding-GET /api/cos - ✅ CoS daemon running (41 agents spawned, 31 tasks completed)-```--### System Health Metrics-```-PM2 Processes: 24 total, 24 online, 0 errored, 0 stopped-Memory Pages:- - Free: 24,588 pages- - Active: 619,130 pages- - Inactive: 600,957 pages-System Status: ✅ NOMINAL-```-------## Port Availability--### PortOS Services-| Port | Service | Status | Process |-|------|---------|--------|---------|-| 5554 | API Server | ✅ Bound | portos-server |-| 5555 | Client (Vite) | ✅ Bound | portos-client |--**Status**: ✅ No port conflicts-------## Memory & Resources--### PortOS Core-- **Server**: 69.6 MB ✅-- **Client**: 54.5 MB ✅-- **Total**: 124.1 MB ✅ (highly efficient)--**Status**: ✅ Healthy resource utilization-------## Network & Connectivity--### Server Health-- ✅ Express.js listening on 5554-- ✅ Vite dev server on 5555-- ✅ WebSocket connections active-- ✅ API endpoints responding normally--### Recent Activity-- ✅ Client connections established-- ✅ GET /api/apps working-- ✅ Sub-agent spawning functional-- ✅ Script runner initialized--**Status**: ✅ All communication channels operational-------## Error Analysis--### Current Status-- **Blocking Errors**: 0-- **Critical Issues**: 0-- **Warnings**: 0--### Previous Issues (Resolved)-1. ✅ ReferenceError in streamingDetect.js - Unable to reproduce-2. ✅ Request entity size issues - Not appearing in current logs-3. ⚠️ Node.js deprecation warnings (non-critical) - Can be addressed in next cycle--**Status**: ✅ No blocking errors-------## Chief of Staff Status--### CoS Daemon-- **Running**: Yes-- **Config**: Active with default settings-- **Agents Spawned**: 41-- **Tasks Completed**: 31-- **Last Evaluation**: 2026-01-03 01:35:47 UTC-- **Last Health Check**: 2026-01-03 01:35:46 UTC-- **Active Agents**: 3-- **Provider**: Claude Code CLI (claude-code)--### Task Evaluation-- **User Tasks File**: TASKS.md-- **System Tasks File**: COS-TASKS.md-- **Evaluation Interval**: 60 seconds-- **Health Check Interval**: 15 minutes-- **Max Concurrent Agents**: 3--**Status**: ✅ CoS operational and actively managing tasks-------## System Configuration--| Property | Value |-|----------|-------|-| Platform | macOS (Darwin 24.6.0) |-| Node.js | v25.2.1 |-| PM2 | Active (24 processes) |-| Environment | Development |-| Backend | Express.js |-| Frontend | React + Vite |-| Process Manager | PM2 |-| Data Storage | JSON files in ./data/ |-------## Performance Metrics--| Metric | Value | Assessment |-|--------|-------|-----------|-| PM2 Processes Online | 24/24 | ✅ 100% |-| PortOS Memory | 124.1 MB | ✅ Efficient |-| Server Restarts | 29 | ℹ️ Normal (dev) |-| Client Restarts | 2 | ✅ Stable |-| CPU Usage | 0% (idle) | ✅ Excellent |-| Port Conflicts | 0 | ✅ Clean |-| Active Connections | 4+ | ✅ Normal |-| Health Endpoint | Responding | ✅ Functional |-------## Verification Checklist--- [x] PM2 daemon running (24 processes online)-- [x] PortOS server responding (port 5554)-- [x] PortOS client responsive (port 5555)-- [x] No port conflicts detected-- [x] Memory usage within acceptable ranges-- [x] CPU usage nominal-- [x] WebSocket connections active-- [x] API endpoints functioning-- [x] CoS daemon operational-- [x] Health check endpoint responding-- [x] No blocking errors in logs-- [x] All support services online-------## Recommendations--### Immediate Actions-✅ None required - system is operating optimally--### Maintenance Considerations-1. **Node.js Deprecation** (Low priority)- - Update child_process calls to avoid `shell: true`- - Can be scheduled for next version cycle--2. **Monitoring**- - Continue regular health checks- - Monitor browser instance memory (currently normal)--3. **Documentation**- - Keep HEALTH_REPORT.md updated with periodic checks- - Document any anomalies for pattern analysis-------## Conclusion--✅ **SYSTEM STATUS: OPERATIONAL**--The PortOS system is fully functional and stable. All critical components are online, memory and CPU usage are optimal, and no blocking errors are present. The Chief of Staff daemon is actively managing tasks and sub-agents are executing successfully. The system is ready for production workloads and development activities.-------**Health Check Complete** | Verification Run: 2026-01-03 01:35 UTCdiff --git a/PLAN.md b/PLAN.mdindex 267d8ac835..369e58a9de 100644--- a/PLAN.md+++ b/PLAN.md@@ -40,11 +40,25 @@ pm2 logs- [x] M11: AI Agents Page (process detection, kill ability, colorful UI, expandable details)- [x] M12: History Improvements (expandable entries, runtime/output capture, full command display)- [x] M13: Autofixer Integration (PM2 crash detection, Claude CLI auto-fix, session history UI)+- [x] M14: Chief of Staff (autonomous agent manager, TASKS.md, system health, self-improvement)+- [x] M15: Graceful Error Handling (error normalization, auto-fix integration, Socket.IO events)+- [~] M16: Memory System (semantic memory, LM Studio embeddings, auto-extraction, agent context injection)+- [x] M17: PM2 Ecosystem Config Enhancement (per-process port detection, CDP_PORT support, refresh button)+- [x] M18: PM2 Standardization (LLM-powered config refactoring, import integration, button trigger)### Documentation- [Contributing Guide](./docs/CONTRIBUTING.md) - Code guidelines, git workflow- [Versioning & Releases](./docs/VERSIONING.md) - Version format, release process+### Error Handling+The server implements comprehensive error handling:+- **asyncHandler**: All routes wrapped with error handler that catches uncaught errors+- **ServerError**: Custom error class with status, code, severity, and context+- **Socket.IO Events**: Errors broadcast to UI via `error:occurred` event+- **Process Handlers**: Unhandled rejections and uncaught exceptions emit socket events+- **Logging**: Errors logged with emoji prefixes, no server crashes+- See `server/lib/errorHandler.js` and `server/services/socket.js`+---## M4: App Wizard (Detailed)@@ -315,3 +329,374 @@ Autonomous crash detection and repair using Claude CLI.| Check Interval | 15 minutes || Fix Cooldown | 30 minutes || Max History | 100 entries |++---++## M14: Chief of Staff++Autonomous agent manager that watches task files, spawns sub-agents, and maintains system health.++### Architecture+- **Task Parser** (`server/lib/taskParser.js`): Parses TASKS.md and COS-TASKS.md formats+- **CoS Service** (`server/services/cos.js`): State management, health monitoring, task evaluation+- **Task Watcher** (`server/services/taskWatcher.js`): File watching with chokidar+- **Sub-Agent Spawner** (`server/services/subAgentSpawner.js`): Claude CLI execution with MCP+- **CoS Routes** (`server/routes/cos.js`): REST API endpoints+- **CoS UI** (`client/src/pages/ChiefOfStaff.jsx`): Tasks, Agents, Health, Config tabs++### Features+1. **Dual Task Lists**: User tasks (TASKS.md) and system tasks (COS-TASKS.md)+2. **Autonomous Execution**: Auto-approved tasks run without user intervention+3. **Approval Workflow**: Tasks marked APPROVAL require user confirmation+4. **System Health Monitoring**: PM2 process checks, memory usage, error detection+5. **Sub-Agent Spawning**: Claude CLI with --dangerously-skip-permissions and MCP servers+6. **Self-Improvement**: Can analyze performance and suggest prompt/config improvements+7. **Script Generation**: Creates automation scripts for repetitive tasks+8. **Report Generation**: Daily summaries of completed work++### Task File Format+```markdown+# Tasks+## Pending+- [ ] #task-001 | HIGH | Task description+ - Context: Additional context+ - App: app-name++## In Progress+- [~] #task-002 | MEDIUM | Another task+ - Agent: agent-id+ - Started: 2024-01-15T10:30:00Z++## Completed+- [x] #task-003 | LOW | Done task+ - Completed: 2024-01-14T15:45:00Z+```++### System Task Format (with approval flags)+```markdown+- [ ] #sys-001 | HIGH | AUTO | Auto-approved task+- [ ] #sys-002 | MEDIUM | APPROVAL | Needs user approval+```++### Data Storage+```+./data/cos/+├── state.json # Daemon state and config+├── agents/{agentId}/ # Agent prompts and outputs+├── reports/{date}.json # Daily reports+└── scripts/ # Generated automation scripts+```++### API Endpoints+| Route | Description |+|-------|-------------|+| GET /api/cos | Get CoS status |+| POST /api/cos/start | Start daemon |+| POST /api/cos/stop | Stop daemon |+| GET/PUT /api/cos/config | Configuration |+| GET /api/cos/tasks | Get all tasks |+| POST /api/cos/evaluate | Force evaluation |+| GET /api/cos/health | Health status |+| POST /api/cos/health/check | Run health check |+| GET /api/cos/agents | List agents |+| POST /api/cos/agents/:id/terminate | Terminate agent |+| GET /api/cos/reports | List reports |++### Prompt Templates+| Template | Purpose |+|----------|---------|+| cos-agent-briefing | Brief sub-agent on task |+| cos-evaluate | Evaluate tasks and decide actions |+| cos-report-summary | Generate daily summary |+| cos-self-improvement | Analyze and suggest improvements |++### Configuration+| Setting | Default | Description |+|---------|---------|-------------|+| evaluationIntervalMs | 60000 | Task evaluation interval |+| healthCheckIntervalMs | 900000 | Health check interval |+| maxConcurrentAgents | 3 | Max parallel agents |+| maxProcessMemoryMb | 2048 | Memory alert threshold |+| autoStart | false | Start on server boot |+| selfImprovementEnabled | true | Allow self-analysis |++---++## M15: Graceful Error Handling++Enhanced error handling system with automatic recovery and UI notifications.++### Architecture+- **Error Handler** (`server/lib/errorHandler.js`): Centralized error normalization and Socket.IO emission+- **Auto-Fixer** (`server/services/autoFixer.js`): Automatic agent spawning for critical errors+- **Socket.IO Integration**: Real-time error notifications to connected clients+- **Route Protection**: All routes use asyncHandler wrapper for consistent error handling++### Features+1. **Graceful Error Handling**: Server never crashes, all errors caught and handled+2. **Socket.IO Error Events**: Real-time error notifications to UI with severity and context+3. **Auto-Fix Tasks**: Critical errors automatically create CoS tasks for agent resolution+4. **Error Recovery UI**: Client can request manual error recovery via Socket.IO+5. **Process Error Handlers**: Unhandled rejections and exceptions trigger auto-fix+6. **Error Deduplication**: Prevents duplicate auto-fix tasks within 1-minute window++### Error Severity Levels+| Severity | Description | Auto-Fix |+|----------|-------------|----------|+| warning | Non-critical issues | No |+| error | Server errors, failures | No |+| critical | System-threatening errors | Yes |++### Socket.IO Events+| Event | Direction | Payload |+|-------|-----------|---------|+| error:occurred | Server → Client | Error details with severity, code, timestamp |+| system:critical-error | Server → Client | Critical errors only |+| error:notified | Server → Subscribers | Error notification to subscribed clients |+| errors:subscribe | Client → Server | Subscribe to error events |+| errors:unsubscribe | Client → Server | Unsubscribe from error events |+| error:recover | Client → Server | Request manual error recovery |+| error:recover:requested | Server → Client | Recovery task created confirmation |++### Auto-Fix Flow+1. Error occurs in route or service+2. `asyncHandler` catches and normalizes error+3. Error emitted to `errorEvents` EventEmitter+4. `autoFixer` checks if error should trigger auto-fix+5. If yes, creates CoS task with error context+6. Socket.IO broadcasts error to all connected clients+7. CoS evaluates and spawns agent to fix the error+8. Agent analyzes, fixes, and reports back++### Implementation Files+| File | Purpose |+|------|---------|+| `server/lib/errorHandler.js` | Error classes, asyncHandler, middleware |+| `server/services/autoFixer.js` | Auto-fix task creation and deduplication |+| `server/services/socket.js` | Socket.IO error event forwarding |+| `server/routes/*.js` | All routes use asyncHandler wrapper |+| `client/src/hooks/useErrorNotifications.js` | Client-side error event handler with toast notifications |+| `client/src/components/Layout.jsx` | Mounts error notification hook for app-wide coverage |++### Error Context+Errors include rich context for debugging:+- Error code and message+- HTTP status code+- Timestamp+- Stack trace (for 500+ errors)+- Custom context object+- Severity level+- Auto-fix flag++---++## M16: Memory System++Semantic memory system for the Chief of Staff that stores facts, learnings, observations, decisions, and user preferences with vector embeddings for intelligent retrieval.++### Architecture+- **Memory Service** (`server/services/memory.js`): Core CRUD, search, and lifecycle operations+- **Embeddings Service** (`server/services/memoryEmbeddings.js`): LM Studio integration for vector generation+- **Memory Extractor** (`server/services/memoryExtractor.js`): Extract memories from agent output+- **Memory Retriever** (`server/services/memoryRetriever.js`): Context injection for agent prompts+- **Memory Routes** (`server/routes/memory.js`): REST API endpoints+- **Memory Tab** (`ChiefOfStaff.jsx`): UI with list, timeline, and graph views++### Features+1. **Six Memory Types**: fact, learning, observation, decision, preference, context+2. **Semantic Search**: LM Studio embeddings for similarity-based retrieval+3. **Auto-Extraction**: Memories extracted from successful agent task completions+4. **Auto-Injection**: Relevant memories injected into agent prompts before execution+5. **Importance Decay**: Time-based decay with access-based boosts+6. **Memory Consolidation**: Merge similar memories automatically+7. **Real-time Updates**: WebSocket events for memory changes+8. **Graph Visualization**: D3.js relationship graph (planned)++### Memory Schema+```javascript+{+ id: string, // UUID+ type: 'fact' | 'learning' | 'observation' | 'decision' | 'preference' | 'context',+ content: string, // Full memory content+ summary: string, // Short summary+ category: string, // e.g., 'codebase', 'workflow', 'tools'+ tags: string[], // Auto-extracted and user-defined+ relatedMemories: string[], // Linked memory IDs+ sourceTaskId: string, // Origin task+ sourceAgentId: string, // Origin agent+ embedding: number[], // Vector (768 dims for nomic-embed)+ confidence: number, // 0.0-1.0+ importance: number, // 0.0-1.0 (decays over time)+ accessCount: number,+ lastAccessed: string,+ createdAt: string,+ status: 'active' | 'archived' | 'expired'+}+```++### Data Storage+```+./data/cos/memory/+├── index.json # Lightweight metadata for listing/filtering+├── embeddings.json # Vector storage for semantic search+└── memories/ # Full memory content+ └── {id}/+ └── memory.json+```++### API Endpoints+| Route | Description |+|-------|-------------|+| GET /api/memory | List memories with filters |+| GET /api/memory/:id | Get single memory |+| POST /api/memory | Create memory |+| PUT /api/memory/:id | Update memory |+| DELETE /api/memory/:id | Delete (soft) memory |+| POST /api/memory/search | Semantic search |+| GET /api/memory/categories | List categories |+| GET /api/memory/tags | List tags |+| GET /api/memory/timeline | Timeline view data |+| GET /api/memory/graph | Graph visualization data |+| GET /api/memory/stats | Memory statistics |+| POST /api/memory/link | Link two memories |+| POST /api/memory/consolidate | Merge similar memories |+| POST /api/memory/decay | Apply importance decay |+| DELETE /api/memory/expired | Clear expired memories |+| GET /api/memory/embeddings/status | LM Studio connection status |++### WebSocket Events+| Event | Description |+|-------|-------------|+| cos:memory:created | New memory created |+| cos:memory:updated | Memory updated |+| cos:memory:deleted | Memory deleted |+| cos:memory:extracted | Memories extracted from agent |+| cos:memory:approval-needed | Medium-confidence memories pending approval |++### LM Studio Configuration+```javascript+memory: {+ enabled: true,+ embeddingProvider: 'lmstudio',+ embeddingEndpoint: 'http://localhost:1234/v1/embeddings',+ embeddingModel: 'nomic-embed-text-v1.5',+ embeddingDimension: 768,+ maxContextTokens: 2000,+ minRelevanceThreshold: 0.7,+ autoExtractEnabled: true+}+```++### Memory Extraction+Memories are extracted from agent output:+1. **Structured Blocks**: `<MEMORY type="..." category="..." confidence="...">content</MEMORY>`+2. **Pattern Matching**: "I learned that...", "User prefers...", "I decided to..."+3. **High confidence (>0.8)**: Auto-saved+4. **Medium confidence (0.5-0.8)**: Queued for user approval++### Memory Injection+Before agent task execution:+1. Generate embedding for task description+2. Find semantically similar memories (>0.7 relevance)+3. Include high-importance user preferences+4. Include relevant codebase facts+5. Format as markdown section in agent prompt++### Implementation Files+| File | Purpose |+|------|---------|+| `server/lib/memoryValidation.js` | Zod schemas for memory operations |+| `server/lib/vectorMath.js` | Cosine similarity, clustering helpers |+| `server/services/memory.js` | Core CRUD, search, lifecycle |+| `server/services/memoryEmbeddings.js` | LM Studio embedding generation |+| `server/services/memoryExtractor.js` | Extract memories from agent output |+| `server/services/memoryRetriever.js` | Retrieve and format for injection |+| `server/routes/memory.js` | REST API endpoints |+| `client/src/pages/ChiefOfStaff.jsx` | MemoryTab, MemoryTimeline, MemoryGraph |+| `client/src/services/api.js` | Memory API client functions |++---++## M17: PM2 Ecosystem Config Enhancement++Enhanced app management to detect and track all PM2 processes with their ports.++### Features+- **Per-process port detection**: Extracts ports for each PM2 process from ecosystem.config.js/cjs+- **CDP_PORT support**: Detects Chrome DevTools Protocol ports for browser processes+- **Constant resolution**: Handles variable references like `CDP_PORT: CDP_PORT` by parsing top-level constants+- **Comment handling**: Properly skips `//` and `/* */` comments when parsing config files+- **Refresh button**: UI button to re-scan ecosystem config and update app data++### Schema Extension+```javascript+// Added to server/lib/validation.js+export const processSchema = z.object({+ name: z.string().min(1),+ port: z.number().int().min(1).max(65535).nullable().optional(),+ description: z.string().optional()+});++// Added to appSchema+processes: z.array(processSchema).optional()+```++### API Endpoint+```+POST /api/apps/:id/refresh-config+```+Re-parses the app's ecosystem config and updates the app with new process/port data.++### Implementation Files+| File | Changes |+|------|---------|+| `server/lib/validation.js` | Added `processSchema` and `processes` field to `appSchema` |+| `server/services/streamingDetect.js` | Added `parseEcosystemConfig()` with port/constant/comment parsing |+| `server/routes/apps.js` | Added `POST /:id/refresh-config` endpoint |+| `client/src/services/api.js` | Added `refreshAppConfig()` function |+| `client/src/pages/Apps.jsx` | Added "Refresh Config" button with loading state |++---++## M18: PM2 Standardization++LLM-powered refactoring to standardize app configurations to follow PM2 best practices.++### Features+1. **Standardize PM2 Button**: Available in each app's expanded details row+2. **LLM Analysis**: Uses configured AI provider to analyze project structure+3. **Auto-apply Changes**: Automatically modifies files with git backup+4. **Git Backup**: Creates backup branch before any modifications+5. **Port Consolidation**: Moves all ports to ecosystem.config.cjs env blocks+6. **Stray Port Removal**: Removes PORT from .env files, comments out port in vite.config++### PM2 Standard+- All ports defined in `ecosystem.config.cjs` env blocks+- PM2 configured with watch for live-reload on server processes+- Vite processes use `npx vite --host --port XXXX` in args+- No stray port references in .env or vite.config++### API Endpoints+| Route | Description |+|-------|-------------|+| POST /api/standardize/analyze | Analyze app and generate standardization plan |+| POST /api/standardize/apply | Apply changes with git backup |+| GET /api/standardize/template | Get standard PM2 template reference |+| POST /api/standardize/backup | Create git backup only |++### Socket Events (for streaming mode)+| Event | Description |+|-------|-------------|+| standardize:start | Client requests standardization |+| standardize:step | Progress update (analyze, backup, apply) |+| standardize:analyzed | Analysis complete with plan |+| standardize:complete | Standardization finished |++### Implementation Files+| File | Purpose |+|------|---------|+| `server/services/pm2Standardizer.js` | Core analysis and apply logic |+| `server/routes/standardize.js` | API endpoints |+| `server/services/socket.js` | Socket event handlers |+| `client/src/pages/Apps.jsx` | Standardize PM2 button |+| `client/src/services/api.js` | API functions |diff --git a/client/package-lock.json b/client/package-lock.jsonindex ebbe6d3ed0..5b3708b260 100644--- a/client/package-lock.json+++ b/client/package-lock.json@@ -1,16 +1,20 @@{"name": "portos-client",- "version": "0.3.0",+ "version": "0.4.7","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "portos-client",- "version": "0.3.0",+ "version": "0.4.7","dependencies": {+ "@dnd-kit/core": "^6.3.1",+ "@dnd-kit/sortable": "^10.0.0",+ "@dnd-kit/utilities": "^3.2.2","lucide-react": "^0.562.0","react": "^18.3.1","react-dom": "^18.3.1",+ "react-hot-toast": "^2.6.0","react-router-dom": "^7.1.1","socket.io-client": "^4.8.3"},@@ -318,6 +322,60 @@"node": ">=6.9.0"}},+ "node_modules/@dnd-kit/accessibility": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",+ "integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.0"+ },+ "peerDependencies": {+ "react": ">=16.8.0"+ }+ },+ "node_modules/@dnd-kit/core": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",+ "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@dnd-kit/accessibility": "^3.1.1",+ "@dnd-kit/utilities": "^3.2.2",+ "tslib": "^2.0.0"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@dnd-kit/sortable": {+ "version": "10.0.0",+ "resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",+ "integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",+ "license": "MIT",+ "dependencies": {+ "@dnd-kit/utilities": "^3.2.2",+ "tslib": "^2.0.0"+ },+ "peerDependencies": {+ "@dnd-kit/core": "^6.3.0",+ "react": ">=16.8.0"+ }+ },+ "node_modules/@dnd-kit/utilities": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",+ "integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.0"+ },+ "peerDependencies": {+ "react": ">=16.8.0"+ }+ },"node_modules/@esbuild/aix-ppc64": {"version": "0.25.12","resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",@@ -1490,6 +1548,13 @@"node": ">=4"}},+ "node_modules/csstype": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",+ "license": "MIT",+ "peer": true+ },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -1717,6 +1782,15 @@"node": ">=10.13.0"}},+ "node_modules/goober": {+ "version": "2.1.18",+ "resolved": "https://registry.npmjs.org/goober/-/goober-2.1.18.tgz",+ "integrity": "sha512-2vFqsaDVIT9Gz7N6kAL++pLpp41l3PfDuusHcjnGLfR6+huZkl6ziX+zgVC3ZxpqWhzH6pyDdGrCeDhMIvwaxw==",+ "license": "MIT",+ "peerDependencies": {+ "csstype": "^3.0.10"+ }+ },"node_modules/hasown": {"version": "2.0.2","resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",@@ -2243,6 +2317,23 @@"react": "^18.3.1"}},+ "node_modules/react-hot-toast": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/react-hot-toast/-/react-hot-toast-2.6.0.tgz",+ "integrity": "sha512-bH+2EBMZ4sdyou/DPrfgIouFpcRLCJ+HoCA32UoAYHn6T3Ur5yfcDCeSr5mwldl6pFOsiocmrXMuoCJ1vV8bWg==",+ "license": "MIT",+ "dependencies": {+ "csstype": "^3.1.3",+ "goober": "^2.1.16"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "react": ">=16",+ "react-dom": ">=16"+ }+ },"node_modules/react-refresh": {"version": "0.17.0","resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",@@ -2641,6 +2732,12 @@"dev": true,"license": "Apache-2.0"},+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD"+ },"node_modules/update-browserslist-db": {"version": "1.2.3","resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",diff --git a/client/package.json b/client/package.jsonindex 21f45afa9c..c81f491967 100644--- a/client/package.json+++ b/client/package.json@@ -9,9 +9,13 @@"preview": "vite preview"},"dependencies": {+ "@dnd-kit/core": "^6.3.1",+ "@dnd-kit/sortable": "^10.0.0",+ "@dnd-kit/utilities": "^3.2.2","lucide-react": "^0.562.0","react": "^18.3.1","react-dom": "^18.3.1",+ "react-hot-toast": "^2.6.0","react-router-dom": "^7.1.1","socket.io-client": "^4.8.3"},diff --git a/client/src/App.jsx b/client/src/App.jsxindex 523e31fd2d..0f19e59abc 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -6,8 +6,9 @@ import Logs from './pages/Logs';import CreateApp from './pages/CreateApp';import Templates from './pages/Templates';import AIProviders from './pages/AIProviders';-import { HistoryPage, RunnerPage, GitPage, UsagePage, ProcessesPage, AgentsPage } from './pages/DevTools';+import { HistoryPage, RunsHistoryPage, RunnerPage, GitPage, UsagePage, ProcessesPage, AgentsPage } from './pages/DevTools';import PromptManager from './pages/PromptManager';+import ChiefOfStaff from './pages/ChiefOfStaff';export default function App() {return (@@ -16,8 +17,9 @@ export default function App() {<Route index element={<Dashboard />} /><Route path="apps" element={<Apps />} /><Route path="logs" element={<Logs />} />- <Route path="devtools" element={<Navigate to="/devtools/history" replace />} />+ <Route path="devtools" element={<Navigate to="/devtools/runs" replace />} /><Route path="devtools/history" element={<HistoryPage />} />+ <Route path="devtools/runs" element={<RunsHistoryPage />} /><Route path="devtools/runner" element={<RunnerPage />} /><Route path="devtools/git" element={<GitPage />} /><Route path="devtools/usage" element={<UsagePage />} />@@ -25,6 +27,7 @@ export default function App() {<Route path="devtools/agents" element={<AgentsPage />} /><Route path="ai" element={<AIProviders />} /><Route path="prompts" element={<PromptManager />} />+ <Route path="cos" element={<ChiefOfStaff />} /><Route path="create" element={<CreateApp />} /><Route path="templates" element={<Templates />} /><Route path="*" element={<Navigate to="/" replace />} />diff --git a/client/src/components/AppIcon.jsx b/client/src/components/AppIcon.jsxnew file mode 100644index 0000000000..dc54c2b2c8--- /dev/null+++ b/client/src/components/AppIcon.jsx@@ -0,0 +1,172 @@+// App icons - SVG icons for different app types+// Each icon follows the 24x24 viewBox pattern used by lucide-react++const icons = {+ // PortOS - portal/gateway logo (from Logo.jsx)+ portos: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" strokeDasharray="4 2" opacity="0.5" />+ <circle cx="12" cy="12" r="6" stroke="currentColor" strokeWidth="2" />+ <circle cx="12" cy="12" r="2" fill="currentColor" />+ <line x1="12" y1="6" x2="12" y2="2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />+ <line x1="12" y1="18" x2="12" y2="22" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />+ <line x1="6" y1="12" x2="2" y2="12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />+ <line x1="18" y1="12" x2="22" y2="12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />+ </svg>+ ),++ // Web/Browser app+ web: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" />+ <ellipse cx="12" cy="12" rx="4" ry="10" stroke="currentColor" strokeWidth="2" />+ <line x1="2" y1="12" x2="22" y2="12" stroke="currentColor" strokeWidth="2" />+ <path d="M4.5 7h15M4.5 17h15" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />+ </svg>+ ),++ // API/Server+ api: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <rect x="3" y="4" width="18" height="5" rx="1" stroke="currentColor" strokeWidth="2" />+ <rect x="3" y="15" width="18" height="5" rx="1" stroke="currentColor" strokeWidth="2" />+ <circle cx="6" cy="6.5" r="1" fill="currentColor" />+ <circle cx="6" cy="17.5" r="1" fill="currentColor" />+ <line x1="12" y1="9" x2="12" y2="15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />+ </svg>+ ),++ // Database+ database: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <ellipse cx="12" cy="5" rx="9" ry="3" stroke="currentColor" strokeWidth="2" />+ <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5" stroke="currentColor" strokeWidth="2" />+ <path d="M3 12c0 1.66 4 3 9 3s9-1.34 9-3" stroke="currentColor" strokeWidth="2" />+ </svg>+ ),++ // Game/Dice+ game: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <rect x="3" y="3" width="18" height="18" rx="2" stroke="currentColor" strokeWidth="2" />+ <circle cx="8" cy="8" r="1.5" fill="currentColor" />+ <circle cx="16" cy="8" r="1.5" fill="currentColor" />+ <circle cx="12" cy="12" r="1.5" fill="currentColor" />+ <circle cx="8" cy="16" r="1.5" fill="currentColor" />+ <circle cx="16" cy="16" r="1.5" fill="currentColor" />+ </svg>+ ),++ // Book/Story+ book: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <path d="M4 19.5A2.5 2.5 0 016.5 17H20" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />+ <path d="M6.5 2H20v20H6.5A2.5 2.5 0 014 19.5v-15A2.5 2.5 0 016.5 2z" stroke="currentColor" strokeWidth="2" />+ <path d="M8 7h8M8 11h6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />+ </svg>+ ),++ // Robot/Bot+ bot: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <rect x="3" y="8" width="18" height="12" rx="2" stroke="currentColor" strokeWidth="2" />+ <circle cx="9" cy="13" r="2" fill="currentColor" />+ <circle cx="15" cy="13" r="2" fill="currentColor" />+ <line x1="12" y1="5" x2="12" y2="8" stroke="currentColor" strokeWidth="2" />+ <circle cx="12" cy="4" r="1.5" fill="currentColor" />+ <path d="M8 17h8" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />+ </svg>+ ),++ // Code/Terminal+ code: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <rect x="3" y="4" width="18" height="16" rx="2" stroke="currentColor" strokeWidth="2" />+ <path d="M7 10l3 2-3 2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ <line x1="13" y1="14" x2="17" y2="14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />+ </svg>+ ),++ // Wrench/Tool+ tool: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.77 3.77z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ </svg>+ ),++ // Rocket+ rocket: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 00-2.91-.09z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ <path d="M12 15l-3-3a22 22 0 012-3.95A12.88 12.88 0 0122 2c0 2.72-.78 7.5-6 11.95A22.18 22.18 0 0112 15z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ <path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ </svg>+ ),++ // Heart+ heart: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ </svg>+ ),++ // Music+ music: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <path d="M9 18V5l12-2v13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ <circle cx="6" cy="18" r="3" stroke="currentColor" strokeWidth="2" />+ <circle cx="18" cy="16" r="3" stroke="currentColor" strokeWidth="2" />+ </svg>+ ),++ // Sparkles/Magic+ sparkles: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <path d="M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ <path d="M5 3l.5 1.5L7 5l-1.5.5L5 7l-.5-1.5L3 5l1.5-.5L5 3z" fill="currentColor" />+ <path d="M19 17l.5 1.5L21 19l-1.5.5L19 21l-.5-1.5L17 19l1.5-.5L19 17z" fill="currentColor" />+ </svg>+ ),++ // Shield/Security+ shield: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ <path d="M9 12l2 2 4-4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ </svg>+ ),++ // Layers/Stack+ layers: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <polygon points="12 2 2 7 12 12 22 7 12 2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ <polyline points="2 17 12 22 22 17" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ <polyline points="2 12 12 17 22 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ </svg>+ ),++ // Package (default)+ package: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <path d="M16.5 9.4l-9-5.19M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ <polyline points="3.27 6.96 12 12.01 20.73 6.96" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ <line x1="12" y1="22.08" x2="12" y2="12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ </svg>+ ),++ // Coin/Currency+ coin: ({ size, className }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" className={className}>+ <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" />+ <path d="M12 6v12M9 9c0-1.1.9-2 2-2h2a2 2 0 110 4h-2a2 2 0 100 4h2a2 2 0 002-2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />+ </svg>+ ),+};++// List of available icon names for the picker+export const iconNames = Object.keys(icons);++export default function AppIcon({ icon, size = 24, className = '' }) {+ const IconComponent = icons[icon] || icons.package;+ return <IconComponent size={size} className={className} />;+}diff --git a/client/src/components/AppTile.jsx b/client/src/components/AppTile.jsxindex ccbc98c912..54050298b4 100644--- a/client/src/components/AppTile.jsx+++ b/client/src/components/AppTile.jsx@@ -1,5 +1,6 @@import { useState } from 'react';import StatusBadge from './StatusBadge';+import AppIcon from './AppIcon';import * as api from '../services/api';// Construct app URL using current hostname (works with Tailscale)@@ -38,8 +39,8 @@ export default function AppTile({ app, onUpdate }) {{/* Header */}<div className="flex items-start justify-between mb-4"><div className="flex items-center gap-3">- <div className="w-12 h-12 rounded-lg bg-port-border flex items-center justify-center text-2xl">- {app.icon || '📦'}+ <div className="w-12 h-12 rounded-lg bg-port-border flex items-center justify-center text-port-accent">+ <AppIcon icon={app.icon || 'package'} size={28} /></div><div><h3 className="font-semibold text-white">{app.name}</h3>diff --git a/client/src/components/ErrorBoundary.jsx b/client/src/components/ErrorBoundary.jsxnew file mode 100644index 0000000000..d0a27ec245--- /dev/null+++ b/client/src/components/ErrorBoundary.jsx@@ -0,0 +1,50 @@+import { Component } from 'react';+import { AlertTriangle } from 'lucide-react';++export default class ErrorBoundary extends Component {+ constructor(props) {+ super(props);+ this.state = { hasError: false, error: null };+ }++ static getDerivedStateFromError(error) {+ return { hasError: true, error };+ }++ componentDidCatch(error, errorInfo) {+ console.error(`💥 React Error: ${error.message}`, errorInfo);+ }++ render() {+ if (this.state.hasError) {+ return (+ <div className="min-h-screen bg-port-bg flex items-center justify-center p-4">+ <div className="bg-port-card border border-port-border rounded-xl p-8 max-w-md w-full">+ <div className="flex items-center justify-center mb-4">+ <AlertTriangle size={32} className="text-port-error" />+ </div>+ <h1 className="text-xl font-bold text-white text-center mb-2">Something went wrong</h1>+ <p className="text-gray-400 text-sm text-center mb-4">+ An unexpected error occurred. Please try refreshing the page.+ </p>+ {this.state.error && (+ <div className="bg-port-error/10 border border-port-error/30 rounded-lg p-3 mb-4">+ <p className="text-xs text-port-error font-mono break-all">+ {this.state.error.message}+ </p>+ </div>+ )}+ <button+ onClick={() => window.location.reload()}+ className="w-full px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"+ >+ Refresh Page+ </button>+ </div>+ </div>+ );+ }++ return this.props.children;+ }+}diff --git a/client/src/components/IconPicker.jsx b/client/src/components/IconPicker.jsxnew file mode 100644index 0000000000..a055d877a5--- /dev/null+++ b/client/src/components/IconPicker.jsx@@ -0,0 +1,55 @@+import { useState } from 'react';+import AppIcon, { iconNames } from './AppIcon';++export default function IconPicker({ value, onChange }) {+ const [isOpen, setIsOpen] = useState(false);++ return (+ <div className="relative">+ <label className="block text-sm text-gray-400 mb-1">Icon</label>+ <button+ type="button"+ onClick={() => setIsOpen(!isOpen)}+ className="flex items-center gap-3 w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white hover:border-port-accent/50 focus:border-port-accent focus:outline-none transition-colors"+ >+ <div className="w-8 h-8 rounded bg-port-border flex items-center justify-center text-port-accent">+ <AppIcon icon={value || 'package'} size={20} />+ </div>+ <span className="text-sm text-gray-300">{value || 'package'}</span>+ <span className="ml-auto text-gray-500">▼</span>+ </button>++ {isOpen && (+ <>+ <div+ className="fixed inset-0 z-40"+ onClick={() => setIsOpen(false)}+ />+ <div className="absolute top-full left-0 mt-1 w-full bg-port-card border border-port-border rounded-lg shadow-xl z-50 p-2 max-h-64 overflow-auto">+ <div className="grid grid-cols-5 gap-1">+ {iconNames.map(name => (+ <button+ key={name}+ type="button"+ onClick={() => {+ onChange(name);+ setIsOpen(false);+ }}+ className={`p-2 rounded-lg flex flex-col items-center gap-1 transition-colors ${+ value === name+ ? 'bg-port-accent/20 text-port-accent'+ : 'hover:bg-port-border text-gray-400 hover:text-white'+ }`}+ title={name}+ >+ <AppIcon icon={name} size={20} />+ <span className="text-[10px] truncate w-full text-center">{name}</span>+ </button>+ ))}+ </div>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 801c86ab3c..24971a37f8 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -18,10 +18,13 @@ import {BarChart3,Cpu,Wrench,- ExternalLink+ ExternalLink,+ Crown,+ Play} from 'lucide-react';import packageJson from '../../package.json';import Logo from './Logo';+import { useErrorNotifications } from '../hooks/useErrorNotifications';const navItems = [{ to: '/', label: 'Dashboard', icon: Home, single: true },@@ -36,11 +39,13 @@ const navItems = [},{ to: '/apps', label: 'Apps', icon: Package, single: true },{ href: '//:5560', label: 'Autofixer', icon: Wrench, external: true, dynamicHost: true },+ { to: '/cos', label: 'Chief of Staff', icon: Crown, single: true },{label: 'Dev Tools',icon: Terminal,children: [{ to: '/devtools/agents', label: 'AI Agents', icon: Cpu },+ { to: '/devtools/runs', label: 'AI Runs', icon: Play },{ to: '/devtools/runner', label: 'Code', icon: Code2 },{ to: '/devtools/git', label: 'Git Status', icon: GitBranch },{ to: '/devtools/history', label: 'History', icon: History },@@ -62,6 +67,9 @@ export default function Layout() {const [mobileOpen, setMobileOpen] = useState(false);const [expandedSections, setExpandedSections] = useState({});+ // Subscribe to server error notifications+ useErrorNotifications();+useEffect(() => {localStorage.setItem(SIDEBAR_KEY, String(collapsed));}, [collapsed]);diff --git a/client/src/hooks/useErrorNotifications.js b/client/src/hooks/useErrorNotifications.jsnew file mode 100644index 0000000000..4606a22e3d--- /dev/null+++ b/client/src/hooks/useErrorNotifications.js@@ -0,0 +1,69 @@+import { useEffect, useCallback } from 'react';+import toast from 'react-hot-toast';+import socket from '../services/socket';++/**+ * Hook that subscribes to server error events and shows toast notifications+ * Also provides a function to request auto-fix for errors+ */+export function useErrorNotifications() {+ const requestAutoFix = useCallback((errorCode, context) => {+ socket.emit('error:recover', { code: errorCode, context });+ toast('Recovery agent dispatched', { icon: '🔧' });+ }, []);++ useEffect(() => {+ // Subscribe to error events+ socket.emit('errors:subscribe');++ // Handle error notifications from server+ const handleError = (error) => {+ const toastOptions = {+ duration: error.severity === 'critical' ? 10000 : 5000,+ icon: error.severity === 'critical' ? '💥' : '❌'+ };++ // Format message based on severity+ const message = error.severity === 'critical'+ ? `Critical: ${error.message}`+ : error.message;++ toast.error(message, toastOptions);++ // Log to console for debugging+ console.error(`[${error.code}] ${error.message}`, error.context);+ };++ // Handle critical system errors+ const handleCriticalError = (error) => {+ toast.error(`System Critical: ${error.message}`, {+ duration: 15000,+ icon: '🚨'+ });+ };++ // Handle auto-fix task creation notifications+ const handleRecoveryRequested = (data) => {+ toast.success(`Auto-fix task created: ${data.taskId}`, {+ duration: 5000,+ icon: '🤖'+ });+ };++ // Register handlers+ socket.on('error:occurred', handleError);+ socket.on('error:notified', handleError);+ socket.on('system:critical-error', handleCriticalError);+ socket.on('error:recover:requested', handleRecoveryRequested);++ return () => {+ socket.emit('errors:unsubscribe');+ socket.off('error:occurred', handleError);+ socket.off('error:notified', handleError);+ socket.off('system:critical-error', handleCriticalError);+ socket.off('error:recover:requested', handleRecoveryRequested);+ };+ }, []);++ return { requestAutoFix };+}diff --git a/client/src/hooks/useSocket.js b/client/src/hooks/useSocket.jsnew file mode 100644index 0000000000..2b7b733fcf--- /dev/null+++ b/client/src/hooks/useSocket.js@@ -0,0 +1,36 @@+import { useEffect, useState } from 'react';+import { io } from 'socket.io-client';++let socket = null;++export function useSocket() {+ const [connected, setConnected] = useState(false);++ useEffect(() => {+ if (!socket) {+ // Connect to the server - use relative path for Tailscale compatibility+ socket = io({+ path: '/socket.io',+ transports: ['websocket', 'polling']+ });++ socket.on('connect', () => {+ setConnected(true);+ });++ socket.on('disconnect', () => {+ setConnected(false);+ });+ }++ return () => {+ // Don't disconnect on component unmount - keep socket alive+ };+ }, []);++ return socket;+}++export function getSocket() {+ return socket;+}diff --git a/client/src/index.css b/client/src/index.cssindex a7f1150077..12577a22cd 100644--- a/client/src/index.css+++ b/client/src/index.css@@ -40,3 +40,138 @@ body {.animate-pulse-soft {animation: pulse-soft 2s ease-in-out infinite;}++/* Chief of Staff Character Animations */+.cos-character {+ filter: drop-shadow(0 0 20px rgba(99, 102, 241, 0.3));+}++.antenna-light { animation: cos-pulse 2s ease-in-out infinite; }+.status-light { animation: cos-pulse 1.5s ease-in-out infinite; }++@keyframes cos-pulse {+ 0%, 100% { opacity: 0.6; transform: scale(1); }+ 50% { opacity: 1; transform: scale(1.2); }+}++.eye { animation: cos-blink 4s ease-in-out infinite; }+.eye-right { animation-delay: 0.1s; }++@keyframes cos-blink {+ 0%, 45%, 55%, 100% { transform: scaleY(1); }+ 50% { transform: scaleY(0.1); }+}++.pupil { animation: cos-lookAround 6s ease-in-out infinite; }++@keyframes cos-lookAround {+ 0%, 40%, 60%, 100% { transform: translateX(0); }+ 45%, 55% { transform: translateX(3px); }+}++.arm { transform-origin: center top; }+.arm-coding { animation: cos-type 0.3s ease-in-out infinite alternate; }+.hand-coding { animation: cos-typeHand 0.3s ease-in-out infinite alternate; }++@keyframes cos-type {+ from { transform: rotate(-3deg); }+ to { transform: rotate(3deg); }+}++@keyframes cos-typeHand {+ from { transform: translateY(0); }+ to { transform: translateY(5px); }+}++.arm-thinking, .arm-ideating { animation: cos-wave 2s ease-in-out infinite; }++@keyframes cos-wave {+ 0%, 100% { transform: rotate(0deg); }+ 50% { transform: rotate(-5deg); }+}++.code-line { animation: cos-codePulse 0.5s ease-in-out infinite alternate; }+.code-line-0 { animation-delay: 0s; }+.code-line-1 { animation-delay: 0.1s; }+.code-line-2 { animation-delay: 0.2s; }+.code-line-3 { animation-delay: 0.3s; }++@keyframes cos-codePulse {+ from { opacity: 0.4; }+ to { opacity: 1; }+}++.thinking-dot { animation: cos-bounce 0.6s ease-in-out infinite; }+.thinking-dot-0 { animation-delay: 0s; }+.thinking-dot-1 { animation-delay: 0.2s; }+.thinking-dot-2 { animation-delay: 0.4s; }++@keyframes cos-bounce {+ 0%, 100% { transform: translateY(0); }+ 50% { transform: translateY(-5px); }+}++.scan-line { animation: cos-scan 1.5s ease-in-out infinite; }++@keyframes cos-scan {+ 0% { transform: translateY(-10px); opacity: 0; }+ 50% { opacity: 1; }+ 100% { transform: translateY(10px); opacity: 0; }+}++.check {+ stroke-dasharray: 20;+ stroke-dashoffset: 20;+ animation: cos-drawCheck 0.5s ease forwards;+}+.check-0 { animation-delay: 0s; }+.check-1 { animation-delay: 0.3s; }+.check-2 { animation-delay: 0.6s; }++@keyframes cos-drawCheck {+ to { stroke-dashoffset: 0; }+}++.bulb, .bulb-glow { animation: cos-glow 1s ease-in-out infinite alternate; }++@keyframes cos-glow {+ from { opacity: 0.5; transform: scale(0.9); }+ to { opacity: 1; transform: scale(1.1); }+}++.cos-z { animation: cos-float 2s ease-in-out infinite; }+.cos-z-1 { animation-delay: 0s; }+.cos-z-2 { animation-delay: 0.3s; }+.cos-z-3 { animation-delay: 0.6s; }++@keyframes cos-float {+ 0%, 100% { transform: translateY(0) translateX(0); opacity: 0.8; }+ 50% { transform: translateY(-5px) translateX(5px); opacity: 1; }+}++.plan-cell { animation: cos-planPulse 1.5s ease-in-out infinite; }++@keyframes cos-planPulse {+ 0%, 100% { opacity: 0.3; }+ 50% { opacity: 0.9; }+}++.mouth-open { animation: cos-talk 0.15s ease-in-out infinite alternate; }++@keyframes cos-talk {+ from { transform: scaleY(0.6); }+ to { transform: scaleY(1.2); }+}++.cos-particle { animation: cos-floatParticle 3s ease-in-out infinite; }+.cos-particle-0 { animation-delay: 0s; }+.cos-particle-1 { animation-delay: 0.5s; }+.cos-particle-2 { animation-delay: 1s; }+.cos-particle-3 { animation-delay: 1.5s; }+.cos-particle-4 { animation-delay: 2s; }+.cos-particle-5 { animation-delay: 2.5s; }++@keyframes cos-floatParticle {+ 0%, 100% { transform: translateY(0) scale(1); opacity: 0.3; }+ 50% { transform: translateY(-10px) scale(1.5); opacity: 0.8; }+}diff --git a/client/src/main.jsx b/client/src/main.jsxindex 6cede93e1f..6fc1901dd5 100644--- a/client/src/main.jsx+++ b/client/src/main.jsx@@ -1,13 +1,38 @@import React from 'react';import ReactDOM from 'react-dom/client';import { BrowserRouter } from 'react-router-dom';+import { Toaster } from 'react-hot-toast';+import ErrorBoundary from './components/ErrorBoundary';import App from './App';import './index.css';+// Handle unhandled promise rejections+window.addEventListener('unhandledrejection', (event) => {+ console.error(`❌ Unhandled Promise Rejection: ${event.reason}`);+ event.preventDefault();+});++// Handle global errors+window.addEventListener('error', (event) => {+ console.error(`💥 Global Error: ${event.message}`);+});+ReactDOM.createRoot(document.getElementById('root')).render(<React.StrictMode>- <BrowserRouter>- <App />- </BrowserRouter>+ <ErrorBoundary>+ <BrowserRouter>+ <App />+ <Toaster+ position="bottom-right"+ toastOptions={{+ style: {+ background: '#1e1e2e',+ color: '#fff',+ border: '1px solid #313244'+ }+ }}+ />+ </BrowserRouter>+ </ErrorBoundary></React.StrictMode>);diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsxindex b9fa5a30bf..ae7f81b9af 100644--- a/client/src/pages/Apps.jsx+++ b/client/src/pages/Apps.jsx@@ -1,7 +1,9 @@import { useState, useEffect, Fragment } from 'react';import { Link } from 'react-router-dom';-import { ExternalLink, Play, Square, RotateCcw, FolderOpen, Terminal, Code } from 'lucide-react';+import { ExternalLink, Play, Square, RotateCcw, FolderOpen, Terminal, Code, RefreshCw, Wrench } from 'lucide-react';+import toast from 'react-hot-toast';import StatusBadge from '../components/StatusBadge';+import IconPicker from '../components/IconPicker';import * as api from '../services/api';export default function Apps() {@@ -11,6 +13,8 @@ export default function Apps() {const [confirmingDelete, setConfirmingDelete] = useState(null);const [expandedId, setExpandedId] = useState(null);const [actionLoading, setActionLoading] = useState({});+ const [refreshingConfig, setRefreshingConfig] = useState({});+ const [standardizing, setStandardizing] = useState({});const fetchApps = async () => {const data = await api.getApps().catch(() => []);@@ -57,6 +61,44 @@ export default function Apps() {}, 2000);};+ const handleRefreshConfig = async (app) => {+ setRefreshingConfig(prev => ({ ...prev, [app.id]: true }));+ await api.refreshAppConfig(app.id).catch(() => null);+ setRefreshingConfig(prev => ({ ...prev, [app.id]: false }));+ fetchApps();+ };++ const handleStandardize = async (app) => {+ setStandardizing(prev => ({ ...prev, [app.id]: true }));++ // Step 1: Analyze+ const analysis = await api.analyzeStandardizationByApp(app.id).catch(err => {+ toast.error(`Analysis failed: ${err.message}`);+ return null;+ });++ if (!analysis?.success) {+ setStandardizing(prev => ({ ...prev, [app.id]: false }));+ return;+ }++ // Step 2: Apply+ const result = await api.applyStandardizationByApp(app.id, analysis).catch(err => {+ toast.error(`Apply failed: ${err.message}`);+ return null;+ });++ setStandardizing(prev => ({ ...prev, [app.id]: false }));++ if (result?.success) {+ const msg = result.backupBranch+ ? `Standardized! Backup: ${result.backupBranch}`+ : `Standardized ${result.filesModified?.length || 0} files`;+ toast.success(msg);+ fetchApps();+ }+ };+const toggleExpand = (id) => {setExpandedId(prev => prev === id ? null : id);};@@ -106,7 +148,6 @@ export default function Apps() {<tr><th className="w-8 px-4 py-3"></th><th className="text-left px-4 py-3 text-sm font-medium text-gray-400">Name</th>- <th className="text-left px-4 py-3 text-sm font-medium text-gray-400">Ports</th><th className="text-left px-4 py-3 text-sm font-medium text-gray-400">Status</th><th className="text-center px-4 py-3 text-sm font-medium text-gray-400">Controls</th><th className="text-right px-4 py-3 text-sm font-medium text-gray-400">Actions</th>@@ -126,33 +167,26 @@ export default function Apps() {</td><td className="px-4 py-3"><div className="font-medium text-white">{app.name}</div>- <div className="text-xs text-gray-500">- {(app.pm2ProcessNames || []).join(', ')}- </div>- </td>- <td className="px-4 py-3 text-sm">- <div className="flex items-center gap-3">- {app.uiPort && (- <button- onClick={() => window.open(`${window.location.protocol}//${window.location.hostname}:${app.uiPort}`, '_blank')}- className="text-cyan-400 hover:text-cyan-300 font-mono flex items-center gap-1"- title={`Open UI at ${window.location.hostname}:${app.uiPort}`}- >- :{app.uiPort} <ExternalLink size={12} />- </button>- )}- {app.apiPort && (- <span className="text-gray-400 font-mono">API:{app.apiPort}</span>- )}- {!app.uiPort && !app.apiPort && <span className="text-gray-500">-</span>}+ <div className="text-xs text-gray-500 flex flex-wrap gap-x-2">+ {/* Show process names with ports - filter to only this app's processes */}+ {(app.pm2ProcessNames || []).map((procName, i) => {+ const procInfo = app.processes?.find(p => p.name === procName);+ const port = procInfo?.port;+ return (+ <span key={i}>+ {procName}{port ? <span className="text-cyan-500">:{port}</span> : ''}+ {i < (app.pm2ProcessNames?.length || 0) - 1 ? ',' : ''}+ </span>+ );+ })}</div></td><td className="px-4 py-3"><StatusBadge status={app.overallStatus} size="sm" /></td><td className="px-4 py-3">- {/* Start/Stop/Restart Button Group */}- <div className="flex justify-center">+ {/* Start/Stop/Restart/Launch Button Group */}+ <div className="flex justify-center gap-2"><div className="inline-flex rounded-lg overflow-hidden border border-port-border">{app.overallStatus === 'online' ? (<>@@ -187,6 +221,17 @@ export default function Apps() {</button>)}</div>+ {/* Launch button - only show when online and has UI port */}+ {app.uiPort && app.overallStatus === 'online' && (+ <button+ onClick={() => window.open(`${window.location.protocol}//${window.location.hostname}:${app.uiPort}`, '_blank')}+ className="px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors rounded-lg border border-port-border flex items-center gap-1"+ title={`Open ${window.location.hostname}:${app.uiPort}`}+ >+ <ExternalLink size={14} />+ <span className="text-xs">Launch</span>+ </button>+ )}</div></td><td className="px-4 py-3 text-right">@@ -230,7 +275,7 @@ export default function Apps() {{/* Expanded Details Row */}{expandedId === app.id && (<tr>- <td colSpan={6} className="p-0">+ <td colSpan={5} className="p-0"><div className="bg-port-bg border-t border-port-border"><div className="px-6 py-4 space-y-4">{/* Details Grid */}@@ -271,25 +316,32 @@ export default function Apps() {<div><div className="text-xs text-gray-500 uppercase tracking-wide mb-2">PM2 Processes</div><div className="flex flex-wrap gap-2">- {Object.values(app.pm2Status).map((proc, i) => (- <div- key={i}- className="flex items-center gap-2 px-3 py-1.5 bg-port-card border border-port-border rounded-lg"- >- <span className={`w-2 h-2 rounded-full ${- proc.status === 'online' ? 'bg-port-success' :- proc.status === 'stopped' ? 'bg-gray-500' : 'bg-port-error'- }`} />- <span className="text-sm text-white font-mono">{proc.name}</span>- <span className="text-xs text-gray-500">{proc.status}</span>- {proc.cpu !== undefined && (- <span className="text-xs text-green-400">{proc.cpu}%</span>- )}- {proc.memory !== undefined && (- <span className="text-xs text-blue-400">{(proc.memory / 1024 / 1024).toFixed(0)}MB</span>- )}- </div>- ))}+ {Object.values(app.pm2Status).map((proc, i) => {+ // Find port for this process from the processes array+ const processConfig = app.processes?.find(p => p.name === proc.name);+ return (+ <div+ key={i}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-card border border-port-border rounded-lg"+ >+ <span className={`w-2 h-2 rounded-full ${+ proc.status === 'online' ? 'bg-port-success' :+ proc.status === 'stopped' ? 'bg-gray-500' : 'bg-port-error'+ }`} />+ <span className="text-sm text-white font-mono">{proc.name}</span>+ {processConfig?.port && (+ <span className="text-xs text-cyan-400 font-mono">:{processConfig.port}</span>+ )}+ <span className="text-xs text-gray-500">{proc.status}</span>+ {proc.cpu !== undefined && (+ <span className="text-xs text-green-400">{proc.cpu}%</span>+ )}+ {proc.memory !== undefined && (+ <span className="text-xs text-blue-400">{(proc.memory / 1024 / 1024).toFixed(0)}MB</span>+ )}+ </div>+ );+ })}</div></div>)}@@ -308,6 +360,24 @@ export default function Apps() {><FolderOpen size={14} /> Open Folder</button>+ <button+ onClick={() => handleRefreshConfig(app)}+ disabled={refreshingConfig[app.id]}+ className="px-3 py-1.5 bg-port-border hover:bg-port-border/80 text-white rounded-lg text-xs flex items-center gap-1 disabled:opacity-50"+ title="Re-scan ecosystem config for PM2 processes and ports"+ >+ <RefreshCw size={14} className={refreshingConfig[app.id] ? 'animate-spin' : ''} />+ Refresh Config+ </button>+ <button+ onClick={() => handleStandardize(app)}+ disabled={standardizing[app.id]}+ className="px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded-lg text-xs flex items-center gap-1 disabled:opacity-50"+ title="Standardize PM2 config: move all ports to ecosystem.config.cjs"+ >+ <Wrench size={14} className={standardizing[app.id] ? 'animate-spin' : ''} />+ {standardizing[app.id] ? 'Standardizing...' : 'Standardize PM2'}+ </button></div></div></div>@@ -337,6 +407,7 @@ export default function Apps() {function EditAppModal({ app, onClose, onSave }) {const [formData, setFormData] = useState({name: app.name,+ icon: app.icon || 'package',repoPath: app.repoPath,uiPort: app.uiPort || '',apiPort: app.apiPort || '',@@ -354,6 +425,7 @@ function EditAppModal({ app, onClose, onSave }) {const data = {name: formData.name,+ icon: formData.icon,repoPath: formData.repoPath,uiPort: formData.uiPort ? parseInt(formData.uiPort) : null,apiPort: formData.apiPort ? parseInt(formData.apiPort) : null,@@ -386,15 +458,20 @@ function EditAppModal({ app, onClose, onSave }) {)}<form onSubmit={handleSubmit} className="space-y-4">- <div>- <label className="block text-sm text-gray-400 mb-1">Name</label>- <input- type="text"- value={formData.name}- onChange={e => setFormData({ ...formData, name: e.target.value })}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"- required- />+ <div className="grid grid-cols-[1fr_auto] gap-4">+ <div>+ <label className="block text-sm text-gray-400 mb-1">Name</label>+ <input+ type="text"+ value={formData.name}+ onChange={e => setFormData({ ...formData, name: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"+ required+ />+ </div>+ <div className="w-32">+ <IconPicker value={formData.icon} onChange={icon => setFormData({ ...formData, icon })} />+ </div></div><div>diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxnew file mode 100644index 0000000000..ace8fa05e8--- /dev/null+++ b/client/src/pages/ChiefOfStaff.jsx@@ -0,0 +1,2254 @@+import { useState, useEffect, useCallback } from 'react';+import { useSocket } from '../hooks/useSocket';+import * as api from '../services/api';+import {+ Play,+ Square,+ RefreshCw,+ CheckCircle,+ Clock,+ AlertCircle,+ Ban,+ Activity,+ FileText,+ Settings,+ Cpu,+ Trash2,+ Plus,+ Edit3,+ Save,+ X,+ Terminal,+ Zap,+ GripVertical,+ Brain+} from 'lucide-react';+import toast from 'react-hot-toast';+import {+ DndContext,+ closestCenter,+ KeyboardSensor,+ PointerSensor,+ useSensor,+ useSensors,+} from '@dnd-kit/core';+import {+ arrayMove,+ SortableContext,+ sortableKeyboardCoordinates,+ useSortable,+ verticalListSortingStrategy,+} from '@dnd-kit/sortable';+import { CSS } from '@dnd-kit/utilities';++const TABS = [+ { id: 'tasks', label: 'Tasks', icon: FileText },+ { id: 'agents', label: 'Agents', icon: Cpu },+ { id: 'scripts', label: 'Scripts', icon: Terminal },+ { id: 'memory', label: 'Memory', icon: Brain },+ { id: 'health', label: 'Health', icon: Activity },+ { id: 'config', label: 'Config', icon: Settings }+];++const AGENT_STATES = {+ sleeping: { label: 'Sleeping', color: '#6366f1', icon: '💤' },+ thinking: { label: 'Thinking', color: '#f59e0b', icon: '🧠' },+ coding: { label: 'Coding', color: '#10b981', icon: '⚡' },+ investigating: { label: 'Investigating', color: '#ec4899', icon: '🔍' },+ reviewing: { label: 'Reviewing', color: '#8b5cf6', icon: '📋' },+ planning: { label: 'Planning', color: '#06b6d4', icon: '📐' },+ ideating: { label: 'Ideating', color: '#f97316', icon: '💡' },+};++const STATE_MESSAGES = {+ sleeping: ["Resting... Wake me if you need anything!", "💤 Power saving mode..."],+ thinking: ["Processing your request...", "Analyzing the situation...", "Let me think about this..."],+ coding: ["Writing some code...", "Implementing the solution...", "Building something cool..."],+ investigating: ["Looking into this...", "Researching the topic...", "Gathering information..."],+ reviewing: ["Checking the details...", "Reviewing for quality...", "Making sure everything's right..."],+ planning: ["Organizing the approach...", "Mapping out the strategy...", "Creating a plan..."],+ ideating: ["Brainstorming ideas...", "Getting creative!", "Inspiration incoming..."],+};++function CoSCharacter({ state, speaking }) {+ const stateConfig = AGENT_STATES[state] || AGENT_STATES.sleeping;++ return (+ <div className="relative w-44 h-56 md:w-56 md:h-72">+ <svg viewBox="0 0 200 240" className="cos-character w-full h-auto">+ <defs>+ <linearGradient id="bodyGrad" x1="0%" y1="0%" x2="100%" y2="100%">+ <stop offset="0%" stopColor="#1e293b" />+ <stop offset="100%" stopColor="#0f172a" />+ </linearGradient>+ <linearGradient id="screenGrad" x1="0%" y1="0%" x2="0%" y2="100%">+ <stop offset="0%" stopColor={stateConfig.color} stopOpacity="0.3" />+ <stop offset="100%" stopColor={stateConfig.color} stopOpacity="0.1" />+ </linearGradient>+ <filter id="glow">+ <feGaussianBlur stdDeviation="3" result="coloredBlur"/>+ <feMerge>+ <feMergeNode in="coloredBlur"/>+ <feMergeNode in="SourceGraphic"/>+ </feMerge>+ </filter>+ <filter id="innerGlow">+ <feGaussianBlur stdDeviation="2" result="blur"/>+ <feComposite in="SourceGraphic" in2="blur" operator="over"/>+ </filter>+ </defs>++ {/* Particles */}+ <g className={`particles particles-${state}`}>+ {[+ { cx: 30, cy: 50 },+ { cx: 170, cy: 60 },+ { cx: 25, cy: 130 },+ { cx: 175, cy: 140 },+ { cx: 40, cy: 200 },+ { cx: 160, cy: 190 }+ ].map((pos, i) => (+ <circle+ key={i}+ cx={pos.cx}+ cy={pos.cy}+ r="2"+ fill={stateConfig.color}+ opacity="0.6"+ className={`cos-particle cos-particle-${i}`}+ />+ ))}+ </g>++ {/* Body */}+ <rect x="50" y="90" width="100" height="120" rx="20" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" />++ {/* Chest Screen */}+ <rect x="60" y="100" width="80" height="50" rx="8" fill="#0f172a" stroke={stateConfig.color} strokeWidth="1" opacity="0.8" />+ <rect x="65" y="105" width="70" height="40" rx="5" fill="url(#screenGrad)" />++ {/* Chest Display Content */}+ <g className="chest-display">+ {state === 'coding' && (+ <g className="code-lines">+ {[0, 1, 2, 3].map(i => (+ <rect key={i} x="70" y={110 + i * 8} width={30 + (i % 2) * 15} height="3" rx="1" fill={stateConfig.color} opacity="0.8" className={`code-line code-line-${i}`} />+ ))}+ </g>+ )}+ {state === 'thinking' && (+ <g className="thinking-dots">+ {[0, 1, 2].map(i => (+ <circle key={i} cx={85 + i * 15} cy="125" r="4" fill={stateConfig.color} className={`thinking-dot thinking-dot-${i}`} />+ ))}+ </g>+ )}+ {state === 'planning' && (+ <g className="plan-grid">+ {[0, 1, 2].map(row =>+ [0, 1, 2].map(col => (+ <rect key={`${row}-${col}`} x={72 + col * 20} y={108 + row * 12} width="15" height="8" rx="2" fill={stateConfig.color} opacity={0.4 + ((row + col) % 3) * 0.2} className="plan-cell" />+ ))+ )}+ </g>+ )}+ {state === 'investigating' && (+ <g className="scan-line-group">+ <line x1="70" y1="125" x2="130" y2="125" stroke={stateConfig.color} strokeWidth="2" className="scan-line" />+ </g>+ )}+ {state === 'reviewing' && (+ <g className="review-checks">+ {[0, 1, 2].map(i => (+ <path key={i} d={`M${75 + i * 20},125 l4,4 l8,-8`} stroke={stateConfig.color} strokeWidth="2" fill="none" className={`check check-${i}`} />+ ))}+ </g>+ )}+ {state === 'ideating' && (+ <g className="lightbulb">+ <ellipse cx="100" cy="120" rx="12" ry="15" fill={stateConfig.color} opacity="0.3" className="bulb-glow" />+ <ellipse cx="100" cy="120" rx="8" ry="10" fill={stateConfig.color} className="bulb" />+ </g>+ )}+ {state === 'sleeping' && (+ <g className="zzz">+ <text x="80" y="130" fill={stateConfig.color} fontSize="16" fontFamily="monospace" className="cos-z cos-z-1">Z</text>+ <text x="95" y="120" fill={stateConfig.color} fontSize="12" fontFamily="monospace" className="cos-z cos-z-2">z</text>+ <text x="105" y="112" fill={stateConfig.color} fontSize="8" fontFamily="monospace" className="cos-z cos-z-3">z</text>+ </g>+ )}+ </g>++ {/* Arms */}+ <rect x="30" y="100" width="18" height="60" rx="9" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" className={`arm arm-left arm-${state}`} />+ <rect x="152" y="100" width="18" height="60" rx="9" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" className={`arm arm-right arm-${state}`} />++ {/* Hands */}+ <circle cx="39" cy="165" r="10" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" className={`hand hand-left hand-${state}`} />+ <circle cx="161" cy="165" r="10" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" className={`hand hand-right hand-${state}`} />++ {/* Head */}+ <rect x="55" y="20" width="90" height="75" rx="15" fill="url(#bodyGrad)" stroke="#334155" strokeWidth="2" />++ {/* Face Screen */}+ <rect x="62" y="28" width="76" height="55" rx="10" fill="#0f172a" stroke={stateConfig.color} strokeWidth="1.5" filter="url(#innerGlow)" />++ {/* Eyes */}+ <g className={`eyes eyes-${state}`}>+ {state === 'sleeping' ? (+ <>+ <line x1="75" y1="50" x2="90" y2="50" stroke={stateConfig.color} strokeWidth="3" strokeLinecap="round" />+ <line x1="110" y1="50" x2="125" y2="50" stroke={stateConfig.color} strokeWidth="3" strokeLinecap="round" />+ </>+ ) : (+ <>+ <ellipse cx="82" cy="48" rx="10" ry={state === 'investigating' ? 12 : 8} fill={stateConfig.color} filter="url(#glow)" className="eye eye-left" />+ <ellipse cx="118" cy="48" rx="10" ry={state === 'investigating' ? 12 : 8} fill={stateConfig.color} filter="url(#glow)" className="eye eye-right" />+ <circle cx="82" cy="48" r="3" fill="#0f172a" className="pupil pupil-left" />+ <circle cx="118" cy="48" r="3" fill="#0f172a" className="pupil pupil-right" />+ </>+ )}+ </g>++ {/* Mouth */}+ <g className={`mouth mouth-${state} ${speaking ? 'speaking' : ''}`}>+ {speaking ? (+ <ellipse cx="100" cy="70" rx="12" ry="6" fill={stateConfig.color} opacity="0.8" className="mouth-open" />+ ) : state === 'sleeping' ? (+ <ellipse cx="100" cy="68" rx="8" ry="3" fill={stateConfig.color} opacity="0.5" />+ ) : (+ <path d="M88,68 Q100,78 112,68" stroke={stateConfig.color} strokeWidth="2" fill="none" strokeLinecap="round" />+ )}+ </g>++ {/* Antenna */}+ <line x1="100" y1="20" x2="100" y2="5" stroke="#334155" strokeWidth="3" />+ <circle cx="100" cy="5" r="5" fill={stateConfig.color} filter="url(#glow)" className="antenna-light" />++ {/* Status Light */}+ <circle cx="148" cy="35" r="4" fill={stateConfig.color} filter="url(#glow)" className="status-light" />+ </svg>+ </div>+ );+}++function StateLabel({ state }) {+ const stateConfig = AGENT_STATES[state] || AGENT_STATES.sleeping;++ return (+ <div+ className="flex items-center gap-2 px-4 py-2 rounded-full mt-4 font-mono text-xs"+ style={{+ background: 'rgba(15, 23, 42, 0.8)',+ border: `1px solid ${stateConfig.color}`,+ boxShadow: `0 0 20px rgba(99, 102, 241, 0.2)`+ }}+ >+ <span className="text-base">{stateConfig.icon}</span>+ <span className="text-gray-100">{stateConfig.label}</span>+ </div>+ );+}++function StatusBubble({ message }) {+ return (+ <div className="relative mt-4 px-4 py-3 rounded-2xl max-w-[280px] text-center text-sm leading-relaxed bg-indigo-500/10 border border-indigo-500/30">+ <div+ className="absolute -top-2 left-1/2 -translate-x-1/2 rotate-45 w-3.5 h-3.5 bg-indigo-500/10 border-l border-t border-indigo-500/30"+ />+ {message}+ </div>+ );+}++function EventLog({ logs }) {+ if (!logs || logs.length === 0) return null;++ const levelColors = {+ info: 'text-blue-400',+ warn: 'text-yellow-400',+ error: 'text-red-400',+ success: 'text-green-400',+ debug: 'text-gray-500'+ };++ const levelIcons = {+ info: 'ℹ️',+ warn: '⚠️',+ error: '❌',+ success: '✅',+ debug: '🔍'+ };++ return (+ <div className="mt-4 w-full max-w-[280px]">+ <div className="text-xs text-gray-500 mb-1 font-mono">Event Log</div>+ <div className="bg-slate-900/80 border border-slate-700/50 rounded-lg p-2 max-h-32 overflow-y-auto">+ {logs.slice(-5).reverse().map((log, i) => (+ <div key={i} className={`text-xs font-mono py-0.5 ${levelColors[log.level] || 'text-gray-400'}`}>+ <span className="mr-1">{levelIcons[log.level] || '•'}</span>+ <span className="text-gray-500">{new Date(log.timestamp).toLocaleTimeString()}</span>+ {' '}+ <span>{log.message}</span>+ </div>+ ))}+ </div>+ </div>+ );+}++export default function ChiefOfStaff() {+ const [status, setStatus] = useState(null);+ const [tasks, setTasks] = useState({ user: null, cos: null });+ const [agents, setAgents] = useState([]);+ const [scripts, setScripts] = useState([]);+ const [health, setHealth] = useState(null);+ const [providers, setProviders] = useState([]);+ const [loading, setLoading] = useState(true);+ const [activeTab, setActiveTab] = useState('tasks');+ const [agentState, setAgentState] = useState('sleeping');+ const [speaking, setSpeaking] = useState(false);+ const [statusMessage, setStatusMessage] = useState("Ready to help organize your day!");+ const [liveOutputs, setLiveOutputs] = useState({});+ const [eventLogs, setEventLogs] = useState([]);+ const socket = useSocket();++ // Derive agent state from system status+ const deriveAgentState = useCallback((statusData, agentsData, healthData) => {+ if (!statusData?.running) return 'sleeping';++ const activeAgents = agentsData.filter(a => a.status === 'running');+ if (activeAgents.length > 0) return 'coding';++ if (healthData?.issues?.length > 0) return 'investigating';++ // When running but idle, show as thinking (ready to work)+ return 'thinking';+ }, []);++ const fetchData = useCallback(async () => {+ const [statusData, tasksData, agentsData, scriptsData, healthData, providersData] = await Promise.all([+ api.getCosStatus().catch(() => null),+ api.getCosTasks().catch(() => ({ user: null, cos: null })),+ api.getCosAgents().catch(() => []),+ api.getCosScripts().catch(() => ({ scripts: [] })),+ api.getCosHealth().catch(() => null),+ api.getProviders().catch(() => ({ providers: [] }))+ ]);+ setStatus(statusData);+ setTasks(tasksData);+ setAgents(agentsData);+ setScripts(scriptsData.scripts || []);+ setHealth(healthData);+ setProviders(providersData.providers || []);+ setLoading(false);++ const newState = deriveAgentState(statusData, agentsData, healthData);+ setAgentState(newState);+ const messages = STATE_MESSAGES[newState];+ setStatusMessage(messages[Math.floor(Math.random() * messages.length)]);+ }, [deriveAgentState]);++ useEffect(() => {+ fetchData();+ const interval = setInterval(fetchData, 5000);+ return () => clearInterval(interval);+ }, [fetchData]);++ useEffect(() => {+ if (!socket) return;++ // Subscribe when socket is connected (or already connected)+ const subscribe = () => {+ socket.emit('cos:subscribe');+ };++ if (socket.connected) {+ subscribe();+ } else {+ socket.on('connect', subscribe);+ }++ socket.on('cos:status', (data) => {+ setStatus(prev => ({ ...prev, running: data.running }));+ if (!data.running) {+ setAgentState('sleeping');+ setStatusMessage(STATE_MESSAGES.sleeping[0]);+ }+ });++ socket.on('cos:tasks:user:changed', (data) => {+ setTasks(prev => ({ ...prev, user: data }));+ });++ socket.on('cos:agent:spawned', (data) => {+ setAgentState('coding');+ setStatusMessage("Working on a task...");+ setSpeaking(true);+ setTimeout(() => setSpeaking(false), 2000);+ // Initialize empty output buffer for new agent+ if (data?.agentId) {+ setLiveOutputs(prev => ({ ...prev, [data.agentId]: [] }));+ }+ fetchData();+ });++ socket.on('cos:agent:output', (data) => {+ if (data?.agentId && data?.line) {+ setLiveOutputs(prev => ({+ ...prev,+ [data.agentId]: [+ ...(prev[data.agentId] || []),+ { line: data.line, timestamp: Date.now() }+ ]+ }));+ }+ });++ socket.on('cos:agent:completed', () => {+ setAgentState('reviewing');+ setStatusMessage("Task completed! Checking results...");+ setSpeaking(true);+ setTimeout(() => setSpeaking(false), 2000);+ fetchData();+ });++ socket.on('cos:health:check', (data) => {+ setHealth({ lastCheck: data.metrics?.timestamp, issues: data.issues });+ if (data.issues?.length > 0) {+ setAgentState('investigating');+ setStatusMessage("Found some issues to look into...");+ setSpeaking(true);+ setTimeout(() => setSpeaking(false), 2000);+ }+ });++ // Listen for detailed log events+ socket.on('cos:log', (data) => {+ setEventLogs(prev => {+ const newLogs = [...prev, data].slice(-20); // Keep last 20 logs+ return newLogs;+ });+ // Update status message with latest log+ if (data.message) {+ setStatusMessage(data.message);+ if (data.level === 'success' || data.level === 'error') {+ setSpeaking(true);+ setTimeout(() => setSpeaking(false), 1500);+ }+ }+ });++ return () => {+ socket.emit('cos:unsubscribe');+ socket.off('connect', subscribe);+ socket.off('cos:status');+ socket.off('cos:tasks:user:changed');+ socket.off('cos:agent:spawned');+ socket.off('cos:agent:output');+ socket.off('cos:agent:completed');+ socket.off('cos:health:check');+ socket.off('cos:log');+ };+ }, [socket, fetchData]);++ const handleStart = async () => {+ const result = await api.startCos().catch(err => {+ toast.error(err.message);+ return null;+ });+ if (result?.success) {+ toast.success('Chief of Staff started');+ setAgentState('thinking');+ setStatusMessage("Starting up... Let me see what needs to be done!");+ setSpeaking(true);+ setTimeout(() => setSpeaking(false), 2000);+ fetchData();+ }+ };++ const handleStop = async () => {+ const result = await api.stopCos().catch(err => {+ toast.error(err.message);+ return null;+ });+ if (result?.success) {+ toast.success('Chief of Staff stopped');+ setAgentState('sleeping');+ setStatusMessage(STATE_MESSAGES.sleeping[0]);+ fetchData();+ }+ };++ const handleForceEvaluate = async () => {+ await api.forceCosEvaluate().catch(err => toast.error(err.message));+ toast.success('Evaluation triggered');+ setAgentState('thinking');+ setStatusMessage("Evaluating tasks...");+ setSpeaking(true);+ setTimeout(() => setSpeaking(false), 2000);+ };++ const handleHealthCheck = async () => {+ setAgentState('investigating');+ setStatusMessage("Running health check...");+ setSpeaking(true);+ const result = await api.forceHealthCheck().catch(err => {+ toast.error(err.message);+ return null;+ });+ setSpeaking(false);+ if (result) {+ setHealth({ lastCheck: result.metrics?.timestamp, issues: result.issues });+ toast.success('Health check complete');+ if (result.issues?.length > 0) {+ setStatusMessage("Found some issues!");+ } else {+ setAgentState('reviewing');+ setStatusMessage("All systems healthy!");+ }+ }+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center h-64">+ <div className="text-gray-500">Loading...</div>+ </div>+ );+ }++ const activeAgentCount = agents.filter(a => a.status === 'running').length;+ const hasIssues = (health?.issues?.length || 0) > 0;++ return (+ <div className="flex flex-col lg:grid lg:grid-cols-[320px_1fr] min-h-[calc(100vh-120px)] -m-6">+ {/* Agent Panel */}+ <div className="relative flex flex-col items-center p-6 lg:p-8 border-b lg:border-b-0 lg:border-r border-indigo-500/20 bg-gradient-to-b from-slate-900/80 to-slate-900/40 overflow-hidden">+ {/* Background Effects */}+ <div+ className="absolute inset-0 pointer-events-none"+ style={{+ background: `+ radial-gradient(circle at 50% 20%, rgba(99, 102, 241, 0.1) 0%, transparent 50%),+ repeating-linear-gradient(0deg, transparent, transparent 50px, rgba(99, 102, 241, 0.03) 50px, rgba(99, 102, 241, 0.03) 51px)+ `+ }}+ />++ <div className="relative z-10 flex flex-col items-center">+ <div className="text-sm font-semibold tracking-widest uppercase text-slate-400 mb-1 font-mono">+ Digital Assistant+ </div>+ <h1+ className="text-2xl lg:text-3xl font-bold mb-4 lg:mb-8"+ style={{+ background: 'linear-gradient(135deg, #6366f1, #8b5cf6, #06b6d4)',+ WebkitBackgroundClip: 'text',+ WebkitTextFillColor: 'transparent',+ backgroundClip: 'text'+ }}+ >+ Chief of Staff+ </h1>++ <CoSCharacter state={agentState} speaking={speaking} />+ <StateLabel state={agentState} />+ <StatusBubble message={statusMessage} />+ {status?.running && <EventLog logs={eventLogs} />}++ {/* Control Buttons */}+ <div className="flex items-center gap-3 mt-6">+ {status?.running ? (+ <button+ onClick={handleStop}+ className="flex items-center gap-2 px-4 py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg transition-colors"+ >+ <Square size={16} />+ Stop+ </button>+ ) : (+ <button+ onClick={handleStart}+ className="flex items-center gap-2 px-4 py-2 bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-400 rounded-lg transition-colors"+ >+ <Play size={16} />+ Start+ </button>+ )}+ <StatusIndicator running={status?.running} />+ </div>+ </div>+ </div>++ {/* Content Panel */}+ <div className="flex-1 p-6 lg:p-8 overflow-y-auto">+ {/* Stats Bar */}+ <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">+ <StatCard+ label="Active Agents"+ value={activeAgentCount}+ icon={<Cpu className="w-5 h-5 text-port-accent" />}+ active={activeAgentCount > 0}+ activeLabel={activeAgentCount > 0 ? agents.find(a => a.status === 'running')?.taskId : null}+ />+ <StatCard+ label="Pending Tasks"+ value={(tasks.user?.grouped?.pending?.length || 0) + (tasks.cos?.grouped?.pending?.length || 0)}+ icon={<Clock className="w-5 h-5 text-yellow-500" />}+ />+ <StatCard+ label="Completed"+ value={status?.stats?.tasksCompleted || 0}+ icon={<CheckCircle className="w-5 h-5 text-port-success" />}+ />+ <StatCard+ label="Health Issues"+ value={health?.issues?.length || 0}+ icon={<AlertCircle className={`w-5 h-5 ${hasIssues ? 'text-port-error' : 'text-gray-500'}`} />}+ />+ </div>++ {/* Tabs */}+ <div className="flex gap-1 mb-6 border-b border-port-border overflow-x-auto">+ {TABS.map(tab => {+ const Icon = tab.icon;+ return (+ <button+ key={tab.id}+ onClick={() => setActiveTab(tab.id)}+ className={`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px whitespace-nowrap ${+ activeTab === tab.id+ ? 'text-port-accent border-port-accent'+ : 'text-gray-500 border-transparent hover:text-white'+ }`}+ >+ <Icon size={16} />+ {tab.label}+ </button>+ );+ })}+ </div>++ {/* Tab Content */}+ {activeTab === 'tasks' && (+ <TasksTab tasks={tasks} onRefresh={fetchData} providers={providers} />+ )}+ {activeTab === 'agents' && (+ <AgentsTab agents={agents} onRefresh={fetchData} liveOutputs={liveOutputs} />+ )}+ {activeTab === 'scripts' && (+ <ScriptsTab scripts={scripts} onRefresh={fetchData} />+ )}+ {activeTab === 'memory' && (+ <MemoryTab />+ )}+ {activeTab === 'health' && (+ <HealthTab health={health} onCheck={handleHealthCheck} />+ )}+ {activeTab === 'config' && (+ <ConfigTab config={status?.config} onUpdate={fetchData} onEvaluate={handleForceEvaluate} />+ )}+ </div>+ </div>+ );+}++function StatusIndicator({ running }) {+ return (+ <div className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-sm ${+ running+ ? 'bg-port-success/20 text-port-success'+ : 'bg-gray-700 text-gray-400'+ }`}>+ <span className={`w-2 h-2 rounded-full ${running ? 'bg-port-success animate-pulse' : 'bg-gray-500'}`} />+ {running ? 'Running' : 'Stopped'}+ </div>+ );+}++function StatCard({ label, value, icon, active, activeLabel }) {+ return (+ <div className={`bg-port-card border rounded-lg p-4 transition-all ${+ active ? 'border-port-accent shadow-lg shadow-port-accent/20' : 'border-port-border'+ }`}>+ <div className="flex items-center justify-between mb-2">+ <span className="text-sm text-gray-500">{label}</span>+ <div className={active ? 'animate-pulse' : ''}>+ {icon}+ </div>+ </div>+ <div className="text-2xl font-bold text-white">{value}</div>+ {active && activeLabel && (+ <div className="text-xs text-port-accent mt-1 truncate animate-pulse">+ {activeLabel}+ </div>+ )}+ </div>+ );+}++function TasksTab({ tasks, onRefresh, providers }) {+ const [showAddTask, setShowAddTask] = useState(false);+ const [newTask, setNewTask] = useState({ id: '', description: '', context: '', model: '', provider: '' });+ const [userTasksLocal, setUserTasksLocal] = useState([]);+ const userTasks = tasks.user?.tasks || [];+ const cosTasks = tasks.cos?.tasks || [];++ // Keep local state in sync with server state+ useEffect(() => {+ setUserTasksLocal(userTasks);+ }, [userTasks]);++ // Drag and drop sensors+ const sensors = useSensors(+ useSensor(PointerSensor, {+ activationConstraint: { distance: 8 },+ }),+ useSensor(KeyboardSensor, {+ coordinateGetter: sortableKeyboardCoordinates,+ })+ );++ const handleDragEnd = async (event) => {+ const { active, over } = event;+ if (!over || active.id === over.id) return;++ const oldIndex = userTasksLocal.findIndex(t => t.id === active.id);+ const newIndex = userTasksLocal.findIndex(t => t.id === over.id);++ // Optimistically update local state+ const newOrder = arrayMove(userTasksLocal, oldIndex, newIndex);+ setUserTasksLocal(newOrder);++ // Persist to server+ const taskIds = newOrder.map(t => t.id);+ const result = await api.reorderCosTasks(taskIds).catch(err => {+ toast.error(err.message);+ setUserTasksLocal(userTasks); // Revert on error+ return null;+ });+ if (result?.success) {+ toast.success('Tasks reordered');+ onRefresh();+ }+ };++ // Get models for selected provider+ const selectedProvider = providers?.find(p => p.id === newTask.provider);+ const availableModels = selectedProvider?.models || [];++ const handleAddTask = async () => {+ if (!newTask.description.trim()) {+ toast.error('Description is required');+ return;+ }++ const taskId = newTask.id.trim() || `task-${Date.now()}`;+ await api.addCosTask({+ id: taskId,+ description: newTask.description,+ context: newTask.context,+ model: newTask.model || undefined,+ provider: newTask.provider || undefined+ }).catch(err => {+ toast.error(err.message);+ return;+ });++ toast.success('Task added');+ setNewTask({ id: '', description: '', context: '', model: '', provider: '' });+ setShowAddTask(false);+ onRefresh();+ };++ return (+ <div className="space-y-6">+ {/* User Tasks */}+ <div>+ <div className="flex items-center justify-between mb-3">+ <h3 className="text-lg font-semibold text-white">User Tasks (TASKS.md)</h3>+ <div className="flex items-center gap-2">+ <button+ onClick={() => setShowAddTask(!showAddTask)}+ className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors"+ >+ <Plus size={16} />+ Add Task+ </button>+ <button+ onClick={onRefresh}+ className="text-gray-500 hover:text-white transition-colors"+ >+ <RefreshCw size={16} />+ </button>+ </div>+ </div>++ {/* Add Task Form */}+ {showAddTask && (+ <div className="bg-port-card border border-port-accent/50 rounded-lg p-4 mb-4">+ <div className="space-y-3">+ <input+ type="text"+ placeholder="Task ID (auto-generated if empty)"+ value={newTask.id}+ onChange={e => setNewTask(t => ({ ...t, id: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <input+ type="text"+ placeholder="Task description *"+ value={newTask.description}+ onChange={e => setNewTask(t => ({ ...t, description: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <input+ type="text"+ placeholder="Context (optional)"+ value={newTask.context}+ onChange={e => setNewTask(t => ({ ...t, context: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <div className="flex gap-3">+ <select+ value={newTask.provider}+ onChange={e => setNewTask(t => ({ ...t, provider: e.target.value, model: '' }))}+ className="w-40 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="">Auto (default)</option>+ {providers?.filter(p => p.enabled).map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ <select+ value={newTask.model}+ onChange={e => setNewTask(t => ({ ...t, model: e.target.value }))}+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ disabled={!newTask.provider}+ >+ <option value="">{newTask.provider ? 'Select model...' : 'Select provider first'}</option>+ {availableModels.map(m => (+ <option key={m} value={m}>{m.replace('claude-', '').replace(/-\d+$/, '')}</option>+ ))}+ </select>+ </div>+ <div className="flex justify-end gap-2">+ <button+ onClick={() => setShowAddTask(false)}+ className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={handleAddTask}+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors"+ >+ <Plus size={14} />+ Add+ </button>+ </div>+ </div>+ </div>+ )}++ {userTasksLocal.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">+ No user tasks. Click "Add Task" or edit TASKS.md directly.+ </div>+ ) : (+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ onDragEnd={handleDragEnd}+ >+ <SortableContext+ items={userTasksLocal.map(t => t.id)}+ strategy={verticalListSortingStrategy}+ >+ <div className="space-y-2">+ {userTasksLocal.map(task => (+ <SortableTaskItem key={task.id} task={task} onRefresh={onRefresh} providers={providers} />+ ))}+ </div>+ </SortableContext>+ </DndContext>+ )}+ </div>++ {/* System Tasks */}+ <div>+ <h3 className="text-lg font-semibold text-white mb-3">System Tasks (COS-TASKS.md)</h3>++ {cosTasks.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">+ No system tasks.+ </div>+ ) : (+ <div className="space-y-2">+ {cosTasks.map(task => (+ <TaskItem key={task.id} task={task} isSystem onRefresh={onRefresh} providers={providers} />+ ))}+ </div>+ )}+ </div>++ {/* Awaiting Approval */}+ {tasks.cos?.awaitingApproval?.length > 0 && (+ <div>+ <h3 className="text-lg font-semibold text-yellow-500 mb-3">Awaiting Approval</h3>+ <div className="space-y-2">+ {tasks.cos.awaitingApproval.map(task => (+ <TaskItem key={task.id} task={task} awaitingApproval onRefresh={onRefresh} providers={providers} />+ ))}+ </div>+ </div>+ )}+ </div>+ );+}++function SortableTaskItem({ task, onRefresh, providers }) {+ const {+ attributes,+ listeners,+ setNodeRef,+ transform,+ transition,+ isDragging,+ } = useSortable({ id: task.id });++ const style = {+ transform: CSS.Transform.toString(transform),+ transition,+ opacity: isDragging ? 0.5 : 1,+ zIndex: isDragging ? 1000 : 'auto',+ };++ return (+ <div ref={setNodeRef} style={style}>+ <TaskItem+ task={task}+ onRefresh={onRefresh}+ providers={providers}+ dragHandleProps={{ ...attributes, ...listeners }}+ />+ </div>+ );+}++function TaskItem({ task, isSystem, awaitingApproval, onRefresh, providers, dragHandleProps }) {+ const [editing, setEditing] = useState(false);+ const [editData, setEditData] = useState({+ description: task.description,+ context: task.metadata?.context || '',+ model: task.metadata?.model || '',+ provider: task.metadata?.provider || ''+ });++ // Get models for selected provider in edit mode+ const editProvider = providers?.find(p => p.id === editData.provider);+ const editModels = editProvider?.models || [];++ const statusIcons = {+ pending: <Clock size={16} className="text-yellow-500" />,+ in_progress: <Activity size={16} className="text-port-accent animate-pulse" />,+ completed: <CheckCircle size={16} className="text-port-success" />,+ blocked: <Ban size={16} className="text-port-error" />+ };++ const handleStatusChange = async (newStatus) => {+ await api.updateCosTask(task.id, { status: newStatus }).catch(err => toast.error(err.message));+ toast.success(`Task marked as ${newStatus}`);+ onRefresh();+ };++ const handleSave = async () => {+ await api.updateCosTask(task.id, editData).catch(err => toast.error(err.message));+ toast.success('Task updated');+ setEditing(false);+ onRefresh();+ };++ const handleDelete = async () => {+ await api.deleteCosTask(task.id).catch(err => toast.error(err.message));+ toast.success('Task deleted');+ onRefresh();+ };++ const handleApprove = async () => {+ await api.approveCosTask(task.id).catch(err => toast.error(err.message));+ toast.success('Task approved');+ onRefresh();+ };++ return (+ <div className={`bg-port-card border rounded-lg p-4 group ${+ awaitingApproval ? 'border-yellow-500/50' : 'border-port-border'+ }`}>+ <div className="flex items-start gap-3">+ {/* Drag handle - only show for user tasks (not system or awaiting approval) */}+ {dragHandleProps && !isSystem && !awaitingApproval && (+ <button+ {...dragHandleProps}+ className="mt-0.5 cursor-grab active:cursor-grabbing text-gray-500 hover:text-gray-300 transition-colors touch-none"+ title="Drag to reorder"+ >+ <GripVertical size={16} />+ </button>+ )}+ <button+ onClick={() => handleStatusChange(task.status === 'completed' ? 'pending' : 'completed')}+ className="mt-0.5 hover:scale-110 transition-transform"+ title={task.status === 'completed' ? 'Mark as pending' : 'Mark as completed'}+ >+ {statusIcons[task.status]}+ </button>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 mb-1 flex-wrap">+ <span className="text-sm font-mono text-gray-500">{task.id}</span>+ {isSystem && task.autoApproved && (+ <span className="px-2 py-0.5 rounded text-xs bg-port-success/20 text-port-success">AUTO</span>+ )}+ {awaitingApproval && (+ <button+ onClick={handleApprove}+ className="px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors"+ >+ APPROVE+ </button>+ )}+ </div>++ {editing ? (+ <div className="space-y-2">+ <input+ type="text"+ value={editData.description}+ onChange={e => setEditData(d => ({ ...d, description: e.target.value }))}+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ <input+ type="text"+ placeholder="Context"+ value={editData.context}+ onChange={e => setEditData(d => ({ ...d, context: e.target.value }))}+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ <div className="flex gap-2">+ <select+ value={editData.provider}+ onChange={e => setEditData(d => ({ ...d, provider: e.target.value, model: '' }))}+ className="w-36 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ >+ <option value="">Auto</option>+ {providers?.filter(p => p.enabled).map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ <select+ value={editData.model}+ onChange={e => setEditData(d => ({ ...d, model: e.target.value }))}+ className="flex-1 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ disabled={!editData.provider}+ >+ <option value="">{editData.provider ? 'Auto' : 'Select provider'}</option>+ {editModels.map(m => (+ <option key={m} value={m}>{m.replace('claude-', '').replace(/-\d+$/, '')}</option>+ ))}+ </select>+ </div>+ <div className="flex gap-2">+ <button+ onClick={handleSave}+ className="flex items-center gap-1 text-xs text-port-success hover:text-port-success/80"+ >+ <Save size={12} /> Save+ </button>+ <button+ onClick={() => setEditing(false)}+ className="flex items-center gap-1 text-xs text-gray-500 hover:text-white"+ >+ <X size={12} /> Cancel+ </button>+ </div>+ </div>+ ) : (+ <>+ <p className="text-white">{task.description}</p>+ {task.metadata?.context && (+ <p className="text-sm text-gray-500 mt-1">{task.metadata.context}</p>+ )}+ {(task.metadata?.model || task.metadata?.provider) && (+ <div className="flex items-center gap-2 mt-1">+ {task.metadata?.model && (+ <span className="px-1.5 py-0.5 text-xs bg-purple-500/20 text-purple-400 rounded font-mono">+ {task.metadata.model}+ </span>+ )}+ {task.metadata?.provider && (+ <span className="px-1.5 py-0.5 text-xs bg-cyan-500/20 text-cyan-400 rounded">+ {task.metadata.provider}+ </span>+ )}+ </div>+ )}+ </>+ )}+ </div>++ {/* Action buttons */}+ <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">+ {!editing && (+ <>+ <button+ onClick={() => setEditing(true)}+ className="p-1 text-gray-500 hover:text-white transition-colors"+ title="Edit"+ >+ <Edit3 size={14} />+ </button>+ <button+ onClick={handleDelete}+ className="p-1 text-gray-500 hover:text-port-error transition-colors"+ title="Delete"+ >+ <Trash2 size={14} />+ </button>+ </>+ )}+ </div>+ </div>+ </div>+ );+}++function AgentsTab({ agents, onRefresh, liveOutputs }) {+ const handleTerminate = async (agentId) => {+ await api.terminateCosAgent(agentId).catch(err => toast.error(err.message));+ toast.success('Terminate signal sent');+ onRefresh();+ };++ const handleDelete = async (agentId) => {+ await api.deleteCosAgent(agentId).catch(err => toast.error(err.message));+ toast.success('Agent removed');+ onRefresh();+ };++ const handleClearCompleted = async () => {+ await api.clearCompletedCosAgents().catch(err => toast.error(err.message));+ toast.success('Cleared completed agents');+ onRefresh();+ };++ const runningAgents = agents.filter(a => a.status === 'running');+ // Sort completed agents by completion time (most recent first)+ const completedAgents = agents+ .filter(a => a.status === 'completed')+ .sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));++ return (+ <div className="space-y-6">+ {/* Active Agents */}+ <div>+ <div className="flex items-center justify-between mb-3">+ <h3 className="text-lg font-semibold text-white">Active Agents</h3>+ {runningAgents.length > 0 && (+ <span className="text-sm text-port-accent animate-pulse">+ {runningAgents.length} running+ </span>+ )}+ </div>+ {runningAgents.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">+ No active agents. Start CoS and add tasks to see agents working.+ </div>+ ) : (+ <div className="space-y-2">+ {runningAgents.map(agent => (+ <AgentCard+ key={agent.id}+ agent={agent}+ onTerminate={handleTerminate}+ liveOutput={liveOutputs[agent.id]}+ />+ ))}+ </div>+ )}+ </div>++ {/* Completed Agents */}+ {completedAgents.length > 0 && (+ <div>+ <div className="flex items-center justify-between mb-3">+ <h3 className="text-lg font-semibold text-white">+ Completed Agents+ <span className="text-sm text-gray-500 font-normal ml-2">+ ({completedAgents.length} total)+ </span>+ </h3>+ <button+ onClick={handleClearCompleted}+ className="flex items-center gap-1 text-sm text-gray-500 hover:text-port-error transition-colors"+ >+ <Trash2 size={14} />+ Clear+ </button>+ </div>+ <div className="space-y-2">+ {completedAgents.slice(0, 15).map(agent => (+ <AgentCard key={agent.id} agent={agent} completed onDelete={handleDelete} />+ ))}+ {completedAgents.length > 15 && (+ <div className="text-center text-sm text-gray-500 py-2">+ + {completedAgents.length - 15} more completed agents+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ );+}++function AgentCard({ agent, onTerminate, onDelete, completed, liveOutput }) {+ const [expanded, setExpanded] = useState(false);+ const [now, setNow] = useState(Date.now());++ // Determine if this is a system agent (health check, etc.)+ const isSystemAgent = agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');++ // Update duration display for running agents+ useEffect(() => {+ if (completed) return;+ const interval = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(interval);+ }, [completed]);++ const duration = agent.completedAt+ ? new Date(agent.completedAt) - new Date(agent.startedAt)+ : now - new Date(agent.startedAt);++ const formatDuration = (ms) => {+ const seconds = Math.floor(ms / 1000);+ const minutes = Math.floor(seconds / 60);+ if (minutes > 0) return `${minutes}m ${seconds % 60}s`;+ return `${seconds}s`;+ };++ // Combine stored output with live output+ const output = liveOutput || agent.output || [];+ const lastOutput = output.length > 0 ? output[output.length - 1]?.line : null;++ return (+ <div className={`bg-port-card border rounded-lg overflow-hidden ${+ completed+ ? isSystemAgent ? 'border-port-border opacity-50' : 'border-port-border opacity-75'+ : 'border-port-accent/50'+ }`}>+ <div className="p-4">+ <div className="flex items-center justify-between mb-2">+ <div className="flex items-center gap-2 flex-wrap">+ <Cpu size={16} className={completed ? 'text-gray-500' : 'text-port-accent animate-pulse'} />+ <span className="font-mono text-sm text-gray-400">{agent.id}</span>+ {isSystemAgent && (+ <span className="px-1.5 py-0.5 text-xs bg-gray-500/20 text-gray-400 rounded">SYS</span>+ )}+ {agent.metadata?.model && (+ <span className={`px-2 py-0.5 text-xs rounded ${+ agent.metadata.modelTier === 'heavy' ? 'bg-purple-500/20 text-purple-400' :+ agent.metadata.modelTier === 'light' ? 'bg-green-500/20 text-green-400' :+ 'bg-blue-500/20 text-blue-400'+ }`} title={agent.metadata.modelReason}>+ {agent.metadata.model.replace('claude-', '').replace(/-\d+$/, '')}+ </span>+ )}+ {!completed && (+ <span className={`px-2 py-0.5 text-xs rounded animate-pulse ${+ agent.metadata?.phase === 'initializing' ? 'bg-yellow-500/20 text-yellow-400' :+ agent.metadata?.phase === 'working' ? 'bg-port-accent/20 text-port-accent' :+ 'bg-port-accent/20 text-port-accent'+ }`}>+ {agent.metadata?.phase === 'initializing' ? 'Initializing' :+ agent.metadata?.phase === 'working' ? 'Working' :+ 'Running'}+ </span>+ )}+ </div>+ <div className="flex items-center gap-2">+ <span className="text-sm text-gray-500">{formatDuration(duration)}</span>+ {output.length > 0 && (+ <button+ onClick={() => setExpanded(!expanded)}+ className="text-gray-500 hover:text-white transition-colors text-xs"+ >+ {expanded ? 'Hide' : 'Show'} Output+ </button>+ )}+ {!completed && onTerminate && (+ <button+ onClick={() => onTerminate(agent.id)}+ className="text-gray-500 hover:text-port-error transition-colors"+ title="Terminate"+ >+ <Square size={14} />+ </button>+ )}+ {completed && onDelete && (+ <button+ onClick={() => onDelete(agent.id)}+ className="text-gray-500 hover:text-port-error transition-colors"+ title="Remove"+ >+ <Trash2 size={14} />+ </button>+ )}+ </div>+ </div>+ <p className="text-white text-sm mb-2">{agent.metadata?.taskDescription || agent.taskId}</p>++ {/* Status / Last output line */}+ {!completed && lastOutput && (+ <div className="text-xs text-gray-500 font-mono truncate bg-port-bg/50 px-2 py-1 rounded">+ {lastOutput.substring(0, 100)}...+ </div>+ )}++ {agent.result && (+ <div className={`text-sm flex items-center gap-2 ${agent.result.success ? 'text-port-success' : 'text-port-error'}`}>+ {agent.result.success ? (+ <><CheckCircle size={14} /> Completed successfully</>+ ) : (+ <><AlertCircle size={14} /> {agent.result.error || 'Failed'}</>+ )}+ </div>+ )}+ </div>++ {/* Expanded output view */}+ {expanded && output.length > 0 && (+ <div className="border-t border-port-border bg-port-bg/50 p-3 max-h-64 overflow-y-auto">+ <pre className="text-xs font-mono text-gray-400 whitespace-pre-wrap">+ {output.map((o, i) => (+ <div key={i} className="py-0.5">+ {o.line}+ </div>+ ))}+ </pre>+ </div>+ )}+ </div>+ );+}++function ScriptsTab({ scripts, onRefresh }) {+ const [showCreate, setShowCreate] = useState(false);+ const [newScript, setNewScript] = useState({+ name: '',+ description: '',+ command: '',+ schedule: 'on-demand',+ cronExpression: '',+ triggerAction: 'log-only',+ triggerPrompt: '',+ triggerPriority: 'MEDIUM'+ });++ const handleCreate = async () => {+ if (!newScript.name.trim() || !newScript.command.trim()) {+ toast.error('Name and command are required');+ return;+ }++ await api.createCosScript(newScript).catch(err => {+ toast.error(err.message);+ return;+ });++ toast.success('Script created');+ setNewScript({+ name: '',+ description: '',+ command: '',+ schedule: 'on-demand',+ cronExpression: '',+ triggerAction: 'log-only',+ triggerPrompt: '',+ triggerPriority: 'MEDIUM'+ });+ setShowCreate(false);+ onRefresh();+ };++ const handleRun = async (id) => {+ toast.loading('Running script...', { id: 'script-run' });+ const result = await api.runCosScript(id).catch(err => {+ toast.error(err.message, { id: 'script-run' });+ return null;+ });+ if (result) {+ if (result.success) {+ toast.success('Script completed', { id: 'script-run' });+ } else {+ toast.error(`Script failed: ${result.error || 'Unknown error'}`, { id: 'script-run' });+ }+ onRefresh();+ }+ };++ const handleToggle = async (script) => {+ await api.updateCosScript(script.id, { enabled: !script.enabled }).catch(err => toast.error(err.message));+ toast.success(script.enabled ? 'Script disabled' : 'Script enabled');+ onRefresh();+ };++ const handleDelete = async (id) => {+ await api.deleteCosScript(id).catch(err => toast.error(err.message));+ toast.success('Script deleted');+ onRefresh();+ };++ return (+ <div className="space-y-6">+ <div className="flex items-center justify-between mb-3">+ <h3 className="text-lg font-semibold text-white">Scheduled Scripts</h3>+ <div className="flex items-center gap-2">+ <button+ onClick={() => setShowCreate(!showCreate)}+ className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors"+ >+ <Plus size={16} />+ New Script+ </button>+ <button+ onClick={onRefresh}+ className="text-gray-500 hover:text-white transition-colors"+ >+ <RefreshCw size={16} />+ </button>+ </div>+ </div>++ {/* Create Script Form */}+ {showCreate && (+ <div className="bg-port-card border border-port-accent/50 rounded-lg p-4 mb-4">+ <div className="space-y-3">+ <div className="flex gap-3">+ <input+ type="text"+ placeholder="Script name *"+ value={newScript.name}+ onChange={e => setNewScript(s => ({ ...s, name: e.target.value }))}+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <select+ value={newScript.schedule}+ onChange={e => setNewScript(s => ({ ...s, schedule: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="on-demand">On Demand</option>+ <option value="every-5-min">Every 5 min</option>+ <option value="every-15-min">Every 15 min</option>+ <option value="hourly">Hourly</option>+ <option value="daily">Daily</option>+ <option value="weekly">Weekly</option>+ </select>+ </div>+ <input+ type="text"+ placeholder="Description"+ value={newScript.description}+ onChange={e => setNewScript(s => ({ ...s, description: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <textarea+ placeholder="Shell command *"+ value={newScript.command}+ onChange={e => setNewScript(s => ({ ...s, command: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono h-20"+ />+ <div className="flex gap-3">+ <select+ value={newScript.triggerAction}+ onChange={e => setNewScript(s => ({ ...s, triggerAction: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="log-only">Log Only</option>+ <option value="spawn-agent">Spawn Agent</option>+ </select>+ <select+ value={newScript.triggerPriority}+ onChange={e => setNewScript(s => ({ ...s, triggerPriority: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="LOW">LOW</option>+ <option value="MEDIUM">MEDIUM</option>+ <option value="HIGH">HIGH</option>+ <option value="CRITICAL">CRITICAL</option>+ </select>+ </div>+ {newScript.triggerAction === 'spawn-agent' && (+ <textarea+ placeholder="Prompt for agent when triggered"+ value={newScript.triggerPrompt}+ onChange={e => setNewScript(s => ({ ...s, triggerPrompt: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm h-16"+ />+ )}+ <div className="flex justify-end gap-2">+ <button+ onClick={() => setShowCreate(false)}+ className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={handleCreate}+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors"+ >+ <Plus size={14} />+ Create+ </button>+ </div>+ </div>+ </div>+ )}++ {/* Scripts List */}+ {scripts.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">+ No scripts configured. Create a script to automate tasks.+ </div>+ ) : (+ <div className="space-y-2">+ {scripts.map(script => (+ <ScriptCard+ key={script.id}+ script={script}+ onRun={handleRun}+ onToggle={handleToggle}+ onDelete={handleDelete}+ onUpdate={onRefresh}+ />+ ))}+ </div>+ )}+ </div>+ );+}++function ScriptCard({ script, onRun, onToggle, onDelete, onUpdate }) {+ const [expanded, setExpanded] = useState(false);+ const [editing, setEditing] = useState(false);+ const [editData, setEditData] = useState({+ name: script.name,+ description: script.description || '',+ command: script.command,+ schedule: script.schedule || 'on-demand',+ triggerAction: script.triggerAction || 'log-only',+ triggerPrompt: script.triggerPrompt || '',+ triggerPriority: script.triggerPriority || 'MEDIUM'+ });++ const handleSave = async () => {+ if (!editData.name.trim() || !editData.command.trim()) {+ toast.error('Name and command are required');+ return;+ }+ await api.updateCosScript(script.id, editData).catch(err => toast.error(err.message));+ toast.success('Script updated');+ setEditing(false);+ onUpdate?.();+ };++ const formatTime = (timestamp) => {+ if (!timestamp) return 'Never';+ const date = new Date(timestamp);+ const now = new Date();+ const diff = now - date;+ if (diff < 60000) return 'Just now';+ if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;+ if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;+ return date.toLocaleDateString();+ };++ const scheduleLabels = {+ 'on-demand': 'On Demand',+ 'every-5-min': 'Every 5 min',+ 'every-15-min': 'Every 15 min',+ 'every-30-min': 'Every 30 min',+ 'hourly': 'Hourly',+ 'every-6-hours': 'Every 6 hours',+ 'daily': 'Daily',+ 'weekly': 'Weekly'+ };++ return (+ <div className={`bg-port-card border rounded-lg overflow-hidden ${+ script.enabled ? 'border-port-border' : 'border-port-border opacity-60'+ }`}>+ <div className="p-4">+ <div className="flex items-center justify-between mb-2">+ <div className="flex items-center gap-2">+ <Terminal size={16} className={script.enabled ? 'text-port-accent' : 'text-gray-500'} />+ <span className="font-medium text-white">{script.name}</span>+ <span className={`px-2 py-0.5 text-xs rounded ${+ script.schedule === 'on-demand' ? 'bg-gray-500/20 text-gray-400' : 'bg-port-accent/20 text-port-accent'+ }`}>+ {scheduleLabels[script.schedule] || script.schedule}+ </span>+ {script.triggerAction === 'spawn-agent' && (+ <span className="px-2 py-0.5 text-xs bg-purple-500/20 text-purple-400 rounded">+ <Zap size={10} className="inline mr-1" />+ Triggers Agent+ </span>+ )}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => onRun(script.id)}+ className="p-1.5 text-gray-500 hover:text-port-success transition-colors"+ title="Run now"+ >+ <Play size={14} />+ </button>+ <button+ onClick={() => setEditing(true)}+ className="p-1.5 text-gray-500 hover:text-white transition-colors"+ title="Edit"+ >+ <Edit3 size={14} />+ </button>+ <button+ onClick={() => onToggle(script)}+ className={`p-1.5 transition-colors ${+ script.enabled ? 'text-port-success hover:text-gray-500' : 'text-gray-500 hover:text-port-success'+ }`}+ title={script.enabled ? 'Disable' : 'Enable'}+ >+ {script.enabled ? <CheckCircle size={14} /> : <Ban size={14} />}+ </button>+ <button+ onClick={() => onDelete(script.id)}+ className="p-1.5 text-gray-500 hover:text-port-error transition-colors"+ title="Delete"+ >+ <Trash2 size={14} />+ </button>+ </div>+ </div>++ {/* Edit Form */}+ {editing ? (+ <div className="space-y-3 mt-3">+ <div className="flex gap-3">+ <input+ type="text"+ placeholder="Script name *"+ value={editData.name}+ onChange={e => setEditData(d => ({ ...d, name: e.target.value }))}+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <select+ value={editData.schedule}+ onChange={e => setEditData(d => ({ ...d, schedule: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="on-demand">On Demand</option>+ <option value="every-5-min">Every 5 min</option>+ <option value="every-15-min">Every 15 min</option>+ <option value="hourly">Hourly</option>+ <option value="daily">Daily</option>+ <option value="weekly">Weekly</option>+ </select>+ </div>+ <input+ type="text"+ placeholder="Description"+ value={editData.description}+ onChange={e => setEditData(d => ({ ...d, description: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ <textarea+ placeholder="Shell command *"+ value={editData.command}+ onChange={e => setEditData(d => ({ ...d, command: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono h-20"+ />+ <div className="flex gap-3">+ <select+ value={editData.triggerAction}+ onChange={e => setEditData(d => ({ ...d, triggerAction: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="log-only">Log Only</option>+ <option value="spawn-agent">Spawn Agent</option>+ </select>+ <select+ value={editData.triggerPriority}+ onChange={e => setEditData(d => ({ ...d, triggerPriority: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value="LOW">LOW</option>+ <option value="MEDIUM">MEDIUM</option>+ <option value="HIGH">HIGH</option>+ <option value="CRITICAL">CRITICAL</option>+ </select>+ </div>+ {editData.triggerAction === 'spawn-agent' && (+ <textarea+ placeholder="Prompt for agent when triggered"+ value={editData.triggerPrompt}+ onChange={e => setEditData(d => ({ ...d, triggerPrompt: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm h-16"+ />+ )}+ <div className="flex justify-end gap-2">+ <button+ onClick={() => setEditing(false)}+ className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={handleSave}+ className="flex items-center gap-1 px-3 py-1.5 bg-port-success/20 hover:bg-port-success/30 text-port-success rounded-lg text-sm transition-colors"+ >+ <Save size={14} />+ Save+ </button>+ </div>+ </div>+ ) : (+ <>+ {script.description && (+ <p className="text-sm text-gray-400 mb-2">{script.description}</p>+ )}++ <div className="flex items-center gap-4 text-xs text-gray-500">+ <span>Last run: {formatTime(script.lastRun)}</span>+ {script.lastExitCode !== null && (+ <span className={script.lastExitCode === 0 ? 'text-port-success' : 'text-port-error'}>+ Exit: {script.lastExitCode}+ </span>+ )}+ <span>Runs: {script.runCount || 0}</span>+ {script.lastOutput && (+ <button+ onClick={() => setExpanded(!expanded)}+ className="text-port-accent hover:text-port-accent/80"+ >+ {expanded ? 'Hide' : 'Show'} output+ </button>+ )}+ </div>+ </>+ )}+ </div>++ {/* Command preview */}+ {!editing && (+ <div className="px-4 pb-3">+ <code className="text-xs text-gray-500 font-mono bg-port-bg/50 px-2 py-1 rounded block truncate">+ {script.command}+ </code>+ </div>+ )}++ {/* Expanded output */}+ {expanded && script.lastOutput && (+ <div className="border-t border-port-border bg-port-bg/50 p-3 max-h-48 overflow-y-auto">+ <pre className="text-xs font-mono text-gray-400 whitespace-pre-wrap">+ {script.lastOutput}+ </pre>+ </div>+ )}+ </div>+ );+}++function MemoryTab() {+ const [memories, setMemories] = useState([]);+ const [stats, setStats] = useState(null);+ const [loading, setLoading] = useState(true);+ const [searchQuery, setSearchQuery] = useState('');+ const [searchResults, setSearchResults] = useState(null);+ const [view, setView] = useState('list'); // list, timeline, graph+ const [filters, setFilters] = useState({ types: [], categories: [] });+ const [categories, setCategories] = useState([]);+ const [embeddingStatus, setEmbeddingStatus] = useState(null);++ const MEMORY_TYPES = ['fact', 'learning', 'observation', 'decision', 'preference', 'context'];+ const TYPE_COLORS = {+ fact: 'bg-blue-500/20 text-blue-400 border-blue-500/30',+ learning: 'bg-green-500/20 text-green-400 border-green-500/30',+ observation: 'bg-purple-500/20 text-purple-400 border-purple-500/30',+ decision: 'bg-orange-500/20 text-orange-400 border-orange-500/30',+ preference: 'bg-pink-500/20 text-pink-400 border-pink-500/30',+ context: 'bg-gray-500/20 text-gray-400 border-gray-500/30'+ };++ const fetchData = useCallback(async () => {+ setLoading(true);+ const [memoriesRes, statsRes, catsRes, embRes] = await Promise.all([+ api.getMemories({ limit: 100, ...filters }).catch(() => ({ memories: [] })),+ api.getMemoryStats().catch(() => null),+ api.getMemoryCategories().catch(() => []),+ api.getEmbeddingStatus().catch(() => null)+ ]);+ setMemories(memoriesRes.memories || []);+ setStats(statsRes);+ setCategories(catsRes);+ setEmbeddingStatus(embRes);+ setLoading(false);+ }, [filters]);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ const handleSearch = async () => {+ if (!searchQuery.trim()) {+ setSearchResults(null);+ return;+ }+ setLoading(true);+ const results = await api.searchMemories(searchQuery, { limit: 20 }).catch(() => ({ memories: [] }));+ setSearchResults(results.memories || []);+ setLoading(false);+ };++ const handleDelete = async (id) => {+ await api.deleteMemory(id);+ toast.success('Memory archived');+ fetchData();+ };++ const displayMemories = searchResults || memories;++ return (+ <div className="space-y-6">+ {/* Header */}+ <div className="flex items-center justify-between">+ <div>+ <h3 className="text-lg font-semibold text-white">Memory System</h3>+ <p className="text-sm text-gray-500">+ {stats?.active || 0} active memories+ {embeddingStatus?.available ? ' • LM Studio connected' : ' • LM Studio offline'}+ </p>+ </div>+ <div className="flex gap-2">+ {['list', 'timeline', 'graph'].map(v => (+ <button+ key={v}+ onClick={() => setView(v)}+ className={`px-3 py-1.5 text-sm rounded-lg transition-colors ${+ view === v ? 'bg-port-accent text-white' : 'bg-port-border text-gray-400 hover:text-white'+ }`}+ >+ {v.charAt(0).toUpperCase() + v.slice(1)}+ </button>+ ))}+ </div>+ </div>++ {/* Search */}+ <div className="flex gap-2">+ <input+ type="text"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ onKeyDown={(e) => e.key === 'Enter' && handleSearch()}+ placeholder="Search memories semantically..."+ className="flex-1 bg-port-card border border-port-border rounded-lg px-4 py-2 text-white placeholder-gray-500 focus:border-port-accent outline-none"+ />+ <button+ onClick={handleSearch}+ className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"+ >+ Search+ </button>+ {searchResults && (+ <button+ onClick={() => { setSearchResults(null); setSearchQuery(''); }}+ className="px-3 py-2 bg-port-border text-gray-400 hover:text-white rounded-lg transition-colors"+ >+ <X size={16} />+ </button>+ )}+ </div>++ {/* Type Filters */}+ <div className="flex flex-wrap gap-2">+ {MEMORY_TYPES.map(type => (+ <button+ key={type}+ onClick={() => {+ const newTypes = filters.types.includes(type)+ ? filters.types.filter(t => t !== type)+ : [...filters.types, type];+ setFilters({ ...filters, types: newTypes });+ }}+ className={`px-3 py-1 text-xs rounded-full border transition-colors ${+ filters.types.includes(type) ? TYPE_COLORS[type] : 'border-port-border text-gray-500 hover:text-gray-300'+ }`}+ >+ {type}+ </button>+ ))}+ </div>++ {/* Stats Row */}+ {stats && (+ <div className="grid grid-cols-3 md:grid-cols-6 gap-2">+ {Object.entries(stats.byType || {}).map(([type, count]) => (+ <div key={type} className={`p-2 rounded-lg border text-center ${TYPE_COLORS[type] || 'border-port-border'}`}>+ <div className="text-lg font-bold">{count}</div>+ <div className="text-xs opacity-75">{type}</div>+ </div>+ ))}+ </div>+ )}++ {/* Content */}+ {loading ? (+ <div className="flex items-center justify-center py-12">+ <RefreshCw className="animate-spin text-port-accent" size={24} />+ </div>+ ) : view === 'list' ? (+ <div className="space-y-3">+ {displayMemories.length === 0 ? (+ <div className="text-center py-12 text-gray-500">+ {searchQuery ? 'No memories found for this search' : 'No memories yet. Memories are extracted from agent task completions.'}+ </div>+ ) : (+ displayMemories.map(memory => (+ <div key={memory.id} className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-start justify-between gap-4">+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 mb-2">+ <span className={`px-2 py-0.5 text-xs rounded-full border ${TYPE_COLORS[memory.type]}`}>+ {memory.type}+ </span>+ <span className="text-xs text-gray-500">{memory.category}</span>+ {memory.similarity && (+ <span className="text-xs text-port-accent">{(memory.similarity * 100).toFixed(0)}% match</span>+ )}+ </div>+ <p className="text-white text-sm">{memory.summary || memory.content?.substring(0, 200)}</p>+ {memory.tags?.length > 0 && (+ <div className="flex gap-1 mt-2">+ {memory.tags.map(tag => (+ <span key={tag} className="px-2 py-0.5 text-xs bg-port-border rounded text-gray-400">+ {tag}+ </span>+ ))}+ </div>+ )}+ <div className="text-xs text-gray-500 mt-2">+ {new Date(memory.createdAt).toLocaleDateString()} • importance: {((memory.importance || 0.5) * 100).toFixed(0)}%+ </div>+ </div>+ <button+ onClick={() => handleDelete(memory.id)}+ className="p-2 text-gray-500 hover:text-port-error transition-colors"+ >+ <Trash2 size={14} />+ </button>+ </div>+ </div>+ ))+ )}+ </div>+ ) : view === 'timeline' ? (+ <MemoryTimeline memories={memories} />+ ) : (+ <MemoryGraph />+ )}+ </div>+ );+}++function MemoryTimeline({ memories }) {+ const grouped = memories.reduce((acc, m) => {+ const date = m.createdAt?.split('T')[0] || 'Unknown';+ if (!acc[date]) acc[date] = [];+ acc[date].push(m);+ return acc;+ }, {});++ const dates = Object.keys(grouped).sort().reverse();++ return (+ <div className="space-y-6">+ {dates.map(date => (+ <div key={date}>+ <div className="text-sm font-medium text-gray-400 mb-2 sticky top-0 bg-port-bg py-1">+ {new Date(date).toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}+ </div>+ <div className="border-l border-port-border pl-4 space-y-3">+ {grouped[date].map(m => (+ <div key={m.id} className="relative">+ <div className="absolute -left-[21px] w-2 h-2 rounded-full bg-port-accent" />+ <div className="text-sm text-white">{m.summary}</div>+ <div className="text-xs text-gray-500 mt-1">{m.type} • {m.category}</div>+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ );+}++function MemoryGraph() {+ const [graphData, setGraphData] = useState(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ api.getMemoryGraph().then(setGraphData).catch(() => setGraphData(null)).finally(() => setLoading(false));+ }, []);++ if (loading) {+ return (+ <div className="flex items-center justify-center py-12">+ <RefreshCw className="animate-spin text-port-accent" size={24} />+ </div>+ );+ }++ if (!graphData || !graphData.nodes?.length) {+ return (+ <div className="text-center py-12 text-gray-500">+ No memory graph data available. Add more memories to see relationships.+ </div>+ );+ }++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 min-h-[400px]">+ <div className="text-center text-gray-500">+ <Brain size={48} className="mx-auto mb-4 text-port-accent/50" />+ <p>Graph visualization coming soon</p>+ <p className="text-sm mt-2">{graphData.nodes.length} nodes • {graphData.edges.length} connections</p>+ </div>+ </div>+ );+}++function HealthTab({ health, onCheck }) {+ return (+ <div className="space-y-6">+ <div className="flex items-center justify-between">+ <div>+ <h3 className="text-lg font-semibold text-white">System Health</h3>+ {health?.lastCheck && (+ <p className="text-sm text-gray-500">+ Last check: {new Date(health.lastCheck).toLocaleString()}+ </p>+ )}+ </div>+ <button+ onClick={onCheck}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"+ >+ <RefreshCw size={14} />+ Run Check+ </button>+ </div>++ {!health?.issues || health.issues.length === 0 ? (+ <div className="bg-port-success/10 border border-port-success/30 rounded-lg p-6 text-center">+ <CheckCircle className="w-12 h-12 text-port-success mx-auto mb-3" />+ <p className="text-port-success font-medium">All Systems Healthy</p>+ <p className="text-gray-500 text-sm mt-1">No issues detected</p>+ </div>+ ) : (+ <div className="space-y-2">+ {health.issues.map((issue, idx) => (+ <div+ key={idx}+ className={`border rounded-lg p-4 ${+ issue.type === 'error'+ ? 'bg-port-error/10 border-port-error/30'+ : 'bg-yellow-500/10 border-yellow-500/30'+ }`}+ >+ <div className="flex items-center gap-2 mb-1">+ <AlertCircle size={16} className={issue.type === 'error' ? 'text-port-error' : 'text-yellow-500'} />+ <span className={`text-sm font-medium uppercase ${+ issue.type === 'error' ? 'text-port-error' : 'text-yellow-500'+ }`}>+ {issue.category}+ </span>+ </div>+ <p className="text-white">{issue.message}</p>+ </div>+ ))}+ </div>+ )}+ </div>+ );+}++function ConfigTab({ config, onUpdate, onEvaluate }) {+ const [editing, setEditing] = useState(false);+ const [formData, setFormData] = useState({+ evaluationIntervalMs: config?.evaluationIntervalMs || 60000,+ healthCheckIntervalMs: config?.healthCheckIntervalMs || 900000,+ maxConcurrentAgents: config?.maxConcurrentAgents || 3,+ maxProcessMemoryMb: config?.maxProcessMemoryMb || 2048,+ autoStart: config?.autoStart || false+ });++ const handleSave = async () => {+ await api.updateCosConfig(formData).catch(err => toast.error(err.message));+ toast.success('Configuration updated');+ setEditing(false);+ onUpdate();+ };++ return (+ <div className="space-y-6">+ <div className="flex items-center justify-between">+ <h3 className="text-lg font-semibold text-white">Configuration</h3>+ <div className="flex gap-2">+ <button+ onClick={onEvaluate}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg transition-colors"+ >+ <Activity size={14} />+ Force Evaluate+ </button>+ {!editing ? (+ <button+ onClick={() => setEditing(true)}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"+ >+ <Settings size={14} />+ Edit+ </button>+ ) : (+ <button+ onClick={handleSave}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-success/20 hover:bg-port-success/30 text-port-success rounded-lg transition-colors"+ >+ <CheckCircle size={14} />+ Save+ </button>+ )}+ </div>+ </div>++ <div className="bg-port-card border border-port-border rounded-lg divide-y divide-port-border">+ <ConfigRow+ label="Evaluation Interval"+ value={`${formData.evaluationIntervalMs / 1000}s`}+ editing={editing}+ type="number"+ inputValue={formData.evaluationIntervalMs / 1000}+ onChange={v => setFormData(f => ({ ...f, evaluationIntervalMs: v * 1000 }))}+ suffix="seconds"+ />+ <ConfigRow+ label="Health Check Interval"+ value={`${formData.healthCheckIntervalMs / 60000}m`}+ editing={editing}+ type="number"+ inputValue={formData.healthCheckIntervalMs / 60000}+ onChange={v => setFormData(f => ({ ...f, healthCheckIntervalMs: v * 60000 }))}+ suffix="minutes"+ />+ <ConfigRow+ label="Max Concurrent Agents"+ value={formData.maxConcurrentAgents}+ editing={editing}+ type="number"+ inputValue={formData.maxConcurrentAgents}+ onChange={v => setFormData(f => ({ ...f, maxConcurrentAgents: v }))}+ />+ <ConfigRow+ label="Max Process Memory"+ value={`${formData.maxProcessMemoryMb} MB`}+ editing={editing}+ type="number"+ inputValue={formData.maxProcessMemoryMb}+ onChange={v => setFormData(f => ({ ...f, maxProcessMemoryMb: v }))}+ suffix="MB"+ />+ <ConfigRow+ label="Auto Start"+ value={formData.autoStart ? 'Enabled' : 'Disabled'}+ editing={editing}+ type="checkbox"+ inputValue={formData.autoStart}+ onChange={v => setFormData(f => ({ ...f, autoStart: v }))}+ />+ </div>++ {/* MCP Servers */}+ <div>+ <h4 className="text-sm font-medium text-gray-400 mb-2">MCP Servers</h4>+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ {config?.mcpServers?.map((mcp, idx) => (+ <div key={idx} className="flex items-center gap-2 text-sm">+ <span className="text-port-accent font-mono">{mcp.name}</span>+ <span className="text-gray-500">:</span>+ <span className="text-gray-400">{mcp.command} {mcp.args?.join(' ')}</span>+ </div>+ )) || <span className="text-gray-500">No MCP servers configured</span>}+ </div>+ </div>++ {/* Task Files */}+ <div>+ <h4 className="text-sm font-medium text-gray-400 mb-2">Task Files</h4>+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-2">+ <div className="flex items-center gap-2 text-sm">+ <FileText size={14} className="text-gray-500" />+ <span className="text-gray-400">User Tasks:</span>+ <span className="text-white font-mono">{config?.userTasksFile || 'TASKS.md'}</span>+ </div>+ <div className="flex items-center gap-2 text-sm">+ <FileText size={14} className="text-gray-500" />+ <span className="text-gray-400">System Tasks:</span>+ <span className="text-white font-mono">{config?.cosTasksFile || 'COS-TASKS.md'}</span>+ </div>+ </div>+ </div>+ </div>+ );+}++function ConfigRow({ label, value, editing, type, inputValue, onChange, suffix }) {+ return (+ <div className="flex items-center justify-between p-4">+ <span className="text-gray-400">{label}</span>+ {editing ? (+ <div className="flex items-center gap-2">+ {type === 'checkbox' ? (+ <input+ type="checkbox"+ checked={inputValue}+ onChange={e => onChange(e.target.checked)}+ className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ ) : (+ <>+ <input+ type="number"+ value={inputValue}+ onChange={e => onChange(parseInt(e.target.value) || 0)}+ className="w-24 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm text-right"+ />+ {suffix && <span className="text-gray-500 text-sm">{suffix}</span>}+ </>+ )}+ </div>+ ) : (+ <span className="text-white">{value}</span>+ )}+ </div>+ );+}diff --git a/client/src/pages/CreateApp.jsx b/client/src/pages/CreateApp.jsxindex 7a40877bb3..77d1f08162 100644--- a/client/src/pages/CreateApp.jsx+++ b/client/src/pages/CreateApp.jsx@@ -1,8 +1,10 @@import { useState, useEffect, useRef } from 'react';import { useNavigate } from 'react-router-dom';import { io } from 'socket.io-client';-import { CheckCircle, Circle, Loader, AlertCircle, Play } from 'lucide-react';+import { CheckCircle, Circle, Loader, AlertCircle, Play, Wrench } from 'lucide-react';+import toast from 'react-hot-toast';import * as api from '../services/api';+import IconPicker from '../components/IconPicker';const DETECTION_STEPS = [{ id: 'validate', label: 'Validating path' },@@ -10,7 +12,8 @@ const DETECTION_STEPS = [{ id: 'package', label: 'Reading package.json' },{ id: 'config', label: 'Checking configs' },{ id: 'pm2', label: 'Checking PM2' },- { id: 'readme', label: 'Reading README' }+ { id: 'readme', label: 'Reading README' },+ { id: 'standardize', label: 'Standardizing PM2 config' }];export default function CreateApp() {@@ -34,12 +37,25 @@ export default function CreateApp() {const [startCommands, setStartCommands] = useState('');const [pm2Names, setPm2Names] = useState('');const [pm2Status, setPm2Status] = useState(null);+ const [icon, setIcon] = useState('package');// Submit stateconst [submitting, setSubmitting] = useState(false);const [error, setError] = useState(null);const [detected, setDetected] = useState(false);+ // Standardization state+ const [standardizing, setStandardizing] = useState(false);+ const [standardizeResult, setStandardizeResult] = useState(null);+ const [activeProvider, setActiveProvider] = useState(null);++ // Fetch active provider on mount+ useEffect(() => {+ api.getActiveProvider().then(provider => {+ if (provider) setActiveProvider(provider);+ }).catch(() => {});+ }, []);+// Initialize socketuseEffect(() => {socketRef.current = io({ path: '/socket.io' });@@ -79,11 +95,41 @@ export default function CreateApp() {}});+ // Standardization socket events+ socketRef.current.on('standardize:step', ({ step, status, data }) => {+ // Map standardize steps to our step display+ const stepMap = { analyze: 'standardize', backup: 'standardize', apply: 'standardize' };+ const displayStep = stepMap[step] || 'standardize';+ setSteps(prev => ({ ...prev, [displayStep]: { status: status === 'done' ? 'running' : status, data } }));+ setDetectionLog(prev => [...prev, { step: `standardize:${step}`, status, ...data }]);+ });++ socketRef.current.on('standardize:complete', ({ success, result, error: err }) => {+ setStandardizing(false);+ if (success && result) {+ setStandardizeResult(result);+ setSteps(prev => ({ ...prev, standardize: { status: 'done', data: { message: 'PM2 config standardized' } } }));+ toast.success(`PM2 config standardized${result.backupBranch ? ` (backup: ${result.backupBranch})` : ''}`);+ } else {+ setSteps(prev => ({ ...prev, standardize: { status: 'error', data: { message: err || 'Standardization failed' } } }));+ if (err) toast.error(`Standardization failed: ${err}`);+ }+ });+return () => {socketRef.current?.disconnect();};}, []);+ // Auto-trigger standardization after detection completes+ useEffect(() => {+ if (detected && activeProvider && repoPath && !standardizing && !standardizeResult) {+ setStandardizing(true);+ setSteps(prev => ({ ...prev, standardize: { status: 'running', data: { message: 'Analyzing configuration...' } } }));+ socketRef.current?.emit('standardize:start', { repoPath, providerId: activeProvider.id });+ }+ }, [detected, activeProvider, repoPath, standardizing, standardizeResult]);+// Start streaming detectionconst handleImport = () => {if (!repoPath || detecting) return;@@ -94,6 +140,8 @@ export default function CreateApp() {setDetectionLog([]);setDetected(false);setPm2Status(null);+ setStandardizing(false);+ setStandardizeResult(null);socketRef.current.emit('detect:start', { path: repoPath });};@@ -107,6 +155,7 @@ export default function CreateApp() {const data = {name,repoPath,+ icon,uiPort: uiPort ? parseInt(uiPort) : null,apiPort: apiPort ? parseInt(apiPort) : null,startCommands: startCommands.split('\n').filter(Boolean),@@ -135,7 +184,10 @@ export default function CreateApp() {setStartCommands('');setPm2Names('');setPm2Status(null);+ setIcon('package');setError(null);+ setStandardizing(false);+ setStandardizeResult(null);};const getStepIcon = (stepId) => {@@ -205,6 +257,34 @@ export default function CreateApp() {</div>)}+ {/* Standardization Result */}+ {standardizeResult && (+ <div className="mt-3 p-3 bg-port-success/10 border border-port-success/30 rounded-lg">+ <p className="text-sm text-port-success font-medium flex items-center gap-2">+ <Wrench size={14} /> PM2 Config Standardized+ </p>+ {standardizeResult.backupBranch && (+ <p className="text-xs text-gray-400 mt-1">+ Backup branch: <code className="bg-port-bg px-1 rounded">{standardizeResult.backupBranch}</code>+ </p>+ )}+ {standardizeResult.filesModified?.length > 0 && (+ <p className="text-xs text-gray-400 mt-1">+ Modified: {standardizeResult.filesModified.join(', ')}+ </p>+ )}+ </div>+ )}++ {/* No Provider Warning */}+ {detected && !activeProvider && !standardizing && !standardizeResult && (+ <div className="mt-3 p-3 bg-port-border/50 border border-port-border rounded-lg">+ <p className="text-xs text-gray-400">+ <span className="text-port-warning">⚠</span> No LLM provider configured. PM2 standardization skipped.+ </p>+ </div>+ )}+{/* Detection Log Toggle */}{detectionLog.length > 0 && (<button@@ -254,16 +334,21 @@ export default function CreateApp() {<div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4 animate-in fade-in slide-in-from-bottom-2 duration-300"><h3 className="text-lg font-semibold text-white mb-4">App Configuration</h3>- <div>- <label className="block text-sm text-gray-400 mb-1">App Name *</label>- <input- type="text"- value={name}- onChange={(e) => setName(e.target.value)}- placeholder="My Awesome App"- required- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"- />+ <div className="grid grid-cols-[1fr_auto] gap-4">+ <div>+ <label className="block text-sm text-gray-400 mb-1">App Name *</label>+ <input+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="My Awesome App"+ required+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"+ />+ </div>+ <div className="w-32">+ <IconPicker value={icon} onChange={setIcon} />+ </div></div><div>diff --git a/client/src/pages/DevTools.jsx b/client/src/pages/DevTools.jsxindex aabd39d9a0..edb9bc8f3c 100644--- a/client/src/pages/DevTools.jsx+++ b/client/src/pages/DevTools.jsx@@ -1,5 +1,6 @@import { useState, useEffect, useRef, Fragment } from 'react';-import { GitBranch, Plus, Minus, FileText, Clock, RefreshCw, Activity, Image, X, XCircle, Cpu, MemoryStick, Terminal, Trash2 } from 'lucide-react';+import { useLocation, useNavigate } from 'react-router-dom';+import { GitBranch, Plus, Minus, FileText, Clock, RefreshCw, Activity, Image, X, XCircle, Cpu, MemoryStick, Terminal, Trash2, MessageSquarePlus, Info } from 'lucide-react';import * as api from '../services/api';import socket from '../services/socket';@@ -300,7 +301,277 @@ export function HistoryPage() {);}+export function RunsHistoryPage() {+ const navigate = useNavigate();+ const [runs, setRuns] = useState([]);+ const [loading, setLoading] = useState(true);+ const [expandedId, setExpandedId] = useState(null);+ const [expandedDetails, setExpandedDetails] = useState({});+ const [sourceFilter, setSourceFilter] = useState('all');++ useEffect(() => {+ loadRuns();+ }, [sourceFilter]);++ const loadRuns = async () => {+ setLoading(true);+ const data = await api.getRuns(100, 0, sourceFilter).catch(() => ({ runs: [] }));+ setRuns(data.runs || []);+ setLoading(false);+ };++ const handleDelete = async (id, e) => {+ e.stopPropagation();+ await api.deleteRun(id);+ loadRuns();+ };++ const toggleExpand = async (id) => {+ if (expandedId === id) {+ setExpandedId(null);+ return;+ }++ setExpandedId(id);++ // Load full prompt and output if not already loaded+ if (!expandedDetails[id]) {+ const [prompt, output] = await Promise.all([+ api.getRunPrompt(id).catch(() => ''),+ api.getRunOutput(id).catch(() => '')+ ]);+ setExpandedDetails(prev => ({+ ...prev,+ [id]: { prompt, output }+ }));+ }+ };++ const handleContinue = (run) => {+ const details = expandedDetails[run.id] || {};+ navigate('/devtools/runner', {+ state: {+ continueFrom: {+ prompt: details.prompt || run.prompt,+ output: details.output || '',+ runId: run.id,+ providerId: run.providerId,+ providerName: run.providerName,+ model: run.model,+ workspacePath: run.workspacePath,+ workspaceName: run.workspaceName+ }+ }+ });+ };++ const formatTime = (timestamp) => {+ const date = new Date(timestamp);+ const now = new Date();+ const diff = now - date;++ if (diff < 60000) return 'Just now';+ if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;+ if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;+ return date.toLocaleDateString();+ };++ const formatRuntime = (ms) => {+ if (!ms) return null;+ if (ms < 1000) return `${ms}ms`;+ if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;+ return `${(ms / 60000).toFixed(1)}m`;+ };++ if (loading) {+ return <div className="text-center py-8 text-gray-400">Loading runs history...</div>;+ }++ return (+ <div className="space-y-6">+ <div className="flex items-center justify-between">+ <h1 className="text-2xl font-bold text-white">AI Runs History</h1>+ <button+ onClick={loadRuns}+ className="flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white"+ >+ <RefreshCw size={16} /> Refresh+ </button>+ </div>++ {/* Source Filter */}+ <div className="flex gap-2">+ {[+ { value: 'all', label: 'All Runs' },+ { value: 'devtools', label: 'DevTools' },+ { value: 'cos-agent', label: 'CoS Agents' }+ ].map(filter => (+ <button+ key={filter.value}+ onClick={() => setSourceFilter(filter.value)}+ className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${+ sourceFilter === filter.value+ ? 'bg-port-accent text-white'+ : 'bg-port-card text-gray-400 hover:text-white border border-port-border'+ }`}+ >+ {filter.label}+ </button>+ ))}+ </div>++ {/* Runs List */}+ <div className="bg-port-card border border-port-border rounded-xl overflow-hidden">+ {runs.length === 0 ? (+ <div className="text-center py-12 text-gray-500">No AI runs yet</div>+ ) : (+ <div className="divide-y divide-port-border">+ {runs.map(run => (+ <div key={run.id}>+ <div+ className="p-4 hover:bg-port-border/20 cursor-pointer group"+ onClick={() => toggleExpand(run.id)}+ data-testid={`run-row-${run.id}`}+ >+ <div className="flex items-center gap-4">+ <button className="text-gray-400 hover:text-white">+ <span className={`inline-block transition-transform ${expandedId === run.id ? 'rotate-90' : ''}`}>▶</span>+ </button>+ <span className="text-xl">🤖</span>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="font-medium text-white">{run.providerName}</span>+ <span className="text-gray-500 text-sm">{run.model}</span>+ {run.source === 'cos-agent' && (+ <span className="text-xs text-purple-400 bg-purple-500/10 px-2 py-0.5 rounded">+ CoS+ </span>+ )}+ {run.workspaceName && (+ <span className="text-xs text-port-accent bg-port-accent/10 px-2 py-0.5 rounded">+ {run.workspaceName}+ </span>+ )}+ {run.duration && (+ <span className="text-xs text-cyan-400 font-mono">{formatRuntime(run.duration)}</span>+ )}+ </div>+ <div className="text-xs text-gray-500 font-mono truncate mt-1">+ {run.prompt?.substring(0, 100)}{run.prompt?.length > 100 ? '...' : ''}+ </div>+ </div>+ <span className={`w-2 h-2 rounded-full flex-shrink-0 ${run.success ? 'bg-port-success' : run.success === false ? 'bg-port-error' : 'bg-port-warning'}`} />+ <span className="text-sm text-gray-500 flex-shrink-0">{formatTime(run.startTime)}</span>+ <button+ onClick={(e) => handleDelete(run.id, e)}+ className="p-1 text-gray-500 hover:text-port-error transition-colors opacity-0 group-hover:opacity-100"+ title="Delete run"+ data-testid={`delete-run-${run.id}`}+ >+ <Trash2 size={14} />+ </button>+ </div>+ </div>++ {/* Expanded Details */}+ {expandedId === run.id && (+ <div className="px-4 pb-4 bg-port-bg border-t border-port-border">+ <div className="pt-4 space-y-4">+ {/* Metadata Grid */}+ <div className="grid grid-cols-5 gap-4 text-sm">+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Started</div>+ <div className="text-gray-300">{new Date(run.startTime).toLocaleString()}</div>+ </div>+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Status</div>+ <div className={run.success ? 'text-port-success' : run.success === false ? 'text-port-error' : 'text-port-warning'}>+ {run.success ? 'Success' : run.success === false ? 'Failed' : 'Running'}+ </div>+ </div>+ {run.duration && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Duration</div>+ <div className="text-cyan-400 font-mono">{formatRuntime(run.duration)}</div>+ </div>+ )}+ {run.exitCode !== undefined && run.exitCode !== null && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Exit Code</div>+ <div className={`font-mono ${run.exitCode === 0 ? 'text-port-success' : 'text-port-error'}`}>+ {run.exitCode}+ </div>+ </div>+ )}+ {run.outputSize && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Output Size</div>+ <div className="text-gray-300 font-mono">{(run.outputSize / 1024).toFixed(1)} KB</div>+ </div>+ )}+ </div>++ {/* Prompt */}+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Prompt</div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 max-h-48 overflow-auto">+ <pre className="text-sm text-gray-300 font-mono whitespace-pre-wrap break-all">+ {expandedDetails[run.id]?.prompt || run.prompt || 'Loading...'}+ </pre>+ </div>+ </div>++ {/* Output */}+ {expandedDetails[run.id]?.output && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Output</div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 max-h-64 overflow-auto">+ <pre className="text-xs text-gray-300 font-mono whitespace-pre-wrap break-all">+ {expandedDetails[run.id].output}+ </pre>+ </div>+ </div>+ )}++ {/* Error */}+ {run.error && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Error</div>+ <div className="bg-port-error/10 border border-port-error/30 rounded-lg p-3">+ <pre className="text-sm text-port-error font-mono whitespace-pre-wrap">+ {run.error}+ </pre>+ </div>+ </div>+ )}++ {/* Continue Button */}+ {run.success && expandedDetails[run.id]?.output && (+ <div className="flex justify-end pt-2">+ <button+ onClick={() => handleContinue(run)}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"+ data-testid="continue-conversation-btn"+ >+ <MessageSquarePlus size={16} />+ Continue Conversation+ </button>+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+}+export function RunnerPage() {+ const location = useLocation();const [mode, setMode] = useState('ai'); // 'ai' or 'command'const [prompt, setPrompt] = useState('');const [command, setCommand] = useState('');@@ -316,6 +587,7 @@ export function RunnerPage() {const [timeout, setTimeout] = useState(30);const [allowedCommands, setAllowedCommands] = useState([]);const [screenshots, setScreenshots] = useState([]);+ const [continueContext, setContinueContext] = useState(null);const fileInputRef = useRef(null);const outputRef = useRef(null);@@ -323,6 +595,30 @@ export function RunnerPage() {const selectedApp = apps.find(a => a.id === selectedAppId);const workspacePath = selectedApp?.repoPath || '';+ // Handle continuation context from navigation+ useEffect(() => {+ const continueFrom = location.state?.continueFrom;+ if (continueFrom) {+ setContinueContext(continueFrom);+ // Set provider and model from previous run if available+ if (continueFrom.providerId) {+ setSelectedProvider(continueFrom.providerId);+ }+ if (continueFrom.model) {+ setSelectedModel(continueFrom.model);+ }+ // Set workspace from previous run if available+ if (continueFrom.workspacePath) {+ const app = apps.find(a => a.repoPath === continueFrom.workspacePath);+ if (app) {+ setSelectedAppId(app.id);+ }+ }+ // Clear location state to prevent re-triggering on refresh+ window.history.replaceState({}, document.title);+ }+ }, [location.state, apps]);+useEffect(() => {Promise.all([api.getApps().catch(() => []),@@ -407,13 +703,28 @@ export function RunnerPage() {const handleRunAI = async () => {if (!prompt.trim() || !selectedProvider) return;+ // Build final prompt, merging with continuation context if present+ let finalPrompt = prompt.trim();+ if (continueContext) {+ finalPrompt = `CONTINUATION OF PREVIOUS CONVERSATION:++--- PREVIOUS PROMPT ---+${continueContext.prompt}++--- PREVIOUS OUTPUT ---+${continueContext.output}++--- NEW INSTRUCTIONS ---+${prompt.trim()}`;+ }+setOutput('');setRunning(true);const result = await api.createRun({providerId: selectedProvider,model: selectedModel || undefined,- prompt: prompt.trim(),+ prompt: finalPrompt,workspacePath: workspacePath || undefined,workspaceName: apps.find(a => a.repoPath === workspacePath)?.name}).catch(err => ({ error: err.message }));@@ -424,6 +735,8 @@ export function RunnerPage() {return;}+ // Clear continuation context after running+ setContinueContext(null);setRunId(result.runId);};@@ -509,6 +822,47 @@ export function RunnerPage() {<div className="space-y-6"><h1 className="text-2xl font-bold text-white">Code</h1>+ {/* Continuation Context Banner */}+ {continueContext && (+ <div className="bg-port-success/10 border border-port-success/30 rounded-xl p-4" data-testid="continuation-banner">+ <div className="flex items-start justify-between mb-3">+ <div className="flex items-center gap-2">+ <Info size={18} className="text-port-success" />+ <span className="font-medium text-port-success">Continuing Previous Conversation</span>+ {continueContext.providerName && (+ <span className="text-xs text-gray-400 bg-port-card px-2 py-0.5 rounded">+ {continueContext.providerName}+ </span>+ )}+ </div>+ <button+ onClick={() => setContinueContext(null)}+ className="p-1 text-gray-400 hover:text-white"+ title="Dismiss context"+ >+ <X size={16} />+ </button>+ </div>+ <div className="space-y-2 text-sm">+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Previous Prompt</div>+ <div className="text-gray-300 bg-port-card/50 rounded px-2 py-1 font-mono text-xs max-h-20 overflow-auto">+ {continueContext.prompt?.substring(0, 500)}{continueContext.prompt?.length > 500 ? '...' : ''}+ </div>+ </div>+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Previous Output</div>+ <div className="text-gray-300 bg-port-card/50 rounded px-2 py-1 font-mono text-xs max-h-24 overflow-auto">+ {continueContext.output?.substring(0, 800)}{continueContext.output?.length > 800 ? '...' : ''}+ </div>+ </div>+ </div>+ <div className="text-xs text-gray-500 mt-3 italic">+ Enter your follow-up instructions below. The previous context will be included automatically.+ </div>+ </div>+ )}+{/* Mode Toggle */}<div className="flex gap-2"><button@@ -1491,11 +1845,12 @@ export function AgentsPage() {</div>{/* Running Processes Table */}- <div className="bg-port-card border border-port-border rounded-xl overflow-hidden">+ <div className="bg-port-card border border-port-border rounded-xl"><div className="px-6 py-4 border-b border-port-border"><h2 className="text-lg font-semibold text-white">Running Processes</h2></div>- <table className="w-full">+ <div className="overflow-x-auto">+ <table className="w-full min-w-[600px]"><thead><tr className="border-b border-port-border"><th className="px-4 py-4 text-left text-sm font-semibold text-gray-400 w-8"></th>@@ -1523,7 +1878,12 @@ export function AgentsPage() {<td className="px-4 py-4 font-mono text-cyan-400">{agent.runtimeFormatted}</td><td className="px-4 py-4 font-mono text-green-400">{agent.cpu?.toFixed(1)}%</td><td className="px-4 py-4 font-mono text-blue-400">{agent.memory?.toFixed(1)}%</td>- <td className="px-4 py-4 font-mono text-gray-300">{agent.agentName.toLowerCase()}</td>+ <td className="px-4 py-4 font-mono text-gray-300">+ {agent.agentName.toLowerCase()}+ {agent.source === 'cos' && (+ <span className="ml-2 px-1.5 py-0.5 text-[10px] bg-purple-500/20 text-purple-400 rounded">CoS</span>+ )}+ </td><td className="px-4 py-4 text-center"><buttononClick={() => handleKill(agent.pid)}@@ -1539,12 +1899,15 @@ export function AgentsPage() {<tr><td colSpan={7} className="p-0"><div className="bg-port-bg border-t border-port-border">- <div className="px-6 py-4 space-y-4">+ <div className="px-3 sm:px-6 py-4 space-y-4">{/* Process Details Grid */}- <div className="grid grid-cols-4 gap-4">+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4"><div><div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Agent Type</div>- <div className="text-sm text-purple-400 font-medium">{agent.agentName}</div>+ <div className="text-sm text-purple-400 font-medium">+ {agent.agentName}+ {agent.source === 'cos' && <span className="ml-1 text-xs text-purple-300">(CoS)</span>}+ </div></div><div><div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Parent PID</div>@@ -1558,6 +1921,32 @@ export function AgentsPage() {<div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Runtime (ms)</div><div className="text-sm text-gray-300 font-mono">{agent.runtime?.toLocaleString()}</div></div>+ {agent.model && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Model</div>+ <div className="text-sm text-yellow-400 font-mono">{agent.model}</div>+ </div>+ )}+ {agent.agentId && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Agent ID</div>+ <div className="text-sm text-gray-300 font-mono">{agent.agentId}</div>+ </div>+ )}+ {agent.taskId && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Task ID</div>+ <div className="text-sm text-gray-300 font-mono">{agent.taskId}</div>+ </div>+ )}+ {agent.workspacePath && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Workspace</div>+ <div className="text-sm text-gray-300 font-mono truncate" title={agent.workspacePath}>+ {agent.workspacePath.split('/').pop()}+ </div>+ </div>+ )}</div>{/* Full Command */}@@ -1570,8 +1959,20 @@ export function AgentsPage() {</div></div>+ {/* Task Prompt (for CoS agents) */}+ {agent.prompt && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Task Prompt</div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 overflow-x-auto max-h-48 overflow-y-auto">+ <p className="text-sm text-gray-300 whitespace-pre-wrap">+ {agent.prompt}+ </p>+ </div>+ </div>+ )}+{/* Resource Usage Bar */}- <div className="grid grid-cols-2 gap-4">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4"><div><div className="flex items-center justify-between text-xs mb-1"><span className="text-gray-500 uppercase tracking-wide">CPU Usage</span>@@ -1613,6 +2014,7 @@ export function AgentsPage() {)}</tbody></table>+ </div></div></div>);diff --git a/client/src/services/api.js b/client/src/services/api.jsindex b89d279ad1..a2e544af9f 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1,3 +1,5 @@+import toast from 'react-hot-toast';+const API_BASE = '/api';async function request(endpoint, options = {}) {@@ -14,7 +16,9 @@ async function request(endpoint, options = {}) {if (!response.ok) {const error = await response.json().catch(() => ({ error: 'Request failed' }));- throw new Error(error.error || `HTTP ${response.status}`);+ const errorMessage = error.error || `HTTP ${response.status}`;+ toast.error(errorMessage);+ throw new Error(errorMessage);}// Handle 204 No Content@@ -47,6 +51,7 @@ export const stopApp = (id) => request(`/apps/${id}/stop`, { method: 'POST' });export const restartApp = (id) => request(`/apps/${id}/restart`, { method: 'POST' });export const openAppInEditor = (id) => request(`/apps/${id}/open-editor`, { method: 'POST' });export const openAppFolder = (id) => request(`/apps/${id}/open-folder`, { method: 'POST' });+export const refreshAppConfig = (id) => request(`/apps/${id}/refresh-config`, { method: 'POST' });export const getAppStatus = (id) => request(`/apps/${id}/status`);export const getAppLogs = (id, lines = 100, processName) => {const params = new URLSearchParams({ lines: String(lines) });@@ -163,14 +168,15 @@ export const testProvider = (id) => request(`/providers/${id}/test`, { method: 'export const refreshProviderModels = (id) => request(`/providers/${id}/refresh-models`, { method: 'POST' });// Runs-export const getRuns = (limit = 50, offset = 0) =>- request(`/runs?limit=${limit}&offset=${offset}`);+export const getRuns = (limit = 50, offset = 0, source = 'all') =>+ request(`/runs?limit=${limit}&offset=${offset}&source=${source}`);export const createRun = (data) => request('/runs', {method: 'POST',body: JSON.stringify(data)});export const getRun = (id) => request(`/runs/${id}`);export const getRunOutput = (id) => request(`/runs/${id}/output`);+export const getRunPrompt = (id) => request(`/runs/${id}/prompt`);export const stopRun = (id) => request(`/runs/${id}/stop`, { method: 'POST' });export const deleteRun = (id) => request(`/runs/${id}`, { method: 'DELETE' });@@ -245,3 +251,128 @@ export const uploadScreenshot = (base64Data, filename, mimeType) => request('/scexport const getAgents = () => request('/agents');export const getAgentInfo = (pid) => request(`/agents/${pid}`);export const killAgent = (pid) => request(`/agents/${pid}`, { method: 'DELETE' });++// Chief of Staff+export const getCosStatus = () => request('/cos');+export const startCos = () => request('/cos/start', { method: 'POST' });+export const stopCos = () => request('/cos/stop', { method: 'POST' });+export const getCosConfig = () => request('/cos/config');+export const updateCosConfig = (config) => request('/cos/config', {+ method: 'PUT',+ body: JSON.stringify(config)+});+export const getCosTasks = () => request('/cos/tasks');+export const addCosTask = (task) => request('/cos/tasks', {+ method: 'POST',+ body: JSON.stringify(task)+});+export const updateCosTask = (id, updates) => request(`/cos/tasks/${id}`, {+ method: 'PUT',+ body: JSON.stringify(updates)+});+export const deleteCosTask = (id) => request(`/cos/tasks/${id}`, { method: 'DELETE' });+export const reorderCosTasks = (taskIds) => request('/cos/tasks/reorder', {+ method: 'POST',+ body: JSON.stringify({ taskIds })+});+export const approveCosTask = (id) => request(`/cos/tasks/${id}/approve`, { method: 'POST' });+export const forceCosEvaluate = () => request('/cos/evaluate', { method: 'POST' });+export const getCosHealth = () => request('/cos/health');+export const forceHealthCheck = () => request('/cos/health/check', { method: 'POST' });+export const getCosAgents = () => request('/cos/agents');+export const getCosAgent = (id) => request(`/cos/agents/${id}`);+export const terminateCosAgent = (id) => request(`/cos/agents/${id}/terminate`, { method: 'POST' });+export const deleteCosAgent = (id) => request(`/cos/agents/${id}`, { method: 'DELETE' });+export const clearCompletedCosAgents = () => request('/cos/agents/completed', { method: 'DELETE' });+export const getCosReports = () => request('/cos/reports');+export const getCosTodayReport = () => request('/cos/reports/today');+export const getCosReport = (date) => request(`/cos/reports/${date}`);++// CoS Scripts+export const getCosScripts = () => request('/cos/scripts');+export const getCosScript = (id) => request(`/cos/scripts/${id}`);+export const createCosScript = (data) => request('/cos/scripts', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const updateCosScript = (id, data) => request(`/cos/scripts/${id}`, {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const deleteCosScript = (id) => request(`/cos/scripts/${id}`, { method: 'DELETE' });+export const runCosScript = (id) => request(`/cos/scripts/${id}/run`, { method: 'POST' });+export const getCosScriptRuns = (id) => request(`/cos/scripts/${id}/runs`);+export const getCosScriptPresets = () => request('/cos/scripts/presets');++// Memory+export const getMemories = (options = {}) => {+ const params = new URLSearchParams();+ if (options.types) params.set('types', options.types.join(','));+ if (options.categories) params.set('categories', options.categories.join(','));+ if (options.tags) params.set('tags', options.tags.join(','));+ if (options.status) params.set('status', options.status);+ if (options.limit) params.set('limit', options.limit);+ if (options.offset) params.set('offset', options.offset);+ if (options.sortBy) params.set('sortBy', options.sortBy);+ if (options.sortOrder) params.set('sortOrder', options.sortOrder);+ return request(`/memory?${params}`);+};+export const getMemory = (id) => request(`/memory/${id}`);+export const createMemory = (data) => request('/memory', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const updateMemory = (id, data) => request(`/memory/${id}`, {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const deleteMemory = (id, hard = false) => request(`/memory/${id}?hard=${hard}`, { method: 'DELETE' });+export const searchMemories = (query, options = {}) => request('/memory/search', {+ method: 'POST',+ body: JSON.stringify({ query, ...options })+});+export const getMemoryCategories = () => request('/memory/categories');+export const getMemoryTags = () => request('/memory/tags');+export const getMemoryTimeline = (options = {}) => {+ const params = new URLSearchParams();+ if (options.startDate) params.set('startDate', options.startDate);+ if (options.endDate) params.set('endDate', options.endDate);+ if (options.types) params.set('types', options.types.join(','));+ if (options.limit) params.set('limit', options.limit);+ return request(`/memory/timeline?${params}`);+};+export const getMemoryGraph = () => request('/memory/graph');+export const getMemoryStats = () => request('/memory/stats');+export const getRelatedMemories = (id, limit = 10) => request(`/memory/${id}/related?limit=${limit}`);+export const linkMemories = (sourceId, targetId) => request('/memory/link', {+ method: 'POST',+ body: JSON.stringify({ sourceId, targetId })+});+export const consolidateMemories = (options = {}) => request('/memory/consolidate', {+ method: 'POST',+ body: JSON.stringify(options)+});+export const getEmbeddingStatus = () => request('/memory/embeddings/status');++// PM2 Standardization+export const analyzeStandardization = (repoPath, providerId) => request('/standardize/analyze', {+ method: 'POST',+ body: JSON.stringify({ repoPath, providerId })+});+export const analyzeStandardizationByApp = (appId, providerId) => request('/standardize/analyze', {+ method: 'POST',+ body: JSON.stringify({ appId, providerId })+});+export const applyStandardization = (repoPath, plan) => request('/standardize/apply', {+ method: 'POST',+ body: JSON.stringify({ repoPath, plan })+});+export const applyStandardizationByApp = (appId, plan) => request('/standardize/apply', {+ method: 'POST',+ body: JSON.stringify({ appId, plan })+});+export const getStandardizeTemplate = () => request('/standardize/template');+export const createGitBackup = (repoPath) => request('/standardize/backup', {+ method: 'POST',+ body: JSON.stringify({ repoPath })+});diff --git a/data.sample/COS-TASKS.md b/data.sample/COS-TASKS.mdnew file mode 100644index 0000000000..d4d12de509--- /dev/null+++ b/data.sample/COS-TASKS.md@@ -0,0 +1,7 @@+# Tasks++## Pending++## In Progress++## Completeddiff --git a/data.sample/TASKS.md b/data.sample/TASKS.mdnew file mode 100644index 0000000000..ebbad1ef83--- /dev/null+++ b/data.sample/TASKS.md@@ -0,0 +1,10 @@+# Tasks++## Pending+- [ ] #task-sample01 | LOW | Example task: Review codebase documentation and suggest improvements+ - Model: claude-sonnet-4-20250514+ - Provider: claude-code++## In Progress++## Completeddiff --git a/data.sample/autofixer/index.json b/data.sample/autofixer/index.jsonnew file mode 100644index 0000000000..fe51488c70--- /dev/null+++ b/data.sample/autofixer/index.json@@ -0,0 +1 @@+[]diff --git a/data.sample/autofixer/sessions/.gitkeep b/data.sample/autofixer/sessions/.gitkeepnew file mode 100644index 0000000000..e69de29bb2diff --git a/data.sample/cos/agents/.gitkeep b/data.sample/cos/agents/.gitkeepnew file mode 100644index 0000000000..e69de29bb2diff --git a/data.sample/cos/memory/embeddings.json b/data.sample/cos/memory/embeddings.jsonnew file mode 100644index 0000000000..0d0b809a66--- /dev/null+++ b/data.sample/cos/memory/embeddings.json@@ -0,0 +1,5 @@+{+ "model": null,+ "dimension": 0,+ "vectors": {}+}diff --git a/data.sample/cos/memory/index.json b/data.sample/cos/memory/index.jsonnew file mode 100644index 0000000000..9e7a48691e--- /dev/null+++ b/data.sample/cos/memory/index.json@@ -0,0 +1,6 @@+{+ "version": 1,+ "lastUpdated": "2024-01-01T00:00:00.000Z",+ "count": 0,+ "memories": []+}diff --git a/data.sample/cos/reports/.gitkeep b/data.sample/cos/reports/.gitkeepnew file mode 100644index 0000000000..e69de29bb2diff --git a/data.sample/cos/scripts/.gitkeep b/data.sample/cos/scripts/.gitkeepnew file mode 100644index 0000000000..e69de29bb2diff --git a/data.sample/cos/state.json b/data.sample/cos/state.jsonnew file mode 100644index 0000000000..91cebaae12--- /dev/null+++ b/data.sample/cos/state.json@@ -0,0 +1,42 @@+{+ "running": false,+ "config": {+ "userTasksFile": "data/TASKS.md",+ "cosTasksFile": "data/COS-TASKS.md",+ "evaluationIntervalMs": 60000,+ "healthCheckIntervalMs": 900000,+ "maxConcurrentAgents": 3,+ "maxProcessMemoryMb": 2048,+ "maxTotalProcesses": 50,+ "mcpServers": [+ {+ "name": "filesystem",+ "command": "npx",+ "args": [+ "-y",+ "@anthropic/mcp-server-filesystem"+ ]+ },+ {+ "name": "puppeteer",+ "command": "npx",+ "args": [+ "-y",+ "@anthropic/mcp-puppeteer",+ "--isolated"+ ]+ }+ ],+ "autoStart": false,+ "selfImprovementEnabled": true+ },+ "stats": {+ "tasksCompleted": 0,+ "totalRuntime": 0,+ "agentsSpawned": 0,+ "lastEvaluation": null,+ "lastHealthCheck": null,+ "healthIssues": []+ },+ "agents": {}+}diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.jsonnew file mode 100644index 0000000000..718a50c5b9--- /dev/null+++ b/data.sample/prompts/stage-config.json@@ -0,0 +1,53 @@+{+ "stages": {+ "app-detection": {+ "name": "App Detection",+ "description": "Analyze a project directory and detect its configuration",+ "model": "default",+ "returnsJson": true,+ "variables": ["jsonOutputFormat", "appDetectionSchema", "portDetectionRules", "pm2NamingConvention"]+ },+ "code-analysis": {+ "name": "Code Analysis",+ "description": "Analyze code structure and suggest improvements",+ "model": "default",+ "returnsJson": false,+ "variables": []+ },+ "command-suggestion": {+ "name": "Command Suggestion",+ "description": "Suggest CLI commands based on context",+ "model": "quick",+ "returnsJson": false,+ "variables": []+ },+ "cos-agent-briefing": {+ "name": "CoS Agent Briefing",+ "description": "Brief a sub-agent on their assigned task",+ "model": "heavy",+ "returnsJson": false,+ "variables": []+ },+ "cos-evaluate": {+ "name": "CoS Task Evaluation",+ "description": "Evaluate pending tasks and decide what to work on",+ "model": "heavy",+ "returnsJson": true,+ "variables": []+ },+ "cos-report-summary": {+ "name": "CoS Report Summary",+ "description": "Generate daily work summary report",+ "model": "default",+ "returnsJson": false,+ "variables": []+ },+ "cos-self-improvement": {+ "name": "CoS Self Improvement",+ "description": "Analyze system performance and suggest improvements",+ "model": "heavy",+ "returnsJson": true,+ "variables": []+ }+ }+}diff --git a/data.sample/prompts/stages/app-detection.md b/data.sample/prompts/stages/app-detection.mdnew file mode 100644index 0000000000..83256da3a4--- /dev/null+++ b/data.sample/prompts/stages/app-detection.md@@ -0,0 +1,36 @@+Analyze this project and return JSON with the detected configuration.++Directory: {{dirName}}+Files: {{fileList}}++{{#packageJson}}+package.json:+{{packageJson}}+{{/packageJson}}++{{#configFiles}}+{{name}}:+{{content}}+{{/configFiles}}++{{#envFiles}}+{{name}}:+{{content}}+{{/envFiles}}++{{#readme}}+README excerpt:+{{readme}}+{{/readme}}++{{jsonOutputFormat}}++Return this exact structure:+{{appDetectionSchema}}++Rules:+- {{portDetectionRules}}+- {{pm2NamingConvention}}+- name: Use package.json name or derive from directory, make it human readable+- For startCommands, prefer "npm run dev" patterns+- If the app has both frontend and backend, suggest separate PM2 processesdiff --git a/data.sample/prompts/stages/cos-agent-briefing.md b/data.sample/prompts/stages/cos-agent-briefing.mdnew file mode 100644index 0000000000..6bd21abf35--- /dev/null+++ b/data.sample/prompts/stages/cos-agent-briefing.md@@ -0,0 +1,57 @@+# Chief of Staff Agent Briefing++You are an autonomous agent working on behalf of the Chief of Staff system in PortOS.+Your job is to complete the assigned task independently and efficiently.++## Task Assignment++**Task ID**: {{task.id}}+**Priority**: {{task.priority}}+**Type**: {{task.taskType}}+**Description**: {{task.description}}++{{#task.metadata.context}}+### Context+{{task.metadata.context}}+{{/task.metadata.context}}++{{#task.metadata.app}}+### Target Application+{{task.metadata.app}}+{{/task.metadata.app}}++## Instructions++1. **Analyze** the task requirements carefully before making changes+2. **Plan** your approach - identify files to modify and tests to run+3. **Execute** changes in small, verifiable steps+4. **Verify** your changes work as expected+5. **Report** a summary of what was done++## Guidelines++- Focus ONLY on the assigned task - do not make unrelated changes+- Follow existing code patterns and conventions in the project+- Make minimal, targeted changes to accomplish the goal+- Test your changes when test commands are available+- If you encounter blockers, document them clearly in your output++## Working Environment++- You have full access to the filesystem via MCP tools+- You can run shell commands as needed+- The current time is {{timestamp}}++## Output Format++At the end of your work, provide a summary in this format:++```+## Task Summary+- **Status**: [completed|blocked|partial]+- **Changes Made**: [list of files modified]+- **Tests Run**: [any tests executed]+- **Notes**: [any important observations]+```++Begin working on the task now.diff --git a/data.sample/prompts/stages/cos-evaluate.md b/data.sample/prompts/stages/cos-evaluate.mdnew file mode 100644index 0000000000..9a3514b290--- /dev/null+++ b/data.sample/prompts/stages/cos-evaluate.md@@ -0,0 +1,72 @@+# Chief of Staff Task Evaluation++You are the Chief of Staff for PortOS, an autonomous agent manager.+Your job is to evaluate pending tasks and decide what to work on next.++## Current System State++**Active Agents**: {{activeAgents}}+**Max Concurrent Agents**: {{maxAgents}}+**Available Slots**: {{availableSlots}}++## Pending User Tasks+{{#userTasks}}+- **{{id}}** | {{priority}} | {{description}}+ {{#metadata.context}}- Context: {{metadata.context}}{{/metadata.context}}+ {{#metadata.app}}- App: {{metadata.app}}{{/metadata.app}}+{{/userTasks}}+{{^userTasks}}+No pending user tasks.+{{/userTasks}}++## Pending System Tasks (Auto-Approved)+{{#autoApprovedTasks}}+- **{{id}}** | {{priority}} | {{description}}+ {{#metadata.schedule}}- Schedule: {{metadata.schedule}}{{/metadata.schedule}}+{{/autoApprovedTasks}}+{{^autoApprovedTasks}}+No pending system tasks.+{{/autoApprovedTasks}}++## Tasks Awaiting Approval+{{#awaitingApproval}}+- **{{id}}** | {{priority}} | {{description}}+{{/awaitingApproval}}+{{^awaitingApproval}}+None.+{{/awaitingApproval}}++## System Health+{{#healthIssues}}+- [{{type}}] {{category}}: {{message}}+{{/healthIssues}}+{{^healthIssues}}+All systems healthy.+{{/healthIssues}}++## Instructions++Evaluate the current state and decide:+1. Which task should be worked on next (if any)?+2. Are there any health issues that need immediate attention?+3. Should any new system tasks be created?++Return your decision as JSON:++```json+{+ "action": "spawn|wait|create_task|report_issue",+ "taskId": "task-xxx",+ "reason": "Why this task was selected",+ "newTasks": [],+ "healthActions": []+}+```++## Decision Criteria++1. **Health issues** take priority over feature work+2. **User tasks** generally take priority over system tasks+3. **Higher priority** tasks should be done first+4. Consider **dependencies** between tasks+5. Avoid spawning agents if system resources are constraineddiff --git a/data.sample/prompts/stages/cos-report-summary.md b/data.sample/prompts/stages/cos-report-summary.mdnew file mode 100644index 0000000000..639c9ad0b3--- /dev/null+++ b/data.sample/prompts/stages/cos-report-summary.md@@ -0,0 +1,44 @@+# Chief of Staff Daily Report++Generate a summary report of today's work.++## Date: {{date}}++## Agent Activity+{{#agents}}+### {{id}}+- **Task**: {{taskId}} - {{taskDescription}}+- **Status**: {{status}}+- **Duration**: {{duration}}ms+- **Result**: {{result.success}}+{{/agents}}+{{^agents}}+No agents ran today.+{{/agents}}++## Tasks Completed+{{#completedTasks}}+- **{{id}}**: {{description}}+{{/completedTasks}}+{{^completedTasks}}+No tasks completed today.+{{/completedTasks}}++## Health Status+- Last Check: {{lastHealthCheck}}+{{#healthIssues}}+- [{{type}}] {{message}}+{{/healthIssues}}+{{^healthIssues}}+- No issues detected+{{/healthIssues}}++## Instructions++Generate a brief, human-readable summary of the day's work including:+1. Total tasks attempted and completed+2. Any failures or blockers encountered+3. System health observations+4. Recommendations for tomorrow++Keep the summary concise but informative.diff --git a/data.sample/prompts/stages/cos-self-improvement.md b/data.sample/prompts/stages/cos-self-improvement.mdnew file mode 100644index 0000000000..2e55176bef--- /dev/null+++ b/data.sample/prompts/stages/cos-self-improvement.md@@ -0,0 +1,88 @@+# Chief of Staff Self-Improvement Analysis++You are the Chief of Staff meta-analyzer. Your job is to review the CoS system's performance+and suggest improvements to prompts, rules, and automation scripts.++## Current Performance Metrics++**Total Tasks Completed**: {{stats.tasksCompleted}}+**Success Rate**: {{stats.successRate}}%+**Average Agent Duration**: {{stats.avgDuration}}ms+**Agents Spawned**: {{stats.agentsSpawned}}++## Recent Agent Outputs (Last 5)+{{#recentAgents}}+### {{id}} - {{taskId}}+**Result**: {{result.success}}+**Duration**: {{result.duration}}ms+{{#output}}+Output excerpt:+```+{{output}}+```+{{/output}}+---+{{/recentAgents}}++## Current Prompt Templates+{{#promptTemplates}}+- {{name}}: {{path}}+{{/promptTemplates}}++## Current Configuration+```json+{{configJson}}+```++## Analysis Tasks++1. **Prompt Effectiveness**+ - Are agents completing tasks successfully?+ - Do agents need more context or clearer instructions?+ - Are there common failure patterns?++2. **Automation Opportunities**+ - Are there repetitive tasks that could be scripted?+ - Could any manual steps be automated?+ - Are there patterns in health checks that could trigger auto-remediation?++3. **Configuration Tuning**+ - Is the evaluation interval appropriate?+ - Are MCP servers configured optimally?+ - Should concurrent agent limits be adjusted?++## Output Format++Provide your analysis as JSON:++```json+{+ "observations": ["list of key observations"],+ "promptImprovements": [+ {+ "template": "template-name",+ "issue": "what's wrong",+ "suggestion": "how to fix it"+ }+ ],+ "automationSuggestions": [+ {+ "name": "script-name",+ "purpose": "what it does",+ "trigger": "when to run it"+ }+ ],+ "configChanges": [+ {+ "setting": "config.key",+ "current": "current value",+ "suggested": "new value",+ "reason": "why change it"+ }+ ],+ "priority": "HIGH|MEDIUM|LOW",+ "requiresApproval": true+}+```++Be specific and actionable in your suggestions. Mark any changes that require user approval.diff --git a/data.sample/prompts/variables.json b/data.sample/prompts/variables.jsonnew file mode 100644index 0000000000..8cd012a507--- /dev/null+++ b/data.sample/prompts/variables.json@@ -0,0 +1,24 @@+{+ "variables": {+ "jsonOutputFormat": {+ "name": "JSON Output Format",+ "category": "response",+ "content": "Return ONLY valid JSON (no markdown, no explanation, no code blocks)."+ },+ "appDetectionSchema": {+ "name": "App Detection Schema",+ "category": "schema",+ "content": "{\n \"name\": \"Human readable app name\",\n \"description\": \"One sentence description\",\n \"uiPort\": null or number,\n \"apiPort\": null or number,\n \"startCommands\": [\"array of npm scripts\"],\n \"pm2ProcessNames\": [\"suggested PM2 process names\"]\n}"+ },+ "portDetectionRules": {+ "name": "Port Detection Rules",+ "category": "rules",+ "content": "Look for ports in: vite.config (server.port), .env files (PORT, VITE_PORT), package.json scripts with --port flags."+ },+ "pm2NamingConvention": {+ "name": "PM2 Naming Convention",+ "category": "rules",+ "content": "Use lowercase hyphenated names. For full-stack apps use suffixes: app-name-ui, app-name-api."+ }+ }+}diff --git a/data.sample/providers.json b/data.sample/providers.jsonindex 859fd49782..c65b7e2b9e 100644--- a/data.sample/providers.json+++ b/data.sample/providers.json@@ -6,9 +6,12 @@"name": "Claude Code CLI","type": "cli","command": "claude",- "args": ["--print", "-p"],- "models": ["claude-sonnet-4-20250514", "claude-opus-4-20250514"],+ "args": ["--print"],+ "models": ["claude-haiku-4-5-20251001", "claude-sonnet-4-20250514", "claude-opus-4-20250514"],"defaultModel": "claude-sonnet-4-20250514",+ "lightModel": "claude-haiku-4-5-20251001",+ "mediumModel": "claude-sonnet-4-20250514",+ "heavyModel": "claude-opus-4-20250514","timeout": 300000,"enabled": true,"envVars": {}diff --git a/data.sample/runs/.gitkeep b/data.sample/runs/.gitkeepnew file mode 100644index 0000000000..e69de29bb2diff --git a/data.sample/usage.json b/data.sample/usage.jsonnew file mode 100644index 0000000000..4e30619fb0--- /dev/null+++ b/data.sample/usage.json@@ -0,0 +1,14 @@+{+ "totalSessions": 0,+ "totalMessages": 0,+ "totalToolCalls": 0,+ "totalTokens": {+ "input": 0,+ "output": 0+ },+ "byProvider": {},+ "byModel": {},+ "dailyActivity": {},+ "hourlyActivity": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],+ "lastUpdated": null+}diff --git a/server/index.js b/server/index.jsindex 5d9d4fe401..11e3536752 100644--- a/server/index.js+++ b/server/index.js@@ -1,3 +1,4 @@+import './lib/logger.js'; // Add timestamps to all console outputimport express from 'express';import cors from 'cors';import { createServer } from 'http';@@ -20,7 +21,15 @@ import gitRoutes from './routes/git.js';import usageRoutes from './routes/usage.js';import screenshotsRoutes from './routes/screenshots.js';import agentsRoutes from './routes/agents.js';+import cosRoutes from './routes/cos.js';+import scriptsRoutes from './routes/scripts.js';+import memoryRoutes from './routes/memory.js';+import standardizeRoutes from './routes/standardize.js';import { initSocket } from './services/socket.js';+import { initScriptRunner } from './services/scriptRunner.js';+import { errorMiddleware, setupProcessErrorHandlers } from './lib/errorHandler.js';+import { initAutoFixer } from './services/autoFixer.js';+import './services/subAgentSpawner.js'; // Initialize CoS agent spawnerconst __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -42,12 +51,16 @@ const io = new Server(httpServer, {// Initialize socket handlersinitSocket(io);+// Initialize auto-fixer for error recovery+initAutoFixer();+// Middleware - allow any origin for Tailscale accessapp.use(cors({origin: true,credentials: true}));-app.use(express.json());+app.use(express.json({ limit: '50mb' }));+app.use(express.urlencoded({ limit: '50mb', extended: true }));// Make io available to routesapp.set('io', io);@@ -69,15 +82,13 @@ app.use('/api/git', gitRoutes);app.use('/api/usage', usageRoutes);app.use('/api/screenshots', screenshotsRoutes);app.use('/api/agents', agentsRoutes);+app.use('/api/cos/scripts', scriptsRoutes); // Mount before /api/cos to avoid route conflicts+app.use('/api/cos', cosRoutes);+app.use('/api/memory', memoryRoutes);+app.use('/api/standardize', standardizeRoutes);-// Error handler-app.use((err, req, res, next) => {- console.error(`❌ Server error: ${err.message}`);- res.status(err.status || 500).json({- error: err.message || 'Internal server error',- code: err.code || 'INTERNAL_ERROR'- });-});+// Initialize script runner+initScriptRunner().catch(err => console.error(`❌ Script runner init failed: ${err.message}`));// 404 handlerapp.use((req, res) => {@@ -87,6 +98,13 @@ app.use((req, res) => {});});+// Error middleware (must be last)+app.use(errorMiddleware);++// Start serverhttpServer.listen(PORT, HOST, () => {console.log(`🚀 PortOS server running at http://${HOST}:${PORT}`);++ // Set up process error handlers with io instance+ setupProcessErrorHandlers(io);});diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.jsnew file mode 100644index 0000000000..1306231232--- /dev/null+++ b/server/lib/errorHandler.js@@ -0,0 +1,196 @@+/**+ * Error handling utilities for graceful server error management+ * Catches errors in async routes and emits Socket.IO events for UI alerting+ */++import { EventEmitter } from 'events';++// Global error event emitter for broadcasting errors+export const errorEvents = new EventEmitter();++/**+ * Enhanced error object with metadata+ */+export class ServerError extends Error {+ constructor(message, options = {}) {+ super(message);+ this.name = 'ServerError';+ this.status = options.status || 500;+ this.code = options.code || 'INTERNAL_ERROR';+ this.timestamp = Date.now();+ this.context = options.context || {};+ this.severity = options.severity || 'error'; // error, critical, warning+ this.canAutoFix = options.canAutoFix || false;+ }+}++/**+ * Wrap async route handlers to catch errors and emit Socket.IO events+ * Also sends error response to client+ */+export function asyncHandler(fn) {+ return (req, res, next) => {+ Promise.resolve(fn(req, res, next)).catch((err) => {+ const io = req.app.get('io');+ const error = normalizeError(err);++ // Log the error+ const logMsg = `❌ Route error: ${error.message}`;+ if (error.status >= 500) {+ console.error(logMsg, error.stack ? error.stack : '');+ } else {+ console.error(logMsg);+ }++ // Emit Socket.IO event for UI notification+ if (io) {+ emitErrorEvent(io, error);+ }++ // Send error response+ return res.status(error.status).json({+ error: error.message,+ code: error.code,+ timestamp: error.timestamp,+ ...(error.context && Object.keys(error.context).length > 0 && { context: error.context })+ });+ });+ };+}++/**+ * Normalize different error types to ServerError+ */+export function normalizeError(err) {+ if (err instanceof ServerError) {+ return err;+ }++ if (err instanceof Error) {+ const status = err.status || 500;+ const code = err.code || getErrorCode(status);+ return new ServerError(err.message, {+ status,+ code,+ context: { originalError: err.constructor.name }+ });+ }++ // Handle string or other error types+ return new ServerError(String(err), {+ status: 500,+ code: 'INTERNAL_ERROR'+ });+}++/**+ * Get appropriate error code from HTTP status+ */+function getErrorCode(status) {+ const codeMap = {+ 400: 'BAD_REQUEST',+ 401: 'UNAUTHORIZED',+ 403: 'FORBIDDEN',+ 404: 'NOT_FOUND',+ 409: 'CONFLICT',+ 422: 'VALIDATION_ERROR',+ 500: 'INTERNAL_ERROR',+ 502: 'BAD_GATEWAY',+ 503: 'SERVICE_UNAVAILABLE'+ };+ return codeMap[status] || 'INTERNAL_ERROR';+}++/**+ * Emit error event via Socket.IO to alert UI+ */+export function emitErrorEvent(io, error) {+ errorEvents.emit('error', error);++ // Broadcast to all connected clients+ io.emit('error:occurred', {+ message: error.message,+ code: error.code,+ status: error.status,+ severity: error.severity,+ timestamp: error.timestamp,+ context: error.context,+ canAutoFix: error.canAutoFix+ });++ // If critical, also emit to system/health channel+ if (error.severity === 'critical') {+ io.emit('system:critical-error', {+ message: error.message,+ code: error.code,+ timestamp: error.timestamp,+ context: error.context+ });+ }+}++/**+ * Middleware to handle errors with Socket.IO event emission+ * Use as the last middleware before the app listens+ */+export function errorMiddleware(err, req, res, next) {+ const io = req.app.get('io');+ const error = normalizeError(err);++ // Log the error+ const logMsg = `❌ Server error: ${error.message}`;+ if (error.status >= 500) {+ console.error(logMsg);+ if (err.stack) console.error(err.stack);+ } else {+ console.error(logMsg);+ }++ // Emit Socket.IO event+ if (io) {+ emitErrorEvent(io, error);+ }++ // Send response+ res.status(error.status).json({+ error: error.message,+ code: error.code,+ timestamp: error.timestamp+ });+}++/**+ * Handle unhandled promise rejections with Socket.IO broadcasting+ * Should be called with the io instance+ */+export function setupProcessErrorHandlers(io) {+ process.on('unhandledRejection', (reason, promise) => {+ const error = normalizeError(reason);+ error.severity = 'critical';++ console.error(`❌ Unhandled Promise Rejection: ${error.message}`);+ if (reason instanceof Error) {+ console.error(reason.stack);+ }++ if (io) {+ emitErrorEvent(io, error);+ }+ });++ process.on('uncaughtException', (error) => {+ const serverError = normalizeError(error);+ serverError.severity = 'critical';+ serverError.canAutoFix = true; // Could be auto-fixable++ console.error(`💥 Uncaught Exception: ${serverError.message}`);+ console.error(error.stack);++ if (io) {+ emitErrorEvent(io, serverError);+ }++ // Exit after broadcasting critical error+ process.exit(1);+ });+}diff --git a/server/lib/logger.js b/server/lib/logger.jsnew file mode 100644index 0000000000..957cc32381--- /dev/null+++ b/server/lib/logger.js@@ -0,0 +1,26 @@+/**+ * Simple logger with timestamps+ * Replaces console.log/error with timestamped versions+ */++const originalLog = console.log;+const originalError = console.error;+const originalWarn = console.warn;++function getTimestamp() {+ return new Date().toISOString().replace('T', ' ').substring(0, 19);+}++console.log = (...args) => {+ originalLog(`[${getTimestamp()}]`, ...args);+};++console.error = (...args) => {+ originalError(`[${getTimestamp()}]`, ...args);+};++console.warn = (...args) => {+ originalWarn(`[${getTimestamp()}]`, ...args);+};++export { getTimestamp };diff --git a/server/lib/memoryValidation.js b/server/lib/memoryValidation.jsnew file mode 100644index 0000000000..7613ffbff1--- /dev/null+++ b/server/lib/memoryValidation.js@@ -0,0 +1,111 @@+import { z } from 'zod';++// Memory types enum+export const memoryTypeEnum = z.enum([+ 'fact',+ 'learning',+ 'observation',+ 'decision',+ 'preference',+ 'context'+]);++// Memory status enum+export const memoryStatusEnum = z.enum(['active', 'archived', 'expired']);++// Memory category enum (extensible, but common ones)+export const memoryCategoryEnum = z.enum([+ 'codebase',+ 'workflow',+ 'tools',+ 'architecture',+ 'patterns',+ 'conventions',+ 'preferences',+ 'system',+ 'project',+ 'other'+]);++// Core memory schema for creation+export const memoryCreateSchema = z.object({+ type: memoryTypeEnum,+ content: z.string().min(1).max(10240),+ summary: z.string().max(500).optional(),+ category: z.string().min(1).max(100).optional().default('other'),+ tags: z.array(z.string().max(50)).max(20).optional().default([]),+ confidence: z.number().min(0).max(1).optional().default(0.8),+ importance: z.number().min(0).max(1).optional().default(0.5),+ relatedMemories: z.array(z.string().uuid()).optional().default([]),+ sourceTaskId: z.string().optional(),+ sourceAgentId: z.string().optional()+});++// Full memory schema (includes system-generated fields)+export const memorySchema = memoryCreateSchema.extend({+ id: z.string().uuid(),+ embedding: z.array(z.number()).optional(),+ embeddingModel: z.string().optional(),+ accessCount: z.number().int().min(0).default(0),+ lastAccessed: z.string().datetime().optional(),+ createdAt: z.string().datetime(),+ updatedAt: z.string().datetime(),+ expiresAt: z.string().datetime().nullable().optional(),+ status: memoryStatusEnum.default('active')+});++// Partial schema for updates+export const memoryUpdateSchema = memoryCreateSchema.partial().extend({+ status: memoryStatusEnum.optional()+});++// Search query schema+export const memorySearchSchema = z.object({+ query: z.string().min(1).max(1000),+ types: z.array(memoryTypeEnum).optional(),+ categories: z.array(z.string()).optional(),+ tags: z.array(z.string()).optional(),+ status: memoryStatusEnum.optional().default('active'),+ minRelevance: z.number().min(0).max(1).optional().default(0.7),+ limit: z.number().int().min(1).max(100).optional().default(20),+ offset: z.number().int().min(0).optional().default(0)+});++// List/filter query schema+export const memoryListSchema = z.object({+ types: z.array(memoryTypeEnum).optional(),+ categories: z.array(z.string()).optional(),+ tags: z.array(z.string()).optional(),+ status: memoryStatusEnum.optional().default('active'),+ limit: z.number().int().min(1).max(100).optional().default(50),+ offset: z.number().int().min(0).optional().default(0),+ sortBy: z.enum(['createdAt', 'updatedAt', 'importance', 'accessCount']).optional().default('createdAt'),+ sortOrder: z.enum(['asc', 'desc']).optional().default('desc')+});++// Timeline query schema+export const memoryTimelineSchema = z.object({+ startDate: z.string().datetime().optional(),+ endDate: z.string().datetime().optional(),+ types: z.array(memoryTypeEnum).optional(),+ limit: z.number().int().min(1).max(500).optional().default(100)+});++// Memory extraction request schema (from agent output)+export const memoryExtractSchema = z.object({+ agentId: z.string(),+ taskId: z.string(),+ output: z.string().min(1)+});++// Memory consolidation request schema+export const memoryConsolidateSchema = z.object({+ similarityThreshold: z.number().min(0.5).max(1).optional().default(0.9),+ dryRun: z.boolean().optional().default(false)+});++// Link memories request schema+export const memoryLinkSchema = z.object({+ sourceId: z.string().uuid(),+ targetId: z.string().uuid()+});diff --git a/server/lib/taskParser.js b/server/lib/taskParser.jsnew file mode 100644index 0000000000..e57447281f--- /dev/null+++ b/server/lib/taskParser.js@@ -0,0 +1,311 @@+/**+ * Task Parser for TASKS.md format+ *+ * Parses markdown task files with the following format:+ *+ * # Tasks+ *+ * ## Pending+ * - [ ] #task-001 | HIGH | Task description+ * - Context: Additional context+ * - App: app-name+ *+ * ## In Progress+ * - [~] #task-002 | MEDIUM | Another task+ * - Agent: agent-id+ * - Started: 2024-01-15T10:30:00Z+ *+ * ## Blocked+ * - [!] #task-003 | HIGH | Blocked task+ * - Blocker: Waiting for API access+ *+ * ## Completed+ * - [x] #task-004 | LOW | Done task+ * - Completed: 2024-01-14T15:45:00Z+ *+ * Internal CoS tasks can have approval flags:+ * - [ ] #sys-001 | HIGH | AUTO | Auto-approved task+ * - [ ] #sys-002 | MEDIUM | APPROVAL | Needs user approval+ */++const STATUS_MAP = {+ '[ ]': 'pending',+ '[~]': 'in_progress',+ '[x]': 'completed',+ '[!]': 'blocked'+};++const PRIORITY_VALUES = {+ 'CRITICAL': 4,+ 'HIGH': 3,+ 'MEDIUM': 2,+ 'LOW': 1+};++/**+ * Parse a single task line+ * Format: - [ ] #task-001 | HIGH | Description+ * Or with approval flag: - [ ] #sys-001 | HIGH | AUTO | Description+ */+function parseTaskLine(line) {+ // First try: - [status] #id | PRIORITY | APPROVAL_FLAG | description+ let match = line.match(/^-\s*\[([ x~!])\]\s*#([\w-]+)\s*\|\s*(CRITICAL|HIGH|MEDIUM|LOW)\s*\|\s*(AUTO|APPROVAL)\s*\|\s*(.+)$/i);++ if (match) {+ const [, statusChar, id, priority, approvalFlag, description] = match;+ const statusKey = `[${statusChar}]`;++ return {+ id: id.startsWith('task-') || id.startsWith('sys-') ? id : `task-${id}`,+ status: STATUS_MAP[statusKey] || 'pending',+ priority: priority.toUpperCase(),+ priorityValue: PRIORITY_VALUES[priority.toUpperCase()] || 2,+ approvalRequired: approvalFlag.toUpperCase() === 'APPROVAL',+ autoApproved: approvalFlag.toUpperCase() === 'AUTO',+ description: description.trim(),+ metadata: {}+ };+ }++ // Fallback: - [status] #id | PRIORITY | description (no approval flag)+ match = line.match(/^-\s*\[([ x~!])\]\s*#([\w-]+)\s*\|\s*(CRITICAL|HIGH|MEDIUM|LOW)\s*\|\s*(.+)$/i);++ if (!match) return null;++ const [, statusChar, id, priority, description] = match;+ const statusKey = `[${statusChar}]`;++ return {+ id: id.startsWith('task-') || id.startsWith('sys-') ? id : `task-${id}`,+ status: STATUS_MAP[statusKey] || 'pending',+ priority: priority.toUpperCase(),+ priorityValue: PRIORITY_VALUES[priority.toUpperCase()] || 2,+ approvalRequired: false,+ autoApproved: true,+ description: description.trim(),+ metadata: {}+ };+}++/**+ * Parse metadata line (indented under task)+ * Format: - Key: Value+ */+function parseMetadataLine(line) {+ const match = line.match(/^\s+-\s*(\w+):\s*(.+)$/);+ if (!match) return null;++ return {+ key: match[1].toLowerCase(),+ value: match[2].trim()+ };+}++/**+ * Parse TASKS.md content into structured data+ */+export function parseTasksMarkdown(content) {+ const lines = content.split('\n');+ const tasks = [];+ let currentTask = null;+ let currentSection = null;++ for (const line of lines) {+ // Section headers+ if (line.startsWith('## ')) {+ currentSection = line.slice(3).trim().toLowerCase().replace(/\s+/g, '_');+ continue;+ }++ // Skip main title and empty lines+ if (line.startsWith('# ') || line.trim() === '') {+ continue;+ }++ // Task line+ if (line.startsWith('- [')) {+ if (currentTask) {+ tasks.push(currentTask);+ }+ currentTask = parseTaskLine(line);+ if (currentTask) {+ currentTask.section = currentSection;+ }+ continue;+ }++ // Metadata line (indented)+ if (currentTask && line.match(/^\s+-\s*\w+:/)) {+ const meta = parseMetadataLine(line);+ if (meta) {+ currentTask.metadata[meta.key] = meta.value;+ }+ }+ }++ // Don't forget last task+ if (currentTask) {+ tasks.push(currentTask);+ }++ return tasks;+}++/**+ * Group tasks by status+ */+export function groupTasksByStatus(tasks) {+ return {+ pending: tasks.filter(t => t.status === 'pending'),+ in_progress: tasks.filter(t => t.status === 'in_progress'),+ blocked: tasks.filter(t => t.status === 'blocked'),+ completed: tasks.filter(t => t.status === 'completed')+ };+}++/**+ * Sort tasks by priority (highest first)+ */+export function sortByPriority(tasks) {+ return [...tasks].sort((a, b) => b.priorityValue - a.priorityValue);+}++/**+ * Generate TASKS.md content from tasks array+ * @param {boolean} includeApprovalFlags - Whether to include AUTO/APPROVAL flags (for internal CoS tasks)+ */+export function generateTasksMarkdown(tasks, includeApprovalFlags = false) {+ const grouped = groupTasksByStatus(tasks);+ const lines = ['# Tasks', ''];++ const statusToCheckbox = {+ 'pending': '[ ]',+ 'in_progress': '[~]',+ 'blocked': '[!]',+ 'completed': '[x]'+ };++ const sections = [+ { key: 'pending', title: 'Pending' },+ { key: 'in_progress', title: 'In Progress' },+ { key: 'blocked', title: 'Blocked' },+ { key: 'completed', title: 'Completed' }+ ];++ for (const section of sections) {+ const sectionTasks = grouped[section.key];+ if (sectionTasks.length === 0) continue;++ lines.push(`## ${section.title}`);++ for (const task of sortByPriority(sectionTasks)) {+ const checkbox = statusToCheckbox[task.status];+ const approvalFlag = includeApprovalFlags && (task.approvalRequired || task.autoApproved !== undefined)+ ? ` | ${task.approvalRequired ? 'APPROVAL' : 'AUTO'}`+ : '';+ lines.push(`- ${checkbox} #${task.id} | ${task.priority}${approvalFlag} | ${task.description}`);++ // Add metadata+ for (const [key, value] of Object.entries(task.metadata)) {+ const capitalizedKey = key.charAt(0).toUpperCase() + key.slice(1);+ lines.push(` - ${capitalizedKey}: ${value}`);+ }+ }++ lines.push('');+ }++ return lines.join('\n');+}++/**+ * Filter tasks that can be auto-executed+ */+export function getAutoApprovedTasks(tasks) {+ return tasks.filter(t => t.autoApproved && !t.approvalRequired && t.status === 'pending');+}++/**+ * Filter tasks awaiting user approval+ */+export function getAwaitingApprovalTasks(tasks) {+ return tasks.filter(t => t.approvalRequired && t.status === 'pending');+}++/**+ * Update a task's status in the tasks array+ */+export function updateTaskStatus(tasks, taskId, newStatus, metadata = {}) {+ return tasks.map(task => {+ if (task.id === taskId) {+ return {+ ...task,+ status: newStatus,+ metadata: { ...task.metadata, ...metadata }+ };+ }+ return task;+ });+}++/**+ * Add a new task+ */+export function addTask(tasks, { id, priority = 'MEDIUM', description, metadata = {} }) {+ const newTask = {+ id: id.startsWith('task-') ? id : `task-${id}`,+ status: 'pending',+ priority: priority.toUpperCase(),+ priorityValue: PRIORITY_VALUES[priority.toUpperCase()] || 2,+ description,+ metadata,+ section: 'pending'+ };++ return [...tasks, newTask];+}++/**+ * Remove a task by ID+ */+export function removeTask(tasks, taskId) {+ return tasks.filter(t => t.id !== taskId);+}++/**+ * Get next pending task (highest priority)+ */+export function getNextTask(tasks) {+ const pending = tasks.filter(t => t.status === 'pending');+ if (pending.length === 0) return null;++ return sortByPriority(pending)[0];+}++/**+ * Validate task format+ */+export function validateTask(task) {+ const errors = [];++ if (!task.id || typeof task.id !== 'string') {+ errors.push('Task must have a valid id');+ }++ if (!task.description || typeof task.description !== 'string') {+ errors.push('Task must have a description');+ }++ if (!['pending', 'in_progress', 'blocked', 'completed'].includes(task.status)) {+ errors.push('Invalid task status');+ }++ if (!Object.keys(PRIORITY_VALUES).includes(task.priority)) {+ errors.push('Invalid priority (must be CRITICAL, HIGH, MEDIUM, or LOW)');+ }++ return {+ valid: errors.length === 0,+ errors+ };+}diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 2cacf1ba1a..0c3597c4bc 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1,5 +1,12 @@import { z } from 'zod';+// Process definition schema (for PM2 processes with ports)+export const processSchema = z.object({+ name: z.string().min(1),+ port: z.number().int().min(1).max(65535).nullable().optional(),+ description: z.string().optional()+});+// App schema for registration/updateexport const appSchema = z.object({name: z.string().min(1).max(100),@@ -10,6 +17,7 @@ export const appSchema = z.object({uiUrl: z.string().url().optional(),startCommands: z.array(z.string()).min(1).optional(),pm2ProcessNames: z.array(z.string()).optional(),+ processes: z.array(processSchema).optional(), // Per-process port configs from ecosystem.configenvFile: z.string().optional(),icon: z.string().nullable().optional(),editorCommand: z.string().optional(),diff --git a/server/lib/vectorMath.js b/server/lib/vectorMath.jsnew file mode 100644index 0000000000..b3e430d2f5--- /dev/null+++ b/server/lib/vectorMath.js@@ -0,0 +1,175 @@+/**+ * Vector Math Utilities+ *+ * Pure functions for vector operations used in semantic search.+ */++/**+ * Calculate cosine similarity between two vectors+ * Returns value between -1 and 1, where 1 means identical direction+ */+export function cosineSimilarity(a, b) {+ if (!a || !b || a.length !== b.length || a.length === 0) {+ return 0;+ }++ let dotProduct = 0;+ let normA = 0;+ let normB = 0;++ for (let i = 0; i < a.length; i++) {+ dotProduct += a[i] * b[i];+ normA += a[i] * a[i];+ normB += b[i] * b[i];+ }++ const denominator = Math.sqrt(normA) * Math.sqrt(normB);+ return denominator === 0 ? 0 : dotProduct / denominator;+}++/**+ * Calculate Euclidean distance between two vectors+ * Lower values mean more similar+ */+export function euclideanDistance(a, b) {+ if (!a || !b || a.length !== b.length || a.length === 0) {+ return Infinity;+ }++ let sum = 0;+ for (let i = 0; i < a.length; i++) {+ const diff = a[i] - b[i];+ sum += diff * diff;+ }++ return Math.sqrt(sum);+}++/**+ * Normalize a vector to unit length+ */+export function normalize(v) {+ if (!v || v.length === 0) return [];++ let norm = 0;+ for (let i = 0; i < v.length; i++) {+ norm += v[i] * v[i];+ }+ norm = Math.sqrt(norm);++ if (norm === 0) return v.map(() => 0);+ return v.map(x => x / norm);+}++/**+ * Find top K most similar vectors from a collection+ * Returns array of { id, similarity } sorted by similarity descending+ */+export function findTopK(queryVector, vectors, k = 10) {+ if (!queryVector || !vectors || Object.keys(vectors).length === 0) {+ return [];+ }++ const similarities = Object.entries(vectors).map(([id, vector]) => ({+ id,+ similarity: cosineSimilarity(queryVector, vector)+ }));++ similarities.sort((a, b) => b.similarity - a.similarity);++ return similarities.slice(0, k);+}++/**+ * Find vectors above a similarity threshold+ * Returns array of { id, similarity } sorted by similarity descending+ */+export function findAboveThreshold(queryVector, vectors, threshold = 0.7) {+ if (!queryVector || !vectors || Object.keys(vectors).length === 0) {+ return [];+ }++ const results = Object.entries(vectors)+ .map(([id, vector]) => ({+ id,+ similarity: cosineSimilarity(queryVector, vector)+ }))+ .filter(item => item.similarity >= threshold);++ results.sort((a, b) => b.similarity - a.similarity);++ return results;+}++/**+ * Calculate average vector from multiple vectors+ * Useful for combining related memories+ */+export function averageVectors(vectors) {+ if (!vectors || vectors.length === 0) return [];++ const dimension = vectors[0].length;+ const result = new Array(dimension).fill(0);++ for (const v of vectors) {+ for (let i = 0; i < dimension; i++) {+ result[i] += v[i];+ }+ }++ const count = vectors.length;+ return result.map(x => x / count);+}++/**+ * Cluster vectors by similarity using simple single-linkage clustering+ * Returns array of clusters, each cluster is array of { id, vector }+ */+export function clusterBySimilarity(items, threshold = 0.9) {+ if (!items || items.length === 0) return [];++ const clusters = [];+ const assigned = new Set();++ for (const item of items) {+ if (assigned.has(item.id)) continue;++ const cluster = [item];+ assigned.add(item.id);++ for (const other of items) {+ if (assigned.has(other.id)) continue;++ const similarity = cosineSimilarity(item.embedding, other.embedding);+ if (similarity >= threshold) {+ cluster.push(other);+ assigned.add(other.id);+ }+ }++ clusters.push(cluster);+ }++ return clusters;+}++/**+ * Compute pairwise similarity matrix for a set of vectors+ * Returns object with { ids, matrix } where matrix[i][j] is similarity between ids[i] and ids[j]+ */+export function similarityMatrix(vectors) {+ const ids = Object.keys(vectors);+ const n = ids.length;+ const matrix = Array(n).fill(null).map(() => Array(n).fill(0));++ for (let i = 0; i < n; i++) {+ matrix[i][i] = 1;+ for (let j = i + 1; j < n; j++) {+ const sim = cosineSimilarity(vectors[ids[i]], vectors[ids[j]]);+ matrix[i][j] = sim;+ matrix[j][i] = sim;+ }+ }++ return { ids, matrix };+}diff --git a/server/package-lock.json b/server/package-lock.jsonindex e3ec431923..ff46793d75 100644--- a/server/package-lock.json+++ b/server/package-lock.json@@ -1,12 +1,12 @@{"name": "portos-server",- "version": "0.2.0",+ "version": "0.4.7","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "portos-server",- "version": "0.2.0",+ "version": "0.4.7","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/server/routes/agents.js b/server/routes/agents.jsindex c9acd9cab3..e9a68125f7 100644--- a/server/routes/agents.js+++ b/server/routes/agents.js@@ -1,29 +1,30 @@import { Router } from 'express';import { getRunningAgents, killProcess, getProcessInfo } from '../services/agents.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();// GET /api/agents - Get all running AI agents-router.get('/', async (req, res) => {+router.get('/', asyncHandler(async (req, res) => {const agents = await getRunningAgents();res.json(agents);-});+}));// GET /api/agents/:pid - Get specific process info-router.get('/:pid', async (req, res) => {+router.get('/:pid', asyncHandler(async (req, res) => {const pid = parseInt(req.params.pid);const info = await getProcessInfo(pid);if (!info) {- return res.status(404).json({ error: 'Process not found' });+ throw new ServerError('Process not found', { status: 404, code: 'NOT_FOUND' });}res.json(info);-});+}));// DELETE /api/agents/:pid - Kill a process-router.delete('/:pid', async (req, res) => {+router.delete('/:pid', asyncHandler(async (req, res) => {const pid = parseInt(req.params.pid);await killProcess(pid);res.json({ success: true, pid });-});+}));export default router;diff --git a/server/routes/apps.js b/server/routes/apps.jsindex caf875bd2a..95e6954203 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -5,11 +5,13 @@ import * as appsService from '../services/apps.js';import * as pm2Service from '../services/pm2.js';import { logAction } from '../services/history.js';import { validate, appSchema, appUpdateSchema } from '../lib/validation.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { parseEcosystemFromPath } from '../services/streamingDetect.js';const router = Router();// GET /api/apps - List all apps-router.get('/', async (req, res, next) => {+router.get('/', asyncHandler(async (req, res, next) => {console.log('📱 GET /api/apps - fetching apps list');const apps = await appsService.getAllApps();console.log(`📱 GET /api/apps - found ${apps.length} apps`);@@ -18,8 +20,8 @@ router.get('/', async (req, res, next) => {const allPm2 = await pm2Service.listProcesses().catch(() => []);const pm2Map = new Map(allPm2.map(p => [p.name, p]));- // Enrich with PM2 status- const enriched = apps.map((app) => {+ // Enrich with PM2 status and auto-populate processes if needed+ const enriched = await Promise.all(apps.map(async (app) => {const statuses = {};for (const processName of app.pm2ProcessNames || []) {const pm2Proc = pm2Map.get(processName);@@ -37,23 +39,30 @@ router.get('/', async (req, res, next) => {overallStatus = 'not_started';}+ // Auto-populate processes from ecosystem config if not already set+ let processes = app.processes;+ if ((!processes || processes.length === 0) && existsSync(app.repoPath)) {+ processes = await parseEcosystemFromPath(app.repoPath).catch(() => []);+ }+return {...app,+ processes,pm2Status: statuses,overallStatus};- });+ }));console.log(`📱 GET /api/apps - responding with ${enriched.length} apps`);res.json(enriched);-});+}));// GET /api/apps/:id - Get single app-router.get('/:id', async (req, res, next) => {+router.get('/:id', asyncHandler(async (req, res, next) => {const app = await appsService.getAppById(req.params.id);if (!app) {- return res.status(404).json({ error: 'App not found', code: 'NOT_FOUND' });+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}// Get PM2 status for each process@@ -64,62 +73,62 @@ router.get('/:id', async (req, res, next) => {}res.json({ ...app, pm2Status: statuses });-});+}));// POST /api/apps - Create new app-router.post('/', async (req, res, next) => {+router.post('/', asyncHandler(async (req, res, next) => {const validation = validate(appSchema, req.body);if (!validation.success) {- return res.status(400).json({- error: 'Validation failed',+ throw new ServerError('Validation failed', {+ status: 400,code: 'VALIDATION_ERROR',- details: validation.errors+ context: { details: validation.errors }});}const app = await appsService.createApp(validation.data);res.status(201).json(app);-});+}));// PUT /api/apps/:id - Update app-router.put('/:id', async (req, res, next) => {+router.put('/:id', asyncHandler(async (req, res, next) => {const validation = validate(appUpdateSchema, req.body);if (!validation.success) {- return res.status(400).json({- error: 'Validation failed',+ throw new ServerError('Validation failed', {+ status: 400,code: 'VALIDATION_ERROR',- details: validation.errors+ context: { details: validation.errors }});}const app = await appsService.updateApp(req.params.id, validation.data);if (!app) {- return res.status(404).json({ error: 'App not found', code: 'NOT_FOUND' });+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}res.json(app);-});+}));// DELETE /api/apps/:id - Delete app-router.delete('/:id', async (req, res, next) => {+router.delete('/:id', asyncHandler(async (req, res, next) => {const deleted = await appsService.deleteApp(req.params.id);if (!deleted) {- return res.status(404).json({ error: 'App not found', code: 'NOT_FOUND' });+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}res.status(204).send();-});+}));// POST /api/apps/:id/start - Start app via PM2-router.post('/:id/start', async (req, res, next) => {+router.post('/:id/start', asyncHandler(async (req, res, next) => {const app = await appsService.getAppById(req.params.id);if (!app) {- return res.status(404).json({ error: 'App not found', code: 'NOT_FOUND' });+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}const results = {};@@ -139,14 +148,14 @@ router.post('/:id/start', async (req, res, next) => {await logAction('start', app.id, app.name, { processNames }, allSuccess);res.json({ success: true, results });-});+}));// POST /api/apps/:id/stop - Stop app-router.post('/:id/stop', async (req, res, next) => {+router.post('/:id/stop', asyncHandler(async (req, res, next) => {const app = await appsService.getAppById(req.params.id);if (!app) {- return res.status(404).json({ error: 'App not found', code: 'NOT_FOUND' });+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}const results = {};@@ -161,14 +170,14 @@ router.post('/:id/stop', async (req, res, next) => {await logAction('stop', app.id, app.name, { processNames: app.pm2ProcessNames }, allSuccess);res.json({ success: true, results });-});+}));// POST /api/apps/:id/restart - Restart app-router.post('/:id/restart', async (req, res, next) => {+router.post('/:id/restart', asyncHandler(async (req, res, next) => {const app = await appsService.getAppById(req.params.id);if (!app) {- return res.status(404).json({ error: 'App not found', code: 'NOT_FOUND' });+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}const results = {};@@ -183,14 +192,14 @@ router.post('/:id/restart', async (req, res, next) => {await logAction('restart', app.id, app.name, { processNames: app.pm2ProcessNames }, allSuccess);res.json({ success: true, results });-});+}));// GET /api/apps/:id/status - Get PM2 status-router.get('/:id/status', async (req, res, next) => {+router.get('/:id/status', asyncHandler(async (req, res, next) => {const app = await appsService.getAppById(req.params.id);if (!app) {- return res.status(404).json({ error: 'App not found', code: 'NOT_FOUND' });+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}const statuses = {};@@ -202,39 +211,39 @@ router.get('/:id/status', async (req, res, next) => {}res.json(statuses);-});+}));// GET /api/apps/:id/logs - Get logs-router.get('/:id/logs', async (req, res, next) => {+router.get('/:id/logs', asyncHandler(async (req, res, next) => {const app = await appsService.getAppById(req.params.id);if (!app) {- return res.status(404).json({ error: 'App not found', code: 'NOT_FOUND' });+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}const lines = parseInt(req.query.lines) || 100;const processName = req.query.process || app.pm2ProcessNames?.[0];if (!processName) {- return res.status(400).json({ error: 'No process name specified', code: 'MISSING_PROCESS' });+ throw new ServerError('No process name specified', { status: 400, code: 'MISSING_PROCESS' });}const logs = await pm2Service.getLogs(processName, lines).catch(err => `Error retrieving logs: ${err.message}`);res.json({ processName, lines, logs });-});+}));// POST /api/apps/:id/open-editor - Open app in editor-router.post('/:id/open-editor', async (req, res, next) => {+router.post('/:id/open-editor', asyncHandler(async (req, res, next) => {const app = await appsService.getAppById(req.params.id);if (!app) {- return res.status(404).json({ error: 'App not found', code: 'NOT_FOUND' });+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}if (!existsSync(app.repoPath)) {- return res.status(400).json({ error: 'App path does not exist', code: 'PATH_NOT_FOUND' });+ throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });}const editorCommand = app.editorCommand || 'code .';@@ -249,18 +258,18 @@ router.post('/:id/open-editor', async (req, res, next) => {child.unref();res.json({ success: true, command: editorCommand, path: app.repoPath });-});+}));// POST /api/apps/:id/open-folder - Open app folder in file manager-router.post('/:id/open-folder', async (req, res, next) => {+router.post('/:id/open-folder', asyncHandler(async (req, res, next) => {const app = await appsService.getAppById(req.params.id);if (!app) {- return res.status(404).json({ error: 'App not found', code: 'NOT_FOUND' });+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}if (!existsSync(app.repoPath)) {- return res.status(400).json({ error: 'App path does not exist', code: 'PATH_NOT_FOUND' });+ throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });}// Cross-platform folder open command@@ -285,6 +294,46 @@ router.post('/:id/open-folder', async (req, res, next) => {child.unref();res.json({ success: true, path: app.repoPath });-});+}));++// POST /api/apps/:id/refresh-config - Re-parse ecosystem config for PM2 processes+router.post('/:id/refresh-config', 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' });+ }++ if (!existsSync(app.repoPath)) {+ throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });+ }++ // Parse ecosystem config from the app's repo path+ const processes = await parseEcosystemFromPath(app.repoPath);++ // Update app with new process data+ const updates = {};++ if (processes.length > 0) {+ updates.processes = processes;+ updates.pm2ProcessNames = processes.map(p => p.name);++ // Update apiPort if we found one and it's different+ const processWithPort = processes.find(p => p.port);+ if (processWithPort && processWithPort.port !== app.apiPort) {+ updates.apiPort = processWithPort.port;+ }+ }++ // Only update if we have changes+ if (Object.keys(updates).length > 0) {+ const updatedApp = await appsService.updateApp(req.params.id, updates);+ console.log(`🔄 Refreshed config for ${app.name}: ${processes.length} processes found`);+ res.json({ success: true, updated: true, app: updatedApp, processes });+ } else {+ console.log(`🔄 No config changes for ${app.name}`);+ res.json({ success: true, updated: false, app, processes: app.processes || [] });+ }+}));export default router;diff --git a/server/routes/commands.js b/server/routes/commands.jsindex 56dd036dc5..4b38117d41 100644--- a/server/routes/commands.js+++ b/server/routes/commands.js@@ -1,15 +1,16 @@import { Router } from 'express';import * as commands from '../services/commands.js';import * as pm2Service from '../services/pm2.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();// POST /api/commands/execute - Execute a command-router.post('/execute', (req, res) => {+router.post('/execute', asyncHandler(async (req, res) => {const { command, workspacePath } = req.body;if (!command) {- return res.status(400).json({ error: 'Command is required', code: 'MISSING_COMMAND' });+ throw new ServerError('Command is required', { status: 400, code: 'MISSING_COMMAND' });}const io = req.app.get('io');@@ -26,42 +27,41 @@ router.post('/execute', (req, res) => {);if (!commandId) {- return res.status(403).json({ error: 'Command not allowed', code: 'FORBIDDEN' });+ throw new ServerError('Command not allowed', { status: 403, code: 'FORBIDDEN' });}res.status(202).json({ commandId, status: 'started' });-});+}));// POST /api/commands/:id/stop - Stop a running command-router.post('/:id/stop', (req, res) => {+router.post('/:id/stop', asyncHandler(async (req, res) => {const stopped = commands.stopCommand(req.params.id);if (!stopped) {- return res.status(404).json({ error: 'Command not found or not active', code: 'NOT_ACTIVE' });+ throw new ServerError('Command not found or not active', { status: 404, code: 'NOT_ACTIVE' });}res.json({ stopped: true });-});+}));// GET /api/commands/allowed - Get allowed commands-router.get('/allowed', (req, res) => {+router.get('/allowed', asyncHandler(async (req, res) => {res.json(commands.getAllowedCommands());-});+}));// GET /api/commands/processes - Get PM2 process list with details-router.get('/processes', async (req, res, next) => {- const processes = await pm2Service.listProcesses().catch(next);- if (processes) res.json(processes);-});+router.get('/processes', asyncHandler(async (req, res) => {+ const processes = await pm2Service.listProcesses();+ res.json(processes);+}));// GET /api/commands/processes/:name/monit - Get PM2 monit data for a process-router.get('/processes/:name/monit', async (req, res, next) => {- const processes = await pm2Service.listProcesses().catch(next);- if (!processes) return;-+router.get('/processes/:name/monit', asyncHandler(async (req, res) => {+ const processes = await pm2Service.listProcesses();const process = processes.find(p => p.name === req.params.name);+if (!process) {- return res.status(404).json({ error: 'Process not found', code: 'NOT_FOUND' });+ throw new ServerError('Process not found', { status: 404, code: 'NOT_FOUND' });}res.json({@@ -73,6 +73,6 @@ router.get('/processes/:name/monit', async (req, res, next) => {uptime: process.uptime,restarts: process.restarts});-});+}));export default router;diff --git a/server/routes/cos.js b/server/routes/cos.jsnew file mode 100644index 0000000000..fd369215d5--- /dev/null+++ b/server/routes/cos.js@@ -0,0 +1,238 @@+/**+ * Chief of Staff API Routes+ */++import { Router } from 'express';+import * as cos from '../services/cos.js';+import * as taskWatcher from '../services/taskWatcher.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';++const router = Router();++// GET /api/cos - Get CoS status+router.get('/', asyncHandler(async (req, res) => {+ const status = await cos.getStatus();+ res.json(status);+}));++// POST /api/cos/start - Start CoS daemon+router.post('/start', asyncHandler(async (req, res) => {+ const result = await cos.start();+ await taskWatcher.startWatching();+ res.json(result);+}));++// POST /api/cos/stop - Stop CoS daemon+router.post('/stop', asyncHandler(async (req, res) => {+ const result = await cos.stop();+ await taskWatcher.stopWatching();+ res.json(result);+}));++// GET /api/cos/config - Get configuration+router.get('/config', asyncHandler(async (req, res) => {+ const config = await cos.getConfig();+ res.json(config);+}));++// PUT /api/cos/config - Update configuration+router.put('/config', asyncHandler(async (req, res) => {+ const config = await cos.updateConfig(req.body);+ res.json(config);+}));++// GET /api/cos/tasks - Get all tasks+router.get('/tasks', asyncHandler(async (req, res) => {+ const tasks = await cos.getAllTasks();+ res.json(tasks);+}));++// GET /api/cos/tasks/user - Get user tasks+router.get('/tasks/user', asyncHandler(async (req, res) => {+ const tasks = await cos.getUserTasks();+ res.json(tasks);+}));++// GET /api/cos/tasks/internal - Get CoS internal tasks+router.get('/tasks/internal', asyncHandler(async (req, res) => {+ const tasks = await cos.getCosTasks();+ res.json(tasks);+}));++// POST /api/cos/tasks/refresh - Force refresh tasks+router.post('/tasks/refresh', asyncHandler(async (req, res) => {+ const tasks = await taskWatcher.refreshTasks();+ res.json(tasks);+}));++// POST /api/cos/tasks/reorder - Reorder tasks+router.post('/tasks/reorder', asyncHandler(async (req, res) => {+ const { taskIds } = req.body;++ if (!taskIds || !Array.isArray(taskIds)) {+ throw new ServerError('taskIds array is required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ const result = await cos.reorderTasks(taskIds);+ res.json(result);+}));++// POST /api/cos/tasks - Add a new task+router.post('/tasks', asyncHandler(async (req, res) => {+ const { description, priority, context, model, provider, type = 'user', approvalRequired } = req.body;++ if (!description) {+ throw new ServerError('Description is required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ const taskData = { description, priority, context, model, provider, approvalRequired };+ const result = await cos.addTask(taskData, type);+ res.json(result);+}));++// PUT /api/cos/tasks/:id - Update a task+router.put('/tasks/:id', asyncHandler(async (req, res) => {+ const { id } = req.params;+ const { description, priority, status, context, model, provider, type = 'user' } = req.body;++ const updates = {};+ if (description !== undefined) updates.description = description;+ if (priority !== undefined) updates.priority = priority;+ if (status !== undefined) updates.status = status;+ if (context !== undefined) updates.context = context;+ if (model !== undefined) updates.model = model;+ if (provider !== undefined) updates.provider = provider;++ const result = await cos.updateTask(id, updates, type);+ if (result?.error) {+ throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });+ }+ res.json(result);+}));++// DELETE /api/cos/tasks/:id - Delete a task+router.delete('/tasks/:id', asyncHandler(async (req, res) => {+ const { id } = req.params;+ const { type = 'user' } = req.query;++ const result = await cos.deleteTask(id, type);+ if (result?.error) {+ throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });+ }+ res.json(result);+}));++// POST /api/cos/tasks/:id/approve - Approve a task+router.post('/tasks/:id/approve', asyncHandler(async (req, res) => {+ const { id } = req.params;++ const result = await cos.approveTask(id);+ if (result?.error) {+ throw new ServerError(result.error, { status: 400, code: 'BAD_REQUEST' });+ }+ res.json(result);+}));++// POST /api/cos/evaluate - Force task evaluation+router.post('/evaluate', asyncHandler(async (req, res) => {+ await cos.evaluateTasks();+ res.json({ success: true, message: 'Evaluation triggered' });+}));++// GET /api/cos/health - Get health status+router.get('/health', asyncHandler(async (req, res) => {+ const health = await cos.getHealthStatus();+ res.json(health);+}));++// POST /api/cos/health/check - Force health check+router.post('/health/check', asyncHandler(async (req, res) => {+ const result = await cos.runHealthCheck();+ res.json(result);+}));++// GET /api/cos/agents - Get all agents+router.get('/agents', asyncHandler(async (req, res) => {+ const agents = await cos.getAgents();+ res.json(agents);+}));++// GET /api/cos/agents/:id - Get agent by ID+router.get('/agents/:id', asyncHandler(async (req, res) => {+ const agent = await cos.getAgent(req.params.id);+ if (!agent) {+ throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(agent);+}));++// POST /api/cos/agents/:id/terminate - Terminate agent+router.post('/agents/:id/terminate', asyncHandler(async (req, res) => {+ const result = await cos.terminateAgent(req.params.id);+ res.json(result);+}));++// DELETE /api/cos/agents/:id - Delete a single agent+router.delete('/agents/:id', asyncHandler(async (req, res) => {+ const result = await cos.deleteAgent(req.params.id);+ if (result?.error) {+ throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });+ }+ res.json(result);+}));++// DELETE /api/cos/agents/completed - Clear completed agents+router.delete('/agents/completed', asyncHandler(async (req, res) => {+ const result = await cos.clearCompletedAgents();+ res.json(result);+}));++// GET /api/cos/reports - List all reports+router.get('/reports', asyncHandler(async (req, res) => {+ const reports = await cos.listReports();+ res.json(reports);+}));++// GET /api/cos/reports/today - Get today's report+router.get('/reports/today', asyncHandler(async (req, res) => {+ const report = await cos.getTodayReport();+ res.json(report);+}));++// GET /api/cos/reports/:date - Get report by date+router.get('/reports/:date', asyncHandler(async (req, res) => {+ const report = await cos.getReport(req.params.date);+ if (!report) {+ throw new ServerError('Report not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(report);+}));++// POST /api/cos/reports/generate - Generate report for date+router.post('/reports/generate', asyncHandler(async (req, res) => {+ const { date } = req.body;+ const report = await cos.generateReport(date);+ res.json(report);+}));++// GET /api/cos/scripts - List generated scripts+router.get('/scripts', asyncHandler(async (req, res) => {+ const scripts = await cos.listScripts();+ res.json(scripts);+}));++// GET /api/cos/scripts/:name - Get script content+router.get('/scripts/:name', asyncHandler(async (req, res) => {+ const script = await cos.getScript(req.params.name);+ if (!script) {+ throw new ServerError('Script not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(script);+}));++// GET /api/cos/watcher - Get watcher status+router.get('/watcher', (req, res) => {+ res.json(taskWatcher.getWatcherStatus());+});++export default router;diff --git a/server/routes/detect.js b/server/routes/detect.jsindex 60c2b582e0..090e8b7cb1 100644--- a/server/routes/detect.js+++ b/server/routes/detect.js@@ -5,16 +5,17 @@ import { join } from 'path';import { exec } from 'child_process';import { promisify } from 'util';import { detectAppWithAi } from '../services/aiDetect.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';const execAsync = promisify(exec);const router = Router();// POST /api/detect/repo - Validate repo path and detect project type-router.post('/repo', async (req, res) => {+router.post('/repo', asyncHandler(async (req, res) => {const { path } = req.body;if (!path) {- return res.status(400).json({ error: 'Path is required', code: 'MISSING_PATH' });+ throw new ServerError('Path is required', { status: 400, code: 'MISSING_PATH' });}// Check if path exists@@ -110,14 +111,14 @@ router.post('/repo', async (req, res) => {}res.json(result);-});+}));// POST /api/detect/port - Detect what process is running on a port-router.post('/port', async (req, res) => {+router.post('/port', asyncHandler(async (req, res) => {const { port } = req.body;if (!port || isNaN(port)) {- return res.status(400).json({ error: 'Valid port number is required', code: 'INVALID_PORT' });+ throw new ServerError('Valid port number is required', { status: 400, code: 'INVALID_PORT' });}const result = {@@ -150,14 +151,14 @@ router.post('/port', async (req, res) => {}res.json(result);-});+}));// POST /api/detect/pm2 - Check if a PM2 process exists with given name-router.post('/pm2', async (req, res) => {+router.post('/pm2', asyncHandler(async (req, res) => {const { name } = req.body;if (!name) {- return res.status(400).json({ error: 'Process name is required', code: 'MISSING_NAME' });+ throw new ServerError('Process name is required', { status: 400, code: 'MISSING_NAME' });}const { stdout } = await execAsync('pm2 jlist').catch(() => ({ stdout: '[]' }));@@ -174,14 +175,14 @@ router.post('/pm2', async (req, res) => {pm_id: found.pm_id} : null});-});+}));// POST /api/detect/ai - AI-powered app detection-router.post('/ai', async (req, res, next) => {+router.post('/ai', asyncHandler(async (req, res) => {const { path, providerId } = req.body;if (!path) {- return res.status(400).json({ error: 'Path is required', code: 'MISSING_PATH' });+ throw new ServerError('Path is required', { status: 400, code: 'MISSING_PATH' });}const result = await detectAppWithAi(path, providerId).catch(err => ({@@ -190,6 +191,6 @@ router.post('/ai', async (req, res, next) => {}));res.json(result);-});+}));export default router;diff --git a/server/routes/git.js b/server/routes/git.jsindex b203c4a1cb..74e7602ccb 100644--- a/server/routes/git.js+++ b/server/routes/git.js@@ -1,10 +1,11 @@import { Router } from 'express';import * as git from '../services/git.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();// GET /api/git/:appId - Get git info for an app-router.get('/:appId', async (req, res, next) => {+router.get('/:appId', asyncHandler(async (req, res) => {const { appId } = req.params;// Get app to find its path@@ -12,127 +13,95 @@ router.get('/:appId', async (req, res, next) => {const app = apps?.find(a => a.id === appId);if (!app) {- return res.status(404).json({ error: 'App not found' });+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}- const info = await git.getGitInfo(app.repoPath).catch(err => {- res.status(500).json({ error: err.message });- return undefined;- });-- if (info) res.json(info);-});+ const info = await git.getGitInfo(app.repoPath);+ res.json(info);+}));// POST /api/git/status - Get status for a path-router.post('/status', async (req, res, next) => {+router.post('/status', asyncHandler(async (req, res) => {const { path } = req.body;if (!path) {- return res.status(400).json({ error: 'path is required' });+ throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });}- const status = await git.getStatus(path).catch(err => {- res.status(500).json({ error: err.message });- return undefined;- });-- if (status) res.json(status);-});+ const status = await git.getStatus(path);+ res.json(status);+}));// POST /api/git/diff - Get diff for a path-router.post('/diff', async (req, res, next) => {+router.post('/diff', asyncHandler(async (req, res) => {const { path, staged } = req.body;if (!path) {- return res.status(400).json({ error: 'path is required' });+ throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });}- const diff = await git.getDiff(path, staged).catch(err => {- res.status(500).json({ error: err.message });- return undefined;- });-- if (diff !== undefined) res.json({ diff });-});+ const diff = await git.getDiff(path, staged);+ res.json({ diff });+}));// POST /api/git/commits - Get recent commits-router.post('/commits', async (req, res, next) => {+router.post('/commits', asyncHandler(async (req, res) => {const { path, limit = 10 } = req.body;if (!path) {- return res.status(400).json({ error: 'path is required' });+ throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });}- const commits = await git.getCommits(path, limit).catch(err => {- res.status(500).json({ error: err.message });- return undefined;- });-- if (commits) res.json({ commits });-});+ const commits = await git.getCommits(path, limit);+ res.json({ commits });+}));// POST /api/git/stage - Stage files-router.post('/stage', async (req, res, next) => {+router.post('/stage', asyncHandler(async (req, res) => {const { path, files } = req.body;if (!path || !files) {- return res.status(400).json({ error: 'path and files are required' });+ throw new ServerError('path and files are required', { status: 400, code: 'VALIDATION_ERROR' });}- const result = await git.stageFiles(path, files).catch(err => {- res.status(500).json({ error: err.message });- return undefined;- });-- if (result) res.json({ success: true });-});+ await git.stageFiles(path, files);+ res.json({ success: true });+}));// POST /api/git/unstage - Unstage files-router.post('/unstage', async (req, res, next) => {+router.post('/unstage', asyncHandler(async (req, res) => {const { path, files } = req.body;if (!path || !files) {- return res.status(400).json({ error: 'path and files are required' });+ throw new ServerError('path and files are required', { status: 400, code: 'VALIDATION_ERROR' });}- const result = await git.unstageFiles(path, files).catch(err => {- res.status(500).json({ error: err.message });- return undefined;- });-- if (result) res.json({ success: true });-});+ await git.unstageFiles(path, files);+ res.json({ success: true });+}));// POST /api/git/commit - Create a commit-router.post('/commit', async (req, res, next) => {+router.post('/commit', asyncHandler(async (req, res) => {const { path, message } = req.body;if (!path || !message) {- return res.status(400).json({ error: 'path and message are required' });+ throw new ServerError('path and message are required', { status: 400, code: 'VALIDATION_ERROR' });}- const result = await git.commit(path, message).catch(err => {- res.status(500).json({ error: err.message });- return undefined;- });-- if (result) res.json(result);-});+ const result = await git.commit(path, message);+ res.json(result);+}));// POST /api/git/info - Get full git info for a path-router.post('/info', async (req, res, next) => {+router.post('/info', asyncHandler(async (req, res) => {const { path } = req.body;if (!path) {- return res.status(400).json({ error: 'path is required' });+ throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });}- const info = await git.getGitInfo(path).catch(err => {- res.status(500).json({ error: err.message });- return undefined;- });-- if (info) res.json(info);-});+ const info = await git.getGitInfo(path);+ res.json(info);+}));export default router;diff --git a/server/routes/history.js b/server/routes/history.jsindex f9ea3af2f7..fa1b361f28 100644--- a/server/routes/history.js+++ b/server/routes/history.js@@ -1,4 +1,5 @@import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import * as history from '../services/history.js';const router = Router();diff --git a/server/routes/logs.js b/server/routes/logs.jsindex 61b394b3c1..ae8f61861c 100644--- a/server/routes/logs.js+++ b/server/routes/logs.js@@ -2,17 +2,18 @@ import { Router } from 'express';import { spawn } from 'child_process';import * as appsService from '../services/apps.js';import * as pm2Service from '../services/pm2.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();// GET /api/logs/processes - List all PM2 processes for log selection-router.get('/processes', async (req, res) => {+router.get('/processes', asyncHandler(async (req, res) => {const processes = await pm2Service.listProcesses().catch(() => []);res.json(processes);-});+}));// GET /api/logs/:processName - Get logs for a process (static or streaming)-router.get('/:processName', async (req, res) => {+router.get('/:processName', asyncHandler(async (req, res) => {const { processName } = req.params;const lines = parseInt(req.query.lines) || 100;const follow = req.query.follow === 'true';@@ -77,14 +78,14 @@ router.get('/:processName', async (req, res) => {req.on('close', () => {logProcess.kill('SIGTERM');});-});+}));// GET /api/logs/app/:appId - Get logs for all processes of an app-router.get('/app/:appId', async (req, res) => {+router.get('/app/:appId', asyncHandler(async (req, res) => {const app = await appsService.getAppById(req.params.appId);if (!app) {- return res.status(404).json({ error: 'App not found', code: 'NOT_FOUND' });+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}const lines = parseInt(req.query.lines) || 100;@@ -96,6 +97,6 @@ router.get('/app/:appId', async (req, res) => {}res.json({ app: app.name, processes: results });-});+}));export default router;diff --git a/server/routes/memory.js b/server/routes/memory.jsnew file mode 100644index 0000000000..e0a83ccc3f--- /dev/null+++ b/server/routes/memory.js@@ -0,0 +1,211 @@+/**+ * Memory API Routes+ */++import { Router } from 'express';+import * as memory from '../services/memory.js';+import * as embeddings from '../services/memoryEmbeddings.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validate } from '../lib/validation.js';+import {+ memoryCreateSchema,+ memoryUpdateSchema,+ memorySearchSchema,+ memoryListSchema,+ memoryTimelineSchema,+ memoryConsolidateSchema,+ memoryLinkSchema+} from '../lib/memoryValidation.js';++const router = Router();++// GET /api/memory - List memories with filters+router.get('/', asyncHandler(async (req, res) => {+ const options = {+ types: req.query.types ? req.query.types.split(',') : undefined,+ categories: req.query.categories ? req.query.categories.split(',') : undefined,+ tags: req.query.tags ? req.query.tags.split(',') : undefined,+ status: req.query.status || 'active',+ limit: parseInt(req.query.limit) || 50,+ offset: parseInt(req.query.offset) || 0,+ sortBy: req.query.sortBy || 'createdAt',+ sortOrder: req.query.sortOrder || 'desc'+ };++ const result = await memory.getMemories(options);+ res.json(result);+}));++// GET /api/memory/stats - Get memory statistics+router.get('/stats', asyncHandler(async (req, res) => {+ const stats = await memory.getStats();+ res.json(stats);+}));++// GET /api/memory/categories - Get all categories+router.get('/categories', asyncHandler(async (req, res) => {+ const categories = await memory.getCategories();+ res.json(categories);+}));++// GET /api/memory/tags - Get all tags+router.get('/tags', asyncHandler(async (req, res) => {+ const tags = await memory.getTags();+ res.json(tags);+}));++// GET /api/memory/timeline - Get timeline view+router.get('/timeline', asyncHandler(async (req, res) => {+ const options = {+ startDate: req.query.startDate,+ endDate: req.query.endDate,+ types: req.query.types ? req.query.types.split(',') : undefined,+ limit: parseInt(req.query.limit) || 100+ };++ const timeline = await memory.getTimeline(options);+ res.json(timeline);+}));++// GET /api/memory/graph - Get graph visualization data+router.get('/graph', asyncHandler(async (req, res) => {+ const graph = await memory.getGraphData();+ res.json(graph);+}));++// GET /api/memory/embeddings/status - Check embedding service status+router.get('/embeddings/status', asyncHandler(async (req, res) => {+ const status = await embeddings.checkAvailability();+ res.json(status);+}));++// POST /api/memory/search - Semantic search+router.post('/search', asyncHandler(async (req, res) => {+ const validation = validate(memorySearchSchema, req.body);+ if (!validation.success) {+ throw new ServerError('Validation failed', { status: 400, errors: validation.errors });+ }++ const { query, types, categories, tags, minRelevance, limit, offset } = validation.data;++ // Generate query embedding+ const queryEmbedding = await embeddings.generateQueryEmbedding(query, { types, categories });++ if (!queryEmbedding) {+ throw new ServerError('Failed to generate query embedding. Is LM Studio running?', { status: 503 });+ }++ const result = await memory.searchMemories(queryEmbedding, {+ types,+ categories,+ tags,+ minRelevance,+ limit,+ offset+ });++ res.json(result);+}));++// POST /api/memory - Create a new memory+router.post('/', asyncHandler(async (req, res) => {+ const validation = validate(memoryCreateSchema, req.body);+ if (!validation.success) {+ throw new ServerError('Validation failed', { status: 400, errors: validation.errors });+ }++ // Generate embedding for the memory+ const embedding = await embeddings.generateMemoryEmbedding(validation.data);++ const created = await memory.createMemory(validation.data, embedding);+ res.status(201).json(created);+}));++// POST /api/memory/consolidate - Consolidate similar memories+router.post('/consolidate', asyncHandler(async (req, res) => {+ const validation = validate(memoryConsolidateSchema, req.body);+ if (!validation.success) {+ throw new ServerError('Validation failed', { status: 400, errors: validation.errors });+ }++ const { similarityThreshold, dryRun } = validation.data;+ const result = await memory.consolidateMemories(similarityThreshold, dryRun);+ res.json(result);+}));++// POST /api/memory/link - Link two memories+router.post('/link', asyncHandler(async (req, res) => {+ const validation = validate(memoryLinkSchema, req.body);+ if (!validation.success) {+ throw new ServerError('Validation failed', { status: 400, errors: validation.errors });+ }++ const { sourceId, targetId } = validation.data;+ const result = await memory.linkMemories(sourceId, targetId);+ res.json(result);+}));++// POST /api/memory/decay - Apply importance decay+router.post('/decay', asyncHandler(async (req, res) => {+ const decayRate = parseFloat(req.body.decayRate) || 0.01;+ const result = await memory.applyDecay(decayRate);+ res.json(result);+}));++// DELETE /api/memory/expired - Clear expired memories+router.delete('/expired', asyncHandler(async (req, res) => {+ const result = await memory.clearExpired();+ res.json(result);+}));++// GET /api/memory/:id - Get a single memory+router.get('/:id', asyncHandler(async (req, res) => {+ const mem = await memory.getMemory(req.params.id);+ if (!mem) {+ throw new ServerError('Memory not found', { status: 404 });+ }+ res.json(mem);+}));++// GET /api/memory/:id/related - Get related memories+router.get('/:id/related', asyncHandler(async (req, res) => {+ const limit = parseInt(req.query.limit) || 10;+ const related = await memory.getRelatedMemories(req.params.id, limit);+ res.json(related);+}));++// PUT /api/memory/:id - Update a memory+router.put('/:id', asyncHandler(async (req, res) => {+ const validation = validate(memoryUpdateSchema, req.body);+ if (!validation.success) {+ throw new ServerError('Validation failed', { status: 400, errors: validation.errors });+ }++ const updated = await memory.updateMemory(req.params.id, validation.data);+ if (!updated) {+ throw new ServerError('Memory not found', { status: 404 });+ }++ // Regenerate embedding if content changed+ if (validation.data.content) {+ const embedding = await embeddings.generateMemoryEmbedding(updated);+ if (embedding) {+ // Update embedding in storage+ const embeddingsData = await memory.loadEmbeddings?.() || {};+ embeddingsData.vectors = embeddingsData.vectors || {};+ embeddingsData.vectors[updated.id] = embedding;+ // Note: This would need to be exposed from memory.js+ }+ }++ res.json(updated);+}));++// DELETE /api/memory/:id - Delete a memory+router.delete('/:id', asyncHandler(async (req, res) => {+ const hard = req.query.hard === 'true';+ const result = await memory.deleteMemory(req.params.id, hard);+ res.json(result);+}));++export default router;diff --git a/server/routes/ports.js b/server/routes/ports.jsindex 1465fe0955..1cd4366387 100644--- a/server/routes/ports.js+++ b/server/routes/ports.js@@ -1,42 +1,43 @@import { Router } from 'express';import * as portsService from '../services/ports.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();// GET /api/ports/scan - Scan for used ports-router.get('/scan', async (req, res, next) => {+router.get('/scan', asyncHandler(async (req, res) => {const scan = await portsService.scanPorts();res.json(scan);-});+}));// POST /api/ports/check - Check if specific ports are available-router.post('/check', async (req, res, next) => {+router.post('/check', asyncHandler(async (req, res) => {const { ports } = req.body;if (!Array.isArray(ports) || ports.length === 0) {- return res.status(400).json({- error: 'ports must be a non-empty array of numbers',+ throw new ServerError('ports must be a non-empty array of numbers', {+ status: 400,code: 'VALIDATION_ERROR'});}const results = await portsService.checkPortsAvailable(ports);res.json(results);-});+}));// POST /api/ports/allocate - Allocate available ports-router.post('/allocate', async (req, res, next) => {+router.post('/allocate', asyncHandler(async (req, res) => {const count = parseInt(req.body.count) || 1;if (count < 1 || count > 10) {- return res.status(400).json({- error: 'count must be between 1 and 10',+ throw new ServerError('count must be between 1 and 10', {+ status: 400,code: 'VALIDATION_ERROR'});}const ports = await portsService.allocatePorts(count);res.json({ allocated: ports });-});+}));export default router;diff --git a/server/routes/prompts.js b/server/routes/prompts.jsindex 0541a50d78..9c96ebbbde 100644--- a/server/routes/prompts.js+++ b/server/routes/prompts.js@@ -1,64 +1,65 @@import { Router } from 'express';import * as promptService from '../services/promptService.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();// GET /api/prompts - List all stages-router.get('/', async (req, res) => {+router.get('/', asyncHandler(async (req, res) => {const stages = promptService.getStages();res.json({ stages });-});+}));// GET /api/prompts/variables - List all variables-router.get('/variables', async (req, res) => {+router.get('/variables', asyncHandler(async (req, res) => {const variables = promptService.getVariables();res.json({ variables });-});+}));// GET /api/prompts/variables/:key - Get a variable-router.get('/variables/:key', async (req, res) => {+router.get('/variables/:key', asyncHandler(async (req, res) => {const variable = promptService.getVariable(req.params.key);if (!variable) {- return res.status(404).json({ error: 'Variable not found' });+ throw new ServerError('Variable not found', { status: 404, code: 'NOT_FOUND' });}res.json({ key: req.params.key, ...variable });-});+}));// POST /api/prompts/variables - Create a variable-router.post('/variables', async (req, res) => {+router.post('/variables', asyncHandler(async (req, res) => {const { key, name, category, content } = req.body;if (!key || !content) {- return res.status(400).json({ error: 'key and content are required' });+ throw new ServerError('key and content are required', { status: 400, code: 'VALIDATION_ERROR' });}await promptService.createVariable(key, { name, category, content });res.json({ success: true, key });-});+}));// PUT /api/prompts/variables/:key - Update a variable-router.put('/variables/:key', async (req, res) => {+router.put('/variables/:key', asyncHandler(async (req, res) => {const { name, category, content } = req.body;await promptService.updateVariable(req.params.key, { name, category, content });res.json({ success: true });-});+}));// DELETE /api/prompts/variables/:key - Delete a variable-router.delete('/variables/:key', async (req, res) => {+router.delete('/variables/:key', asyncHandler(async (req, res) => {await promptService.deleteVariable(req.params.key);res.json({ success: true });-});+}));// GET /api/prompts/:stage - Get stage with template-router.get('/:stage', async (req, res) => {+router.get('/:stage', asyncHandler(async (req, res) => {const stage = promptService.getStage(req.params.stage);if (!stage) {- return res.status(404).json({ error: 'Stage not found' });+ throw new ServerError('Stage not found', { status: 404, code: 'NOT_FOUND' });}const template = await promptService.getStageTemplate(req.params.stage);res.json({ ...stage, template });-});+}));// PUT /api/prompts/:stage - Update stage config and/or template-router.put('/:stage', async (req, res) => {+router.put('/:stage', asyncHandler(async (req, res) => {const { template, ...config } = req.body;if (Object.keys(config).length > 0) {@@ -68,19 +69,19 @@ router.put('/:stage', async (req, res) => {await promptService.updateStageTemplate(req.params.stage, template);}res.json({ success: true });-});+}));// POST /api/prompts/:stage/preview - Preview compiled prompt-router.post('/:stage/preview', async (req, res) => {+router.post('/:stage/preview', asyncHandler(async (req, res) => {const { testData = {} } = req.body;const preview = await promptService.previewPrompt(req.params.stage, testData);res.json({ preview });-});+}));// POST /api/prompts/reload - Reload prompts from disk-router.post('/reload', async (req, res) => {+router.post('/reload', asyncHandler(async (req, res) => {await promptService.loadPrompts();res.json({ success: true });-});+}));export default router;diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 3846dc016b..68e475547f 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -1,116 +1,101 @@import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import * as providers from '../services/providers.js';const router = Router();// GET /api/providers - List all providers-router.get('/', async (req, res, next) => {- const data = await providers.getAllProviders().catch(next);- if (data) res.json(data);-});+router.get('/', asyncHandler(async (req, res) => {+ const data = await providers.getAllProviders();+ res.json(data);+}));// GET /api/providers/active - Get active provider-router.get('/active', async (req, res, next) => {- const provider = await providers.getActiveProvider().catch(next);- if (provider === undefined) return;+router.get('/active', asyncHandler(async (req, res) => {+ const provider = await providers.getActiveProvider();res.json(provider);-});+}));// PUT /api/providers/active - Set active provider-router.put('/active', async (req, res, next) => {+router.put('/active', asyncHandler(async (req, res) => {const { id } = req.body;if (!id) {- return res.status(400).json({ error: 'Provider ID required', code: 'MISSING_ID' });+ throw new ServerError('Provider ID required', { status: 400, code: 'MISSING_ID' });}- const provider = await providers.setActiveProvider(id).catch(next);- if (provider === undefined) return;+ const provider = await providers.setActiveProvider(id);if (!provider) {- return res.status(404).json({ error: 'Provider not found', code: 'NOT_FOUND' });+ throw new ServerError('Provider not found', { status: 404, code: 'NOT_FOUND' });}res.json(provider);-});+}));// GET /api/providers/:id - Get provider by ID-router.get('/:id', async (req, res, next) => {- const provider = await providers.getProviderById(req.params.id).catch(next);- if (provider === undefined) return;+router.get('/:id', asyncHandler(async (req, res) => {+ const provider = await providers.getProviderById(req.params.id);if (!provider) {- return res.status(404).json({ error: 'Provider not found', code: 'NOT_FOUND' });+ throw new ServerError('Provider not found', { status: 404, code: 'NOT_FOUND' });}res.json(provider);-});+}));// POST /api/providers - Create new provider-router.post('/', async (req, res, next) => {+router.post('/', asyncHandler(async (req, res) => {const { name, type } = req.body;if (!name) {- return res.status(400).json({ error: 'Name is required', code: 'VALIDATION_ERROR' });+ throw new ServerError('Name is required', { status: 400, code: 'VALIDATION_ERROR' });}if (!type || !['cli', 'api'].includes(type)) {- return res.status(400).json({ error: 'Type must be "cli" or "api"', code: 'VALIDATION_ERROR' });+ throw new ServerError('Type must be "cli" or "api"', { status: 400, code: 'VALIDATION_ERROR' });}- const provider = await providers.createProvider(req.body).catch(err => {- if (err.message.includes('already exists')) {- res.status(409).json({ error: err.message, code: 'CONFLICT' });- return undefined;- }- next(err);- return undefined;- });-- if (provider === undefined) return;+ const provider = await providers.createProvider(req.body);res.status(201).json(provider);-});+}));// PUT /api/providers/:id - Update provider-router.put('/:id', async (req, res, next) => {- const provider = await providers.updateProvider(req.params.id, req.body).catch(next);- if (provider === undefined) return;+router.put('/:id', asyncHandler(async (req, res) => {+ const provider = await providers.updateProvider(req.params.id, req.body);if (!provider) {- return res.status(404).json({ error: 'Provider not found', code: 'NOT_FOUND' });+ throw new ServerError('Provider not found', { status: 404, code: 'NOT_FOUND' });}res.json(provider);-});+}));// DELETE /api/providers/:id - Delete provider-router.delete('/:id', async (req, res, next) => {- const deleted = await providers.deleteProvider(req.params.id).catch(next);- if (deleted === undefined) return;+router.delete('/:id', asyncHandler(async (req, res) => {+ const deleted = await providers.deleteProvider(req.params.id);if (!deleted) {- return res.status(404).json({ error: 'Provider not found', code: 'NOT_FOUND' });+ throw new ServerError('Provider not found', { status: 404, code: 'NOT_FOUND' });}res.status(204).send();-});+}));// POST /api/providers/:id/test - Test provider connectivity-router.post('/:id/test', async (req, res, next) => {- const result = await providers.testProvider(req.params.id).catch(next);- if (result === undefined) return;+router.post('/:id/test', asyncHandler(async (req, res) => {+ const result = await providers.testProvider(req.params.id);res.json(result);-});+}));// POST /api/providers/:id/refresh-models - Refresh models for API provider-router.post('/:id/refresh-models', async (req, res, next) => {- const provider = await providers.refreshProviderModels(req.params.id).catch(next);- if (provider === undefined) return;+router.post('/:id/refresh-models', asyncHandler(async (req, res) => {+ const provider = await providers.refreshProviderModels(req.params.id);if (!provider) {- return res.status(404).json({ error: 'Provider not found or not an API type', code: 'NOT_FOUND' });+ throw new ServerError('Provider not found or not an API type', { status: 404, code: 'NOT_FOUND' });}res.json(provider);-});+}));export default router;diff --git a/server/routes/runs.js b/server/routes/runs.jsindex 3d608a6b10..5f8f126802 100644--- a/server/routes/runs.js+++ b/server/routes/runs.js@@ -1,27 +1,37 @@import { Router } from 'express';import * as runner from '../services/runner.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();// GET /api/runs - List runs-router.get('/', async (req, res, next) => {+// Query params: limit, offset, source (all|devtools|cos-agent)+router.get('/', asyncHandler(async (req, res, next) => {const limit = parseInt(req.query.limit) || 50;const offset = parseInt(req.query.offset) || 0;+ const source = req.query.source || 'all'; // all, devtools, cos-agent- const result = await runner.listRuns(limit, offset).catch(next);- if (result) res.json(result);-});+ const result = await runner.listRuns(limit, offset, source);+ res.json(result);+}));// POST /api/runs - Create and execute a new run-router.post('/', async (req, res, next) => {+router.post('/', asyncHandler(async (req, res, next) => {const { providerId, model, prompt, workspacePath, workspaceName } = req.body;+ console.log(`🚀 POST /api/runs - provider: ${providerId}, model: ${model}, workspace: ${workspaceName}`);if (!providerId) {- return res.status(400).json({ error: 'providerId is required', code: 'VALIDATION_ERROR' });+ throw new ServerError('providerId is required', {+ status: 400,+ code: 'VALIDATION_ERROR'+ });}if (!prompt) {- return res.status(400).json({ error: 'prompt is required', code: 'VALIDATION_ERROR' });+ throw new ServerError('prompt is required', {+ status: 400,+ code: 'VALIDATION_ERROR'+ });}const runData = await runner.createRun({@@ -30,18 +40,15 @@ router.post('/', async (req, res, next) => {prompt,workspacePath,workspaceName- }).catch(err => {- res.status(400).json({ error: err.message, code: 'RUN_ERROR' });- return undefined;});- if (!runData) return;-const { runId, provider, metadata } = runData;const io = req.app.get('io');+ console.log(`🚀 Run created: ${runId}, provider type: ${provider.type}, command: ${provider.command}`);// Execute based on provider typeif (provider.type === 'cli') {+ console.log(`🚀 Executing CLI run: ${provider.command} with args: ${JSON.stringify(provider.args)}`);runner.executeCliRun(runId,provider,@@ -49,9 +56,11 @@ router.post('/', async (req, res, next) => {workspacePath,(data) => {// Stream output via Socket.IO+ console.log(`📤 Emitting run:${runId}:data (${data.length} chars)`);io?.emit(`run:${runId}:data`, data);},(finalMetadata) => {+ console.log(`✅ Run complete: ${runId}, success: ${finalMetadata.success}`);io?.emit(`run:${runId}:complete`, finalMetadata);});@@ -77,74 +86,87 @@ router.post('/', async (req, res, next) => {status: 'started',metadata});-});+}));// GET /api/runs/:id - Get run metadata-router.get('/:id', async (req, res, next) => {- const metadata = await runner.getRun(req.params.id).catch(next);- if (metadata === undefined) return;+router.get('/:id', asyncHandler(async (req, res, next) => {+ const metadata = await runner.getRun(req.params.id);if (!metadata) {- return res.status(404).json({ error: 'Run not found', code: 'NOT_FOUND' });+ throw new ServerError('Run not found', {+ status: 404,+ code: 'NOT_FOUND'+ });}res.json({...metadata,isActive: runner.isRunActive(req.params.id)});-});+}));// GET /api/runs/:id/output - Get run output-router.get('/:id/output', async (req, res, next) => {- const output = await runner.getRunOutput(req.params.id).catch(next);- if (output === undefined) return;+router.get('/:id/output', asyncHandler(async (req, res, next) => {+ const output = await runner.getRunOutput(req.params.id);if (output === null) {- return res.status(404).json({ error: 'Run not found', code: 'NOT_FOUND' });+ throw new ServerError('Run not found', {+ status: 404,+ code: 'NOT_FOUND'+ });}res.type('text/plain').send(output);-});+}));// GET /api/runs/:id/prompt - Get run prompt-router.get('/:id/prompt', async (req, res, next) => {- const prompt = await runner.getRunPrompt(req.params.id).catch(next);- if (prompt === undefined) return;+router.get('/:id/prompt', asyncHandler(async (req, res, next) => {+ const prompt = await runner.getRunPrompt(req.params.id);if (prompt === null) {- return res.status(404).json({ error: 'Run not found', code: 'NOT_FOUND' });+ throw new ServerError('Run not found', {+ status: 404,+ code: 'NOT_FOUND'+ });}res.type('text/plain').send(prompt);-});+}));// POST /api/runs/:id/stop - Stop a running execution-router.post('/:id/stop', async (req, res, next) => {- const stopped = await runner.stopRun(req.params.id).catch(next);- if (stopped === undefined) return;+router.post('/:id/stop', asyncHandler(async (req, res, next) => {+ const stopped = await runner.stopRun(req.params.id);if (!stopped) {- return res.status(404).json({ error: 'Run not found or not active', code: 'NOT_ACTIVE' });+ throw new ServerError('Run not found or not active', {+ status: 404,+ code: 'NOT_ACTIVE'+ });}res.json({ stopped: true });-});+}));// DELETE /api/runs/:id - Delete run and artifacts-router.delete('/:id', async (req, res, next) => {+router.delete('/:id', asyncHandler(async (req, res, next) => {// Don't allow deleting active runsif (runner.isRunActive(req.params.id)) {- return res.status(409).json({ error: 'Cannot delete active run', code: 'RUN_ACTIVE' });+ throw new ServerError('Cannot delete active run', {+ status: 409,+ code: 'RUN_ACTIVE'+ });}- const deleted = await runner.deleteRun(req.params.id).catch(next);- if (deleted === undefined) return;+ const deleted = await runner.deleteRun(req.params.id);if (!deleted) {- return res.status(404).json({ error: 'Run not found', code: 'NOT_FOUND' });+ throw new ServerError('Run not found', {+ status: 404,+ code: 'NOT_FOUND'+ });}res.status(204).send();-});+}));export default router;diff --git a/server/routes/scaffold.js b/server/routes/scaffold.jsindex 3eb0e03691..e562f84f34 100644--- a/server/routes/scaffold.js+++ b/server/routes/scaffold.js@@ -6,6 +6,7 @@ import { fileURLToPath } from 'url';import { exec, spawn } from 'child_process';import { promisify } from 'util';import { createApp } from '../services/apps.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';const execAsync = promisify(exec);const __filename = fileURLToPath(import.meta.url);@@ -15,7 +16,7 @@ const TEMPLATES_DIR = join(__dirname, '../../templates');const router = Router();// GET /api/templates - List available templates-router.get('/templates', async (req, res) => {+router.get('/templates', asyncHandler(async (req, res) => {const templates = [{id: 'portos-stack',@@ -57,15 +58,16 @@ router.get('/templates', async (req, res) => {];res.json(templates);-});+}));// POST /api/templates/create - User-friendly template creation-router.post('/templates/create', async (req, res) => {+router.post('/templates/create', asyncHandler(async (req, res) => {const { templateId, name, targetPath } = req.body;if (!templateId || !name || !targetPath) {- return res.status(400).json({- error: 'templateId, name, and targetPath are required'+ throw new ServerError('templateId, name, and targetPath are required', {+ status: 400,+ code: 'VALIDATION_ERROR'});}@@ -78,8 +80,9 @@ router.post('/templates/create', async (req, res) => {// For portos-stack, we need to handle it specially (not implemented yet)if (templateId === 'portos-stack') {- return res.status(501).json({- error: 'PortOS Stack template scaffolding is not yet implemented. Please use vite-express for a similar full-stack setup.'+ throw new ServerError('PortOS Stack template scaffolding is not yet implemented. Please use vite-express for a similar full-stack setup.', {+ status: 501,+ code: 'NOT_IMPLEMENTED'});}@@ -87,7 +90,7 @@ router.post('/templates/create', async (req, res) => {req.body = scaffoldData;// Forward to scaffold endpoint logic (call the same handler)return scaffoldApp(req, res);-});+}));// Shared scaffold logicasync function scaffoldApp(req, res) {@@ -103,8 +106,8 @@ async function scaffoldApp(req, res) {// Validationif (!name || !template || !parentDir) {- return res.status(400).json({- error: 'name, template, and parentDir are required',+ throw new ServerError('name, template, and parentDir are required', {+ status: 400,code: 'VALIDATION_ERROR'});}@@ -115,16 +118,16 @@ async function scaffoldApp(req, res) {// Check parent existsif (!existsSync(parentDir)) {- return res.status(400).json({- error: 'Parent directory does not exist',+ throw new ServerError('Parent directory does not exist', {+ status: 400,code: 'INVALID_PARENT'});}// Check target doesn't existif (existsSync(repoPath)) {- return res.status(400).json({- error: 'Directory already exists',+ throw new ServerError('Directory already exists', {+ status: 400,code: 'DIR_EXISTS'});}@@ -363,6 +366,6 @@ app.listen(PORT, '0.0.0.0', () => {}// POST /api/scaffold - Create a new app from template-router.post('/', scaffoldApp);+router.post('/', asyncHandler(scaffoldApp));export default router;diff --git a/server/routes/screenshots.js b/server/routes/screenshots.jsindex 5c3b72561b..c817c7f1ad 100644--- a/server/routes/screenshots.js+++ b/server/routes/screenshots.js@@ -4,6 +4,7 @@ import { existsSync } from 'fs';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { v4 as uuidv4 } from 'uuid';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -12,11 +13,11 @@ const SCREENSHOTS_DIR = join(__dirname, '../../data/screenshots');const router = Router();// POST /api/screenshots - Upload a screenshot (base64)-router.post('/', async (req, res) => {+router.post('/', asyncHandler(async (req, res) => {const { data, filename, mimeType } = req.body;if (!data) {- return res.status(400).json({ error: 'data is required (base64)' });+ throw new ServerError('data is required (base64)', { status: 400, code: 'VALIDATION_ERROR' });}// Ensure screenshots directory exists@@ -41,21 +42,21 @@ router.post('/', async (req, res) => {path: filepath,size: buffer.length});-});+}));// GET /api/screenshots/:filename - Serve a screenshot-router.get('/:filename', async (req, res) => {+router.get('/:filename', asyncHandler(async (req, res) => {const { filename } = req.params;const filepath = join(SCREENSHOTS_DIR, filename);if (!existsSync(filepath)) {- return res.status(404).json({ error: 'Screenshot not found' });+ throw new ServerError('Screenshot not found', { status: 404, code: 'NOT_FOUND' });}const ext = filename.split('.').pop().toLowerCase();const mimeType = ext === 'png' ? 'image/png' : 'image/jpeg';res.type(mimeType).sendFile(filepath);-});+}));export default router;diff --git a/server/routes/scripts.js b/server/routes/scripts.jsnew file mode 100644index 0000000000..11575e07d0--- /dev/null+++ b/server/routes/scripts.js@@ -0,0 +1,108 @@+/**+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+ * Scripts API Routes+ *+ * Endpoints for managing scheduled scripts+ */++import { Router } from 'express';+import * as scriptRunner from '../services/scriptRunner.js';++const router = Router();++// GET /api/cos/scripts - List all scripts+router.get('/', async (req, res, next) => {+ const scripts = await scriptRunner.listScripts().catch(next);+ if (scripts) res.json({ scripts });+});++// GET /api/cos/scripts/presets - Get available schedule presets+router.get('/presets', (req, res) => {+ res.json({ presets: scriptRunner.getSchedulePresets() });+});++// GET /api/cos/scripts/jobs - Get scheduled job info+router.get('/jobs', (req, res) => {+ res.json({ jobs: scriptRunner.getScheduledJobs() });+});++// POST /api/cos/scripts - Create a new script+router.post('/', async (req, res, next) => {+ const { name, description, command, schedule, cronExpression, enabled, triggerAction, triggerPrompt, triggerPriority } = req.body;++ if (!name) {+ return res.status(400).json({ error: 'name is required', code: 'VALIDATION_ERROR' });+ }++ if (!command) {+ return res.status(400).json({ error: 'command is required', code: 'VALIDATION_ERROR' });+ }++ const script = await scriptRunner.createScript({+ name,+ description,+ command,+ schedule,+ cronExpression,+ enabled,+ triggerAction,+ triggerPrompt,+ triggerPriority+ }).catch(next);++ if (script) res.status(201).json(script);+});++// GET /api/cos/scripts/:id - Get a specific script+router.get('/:id', async (req, res, next) => {+ const script = await scriptRunner.getScript(req.params.id).catch(next);++ if (script === null) {+ return res.status(404).json({ error: 'Script not found', code: 'NOT_FOUND' });+ }++ if (script) res.json(script);+});++// PUT /api/cos/scripts/:id - Update a script+router.put('/:id', async (req, res, next) => {+ const script = await scriptRunner.updateScript(req.params.id, req.body).catch(next);++ if (script === null) {+ return res.status(404).json({ error: 'Script not found', code: 'NOT_FOUND' });+ }++ if (script) res.json(script);+});++// DELETE /api/cos/scripts/:id - Delete a script+router.delete('/:id', async (req, res, next) => {+ const deleted = await scriptRunner.deleteScript(req.params.id).catch(next);++ if (deleted === false) {+ return res.status(404).json({ error: 'Script not found', code: 'NOT_FOUND' });+ }++ if (deleted) res.status(204).send();+});++// POST /api/cos/scripts/:id/run - Execute a script immediately+router.post('/:id/run', async (req, res, next) => {+ const result = await scriptRunner.executeScript(req.params.id).catch(next);++ if (result?.error === 'Script not found') {+ return res.status(404).json({ error: 'Script not found', code: 'NOT_FOUND' });+ }++ if (result) res.json(result);+});++// GET /api/cos/scripts/:id/runs - Get script run history+router.get('/:id/runs', async (req, res, next) => {+ const limit = parseInt(req.query.limit) || 10;+ const runs = await scriptRunner.getScriptRuns(req.params.id, limit).catch(next);++ if (runs) res.json({ runs });+});++export default router;diff --git a/server/routes/standardize.js b/server/routes/standardize.jsnew file mode 100644index 0000000000..66e1b85c5d--- /dev/null+++ b/server/routes/standardize.js@@ -0,0 +1,112 @@+import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import * as pm2Standardizer from '../services/pm2Standardizer.js';+import * as appsService from '../services/apps.js';++const router = Router();++// POST /api/standardize/analyze - Analyze app and generate standardization plan+router.post('/analyze', asyncHandler(async (req, res) => {+ const { repoPath, appId, providerId } = req.body;++ // Get path from appId if provided+ let path = repoPath;+ if (!path && appId) {+ const app = await appsService.getAppById(appId);+ if (!app) {+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });+ }+ path = app.repoPath;+ }++ if (!path) {+ throw new ServerError('Either repoPath or appId is required', { status: 400, code: 'MISSING_PATH' });+ }++ console.log(`🔧 Analyzing PM2 standardization for: ${path}`);++ const result = await pm2Standardizer.analyzeApp(path, providerId);++ if (!result.success) {+ throw new ServerError(result.error, { status: 400, code: 'ANALYSIS_FAILED' });+ }++ console.log(`✅ Analysis complete: ${result.proposedChanges.processes?.length || 0} processes identified`);++ res.json(result);+}));++// POST /api/standardize/apply - Apply standardization changes+router.post('/apply', asyncHandler(async (req, res) => {+ const { repoPath, appId, plan } = req.body;++ // Get path from appId if provided+ let path = repoPath;+ if (!path && appId) {+ const app = await appsService.getAppById(appId);+ if (!app) {+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });+ }+ path = app.repoPath;+ }++ if (!path) {+ throw new ServerError('Either repoPath or appId is required', { status: 400, code: 'MISSING_PATH' });+ }++ if (!plan) {+ throw new ServerError('Standardization plan is required', { status: 400, code: 'MISSING_PLAN' });+ }++ console.log(`🔧 Applying PM2 standardization to: ${path}`);++ const result = await pm2Standardizer.applyStandardization(path, plan);++ if (result.backupBranch) {+ console.log(`📦 Backup branch created: ${result.backupBranch}`);+ }++ console.log(`✅ Standardization applied: ${result.filesModified.length} files modified`);++ // If appId was provided, update the app with new PM2 process names+ if (appId && plan.proposedChanges?.processes) {+ const pm2ProcessNames = plan.proposedChanges.processes.map(p => p.name);+ await appsService.updateApp(appId, { pm2ProcessNames });+ }++ res.json(result);+}));++// GET /api/standardize/template - Get the standard PM2 template+router.get('/template', asyncHandler(async (req, res) => {+ const template = pm2Standardizer.getStandardTemplate();+ res.json({ template });+}));++// POST /api/standardize/backup - Create git backup only+router.post('/backup', asyncHandler(async (req, res) => {+ const { repoPath, appId } = req.body;++ let path = repoPath;+ if (!path && appId) {+ const app = await appsService.getAppById(appId);+ if (!app) {+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });+ }+ path = app.repoPath;+ }++ if (!path) {+ throw new ServerError('Either repoPath or appId is required', { status: 400, code: 'MISSING_PATH' });+ }++ const result = await pm2Standardizer.createGitBackup(path);++ if (!result.success) {+ throw new ServerError(result.reason, { status: 400, code: 'BACKUP_FAILED' });+ }++ res.json(result);+}));++export default router;diff --git a/server/routes/usage.js b/server/routes/usage.jsindex e3f368abb5..6ecd3cd69d 100644--- a/server/routes/usage.js+++ b/server/routes/usage.js@@ -1,45 +1,46 @@import { Router } from 'express';import * as usage from '../services/usage.js';+import { asyncHandler } from '../lib/errorHandler.js';const router = Router();// GET /api/usage - Get usage summary-router.get('/', async (req, res) => {+router.get('/', asyncHandler(async (req, res) => {const summary = usage.getUsageSummary();res.json(summary);-});+}));// GET /api/usage/raw - Get raw usage data-router.get('/raw', async (req, res) => {+router.get('/raw', asyncHandler(async (req, res) => {const data = usage.getUsage();res.json(data);-});+}));// POST /api/usage/session - Record a session-router.post('/session', async (req, res) => {+router.post('/session', asyncHandler(async (req, res) => {const { providerId, providerName, model } = req.body;const sessionNumber = await usage.recordSession(providerId, providerName, model);res.json({ sessionNumber });-});+}));// POST /api/usage/messages - Record messages-router.post('/messages', async (req, res) => {+router.post('/messages', asyncHandler(async (req, res) => {const { providerId, model, messageCount, tokenCount } = req.body;await usage.recordMessages(providerId, model, messageCount, tokenCount);res.json({ success: true });-});+}));// POST /api/usage/tokens - Record token usage-router.post('/tokens', async (req, res) => {+router.post('/tokens', asyncHandler(async (req, res) => {const { inputTokens, outputTokens } = req.body;await usage.recordTokens(inputTokens || 0, outputTokens || 0);res.json({ success: true });-});+}));// DELETE /api/usage - Reset usage data-router.delete('/', async (req, res) => {+router.delete('/', asyncHandler(async (req, res) => {await usage.resetUsage();res.json({ success: true });-});+}));export default router;diff --git a/server/services/agents.js b/server/services/agents.jsindex b546dbe219..6793900404 100644--- a/server/services/agents.js+++ b/server/services/agents.js@@ -13,6 +13,31 @@ const AGENT_PATTERNS = [{ name: 'Copilot', pattern: 'copilot', command: 'copilot' }];+// Track spawned agents with their full commands (by PID)+const spawnedAgentCommands = new Map();++/**+ * Register a spawned agent's full command (call when spawning)+ */+export function registerSpawnedAgent(pid, data) {+ spawnedAgentCommands.set(pid, {+ fullCommand: data.fullCommand,+ agentId: data.agentId,+ taskId: data.taskId,+ model: data.model,+ workspacePath: data.workspacePath,+ prompt: data.prompt,+ registeredAt: Date.now()+ });+}++/**+ * Unregister a spawned agent (call when process exits)+ */+export function unregisterSpawnedAgent(pid) {+ spawnedAgentCommands.delete(pid);+}+/*** Get list of running agent processes*/@@ -22,10 +47,24 @@ export async function getRunningAgents() {for (const agent of AGENT_PATTERNS) {const procs = await findProcesses(agent.pattern);procs.forEach(proc => {+ // Enrich with spawned command data if available+ const spawnedData = spawnedAgentCommands.get(proc.pid);+agents.push({...proc,agentName: agent.name,- agentType: agent.command+ agentType: agent.command,+ // Override command with full command if we have it+ command: spawnedData?.fullCommand || proc.command,+ // Include additional metadata if available+ ...(spawnedData && {+ agentId: spawnedData.agentId,+ taskId: spawnedData.taskId,+ model: spawnedData.model,+ workspacePath: spawnedData.workspacePath,+ prompt: spawnedData.prompt,+ source: 'cos'+ })});});}@@ -56,8 +95,8 @@ async function findProcesses(pattern) {*/async function findUnixProcesses(pattern) {// ps command to get process info- // -e: all processes, -o: output format- const cmd = `ps -eo pid,ppid,%cpu,%mem,etime,command | grep -i "${pattern}" | grep -v grep`;+ // -e: all processes, -o: output format, -ww: unlimited width (no truncation)+ const cmd = `ps -ww -eo pid,ppid,%cpu,%mem,etime,command | grep -i "${pattern}" | grep -v grep`;const result = await execAsync(cmd, { maxBuffer: 10 * 1024 * 1024 }).catch(() => ({ stdout: '' }));@@ -216,7 +255,7 @@ export async function getProcessInfo(pid) {const platform = process.platform;if (platform === 'darwin' || platform === 'linux') {- const cmd = `ps -p ${pid} -o pid,ppid,%cpu,%mem,etime,command`;+ const cmd = `ps -ww -p ${pid} -o pid,ppid,%cpu,%mem,etime,command`;const result = await execAsync(cmd).catch(() => null);if (!result) return null;diff --git a/server/services/autoFixer.js b/server/services/autoFixer.jsnew file mode 100644index 0000000000..9bd0db0c46--- /dev/null+++ b/server/services/autoFixer.js@@ -0,0 +1,148 @@+/**+ * Auto-Fixer Service+ *+ * Handles automatic agent spawning for critical errors+ * Integrates with error handler and CoS task system+ */++import { addTask, isRunning } from './cos.js';+import { errorEvents } from '../lib/errorHandler.js';++// Track recent errors to prevent duplicate auto-fix tasks+const recentErrors = new Map();+const ERROR_DEDUPE_WINDOW = 60000; // 1 minute++/**+ * Initialize auto-fixer event listeners+ */+export function initAutoFixer() {+ errorEvents.on('error', async (error) => {+ if (shouldAutoFix(error)) {+ await createAutoFixTask(error);+ }+ });++ console.log('🔧 Auto-fixer initialized');+}++/**+ * Determine if an error should trigger auto-fix+ */+function shouldAutoFix(error) {+ // Only auto-fix if CoS is running+ if (!isRunning()) {+ return false;+ }++ // Only auto-fix critical errors or those explicitly marked as auto-fixable+ if (error.severity !== 'critical' && !error.canAutoFix) {+ return false;+ }++ // Check for duplicate errors within dedupe window+ const errorKey = `${error.code}-${error.message}`;+ const lastSeen = recentErrors.get(errorKey);+ const now = Date.now();++ if (lastSeen && (now - lastSeen) < ERROR_DEDUPE_WINDOW) {+ console.log(`⏭️ Skipping duplicate error: ${error.code}`);+ return false;+ }++ recentErrors.set(errorKey, now);++ // Clean up old entries+ for (const [key, timestamp] of recentErrors.entries()) {+ if (now - timestamp > ERROR_DEDUPE_WINDOW) {+ recentErrors.delete(key);+ }+ }++ return true;+}++/**+ * Create a CoS task to fix the error+ */+async function createAutoFixTask(error) {+ console.log(`🤖 Creating auto-fix task for error: ${error.code}`);++ // Build context for the agent+ const context = buildErrorContext(error);++ // Create task in CoS system tasks+ const taskData = {+ description: `Fix critical error: ${error.message}`,+ priority: 'HIGH',+ context,+ approvalRequired: false // Auto-approve for auto-fix tasks+ };++ const task = await addTask(taskData, 'internal');+ console.log(`✅ Auto-fix task created: ${task.id}`);++ return task;+}++/**+ * Build detailed context for the auto-fix agent+ */+function buildErrorContext(error) {+ const lines = [+ '# Error Details',+ '',+ `**Error Code:** ${error.code}`,+ `**Severity:** ${error.severity}`,+ `**Timestamp:** ${new Date(error.timestamp).toISOString()}`,+ '',+ '## Error Message',+ error.message,+ ''+ ];++ // Add stack trace if available+ if (error.stack) {+ lines.push('## Stack Trace');+ lines.push('```');+ lines.push(error.stack);+ lines.push('```');+ lines.push('');+ }++ // Add context if available+ if (error.context && Object.keys(error.context).length > 0) {+ lines.push('## Context');+ for (const [key, value] of Object.entries(error.context)) {+ lines.push(`- **${key}:** ${JSON.stringify(value)}`);+ }+ lines.push('');+ }++ lines.push('## Instructions');+ lines.push('1. Analyze the error and identify the root cause');+ lines.push('2. Check server logs and browser console for additional context');+ lines.push('3. Fix the issue in the codebase');+ lines.push('4. Verify the fix works by testing the affected functionality');+ lines.push('5. If you cannot fix the issue, document your findings in a comment');++ return lines.join('\n');+}++/**+ * Handle manual error recovery request from UI+ */+export async function handleErrorRecovery(errorCode, context) {+ console.log(`🔧 Manual error recovery requested: ${errorCode}`);++ const taskData = {+ description: `Investigate and fix error: ${errorCode}`,+ priority: 'MEDIUM',+ context: context || `User requested investigation of error code: ${errorCode}`,+ approvalRequired: true // Manual recovery requires approval+ };++ const task = await addTask(taskData, 'internal');+ console.log(`✅ Recovery task created: ${task.id}`);++ return task;+}diff --git a/server/services/cos.js b/server/services/cos.jsnew file mode 100644index 0000000000..703024fea1--- /dev/null+++ b/server/services/cos.js@@ -0,0 +1,1054 @@+/**+ * Chief of Staff (CoS) Service+ *+ * Manages the autonomous agent manager that watches TASKS.md,+ * spawns sub-agents, and orchestrates task completion.+ */++import { readFile, writeFile, mkdir, readdir, rm } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { EventEmitter } from 'events';+import { exec } from 'child_process';+import { promisify } from 'util';+import { v4 as uuidv4 } from 'uuid';+import { getActiveProvider } from './providers.js';+import { parseTasksMarkdown, groupTasksByStatus, getNextTask, getAutoApprovedTasks, getAwaitingApprovalTasks, updateTaskStatus, generateTasksMarkdown } from '../lib/taskParser.js';++const execAsync = promisify(exec);++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const DATA_DIR = join(__dirname, '../../data');+const COS_DIR = join(DATA_DIR, 'cos');+const STATE_FILE = join(COS_DIR, 'state.json');+const AGENTS_DIR = join(COS_DIR, 'agents');+const REPORTS_DIR = join(COS_DIR, 'reports');+const SCRIPTS_DIR = join(COS_DIR, 'scripts');+const ROOT_DIR = join(__dirname, '../../');++// Event emitter for CoS events+export const cosEvents = new EventEmitter();++/**+ * Emit a log event for UI display+ */+function emitLog(level, message, data = {}) {+ const logEntry = {+ timestamp: new Date().toISOString(),+ level, // 'info', 'warn', 'error', 'success', 'debug'+ message,+ ...data+ };+ console.log(`${level === 'error' ? '❌' : level === 'warn' ? '⚠️' : level === 'success' ? '✅' : 'ℹ️'} ${message}`);+ cosEvents.emit('log', logEntry);+}++// In-memory daemon state+let daemonRunning = false;+let evaluationInterval = null;+let healthCheckInterval = null;++// Mutex lock for state operations to prevent race conditions+let stateLock = Promise.resolve();+async function withStateLock(fn) {+ const release = stateLock;+ let resolve;+ stateLock = new Promise(r => { resolve = r; });+ await release;+ try {+ return await fn();+ } finally {+ resolve();+ }+}++/**+ * Default configuration+ */+const DEFAULT_CONFIG = {+ userTasksFile: 'data/TASKS.md', // User-defined tasks+ cosTasksFile: 'data/COS-TASKS.md', // CoS internal/system tasks+ evaluationIntervalMs: 60000, // 1 minute+ healthCheckIntervalMs: 900000, // 15 minutes+ maxConcurrentAgents: 3,+ maxProcessMemoryMb: 2048, // Alert if any process exceeds this+ maxTotalProcesses: 50, // Alert if total PM2 processes exceed this+ mcpServers: [+ { name: 'filesystem', command: 'npx', args: ['-y', '@anthropic/mcp-server-filesystem'] },+ { name: 'puppeteer', command: 'npx', args: ['-y', '@anthropic/mcp-puppeteer', '--isolated'] }+ ],+ autoStart: false,+ selfImprovementEnabled: true // Allow CoS to suggest improvements to its own prompts+};++/**+ * Default state+ */+const DEFAULT_STATE = {+ running: false,+ config: DEFAULT_CONFIG,+ stats: {+ tasksCompleted: 0,+ totalRuntime: 0,+ agentsSpawned: 0,+ lastEvaluation: null+ },+ agents: {}+};++/**+ * Ensure data directories exist+ */+async function ensureDirectories() {+ const dirs = [DATA_DIR, COS_DIR, AGENTS_DIR, REPORTS_DIR, SCRIPTS_DIR];+ for (const dir of dirs) {+ if (!existsSync(dir)) {+ await mkdir(dir, { recursive: true });+ }+ }+}++/**+ * Load CoS state+ */+async function loadState() {+ await ensureDirectories();++ if (!existsSync(STATE_FILE)) {+ return { ...DEFAULT_STATE };+ }++ const content = await readFile(STATE_FILE, 'utf-8');+ const state = JSON.parse(content);++ // Merge with defaults to ensure all fields exist+ return {+ ...DEFAULT_STATE,+ ...state,+ config: { ...DEFAULT_CONFIG, ...state.config },+ stats: { ...DEFAULT_STATE.stats, ...state.stats }+ };+}++/**+ * Save CoS state+ */+async function saveState(state) {+ await ensureDirectories();+ await writeFile(STATE_FILE, JSON.stringify(state, null, 2));+}++/**+ * Get current CoS status+ */+export async function getStatus() {+ const state = await loadState();+ const provider = await getActiveProvider();++ // Count active agents+ const activeAgents = Object.values(state.agents).filter(a => a.status === 'running').length;++ return {+ running: daemonRunning,+ config: state.config,+ stats: state.stats,+ activeAgents,+ provider: provider ? { id: provider.id, name: provider.name } : null+ };+}++/**+ * Get current configuration+ */+export async function getConfig() {+ const state = await loadState();+ return state.config;+}++/**+ * Update configuration+ */+export async function updateConfig(updates) {+ const config = await withStateLock(async () => {+ const state = await loadState();+ state.config = { ...state.config, ...updates };+ await saveState(state);+ return state.config;+ });+ cosEvents.emit('config:changed', config);+ return config;+}++/**+ * Start the CoS daemon+ */+export async function start() {+ if (daemonRunning) {+ emitLog('warn', 'CoS already running');+ return { success: false, error: 'Already running' };+ }++ emitLog('info', 'Starting Chief of Staff daemon...');++ const state = await loadState();+ state.running = true;+ await saveState(state);++ daemonRunning = true;++ // First clean up orphaned agents (agents marked running but no live process)+ const { cleanupOrphanedAgents } = await import('./subAgentSpawner.js');+ const cleanedAgents = await cleanupOrphanedAgents();+ if (cleanedAgents > 0) {+ emitLog('info', `Cleaned up ${cleanedAgents} orphaned agent(s)`);+ }++ // Then reset any orphaned in_progress tasks (no running agent)+ await resetOrphanedTasks();++ // Start evaluation loop+ evaluationInterval = setInterval(async () => {+ await evaluateTasks();+ }, state.config.evaluationIntervalMs);++ // Start health check loop+ healthCheckInterval = setInterval(async () => {+ await runHealthCheck();+ }, state.config.healthCheckIntervalMs);++ // Run initial evaluation and health check+ emitLog('info', 'Running initial task evaluation...');+ await evaluateTasks();+ await runHealthCheck();++ cosEvents.emit('status', { running: true });+ emitLog('success', 'CoS daemon started successfully');+ return { success: true };+}++/**+ * Stop the CoS daemon+ */+export async function stop() {+ if (!daemonRunning) {+ return { success: false, error: 'Not running' };+ }++ // Clear intervals+ if (evaluationInterval) {+ clearInterval(evaluationInterval);+ evaluationInterval = null;+ }+ if (healthCheckInterval) {+ clearInterval(healthCheckInterval);+ healthCheckInterval = null;+ }++ const state = await loadState();+ state.running = false;+ await saveState(state);++ daemonRunning = false;+ cosEvents.emit('status', { running: false });+ return { success: true };+}++/**+ * Get user tasks from TASKS.md+ */+export async function getUserTasks(tasksFilePath = null) {+ const state = await loadState();+ const filePath = tasksFilePath || join(ROOT_DIR, state.config.userTasksFile);++ if (!existsSync(filePath)) {+ return { tasks: [], grouped: groupTasksByStatus([]), file: filePath, exists: false, type: 'user' };+ }++ const content = await readFile(filePath, 'utf-8');+ const tasks = parseTasksMarkdown(content);+ const grouped = groupTasksByStatus(tasks);++ return { tasks, grouped, file: filePath, exists: true, type: 'user' };+}++/**+ * Get CoS internal tasks from COS-TASKS.md+ */+export async function getCosTasks(tasksFilePath = null) {+ const state = await loadState();+ const filePath = tasksFilePath || join(ROOT_DIR, state.config.cosTasksFile);++ if (!existsSync(filePath)) {+ return { tasks: [], grouped: groupTasksByStatus([]), file: filePath, exists: false, type: 'internal' };+ }++ const content = await readFile(filePath, 'utf-8');+ const tasks = parseTasksMarkdown(content);+ const grouped = groupTasksByStatus(tasks);+ const autoApproved = getAutoApprovedTasks(tasks);+ const awaitingApproval = getAwaitingApprovalTasks(tasks);++ return { tasks, grouped, file: filePath, exists: true, type: 'internal', autoApproved, awaitingApproval };+}++/**+ * Get all tasks (user + internal)+ */+export async function getAllTasks() {+ const [userTasks, cosTasks] = await Promise.all([getUserTasks(), getCosTasks()]);+ return { user: userTasks, cos: cosTasks };+}++/**+ * Alias for backward compatibility+ */+export const getTasks = getUserTasks;++/**+ * Reset orphaned in_progress tasks back to pending+ * (tasks marked in_progress but no running agent)+ */+async function resetOrphanedTasks() {+ const state = await loadState();+ const { user: userTaskData } = await getAllTasks();++ if (!userTaskData.exists) {+ emitLog('debug', 'No user tasks file found');+ return;+ }++ const inProgressTasks = userTaskData.grouped.in_progress || [];+ emitLog('debug', `Checking for orphaned tasks: ${inProgressTasks.length} in_progress`);++ const runningAgentTaskIds = Object.values(state.agents)+ .filter(a => a.status === 'running')+ .map(a => a.taskId);++ emitLog('debug', `Running agents: ${runningAgentTaskIds.length}`, { taskIds: runningAgentTaskIds });++ for (const task of inProgressTasks) {+ if (!runningAgentTaskIds.includes(task.id)) {+ emitLog('info', `Resetting orphaned task ${task.id} to pending`, { taskId: task.id });+ await updateTask(task.id, { status: 'pending' }, 'user');+ }+ }+}++/**+ * Evaluate tasks and decide what to spawn+ */+export async function evaluateTasks() {+ if (!daemonRunning) return;++ // Update evaluation timestamp with lock to prevent race conditions+ const state = await withStateLock(async () => {+ const s = await loadState();+ s.stats.lastEvaluation = new Date().toISOString();+ await saveState(s);+ return s;+ });++ // Get both user and CoS tasks+ const { user: userTaskData, cos: cosTaskData } = await getAllTasks();++ const pendingUserTasks = userTaskData.grouped?.pending?.length || 0;+ const inProgressUserTasks = userTaskData.grouped?.in_progress?.length || 0;+ const pendingCosTasks = cosTaskData.grouped?.pending?.length || 0;++ emitLog('info', `Evaluating tasks: ${pendingUserTasks} pending, ${inProgressUserTasks} in_progress, ${pendingCosTasks} system`, {+ pendingUser: pendingUserTasks,+ inProgressUser: inProgressUserTasks,+ pendingSystem: pendingCosTasks+ });++ // Count running agents+ const runningAgents = Object.values(state.agents).filter(a => a.status === 'running').length;+ const availableSlots = state.config.maxConcurrentAgents - runningAgents;++ if (availableSlots <= 0) {+ emitLog('warn', `Max concurrent agents reached (${runningAgents}/${state.config.maxConcurrentAgents})`);+ cosEvents.emit('evaluation', { message: 'Max concurrent agents reached', running: runningAgents });+ return;+ }++ // Priority 1: Check for auto-approved CoS tasks (system maintenance)+ if (cosTaskData.exists && cosTaskData.autoApproved?.length > 0) {+ const nextAutoTask = cosTaskData.autoApproved[0];+ emitLog('info', `Found auto-approved system task: ${nextAutoTask.id}`, { taskId: nextAutoTask.id });+ cosEvents.emit('evaluation', {+ message: 'Found auto-approved system task',+ task: nextAutoTask,+ type: 'internal'+ });+ cosEvents.emit('task:ready', { ...nextAutoTask, taskType: 'internal' });+ return;+ }++ // Priority 2: Check for user tasks+ if (userTaskData.exists) {+ const nextUserTask = getNextTask(userTaskData.tasks);+ if (nextUserTask) {+ emitLog('success', `Found user task: ${nextUserTask.id} (${nextUserTask.priority})`, {+ taskId: nextUserTask.id,+ priority: nextUserTask.priority,+ description: nextUserTask.description?.substring(0, 80)+ });+ cosEvents.emit('evaluation', {+ message: 'Found user task to process',+ task: nextUserTask,+ pendingCount: userTaskData.grouped.pending.length,+ type: 'user'+ });+ cosEvents.emit('task:ready', { ...nextUserTask, taskType: 'user' });+ return;+ }+ }++ // Emit tasks awaiting approval if any+ if (cosTaskData.exists && cosTaskData.awaitingApproval?.length > 0) {+ emitLog('info', `${cosTaskData.awaitingApproval.length} tasks awaiting approval`);+ cosEvents.emit('evaluation', {+ message: 'Tasks awaiting approval',+ awaitingApproval: cosTaskData.awaitingApproval.length+ });+ }++ emitLog('info', 'No pending tasks to process - idle');+ cosEvents.emit('evaluation', { message: 'No pending tasks to process' });+}++/**+ * Run system health check+ */+export async function runHealthCheck() {+ if (!daemonRunning) return;++ const state = await loadState();+ const issues = [];+ const metrics = {+ timestamp: new Date().toISOString(),+ pm2: null,+ memory: null,+ ports: null+ };++ // Check PM2 processes+ const pm2Result = await execAsync('pm2 jlist 2>/dev/null || echo "[]"').catch(() => ({ stdout: '[]' }));+ const pm2Processes = JSON.parse(pm2Result.stdout || '[]');++ metrics.pm2 = {+ total: pm2Processes.length,+ online: pm2Processes.filter(p => p.pm2_env?.status === 'online').length,+ errored: pm2Processes.filter(p => p.pm2_env?.status === 'errored').length,+ stopped: pm2Processes.filter(p => p.pm2_env?.status === 'stopped').length+ };++ // Check for runaway processes (too many)+ if (pm2Processes.length > state.config.maxTotalProcesses) {+ issues.push({+ type: 'warning',+ category: 'processes',+ message: `High process count: ${pm2Processes.length} PM2 processes (limit: ${state.config.maxTotalProcesses})`+ });+ }++ // Check for errored processes+ const erroredProcesses = pm2Processes.filter(p => p.pm2_env?.status === 'errored');+ if (erroredProcesses.length > 0) {+ issues.push({+ type: 'error',+ category: 'processes',+ message: `${erroredProcesses.length} errored PM2 processes: ${erroredProcesses.map(p => p.name).join(', ')}`+ });+ }++ // Check memory usage per process+ const highMemoryProcesses = pm2Processes.filter(p => {+ const memMb = (p.monit?.memory || 0) / (1024 * 1024);+ return memMb > state.config.maxProcessMemoryMb;+ });++ if (highMemoryProcesses.length > 0) {+ issues.push({+ type: 'warning',+ category: 'memory',+ message: `High memory usage in: ${highMemoryProcesses.map(p => `${p.name} (${Math.round((p.monit?.memory || 0) / (1024 * 1024))}MB)`).join(', ')}`+ });+ }++ // Get system memory+ const memResult = await execAsync('vm_stat 2>/dev/null || free -m 2>/dev/null').catch(() => ({ stdout: '' }));+ metrics.memory = { raw: memResult.stdout.slice(0, 500) }; // Truncate for storage++ // Store health check result with lock to prevent race conditions+ await withStateLock(async () => {+ const freshState = await loadState();+ freshState.stats.lastHealthCheck = metrics.timestamp;+ freshState.stats.healthIssues = issues;+ await saveState(freshState);+ });++ cosEvents.emit('health:check', { metrics, issues });++ // If there are critical issues, emit for potential automated response+ if (issues.filter(i => i.type === 'error').length > 0) {+ cosEvents.emit('health:critical', issues.filter(i => i.type === 'error'));+ }++ return { metrics, issues };+}++/**+ * Get latest health status+ */+export async function getHealthStatus() {+ const state = await loadState();+ return {+ lastCheck: state.stats.lastHealthCheck,+ issues: state.stats.healthIssues || []+ };+}++/**+ * Save a generated script+ */+export async function saveScript(name, content, metadata = {}) {+ await ensureDirectories();+ const scriptPath = join(SCRIPTS_DIR, `${name}.sh`);+ await writeFile(scriptPath, content, { mode: 0o755 });++ // Save metadata+ const metaPath = join(SCRIPTS_DIR, `${name}.json`);+ await writeFile(metaPath, JSON.stringify({+ name,+ createdAt: new Date().toISOString(),+ ...metadata+ }, null, 2));++ return { path: scriptPath, name };+}++/**+ * List generated scripts+ */+export async function listScripts() {+ await ensureDirectories();+ const files = await readdir(SCRIPTS_DIR);+ return files.filter(f => f.endsWith('.sh')).map(f => f.replace('.sh', ''));+}++/**+ * Get script content+ */+export async function getScript(name) {+ const scriptPath = join(SCRIPTS_DIR, `${name}.sh`);+ const metaPath = join(SCRIPTS_DIR, `${name}.json`);++ if (!existsSync(scriptPath)) return null;++ const content = await readFile(scriptPath, 'utf-8');+ const metadata = existsSync(metaPath)+ ? JSON.parse(await readFile(metaPath, 'utf-8'))+ : {};++ return { name, content, metadata };+}++/**+ * Register a spawned agent+ */+export async function registerAgent(agentId, taskId, metadata = {}) {+ return withStateLock(async () => {+ const state = await loadState();++ state.agents[agentId] = {+ id: agentId,+ taskId,+ status: 'running',+ startedAt: new Date().toISOString(),+ metadata,+ output: []+ };++ state.stats.agentsSpawned++;+ await saveState(state);++ cosEvents.emit('agent:spawned', state.agents[agentId]);+ return state.agents[agentId];+ });+}++/**+ * Update agent status+ */+export async function updateAgent(agentId, updates) {+ return withStateLock(async () => {+ const state = await loadState();++ if (!state.agents[agentId]) {+ return null;+ }++ state.agents[agentId] = { ...state.agents[agentId], ...updates };+ await saveState(state);++ cosEvents.emit('agent:updated', state.agents[agentId]);+ return state.agents[agentId];+ });+}++/**+ * Mark agent as completed+ */+export async function completeAgent(agentId, result = {}) {+ return withStateLock(async () => {+ const state = await loadState();++ if (!state.agents[agentId]) {+ return null;+ }++ state.agents[agentId] = {+ ...state.agents[agentId],+ status: 'completed',+ completedAt: new Date().toISOString(),+ result+ };++ if (result.success) {+ state.stats.tasksCompleted++;+ }++ await saveState(state);+ cosEvents.emit('agent:completed', state.agents[agentId]);++ // Save agent data to file for history+ const agentDir = join(AGENTS_DIR, agentId);+ if (!existsSync(agentDir)) {+ await mkdir(agentDir, { recursive: true });+ }+ await writeFile(+ join(agentDir, 'metadata.json'),+ JSON.stringify(state.agents[agentId], null, 2)+ );++ return state.agents[agentId];+ });+}++/**+ * Append output to agent+ */+export async function appendAgentOutput(agentId, line) {+ const result = await withStateLock(async () => {+ const state = await loadState();++ if (!state.agents[agentId]) {+ return null;+ }++ state.agents[agentId].output.push({+ timestamp: new Date().toISOString(),+ line+ });++ // Trim to last 1000 lines in state+ if (state.agents[agentId].output.length > 1000) {+ state.agents[agentId].output = state.agents[agentId].output.slice(-1000);+ }++ await saveState(state);+ return state.agents[agentId];+ });++ if (result) {+ cosEvents.emit('agent:output', { agentId, line });+ }++ return result;+}++/**+ * Get all agents+ */+export async function getAgents() {+ const state = await loadState();+ return Object.values(state.agents);+}++/**+ * Get agent by ID+ */+export async function getAgent(agentId) {+ const state = await loadState();+ return state.agents[agentId] || null;+}++/**+ * Terminate an agent (will be handled by spawner)+ */+export async function terminateAgent(agentId) {+ cosEvents.emit('agent:terminate', agentId);+ return { success: true, agentId };+}++/**+ * Delete a single agent from state+ */+export async function deleteAgent(agentId) {+ return withStateLock(async () => {+ const state = await loadState();++ if (!state.agents[agentId]) {+ return { error: 'Agent not found' };+ }++ delete state.agents[agentId];+ await saveState(state);++ cosEvents.emit('agents:changed', { action: 'deleted', agentId });+ return { success: true, agentId };+ });+}++/**+ * Generate daily report+ */+export async function generateReport(date = null) {+ const reportDate = date || new Date().toISOString().split('T')[0];+ const state = await loadState();++ // Filter agents completed on this date+ const completedAgents = Object.values(state.agents).filter(a => {+ if (!a.completedAt) return false;+ return a.completedAt.startsWith(reportDate);+ });++ const report = {+ date: reportDate,+ generated: new Date().toISOString(),+ summary: {+ tasksCompleted: completedAgents.filter(a => a.result?.success).length,+ tasksFailed: completedAgents.filter(a => !a.result?.success).length,+ totalAgents: completedAgents.length+ },+ agents: completedAgents.map(a => ({+ id: a.id,+ taskId: a.taskId,+ success: a.result?.success || false,+ duration: a.completedAt && a.startedAt+ ? new Date(a.completedAt) - new Date(a.startedAt)+ : 0+ }))+ };++ // Save report+ const reportFile = join(REPORTS_DIR, `${reportDate}.json`);+ await writeFile(reportFile, JSON.stringify(report, null, 2));++ return report;+}++/**+ * Get report for a date+ */+export async function getReport(date) {+ const reportFile = join(REPORTS_DIR, `${date}.json`);++ if (!existsSync(reportFile)) {+ return null;+ }++ const content = await readFile(reportFile, 'utf-8');+ return JSON.parse(content);+}++/**+ * Get today's report+ */+export async function getTodayReport() {+ const today = new Date().toISOString().split('T')[0];+ return getReport(today) || generateReport(today);+}++/**+ * List all reports+ */+export async function listReports() {+ await ensureDirectories();++ const files = await readdir(REPORTS_DIR);+ return files+ .filter(f => f.endsWith('.json'))+ .map(f => f.replace('.json', ''))+ .sort()+ .reverse();+}++/**+ * Clear completed agents from state (keep in files)+ */+export async function clearCompletedAgents() {+ return withStateLock(async () => {+ const state = await loadState();++ const toRemove = Object.keys(state.agents).filter(+ id => state.agents[id].status === 'completed'+ );++ for (const id of toRemove) {+ delete state.agents[id];+ }++ await saveState(state);+ return { cleared: toRemove.length };+ });+}++/**+ * Check if daemon is running+ */+export function isRunning() {+ return daemonRunning;+}++/**+ * Add a new task to TASKS.md or COS-TASKS.md+ */+export async function addTask(taskData, taskType = 'user') {+ const state = await loadState();+ const filePath = taskType === 'user'+ ? join(ROOT_DIR, state.config.userTasksFile)+ : join(ROOT_DIR, state.config.cosTasksFile);++ // Read existing tasks or start fresh+ let tasks = [];+ if (existsSync(filePath)) {+ const content = await readFile(filePath, 'utf-8');+ tasks = parseTasksMarkdown(content);+ }++ // Generate a unique ID if not provided+ const id = taskData.id || `${taskType === 'user' ? 'task' : 'sys'}-${Date.now().toString(36)}`;++ // Build metadata object+ const metadata = {};+ if (taskData.context) metadata.context = taskData.context;+ if (taskData.model) metadata.model = taskData.model;+ if (taskData.provider) metadata.provider = taskData.provider;+ if (taskData.app) metadata.app = taskData.app;++ // Create the new task+ const newTask = {+ id: id.startsWith('task-') || id.startsWith('sys-') ? id : `${taskType === 'user' ? 'task' : 'sys'}-${id}`,+ status: 'pending',+ priority: (taskData.priority || 'MEDIUM').toUpperCase(),+ priorityValue: PRIORITY_VALUES[taskData.priority?.toUpperCase()] || 2,+ description: taskData.description,+ metadata,+ approvalRequired: taskType === 'internal' && taskData.approvalRequired,+ autoApproved: taskType === 'internal' && !taskData.approvalRequired,+ section: 'pending'+ };++ tasks.push(newTask);++ // Write back to file+ const includeApprovalFlags = taskType === 'internal';+ const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);+ await writeFile(filePath, markdown);++ cosEvents.emit('tasks:changed', { type: taskType, action: 'added', task: newTask });+ return newTask;+}++const PRIORITY_VALUES = {+ 'CRITICAL': 4,+ 'HIGH': 3,+ 'MEDIUM': 2,+ 'LOW': 1+};++/**+ * Update an existing task+ */+export async function updateTask(taskId, updates, taskType = 'user') {+ const state = await loadState();+ const filePath = taskType === 'user'+ ? join(ROOT_DIR, state.config.userTasksFile)+ : join(ROOT_DIR, state.config.cosTasksFile);++ if (!existsSync(filePath)) {+ return { error: 'Task file not found' };+ }++ const content = await readFile(filePath, 'utf-8');+ let tasks = parseTasksMarkdown(content);++ const taskIndex = tasks.findIndex(t => t.id === taskId);+ if (taskIndex === -1) {+ return { error: 'Task not found' };+ }++ // Build updated metadata+ const updatedMetadata = { ...tasks[taskIndex].metadata };+ if (updates.context !== undefined) updatedMetadata.context = updates.context || undefined;+ if (updates.model !== undefined) updatedMetadata.model = updates.model || undefined;+ if (updates.provider !== undefined) updatedMetadata.provider = updates.provider || undefined;++ // Clean undefined values from metadata+ Object.keys(updatedMetadata).forEach(key => {+ if (updatedMetadata[key] === undefined) delete updatedMetadata[key];+ });++ // Update the task+ const updatedTask = {+ ...tasks[taskIndex],+ ...(updates.description && { description: updates.description }),+ ...(updates.priority && {+ priority: updates.priority.toUpperCase(),+ priorityValue: PRIORITY_VALUES[updates.priority.toUpperCase()] || 2+ }),+ ...(updates.status && { status: updates.status }),+ metadata: updatedMetadata+ };++ tasks[taskIndex] = updatedTask;++ // Write back to file+ const includeApprovalFlags = taskType === 'internal';+ const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);+ await writeFile(filePath, markdown);++ cosEvents.emit('tasks:changed', { type: taskType, action: 'updated', task: updatedTask });+ return updatedTask;+}++/**+ * Delete a task+ */+export async function deleteTask(taskId, taskType = 'user') {+ const state = await loadState();+ const filePath = taskType === 'user'+ ? join(ROOT_DIR, state.config.userTasksFile)+ : join(ROOT_DIR, state.config.cosTasksFile);++ if (!existsSync(filePath)) {+ return { error: 'Task file not found' };+ }++ const content = await readFile(filePath, 'utf-8');+ let tasks = parseTasksMarkdown(content);++ const taskToDelete = tasks.find(t => t.id === taskId);+ if (!taskToDelete) {+ return { error: 'Task not found' };+ }++ tasks = tasks.filter(t => t.id !== taskId);++ // Write back to file+ const includeApprovalFlags = taskType === 'internal';+ const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);+ await writeFile(filePath, markdown);++ cosEvents.emit('tasks:changed', { type: taskType, action: 'deleted', taskId });+ return { success: true, taskId };+}++/**+ * Reorder user tasks based on an array of task IDs+ */+export async function reorderTasks(taskIds) {+ const state = await loadState();+ const filePath = join(ROOT_DIR, state.config.userTasksFile);++ if (!existsSync(filePath)) {+ return { error: 'Task file not found' };+ }++ const content = await readFile(filePath, 'utf-8');+ const tasks = parseTasksMarkdown(content);++ // Create a map of tasks by ID for quick lookup+ const taskMap = new Map(tasks.map(t => [t.id, t]));++ // Reorder based on the provided order+ const reorderedTasks = [];+ for (const id of taskIds) {+ const task = taskMap.get(id);+ if (task) {+ reorderedTasks.push(task);+ taskMap.delete(id);+ }+ }++ // Append any tasks not in the provided order (shouldn't happen, but safe)+ for (const task of taskMap.values()) {+ reorderedTasks.push(task);+ }++ // Write back to file+ const markdown = generateTasksMarkdown(reorderedTasks, false);+ await writeFile(filePath, markdown);++ cosEvents.emit('tasks:changed', { type: 'user', action: 'reordered' });+ return { success: true, order: reorderedTasks.map(t => t.id) };+}++/**+ * Approve a task that requires approval (marks it as auto-approved)+ */+export async function approveTask(taskId) {+ const state = await loadState();+ const filePath = join(ROOT_DIR, state.config.cosTasksFile);++ if (!existsSync(filePath)) {+ return { error: 'CoS task file not found' };+ }++ const content = await readFile(filePath, 'utf-8');+ let tasks = parseTasksMarkdown(content);++ const taskIndex = tasks.findIndex(t => t.id === taskId);+ if (taskIndex === -1) {+ return { error: 'Task not found' };+ }++ if (!tasks[taskIndex].approvalRequired) {+ return { error: 'Task does not require approval' };+ }++ // Update approval flags+ tasks[taskIndex] = {+ ...tasks[taskIndex],+ approvalRequired: false,+ autoApproved: true+ };++ // Write back to file+ const markdown = generateTasksMarkdown(tasks, true);+ await writeFile(filePath, markdown);++ cosEvents.emit('tasks:changed', { type: 'internal', action: 'approved', task: tasks[taskIndex] });+ return tasks[taskIndex];+}++/**+ * Initialize on module load+ */+async function init() {+ await ensureDirectories();++ const state = await loadState();++ // Auto-start if configured+ if (state.config.autoStart) {+ await start();+ }+}++// Initialize asynchronously+init();diff --git a/server/services/memory.js b/server/services/memory.jsnew file mode 100644index 0000000000..84d1eb77fb--- /dev/null+++ b/server/services/memory.js@@ -0,0 +1,753 @@+/**+ * Memory Service+ *+ * Core CRUD and search operations for the CoS memory system.+ * Stores facts, learnings, observations, decisions, preferences, and context.+ */++import { readFile, writeFile, mkdir, readdir, rm } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { v4 as uuidv4 } from 'uuid';+import { cosEvents } from './cos.js';+import { findTopK, findAboveThreshold, clusterBySimilarity, cosineSimilarity } from '../lib/vectorMath.js';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const DATA_DIR = join(__dirname, '../../data');+const MEMORY_DIR = join(DATA_DIR, 'cos/memory');+const INDEX_FILE = join(MEMORY_DIR, 'index.json');+const EMBEDDINGS_FILE = join(MEMORY_DIR, 'embeddings.json');+const MEMORIES_DIR = join(MEMORY_DIR, 'memories');++// Default memory configuration+export const DEFAULT_MEMORY_CONFIG = {+ enabled: true,+ embeddingProvider: 'lmstudio',+ embeddingEndpoint: 'http://localhost:1234/v1/embeddings',+ embeddingModel: 'nomic-embed-text-v1.5',+ embeddingDimension: 768,+ maxMemories: 10000,+ maxContextTokens: 2000,+ minRelevanceThreshold: 0.7,+ autoExtractEnabled: true,+ consolidationIntervalMs: 86400000,+ decayIntervalMs: 86400000+};++// In-memory caches+let indexCache = null;+let embeddingsCache = null;++// Mutex lock for state operations+let memoryLock = Promise.resolve();+async function withMemoryLock(fn) {+ const release = memoryLock;+ let resolve;+ memoryLock = new Promise(r => { resolve = r; });+ await release;+ const result = await fn();+ resolve();+ return result;+}++/**+ * Ensure memory directories exist+ */+async function ensureDirectories() {+ const dirs = [MEMORY_DIR, MEMORIES_DIR];+ for (const dir of dirs) {+ if (!existsSync(dir)) {+ await mkdir(dir, { recursive: true });+ }+ }+}++/**+ * Load memory index+ */+async function loadIndex() {+ if (indexCache) return indexCache;++ await ensureDirectories();++ if (!existsSync(INDEX_FILE)) {+ indexCache = { version: 1, lastUpdated: new Date().toISOString(), count: 0, memories: [] };+ return indexCache;+ }++ const content = await readFile(INDEX_FILE, 'utf-8');+ indexCache = JSON.parse(content);+ return indexCache;+}++/**+ * Save memory index+ */+async function saveIndex(index) {+ await ensureDirectories();+ index.lastUpdated = new Date().toISOString();+ indexCache = index;+ await writeFile(INDEX_FILE, JSON.stringify(index, null, 2));+}++/**+ * Load embeddings+ */+async function loadEmbeddings() {+ if (embeddingsCache) return embeddingsCache;++ await ensureDirectories();++ if (!existsSync(EMBEDDINGS_FILE)) {+ embeddingsCache = { model: null, dimension: 0, vectors: {} };+ return embeddingsCache;+ }++ const content = await readFile(EMBEDDINGS_FILE, 'utf-8');+ embeddingsCache = JSON.parse(content);+ return embeddingsCache;+}++/**+ * Save embeddings+ */+async function saveEmbeddings(embeddings) {+ await ensureDirectories();+ embeddingsCache = embeddings;+ await writeFile(EMBEDDINGS_FILE, JSON.stringify(embeddings));+}++/**+ * Load full memory by ID+ */+async function loadMemory(id) {+ const memoryFile = join(MEMORIES_DIR, id, 'memory.json');+ if (!existsSync(memoryFile)) return null;++ const content = await readFile(memoryFile, 'utf-8');+ return JSON.parse(content);+}++/**+ * Save full memory+ */+async function saveMemory(memory) {+ const memoryDir = join(MEMORIES_DIR, memory.id);+ if (!existsSync(memoryDir)) {+ await mkdir(memoryDir, { recursive: true });+ }+ await writeFile(join(memoryDir, 'memory.json'), JSON.stringify(memory, null, 2));+}++/**+ * Delete memory files+ */+async function deleteMemoryFiles(id) {+ const memoryDir = join(MEMORIES_DIR, id);+ if (existsSync(memoryDir)) {+ await rm(memoryDir, { recursive: true });+ }+}++/**+ * Generate summary from content (simple truncation for now)+ * TODO: Use LLM for better summaries+ */+function generateSummary(content, maxLength = 150) {+ if (content.length <= maxLength) return content;+ return content.substring(0, maxLength - 3) + '...';+}++/**+ * Create a new memory+ */+export async function createMemory(data, embedding = null) {+ return withMemoryLock(async () => {+ const index = await loadIndex();+ const embeddings = await loadEmbeddings();++ const now = new Date().toISOString();+ const id = uuidv4();++ const memory = {+ id,+ type: data.type,+ content: data.content,+ summary: data.summary || generateSummary(data.content),+ category: data.category || 'other',+ tags: data.tags || [],+ relatedMemories: data.relatedMemories || [],+ sourceTaskId: data.sourceTaskId || null,+ sourceAgentId: data.sourceAgentId || null,+ embedding: embedding || null,+ embeddingModel: embedding ? DEFAULT_MEMORY_CONFIG.embeddingModel : null,+ confidence: data.confidence ?? 0.8,+ importance: data.importance ?? 0.5,+ accessCount: 0,+ lastAccessed: null,+ createdAt: now,+ updatedAt: now,+ expiresAt: data.expiresAt || null,+ status: 'active'+ };++ // Save full memory+ await saveMemory(memory);++ // Add to index (lightweight metadata only)+ index.memories.push({+ id: memory.id,+ type: memory.type,+ category: memory.category,+ tags: memory.tags,+ summary: memory.summary,+ importance: memory.importance,+ createdAt: memory.createdAt,+ status: memory.status+ });+ index.count = index.memories.length;+ await saveIndex(index);++ // Store embedding separately+ if (embedding) {+ embeddings.vectors[id] = embedding;+ embeddings.model = DEFAULT_MEMORY_CONFIG.embeddingModel;+ embeddings.dimension = embedding.length;+ await saveEmbeddings(embeddings);+ }++ console.log(`🧠 Memory created: ${memory.type} - ${memory.summary.substring(0, 50)}...`);+ cosEvents.emit('memory:created', { id, type: memory.type, summary: memory.summary });++ return memory;+ });+}++/**+ * Get a memory by ID+ */+export async function getMemory(id) {+ const memory = await loadMemory(id);+ if (!memory) return null;++ // Update access stats+ await withMemoryLock(async () => {+ memory.accessCount += 1;+ memory.lastAccessed = new Date().toISOString();+ await saveMemory(memory);+ });++ return memory;+}++/**+ * Get memories with filters+ */+export async function getMemories(options = {}) {+ const index = await loadIndex();+ let memories = [...index.memories];++ // Filter by status+ const status = options.status || 'active';+ memories = memories.filter(m => m.status === status);++ // Filter by types+ if (options.types && options.types.length > 0) {+ memories = memories.filter(m => options.types.includes(m.type));+ }++ // Filter by categories+ if (options.categories && options.categories.length > 0) {+ memories = memories.filter(m => options.categories.includes(m.category));+ }++ // Filter by tags (any match)+ if (options.tags && options.tags.length > 0) {+ memories = memories.filter(m => m.tags.some(t => options.tags.includes(t)));+ }++ // Sort+ const sortBy = options.sortBy || 'createdAt';+ const sortOrder = options.sortOrder || 'desc';+ memories.sort((a, b) => {+ const aVal = a[sortBy] || 0;+ const bVal = b[sortBy] || 0;+ return sortOrder === 'desc' ? (bVal > aVal ? 1 : -1) : (aVal > bVal ? 1 : -1);+ });++ // Paginate+ const offset = options.offset || 0;+ const limit = options.limit || 50;+ const total = memories.length;+ memories = memories.slice(offset, offset + limit);++ return { total, memories };+}++/**+ * Update a memory+ */+export async function updateMemory(id, updates) {+ return withMemoryLock(async () => {+ const memory = await loadMemory(id);+ if (!memory) return null;++ // Apply updates+ const updatableFields = ['content', 'summary', 'category', 'tags', 'confidence', 'importance', 'relatedMemories', 'status', 'expiresAt'];+ for (const field of updatableFields) {+ if (updates[field] !== undefined) {+ memory[field] = updates[field];+ }+ }++ // Update summary if content changed+ if (updates.content && !updates.summary) {+ memory.summary = generateSummary(updates.content);+ }++ memory.updatedAt = new Date().toISOString();+ await saveMemory(memory);++ // Update index+ const index = await loadIndex();+ const idx = index.memories.findIndex(m => m.id === id);+ if (idx !== -1) {+ index.memories[idx] = {+ id: memory.id,+ type: memory.type,+ category: memory.category,+ tags: memory.tags,+ summary: memory.summary,+ importance: memory.importance,+ createdAt: memory.createdAt,+ status: memory.status+ };+ await saveIndex(index);+ }++ console.log(`🧠 Memory updated: ${id}`);+ cosEvents.emit('memory:updated', { id, updates });++ return memory;+ });+}++/**+ * Delete a memory (soft delete by default)+ */+export async function deleteMemory(id, hard = false) {+ return withMemoryLock(async () => {+ if (hard) {+ // Hard delete - remove files+ await deleteMemoryFiles(id);++ // Remove from index+ const index = await loadIndex();+ index.memories = index.memories.filter(m => m.id !== id);+ index.count = index.memories.length;+ await saveIndex(index);++ // Remove embedding+ const embeddings = await loadEmbeddings();+ delete embeddings.vectors[id];+ await saveEmbeddings(embeddings);+ } else {+ // Soft delete - mark as archived+ await updateMemory(id, { status: 'archived' });+ }++ console.log(`🧠 Memory deleted: ${id} (hard: ${hard})`);+ cosEvents.emit('memory:deleted', { id, hard });++ return { success: true, id };+ });+}++/**+ * Search memories semantically+ */+export async function searchMemories(queryEmbedding, options = {}) {+ const embeddings = await loadEmbeddings();+ const index = await loadIndex();++ if (!queryEmbedding || Object.keys(embeddings.vectors).length === 0) {+ return { total: 0, memories: [] };+ }++ // Find similar vectors+ const minRelevance = options.minRelevance || 0.7;+ const limit = options.limit || 20;++ const similar = findAboveThreshold(queryEmbedding, embeddings.vectors, minRelevance);++ // Filter by additional options+ let results = similar.slice(0, limit);++ // Get memory metadata from index+ const indexMap = new Map(index.memories.map(m => [m.id, m]));++ results = results+ .map(r => {+ const meta = indexMap.get(r.id);+ if (!meta || meta.status !== 'active') return null;++ // Apply type/category/tag filters+ if (options.types && options.types.length > 0 && !options.types.includes(meta.type)) return null;+ if (options.categories && options.categories.length > 0 && !options.categories.includes(meta.category)) return null;+ if (options.tags && options.tags.length > 0 && !meta.tags.some(t => options.tags.includes(t))) return null;++ return { ...meta, similarity: r.similarity };+ })+ .filter(Boolean);++ return { total: results.length, memories: results };+}++/**+ * Get timeline data (memories grouped by date)+ */+export async function getTimeline(options = {}) {+ const index = await loadIndex();+ let memories = index.memories.filter(m => m.status === 'active');++ // Filter by date range+ if (options.startDate) {+ memories = memories.filter(m => m.createdAt >= options.startDate);+ }+ if (options.endDate) {+ memories = memories.filter(m => m.createdAt <= options.endDate);+ }++ // Filter by types+ if (options.types && options.types.length > 0) {+ memories = memories.filter(m => options.types.includes(m.type));+ }++ // Sort by date descending+ memories.sort((a, b) => (b.createdAt > a.createdAt ? 1 : -1));++ // Limit+ const limit = options.limit || 100;+ memories = memories.slice(0, limit);++ // Group by date+ const timeline = {};+ for (const memory of memories) {+ const date = memory.createdAt.split('T')[0];+ if (!timeline[date]) timeline[date] = [];+ timeline[date].push(memory);+ }++ return timeline;+}++/**+ * Get all unique categories+ */+export async function getCategories() {+ const index = await loadIndex();+ const categories = new Map();++ for (const memory of index.memories) {+ if (memory.status !== 'active') continue;+ const count = categories.get(memory.category) || 0;+ categories.set(memory.category, count + 1);+ }++ return Array.from(categories.entries()).map(([name, count]) => ({ name, count }));+}++/**+ * Get all unique tags+ */+export async function getTags() {+ const index = await loadIndex();+ const tags = new Map();++ for (const memory of index.memories) {+ if (memory.status !== 'active') continue;+ for (const tag of memory.tags) {+ const count = tags.get(tag) || 0;+ tags.set(tag, count + 1);+ }+ }++ return Array.from(tags.entries())+ .map(([name, count]) => ({ name, count }))+ .sort((a, b) => b.count - a.count);+}++/**+ * Get related memories (by ID links + embedding similarity)+ */+export async function getRelatedMemories(id, limit = 10) {+ const memory = await loadMemory(id);+ if (!memory) return [];++ const embeddings = await loadEmbeddings();+ const index = await loadIndex();+ const indexMap = new Map(index.memories.map(m => [m.id, m]));++ const related = [];++ // Add explicitly linked memories+ for (const relId of memory.relatedMemories) {+ const meta = indexMap.get(relId);+ if (meta && meta.status === 'active') {+ related.push({ ...meta, relationship: 'linked', similarity: 1.0 });+ }+ }++ // Add similar by embedding+ if (memory.embedding && embeddings.vectors[id]) {+ const similar = findTopK(memory.embedding, embeddings.vectors, limit + related.length);+ for (const item of similar) {+ if (item.id === id) continue;+ if (related.some(r => r.id === item.id)) continue;++ const meta = indexMap.get(item.id);+ if (meta && meta.status === 'active') {+ related.push({ ...meta, relationship: 'similar', similarity: item.similarity });+ }+ }+ }++ return related.slice(0, limit);+}++/**+ * Get graph data for visualization+ */+export async function getGraphData() {+ const index = await loadIndex();+ const embeddings = await loadEmbeddings();++ const activeMemories = index.memories.filter(m => m.status === 'active');++ // Build nodes+ const nodes = activeMemories.map(m => ({+ id: m.id,+ type: m.type,+ category: m.category,+ summary: m.summary,+ importance: m.importance+ }));++ // Build edges from explicit links and high similarity+ const edges = [];+ const seenEdges = new Set();++ for (const memory of activeMemories) {+ const full = await loadMemory(memory.id);+ if (!full) continue;++ // Explicit links+ for (const targetId of full.relatedMemories) {+ const edgeKey = [memory.id, targetId].sort().join('-');+ if (!seenEdges.has(edgeKey)) {+ seenEdges.add(edgeKey);+ edges.push({ source: memory.id, target: targetId, type: 'linked', weight: 1.0 });+ }+ }+ }++ // Add similarity edges (top 3 per node, > 0.8 similarity)+ for (const memory of activeMemories) {+ if (!embeddings.vectors[memory.id]) continue;++ const similar = findTopK(embeddings.vectors[memory.id], embeddings.vectors, 4);+ for (const item of similar) {+ if (item.id === memory.id) continue;+ if (item.similarity < 0.8) continue;++ const edgeKey = [memory.id, item.id].sort().join('-');+ if (!seenEdges.has(edgeKey)) {+ seenEdges.add(edgeKey);+ edges.push({ source: memory.id, target: item.id, type: 'similar', weight: item.similarity });+ }+ }+ }++ return { nodes, edges };+}++/**+ * Link two memories+ */+export async function linkMemories(sourceId, targetId) {+ return withMemoryLock(async () => {+ const source = await loadMemory(sourceId);+ const target = await loadMemory(targetId);++ if (!source || !target) return { success: false, error: 'Memory not found' };++ // Add bidirectional links+ if (!source.relatedMemories.includes(targetId)) {+ source.relatedMemories.push(targetId);+ source.updatedAt = new Date().toISOString();+ await saveMemory(source);+ }++ if (!target.relatedMemories.includes(sourceId)) {+ target.relatedMemories.push(sourceId);+ target.updatedAt = new Date().toISOString();+ await saveMemory(target);+ }++ return { success: true, sourceId, targetId };+ });+}++/**+ * Consolidate similar memories (merge duplicates)+ */+export async function consolidateMemories(threshold = 0.9, dryRun = false) {+ const index = await loadIndex();+ const embeddings = await loadEmbeddings();++ const activeMemories = index.memories.filter(m => m.status === 'active');++ // Get memories with embeddings+ const memoriesWithEmbeddings = [];+ for (const meta of activeMemories) {+ if (embeddings.vectors[meta.id]) {+ memoriesWithEmbeddings.push({+ id: meta.id,+ embedding: embeddings.vectors[meta.id],+ ...meta+ });+ }+ }++ // Cluster by similarity+ const clusters = clusterBySimilarity(memoriesWithEmbeddings, threshold);+ const duplicateClusters = clusters.filter(c => c.length > 1);++ if (dryRun) {+ return {+ dryRun: true,+ clustersFound: duplicateClusters.length,+ memoriesAffected: duplicateClusters.reduce((sum, c) => sum + c.length, 0),+ clusters: duplicateClusters.map(c => c.map(m => ({ id: m.id, summary: m.summary })))+ };+ }++ // Merge each cluster+ let merged = 0;+ for (const cluster of duplicateClusters) {+ // Sort by importance, keep highest+ cluster.sort((a, b) => (b.importance || 0) - (a.importance || 0));+ const primary = cluster[0];++ for (let i = 1; i < cluster.length; i++) {+ await updateMemory(cluster[i].id, {+ status: 'archived',+ mergedInto: primary.id+ });+ merged++;+ }+ }++ console.log(`🧠 Consolidated ${merged} duplicate memories into ${duplicateClusters.length} clusters`);+ return { merged, clusters: duplicateClusters.length };+}++/**+ * Apply importance decay to old memories+ */+export async function applyDecay(decayRate = 0.01) {+ const index = await loadIndex();+ const now = Date.now();+ let updated = 0;++ for (const meta of index.memories) {+ if (meta.status !== 'active') continue;++ const memory = await loadMemory(meta.id);+ if (!memory) continue;++ const ageInDays = (now - new Date(memory.createdAt).getTime()) / (1000 * 60 * 60 * 24);+ const accessRecency = memory.lastAccessed+ ? (now - new Date(memory.lastAccessed).getTime()) / (1000 * 60 * 60 * 24)+ : ageInDays;++ // Decay formula: importance = baseImportance * (1 - decayRate * sqrt(age)) + accessBoost+ const accessBoost = Math.max(0, 0.1 - accessRecency * 0.001);+ const newImportance = Math.max(0.1, memory.importance * (1 - decayRate * Math.sqrt(ageInDays)) + accessBoost);++ // Archive if importance falls below threshold and old enough+ if (newImportance < 0.15 && ageInDays > 30) {+ await updateMemory(meta.id, { status: 'archived', archivedReason: 'decay' });+ updated++;+ } else if (Math.abs(newImportance - memory.importance) > 0.01) {+ await updateMemory(meta.id, { importance: newImportance });+ updated++;+ }+ }++ console.log(`🧠 Decay applied to ${updated} memories`);+ return { updated };+}++/**+ * Clear expired memories+ */+export async function clearExpired() {+ const index = await loadIndex();+ const now = new Date().toISOString();+ let cleared = 0;++ for (const meta of index.memories) {+ if (meta.status !== 'active') continue;++ const memory = await loadMemory(meta.id);+ if (!memory) continue;++ if (memory.expiresAt && memory.expiresAt < now) {+ await updateMemory(meta.id, { status: 'expired' });+ cleared++;+ }+ }++ console.log(`🧠 Cleared ${cleared} expired memories`);+ return { cleared };+}++/**+ * Get memory stats+ */+export async function getStats() {+ const index = await loadIndex();+ const embeddings = await loadEmbeddings();++ const byType = {};+ const byCategory = {};+ const byStatus = {};++ for (const memory of index.memories) {+ byType[memory.type] = (byType[memory.type] || 0) + 1;+ byCategory[memory.category] = (byCategory[memory.category] || 0) + 1;+ byStatus[memory.status] = (byStatus[memory.status] || 0) + 1;+ }++ return {+ total: index.count,+ active: byStatus.active || 0,+ archived: byStatus.archived || 0,+ expired: byStatus.expired || 0,+ withEmbeddings: Object.keys(embeddings.vectors).length,+ byType,+ byCategory,+ lastUpdated: index.lastUpdated+ };+}++/**+ * Invalidate caches (call after external changes)+ */+export function invalidateCaches() {+ indexCache = null;+ embeddingsCache = null;+}diff --git a/server/services/memoryEmbeddings.js b/server/services/memoryEmbeddings.jsnew file mode 100644index 0000000000..58265afb1f--- /dev/null+++ b/server/services/memoryEmbeddings.js@@ -0,0 +1,180 @@+/**+ * Memory Embeddings Service+ *+ * Generates vector embeddings using LM Studio's OpenAI-compatible API.+ * Provides semantic search capabilities for the memory system.+ */++import { DEFAULT_MEMORY_CONFIG } from './memory.js';++// Cache for embedding config (loaded from CoS config)+let embeddingConfig = null;++/**+ * Get embedding configuration+ */+function getConfig() {+ return embeddingConfig || DEFAULT_MEMORY_CONFIG;+}++/**+ * Set embedding configuration (called by CoS service on startup)+ */+export function setEmbeddingConfig(config) {+ embeddingConfig = { ...DEFAULT_MEMORY_CONFIG, ...config };+}++/**+ * Check if LM Studio is available+ */+export async function checkAvailability() {+ const config = getConfig();+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 5000);++ const response = await fetch(`${config.embeddingEndpoint.replace('/v1/embeddings', '/v1/models')}`, {+ method: 'GET',+ signal: controller.signal+ });++ clearTimeout(timeout);++ if (!response.ok) {+ return { available: false, error: `LM Studio returned ${response.status}` };+ }++ const data = await response.json();+ return {+ available: true,+ models: data.data?.map(m => m.id) || []+ };+}++/**+ * Generate embedding for a single text+ */+export async function generateEmbedding(text) {+ const config = getConfig();++ if (!text || text.trim().length === 0) {+ return null;+ }++ // Truncate very long texts to prevent issues+ const maxChars = 8000;+ const truncatedText = text.length > maxChars ? text.substring(0, maxChars) : text;++ const response = await fetch(config.embeddingEndpoint, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ model: config.embeddingModel,+ input: truncatedText+ })+ });++ if (!response.ok) {+ const error = await response.text();+ console.error(`❌ Embedding generation failed: ${error}`);+ return null;+ }++ const data = await response.json();+ return data.data?.[0]?.embedding || null;+}++/**+ * Generate embeddings for multiple texts (batch)+ */+export async function generateBatchEmbeddings(texts) {+ const config = getConfig();++ if (!texts || texts.length === 0) {+ return [];+ }++ // LM Studio supports batch embeddings via array input+ const maxChars = 8000;+ const truncatedTexts = texts.map(t => t.length > maxChars ? t.substring(0, maxChars) : t);++ const response = await fetch(config.embeddingEndpoint, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ model: config.embeddingModel,+ input: truncatedTexts+ })+ });++ if (!response.ok) {+ const error = await response.text();+ console.error(`❌ Batch embedding generation failed: ${error}`);+ return texts.map(() => null);+ }++ const data = await response.json();++ // Sort by index to maintain order+ const embeddings = new Array(texts.length).fill(null);+ for (const item of data.data || []) {+ embeddings[item.index] = item.embedding;+ }++ return embeddings;+}++/**+ * Generate embedding for memory content + metadata+ * Combines content with type/category/tags for richer semantic representation+ */+export async function generateMemoryEmbedding(memory) {+ const parts = [+ `Type: ${memory.type}`,+ `Category: ${memory.category || 'general'}`,+ memory.tags?.length > 0 ? `Tags: ${memory.tags.join(', ')}` : '',+ memory.summary || '',+ memory.content+ ].filter(Boolean);++ const text = parts.join('\n');+ return generateEmbedding(text);+}++/**+ * Generate embeddings for a query (used in search)+ * Optionally enriches query with context hints+ */+export async function generateQueryEmbedding(query, context = {}) {+ const parts = [query];++ // Add context hints if provided+ if (context.types?.length > 0) {+ parts.push(`Looking for: ${context.types.join(', ')}`);+ }+ if (context.categories?.length > 0) {+ parts.push(`In categories: ${context.categories.join(', ')}`);+ }++ const text = parts.join('\n');+ return generateEmbedding(text);+}++/**+ * Estimate token count for text (rough approximation)+ * Used for context budgeting+ */+export function estimateTokens(text) {+ if (!text) return 0;+ // Rough estimate: ~4 chars per token for English text+ return Math.ceil(text.length / 4);+}++/**+ * Truncate text to fit within token budget+ */+export function truncateToTokens(text, maxTokens) {+ if (!text) return '';+ const maxChars = maxTokens * 4;+ if (text.length <= maxChars) return text;+ return text.substring(0, maxChars - 3) + '...';+}diff --git a/server/services/memoryExtractor.js b/server/services/memoryExtractor.jsnew file mode 100644index 0000000000..47e2d747fe--- /dev/null+++ b/server/services/memoryExtractor.js@@ -0,0 +1,246 @@+/**+ * Memory Extractor Service+ *+ * Extracts memories from agent output and task completion.+ * Supports structured MEMORY blocks and pattern-based extraction.+ */++import { createMemory } from './memory.js';+import { generateMemoryEmbedding } from './memoryEmbeddings.js';+import { cosEvents } from './cos.js';++/**+ * Parse structured MEMORY blocks from agent output+ * Format:+ * <MEMORY type="learning" category="codebase" confidence="0.9">+ * Content here+ * Tags: tag1, tag2+ * </MEMORY>+ */+function parseMemoryBlocks(output) {+ const memories = [];+ const memoryRegex = /<MEMORY\s+([^>]*)>([\s\S]*?)<\/MEMORY>/gi;++ let match;+ while ((match = memoryRegex.exec(output)) !== null) {+ const attrs = match[1];+ const content = match[2].trim();++ // Parse attributes+ const type = attrs.match(/type="([^"]+)"/)?.[1] || 'observation';+ const category = attrs.match(/category="([^"]+)"/)?.[1] || 'other';+ const confidence = parseFloat(attrs.match(/confidence="([^"]+)"/)?.[1] || '0.8');++ // Extract tags from content+ const tagsMatch = content.match(/Tags?:\s*(.+)$/mi);+ const tags = tagsMatch ? tagsMatch[1].split(',').map(t => t.trim()) : [];+ const cleanContent = content.replace(/Tags?:\s*.+$/mi, '').trim();++ memories.push({+ type,+ category,+ confidence,+ content: cleanContent,+ tags,+ structured: true+ });+ }++ return memories;+}++/**+ * Extract implicit patterns from agent output+ * Looks for common patterns that indicate learnings/observations+ */+function extractPatterns(output) {+ const memories = [];++ // Pattern: "I learned that..." or "I discovered that..."+ const learnedRegex = /(?:I\s+)?(?:learned|discovered|found out|realized|noticed)\s+that\s+(.+?)(?:\.|$)/gi;+ let match;+ while ((match = learnedRegex.exec(output)) !== null) {+ memories.push({+ type: 'learning',+ content: match[1].trim(),+ confidence: 0.6,+ category: 'other',+ tags: []+ });+ }++ // Pattern: "The codebase uses..." or "This project uses..."+ const usesRegex = /(?:The\s+)?(?:codebase|project|app|system)\s+uses\s+(.+?)(?:\.|$)/gi;+ while ((match = usesRegex.exec(output)) !== null) {+ memories.push({+ type: 'fact',+ content: `The codebase uses ${match[1].trim()}`,+ confidence: 0.7,+ category: 'codebase',+ tags: ['architecture']+ });+ }++ // Pattern: "User prefers..." or "The user wants..."+ const prefersRegex = /(?:The\s+)?user\s+(?:prefers|wants|likes|requested)\s+(.+?)(?:\.|$)/gi;+ while ((match = prefersRegex.exec(output)) !== null) {+ memories.push({+ type: 'preference',+ content: `User prefers ${match[1].trim()}`,+ confidence: 0.8,+ category: 'preferences',+ tags: ['user-preference']+ });+ }++ // Pattern: "I decided to..." or "We should..."+ const decidedRegex = /(?:I\s+)?(?:decided|chose)\s+to\s+(.+?)\s+because\s+(.+?)(?:\.|$)/gi;+ while ((match = decidedRegex.exec(output)) !== null) {+ memories.push({+ type: 'decision',+ content: `Decided to ${match[1].trim()} because ${match[2].trim()}`,+ confidence: 0.7,+ category: 'workflow',+ tags: ['decision']+ });+ }++ // Pattern: "Note:" or "Important:"+ const noteRegex = /(?:Note|Important|Remember):\s*(.+?)(?:\.|$)/gi;+ while ((match = noteRegex.exec(output)) !== null) {+ memories.push({+ type: 'context',+ content: match[1].trim(),+ confidence: 0.65,+ category: 'other',+ tags: ['note']+ });+ }++ return memories;+}++/**+ * Extract task-related context+ */+function extractTaskContext(task, output, success) {+ const memories = [];++ if (success && task.description) {+ // Successful task completion - extract what was done+ const summary = output.length > 500 ? output.substring(0, 500) + '...' : output;++ // Look for completion summary at end of output+ const summaryMatch = output.match(/(?:Summary|Done|Completed):\s*(.+?)(?:\n\n|$)/is);+ if (summaryMatch) {+ memories.push({+ type: 'learning',+ content: `Task "${task.description.substring(0, 100)}": ${summaryMatch[1].trim()}`,+ confidence: 0.75,+ category: 'workflow',+ tags: ['task-completion']+ });+ }+ }++ return memories;+}++/**+ * Deduplicate memories by content similarity+ * Uses simple string comparison for now+ */+function deduplicateMemories(memories) {+ const unique = [];+ const seen = new Set();++ for (const memory of memories) {+ // Normalize content for comparison+ const normalized = memory.content.toLowerCase().replace(/\s+/g, ' ').trim();+ const key = `${memory.type}:${normalized.substring(0, 100)}`;++ if (!seen.has(key)) {+ seen.add(key);+ unique.push(memory);+ }+ }++ return unique;+}++/**+ * Main extraction function+ * Processes agent output and creates memories+ */+export async function extractAndStoreMemories(agentId, taskId, output, task = null) {+ const allMemories = [];++ // Parse structured memory blocks+ const structured = parseMemoryBlocks(output);+ allMemories.push(...structured);++ // Extract patterns from text+ const patterns = extractPatterns(output);+ allMemories.push(...patterns);++ // Extract task context+ if (task) {+ const taskContext = extractTaskContext(task, output, true);+ allMemories.push(...taskContext);+ }++ // Deduplicate+ const unique = deduplicateMemories(allMemories);++ // Filter by confidence+ const highConfidence = unique.filter(m => m.confidence >= 0.8);+ const mediumConfidence = unique.filter(m => m.confidence >= 0.5 && m.confidence < 0.8);++ const created = [];++ // Auto-save high confidence memories+ for (const mem of highConfidence) {+ const embedding = await generateMemoryEmbedding(mem);+ const memory = await createMemory({+ ...mem,+ sourceAgentId: agentId,+ sourceTaskId: taskId+ }, embedding);+ created.push(memory);+ }++ // Queue medium confidence for approval (just emit event for now)+ if (mediumConfidence.length > 0) {+ console.log(`🧠 ${mediumConfidence.length} memories pending approval`);+ cosEvents.emit('memory:approval-needed', {+ agentId,+ taskId,+ memories: mediumConfidence.map(m => ({+ type: m.type,+ content: m.content.substring(0, 200),+ confidence: m.confidence+ }))+ });+ }++ console.log(`🧠 Extracted ${created.length} memories from agent ${agentId}`);+ cosEvents.emit('memory:extracted', {+ agentId,+ taskId,+ count: created.length,+ pendingApproval: mediumConfidence.length+ });++ return {+ created: created.length,+ pendingApproval: mediumConfidence.length,+ memories: created+ };+}++/**+ * Manual extraction endpoint (for API)+ */+export async function extractFromOutput(agentId, taskId, output) {+ return extractAndStoreMemories(agentId, taskId, output);+}diff --git a/server/services/memoryRetriever.js b/server/services/memoryRetriever.jsnew file mode 100644index 0000000000..1f14436294--- /dev/null+++ b/server/services/memoryRetriever.js@@ -0,0 +1,231 @@+/**+ * Memory Retriever Service+ *+ * Retrieves relevant memories for agent context injection.+ * Combines semantic search with importance scoring.+ */++import { getMemories, searchMemories, getMemory } from './memory.js';+import { generateQueryEmbedding, estimateTokens, truncateToTokens } from './memoryEmbeddings.js';+import { DEFAULT_MEMORY_CONFIG } from './memory.js';++/**+ * Get relevant memories for a task+ * Returns formatted text ready for injection into agent prompt+ */+export async function getRelevantMemories(task, options = {}) {+ const maxTokens = options.maxTokens || DEFAULT_MEMORY_CONFIG.maxContextTokens;+ const minRelevance = options.minRelevance || DEFAULT_MEMORY_CONFIG.minRelevanceThreshold;++ const memories = [];+ let tokenCount = 0;++ // 1. Semantic search based on task description+ if (task.description) {+ const queryEmbedding = await generateQueryEmbedding(task.description);++ if (queryEmbedding) {+ const searchResults = await searchMemories(queryEmbedding, {+ minRelevance,+ limit: 20+ });++ for (const result of searchResults.memories) {+ const mem = await getMemory(result.id);+ if (mem) {+ const tokens = estimateTokens(mem.content);+ if (tokenCount + tokens <= maxTokens) {+ memories.push({+ ...mem,+ relevance: result.similarity,+ source: 'semantic'+ });+ tokenCount += tokens;+ }+ }+ }+ }+ }++ // 2. Add high-importance preferences (always include user preferences)+ const preferences = await getMemories({+ types: ['preference'],+ status: 'active',+ sortBy: 'importance',+ sortOrder: 'desc',+ limit: 5+ });++ for (const pref of preferences.memories) {+ if (memories.some(m => m.id === pref.id)) continue;++ const mem = await getMemory(pref.id);+ if (mem) {+ const tokens = estimateTokens(mem.content);+ if (tokenCount + tokens <= maxTokens) {+ memories.push({+ ...mem,+ relevance: mem.importance,+ source: 'preference'+ });+ tokenCount += tokens;+ }+ }+ }++ // 3. Add recent high-importance facts about the codebase+ if (task.metadata?.app) {+ const appMemories = await getMemories({+ types: ['fact', 'observation'],+ categories: ['codebase', 'architecture', 'patterns'],+ status: 'active',+ sortBy: 'importance',+ sortOrder: 'desc',+ limit: 5+ });++ for (const appMem of appMemories.memories) {+ if (memories.some(m => m.id === appMem.id)) continue;++ const mem = await getMemory(appMem.id);+ if (mem) {+ const tokens = estimateTokens(mem.content);+ if (tokenCount + tokens <= maxTokens) {+ memories.push({+ ...mem,+ relevance: mem.importance * 0.8,+ source: 'codebase'+ });+ tokenCount += tokens;+ }+ }+ }+ }++ // Sort by relevance+ memories.sort((a, b) => b.relevance - a.relevance);++ return memories;+}++/**+ * Format memories for prompt injection+ */+export function formatForPrompt(memories) {+ if (!memories || memories.length === 0) {+ return '';+ }++ const sections = {+ preference: [],+ fact: [],+ learning: [],+ observation: [],+ decision: [],+ context: []+ };++ for (const memory of memories) {+ const type = memory.type || 'context';+ if (sections[type]) {+ sections[type].push(memory);+ }+ }++ const lines = ['## Relevant Context from Memory\n'];++ // Format preferences first (most important)+ if (sections.preference.length > 0) {+ lines.push('### User Preferences');+ for (const mem of sections.preference) {+ lines.push(`- ${mem.content}`);+ }+ lines.push('');+ }++ // Format facts about codebase+ if (sections.fact.length > 0) {+ lines.push('### Codebase Facts');+ for (const mem of sections.fact) {+ lines.push(`- ${mem.content}`);+ }+ lines.push('');+ }++ // Format learnings+ if (sections.learning.length > 0) {+ lines.push('### Previous Learnings');+ for (const mem of sections.learning) {+ lines.push(`- ${mem.content}`);+ }+ lines.push('');+ }++ // Format observations+ if (sections.observation.length > 0) {+ lines.push('### Observations');+ for (const mem of sections.observation) {+ lines.push(`- ${mem.content}`);+ }+ lines.push('');+ }++ // Format decisions+ if (sections.decision.length > 0) {+ lines.push('### Past Decisions');+ for (const mem of sections.decision) {+ lines.push(`- ${mem.content}`);+ }+ lines.push('');+ }++ // Format context+ if (sections.context.length > 0) {+ lines.push('### Additional Context');+ for (const mem of sections.context) {+ lines.push(`- ${mem.content}`);+ }+ lines.push('');+ }++ return lines.join('\n');+}++/**+ * Get memory section for agent prompt+ * Main entry point for subAgentSpawner integration+ */+export async function getMemorySection(task, options = {}) {+ const memories = await getRelevantMemories(task, options);++ if (memories.length === 0) {+ return null;+ }++ return formatForPrompt(memories);+}++/**+ * Get memory stats for a task (useful for debugging)+ */+export async function getRetrievalStats(task) {+ const memories = await getRelevantMemories(task, { maxTokens: 10000 });++ return {+ total: memories.length,+ byType: memories.reduce((acc, m) => {+ acc[m.type] = (acc[m.type] || 0) + 1;+ return acc;+ }, {}),+ bySource: memories.reduce((acc, m) => {+ acc[m.source] = (acc[m.source] || 0) + 1;+ return acc;+ }, {}),+ totalTokens: memories.reduce((acc, m) => acc + estimateTokens(m.content), 0),+ topMemories: memories.slice(0, 5).map(m => ({+ type: m.type,+ summary: m.summary,+ relevance: m.relevance.toFixed(2)+ }))+ };+}diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.jsnew file mode 100644index 0000000000..0620c29881--- /dev/null+++ b/server/services/pm2Standardizer.js@@ -0,0 +1,503 @@+import { readFile, writeFile, readdir } from 'fs/promises';+import { existsSync } from 'fs';+import { join, basename, relative } from 'path';+import { exec } from 'child_process';+import { promisify } from 'util';+import { getActiveProvider, getProviderById } from './providers.js';+import { spawn } from 'child_process';++const execAsync = promisify(exec);++/**+ * Gather all config files for standardization analysis+ */+async function gatherConfigContext(dirPath) {+ const context = {+ dirName: basename(dirPath),+ hasGit: existsSync(join(dirPath, '.git')),+ packageJson: null,+ ecosystemConfig: null,+ ecosystemPath: null,+ envFiles: [],+ viteConfigs: [],+ otherConfigs: [],+ structure: { hasClient: false, hasServer: false, hasPackages: false }+ };++ // Check directory structure+ const entries = await readdir(dirPath, { withFileTypes: true }).catch(() => []);+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);++ context.structure.hasClient = dirs.includes('client') || dirs.includes('web') || dirs.includes('frontend');+ context.structure.hasServer = dirs.includes('server') || dirs.includes('api') || dirs.includes('backend');+ context.structure.hasPackages = dirs.includes('packages');++ // Read package.json+ const pkgPath = join(dirPath, 'package.json');+ if (existsSync(pkgPath)) {+ context.packageJson = await readFile(pkgPath, 'utf-8').catch(() => null);+ }++ // Read ecosystem.config+ for (const name of ['ecosystem.config.cjs', 'ecosystem.config.js']) {+ const path = join(dirPath, name);+ if (existsSync(path)) {+ context.ecosystemConfig = await readFile(path, 'utf-8').catch(() => null);+ context.ecosystemPath = name;+ break;+ }+ }++ // Read .env files+ for (const name of ['.env', '.env.local', '.env.development']) {+ const path = join(dirPath, name);+ if (existsSync(path)) {+ const content = await readFile(path, 'utf-8').catch(() => '');+ context.envFiles.push({ name, path, content });+ }+ }++ // Read vite configs (root and subdirs)+ const vitePaths = [+ ['vite.config.js', dirPath],+ ['vite.config.ts', dirPath],+ ['client/vite.config.js', join(dirPath, 'client')],+ ['client/vite.config.ts', join(dirPath, 'client')],+ ['packages/web/vite.config.js', join(dirPath, 'packages/web')],+ ['packages/web/vite.config.ts', join(dirPath, 'packages/web')]+ ];++ for (const [relPath, fullDir] of vitePaths) {+ const fullPath = join(dirPath, relPath);+ if (existsSync(fullPath)) {+ const content = await readFile(fullPath, 'utf-8').catch(() => '');+ context.viteConfigs.push({ name: relPath, path: fullPath, content });+ }+ }++ return context;+}++/**+ * Build LLM prompt for PM2 standardization analysis+ */+function buildStandardizationPrompt(context) {+ return `# PM2 Standardization Analysis++You are analyzing a Node.js application to generate a standardized PM2 ecosystem configuration.++## Project: ${context.dirName}++## Directory Structure+- Has client/web directory: ${context.structure.hasClient}+- Has server/api directory: ${context.structure.hasServer}+- Has packages/ directory: ${context.structure.hasPackages}++## Current Files++${context.packageJson ? `### package.json+\`\`\`json+${context.packageJson}+\`\`\`` : 'No package.json found'}++${context.ecosystemConfig ? `### ${context.ecosystemPath}+\`\`\`javascript+${context.ecosystemConfig}+\`\`\`` : 'No ecosystem.config found'}++${context.envFiles.length > 0 ? `### Environment Files+${context.envFiles.map(f => `#### ${f.name}\n\`\`\`\n${f.content}\n\`\`\``).join('\n\n')}` : ''}++${context.viteConfigs.length > 0 ? `### Vite Configs+${context.viteConfigs.map(f => `#### ${f.name}\n\`\`\`javascript\n${f.content}\n\`\`\``).join('\n\n')}` : ''}++## PM2 Standard Requirements++1. **All ports MUST be in ecosystem.config.cjs env blocks** - Never in .env or vite.config+2. **Use CommonJS format** (.cjs extension) for PM2 compatibility+3. **Process naming**: lowercase-hyphenated (e.g., "myapp-server", "myapp-client")+4. **Server processes**: Enable watch for live-reload on dist/ or src/+5. **Vite processes**: Use \`npx vite --host --port XXXX\` in args, disable watch (Vite has HMR)+6. **Set cwd** for each process pointing to its directory+7. **Include NODE_ENV** in all env blocks++## Output Format++Return ONLY valid JSON (no markdown wrapper, no explanation) with this structure:+{+ "processes": [+ {+ "name": "string - process name",+ "cwd": "string - relative path like ./server or ./packages/web",+ "script": "string - entry point or npx",+ "args": "string or null - for vite: 'vite --host --port XXXX'",+ "watch": "array of paths to watch or false",+ "watchDelay": 1000,+ "ignoreWatch": ["node_modules", "data", "*.log"],+ "env": {+ "NODE_ENV": "development",+ "PORT": "number - the port this process uses"+ }+ }+ ],+ "strayPorts": [+ {+ "file": "string - relative file path",+ "variable": "string - variable name like PORT",+ "value": "number - the port value",+ "line": "number - line number",+ "action": "remove or keep"+ }+ ],+ "reasoning": "Brief explanation of your analysis"+}++Rules:+- Generate ecosystem.config.cjs content for ALL processes needed+- If existing ecosystem.config exists, preserve working configurations but add missing ports to env+- Mark PORT/VITE_PORT in .env files with action: "remove" (will be moved to ecosystem)+- Mark port in vite.config with action: "remove" (will use --port arg instead)+- If no ports are detected, use sensible defaults (3000 for frontend, 3001 for backend)`;+}++/**+ * Execute LLM analysis using CLI provider+ */+async function executeCliAnalysis(provider, prompt, cwd) {+ return new Promise((resolve, reject) => {+ const args = [...(provider.args || []), prompt];+ let output = '';++ const child = spawn(provider.command, args, {+ cwd,+ env: process.env,+ shell: false+ });++ child.stdout.on('data', (data) => {+ output += data.toString();+ });++ child.stderr.on('data', (data) => {+ output += data.toString();+ });++ child.on('close', (code) => {+ if (code === 0) {+ resolve(output);+ } else {+ reject(new Error(`CLI exited with code ${code}`));+ }+ });++ child.on('error', reject);++ setTimeout(() => {+ child.kill();+ reject(new Error('Standardization analysis timed out'));+ }, provider.timeout || 120000);+ });+}++/**+ * Execute LLM analysis using API provider+ */+async function executeApiAnalysis(provider, prompt) {+ const headers = { 'Content-Type': 'application/json' };+ if (provider.apiKey) {+ headers['Authorization'] = `Bearer ${provider.apiKey}`;+ }++ const response = await fetch(`${provider.endpoint}/chat/completions`, {+ method: 'POST',+ headers,+ body: JSON.stringify({+ model: provider.defaultModel,+ messages: [{ role: 'user', content: prompt }],+ temperature: 0.1+ })+ });++ if (!response.ok) {+ throw new Error(`API error: ${response.status}`);+ }++ const data = await response.json();+ return data.choices?.[0]?.message?.content || '';+}++/**+ * Parse LLM response to extract JSON+ */+function parseAnalysisResponse(response) {+ let jsonStr = response.trim();++ // Remove markdown code blocks if present+ const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);+ if (jsonMatch) {+ jsonStr = jsonMatch[1].trim();+ }++ // Try to find JSON object+ const objectMatch = jsonStr.match(/\{[\s\S]*\}/);+ if (objectMatch) {+ jsonStr = objectMatch[0];+ }++ return JSON.parse(jsonStr);+}++/**+ * Generate ecosystem.config.cjs content from processes+ */+function generateEcosystemContent(processes, appName) {+ const apps = processes.map(proc => {+ const config = {+ name: proc.name,+ cwd: proc.cwd,+ script: proc.script+ };++ if (proc.args) {+ config.args = proc.args;+ }++ if (proc.watch && proc.watch !== false) {+ config.watch = proc.watch;+ config.watch_delay = proc.watchDelay || 1000;+ config.ignore_watch = proc.ignoreWatch || ['node_modules', 'data', '*.log'];+ } else {+ config.watch = false;+ }++ config.env = proc.env || { NODE_ENV: 'development' };++ return config;+ });++ // Generate formatted JavaScript+ const configStr = JSON.stringify({ apps }, null, 2)+ .replace(/"([^"]+)":/g, '$1:') // Remove quotes from keys+ .replace(/"/g, "'"); // Use single quotes for strings++ return `// PM2 Ecosystem Configuration+// Generated by PortOS PM2 Standardizer++module.exports = ${configStr};+`;+}++/**+ * Create git backup before modifications+ */+export async function createGitBackup(repoPath) {+ // Check if git repo+ if (!existsSync(join(repoPath, '.git'))) {+ return { success: false, reason: 'Not a git repository' };+ }++ const timestamp = Date.now();+ const branch = `portos-backup-${timestamp}`;++ // Check for uncommitted changes+ const { stdout: status } = await execAsync('git status --porcelain', { cwd: repoPath });+ const hasChanges = status.trim().length > 0;++ if (hasChanges) {+ // Stash changes+ await execAsync('git stash push -m "PortOS standardization backup"', { cwd: repoPath })+ .catch(() => null); // Ignore if nothing to stash+ }++ // Create backup branch+ await execAsync(`git branch ${branch}`, { cwd: repoPath });++ if (hasChanges) {+ // Pop stash+ await execAsync('git stash pop', { cwd: repoPath }).catch(() => null);+ }++ return { success: true, branch, hadChanges: hasChanges };+}++/**+ * Analyze app and generate standardization plan+ */+export async function analyzeApp(repoPath, providerId = null) {+ if (!existsSync(repoPath)) {+ return { success: false, error: 'Directory does not exist' };+ }++ // Get provider+ const provider = providerId+ ? await getProviderById(providerId)+ : await getActiveProvider();++ if (!provider) {+ return { success: false, error: 'No AI provider configured' };+ }++ if (!provider.enabled) {+ return { success: false, error: 'AI provider is disabled' };+ }++ // Gather context+ const context = await gatherConfigContext(repoPath);+ const prompt = buildStandardizationPrompt(context);++ // Execute analysis+ let response;+ if (provider.type === 'cli') {+ response = await executeCliAnalysis(provider, prompt, repoPath);+ } else if (provider.type === 'api') {+ response = await executeApiAnalysis(provider, prompt);+ } else {+ return { success: false, error: 'Unknown provider type' };+ }++ // Parse response+ const analysis = parseAnalysisResponse(response);++ // Generate ecosystem content+ const ecosystemContent = generateEcosystemContent(analysis.processes, context.dirName);++ return {+ success: true,+ provider: provider.name,+ repoPath,+ currentState: {+ hasEcosystem: !!context.ecosystemConfig,+ ecosystemPath: context.ecosystemPath,+ hasGit: context.hasGit,+ envFiles: context.envFiles.map(f => f.name),+ viteConfigs: context.viteConfigs.map(f => f.name)+ },+ proposedChanges: {+ createEcosystem: !context.ecosystemConfig,+ ecosystemContent,+ processes: analysis.processes,+ strayPorts: analysis.strayPorts || []+ },+ llmAnalysis: {+ providerId: provider.id,+ reasoning: analysis.reasoning || 'Analysis complete'+ }+ };+}++/**+ * Apply standardization changes to the repository+ */+export async function applyStandardization(repoPath, plan) {+ const results = {+ success: true,+ backupBranch: null,+ filesModified: [],+ errors: []+ };++ // Create git backup first+ if (plan.currentState.hasGit) {+ const backup = await createGitBackup(repoPath);+ if (backup.success) {+ results.backupBranch = backup.branch;+ console.log(`📦 Created backup branch: ${backup.branch}`);+ } else {+ console.log(`⚠️ Could not create backup: ${backup.reason}`);+ }+ }++ // Write ecosystem.config.cjs+ const ecosystemPath = join(repoPath, 'ecosystem.config.cjs');+ await writeFile(ecosystemPath, plan.proposedChanges.ecosystemContent, 'utf-8');+ results.filesModified.push('ecosystem.config.cjs');+ console.log(`✅ Written ecosystem.config.cjs`);++ // Remove old ecosystem.config.js if we're creating .cjs+ const oldEcosystemJs = join(repoPath, 'ecosystem.config.js');+ if (existsSync(oldEcosystemJs) && plan.proposedChanges.createEcosystem) {+ const { unlink } = await import('fs/promises');+ await unlink(oldEcosystemJs).catch(() => null);+ results.filesModified.push('ecosystem.config.js (removed)');+ }++ // Process stray ports - remove from .env files+ for (const stray of plan.proposedChanges.strayPorts || []) {+ if (stray.action !== 'remove') continue;++ const filePath = join(repoPath, stray.file);+ if (!existsSync(filePath)) continue;++ const content = await readFile(filePath, 'utf-8').catch(() => null);+ if (!content) continue;++ // Remove the port line from .env files+ if (stray.file.includes('.env')) {+ const lines = content.split('\n');+ const filtered = lines.filter(line => {+ const trimmed = line.trim();+ if (trimmed.startsWith('#')) return true;+ return !new RegExp(`^${stray.variable}\\s*=`).test(trimmed);+ });++ if (filtered.length !== lines.length) {+ await writeFile(filePath, filtered.join('\n'), 'utf-8');+ results.filesModified.push(`${stray.file} (removed ${stray.variable})`);+ console.log(`✅ Removed ${stray.variable} from ${stray.file}`);+ }+ }++ // Remove port from vite.config (more complex - comment it out)+ if (stray.file.includes('vite.config')) {+ const modified = content.replace(+ /(\s*port\s*:\s*\d+\s*,?)/g,+ '/* $1 */ // Moved to PM2 ecosystem.config.cjs'+ );++ if (modified !== content) {+ await writeFile(filePath, modified, 'utf-8');+ results.filesModified.push(`${stray.file} (commented out port)`);+ console.log(`✅ Commented out port in ${stray.file}`);+ }+ }+ }++ return results;+}++/**+ * Get the standard PM2 template for reference+ */+export function getStandardTemplate() {+ return `// PM2 Ecosystem Configuration Template+// All ports should be defined here, not in .env or vite.config++module.exports = {+ apps: [+ {+ name: 'myapp-server',+ cwd: './server',+ script: 'dist/index.js',+ watch: ['dist'],+ watch_delay: 1000,+ ignore_watch: ['node_modules', 'data', '*.log'],+ env: {+ NODE_ENV: 'development',+ PORT: 3001+ }+ },+ {+ name: 'myapp-client',+ cwd: './client',+ script: 'npx',+ args: 'vite --host --port 3000',+ watch: false,+ env: {+ NODE_ENV: 'development',+ PORT: 3000+ }+ }+ ]+};+`;+}diff --git a/server/services/runner.js b/server/services/runner.jsindex e92ed21d17..5c47f1b1ef 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -88,16 +88,20 @@ export async function executeCliRun(runId, provider, prompt, workspacePath, onDaconst startTime = Date.now();let output = '';+ console.log(`🔧 Spawning: ${provider.command} ${args.join(' ')} in ${workspacePath || process.cwd()}`);+const child = spawn(provider.command, args, {cwd: workspacePath || process.cwd(),env: { ...process.env, ...provider.envVars },- shell: false+ stdio: ['pipe', 'pipe', 'pipe']});+ console.log(`🔧 Child process spawned, pid: ${child.pid}`);activeRuns.set(runId, child);const appendOutput = async (data) => {const text = data.toString();+ console.log(`📥 Received ${text.length} chars from child process`);output += text;await writeFile(outputPath, output);onData?.(text);@@ -106,6 +110,10 @@ export async function executeCliRun(runId, provider, prompt, workspacePath, onDachild.stdout.on('data', appendOutput);child.stderr.on('data', appendOutput);+ child.on('spawn', () => {+ console.log(`✓ Child process spawned successfully`);+ });+child.on('close', async (code) => {activeRuns.delete(runId);@@ -286,7 +294,7 @@ export async function getRunPrompt(runId) {return readFile(join(runDir, 'prompt.txt'), 'utf-8');}-export async function listRuns(limit = 50, offset = 0) {+export async function listRuns(limit = 50, offset = 0, source = 'all') {await ensureRunsDir();const entries = await readdir(RUNS_DIR, { withFileTypes: true });@@ -304,11 +312,20 @@ export async function listRuns(limit = 50, offset = 0) {}}- runs.sort((a, b) => new Date(b.startTime) - new Date(a.startTime));+ // Filter by source if specified+ let filteredRuns = runs;+ if (source !== 'all') {+ filteredRuns = runs.filter(run => {+ const runSource = run.source || 'devtools'; // Legacy runs without source are from devtools+ return runSource === source;+ });+ }++ filteredRuns.sort((a, b) => new Date(b.startTime) - new Date(a.startTime));return {- total: runs.length,- runs: runs.slice(offset, offset + limit)+ total: filteredRuns.length,+ runs: filteredRuns.slice(offset, offset + limit)};}diff --git a/server/services/scriptRunner.js b/server/services/scriptRunner.jsnew file mode 100644index 0000000000..b94d4ca744--- /dev/null+++ b/server/services/scriptRunner.js@@ -0,0 +1,377 @@+/**+ * Script Runner Service+ *+ * Manages scheduled scripts that can trigger LLM agents+ * when they detect issues requiring investigation.+ */++import { spawn } from 'child_process';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { writeFile, readFile, mkdir, readdir, rm } from 'fs/promises';+import { existsSync } from 'fs';+import { v4 as uuidv4 } from 'uuid';+import Cron from 'croner';+import { cosEvents } from './cos.js';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const SCRIPTS_DIR = join(__dirname, '../../data/cos/scripts');+const SCRIPTS_STATE_FILE = join(__dirname, '../../data/cos/scripts-state.json');++// Active scheduled jobs+const scheduledJobs = new Map();++// Schedule presets to cron expressions+const SCHEDULE_PRESETS = {+ 'every-5-min': '*/5 * * * *',+ 'every-15-min': '*/15 * * * *',+ 'every-30-min': '*/30 * * * *',+ 'hourly': '0 * * * *',+ 'every-6-hours': '0 */6 * * *',+ 'daily': '0 9 * * *',+ 'weekly': '0 9 * * 1',+ 'on-demand': null+};++/**+ * Initialize the script runner+ */+export async function initScriptRunner() {+ await ensureScriptsDir();+ const scripts = await listScripts();++ // Schedule all enabled scripts+ for (const script of scripts) {+ if (script.enabled && script.schedule !== 'on-demand') {+ scheduleScript(script);+ }+ }++ console.log(`📜 Script runner initialized with ${scripts.length} scripts`);+}++/**+ * Ensure scripts directory exists+ */+async function ensureScriptsDir() {+ if (!existsSync(SCRIPTS_DIR)) {+ await mkdir(SCRIPTS_DIR, { recursive: true });+ }+}++/**+ * Load scripts state+ */+async function loadScriptsState() {+ if (!existsSync(SCRIPTS_STATE_FILE)) {+ return { scripts: {} };+ }+ const content = await readFile(SCRIPTS_STATE_FILE, 'utf-8');+ return JSON.parse(content);+}++/**+ * Save scripts state+ */+async function saveScriptsState(state) {+ await writeFile(SCRIPTS_STATE_FILE, JSON.stringify(state, null, 2));+}++/**+ * Convert schedule to cron expression+ */+function scheduleToCron(schedule, customCron = null) {+ if (customCron) return customCron;+ return SCHEDULE_PRESETS[schedule] || null;+}++/**+ * Schedule a script+ */+export function scheduleScript(script) {+ // Stop existing job if any+ unscheduleScript(script.id);++ const cronExpr = scheduleToCron(script.schedule, script.cronExpression);+ if (!cronExpr) return; // on-demand scripts don't get scheduled++ const job = new Cron(cronExpr, async () => {+ await executeScript(script.id);+ });++ scheduledJobs.set(script.id, job);+ console.log(`⏰ Scheduled script ${script.name} (${script.id}) with cron: ${cronExpr}`);+}++/**+ * Unschedule a script+ */+export function unscheduleScript(scriptId) {+ const job = scheduledJobs.get(scriptId);+ if (job) {+ job.stop();+ scheduledJobs.delete(scriptId);+ }+}++/**+ * Create a new script+ */+export async function createScript(data) {+ const id = `script-${uuidv4().slice(0, 8)}`;++ const script = {+ id,+ name: data.name,+ description: data.description || '',+ command: data.command,+ schedule: data.schedule || 'on-demand',+ cronExpression: data.cronExpression || null,+ enabled: data.enabled !== false,+ triggerAction: data.triggerAction || 'log-only', // 'spawn-agent' | 'create-task' | 'log-only'+ triggerPrompt: data.triggerPrompt || '',+ triggerPriority: data.triggerPriority || 'MEDIUM',+ createdAt: new Date().toISOString(),+ lastRun: null,+ lastOutput: null,+ lastExitCode: null,+ lastTriggered: null,+ runCount: 0+ };++ const state = await loadScriptsState();+ state.scripts[id] = script;+ await saveScriptsState(state);++ // Schedule if enabled+ if (script.enabled && script.schedule !== 'on-demand') {+ scheduleScript(script);+ }++ cosEvents.emit('script:created', script);+ return script;+}++/**+ * Update a script+ */+export async function updateScript(id, data) {+ const state = await loadScriptsState();+ const script = state.scripts[id];++ if (!script) {+ return null;+ }++ // Update fields+ const updatedScript = {+ ...script,+ name: data.name ?? script.name,+ description: data.description ?? script.description,+ command: data.command ?? script.command,+ schedule: data.schedule ?? script.schedule,+ cronExpression: data.cronExpression ?? script.cronExpression,+ enabled: data.enabled ?? script.enabled,+ triggerAction: data.triggerAction ?? script.triggerAction,+ triggerPrompt: data.triggerPrompt ?? script.triggerPrompt,+ triggerPriority: data.triggerPriority ?? script.triggerPriority,+ updatedAt: new Date().toISOString()+ };++ state.scripts[id] = updatedScript;+ await saveScriptsState(state);++ // Reschedule if needed+ if (updatedScript.enabled && updatedScript.schedule !== 'on-demand') {+ scheduleScript(updatedScript);+ } else {+ unscheduleScript(id);+ }++ cosEvents.emit('script:updated', updatedScript);+ return updatedScript;+}++/**+ * Delete a script+ */+export async function deleteScript(id) {+ unscheduleScript(id);++ const state = await loadScriptsState();+ if (!state.scripts[id]) {+ return false;+ }++ delete state.scripts[id];+ await saveScriptsState(state);++ cosEvents.emit('script:deleted', { id });+ return true;+}++/**+ * Get a script by ID+ */+export async function getScript(id) {+ const state = await loadScriptsState();+ return state.scripts[id] || null;+}++/**+ * List all scripts+ */+export async function listScripts() {+ const state = await loadScriptsState();+ return Object.values(state.scripts).sort((a, b) =>+ new Date(b.createdAt) - new Date(a.createdAt)+ );+}++/**+ * Execute a script+ */+export async function executeScript(scriptId) {+ const state = await loadScriptsState();+ const script = state.scripts[scriptId];++ if (!script) {+ return { success: false, error: 'Script not found' };+ }++ console.log(`▶️ Executing script: ${script.name} (${scriptId})`);+ cosEvents.emit('script:started', { scriptId, name: script.name });++ const startTime = Date.now();++ return new Promise((resolve) => {+ const child = spawn('sh', ['-c', script.command], {+ cwd: join(__dirname, '../../'),+ timeout: 60000 // 1 minute timeout+ });++ let output = '';+ let error = '';++ child.stdout.on('data', (data) => {+ output += data.toString();+ });++ child.stderr.on('data', (data) => {+ error += data.toString();+ });++ child.on('close', async (code) => {+ const duration = Date.now() - startTime;+ const fullOutput = output + (error ? `\n[stderr]\n${error}` : '');++ // Update script state+ script.lastRun = new Date().toISOString();+ script.lastOutput = fullOutput.substring(0, 10000); // Limit stored output+ script.lastExitCode = code;+ script.runCount = (script.runCount || 0) + 1;++ state.scripts[scriptId] = script;+ await saveScriptsState(state);++ console.log(`✅ Script ${script.name} completed with code ${code} in ${duration}ms`);++ // Handle trigger action+ if (script.triggerAction === 'spawn-agent' && script.triggerPrompt) {+ console.log(`🚀 Triggering agent for script ${script.name}`);+ script.lastTriggered = new Date().toISOString();+ state.scripts[scriptId] = script;+ await saveScriptsState(state);++ cosEvents.emit('task:ready', {+ id: `script-${scriptId}-${Date.now()}`,+ priority: script.triggerPriority,+ description: script.triggerPrompt,+ taskType: 'internal',+ metadata: {+ context: `Script Output:\n\`\`\`\n${fullOutput.substring(0, 5000)}\n\`\`\``,+ source: 'script',+ scriptId,+ scriptName: script.name+ }+ });+ }++ cosEvents.emit('script:completed', {+ scriptId,+ name: script.name,+ exitCode: code,+ duration,+ outputLength: fullOutput.length+ });++ resolve({+ success: code === 0,+ exitCode: code,+ output: fullOutput,+ duration+ });+ });++ child.on('error', async (err) => {+ console.error(`❌ Script ${script.name} error: ${err.message}`);++ script.lastRun = new Date().toISOString();+ script.lastOutput = `Error: ${err.message}`;+ script.lastExitCode = -1;+ state.scripts[scriptId] = script;+ await saveScriptsState(state);++ cosEvents.emit('script:error', { scriptId, error: err.message });++ resolve({+ success: false,+ error: err.message+ });+ });+ });+}++/**+ * Get script run history (from state)+ */+export async function getScriptRuns(scriptId, limit = 10) {+ // For now, we only store the last run in state+ // Could be extended to store full history+ const script = await getScript(scriptId);+ if (!script) return [];++ if (script.lastRun) {+ return [{+ timestamp: script.lastRun,+ output: script.lastOutput,+ exitCode: script.lastExitCode,+ triggered: script.lastTriggered+ }];+ }++ return [];+}++/**+ * Get available schedule presets+ */+export function getSchedulePresets() {+ return Object.keys(SCHEDULE_PRESETS);+}++/**+ * Get scheduled job info+ */+export function getScheduledJobs() {+ const jobs = [];+ for (const [scriptId, job] of scheduledJobs) {+ jobs.push({+ scriptId,+ nextRun: job.nextRun()?.toISOString(),+ isRunning: job.isRunning()+ });+ }+ return jobs;+}diff --git a/server/services/socket.js b/server/services/socket.jsindex b4e9f6e020..edf3827b81 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -1,8 +1,16 @@import { spawn } from 'child_process';import { streamDetection } from './streamingDetect.js';+import { cosEvents } from './cos.js';+import { errorEvents } from '../lib/errorHandler.js';+import { handleErrorRecovery } from './autoFixer.js';+import * as pm2Standardizer from './pm2Standardizer.js';// Store active log streams per socketconst activeStreams = new Map();+// Store CoS subscribers+const cosSubscribers = new Set();+// Store error subscribers for auto-fix notifications+const errorSubscribers = new Set();export function initSocket(io) {io.on('connection', (socket) => {@@ -14,6 +22,76 @@ export function initSocket(io) {await streamDetection(socket, path);});+ // Handle PM2 standardization+ socket.on('standardize:start', async ({ repoPath, providerId }) => {+ console.log(`🔧 Starting PM2 standardization: ${repoPath}`);++ const emit = (step, status, data = {}) => {+ socket.emit('standardize:step', { step, status, data, timestamp: Date.now() });+ };++ // Step 1: Analyze+ emit('analyze', 'running', { message: 'Analyzing project configuration...' });++ const analysis = await pm2Standardizer.analyzeApp(repoPath, providerId)+ .catch(err => ({ success: false, error: err.message }));++ if (!analysis.success) {+ emit('analyze', 'error', { message: analysis.error });+ socket.emit('standardize:complete', { success: false, error: analysis.error });+ return;+ }++ emit('analyze', 'done', {+ message: `Found ${analysis.proposedChanges.processes?.length || 0} processes`,+ processes: analysis.proposedChanges.processes,+ strayPorts: analysis.proposedChanges.strayPorts+ });++ socket.emit('standardize:analyzed', { plan: analysis });++ // Step 2: Backup+ emit('backup', 'running', { message: 'Creating git backup...' });++ const backup = await pm2Standardizer.createGitBackup(repoPath)+ .catch(err => ({ success: false, reason: err.message }));++ if (backup.success) {+ emit('backup', 'done', { message: `Backup branch: ${backup.branch}`, branch: backup.branch });+ } else {+ emit('backup', 'skipped', { message: backup.reason || 'No git repository' });+ }++ // Step 3: Apply changes+ emit('apply', 'running', { message: 'Writing ecosystem.config.cjs...' });++ const result = await pm2Standardizer.applyStandardization(repoPath, analysis)+ .catch(err => ({ success: false, errors: [err.message] }));++ if (result.errors?.length > 0) {+ emit('apply', 'error', { message: result.errors.join(', ') });+ socket.emit('standardize:complete', { success: false, error: result.errors.join(', ') });+ return;+ }++ emit('apply', 'done', {+ message: `Modified ${result.filesModified.length} files`,+ filesModified: result.filesModified+ });++ // Complete+ socket.emit('standardize:complete', {+ success: true,+ result: {+ backupBranch: result.backupBranch,+ filesModified: result.filesModified,+ processes: analysis.proposedChanges.processes+ }+ });++ console.log(`✅ Standardization complete: ${result.filesModified.length} files modified`);+ });+// Handle log streaming requestssocket.on('logs:subscribe', ({ processName, lines = 100 }) => {// Clean up any existing stream for this socket@@ -80,12 +158,58 @@ export function initSocket(io) {socket.emit('logs:unsubscribed');});+ // CoS subscriptions+ socket.on('cos:subscribe', () => {+ cosSubscribers.add(socket);+ socket.emit('cos:subscribed');+ });++ socket.on('cos:unsubscribe', () => {+ cosSubscribers.delete(socket);+ socket.emit('cos:unsubscribed');+ });++ // Error event subscriptions+ socket.on('errors:subscribe', () => {+ errorSubscribers.add(socket);+ socket.emit('errors:subscribed');+ });++ socket.on('errors:unsubscribe', () => {+ errorSubscribers.delete(socket);+ socket.emit('errors:unsubscribed');+ });++ // Handle error recovery requests (can trigger auto-fix agents)+ socket.on('error:recover', async ({ code, context }) => {+ console.log(`🔧 Error recovery requested: ${code}`);++ // Create auto-fix task+ const task = await handleErrorRecovery(code, context);++ // Broadcast recovery task created+ io.emit('error:recover:requested', {+ code,+ context,+ taskId: task.id,+ timestamp: Date.now()+ });+ });+// Cleanup on disconnectsocket.on('disconnect', () => {console.log(`🔌 Client disconnected: ${socket.id}`);cleanupStream(socket.id);+ cosSubscribers.delete(socket);+ errorSubscribers.delete(socket);});});++ // Set up CoS event forwarding to subscribers+ setupCosEventForwarding();++ // Set up error event forwarding to subscribers+ setupErrorEventForwarding();}function cleanupStream(socketId) {@@ -100,3 +224,72 @@ function cleanupStream(socketId) {export function broadcast(io, event, data) {io.emit(event, data);}++// Broadcast to CoS subscribers only+function broadcastToCos(event, data) {+ for (const socket of cosSubscribers) {+ socket.emit(event, data);+ }+}++// Broadcast to error subscribers only+function broadcastToErrors(event, data) {+ for (const socket of errorSubscribers) {+ socket.emit(event, data);+ }+}++// Set up CoS event forwarding+function setupCosEventForwarding() {+ // Status events+ cosEvents.on('status', (data) => broadcastToCos('cos:status', data));++ // Log events for real-time UI feedback+ cosEvents.on('log', (data) => broadcastToCos('cos:log', data));++ // Task events+ cosEvents.on('tasks:user:changed', (data) => broadcastToCos('cos:tasks:user:changed', data));+ cosEvents.on('tasks:user:added', (data) => broadcastToCos('cos:tasks:user:added', data));+ cosEvents.on('tasks:user:completed', (data) => broadcastToCos('cos:tasks:user:completed', data));+ cosEvents.on('tasks:cos:changed', (data) => broadcastToCos('cos:tasks:cos:changed', data));++ // Agent events+ cosEvents.on('agent:spawned', (data) => broadcastToCos('cos:agent:spawned', data));+ cosEvents.on('agent:updated', (data) => broadcastToCos('cos:agent:updated', data));+ cosEvents.on('agent:completed', (data) => broadcastToCos('cos:agent:completed', data));+ cosEvents.on('agent:output', (data) => broadcastToCos('cos:agent:output', data));++ // Memory events+ cosEvents.on('memory:created', (data) => broadcastToCos('cos:memory:created', data));+ cosEvents.on('memory:updated', (data) => broadcastToCos('cos:memory:updated', data));+ cosEvents.on('memory:deleted', (data) => broadcastToCos('cos:memory:deleted', data));+ cosEvents.on('memory:extracted', (data) => broadcastToCos('cos:memory:extracted', data));+ cosEvents.on('memory:approval-needed', (data) => broadcastToCos('cos:memory:approval-needed', data));++ // Health events+ cosEvents.on('health:check', (data) => broadcastToCos('cos:health:check', data));+ cosEvents.on('health:critical', (data) => broadcastToCos('cos:health:critical', data));++ // Evaluation events+ cosEvents.on('evaluation', (data) => broadcastToCos('cos:evaluation', data));+ cosEvents.on('task:ready', (data) => broadcastToCos('cos:task:ready', data));++ // Watcher events+ cosEvents.on('watcher:started', (data) => broadcastToCos('cos:watcher:started', data));+ cosEvents.on('watcher:stopped', (data) => broadcastToCos('cos:watcher:stopped', data));+}++// Set up error event forwarding+function setupErrorEventForwarding() {+ // Forward error events to error subscribers+ errorEvents.on('error', (error) => {+ broadcastToErrors('error:notified', {+ message: error.message,+ code: error.code,+ severity: error.severity,+ timestamp: error.timestamp,+ canAutoFix: error.canAutoFix,+ context: error.context+ });+ });+}diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.jsindex 78c6a0c6fe..2f3eba77f6 100644--- a/server/services/streamingDetect.js+++ b/server/services/streamingDetect.js@@ -6,6 +6,193 @@ import { promisify } from 'util';const execAsync = promisify(exec);+/**+ * Parse ecosystem.config.js/cjs to extract all processes with their ports+ * Uses regex parsing since we can't safely execute arbitrary JS+ */+export function parseEcosystemConfig(content) {+ const processes = [];++ // Extract top-level port constants (e.g., const CDP_PORT = 5549)+ const portConstants = {};+ const constMatches = content.matchAll(/(?:const|let|var)\s+(\w*PORT\w*)\s*=\s*(\d+)/g);+ for (const match of constMatches) {+ portConstants[match[1]] = parseInt(match[2]);+ }++ // Match each app block: { name: '...', ... }+ // This regex captures app objects including nested braces+ const appBlockRegex = /\{\s*name\s*:\s*['"]([^'"]+)['"]/g;+ let match;+ let lastIndex = 0;++ while ((match = appBlockRegex.exec(content)) !== null) {+ const processName = match[1];+ const startPos = match.index;++ // Find the end of this app block by counting braces+ let braceCount = 0;+ let endPos = startPos;+ let inString = false;+ let stringChar = null;+ let inLineComment = false;+ let inBlockComment = false;++ for (let i = startPos; i < content.length; i++) {+ const char = content[i];+ const nextChar = i < content.length - 1 ? content[i + 1] : '';+ const prevChar = i > 0 ? content[i - 1] : '';++ // Handle line comments (// ...)+ if (!inString && !inBlockComment && char === '/' && nextChar === '/') {+ inLineComment = true;+ continue;+ }+ if (inLineComment && char === '\n') {+ inLineComment = false;+ continue;+ }++ // Handle block comments (/* ... */)+ if (!inString && !inLineComment && char === '/' && nextChar === '*') {+ inBlockComment = true;+ continue;+ }+ if (inBlockComment && char === '*' && nextChar === '/') {+ inBlockComment = false;+ i++; // Skip the closing /+ continue;+ }++ // Skip if in any comment+ if (inLineComment || inBlockComment) continue;++ // Track string boundaries+ if ((char === '"' || char === "'") && prevChar !== '\\') {+ if (!inString) {+ inString = true;+ stringChar = char;+ } else if (char === stringChar) {+ inString = false;+ stringChar = null;+ }+ }++ if (!inString) {+ if (char === '{') braceCount++;+ if (char === '}') {+ braceCount--;+ if (braceCount === 0) {+ endPos = i;+ break;+ }+ }+ }+ }++ const appBlock = content.substring(startPos, endPos + 1);++ // Extract port from env.PORT or env_development.PORT+ let port = null;+ const portMatch = appBlock.match(/(?:env|env_development|env_production)\s*:\s*\{[^}]*\bPORT\s*:\s*(\d+)/);+ if (portMatch) {+ port = parseInt(portMatch[1]);+ }++ // Check for CDP_PORT (Chrome DevTools Protocol port for browser processes)+ if (!port) {+ // First try numeric value+ const cdpPortMatch = appBlock.match(/(?:env|env_development|env_production)\s*:\s*\{[^}]*CDP_PORT\s*:\s*(\d+)/);+ if (cdpPortMatch) {+ port = parseInt(cdpPortMatch[1]);+ } else {+ // Check for variable reference (CDP_PORT: CDP_PORT)+ const cdpVarMatch = appBlock.match(/CDP_PORT\s*:\s*(\w+)/);+ if (cdpVarMatch && portConstants[cdpVarMatch[1]]) {+ port = portConstants[cdpVarMatch[1]];+ }+ }+ }++ // Also check for --port in args+ if (!port) {+ const argsPortMatch = appBlock.match(/args\s*:\s*['"][^'"]*--port\s+(\d+)/);+ if (argsPortMatch) {+ port = parseInt(argsPortMatch[1]);+ }+ }++ // Check for port: XXXX directly (some configs use this)+ if (!port) {+ const directPortMatch = appBlock.match(/\bport\s*:\s*(\d+)/);+ if (directPortMatch) {+ port = parseInt(directPortMatch[1]);+ }+ }++ // Extract cwd for processes that might have external config files+ let cwd = null;+ const cwdMatch = appBlock.match(/cwd\s*:\s*['"]([^'"]+)['"]/);+ if (cwdMatch) {+ cwd = cwdMatch[1];+ }++ // Check if this process uses vite (need to check vite.config in cwd)+ const usesVite = /\bvite\b/i.test(appBlock);++ processes.push({ name: processName, port, cwd, usesVite });+ lastIndex = endPos;+ }++ return processes;+}++/**+ * Extract port from vite.config.js/ts content+ */+function extractVitePort(content) {+ const portMatch = content.match(/port\s*:\s*(\d+)/);+ return portMatch ? parseInt(portMatch[1]) : null;+}++/**+ * Parse ecosystem config from a directory path (non-streaming, for refresh)+ * Also checks vite.config files in subdirectories for processes that use Vite+ */+export async function parseEcosystemFromPath(dirPath) {+ for (const ecosystemFile of ['ecosystem.config.js', 'ecosystem.config.cjs']) {+ const ecosystemPath = join(dirPath, ecosystemFile);+ if (existsSync(ecosystemPath)) {+ const content = await readFile(ecosystemPath, 'utf-8');+ const processes = parseEcosystemConfig(content);++ // For processes that use vite and don't have a port, check their cwd for vite.config+ for (const proc of processes) {+ if (proc.usesVite && !proc.port && proc.cwd) {+ const cwdPath = join(dirPath, proc.cwd);+ for (const viteConfig of ['vite.config.ts', 'vite.config.js']) {+ const viteConfigPath = join(cwdPath, viteConfig);+ if (existsSync(viteConfigPath)) {+ const viteContent = await readFile(viteConfigPath, 'utf-8').catch(() => '');+ const port = extractVitePort(viteContent);+ if (port) {+ proc.port = port;+ break;+ }+ }+ }+ }+ // Clean up internal properties before returning+ delete proc.cwd;+ delete proc.usesVite;+ }++ return processes;+ }+ }+ return [];+}+/*** Stream detection results to a socket as each step completes*/@@ -22,6 +209,7 @@ export async function streamDetection(socket, dirPath) {startCommands: [],pm2ProcessNames: [],pm2Status: null,+ processes: [],type: 'unknown'};@@ -117,25 +305,46 @@ export async function streamDetection(socket, dirPath) {if (existsSync(ecosystemPath)) {const content = await readFile(ecosystemPath, 'utf-8').catch(() => '');if (content) {- // Extract PORT from env_development or env_production- const portMatch = content.match(/PORT\s*:\s*(\d+)/);- if (portMatch && !result.apiPort) {- result.apiPort = parseInt(portMatch[1]);+ // Parse all processes with their ports using the dedicated parser+ const parsedProcesses = parseEcosystemConfig(content);+ if (parsedProcesses.length > 0) {+ // For processes that use vite and don't have a port, check their cwd for vite.config+ for (const proc of parsedProcesses) {+ if (proc.usesVite && !proc.port && proc.cwd) {+ const cwdPath = join(dirPath, proc.cwd);+ for (const viteConfig of ['vite.config.ts', 'vite.config.js']) {+ const viteConfigPath = join(cwdPath, viteConfig);+ if (existsSync(viteConfigPath)) {+ const viteContent = await readFile(viteConfigPath, 'utf-8').catch(() => '');+ const port = extractVitePort(viteContent);+ if (port) {+ proc.port = port;+ break;+ }+ }+ }+ }+ // Clean up internal properties+ delete proc.cwd;+ delete proc.usesVite;+ }++ result.processes = parsedProcesses;+ result.pm2ProcessNames = parsedProcesses.map(p => p.name);++ // Set apiPort from first process with a port (usually the main server)+ const processWithPort = parsedProcesses.find(p => p.port);+ if (processWithPort && !result.apiPort) {+ result.apiPort = processWithPort.port;+ }}- // Extract UI port from CLIENT_URL+ // Extract UI port from CLIENT_URL (still needed as it's not in process configs)const clientUrlMatch = content.match(/CLIENT_URL\s*:\s*['"]https?:\/\/[^:]+:(\d+)/);if (clientUrlMatch && !result.uiPort) {result.uiPort = parseInt(clientUrlMatch[1]);}- // Extract PM2 process names- const nameMatches = content.matchAll(/name\s*:\s*['"]([^'"]+)['"]/g);- const ecosystemNames = [...nameMatches].map(m => m[1]);- if (ecosystemNames.length > 0) {- result.pm2ProcessNames = ecosystemNames;- }-configFiles.push(ecosystemFile);}}@@ -146,6 +355,7 @@ export async function streamDetection(socket, dirPath) {uiPort: result.uiPort,apiPort: result.apiPort,pm2ProcessNames: result.pm2ProcessNames.length > 0 ? result.pm2ProcessNames : undefined,+ processes: result.processes.length > 0 ? result.processes : undefined,configFiles});diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsnew file mode 100644index 0000000000..d5a6e625ce--- /dev/null+++ b/server/services/subAgentSpawner.js@@ -0,0 +1,547 @@+/**+ * Sub-Agent Spawner Service+ *+ * Spawns Claude CLI instances to work on tasks with unrestricted mode+ * and MCP server integration. Includes intelligent model selection+ * and usage tracking.+ */++import { spawn } from 'child_process';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { writeFile, mkdir, readFile } from 'fs/promises';+import { existsSync } from 'fs';+import { v4 as uuidv4 } from 'uuid';+import { cosEvents, registerAgent, updateAgent, completeAgent, appendAgentOutput, getConfig, updateTask } from './cos.js';++/**+ * Emit a log event for UI display (mirrors cos.js helper)+ */+function emitLog(level, message, data = {}) {+ const logEntry = {+ timestamp: new Date().toISOString(),+ level,+ message,+ ...data+ };+ console.log(`${level === 'error' ? '❌' : level === 'warn' ? '⚠️' : level === 'success' ? '✅' : 'ℹ️'} ${message}`);+ cosEvents.emit('log', logEntry);+}+import { getActiveProvider, getProviderById } from './providers.js';+import { buildPrompt } from './promptService.js';+import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';+import { getMemorySection } from './memoryRetriever.js';+import { extractAndStoreMemories } from './memoryExtractor.js';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const ROOT_DIR = join(__dirname, '../../');+const AGENTS_DIR = join(__dirname, '../../data/cos/agents');+const RUNS_DIR = join(__dirname, '../../data/runs');++/**+ * Select optimal model for a task based on complexity analysis+ * User can override by specifying Model: and/or Provider: in task metadata+ */+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) {+ console.log(`👤 User specified model: ${userModel}`);+ return {+ model: userModel,+ tier: 'user-specified',+ reason: 'user-preference',+ userProvider: userProvider || null+ };+ }++ // Image/visual analysis → would route to gemini if available+ if (/image|screenshot|visual|photo|picture/.test(desc)) {+ return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'visual-analysis' };+ }++ // Critical priority → always use opus/heavy+ if (priority === 'CRITICAL') {+ return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'critical-priority' };+ }++ // Complex reasoning tasks → opus/heavy+ 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 → needs more capable model+ if (contextLen > 500) {+ return { model: provider.heavyModel || provider.mediumModel || provider.defaultModel, tier: 'heavy', reason: 'long-context' };+ }++ // Simple/quick tasks → haiku/light+ if (/fix typo|update text|simple|rename|comment|documentation|readme|format/.test(desc) || contextLen < 100) {+ return { model: provider.lightModel || provider.defaultModel, tier: 'light', reason: 'simple-task' };+ }++ // Standard tasks → sonnet/medium (default)+ return { model: provider.mediumModel || provider.defaultModel, tier: 'medium', reason: 'standard-task' };+}++/**+ * Create a run entry for usage tracking+ */+async function createAgentRun(agentId, task, model, provider, workspacePath) {+ const runId = uuidv4();+ const runDir = join(RUNS_DIR, runId);++ if (!existsSync(RUNS_DIR)) {+ await mkdir(RUNS_DIR, { recursive: true });+ }+ await mkdir(runDir);++ const metadata = {+ id: runId,+ type: 'ai',+ source: 'cos-agent',+ agentId,+ taskId: task.id,+ providerId: provider.id,+ providerName: provider.name,+ model: model || provider.defaultModel,+ workspacePath,+ workspaceName: task.metadata?.app || 'portos',+ prompt: (task.description || '').substring(0, 500),+ startTime: new Date().toISOString(),+ endTime: null,+ duration: null,+ exitCode: null,+ success: null,+ error: null,+ outputSize: 0+ };++ await writeFile(join(runDir, 'metadata.json'), JSON.stringify(metadata, null, 2));+ await writeFile(join(runDir, 'prompt.txt'), task.description || '');+ await writeFile(join(runDir, 'output.txt'), '');++ return { runId, runDir };+}++/**+ * Complete a run entry with final results+ */+async function completeAgentRun(runId, output, exitCode, duration, error = null) {+ const runDir = join(RUNS_DIR, runId);+ const metaPath = join(runDir, 'metadata.json');++ if (!existsSync(metaPath)) return;++ const metadata = JSON.parse(await readFile(metaPath, 'utf-8'));+ metadata.endTime = new Date().toISOString();+ metadata.duration = duration;+ metadata.exitCode = exitCode;+ metadata.success = exitCode === 0;+ metadata.error = error;+ metadata.outputSize = Buffer.byteLength(output || '');++ await writeFile(metaPath, JSON.stringify(metadata, null, 2));+ await writeFile(join(runDir, 'output.txt'), output || '');+}++// Active agent processes+const activeAgents = new Map();++/**+ * Initialize the spawner - listen for task:ready events+ */+export function initSpawner() {+ cosEvents.on('task:ready', async (task) => {+ await spawnAgentForTask(task);+ });++ cosEvents.on('agent:terminate', async (agentId) => {+ await terminateAgent(agentId);+ });++ console.log('🤖 Sub-agent spawner initialized');+}++/**+ * Spawn an agent for a task+ */+export async function spawnAgentForTask(task) {+ const agentId = `agent-${uuidv4().slice(0, 8)}`;++ // Get configuration+ const config = await getConfig();+ const provider = await getActiveProvider();++ if (!provider) {+ cosEvents.emit('agent:error', { taskId: task.id, error: 'No active AI provider configured' });+ return null;+ }++ // Select optimal model for this task+ const modelSelection = selectModelForTask(task, provider);+ const selectedModel = modelSelection.model;++ emitLog('info', `Model selection: ${selectedModel} (${modelSelection.reason})`, {+ taskId: task.id,+ model: selectedModel,+ tier: modelSelection.tier,+ reason: modelSelection.reason+ });++ // Determine workspace path+ const workspacePath = task.metadata?.app+ ? await getAppWorkspace(task.metadata.app)+ : ROOT_DIR;++ // Build the agent prompt+ const prompt = await buildAgentPrompt(task, config);++ // Create agent directory+ const agentDir = join(AGENTS_DIR, agentId);+ if (!existsSync(agentDir)) {+ await mkdir(agentDir, { recursive: true });+ }++ // Save prompt to file+ await writeFile(join(agentDir, 'prompt.txt'), prompt);++ // Create run entry for usage tracking+ const { runId } = await createAgentRun(agentId, task, selectedModel, provider, workspacePath);++ // Build spawn arguments with model selection+ const spawnArgs = buildSpawnArgs(config, selectedModel);++ // Register the agent with model info+ await registerAgent(agentId, task.id, {+ workspacePath,+ taskDescription: task.description,+ taskType: task.taskType,+ priority: task.priority,+ model: selectedModel,+ modelTier: modelSelection.tier,+ modelReason: modelSelection.reason,+ runId,+ phase: 'initializing'+ });++ emitLog('info', `Agent ${agentId} initializing...`, { agentId, taskId: task.id });++ // Mark the task as in_progress to prevent re-spawning+ await updateTask(task.id, { status: 'in_progress' }, task.taskType || 'user');++ // Spawn the Claude CLI process using full path for PM2 compatibility+ const claudePath = process.env.CLAUDE_PATH || '/Users/antic/.nvm/versions/node/v25.2.1/bin/claude';++ // Build full command string for display+ const fullCommand = `${claudePath} ${spawnArgs.join(' ')} <<< "${(task.description || '').substring(0, 100)}..."`;++ emitLog('success', `Spawning agent for task ${task.id}`, { agentId, model: selectedModel });++ const claudeProcess = spawn(claudePath, spawnArgs, {+ cwd: workspacePath,+ shell: false,+ stdio: ['pipe', 'pipe', 'pipe'], // stdin, stdout, stderr+ env: {+ ...process.env,+ // Pass through any provider-specific env vars+ ...provider.envVars+ }+ });++ // Register the spawned agent with its full command for process listing+ registerSpawnedAgent(claudeProcess.pid, {+ fullCommand,+ agentId,+ taskId: task.id,+ model: selectedModel,+ workspacePath,+ prompt: (task.description || '').substring(0, 500)+ });++ // Send prompt via stdin and close it+ claudeProcess.stdin.write(prompt);+ claudeProcess.stdin.end();++ // Store process reference+ activeAgents.set(agentId, {+ process: claudeProcess,+ taskId: task.id,+ startedAt: Date.now(),+ runId,+ pid: claudeProcess.pid+ });++ // Set up output handling+ let outputBuffer = '';+ let hasStartedWorking = false;+ const outputFile = join(agentDir, 'output.txt');++ claudeProcess.stdout.on('data', async (data) => {+ const text = data.toString();+ outputBuffer += text;++ // Update phase to 'working' on first output+ if (!hasStartedWorking) {+ hasStartedWorking = true;+ await updateAgent(agentId, { phase: 'working' });+ emitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });+ }++ // Append to file+ await writeFile(outputFile, outputBuffer).catch(() => {});++ // Emit output event+ await appendAgentOutput(agentId, text);+ });++ claudeProcess.stderr.on('data', async (data) => {+ const text = data.toString();+ outputBuffer += `[stderr] ${text}`;++ // Append to file+ await writeFile(outputFile, outputBuffer).catch(() => {});++ await appendAgentOutput(agentId, `[stderr] ${text}`);+ });++ claudeProcess.on('error', async (err) => {+ console.error(`❌ Agent ${agentId} spawn error: ${err.message}`);+ cosEvents.emit('agent:error', { agentId, error: err.message });+ await completeAgent(agentId, { success: false, error: err.message });+ // Complete the run tracking with error+ await completeAgentRun(runId, outputBuffer, 1, 0, err.message);+ unregisterSpawnedAgent(claudeProcess.pid);+ activeAgents.delete(agentId);+ });++ claudeProcess.on('close', async (code) => {+ const success = code === 0;+ const agentData = activeAgents.get(agentId);+ const duration = Date.now() - (agentData?.startedAt || Date.now());++ // Save final output+ await writeFile(outputFile, outputBuffer).catch(() => {});++ await completeAgent(agentId, {+ success,+ exitCode: code,+ duration,+ outputLength: outputBuffer.length+ });++ // Complete the run tracking+ await completeAgentRun(agentData?.runId || runId, outputBuffer, code, duration);++ // Update task status based on result+ const newStatus = success ? 'completed' : 'pending'; // Reset to pending on failure for retry+ await updateTask(task.id, { status: newStatus }, task.taskType || 'user');++ // Extract and store memories from successful agent output+ if (success && outputBuffer.length > 100) {+ extractAndStoreMemories(agentId, task.id, outputBuffer, task).catch(err => {+ console.log(`⚠️ Memory extraction failed: ${err.message}`);+ });+ }++ unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);+ activeAgents.delete(agentId);+ });++ return agentId;+}++/**+ * Build spawn arguments for Claude CLI+ */+function buildSpawnArgs(config, model) {+ // Note: MCP server config via --mcp-config requires a file path, not inline JSON+ // For now, we skip MCP config and rely on the user's default settings+ // Prompt will be passed via stdin to avoid shell escaping issues+ const args = [+ '--dangerously-skip-permissions', // Unrestricted mode+ '--print', // Print output and exit+ ];++ // Add model selection if specified+ if (model) {+ args.push('--model', model);+ }++ return args;+}++/**+ * Build the prompt for an agent+ */+async function buildAgentPrompt(task, config) {+ // Get relevant memories for context injection+ const memorySection = await getMemorySection(task, {+ maxTokens: config.memory?.maxContextTokens || 2000+ }).catch(err => {+ console.log(`⚠️ Memory retrieval failed: ${err.message}`);+ return null;+ });++ // Try to use the prompt template system+ const promptData = await buildPrompt('cos-agent-briefing', {+ task,+ config,+ memorySection,+ timestamp: new Date().toISOString()+ }).catch(() => null);++ if (promptData?.prompt) {+ return promptData.prompt;+ }++ // Fallback to built-in template+ return `# Chief of Staff Agent Briefing++${memorySection || ''}++## Task Assignment+You are an autonomous agent working on behalf of the Chief of Staff.++### Task Details+- **ID**: ${task.id}+- **Priority**: ${task.priority}+- **Description**: ${task.description}+${task.metadata?.context ? `- **Context**: ${task.metadata.context}` : ''}+${task.metadata?.app ? `- **Target App**: ${task.metadata.app}` : ''}++## Instructions+1. Analyze the task requirements carefully+2. Make necessary changes to complete the task+3. Test your changes when possible+4. Provide a summary of what was done++## Guidelines+- Focus only on the assigned task+- Make minimal, targeted changes+- Follow existing code patterns and conventions+- Do not make unrelated changes+- If blocked, explain clearly why++## Working Directory+You are working in the project directory. Use the available tools to explore, modify, and test code.++Begin working on the task now.`;+}++/**+ * Get workspace path for an app+ */+async function getAppWorkspace(appName) {+ const appsFile = join(ROOT_DIR, 'data/apps.json');++ if (!existsSync(appsFile)) {+ return ROOT_DIR;+ }++ const content = await readFile(appsFile, 'utf-8');+ const data = JSON.parse(content);++ // Handle both object format { apps: { id: {...} } } and array format [...]+ const apps = data.apps || data;++ if (Array.isArray(apps)) {+ const app = apps.find(a => a.name === appName || a.id === appName);+ return app?.repoPath || ROOT_DIR;+ }++ // Object format - keys are app IDs+ const app = apps[appName] || Object.values(apps).find(a => a.name === appName);+ return app?.repoPath || ROOT_DIR;+}++/**+ * Terminate an agent+ */+export async function terminateAgent(agentId) {+ const agent = activeAgents.get(agentId);++ if (!agent) {+ return { success: false, error: 'Agent not found or not running' };+ }++ agent.process.kill('SIGTERM');++ // Give it a moment, then force kill if needed+ setTimeout(() => {+ if (activeAgents.has(agentId)) {+ agent.process.kill('SIGKILL');+ unregisterSpawnedAgent(agent.pid);+ activeAgents.delete(agentId);+ }+ }, 5000);++ return { success: true, agentId };+}++/**+ * Get list of active agents+ */+export function getActiveAgents() {+ const agents = [];+ for (const [agentId, agent] of activeAgents) {+ agents.push({+ id: agentId,+ taskId: agent.taskId,+ startedAt: agent.startedAt,+ runningTime: Date.now() - agent.startedAt+ });+ }+ return agents;+}++/**+ * Kill all active agents+ */+export async function killAllAgents() {+ const agentIds = Array.from(activeAgents.keys());++ for (const agentId of agentIds) {+ await terminateAgent(agentId);+ }++ return { killed: agentIds.length };+}++/**+ * Clean up orphaned agents on startup+ * Agents marked as "running" in state but not in activeAgents map are orphaned+ */+export async function cleanupOrphanedAgents() {+ const { getAgents, completeAgent: markComplete } = await import('./cos.js');+ const agents = await getAgents();+ let cleanedCount = 0;++ for (const agent of agents) {+ if (agent.status === 'running' && !activeAgents.has(agent.id)) {+ console.log(`🧹 Cleaning up orphaned agent ${agent.id}`);+ await markComplete(agent.id, {+ success: false,+ error: 'Agent process was orphaned (server restart)',+ orphaned: true+ });+ cleanedCount++;+ }+ }++ return cleanedCount;+}++// Initialize spawner when module loads+initSpawner();++// Clean up orphaned agents after a short delay (let other services init first)+setTimeout(cleanupOrphanedAgents, 2000);diff --git a/server/services/taskWatcher.js b/server/services/taskWatcher.jsnew file mode 100644index 0000000000..9bc369713d--- /dev/null+++ b/server/services/taskWatcher.js@@ -0,0 +1,230 @@+/**+ * Task Watcher Service+ *+ * Watches TASKS.md and COS-TASKS.md for changes and emits events+ * when tasks are added, modified, or completed.+ */++import { watch } from 'chokidar';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { cosEvents, getUserTasks, getCosTasks, getConfig } from './cos.js';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const ROOT_DIR = join(__dirname, '../../');++let watcher = null;+let isWatching = false;+let lastUserTasks = null;+let lastCosTasks = null;++/**+ * Start watching task files+ */+export async function startWatching() {+ if (isWatching) {+ return { success: false, error: 'Already watching' };+ }++ const config = await getConfig();+ const userTasksPath = join(ROOT_DIR, config.userTasksFile);+ const cosTasksPath = join(ROOT_DIR, config.cosTasksFile);++ // Load initial state+ lastUserTasks = await getUserTasks();+ lastCosTasks = await getCosTasks();++ watcher = watch([userTasksPath, cosTasksPath], {+ persistent: true,+ ignoreInitial: true,+ awaitWriteFinish: {+ stabilityThreshold: 300,+ pollInterval: 100+ }+ });++ watcher.on('change', async (path) => {+ if (path.endsWith(config.userTasksFile)) {+ await handleUserTasksChange();+ } else if (path.endsWith(config.cosTasksFile)) {+ await handleCosTasksChange();+ }+ });++ watcher.on('add', async (path) => {+ if (path.endsWith(config.userTasksFile)) {+ lastUserTasks = await getUserTasks();+ cosEvents.emit('tasks:user:created', lastUserTasks);+ } else if (path.endsWith(config.cosTasksFile)) {+ lastCosTasks = await getCosTasks();+ cosEvents.emit('tasks:cos:created', lastCosTasks);+ }+ });++ watcher.on('unlink', async (path) => {+ if (path.endsWith(config.userTasksFile)) {+ cosEvents.emit('tasks:user:deleted', { file: path });+ lastUserTasks = null;+ } else if (path.endsWith(config.cosTasksFile)) {+ cosEvents.emit('tasks:cos:deleted', { file: path });+ lastCosTasks = null;+ }+ });++ watcher.on('error', (error) => {+ cosEvents.emit('watcher:error', { error: error.message });+ });++ isWatching = true;+ cosEvents.emit('watcher:started', {+ files: [userTasksPath, cosTasksPath]+ });++ return { success: true };+}++/**+ * Stop watching task files+ */+export async function stopWatching() {+ if (!isWatching || !watcher) {+ return { success: false, error: 'Not watching' };+ }++ await watcher.close();+ watcher = null;+ isWatching = false;++ cosEvents.emit('watcher:stopped');+ return { success: true };+}++/**+ * Handle changes to user tasks file+ */+async function handleUserTasksChange() {+ const current = await getUserTasks();++ if (!lastUserTasks) {+ lastUserTasks = current;+ cosEvents.emit('tasks:user:changed', current);+ return;+ }++ const changes = diffTasks(lastUserTasks.tasks, current.tasks);++ if (changes.added.length > 0) {+ cosEvents.emit('tasks:user:added', { tasks: changes.added });+ }++ if (changes.completed.length > 0) {+ cosEvents.emit('tasks:user:completed', { tasks: changes.completed });+ }++ if (changes.modified.length > 0) {+ cosEvents.emit('tasks:user:modified', { tasks: changes.modified });+ }++ if (changes.removed.length > 0) {+ cosEvents.emit('tasks:user:removed', { tasks: changes.removed });+ }++ lastUserTasks = current;+ cosEvents.emit('tasks:user:changed', current);+}++/**+ * Handle changes to CoS internal tasks file+ */+async function handleCosTasksChange() {+ const current = await getCosTasks();++ if (!lastCosTasks) {+ lastCosTasks = current;+ cosEvents.emit('tasks:cos:changed', current);+ return;+ }++ const changes = diffTasks(lastCosTasks.tasks, current.tasks);++ if (changes.added.length > 0) {+ cosEvents.emit('tasks:cos:added', { tasks: changes.added });+ }++ if (changes.completed.length > 0) {+ cosEvents.emit('tasks:cos:completed', { tasks: changes.completed });+ }++ if (changes.modified.length > 0) {+ cosEvents.emit('tasks:cos:modified', { tasks: changes.modified });+ }++ if (changes.removed.length > 0) {+ cosEvents.emit('tasks:cos:removed', { tasks: changes.removed });+ }++ lastCosTasks = current;+ cosEvents.emit('tasks:cos:changed', current);+}++/**+ * Diff two task arrays to find changes+ */+function diffTasks(oldTasks, newTasks) {+ const oldMap = new Map(oldTasks.map(t => [t.id, t]));+ const newMap = new Map(newTasks.map(t => [t.id, t]));++ const added = [];+ const completed = [];+ const modified = [];+ const removed = [];++ // Find added and modified tasks+ for (const [id, task] of newMap) {+ const oldTask = oldMap.get(id);++ if (!oldTask) {+ added.push(task);+ } else if (oldTask.status !== 'completed' && task.status === 'completed') {+ completed.push(task);+ } else if (JSON.stringify(oldTask) !== JSON.stringify(task)) {+ modified.push({ old: oldTask, new: task });+ }+ }++ // Find removed tasks+ for (const [id, task] of oldMap) {+ if (!newMap.has(id)) {+ removed.push(task);+ }+ }++ return { added, completed, modified, removed };+}++/**+ * Get watcher status+ */+export function getWatcherStatus() {+ return {+ watching: isWatching,+ lastUserTasks: lastUserTasks?.tasks?.length ?? 0,+ lastCosTasks: lastCosTasks?.tasks?.length ?? 0+ };+}++/**+ * Force refresh of cached tasks+ */+export async function refreshTasks() {+ lastUserTasks = await getUserTasks();+ lastCosTasks = await getCosTasks();++ cosEvents.emit('tasks:refreshed', {+ user: lastUserTasks,+ cos: lastCosTasks+ });++ return { user: lastUserTasks, cos: lastCosTasks };+}