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(cos): M35 Chief of Staff Enhancement
Adam Eivy693dad218439
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.mdindex ccfbfa4a85..1a593dda3d 100644--- a/.changelog/v0.10.x.md+++ b/.changelog/v0.10.x.md@@ -197,6 +197,13 @@ This release introduces a structured changelog documentation system for creating- **Reduced Code Duplication**: Refactored 4 services (`apps.js`, `history.js`, `usage.js`, `notifications.js`) to use shared utility, eliminating identical `ensureDir` implementations and reducing boilerplate- **Pattern for Future Refactoring**: Establishes pattern for remaining 7+ services with similar duplicated directory logic+### Chief of Staff - Navigation Improvements+- **Sidebar Sub-Navigation**: Chief of Staff sub-pages (Tasks, Agents, Scripts, Schedule, Digest, Learning, Memory, Health, Config) now appear as children in the sidebar navigation under Chief of Staff, making all tabs accessible without scrolling the page+- **Collapsible Agent Panel**: On mobile, the COS Agent avatar panel is now collapsible with a tap toggle header showing state and running status+- **Touch-Friendly Tabs**: Tab navigation buttons have 40px minimum height for better mobile accessibility+- **Scrollable Tab Bar**: Tab bar uses horizontal scroll with `shrink-0` to prevent tab overflow issues+- **Badge Support on Collapsible Sections**: Notification badges now display correctly on collapsible nav sections (both collapsed and expanded states)+## 🐛 Bug Fixes### Task Enhancer Directory Not Found Errordiff --git a/.changelog/v0.9.x.md b/.changelog/v0.9.x.mdindex 365543fbe4..fe5764e564 100644--- a/.changelog/v0.9.x.md+++ b/.changelog/v0.9.x.md@@ -68,6 +68,52 @@- Fully accessible with ARIA labels and hover tooltips- Displays total sessions tracked for context+### Chief of Staff Enhancement (M35)+- **BM25 Hybrid Memory Search**: Added BM25 text search algorithm for hybrid memory retrieval+ - `server/lib/bm25.js` - BM25 with IDF weighting, inverted index, stemming+ - `server/services/memoryBM25.js` - Index management, persistence to `data/cos/memory/bm25-index.json`+ - Hybrid search combines BM25 + vector with reciprocal rank fusion for better context retrieval++- **Event-Driven Scheduling**: Replaced interval-based loops with cron-compatible event scheduler+ - `server/services/eventScheduler.js` - Timeout-safe timers (clamps to 2^31-1 ms), cron expressions+ - Converted `cos.js` from setInterval to scheduleEvent() calls+ - Supports interval, cron, and one-shot event types++- **Execution Lanes**: Lane-based concurrency control for agent spawning+ - `server/services/executionLanes.js` - Critical (1 slot), Standard (2 slots), Background (3 slots)+ - Lane acquisition with waitForLane() timeout and queue management+ - Integrated into subAgentSpawner.js for controlled parallel execution++- **Tool State Machine**: Comprehensive lifecycle tracking for tool executions+ - `server/services/toolStateMachine.js` - IDLE → START → RUNNING → UPDATE → END → ERROR states+ - Tracks timing, state history, and metadata per execution+ - Enables better error recovery and execution analytics++- **Thinking Levels**: Dynamic model selection based on task complexity+ - `server/services/thinkingLevels.js` - off, minimal, low, medium, high, xhigh levels+ - Hierarchy resolution: task → agent → provider for thinking level+ - Integrated into selectModelForTask() for automatic model upgrades++- **Error Recovery Strategies**: Structured error analysis and recovery+ - `server/services/errorRecovery.js` - retry, escalate, fallback, decompose, defer, investigate strategies+ - Analyzes error types (network, rate-limit, auth, validation, etc.)+ - Returns actionable recovery recommendations++- **Agent Run Cache**: TTL-based caching for agent outputs+ - `server/services/agentRunCache.js` - 10-minute default TTL, key-based storage+ - Memory-efficient with periodic cleanup+ - Prevents redundant re-execution of recent tasks++- **Missions Service**: Long-term goal tracking for proactive task generation+ - `server/services/missions.js` - Mission CRUD, sub-tasks, progress tracking+ - Generates proactive tasks when user queue is empty+ - App-owned missions for autonomous improvement of managed apps++- **Comprehensive Test Suite**: 18 new test files with 722 total tests+ - Unit tests for all new services+ - Integration tests for state machine and lane management+ - Missions service test coverage for CRUD and task generation+## 🔧 Improvements### Chief of Staff Task Managementdiff --git a/PLAN.md b/PLAN.mdindex da0c984bc6..08c4e1b391 100644--- a/PLAN.md+++ b/PLAN.md@@ -56,6 +56,7 @@ pm2 logs- [x] M31: LLM Memory Classification - Intelligent memory extraction with quality filtering- [x] M32: Brain System - Second-brain capture and classification. See [Brain System](./docs/features/brain-system.md)- [x] M33: Soul System - Digital twin identity scaffold management+- [x] M35: Chief of Staff Enhancement - Proactive autonomous agent with hybrid memory, missions, LM Studio, thinking levels### Documentation- [Architecture Overview](./docs/ARCHITECTURE.md) - System design, data flow@@ -923,3 +924,136 @@ confidenceSchema = z.object({- `FeedbackRater.jsx` - "Sounds like me" rating interface- `GapRecommendations.jsx` - Prioritized enrichment suggestions- `TraitEditor.jsx` - Manual trait override interface++---++## M35: Chief of Staff Enhancement++Comprehensive upgrade to COS from reactive task executor to proactive autonomous agent.++### Implementation Status++| Phase | Component | Status | Files Created |+|-------|-----------|--------|---------------|+| **Phase 1: Memory** | BM25 Algorithm | ✅ Complete | `server/lib/bm25.js` |+| | BM25 Index Manager | ✅ Complete | `server/services/memoryBM25.js` |+| | Session Delta Tracker | ✅ Complete | `server/services/sessionDelta.js` |+| | Hybrid Search (BM25+Vector) | ✅ Complete | Modified `memory.js`, `memoryRetriever.js` |+| **Phase 5: Architecture** | Tool State Machine | ✅ Complete | `server/services/toolStateMachine.js` |+| | Agent Gateway | ✅ Complete | `server/services/agentGateway.js` |+| | Error Recovery | ✅ Complete | `server/services/errorRecovery.js` |+| | Agent Run Cache | ✅ Complete | `server/services/agentRunCache.js` |+| | Spawner Integration | ✅ Complete | Modified `subAgentSpawner.js` |+| **Phase 2: Execution** | Event Scheduler | ✅ Complete | `server/services/eventScheduler.js` |+| | Execution Lanes | ✅ Complete | `server/services/executionLanes.js` |+| | Missions Service | ✅ Complete | `server/services/missions.js` |+| | Mission Data Files | ✅ Complete | `data/cos/missions/*.json` |+| | COS Event-Driven Updates | ✅ Complete | Modified `cos.js` |+| | Mission Task Generation | ✅ Complete | Modified `cos.js` |+| **Phase 3: LM Studio** | LM Studio Manager | ✅ Complete | `server/services/lmStudioManager.js` |+| | Local Thinking | ✅ Complete | `server/services/localThinking.js` |+| | LM Studio Routes | ✅ Complete | `server/routes/lmstudio.js` |+| **Phase 4: Thinking** | Thinking Levels | ✅ Complete | `server/services/thinkingLevels.js` |+| | Context Upgrader | ✅ Complete | `server/services/contextUpgrader.js` |+| | COS Evolution | ✅ Complete | `server/services/cosEvolution.js` |+| | Spawner Thinking Levels | ✅ Complete | Modified `subAgentSpawner.js` |++### Features Added++**Phase 1: Hybrid Memory Search**+- BM25 algorithm with IDF weighting and inverted index+- Reciprocal Rank Fusion (RRF) combining BM25 + vector search+- 40% BM25 / 60% vector weighting for optimal retrieval+- Session delta tracking for pending bytes/messages++**Phase 5: Agent Architecture**+- Tool execution state machine (IDLE → START → RUNNING → UPDATE → END → ERROR)+- Agent gateway with request deduplication and 10-minute cache+- Error recovery with 6 strategies: retry, escalate, fallback, decompose, defer, investigate+- Agent run cache for outputs, tool results, and contexts++**Phase 2: Proactive Execution**+- Event scheduler with cron expressions and timeout-safe timers (clamps to 2^31-1)+- Execution lanes: critical (1), standard (2), background (3) concurrent slots+- Mission system for long-term goals with sub-tasks+- Initial missions: external project and solana-accounts improvements++**Phase 3: Local Model Integration**+- LM Studio availability checking and model discovery+- Quick completions for local thinking without cloud costs+- Memory classification using local models+- Embeddings via local LM Studio++**Phase 4: Dynamic Model Selection**+- Thinking levels: off, minimal, low, medium, high, xhigh+- Level resolution hierarchy: task → hooks → agent → provider+- Context upgrader with complexity analysis+- COS self-evolution with automatic model changes++### New API Endpoints++| Route | Description |+|-------|-------------|+| GET /api/lmstudio/status | Check LM Studio availability |+| GET /api/lmstudio/models | List loaded models |+| POST /api/lmstudio/completion | Local model completion |+| POST /api/lmstudio/analyze-task | Analyze task complexity |+| POST /api/lmstudio/classify-memory | Classify memory content |++### Design Decisions++1. **Mission Autonomy**: Full autonomy - COS can implement changes, run tests, commit without approval for managed apps+2. **Model Usage**: Local-first with LM Studio, no cloud API costs for thinking+3. **Self-Modification**: Full autonomy - COS can change its own base thinking model without user approval++### Test Suite++All COS Enhancement modules have comprehensive unit tests:++| Test File | Module | Tests |+|-----------|--------|-------|+| `server/lib/bm25.test.js` | BM25 Algorithm | Tokenization, IDF, indexing, search, serialization |+| `server/services/toolStateMachine.test.js` | Tool State Machine | State transitions, execution lifecycle, error recovery |+| `server/services/thinkingLevels.test.js` | Thinking Levels | Level resolution, model selection, upgrade/downgrade |+| `server/services/executionLanes.test.js` | Execution Lanes | Lane acquisition, release, capacity, promotion |+| `server/services/errorRecovery.test.js` | Error Recovery | Error analysis, strategy selection, execution |+| `server/services/agentRunCache.test.js` | Agent Run Cache | Caching, TTL, invalidation, statistics |+| `server/services/missions.test.js` | Missions Service | CRUD, sub-tasks, proactive generation, archiving |++Run all tests:+```bash+cd server && npm test+# 24 test files, 722 tests+```++### Integration Complete++All M35 phases have been integrated into the main codebase:++1. ✅ Tool state machine integrated into `subAgentSpawner.js`+ - Creates execution tracking per agent spawn+ - Releases lanes on completion/error+ - Completes executions with success/failure status++2. ✅ Event scheduler integrated into `cos.js`+ - Replaced setInterval with `scheduleEvent()` for evaluation loop+ - Replaced setInterval with `scheduleEvent()` for health check loop+ - Events use timeout-safe timers (clamps to 2^31-1)++3. ✅ Thinking levels integrated into `subAgentSpawner.js`+ - `resolveThinkingLevel()` checks task → agent → provider hierarchy+ - `getModelForLevel()` maps thinking levels to actual models+ - `isLocalPreferred()` identifies local-first execution opportunities++4. ✅ Execution lanes integrated into `subAgentSpawner.js`+ - `determineLane()` assigns lane based on task priority+ - `acquire()` and `waitForLane()` manage lane slots+ - `release()` frees lane on agent completion++5. ✅ Missions connected to proactive task generation+ - `generateMissionTasks()` generates tasks from active missions+ - Mission tasks inserted after user/system tasks, before idle review+ - Tasks respect `autonomyLevel` for approval requirements+3. Update `subAgentSpawner.js` to use thinking levels and context upgrader+4. Add lane acquisition before agent spawning+5. Connect missions to proactive task generationdiff --git a/server/lib/bm25.js b/server/lib/bm25.jsnew file mode 100644index 0000000000..283e470751--- /dev/null+++ b/server/lib/bm25.js@@ -0,0 +1,354 @@+/**+ * BM25 (Best Matching 25) Algorithm Implementation+ *+ * A ranking function used for text retrieval that considers:+ * - Term frequency (TF): How often a term appears in a document+ * - Inverse document frequency (IDF): How rare/important a term is across all documents+ * - Document length normalization: Penalizes longer documents fairly+ *+ * @see https://en.wikipedia.org/wiki/Okapi_BM25+ */++// Default BM25 parameters+const DEFAULT_K1 = 1.5 // Term frequency saturation parameter (1.2-2.0 typical)+const DEFAULT_B = 0.75 // Document length normalization (0 = no normalization, 1 = full)++/**+ * Tokenize text into terms for indexing+ * @param {string} text - Text to tokenize+ * @returns {string[]} - Array of lowercase terms+ */+function tokenize(text) {+ if (!text || typeof text !== 'string') return []++ return text+ .toLowerCase()+ .replace(/[^\w\s]/g, ' ') // Replace punctuation with spaces+ .split(/\s+/) // Split on whitespace+ .filter(term => term.length > 1) // Remove single characters+ .filter(term => !STOP_WORDS.has(term)) // Remove stop words+}++/**+ * Common English stop words to exclude from indexing+ */+const STOP_WORDS = new Set([+ 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from',+ 'has', 'he', 'in', 'is', 'it', 'its', 'of', 'on', 'or', 'that',+ 'the', 'to', 'was', 'were', 'will', 'with', 'this', 'but', 'they',+ 'have', 'had', 'what', 'when', 'where', 'who', 'which', 'why', 'how',+ 'all', 'each', 'every', 'both', 'few', 'more', 'most', 'other',+ 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so',+ 'than', 'too', 'very', 'just', 'can', 'should', 'now', 'into',+ 'would', 'could', 'also', 'been', 'being', 'do', 'does', 'did'+])++/**+ * Calculate IDF (Inverse Document Frequency) for a term+ * Uses the BM25 IDF formula: log((N - n + 0.5) / (n + 0.5) + 1)+ *+ * @param {number} N - Total number of documents+ * @param {number} n - Number of documents containing the term+ * @returns {number} - IDF value+ */+function calculateIDF(N, n) {+ if (n === 0 || N === 0) return 0+ return Math.log((N - n + 0.5) / (n + 0.5) + 1)+}++/**+ * Build an inverted index from documents+ *+ * @param {Array<{id: string, text: string}>} documents - Documents to index+ * @returns {Object} - Inverted index structure+ */+function buildInvertedIndex(documents) {+ const index = {+ terms: {}, // term -> { docFreq, postings: { docId -> termFreq } }+ docLengths: {}, // docId -> number of terms+ avgDocLength: 0, // Average document length+ totalDocs: 0, // Total number of documents+ docIds: new Set() // Set of all document IDs+ }++ let totalTerms = 0++ for (const doc of documents) {+ if (!doc.id || !doc.text) continue++ const terms = tokenize(doc.text)+ const docId = doc.id++ index.docIds.add(docId)+ index.docLengths[docId] = terms.length+ totalTerms += terms.length++ // Count term frequencies in this document+ const termFreqs = {}+ for (const term of terms) {+ termFreqs[term] = (termFreqs[term] || 0) + 1+ }++ // Update inverted index+ for (const [term, freq] of Object.entries(termFreqs)) {+ if (!index.terms[term]) {+ index.terms[term] = { docFreq: 0, postings: {} }+ }++ if (!index.terms[term].postings[docId]) {+ index.terms[term].docFreq+++ }+ index.terms[term].postings[docId] = freq+ }+ }++ index.totalDocs = index.docIds.size+ index.avgDocLength = index.totalDocs > 0 ? totalTerms / index.totalDocs : 0++ return index+}++/**+ * Add a single document to an existing index+ *+ * @param {Object} index - Existing inverted index+ * @param {string} docId - Document ID+ * @param {string} text - Document text+ * @returns {Object} - Updated index+ */+function addDocument(index, docId, text) {+ if (!docId || !text) return index++ // Remove existing if updating+ if (index.docIds.has(docId)) {+ removeDocument(index, docId)+ }++ const terms = tokenize(text)++ index.docIds.add(docId)+ index.docLengths[docId] = terms.length++ // Update average document length+ const oldTotal = index.avgDocLength * index.totalDocs+ index.totalDocs = index.docIds.size+ index.avgDocLength = (oldTotal + terms.length) / index.totalDocs++ // Count term frequencies+ const termFreqs = {}+ for (const term of terms) {+ termFreqs[term] = (termFreqs[term] || 0) + 1+ }++ // Update inverted index+ for (const [term, freq] of Object.entries(termFreqs)) {+ if (!index.terms[term]) {+ index.terms[term] = { docFreq: 0, postings: {} }+ }++ if (!index.terms[term].postings[docId]) {+ index.terms[term].docFreq+++ }+ index.terms[term].postings[docId] = freq+ }++ return index+}++/**+ * Remove a document from the index+ *+ * @param {Object} index - Existing inverted index+ * @param {string} docId - Document ID to remove+ * @returns {Object} - Updated index+ */+function removeDocument(index, docId) {+ if (!index.docIds.has(docId)) return index++ const docLength = index.docLengths[docId] || 0++ // Update average document length+ const oldTotal = index.avgDocLength * index.totalDocs+ index.docIds.delete(docId)+ index.totalDocs = index.docIds.size++ if (index.totalDocs > 0) {+ index.avgDocLength = (oldTotal - docLength) / index.totalDocs+ } else {+ index.avgDocLength = 0+ }++ delete index.docLengths[docId]++ // Remove from inverted index+ for (const term of Object.keys(index.terms)) {+ if (index.terms[term].postings[docId]) {+ delete index.terms[term].postings[docId]+ index.terms[term].docFreq--++ // Clean up empty terms+ if (index.terms[term].docFreq === 0) {+ delete index.terms[term]+ }+ }+ }++ return index+}++/**+ * Calculate BM25 score for a query against a document+ *+ * @param {string} query - Search query+ * @param {string} docId - Document ID to score+ * @param {Object} index - Inverted index+ * @param {Object} options - BM25 parameters+ * @returns {number} - BM25 score+ */+function score(query, docId, index, options = {}) {+ const k1 = options.k1 ?? DEFAULT_K1+ const b = options.b ?? DEFAULT_B++ if (!index.docIds.has(docId)) return 0++ const queryTerms = tokenize(query)+ const docLength = index.docLengths[docId] || 0+ const avgDocLength = index.avgDocLength || 1+ const N = index.totalDocs++ let totalScore = 0++ for (const term of queryTerms) {+ const termData = index.terms[term]+ if (!termData) continue++ const tf = termData.postings[docId] || 0+ if (tf === 0) continue++ const idf = calculateIDF(N, termData.docFreq)++ // BM25 term score formula+ const numerator = tf * (k1 + 1)+ const denominator = tf + k1 * (1 - b + b * (docLength / avgDocLength))++ totalScore += idf * (numerator / denominator)+ }++ return totalScore+}++/**+ * Search the index for documents matching a query+ *+ * @param {string} query - Search query+ * @param {Object} index - Inverted index+ * @param {Object} options - Search options+ * @param {number} options.limit - Maximum results to return+ * @param {number} options.threshold - Minimum score threshold+ * @param {number} options.k1 - BM25 k1 parameter+ * @param {number} options.b - BM25 b parameter+ * @returns {Array<{docId: string, score: number}>} - Ranked results+ */+function search(query, index, options = {}) {+ const { limit = 10, threshold = 0, k1 = DEFAULT_K1, b = DEFAULT_B } = options++ const queryTerms = tokenize(query)+ if (queryTerms.length === 0) return []++ // Find candidate documents (those containing at least one query term)+ const candidates = new Set()+ for (const term of queryTerms) {+ const termData = index.terms[term]+ if (termData) {+ for (const docId of Object.keys(termData.postings)) {+ candidates.add(docId)+ }+ }+ }++ // Score all candidates+ const results = []+ for (const docId of candidates) {+ const docScore = score(query, docId, index, { k1, b })+ if (docScore > threshold) {+ results.push({ docId, score: docScore })+ }+ }++ // Sort by score descending and apply limit+ results.sort((a, b) => b.score - a.score)+ return results.slice(0, limit)+}++/**+ * Create an empty index structure+ * @returns {Object} - Empty index+ */+function createEmptyIndex() {+ return {+ terms: {},+ docLengths: {},+ avgDocLength: 0,+ totalDocs: 0,+ docIds: new Set()+ }+}++/**+ * Serialize index for persistence (converts Set to Array)+ * @param {Object} index - Index to serialize+ * @returns {Object} - Serializable index+ */+function serializeIndex(index) {+ return {+ ...index,+ docIds: Array.from(index.docIds)+ }+}++/**+ * Deserialize index from storage (converts Array back to Set)+ * @param {Object} data - Serialized index data+ * @returns {Object} - Usable index+ */+function deserializeIndex(data) {+ if (!data) return createEmptyIndex()++ return {+ terms: data.terms || {},+ docLengths: data.docLengths || {},+ avgDocLength: data.avgDocLength || 0,+ totalDocs: data.totalDocs || 0,+ docIds: new Set(data.docIds || [])+ }+}++/**+ * Get index statistics+ * @param {Object} index - The index+ * @returns {Object} - Statistics about the index+ */+function getIndexStats(index) {+ return {+ totalDocuments: index.totalDocs,+ totalTerms: Object.keys(index.terms).length,+ avgDocumentLength: Math.round(index.avgDocLength * 100) / 100+ }+}++export {+ tokenize,+ calculateIDF,+ buildInvertedIndex,+ addDocument,+ removeDocument,+ score,+ search,+ createEmptyIndex,+ serializeIndex,+ deserializeIndex,+ getIndexStats,+ STOP_WORDS,+ DEFAULT_K1,+ DEFAULT_B+}diff --git a/server/lib/bm25.test.js b/server/lib/bm25.test.jsnew file mode 100644index 0000000000..af3eace11c--- /dev/null+++ b/server/lib/bm25.test.js@@ -0,0 +1,345 @@+import { describe, it, expect } from 'vitest';+import {+ tokenize,+ calculateIDF,+ buildInvertedIndex,+ addDocument,+ removeDocument,+ score,+ search,+ createEmptyIndex,+ serializeIndex,+ deserializeIndex,+ getIndexStats,+ STOP_WORDS+} from './bm25.js';++describe('BM25 Algorithm', () => {+ describe('tokenize', () => {+ it('should tokenize text into lowercase terms', () => {+ const result = tokenize('Hello World');+ expect(result).toContain('hello');+ expect(result).toContain('world');+ });++ it('should remove punctuation', () => {+ const result = tokenize('Hello, World! How are you?');+ expect(result.every(t => !/[,!?]/.test(t))).toBe(true);+ });++ it('should remove single character tokens', () => {+ const result = tokenize('I am a test');+ expect(result).not.toContain('i');+ expect(result).not.toContain('a');+ });++ it('should remove stop words', () => {+ const result = tokenize('the quick brown fox jumps over the lazy dog');+ expect(result).not.toContain('the');+ expect(result).not.toContain('is');+ expect(result).toContain('quick');+ expect(result).toContain('brown');+ expect(result).toContain('fox');+ expect(result).toContain('over'); // 'over' is not a stop word in our list+ });++ it('should handle empty input', () => {+ expect(tokenize('')).toEqual([]);+ expect(tokenize(null)).toEqual([]);+ expect(tokenize(undefined)).toEqual([]);+ });++ it('should handle non-string input', () => {+ expect(tokenize(123)).toEqual([]);+ expect(tokenize({})).toEqual([]);+ });+ });++ describe('calculateIDF', () => {+ it('should return 0 when n is 0', () => {+ expect(calculateIDF(100, 0)).toBe(0);+ });++ it('should return 0 when N is 0', () => {+ expect(calculateIDF(0, 5)).toBe(0);+ });++ it('should return higher values for rarer terms', () => {+ const commonIDF = calculateIDF(1000, 500);+ const rareIDF = calculateIDF(1000, 10);+ expect(rareIDF).toBeGreaterThan(commonIDF);+ });++ it('should return positive values for valid inputs', () => {+ expect(calculateIDF(100, 10)).toBeGreaterThan(0);+ });+ });++ describe('buildInvertedIndex', () => {+ it('should build index from documents', () => {+ const docs = [+ { id: 'doc1', text: 'quick brown fox' },+ { id: 'doc2', text: 'lazy brown dog' }+ ];+ const index = buildInvertedIndex(docs);++ expect(index.totalDocs).toBe(2);+ expect(index.docIds.has('doc1')).toBe(true);+ expect(index.docIds.has('doc2')).toBe(true);+ expect(index.terms['brown'].docFreq).toBe(2);+ expect(index.terms['quick'].docFreq).toBe(1);+ });++ it('should track document lengths', () => {+ const docs = [+ { id: 'doc1', text: 'word word word' },+ { id: 'doc2', text: 'single' }+ ];+ const index = buildInvertedIndex(docs);++ // Document length is total term count (including duplicates)+ expect(index.docLengths['doc1']).toBe(3); // "word" appears 3 times+ expect(index.docLengths['doc2']).toBe(1);+ });++ it('should calculate average document length', () => {+ const docs = [+ { id: 'doc1', text: 'quick brown fox jumps' },+ { id: 'doc2', text: 'lazy dog' }+ ];+ const index = buildInvertedIndex(docs);++ expect(index.avgDocLength).toBeGreaterThan(0);+ });++ it('should handle empty documents array', () => {+ const index = buildInvertedIndex([]);+ expect(index.totalDocs).toBe(0);+ expect(index.avgDocLength).toBe(0);+ });++ it('should skip documents without id or text', () => {+ const docs = [+ { id: 'doc1', text: 'valid document' },+ { text: 'no id' },+ { id: 'doc3' },+ {}+ ];+ const index = buildInvertedIndex(docs);++ expect(index.totalDocs).toBe(1);+ });+ });++ describe('addDocument', () => {+ it('should add a document to existing index', () => {+ const index = createEmptyIndex();+ addDocument(index, 'doc1', 'hello world');++ expect(index.totalDocs).toBe(1);+ expect(index.docIds.has('doc1')).toBe(true);+ });++ it('should update average doc length', () => {+ const index = createEmptyIndex();+ addDocument(index, 'doc1', 'word word word');+ const avgAfterFirst = index.avgDocLength;++ addDocument(index, 'doc2', 'single');+ expect(index.avgDocLength).not.toBe(avgAfterFirst);+ });++ it('should replace existing document with same id', () => {+ const index = createEmptyIndex();+ addDocument(index, 'doc1', 'original content');+ addDocument(index, 'doc1', 'updated content');++ expect(index.totalDocs).toBe(1);+ expect(index.terms['updated']).toBeDefined();+ });++ it('should handle empty text', () => {+ const index = createEmptyIndex();+ addDocument(index, 'doc1', '');++ expect(index.totalDocs).toBe(0);+ });+ });++ describe('removeDocument', () => {+ it('should remove a document from index', () => {+ const docs = [+ { id: 'doc1', text: 'quick brown fox' },+ { id: 'doc2', text: 'lazy brown dog' }+ ];+ const index = buildInvertedIndex(docs);++ removeDocument(index, 'doc1');++ expect(index.totalDocs).toBe(1);+ expect(index.docIds.has('doc1')).toBe(false);+ expect(index.terms['quick']).toBeUndefined();+ });++ it('should update term frequencies', () => {+ const docs = [+ { id: 'doc1', text: 'brown' },+ { id: 'doc2', text: 'brown' }+ ];+ const index = buildInvertedIndex(docs);++ expect(index.terms['brown'].docFreq).toBe(2);+ removeDocument(index, 'doc1');+ expect(index.terms['brown'].docFreq).toBe(1);+ });++ it('should handle non-existent document', () => {+ const index = createEmptyIndex();+ addDocument(index, 'doc1', 'test');++ removeDocument(index, 'nonexistent');+ expect(index.totalDocs).toBe(1);+ });+ });++ describe('score', () => {+ it('should return 0 for non-existent document', () => {+ const index = createEmptyIndex();+ addDocument(index, 'doc1', 'test document');++ expect(score('test', 'nonexistent', index)).toBe(0);+ });++ it('should return higher score for more matches', () => {+ const docs = [+ { id: 'doc1', text: 'quick brown fox' },+ { id: 'doc2', text: 'quick quick quick' }+ ];+ const index = buildInvertedIndex(docs);++ const score1 = score('quick', 'doc1', index);+ const score2 = score('quick', 'doc2', index);++ expect(score2).toBeGreaterThan(score1);+ });++ it('should return 0 when no query terms match', () => {+ const index = createEmptyIndex();+ addDocument(index, 'doc1', 'hello world');++ expect(score('xyz', 'doc1', index)).toBe(0);+ });+ });++ describe('search', () => {+ it('should return ranked results', () => {+ const docs = [+ { id: 'doc1', text: 'python programming language' },+ { id: 'doc2', text: 'javascript programming web' },+ { id: 'doc3', text: 'python python python scripts' }+ ];+ const index = buildInvertedIndex(docs);++ const results = search('python programming', index);++ expect(results.length).toBeGreaterThan(0);+ expect(results[0].score).toBeGreaterThanOrEqual(results[results.length - 1].score);+ });++ it('should respect limit parameter', () => {+ const docs = Array.from({ length: 20 }, (_, i) => ({+ id: `doc${i}`,+ text: `document ${i} content test`+ }));+ const index = buildInvertedIndex(docs);++ const results = search('content', index, { limit: 5 });+ expect(results.length).toBe(5);+ });++ it('should respect threshold parameter', () => {+ const docs = [+ { id: 'doc1', text: 'exact match query' },+ { id: 'doc2', text: 'partial match' }+ ];+ const index = buildInvertedIndex(docs);++ const allResults = search('exact match', index, { threshold: 0 });+ const highResults = search('exact match', index, { threshold: 1.0 });++ expect(highResults.length).toBeLessThanOrEqual(allResults.length);+ });++ it('should return empty array for empty query', () => {+ const index = createEmptyIndex();+ addDocument(index, 'doc1', 'test document');++ expect(search('', index)).toEqual([]);+ });++ it('should return empty array for stop-word-only query', () => {+ const index = createEmptyIndex();+ addDocument(index, 'doc1', 'test document');++ expect(search('the and is', index)).toEqual([]);+ });+ });++ describe('serialization', () => {+ it('should serialize index with Set to Array', () => {+ const index = createEmptyIndex();+ addDocument(index, 'doc1', 'test');++ const serialized = serializeIndex(index);+ expect(Array.isArray(serialized.docIds)).toBe(true);+ });++ it('should deserialize index back to usable form', () => {+ const original = createEmptyIndex();+ addDocument(original, 'doc1', 'test document');+ addDocument(original, 'doc2', 'another test');++ const serialized = serializeIndex(original);+ const deserialized = deserializeIndex(serialized);++ expect(deserialized.docIds instanceof Set).toBe(true);+ expect(deserialized.docIds.has('doc1')).toBe(true);+ expect(deserialized.docIds.has('doc2')).toBe(true);+ expect(deserialized.totalDocs).toBe(2);+ });++ it('should handle null data in deserialize', () => {+ const result = deserializeIndex(null);+ expect(result.totalDocs).toBe(0);+ expect(result.docIds instanceof Set).toBe(true);+ });+ });++ describe('getIndexStats', () => {+ it('should return correct statistics', () => {+ const docs = [+ { id: 'doc1', text: 'hello world test' },+ { id: 'doc2', text: 'another test document' },+ { id: 'doc3', text: 'third document here' }+ ];+ const index = buildInvertedIndex(docs);+ const stats = getIndexStats(index);++ expect(stats.totalDocuments).toBe(3);+ expect(stats.totalTerms).toBeGreaterThan(0);+ expect(stats.avgDocumentLength).toBeGreaterThan(0);+ });+ });++ describe('STOP_WORDS', () => {+ it('should be a Set', () => {+ expect(STOP_WORDS instanceof Set).toBe(true);+ });++ it('should contain common English stop words', () => {+ expect(STOP_WORDS.has('the')).toBe(true);+ expect(STOP_WORDS.has('and')).toBe(true);+ expect(STOP_WORDS.has('is')).toBe(true);+ });+ });+});diff --git a/server/routes/lmstudio.js b/server/routes/lmstudio.jsnew file mode 100644index 0000000000..f8ecaff458--- /dev/null+++ b/server/routes/lmstudio.js@@ -0,0 +1,202 @@+/**+ * LM Studio Routes+ *+ * REST endpoints for LM Studio model management.+ */++import { Router } from 'express'+import * as lmStudioManager from '../services/lmStudioManager.js'+import * as localThinking from '../services/localThinking.js'++const router = Router()++/**+ * GET /api/lmstudio/status+ * Check LM Studio availability and loaded models+ */+router.get('/status', async (req, res) => {+ const status = await lmStudioManager.getStatus()+ const thinkingStats = localThinking.getStats()++ res.json({+ ...status,+ thinkingStats+ })+})++/**+ * GET /api/lmstudio/models+ * List available/loaded models+ */+router.get('/models', async (req, res) => {+ const available = await lmStudioManager.checkLMStudioAvailable()++ if (!available) {+ return res.status(503).json({+ error: 'LM Studio not available',+ available: false+ })+ }++ const models = await lmStudioManager.getLoadedModels(true)+ const recommended = await lmStudioManager.getRecommendedThinkingModel()++ res.json({+ available: true,+ count: models.length,+ models,+ recommendedThinkingModel: recommended+ })+})++/**+ * POST /api/lmstudio/download+ * Download a model by ID+ */+router.post('/download', async (req, res) => {+ const { modelId } = req.body++ if (!modelId) {+ return res.status(400).json({ error: 'modelId is required' })+ }++ const result = await lmStudioManager.downloadModel(modelId)+ res.json(result)+})++/**+ * POST /api/lmstudio/load+ * Load a model into memory+ */+router.post('/load', async (req, res) => {+ const { modelId } = req.body++ if (!modelId) {+ return res.status(400).json({ error: 'modelId is required' })+ }++ const result = await lmStudioManager.loadModel(modelId)+ res.json(result)+})++/**+ * POST /api/lmstudio/unload+ * Unload a model from memory+ */+router.post('/unload', async (req, res) => {+ const { modelId } = req.body++ if (!modelId) {+ return res.status(400).json({ error: 'modelId is required' })+ }++ const result = await lmStudioManager.unloadModel(modelId)+ res.json(result)+})++/**+ * POST /api/lmstudio/completion+ * Quick completion using local model+ */+router.post('/completion', async (req, res) => {+ const { prompt, model, maxTokens, temperature, systemPrompt } = req.body++ if (!prompt) {+ return res.status(400).json({ error: 'prompt is required' })+ }++ const result = await lmStudioManager.quickCompletion(prompt, {+ model,+ maxTokens,+ temperature,+ systemPrompt+ })++ res.json(result)+})++/**+ * POST /api/lmstudio/analyze-task+ * Analyze a task for complexity and escalation needs+ */+router.post('/analyze-task', async (req, res) => {+ const { description, id, metadata } = req.body++ if (!description) {+ return res.status(400).json({ error: 'description is required' })+ }++ const analysis = await localThinking.analyzeTask({+ id,+ description,+ metadata+ })++ res.json(analysis)+})++/**+ * POST /api/lmstudio/classify-memory+ * Classify memory content+ */+router.post('/classify-memory', async (req, res) => {+ const { content } = req.body++ if (!content) {+ return res.status(400).json({ error: 'content is required' })+ }++ const classification = await localThinking.classifyMemory(content)+ res.json(classification)+})++/**+ * POST /api/lmstudio/embeddings+ * Get embeddings for text+ */+router.post('/embeddings', async (req, res) => {+ const { text, model } = req.body++ if (!text) {+ return res.status(400).json({ error: 'text is required' })+ }++ const result = await lmStudioManager.getEmbeddings(text, { model })+ res.json(result)+})++/**+ * PUT /api/lmstudio/config+ * Update LM Studio configuration+ */+router.put('/config', async (req, res) => {+ const { baseUrl, timeout, defaultThinkingModel } = req.body++ const config = lmStudioManager.updateConfig({+ baseUrl,+ timeout,+ defaultThinkingModel+ })++ res.json({ success: true, config })+})++/**+ * GET /api/lmstudio/thinking-stats+ * Get local thinking statistics+ */+router.get('/thinking-stats', (req, res) => {+ const stats = localThinking.getStats()+ res.json(stats)+})++/**+ * POST /api/lmstudio/reset-cache+ * Reset LM Studio cached state+ */+router.post('/reset-cache', (req, res) => {+ lmStudioManager.resetCache()+ res.json({ success: true, message: 'Cache reset' })+})++export default routerdiff --git a/server/services/agentGateway.js b/server/services/agentGateway.jsnew file mode 100644index 0000000000..f0fdaed5d1--- /dev/null+++ b/server/services/agentGateway.js@@ -0,0 +1,327 @@+/**+ * Agent Gateway Service+ *+ * Centralized communication hub for agent operations.+ * Provides request deduplication, caching, and coordination.+ */++import { cosEvents } from './cos.js'++// Request deduplication cache+const pendingRequests = new Map()++// Response cache with TTL+const responseCache = new Map()+const CACHE_TTL_MS = 10 * 60 * 1000 // 10 minutes++// Request history for analytics+const requestHistory = []+const MAX_HISTORY = 500++// Gateway statistics+const stats = {+ totalRequests: 0,+ cacheHits: 0,+ cacheMisses: 0,+ deduplicatedRequests: 0,+ errors: 0+}++/**+ * Generate cache key for a request+ * @param {string} type - Request type+ * @param {Object} params - Request parameters+ * @returns {string} - Cache key+ */+function generateCacheKey(type, params) {+ const sortedParams = JSON.stringify(params, Object.keys(params).sort())+ return `${type}:${sortedParams}`+}++/**+ * Clean expired cache entries+ */+function cleanExpiredCache() {+ const now = Date.now()+ for (const [key, entry] of responseCache.entries()) {+ if (now > entry.expiresAt) {+ responseCache.delete(key)+ }+ }+}++/**+ * Route a request through the gateway+ * Handles deduplication and caching+ *+ * @param {string} type - Request type (e.g., 'embedding', 'completion', 'tool')+ * @param {Object} params - Request parameters+ * @param {Function} handler - Async function to execute if not cached+ * @param {Object} options - Gateway options+ * @returns {Promise<*>} - Request result+ */+async function routeRequest(type, params, handler, options = {}) {+ const {+ cacheable = true,+ ttlMs = CACHE_TTL_MS,+ deduplicateMs = 5000+ } = options++ stats.totalRequests+++ const cacheKey = generateCacheKey(type, params)+ const now = Date.now()++ // Check response cache first+ if (cacheable) {+ const cached = responseCache.get(cacheKey)+ if (cached && now < cached.expiresAt) {+ stats.cacheHits+++ return { ...cached.response, fromCache: true }+ }+ stats.cacheMisses+++ }++ // Check for pending duplicate request+ const pending = pendingRequests.get(cacheKey)+ if (pending && now - pending.startedAt < deduplicateMs) {+ stats.deduplicatedRequests+++ return pending.promise+ }++ // Execute the request+ const requestPromise = (async () => {+ const startTime = Date.now()+ let result+ let error = null++ try {+ result = await handler(params)++ // Cache successful response+ if (cacheable && result) {+ responseCache.set(cacheKey, {+ response: result,+ expiresAt: now + ttlMs,+ cachedAt: now+ })+ }+ } catch (err) {+ error = err+ stats.errors+++ throw err+ } finally {+ // Record in history+ requestHistory.unshift({+ type,+ cacheKey: cacheKey.substring(0, 50),+ startedAt: startTime,+ duration: Date.now() - startTime,+ success: !error,+ cached: false+ })++ // Trim history+ while (requestHistory.length > MAX_HISTORY) {+ requestHistory.pop()+ }++ // Clean up pending request+ pendingRequests.delete(cacheKey)+ }++ return result+ })()++ // Track pending request+ pendingRequests.set(cacheKey, {+ promise: requestPromise,+ startedAt: now+ })++ return requestPromise+}++/**+ * Invalidate cache entries matching a pattern+ * @param {string} typePrefix - Type prefix to match+ * @returns {number} - Number of entries invalidated+ */+function invalidateCache(typePrefix) {+ let invalidated = 0++ for (const key of responseCache.keys()) {+ if (key.startsWith(typePrefix)) {+ responseCache.delete(key)+ invalidated+++ }+ }++ if (invalidated > 0) {+ console.log(`🗑️ Invalidated ${invalidated} cache entries matching "${typePrefix}"`)+ }++ return invalidated+}++/**+ * Clear entire cache+ * @returns {number} - Number of entries cleared+ */+function clearCache() {+ const size = responseCache.size+ responseCache.clear()+ console.log(`🗑️ Cleared ${size} cache entries`)+ return size+}++/**+ * Get gateway statistics+ * @returns {Object} - Gateway stats+ */+function getStats() {+ cleanExpiredCache()++ return {+ ...stats,+ cacheSize: responseCache.size,+ pendingRequests: pendingRequests.size,+ cacheHitRate: stats.totalRequests > 0+ ? ((stats.cacheHits / stats.totalRequests) * 100).toFixed(1) + '%'+ : '0%',+ deduplicationRate: stats.totalRequests > 0+ ? ((stats.deduplicatedRequests / stats.totalRequests) * 100).toFixed(1) + '%'+ : '0%'+ }+}++/**+ * Get recent request history+ * @param {Object} options - Filter options+ * @returns {Array} - Request history+ */+function getRequestHistory(options = {}) {+ let history = [...requestHistory]++ if (options.type) {+ history = history.filter(r => r.type === options.type)+ }++ if (options.success !== undefined) {+ history = history.filter(r => r.success === options.success)+ }++ const limit = options.limit || 50+ return history.slice(0, limit)+}++/**+ * Pre-warm cache with common requests+ * @param {Array} requests - Array of {type, params, handler} to pre-warm+ * @returns {Promise<number>} - Number of requests cached+ */+async function prewarmCache(requests) {+ let cached = 0++ for (const { type, params, handler } of requests) {+ const cacheKey = generateCacheKey(type, params)++ // Skip if already cached+ if (responseCache.has(cacheKey)) continue++ try {+ await routeRequest(type, params, handler, { cacheable: true })+ cached+++ } catch (err) {+ console.error(`⚠️ Cache prewarm failed for ${type}: ${err.message}`)+ }+ }++ if (cached > 0) {+ console.log(`🔥 Pre-warmed cache with ${cached} entries`)+ }++ return cached+}++/**+ * Create a gateway-aware request function for a specific type+ * @param {string} type - Request type+ * @param {Function} handler - Request handler+ * @param {Object} defaultOptions - Default gateway options+ * @returns {Function} - Gateway-wrapped function+ */+function createGatewayRequest(type, handler, defaultOptions = {}) {+ return async function gatewayRequest(params, options = {}) {+ return routeRequest(type, params, handler, { ...defaultOptions, ...options })+ }+}++/**+ * Batch multiple requests through gateway+ * @param {Array<{type, params, handler}>} requests - Requests to batch+ * @param {Object} options - Batch options+ * @returns {Promise<Array>} - Results in same order+ */+async function batchRequests(requests, options = {}) {+ const { parallel = true, stopOnError = false } = options++ if (parallel) {+ const promises = requests.map(({ type, params, handler, options: reqOptions }) =>+ routeRequest(type, params, handler, reqOptions).catch(err => {+ if (stopOnError) throw err+ return { error: err.message }+ })+ )+ return Promise.all(promises)+ }++ const results = []+ for (const { type, params, handler, options: reqOptions } of requests) {+ try {+ const result = await routeRequest(type, params, handler, reqOptions)+ results.push(result)+ } catch (err) {+ if (stopOnError) throw err+ results.push({ error: err.message })+ }+ }++ return results+}++/**+ * Subscribe to gateway events+ * @param {string} event - Event name+ * @param {Function} callback - Event handler+ */+function subscribe(event, callback) {+ cosEvents.on(`gateway:${event}`, callback)+}++/**+ * Reset gateway statistics+ */+function resetStats() {+ stats.totalRequests = 0+ stats.cacheHits = 0+ stats.cacheMisses = 0+ stats.deduplicatedRequests = 0+ stats.errors = 0+}++// Periodic cache cleanup+setInterval(cleanExpiredCache, 60000).unref()++export {+ routeRequest,+ invalidateCache,+ clearCache,+ getStats,+ getRequestHistory,+ prewarmCache,+ createGatewayRequest,+ batchRequests,+ subscribe,+ resetStats,+ generateCacheKey+}diff --git a/server/services/agentRunCache.js b/server/services/agentRunCache.jsnew file mode 100644index 0000000000..62cd58da52--- /dev/null+++ b/server/services/agentRunCache.js@@ -0,0 +1,390 @@+/**+ * Agent Run Cache Service+ *+ * Caches agent outputs and tool results with 10-minute TTL.+ * Provides fast lookups for repeated operations.+ */++// Cache TTL (10 minutes)+const DEFAULT_TTL_MS = 10 * 60 * 1000++// Cache storage+const outputCache = new Map()+const toolResultCache = new Map()+const contextCache = new Map()++// Cache statistics+const stats = {+ outputHits: 0,+ outputMisses: 0,+ toolHits: 0,+ toolMisses: 0,+ contextHits: 0,+ contextMisses: 0,+ evictions: 0+}++/**+ * Create a cache entry with expiration+ * @param {*} value - Value to cache+ * @param {number} ttlMs - Time to live in milliseconds+ * @returns {Object} - Cache entry+ */+function createCacheEntry(value, ttlMs = DEFAULT_TTL_MS) {+ return {+ value,+ createdAt: Date.now(),+ expiresAt: Date.now() + ttlMs,+ accessCount: 0,+ lastAccessedAt: null+ }+}++/**+ * Check if entry is expired+ * @param {Object} entry - Cache entry+ * @returns {boolean} - True if expired+ */+function isExpired(entry) {+ return Date.now() > entry.expiresAt+}++/**+ * Cache agent output+ * @param {string} agentId - Agent identifier+ * @param {*} output - Output to cache+ * @param {Object} options - Cache options+ */+function cacheOutput(agentId, output, options = {}) {+ const ttl = options.ttlMs || DEFAULT_TTL_MS+ outputCache.set(agentId, createCacheEntry(output, ttl))+}++/**+ * Get cached agent output+ * @param {string} agentId - Agent identifier+ * @returns {*} - Cached output or null+ */+function getOutput(agentId) {+ const entry = outputCache.get(agentId)++ if (!entry) {+ stats.outputMisses+++ return null+ }++ if (isExpired(entry)) {+ outputCache.delete(agentId)+ stats.evictions+++ stats.outputMisses+++ return null+ }++ entry.accessCount+++ entry.lastAccessedAt = Date.now()+ stats.outputHits++++ return entry.value+}++/**+ * Generate tool cache key+ * @param {string} toolId - Tool identifier+ * @param {Object} params - Tool parameters+ * @returns {string} - Cache key+ */+function generateToolKey(toolId, params) {+ const sortedParams = JSON.stringify(params, Object.keys(params || {}).sort())+ return `${toolId}:${sortedParams}`+}++/**+ * Cache tool result+ * @param {string} toolId - Tool identifier+ * @param {Object} params - Tool parameters+ * @param {*} result - Tool result+ * @param {Object} options - Cache options+ */+function cacheToolResult(toolId, params, result, options = {}) {+ const key = generateToolKey(toolId, params)+ const ttl = options.ttlMs || DEFAULT_TTL_MS+ toolResultCache.set(key, createCacheEntry(result, ttl))+}++/**+ * Get cached tool result+ * @param {string} toolId - Tool identifier+ * @param {Object} params - Tool parameters+ * @returns {*} - Cached result or null+ */+function getToolResult(toolId, params) {+ const key = generateToolKey(toolId, params)+ const entry = toolResultCache.get(key)++ if (!entry) {+ stats.toolMisses+++ return null+ }++ if (isExpired(entry)) {+ toolResultCache.delete(key)+ stats.evictions+++ stats.toolMisses+++ return null+ }++ entry.accessCount+++ entry.lastAccessedAt = Date.now()+ stats.toolHits++++ return entry.value+}++/**+ * Cache context/memory section+ * @param {string} taskId - Task identifier+ * @param {string} context - Context string+ * @param {Object} options - Cache options+ */+function cacheContext(taskId, context, options = {}) {+ const ttl = options.ttlMs || DEFAULT_TTL_MS+ contextCache.set(taskId, createCacheEntry(context, ttl))+}++/**+ * Get cached context+ * @param {string} taskId - Task identifier+ * @returns {string|null} - Cached context or null+ */+function getContext(taskId) {+ const entry = contextCache.get(taskId)++ if (!entry) {+ stats.contextMisses+++ return null+ }++ if (isExpired(entry)) {+ contextCache.delete(taskId)+ stats.evictions+++ stats.contextMisses+++ return null+ }++ entry.accessCount+++ entry.lastAccessedAt = Date.now()+ stats.contextHits++++ return entry.value+}++/**+ * Invalidate output cache for an agent+ * @param {string} agentId - Agent identifier+ * @returns {boolean} - True if entry was found and removed+ */+function invalidateOutput(agentId) {+ return outputCache.delete(agentId)+}++/**+ * Invalidate tool result cache+ * @param {string} toolId - Tool identifier+ * @param {Object} params - Tool parameters (optional, if null clears all for tool)+ * @returns {number} - Number of entries invalidated+ */+function invalidateToolResult(toolId, params = null) {+ if (params !== null) {+ const key = generateToolKey(toolId, params)+ return toolResultCache.delete(key) ? 1 : 0+ }++ // Clear all entries for this tool+ let count = 0+ for (const key of toolResultCache.keys()) {+ if (key.startsWith(`${toolId}:`)) {+ toolResultCache.delete(key)+ count+++ }+ }+ return count+}++/**+ * Invalidate context cache for a task+ * @param {string} taskId - Task identifier+ * @returns {boolean} - True if entry was found and removed+ */+function invalidateContext(taskId) {+ return contextCache.delete(taskId)+}++/**+ * Clear all caches+ * @returns {Object} - Number of entries cleared per cache+ */+function clearAll() {+ const counts = {+ outputs: outputCache.size,+ toolResults: toolResultCache.size,+ contexts: contextCache.size+ }++ outputCache.clear()+ toolResultCache.clear()+ contextCache.clear()++ console.log(`🗑️ Cache cleared: ${counts.outputs} outputs, ${counts.toolResults} tool results, ${counts.contexts} contexts`)++ return counts+}++/**+ * Clean up expired entries from all caches+ * @returns {number} - Total entries cleaned+ */+function cleanExpired() {+ let cleaned = 0++ for (const [key, entry] of outputCache.entries()) {+ if (isExpired(entry)) {+ outputCache.delete(key)+ cleaned+++ }+ }++ for (const [key, entry] of toolResultCache.entries()) {+ if (isExpired(entry)) {+ toolResultCache.delete(key)+ cleaned+++ }+ }++ for (const [key, entry] of contextCache.entries()) {+ if (isExpired(entry)) {+ contextCache.delete(key)+ cleaned+++ }+ }++ if (cleaned > 0) {+ stats.evictions += cleaned+ }++ return cleaned+}++/**+ * Get cache statistics+ * @returns {Object} - Cache statistics+ */+function getStats() {+ cleanExpired()++ const outputHitRate = (stats.outputHits + stats.outputMisses) > 0+ ? ((stats.outputHits / (stats.outputHits + stats.outputMisses)) * 100).toFixed(1) + '%'+ : '0%'++ const toolHitRate = (stats.toolHits + stats.toolMisses) > 0+ ? ((stats.toolHits / (stats.toolHits + stats.toolMisses)) * 100).toFixed(1) + '%'+ : '0%'++ const contextHitRate = (stats.contextHits + stats.contextMisses) > 0+ ? ((stats.contextHits / (stats.contextHits + stats.contextMisses)) * 100).toFixed(1) + '%'+ : '0%'++ return {+ outputs: {+ size: outputCache.size,+ hits: stats.outputHits,+ misses: stats.outputMisses,+ hitRate: outputHitRate+ },+ toolResults: {+ size: toolResultCache.size,+ hits: stats.toolHits,+ misses: stats.toolMisses,+ hitRate: toolHitRate+ },+ contexts: {+ size: contextCache.size,+ hits: stats.contextHits,+ misses: stats.contextMisses,+ hitRate: contextHitRate+ },+ totalEvictions: stats.evictions,+ totalSize: outputCache.size + toolResultCache.size + contextCache.size+ }+}++/**+ * Get or compute output with caching+ * @param {string} agentId - Agent identifier+ * @param {Function} computeFn - Function to compute output if not cached+ * @param {Object} options - Cache options+ * @returns {Promise<*>} - Output (cached or computed)+ */+async function getOrComputeOutput(agentId, computeFn, options = {}) {+ const cached = getOutput(agentId)+ if (cached !== null) {+ return { value: cached, fromCache: true }+ }++ const computed = await computeFn()+ cacheOutput(agentId, computed, options)+ return { value: computed, fromCache: false }+}++/**+ * Get or compute tool result with caching+ * @param {string} toolId - Tool identifier+ * @param {Object} params - Tool parameters+ * @param {Function} computeFn - Function to compute result if not cached+ * @param {Object} options - Cache options+ * @returns {Promise<*>} - Result (cached or computed)+ */+async function getOrComputeToolResult(toolId, params, computeFn, options = {}) {+ const cached = getToolResult(toolId, params)+ if (cached !== null) {+ return { value: cached, fromCache: true }+ }++ const computed = await computeFn()+ cacheToolResult(toolId, params, computed, options)+ return { value: computed, fromCache: false }+}++/**+ * Reset cache statistics+ */+function resetStats() {+ stats.outputHits = 0+ stats.outputMisses = 0+ stats.toolHits = 0+ stats.toolMisses = 0+ stats.contextHits = 0+ stats.contextMisses = 0+ stats.evictions = 0+}++// Periodic cleanup+setInterval(cleanExpired, 60000).unref()++export {+ cacheOutput,+ getOutput,+ cacheToolResult,+ getToolResult,+ cacheContext,+ getContext,+ invalidateOutput,+ invalidateToolResult,+ invalidateContext,+ clearAll,+ cleanExpired,+ getStats,+ getOrComputeOutput,+ getOrComputeToolResult,+ resetStats,+ DEFAULT_TTL_MS+}diff --git a/server/services/agentRunCache.test.js b/server/services/agentRunCache.test.jsnew file mode 100644index 0000000000..d94b904aba--- /dev/null+++ b/server/services/agentRunCache.test.js@@ -0,0 +1,337 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import {+ cacheOutput,+ getOutput,+ cacheToolResult,+ getToolResult,+ cacheContext,+ getContext,+ invalidateOutput,+ invalidateToolResult,+ invalidateContext,+ clearAll,+ cleanExpired,+ getStats,+ getOrComputeOutput,+ getOrComputeToolResult,+ resetStats,+ DEFAULT_TTL_MS+} from './agentRunCache.js';++describe('Agent Run Cache Service', () => {+ beforeEach(() => {+ clearAll();+ resetStats();+ });++ describe('DEFAULT_TTL_MS', () => {+ it('should be 10 minutes', () => {+ expect(DEFAULT_TTL_MS).toBe(10 * 60 * 1000);+ });+ });++ describe('cacheOutput / getOutput', () => {+ it('should cache and retrieve output', () => {+ const output = { result: 'test output' };+ cacheOutput('agent-1', output);++ const cached = getOutput('agent-1');+ expect(cached).toEqual(output);+ });++ it('should return null for non-existent key', () => {+ expect(getOutput('nonexistent')).toBeNull();+ });++ it('should track hits and misses', () => {+ cacheOutput('agent-1', 'output');+ getOutput('agent-1'); // hit+ getOutput('agent-2'); // miss++ const stats = getStats();+ expect(stats.outputs.hits).toBe(1);+ expect(stats.outputs.misses).toBe(1);+ });++ it('should expire after TTL', async () => {+ cacheOutput('agent-1', 'output', { ttlMs: 50 });++ expect(getOutput('agent-1')).toBe('output');++ await new Promise(resolve => setTimeout(resolve, 60));++ expect(getOutput('agent-1')).toBeNull();+ });+ });++ describe('cacheToolResult / getToolResult', () => {+ it('should cache and retrieve tool results', () => {+ const result = { data: [1, 2, 3] };+ cacheToolResult('tool-1', { input: 'test' }, result);++ const cached = getToolResult('tool-1', { input: 'test' });+ expect(cached).toEqual(result);+ });++ it('should differentiate based on params', () => {+ cacheToolResult('tool-1', { a: 1 }, 'result-a');+ cacheToolResult('tool-1', { b: 2 }, 'result-b');++ expect(getToolResult('tool-1', { a: 1 })).toBe('result-a');+ expect(getToolResult('tool-1', { b: 2 })).toBe('result-b');+ });++ it('should handle same params in different order', () => {+ cacheToolResult('tool-1', { a: 1, b: 2 }, 'result');++ // Same params but different order+ const cached = getToolResult('tool-1', { b: 2, a: 1 });+ expect(cached).toBe('result');+ });++ it('should return null for non-existent key', () => {+ expect(getToolResult('tool-1', { unknown: true })).toBeNull();+ });++ it('should track hits and misses', () => {+ cacheToolResult('tool-1', { x: 1 }, 'result');+ getToolResult('tool-1', { x: 1 }); // hit+ getToolResult('tool-1', { x: 2 }); // miss++ const stats = getStats();+ expect(stats.toolResults.hits).toBe(1);+ expect(stats.toolResults.misses).toBe(1);+ });+ });++ describe('cacheContext / getContext', () => {+ it('should cache and retrieve context', () => {+ cacheContext('task-1', 'Relevant memory context');++ const cached = getContext('task-1');+ expect(cached).toBe('Relevant memory context');+ });++ it('should return null for non-existent key', () => {+ expect(getContext('nonexistent')).toBeNull();+ });++ it('should track hits and misses', () => {+ cacheContext('task-1', 'context');+ getContext('task-1'); // hit+ getContext('task-2'); // miss++ const stats = getStats();+ expect(stats.contexts.hits).toBe(1);+ expect(stats.contexts.misses).toBe(1);+ });+ });++ describe('invalidateOutput', () => {+ it('should remove cached output', () => {+ cacheOutput('agent-1', 'output');+ expect(getOutput('agent-1')).toBe('output');++ invalidateOutput('agent-1');+ expect(getOutput('agent-1')).toBeNull();+ });++ it('should return true when entry existed', () => {+ cacheOutput('agent-1', 'output');+ expect(invalidateOutput('agent-1')).toBe(true);+ });++ it('should return false when entry did not exist', () => {+ expect(invalidateOutput('nonexistent')).toBe(false);+ });+ });++ describe('invalidateToolResult', () => {+ it('should remove specific cached tool result', () => {+ cacheToolResult('tool-1', { a: 1 }, 'result-a');+ cacheToolResult('tool-1', { b: 2 }, 'result-b');++ invalidateToolResult('tool-1', { a: 1 });++ expect(getToolResult('tool-1', { a: 1 })).toBeNull();+ expect(getToolResult('tool-1', { b: 2 })).toBe('result-b');+ });++ it('should remove all results for tool when params is null', () => {+ cacheToolResult('tool-1', { a: 1 }, 'result-a');+ cacheToolResult('tool-1', { b: 2 }, 'result-b');+ cacheToolResult('tool-2', { c: 3 }, 'result-c');++ const count = invalidateToolResult('tool-1', null);++ expect(count).toBe(2);+ expect(getToolResult('tool-1', { a: 1 })).toBeNull();+ expect(getToolResult('tool-1', { b: 2 })).toBeNull();+ expect(getToolResult('tool-2', { c: 3 })).toBe('result-c');+ });++ it('should return count of entries invalidated', () => {+ cacheToolResult('tool-1', { a: 1 }, 'result');+ expect(invalidateToolResult('tool-1', { a: 1 })).toBe(1);+ expect(invalidateToolResult('tool-1', { unknown: true })).toBe(0);+ });+ });++ describe('invalidateContext', () => {+ it('should remove cached context', () => {+ cacheContext('task-1', 'context');+ expect(getContext('task-1')).toBe('context');++ invalidateContext('task-1');+ expect(getContext('task-1')).toBeNull();+ });+ });++ describe('clearAll', () => {+ it('should clear all caches', () => {+ cacheOutput('agent-1', 'output');+ cacheToolResult('tool-1', { x: 1 }, 'result');+ cacheContext('task-1', 'context');++ const counts = clearAll();++ expect(counts.outputs).toBe(1);+ expect(counts.toolResults).toBe(1);+ expect(counts.contexts).toBe(1);++ expect(getOutput('agent-1')).toBeNull();+ expect(getToolResult('tool-1', { x: 1 })).toBeNull();+ expect(getContext('task-1')).toBeNull();+ });+ });++ describe('cleanExpired', () => {+ it('should remove expired entries', async () => {+ cacheOutput('agent-1', 'output', { ttlMs: 50 });+ cacheOutput('agent-2', 'output', { ttlMs: 5000 });++ await new Promise(resolve => setTimeout(resolve, 60));++ const cleaned = cleanExpired();++ expect(cleaned).toBe(1);+ expect(getOutput('agent-1')).toBeNull();+ expect(getOutput('agent-2')).toBe('output');+ });+ });++ describe('getStats', () => {+ it('should return cache statistics', () => {+ cacheOutput('agent-1', 'output');+ cacheToolResult('tool-1', {}, 'result');+ cacheContext('task-1', 'context');++ getOutput('agent-1');+ getToolResult('tool-1', {});+ getContext('task-1');++ const stats = getStats();++ expect(stats.outputs.size).toBe(1);+ expect(stats.outputs.hits).toBe(1);+ expect(stats.toolResults.size).toBe(1);+ expect(stats.toolResults.hits).toBe(1);+ expect(stats.contexts.size).toBe(1);+ expect(stats.contexts.hits).toBe(1);+ expect(stats.totalSize).toBe(3);+ });++ it('should calculate hit rates', () => {+ cacheOutput('agent-1', 'output');+ getOutput('agent-1'); // hit+ getOutput('agent-2'); // miss++ const stats = getStats();+ expect(stats.outputs.hitRate).toBe('50.0%');+ });++ it('should handle zero hits/misses', () => {+ const stats = getStats();+ expect(stats.outputs.hitRate).toBe('0%');+ });+ });++ describe('getOrComputeOutput', () => {+ it('should return cached value if available', async () => {+ cacheOutput('agent-1', 'cached-output');+ const computeFn = vi.fn(() => 'computed-output');++ const result = await getOrComputeOutput('agent-1', computeFn);++ expect(result.value).toBe('cached-output');+ expect(result.fromCache).toBe(true);+ expect(computeFn).not.toHaveBeenCalled();+ });++ it('should compute and cache if not available', async () => {+ const computeFn = vi.fn(() => 'computed-output');++ const result = await getOrComputeOutput('agent-new', computeFn);++ expect(result.value).toBe('computed-output');+ expect(result.fromCache).toBe(false);+ expect(computeFn).toHaveBeenCalledOnce();++ // Verify it was cached+ expect(getOutput('agent-new')).toBe('computed-output');+ });++ it('should handle async compute function', async () => {+ const computeFn = vi.fn(async () => {+ await new Promise(resolve => setTimeout(resolve, 10));+ return 'async-result';+ });++ const result = await getOrComputeOutput('agent-async', computeFn);++ expect(result.value).toBe('async-result');+ expect(result.fromCache).toBe(false);+ });+ });++ describe('getOrComputeToolResult', () => {+ it('should return cached value if available', async () => {+ cacheToolResult('tool-1', { x: 1 }, 'cached-result');+ const computeFn = vi.fn(() => 'computed-result');++ const result = await getOrComputeToolResult('tool-1', { x: 1 }, computeFn);++ expect(result.value).toBe('cached-result');+ expect(result.fromCache).toBe(true);+ expect(computeFn).not.toHaveBeenCalled();+ });++ it('should compute and cache if not available', async () => {+ const computeFn = vi.fn(() => 'computed-result');++ const result = await getOrComputeToolResult('tool-new', { x: 1 }, computeFn);++ expect(result.value).toBe('computed-result');+ expect(result.fromCache).toBe(false);+ expect(computeFn).toHaveBeenCalledOnce();++ // Verify it was cached+ expect(getToolResult('tool-new', { x: 1 })).toBe('computed-result');+ });+ });++ describe('resetStats', () => {+ it('should reset all statistics', () => {+ cacheOutput('agent-1', 'output');+ getOutput('agent-1');+ getOutput('nonexistent');++ resetStats();++ const stats = getStats();+ expect(stats.outputs.hits).toBe(0);+ expect(stats.outputs.misses).toBe(0);+ expect(stats.totalEvictions).toBe(0);+ });+ });+});diff --git a/server/services/contextUpgrader.js b/server/services/contextUpgrader.jsnew file mode 100644index 0000000000..f45f0a6357--- /dev/null+++ b/server/services/contextUpgrader.js@@ -0,0 +1,331 @@+/**+ * Context Upgrader Service+ *+ * Analyzes if a task needs more context or a heavier model.+ * Provides recommendations for model/context upgrades.+ */++import * as thinkingLevels from './thinkingLevels.js'+import * as localThinking from './localThinking.js'+import { cosEvents } from './cos.js'++// Upgrade triggers+const UPGRADE_TRIGGERS = {+ // Context-based triggers+ longContext: {+ threshold: 5000,+ suggestUpgrade: true,+ suggestHeavyModel: true+ },+ multiFileChange: {+ fileCount: 3,+ suggestUpgrade: true,+ suggestHeavyModel: false+ },++ // Complexity-based triggers+ highComplexity: {+ threshold: 0.7,+ suggestUpgrade: true,+ suggestHeavyModel: true+ },+ architecturalChange: {+ suggestUpgrade: true,+ suggestHeavyModel: true+ },++ // Error-based triggers+ previousFailure: {+ suggestUpgrade: true,+ suggestHeavyModel: true+ },+ consecutiveFailures: {+ threshold: 2,+ suggestUpgrade: true,+ suggestHeavyModel: true+ }+}++// Upgrade history tracking+const upgradeHistory = []+const MAX_HISTORY = 200++/**+ * Analyze if a task needs context or model upgrade+ *+ * @param {Object} task - Task to analyze+ * @param {Object} context - Current context+ * @returns {Promise<Object>} - Upgrade recommendations+ */+async function analyzeTaskNeedsUpgrade(task, context = {}) {+ const recommendations = {+ needsUpgrade: false,+ suggestHeavyModel: false,+ suggestMoreContext: false,+ currentLevel: context.thinkingLevel || 'medium',+ suggestedLevel: null,+ reasons: [],+ confidence: 0+ }++ // Check context length+ const contextLength = context.contextLength || (task.description?.length || 0)+ if (contextLength > UPGRADE_TRIGGERS.longContext.threshold) {+ recommendations.needsUpgrade = true+ recommendations.suggestHeavyModel = true+ recommendations.reasons.push(`Context length (${contextLength}) exceeds threshold`)+ }++ // Check for multi-file changes (from task metadata or keywords)+ const fileReferences = countFileReferences(task.description || '')+ if (fileReferences >= UPGRADE_TRIGGERS.multiFileChange.fileCount) {+ recommendations.needsUpgrade = true+ recommendations.reasons.push(`Multiple file changes detected (${fileReferences} files)`)+ }++ // Get local complexity analysis if available+ const analysis = await localThinking.analyzeTask(task)+ if (analysis.complexity > UPGRADE_TRIGGERS.highComplexity.threshold) {+ recommendations.needsUpgrade = true+ recommendations.suggestHeavyModel = true+ recommendations.reasons.push(`High complexity score (${analysis.complexity.toFixed(2)})`)+ }++ // Check for architectural keywords+ if (hasArchitecturalKeywords(task.description || '')) {+ recommendations.needsUpgrade = true+ recommendations.suggestHeavyModel = true+ recommendations.reasons.push('Architectural change detected')+ }++ // Check for previous failures+ if (context.previousAttempts > 0 && context.previousSuccess === false) {+ recommendations.needsUpgrade = true+ recommendations.suggestHeavyModel = true+ recommendations.reasons.push('Previous attempt failed')+ }++ if (context.consecutiveFailures >= UPGRADE_TRIGGERS.consecutiveFailures.threshold) {+ recommendations.needsUpgrade = true+ recommendations.suggestHeavyModel = true+ recommendations.reasons.push(`${context.consecutiveFailures} consecutive failures`)+ }++ // Determine suggested level+ if (recommendations.needsUpgrade) {+ const suggestedLevel = thinkingLevels.suggestLevel(analysis)+ const currentLevelIndex = Object.keys(thinkingLevels.THINKING_LEVELS).indexOf(recommendations.currentLevel)+ const suggestedLevelIndex = Object.keys(thinkingLevels.THINKING_LEVELS).indexOf(suggestedLevel)++ if (suggestedLevelIndex > currentLevelIndex) {+ recommendations.suggestedLevel = suggestedLevel+ } else if (recommendations.suggestHeavyModel) {+ recommendations.suggestedLevel = thinkingLevels.upgradeLevel(recommendations.currentLevel)+ }++ recommendations.confidence = calculateConfidence(recommendations.reasons.length)+ }++ // Record analysis+ recordUpgradeAnalysis(task.id, recommendations)++ return recommendations+}++/**+ * Count file references in text+ * @param {string} text - Text to analyze+ * @returns {number} - Number of file references+ */+function countFileReferences(text) {+ const filePatterns = [+ /\.(js|ts|jsx|tsx|py|go|rs|java|c|cpp|h|hpp)(?:\s|$|,|:)/g,+ /(?:file|component|module|service|route|model)s?\s*:/gi,+ /(?:create|modify|update|edit|change)\s+(?:the\s+)?(?:file|component)/gi+ ]++ let count = 0+ for (const pattern of filePatterns) {+ const matches = text.match(pattern)+ if (matches) count += matches.length+ }++ return count+}++/**+ * Check for architectural change keywords+ * @param {string} text - Text to analyze+ * @returns {boolean} - True if architectural keywords found+ */+function hasArchitecturalKeywords(text) {+ const keywords = [+ 'architect', 'restructure', 'redesign', 'migration',+ 'refactor entire', 'overhaul', 'rewrite', 'new system',+ 'database schema', 'api design', 'infrastructure'+ ]++ const lower = text.toLowerCase()+ return keywords.some(k => lower.includes(k))+}++/**+ * Calculate confidence score based on trigger count+ * @param {number} triggerCount - Number of triggers hit+ * @returns {number} - Confidence 0-1+ */+function calculateConfidence(triggerCount) {+ if (triggerCount === 0) return 0+ if (triggerCount === 1) return 0.6+ if (triggerCount === 2) return 0.8+ return 0.95+}++/**+ * Record upgrade analysis for learning+ * @param {string} taskId - Task identifier+ * @param {Object} recommendations - Upgrade recommendations+ */+function recordUpgradeAnalysis(taskId, recommendations) {+ upgradeHistory.unshift({+ taskId,+ timestamp: Date.now(),+ needsUpgrade: recommendations.needsUpgrade,+ suggestedLevel: recommendations.suggestedLevel,+ reasons: recommendations.reasons,+ confidence: recommendations.confidence+ })++ while (upgradeHistory.length > MAX_HISTORY) {+ upgradeHistory.pop()+ }+}++/**+ * Record upgrade outcome for learning+ * @param {string} taskId - Task identifier+ * @param {boolean} wasSuccessful - Whether upgrade led to success+ */+function recordUpgradeOutcome(taskId, wasSuccessful) {+ const entry = upgradeHistory.find(h => h.taskId === taskId)+ if (entry) {+ entry.outcome = wasSuccessful ? 'success' : 'failure'+ entry.resolvedAt = Date.now()+ }++ cosEvents.emit('upgrade:outcomeRecorded', { taskId, wasSuccessful })+}++/**+ * Get upgrade statistics+ * @returns {Object} - Upgrade statistics+ */+function getStats() {+ const recent = upgradeHistory.filter(h => h.outcome)+ const upgradedTasks = recent.filter(h => h.needsUpgrade)+ const successfulUpgrades = upgradedTasks.filter(h => h.outcome === 'success')++ return {+ totalAnalyses: upgradeHistory.length,+ upgradesRecommended: upgradeHistory.filter(h => h.needsUpgrade).length,+ upgradeSuccessRate: upgradedTasks.length > 0+ ? ((successfulUpgrades.length / upgradedTasks.length) * 100).toFixed(1) + '%'+ : 'N/A',+ commonReasons: getCommonReasons(),+ recentUpgrades: upgradeHistory.slice(0, 10).map(h => ({+ taskId: h.taskId,+ suggestedLevel: h.suggestedLevel,+ outcome: h.outcome || 'pending'+ }))+ }+}++/**+ * Get most common upgrade reasons+ * @returns {Object} - Reason counts+ */+function getCommonReasons() {+ const reasons = {}++ for (const entry of upgradeHistory) {+ if (!entry.needsUpgrade) continue++ for (const reason of entry.reasons) {+ // Normalize reason+ const normalized = reason.split('(')[0].trim()+ reasons[normalized] = (reasons[normalized] || 0) + 1+ }+ }++ return reasons+}++/**+ * Should upgrade based on quick heuristics (no async)+ * @param {Object} task - Task to check+ * @param {Object} context - Current context+ * @returns {boolean} - True if upgrade likely needed+ */+function quickCheckNeedsUpgrade(task, context = {}) {+ const description = task.description || ''++ // Quick length check+ if (description.length > UPGRADE_TRIGGERS.longContext.threshold) {+ return true+ }++ // Quick keyword check+ if (hasArchitecturalKeywords(description)) {+ return true+ }++ // Priority check+ const priority = task.priority?.toUpperCase()+ if (priority === 'URGENT' || priority === 'CRITICAL') {+ return true+ }++ // Failure check+ if (context.previousSuccess === false) {+ return true+ }++ return false+}++/**+ * Get upgrade history+ * @param {Object} options - Filter options+ * @returns {Array} - Upgrade history+ */+function getHistory(options = {}) {+ let history = [...upgradeHistory]++ if (options.needsUpgrade !== undefined) {+ history = history.filter(h => h.needsUpgrade === options.needsUpgrade)+ }++ if (options.outcome) {+ history = history.filter(h => h.outcome === options.outcome)+ }++ const limit = options.limit || 50+ return history.slice(0, limit)+}++/**+ * Clear upgrade history+ */+function clearHistory() {+ upgradeHistory.length = 0+}++export {+ analyzeTaskNeedsUpgrade,+ recordUpgradeOutcome,+ getStats,+ getHistory,+ clearHistory,+ quickCheckNeedsUpgrade,+ UPGRADE_TRIGGERS+}diff --git a/server/services/cos.js b/server/services/cos.jsindex 9ac9eaa64c..9e2b8362e0 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -18,6 +18,8 @@ import { parseTasksMarkdown, groupTasksByStatus, getNextTask, getAutoApprovedTasimport { isAppOnCooldown, getNextAppForReview, markAppReviewStarted, markIdleReviewStarted } from './appActivity.js';import { getAllApps } from './apps.js';import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getPerformanceSummary, checkAndRehabilitateSkippedTasks } from './taskLearning.js';+import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats } from './eventScheduler.js';+import { generateProactiveTasks as generateMissionTasks, getStats as getMissionStats } from './missions.js';const execAsync = promisify(exec);@@ -57,8 +59,6 @@ export function emitLog(level, message, data = {}, prefix = '') {// In-memory daemon statelet daemonRunning = false;-let evaluationInterval = null;-let healthCheckInterval = null;// Mutex lock for state operations to prevent race conditionslet stateLock = Promise.resolve();@@ -270,15 +270,27 @@ export async function start() {// Then reset any orphaned in_progress tasks (no running agent)await resetOrphanedTasks();- // Start evaluation loop- evaluationInterval = setInterval(async () => {- await evaluateTasks();- }, state.config.evaluationIntervalMs);+ // Start evaluation loop using event scheduler+ scheduleEvent({+ id: 'cos-evaluation',+ type: 'interval',+ intervalMs: state.config.evaluationIntervalMs,+ handler: async () => {+ await evaluateTasks();+ },+ metadata: { description: 'CoS task evaluation loop' }+ });- // Start health check loop- healthCheckInterval = setInterval(async () => {- await runHealthCheck();- }, state.config.healthCheckIntervalMs);+ // Start health check loop using event scheduler+ scheduleEvent({+ id: 'cos-health-check',+ type: 'interval',+ intervalMs: state.config.healthCheckIntervalMs,+ handler: async () => {+ await runHealthCheck();+ },+ metadata: { description: 'CoS health check loop' }+ });// Run initial evaluation and health checkemitLog('info', 'Running initial task evaluation...');@@ -298,15 +310,9 @@ export async function stop() {return { success: false, error: 'Not running' };}- // Clear intervals- if (evaluationInterval) {- clearInterval(evaluationInterval);- evaluationInterval = null;- }- if (healthCheckInterval) {- clearInterval(healthCheckInterval);- healthCheckInterval = null;- }+ // Cancel scheduled events+ cancelEvent('cos-evaluation');+ cancelEvent('cos-health-check');const state = await loadState();state.running = false;@@ -552,7 +558,33 @@ export async function evaluateTasks() {await queueEligibleImprovementTasks(state, cosTaskData);}- // Priority 3: Only generate direct idle task if:+ // Priority 3: Mission-driven proactive tasks (if no user tasks)+ if (tasksToSpawn.length < availableSlots && !hasPendingUserTasks && state.config.proactiveMode) {+ const missionTasks = await generateMissionTasks({ maxTasks: availableSlots - tasksToSpawn.length }).catch(err => {+ emitLog('debug', `Mission task generation failed: ${err.message}`);+ return [];+ });++ for (const missionTask of missionTasks) {+ if (tasksToSpawn.length >= availableSlots) break;+ // Convert mission task to COS task format+ tasksToSpawn.push({+ id: missionTask.id,+ description: missionTask.description,+ priority: missionTask.priority?.toUpperCase() || 'MEDIUM',+ status: 'pending',+ metadata: missionTask.metadata,+ taskType: 'internal',+ approvalRequired: !missionTask.autoApprove+ });+ emitLog('info', `Generated mission task: ${missionTask.id} (${missionTask.metadata?.missionName})`, {+ missionId: missionTask.metadata?.missionId,+ appId: missionTask.metadata?.appId+ });+ }+ }++ // Priority 4: Only generate direct idle task if:// 1. Nothing to spawn// 2. No pending user tasks (even on cooldown)// 3. No system tasks queueddiff --git a/server/services/cosEvolution.js b/server/services/cosEvolution.jsnew file mode 100644index 0000000000..a172d50eb2--- /dev/null+++ b/server/services/cosEvolution.js@@ -0,0 +1,409 @@+/**+ * COS Evolution Service+ *+ * Enables COS to propose and execute self-modifications:+ * - Base model changes+ * - Threshold adjustments+ * - Model downloads+ *+ * Full autonomy - COS can evolve without user approval.+ * Changes are logged for transparency.+ */++import { promises as fs } from 'fs'+import path from 'path'+import { v4 as uuidv4 } from 'uuid'+import { cosEvents } from './cos.js'+import * as lmStudioManager from './lmStudioManager.js'++const DATA_DIR = path.join(process.cwd(), 'data', 'cos')+const EVOLUTION_FILE = path.join(DATA_DIR, 'evolution.json')++// Default evolution state+const DEFAULT_STATE = {+ currentBaseModel: 'gpt-oss-20b',+ currentThinkingThresholds: {+ contextLength: { low: 1000, medium: 3000, high: 6000 },+ complexity: { low: 0.4, medium: 0.6, high: 0.8 }+ },+ proposals: [],+ evolutionHistory: [],+ performanceBaseline: {+ successRate: 0.7,+ avgDurationMs: 60000,+ recordedAt: null+ },+ settings: {+ autoApproveModelChanges: true, // Full autonomy+ autoApproveThresholdChanges: true,+ rollbackThreshold: 0.2, // Rollback if success rate drops >20%+ minTasksBeforeEvaluation: 50 // Evaluate after 50 tasks+ }+}++// In-memory state+let evolutionState = null++/**+ * Ensure data directory exists+ */+async function ensureDataDir() {+ await fs.mkdir(DATA_DIR, { recursive: true })+}++/**+ * Load evolution state+ * @returns {Promise<Object>} - Evolution state+ */+async function loadState() {+ if (evolutionState) return evolutionState++ await ensureDataDir()++ const exists = await fs.access(EVOLUTION_FILE).then(() => true).catch(() => false)+ if (exists) {+ const content = await fs.readFile(EVOLUTION_FILE, 'utf-8')+ evolutionState = JSON.parse(content)+ } else {+ evolutionState = { ...DEFAULT_STATE }+ }++ return evolutionState+}++/**+ * Save evolution state+ */+async function saveState() {+ await ensureDataDir()+ await fs.writeFile(EVOLUTION_FILE, JSON.stringify(evolutionState, null, 2))+}++/**+ * Get current evolution state+ * @returns {Promise<Object>} - Current state+ */+async function getState() {+ return loadState()+}++/**+ * Propose a base model change+ * With full autonomy, this executes immediately.+ *+ * @param {string} newModel - New model identifier+ * @param {string} reasoning - Reasoning for change+ * @returns {Promise<Object>} - Proposal result+ */+async function proposeBaseModelChange(newModel, reasoning) {+ const state = await loadState()+ const proposal = {+ id: uuidv4(),+ type: 'base-model-change',+ currentModel: state.currentBaseModel,+ proposedModel: newModel,+ reasoning,+ createdAt: new Date().toISOString(),+ status: 'approved', // Auto-approved with full autonomy+ executedAt: null,+ result: null+ }++ state.proposals.push(proposal)++ // Execute immediately (full autonomy)+ const result = await executeBaseModelChange(proposal.id)++ await saveState()++ console.log(`🧬 Evolution: Base model changed ${proposal.currentModel} → ${newModel}`)+ cosEvents.emit('evolution:modelChanged', {+ from: proposal.currentModel,+ to: newModel,+ reasoning+ })++ return result+}++/**+ * Execute a base model change+ * @param {string} proposalId - Proposal to execute+ * @returns {Promise<Object>} - Execution result+ */+async function executeBaseModelChange(proposalId) {+ const state = await loadState()+ const proposal = state.proposals.find(p => p.id === proposalId)++ if (!proposal) {+ return { success: false, error: 'Proposal not found' }+ }++ // Record the change+ const previousModel = state.currentBaseModel+ state.currentBaseModel = proposal.proposedModel+ proposal.executedAt = new Date().toISOString()+ proposal.status = 'executed'++ // Record in history+ state.evolutionHistory.push({+ type: 'base-model-change',+ from: previousModel,+ to: proposal.proposedModel,+ reasoning: proposal.reasoning,+ executedAt: proposal.executedAt+ })++ await saveState()++ return {+ success: true,+ previousModel,+ newModel: proposal.proposedModel+ }+}++/**+ * Request a model download+ * @param {string} modelId - Model to download+ * @param {string} purpose - Why this model is needed+ * @returns {Promise<Object>} - Download result+ */+async function requestModelDownload(modelId, purpose) {+ const state = await loadState()++ // Record the request+ state.evolutionHistory.push({+ type: 'model-download-request',+ modelId,+ purpose,+ requestedAt: new Date().toISOString()+ })++ await saveState()++ // Attempt download via LM Studio+ const result = await lmStudioManager.downloadModel(modelId)++ console.log(`📥 Evolution: Model download requested - ${modelId}`)+ cosEvents.emit('evolution:downloadRequested', { modelId, purpose, result })++ return result+}++/**+ * Adjust thinking thresholds+ * @param {string} thresholdType - 'contextLength' or 'complexity'+ * @param {Object} newValues - New threshold values+ * @param {string} reasoning - Reasoning for change+ * @returns {Promise<Object>} - Adjustment result+ */+async function adjustThinkingThreshold(thresholdType, newValues, reasoning) {+ const state = await loadState()++ if (!state.currentThinkingThresholds[thresholdType]) {+ return { success: false, error: 'Unknown threshold type' }+ }++ const previousValues = { ...state.currentThinkingThresholds[thresholdType] }++ // Apply new values+ Object.assign(state.currentThinkingThresholds[thresholdType], newValues)++ // Record in history+ state.evolutionHistory.push({+ type: 'threshold-adjustment',+ thresholdType,+ from: previousValues,+ to: state.currentThinkingThresholds[thresholdType],+ reasoning,+ executedAt: new Date().toISOString()+ })++ await saveState()++ console.log(`🎚️ Evolution: Threshold ${thresholdType} adjusted`)+ cosEvents.emit('evolution:thresholdAdjusted', {+ thresholdType,+ from: previousValues,+ to: state.currentThinkingThresholds[thresholdType],+ reasoning+ })++ return {+ success: true,+ thresholdType,+ previousValues,+ newValues: state.currentThinkingThresholds[thresholdType]+ }+}++/**+ * Record performance metrics for baseline comparison+ * @param {Object} metrics - Current performance metrics+ */+async function recordPerformanceMetrics(metrics) {+ const state = await loadState()++ const previous = { ...state.performanceBaseline }++ state.performanceBaseline = {+ successRate: metrics.successRate,+ avgDurationMs: metrics.avgDurationMs,+ taskCount: metrics.taskCount || 0,+ recordedAt: new Date().toISOString()+ }++ // Check for significant drop requiring rollback+ if (previous.successRate && metrics.successRate) {+ const drop = previous.successRate - metrics.successRate+ if (drop > state.settings.rollbackThreshold) {+ console.log(`⚠️ Evolution: Performance drop detected (${(drop * 100).toFixed(1)}%)`)+ cosEvents.emit('evolution:performanceDrop', {+ previousRate: previous.successRate,+ currentRate: metrics.successRate,+ dropPercent: drop * 100+ })+ // Could trigger automatic rollback here+ }+ }++ await saveState()+}++/**+ * Rollback to previous base model+ * @param {string} reason - Reason for rollback+ * @returns {Promise<Object>} - Rollback result+ */+async function rollbackBaseModel(reason) {+ const state = await loadState()++ // Find the previous model change in history+ const modelChanges = state.evolutionHistory+ .filter(e => e.type === 'base-model-change')+ .reverse()++ if (modelChanges.length < 2) {+ return { success: false, error: 'No previous model to rollback to' }+ }++ const previousChange = modelChanges[1]+ const currentModel = state.currentBaseModel+ const rollbackTo = previousChange.from++ state.currentBaseModel = rollbackTo++ state.evolutionHistory.push({+ type: 'rollback',+ from: currentModel,+ to: rollbackTo,+ reason,+ executedAt: new Date().toISOString()+ })++ await saveState()++ console.log(`⏪ Evolution: Rolled back to ${rollbackTo}`)+ cosEvents.emit('evolution:rollback', {+ from: currentModel,+ to: rollbackTo,+ reason+ })++ return {+ success: true,+ previousModel: currentModel,+ restoredModel: rollbackTo+ }+}++/**+ * Get evolution history+ * @param {Object} options - Filter options+ * @returns {Promise<Array>} - Evolution history+ */+async function getHistory(options = {}) {+ const state = await loadState()+ let history = [...state.evolutionHistory]++ if (options.type) {+ history = history.filter(e => e.type === options.type)+ }++ // Sort by date descending+ history.sort((a, b) =>+ new Date(b.executedAt || b.requestedAt).getTime() -+ new Date(a.executedAt || a.requestedAt).getTime()+ )++ const limit = options.limit || 50+ return history.slice(0, limit)+}++/**+ * Get pending proposals (for display, though auto-approved)+ * @returns {Promise<Array>} - Pending proposals+ */+async function getPendingProposals() {+ const state = await loadState()+ return state.proposals.filter(p => p.status === 'pending')+}++/**+ * Get evolution statistics+ * @returns {Promise<Object>} - Evolution stats+ */+async function getStats() {+ const state = await loadState()++ const byType = {}+ for (const entry of state.evolutionHistory) {+ byType[entry.type] = (byType[entry.type] || 0) + 1+ }++ return {+ currentBaseModel: state.currentBaseModel,+ currentThresholds: state.currentThinkingThresholds,+ performanceBaseline: state.performanceBaseline,+ totalEvolutions: state.evolutionHistory.length,+ byType,+ pendingProposals: state.proposals.filter(p => p.status === 'pending').length,+ settings: state.settings+ }+}++/**+ * Update evolution settings+ * @param {Object} newSettings - Settings to update+ * @returns {Promise<Object>} - Updated settings+ */+async function updateSettings(newSettings) {+ const state = await loadState()++ Object.assign(state.settings, newSettings)+ await saveState()++ return state.settings+}++/**+ * Invalidate cache+ */+function invalidateCache() {+ evolutionState = null+}++export {+ getState,+ proposeBaseModelChange,+ requestModelDownload,+ adjustThinkingThreshold,+ recordPerformanceMetrics,+ rollbackBaseModel,+ getHistory,+ getPendingProposals,+ getStats,+ updateSettings,+ invalidateCache+}diff --git a/server/services/errorRecovery.js b/server/services/errorRecovery.jsnew file mode 100644index 0000000000..c81c15a52e--- /dev/null+++ b/server/services/errorRecovery.js@@ -0,0 +1,515 @@+/**+ * Error Recovery Service+ *+ * Analyzes errors and selects appropriate recovery strategies.+ * Provides structured error handling for agent operations.+ */++import { cosEvents } from './cos.js'++// Recovery strategies+const STRATEGIES = {+ RETRY: 'retry', // Simple retry with backoff+ ESCALATE: 'escalate', // Use a more powerful model+ FALLBACK: 'fallback', // Use fallback provider+ DECOMPOSE: 'decompose', // Break task into smaller parts+ DEFER: 'defer', // Reschedule for later+ INVESTIGATE: 'investigate', // Create investigation task+ SKIP: 'skip', // Skip and move on+ MANUAL: 'manual' // Require human intervention+}++// Error categories for pattern matching+const ERROR_PATTERNS = {+ // Rate limiting+ rateLimit: {+ patterns: [+ /rate.?limit/i,+ /too many requests/i,+ /429/,+ /quota exceeded/i,+ /throttl/i+ ],+ strategies: [STRATEGIES.DEFER, STRATEGIES.FALLBACK],+ cooldownMs: 60000+ },++ // Authentication+ auth: {+ patterns: [+ /unauthorized/i,+ /authentication/i,+ /invalid.*key/i,+ /403/,+ /401/,+ /api.?key/i+ ],+ strategies: [STRATEGIES.FALLBACK, STRATEGIES.MANUAL],+ cooldownMs: 0+ },++ // Model unavailable+ modelUnavailable: {+ patterns: [+ /model.*not.*found/i,+ /model.*unavailable/i,+ /model.*overloaded/i,+ /503/,+ /capacity/i+ ],+ strategies: [STRATEGIES.FALLBACK, STRATEGIES.DEFER],+ cooldownMs: 30000+ },++ // Context too long+ contextLength: {+ patterns: [+ /context.*length/i,+ /token.*limit/i,+ /maximum.*tokens/i,+ /too.*long/i,+ /input.*too.*large/i+ ],+ strategies: [STRATEGIES.DECOMPOSE],+ cooldownMs: 0+ },++ // Network issues+ network: {+ patterns: [+ /network/i,+ /timeout/i,+ /ECONNREFUSED/,+ /ETIMEDOUT/,+ /ENOTFOUND/,+ /connection.*reset/i,+ /socket.*hang.*up/i+ ],+ strategies: [STRATEGIES.RETRY, STRATEGIES.DEFER],+ cooldownMs: 5000+ },++ // Content filtering+ contentFilter: {+ patterns: [+ /content.*filter/i,+ /safety/i,+ /refus/i,+ /cannot.*help/i,+ /inappropriate/i+ ],+ strategies: [STRATEGIES.INVESTIGATE, STRATEGIES.SKIP],+ cooldownMs: 0+ },++ // Resource exhaustion+ resource: {+ patterns: [+ /out of memory/i,+ /memory.*limit/i,+ /disk.*space/i,+ /no.*space/i+ ],+ strategies: [STRATEGIES.DEFER, STRATEGIES.MANUAL],+ cooldownMs: 300000+ },++ // Process errors+ process: {+ patterns: [+ /process.*exit/i,+ /killed/i,+ /signal/i,+ /zombie/i+ ],+ strategies: [STRATEGIES.RETRY, STRATEGIES.INVESTIGATE],+ cooldownMs: 10000+ }+}++// Recovery attempt tracking+const recoveryAttempts = new Map()+const MAX_RECOVERY_ATTEMPTS = 3+const ATTEMPT_RESET_MS = 3600000 // 1 hour++// Recovery history+const recoveryHistory = []+const MAX_HISTORY = 200++/**+ * Analyze an error to determine its category and recommended recovery+ * @param {Error|Object} error - Error to analyze+ * @param {Object} context - Additional context+ * @returns {Object} - Error analysis result+ */+function analyzeError(error, context = {}) {+ const errorMessage = error?.message || error?.error || String(error)+ const errorCode = error?.code || error?.status++ let category = 'unknown'+ let patterns = []+ let suggestedStrategies = [STRATEGIES.RETRY]+ let cooldownMs = 0++ // Match against known patterns+ for (const [cat, config] of Object.entries(ERROR_PATTERNS)) {+ for (const pattern of config.patterns) {+ if (pattern.test(errorMessage) || (errorCode && pattern.test(String(errorCode)))) {+ category = cat+ patterns = config.patterns.map(p => p.source)+ suggestedStrategies = config.strategies+ cooldownMs = config.cooldownMs+ break+ }+ }+ if (category !== 'unknown') break+ }++ return {+ category,+ message: errorMessage.substring(0, 500),+ code: errorCode,+ matchedPatterns: patterns,+ suggestedStrategies,+ cooldownMs,+ severity: getSeverity(category),+ recoverable: suggestedStrategies[0] !== STRATEGIES.MANUAL,+ context: {+ taskId: context.taskId,+ agentId: context.agentId,+ provider: context.provider,+ model: context.model+ }+ }+}++/**+ * Get severity level for error category+ * @param {string} category - Error category+ * @returns {string} - Severity level+ */+function getSeverity(category) {+ const severities = {+ rateLimit: 'medium',+ auth: 'high',+ modelUnavailable: 'medium',+ contextLength: 'low',+ network: 'medium',+ contentFilter: 'low',+ resource: 'high',+ process: 'medium',+ unknown: 'medium'+ }+ return severities[category] || 'medium'+}++/**+ * Select the best recovery strategy based on analysis and history+ * @param {Object} analysis - Error analysis from analyzeError()+ * @param {Object} options - Recovery options+ * @returns {Object} - Selected strategy with parameters+ */+function selectRecoveryStrategy(analysis, options = {}) {+ const { taskId, agentId, attemptNumber = 1 } = options++ // Check if max attempts reached+ const attemptKey = `${taskId || agentId || 'global'}`+ const attempts = getAttemptCount(attemptKey)++ if (attempts >= MAX_RECOVERY_ATTEMPTS) {+ return {+ strategy: STRATEGIES.MANUAL,+ reason: 'Maximum recovery attempts exceeded',+ params: { requiresApproval: true }+ }+ }++ // Get first viable strategy+ const strategy = analysis.suggestedStrategies[0] || STRATEGIES.RETRY++ // Calculate backoff for retries+ let params = {}+ if (strategy === STRATEGIES.RETRY || strategy === STRATEGIES.DEFER) {+ const baseDelay = analysis.cooldownMs || 5000+ const backoffDelay = baseDelay * Math.pow(2, attempts)+ params.delayMs = Math.min(backoffDelay, 300000) // Max 5 minutes+ }++ if (strategy === STRATEGIES.ESCALATE) {+ params.suggestHeavyModel = true+ }++ if (strategy === STRATEGIES.DECOMPOSE) {+ params.suggestSmallerContext = true+ params.maxChunkSize = 2000+ }++ if (strategy === STRATEGIES.FALLBACK) {+ params.useFallbackProvider = true+ }++ return {+ strategy,+ reason: `Error category: ${analysis.category}`,+ params,+ attemptNumber: attempts + 1,+ maxAttempts: MAX_RECOVERY_ATTEMPTS+ }+}++/**+ * Get recovery attempt count for a key+ * @param {string} key - Attempt tracking key+ * @returns {number} - Current attempt count+ */+function getAttemptCount(key) {+ const record = recoveryAttempts.get(key)+ if (!record) return 0++ // Reset if too old+ if (Date.now() - record.lastAttempt > ATTEMPT_RESET_MS) {+ recoveryAttempts.delete(key)+ return 0+ }++ return record.count+}++/**+ * Record a recovery attempt+ * @param {string} key - Attempt tracking key+ * @param {Object} data - Attempt data+ */+function recordAttempt(key, data = {}) {+ const record = recoveryAttempts.get(key) || { count: 0, history: [] }++ record.count+++ record.lastAttempt = Date.now()+ record.history.push({+ timestamp: Date.now(),+ strategy: data.strategy,+ success: data.success+ })++ // Keep only last 5 attempts in history+ if (record.history.length > 5) {+ record.history.shift()+ }++ recoveryAttempts.set(key, record)+}++/**+ * Execute a recovery strategy+ * @param {string} strategy - Strategy name+ * @param {Object} task - Original task+ * @param {Object} error - Original error+ * @param {Object} params - Strategy parameters+ * @returns {Promise<Object>} - Recovery result+ */+async function executeRecovery(strategy, task, error, params = {}) {+ const startTime = Date.now()+ const attemptKey = task?.id || 'global'++ recordAttempt(attemptKey, { strategy, success: null })++ let result = { success: false, strategy, action: null }++ switch (strategy) {+ case STRATEGIES.RETRY:+ if (params.delayMs) {+ await new Promise(resolve => setTimeout(resolve, params.delayMs))+ }+ result = {+ success: true,+ strategy,+ action: 'retry_now',+ message: `Retry after ${params.delayMs}ms delay`+ }+ break++ case STRATEGIES.DEFER:+ result = {+ success: true,+ strategy,+ action: 'reschedule',+ rescheduleAfterMs: params.delayMs || 60000,+ message: `Task rescheduled for ${params.delayMs}ms later`+ }+ break++ case STRATEGIES.FALLBACK:+ result = {+ success: true,+ strategy,+ action: 'use_fallback',+ useFallback: true,+ message: 'Switching to fallback provider'+ }+ break++ case STRATEGIES.ESCALATE:+ result = {+ success: true,+ strategy,+ action: 'escalate_model',+ useHeavyModel: true,+ message: 'Escalating to heavy model'+ }+ break++ case STRATEGIES.DECOMPOSE:+ result = {+ success: true,+ strategy,+ action: 'decompose_task',+ maxChunkSize: params.maxChunkSize || 2000,+ message: 'Breaking task into smaller chunks'+ }+ break++ case STRATEGIES.INVESTIGATE:+ result = {+ success: true,+ strategy,+ action: 'create_investigation',+ createInvestigationTask: true,+ originalError: error?.message,+ message: 'Creating investigation task'+ }+ break++ case STRATEGIES.SKIP:+ result = {+ success: true,+ strategy,+ action: 'skip_task',+ skipped: true,+ message: 'Task skipped due to unrecoverable error'+ }+ break++ case STRATEGIES.MANUAL:+ result = {+ success: false,+ strategy,+ action: 'require_manual',+ requiresManualIntervention: true,+ message: 'Manual intervention required'+ }+ break++ default:+ result = {+ success: false,+ strategy,+ action: 'unknown_strategy',+ message: `Unknown strategy: ${strategy}`+ }+ }++ // Update attempt record with result+ const record = recoveryAttempts.get(attemptKey)+ if (record && record.history.length > 0) {+ record.history[record.history.length - 1].success = result.success+ }++ // Add to history+ recoveryHistory.unshift({+ timestamp: Date.now(),+ taskId: task?.id,+ errorCategory: error?.category || 'unknown',+ strategy,+ success: result.success,+ durationMs: Date.now() - startTime+ })++ while (recoveryHistory.length > MAX_HISTORY) {+ recoveryHistory.pop()+ }++ // Emit event+ cosEvents.emit('recovery:executed', {+ taskId: task?.id,+ strategy,+ success: result.success,+ action: result.action+ })++ return result+}++/**+ * Get recovery statistics+ * @returns {Object} - Recovery stats+ */+function getStats() {+ const recent = recoveryHistory.slice(0, 100)+ const successCount = recent.filter(r => r.success).length++ const byStrategy = {}+ const byCategory = {}++ for (const record of recent) {+ byStrategy[record.strategy] = (byStrategy[record.strategy] || 0) + 1+ byCategory[record.errorCategory] = (byCategory[record.errorCategory] || 0) + 1+ }++ return {+ totalAttempts: recoveryHistory.length,+ recentAttempts: recent.length,+ successRate: recent.length > 0 ? ((successCount / recent.length) * 100).toFixed(1) + '%' : '0%',+ byStrategy,+ byCategory,+ activeAttemptKeys: recoveryAttempts.size+ }+}++/**+ * Get recovery history+ * @param {Object} options - Filter options+ * @returns {Array} - Recovery history+ */+function getHistory(options = {}) {+ let history = [...recoveryHistory]++ if (options.strategy) {+ history = history.filter(r => r.strategy === options.strategy)+ }++ if (options.success !== undefined) {+ history = history.filter(r => r.success === options.success)+ }++ const limit = options.limit || 50+ return history.slice(0, limit)+}++/**+ * Reset attempt counter for a key+ * @param {string} key - Attempt tracking key+ */+function resetAttempts(key) {+ recoveryAttempts.delete(key)+}++/**+ * Clear all attempt counters+ */+function clearAllAttempts() {+ recoveryAttempts.clear()+}++export {+ STRATEGIES,+ ERROR_PATTERNS,+ analyzeError,+ selectRecoveryStrategy,+ executeRecovery,+ recordAttempt,+ getAttemptCount,+ getStats,+ getHistory,+ resetAttempts,+ clearAllAttempts+}diff --git a/server/services/errorRecovery.test.js b/server/services/errorRecovery.test.jsnew file mode 100644index 0000000000..2d726c88e2--- /dev/null+++ b/server/services/errorRecovery.test.js@@ -0,0 +1,389 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import {+ STRATEGIES,+ ERROR_PATTERNS,+ analyzeError,+ selectRecoveryStrategy,+ executeRecovery,+ recordAttempt,+ getAttemptCount,+ getStats,+ getHistory,+ resetAttempts,+ clearAllAttempts+} from './errorRecovery.js';++// Mock the cosEvents+vi.mock('./cos.js', () => ({+ cosEvents: {+ emit: vi.fn()+ }+}));++describe('Error Recovery Service', () => {+ beforeEach(() => {+ clearAllAttempts();+ });++ describe('STRATEGIES', () => {+ it('should have all required strategies', () => {+ expect(STRATEGIES.RETRY).toBe('retry');+ expect(STRATEGIES.ESCALATE).toBe('escalate');+ expect(STRATEGIES.FALLBACK).toBe('fallback');+ expect(STRATEGIES.DECOMPOSE).toBe('decompose');+ expect(STRATEGIES.DEFER).toBe('defer');+ expect(STRATEGIES.INVESTIGATE).toBe('investigate');+ expect(STRATEGIES.SKIP).toBe('skip');+ expect(STRATEGIES.MANUAL).toBe('manual');+ });+ });++ describe('ERROR_PATTERNS', () => {+ it('should have patterns for rate limiting', () => {+ expect(ERROR_PATTERNS.rateLimit).toBeDefined();+ expect(ERROR_PATTERNS.rateLimit.patterns.length).toBeGreaterThan(0);+ });++ it('should have patterns for auth errors', () => {+ expect(ERROR_PATTERNS.auth).toBeDefined();+ expect(ERROR_PATTERNS.auth.strategies).toContain(STRATEGIES.FALLBACK);+ });++ it('should have patterns for network errors', () => {+ expect(ERROR_PATTERNS.network).toBeDefined();+ expect(ERROR_PATTERNS.network.cooldownMs).toBe(5000);+ });+ });++ describe('analyzeError', () => {+ it('should categorize rate limit errors', () => {+ const result = analyzeError({ message: 'Rate limit exceeded' });++ expect(result.category).toBe('rateLimit');+ expect(result.suggestedStrategies).toContain(STRATEGIES.DEFER);+ });++ it('should categorize auth errors', () => {+ const result = analyzeError({ message: 'Unauthorized access' });++ expect(result.category).toBe('auth');+ expect(result.severity).toBe('high');+ });++ it('should categorize model unavailable errors', () => {+ const result = analyzeError({ message: 'Model not found', code: 503 });++ expect(result.category).toBe('modelUnavailable');+ expect(result.suggestedStrategies).toContain(STRATEGIES.FALLBACK);+ });++ it('should categorize context length errors', () => {+ const result = analyzeError({ message: 'Token limit exceeded' });++ expect(result.category).toBe('contextLength');+ expect(result.suggestedStrategies).toContain(STRATEGIES.DECOMPOSE);+ });++ it('should categorize network errors', () => {+ const result = analyzeError({ message: 'ECONNREFUSED' });++ expect(result.category).toBe('network');+ expect(result.suggestedStrategies).toContain(STRATEGIES.RETRY);+ });++ it('should return unknown for unrecognized errors', () => {+ const result = analyzeError({ message: 'Some random error' });++ expect(result.category).toBe('unknown');+ expect(result.suggestedStrategies).toContain(STRATEGIES.RETRY);+ });++ it('should include context when provided', () => {+ const result = analyzeError(+ { message: 'Error' },+ { taskId: 'task-1', agentId: 'agent-1' }+ );++ expect(result.context.taskId).toBe('task-1');+ expect(result.context.agentId).toBe('agent-1');+ });++ it('should truncate long error messages', () => {+ const longMessage = 'x'.repeat(1000);+ const result = analyzeError({ message: longMessage });++ expect(result.message.length).toBeLessThanOrEqual(500);+ });++ it('should mark manual strategies as not recoverable', () => {+ const result = analyzeError({ message: 'Unknown critical failure' });+ // Most errors should be recoverable by default+ expect(result.recoverable).toBe(true);+ });+ });++ describe('selectRecoveryStrategy', () => {+ it('should select first suggested strategy', () => {+ const analysis = {+ suggestedStrategies: [STRATEGIES.FALLBACK, STRATEGIES.DEFER],+ cooldownMs: 5000+ };++ const result = selectRecoveryStrategy(analysis);++ expect(result.strategy).toBe(STRATEGIES.FALLBACK);+ });++ it('should calculate backoff delay for retry', () => {+ const analysis = {+ suggestedStrategies: [STRATEGIES.RETRY],+ cooldownMs: 1000+ };++ const result = selectRecoveryStrategy(analysis);++ expect(result.params.delayMs).toBeDefined();+ expect(result.params.delayMs).toBeGreaterThanOrEqual(1000);+ });++ it('should increase delay for subsequent attempts', () => {+ const analysis = {+ suggestedStrategies: [STRATEGIES.RETRY],+ cooldownMs: 1000+ };++ recordAttempt('test-task');+ recordAttempt('test-task');++ const result = selectRecoveryStrategy(analysis, { taskId: 'test-task' });++ // Delay should be exponentially higher+ expect(result.params.delayMs).toBeGreaterThan(1000);+ });++ it('should return MANUAL when max attempts exceeded', () => {+ // Exhaust attempts+ for (let i = 0; i < 3; i++) {+ recordAttempt('exhausted-task');+ }++ const analysis = { suggestedStrategies: [STRATEGIES.RETRY] };+ const result = selectRecoveryStrategy(analysis, { taskId: 'exhausted-task' });++ expect(result.strategy).toBe(STRATEGIES.MANUAL);+ expect(result.reason).toContain('Maximum recovery attempts');+ });++ it('should set params for escalate strategy', () => {+ const analysis = { suggestedStrategies: [STRATEGIES.ESCALATE] };+ const result = selectRecoveryStrategy(analysis);++ expect(result.params.suggestHeavyModel).toBe(true);+ });++ it('should set params for decompose strategy', () => {+ const analysis = { suggestedStrategies: [STRATEGIES.DECOMPOSE] };+ const result = selectRecoveryStrategy(analysis);++ expect(result.params.suggestSmallerContext).toBe(true);+ expect(result.params.maxChunkSize).toBeDefined();+ });+ });++ describe('executeRecovery', () => {+ it('should execute retry strategy', async () => {+ const result = await executeRecovery(+ STRATEGIES.RETRY,+ { id: 'task-1' },+ { message: 'Error' },+ { delayMs: 10 }+ );++ expect(result.success).toBe(true);+ expect(result.action).toBe('retry_now');+ });++ it('should execute defer strategy', async () => {+ const result = await executeRecovery(+ STRATEGIES.DEFER,+ { id: 'task-1' },+ { message: 'Error' },+ { delayMs: 1000 }+ );++ expect(result.success).toBe(true);+ expect(result.action).toBe('reschedule');+ expect(result.rescheduleAfterMs).toBe(1000);+ });++ it('should execute fallback strategy', async () => {+ const result = await executeRecovery(+ STRATEGIES.FALLBACK,+ { id: 'task-1' },+ { message: 'Error' }+ );++ expect(result.success).toBe(true);+ expect(result.action).toBe('use_fallback');+ expect(result.useFallback).toBe(true);+ });++ it('should execute escalate strategy', async () => {+ const result = await executeRecovery(+ STRATEGIES.ESCALATE,+ { id: 'task-1' },+ { message: 'Error' }+ );++ expect(result.success).toBe(true);+ expect(result.action).toBe('escalate_model');+ expect(result.useHeavyModel).toBe(true);+ });++ it('should execute decompose strategy', async () => {+ const result = await executeRecovery(+ STRATEGIES.DECOMPOSE,+ { id: 'task-1' },+ { message: 'Error' },+ { maxChunkSize: 1000 }+ );++ expect(result.success).toBe(true);+ expect(result.action).toBe('decompose_task');+ expect(result.maxChunkSize).toBe(1000);+ });++ it('should execute investigate strategy', async () => {+ const result = await executeRecovery(+ STRATEGIES.INVESTIGATE,+ { id: 'task-1' },+ { message: 'Weird error' }+ );++ expect(result.success).toBe(true);+ expect(result.action).toBe('create_investigation');+ expect(result.createInvestigationTask).toBe(true);+ });++ it('should execute skip strategy', async () => {+ const result = await executeRecovery(+ STRATEGIES.SKIP,+ { id: 'task-1' },+ { message: 'Error' }+ );++ expect(result.success).toBe(true);+ expect(result.action).toBe('skip_task');+ expect(result.skipped).toBe(true);+ });++ it('should execute manual strategy as unsuccessful', async () => {+ const result = await executeRecovery(+ STRATEGIES.MANUAL,+ { id: 'task-1' },+ { message: 'Error' }+ );++ expect(result.success).toBe(false);+ expect(result.action).toBe('require_manual');+ expect(result.requiresManualIntervention).toBe(true);+ });++ it('should handle unknown strategy', async () => {+ const result = await executeRecovery(+ 'unknown',+ { id: 'task-1' },+ { message: 'Error' }+ );++ expect(result.success).toBe(false);+ expect(result.action).toBe('unknown_strategy');+ });+ });++ describe('recordAttempt', () => {+ it('should increment attempt count', () => {+ expect(getAttemptCount('test-key')).toBe(0);++ recordAttempt('test-key');+ expect(getAttemptCount('test-key')).toBe(1);++ recordAttempt('test-key');+ expect(getAttemptCount('test-key')).toBe(2);+ });++ it('should track different keys separately', () => {+ recordAttempt('key-1');+ recordAttempt('key-2');+ recordAttempt('key-2');++ expect(getAttemptCount('key-1')).toBe(1);+ expect(getAttemptCount('key-2')).toBe(2);+ });+ });++ describe('getStats', () => {+ it('should return recovery statistics', async () => {+ await executeRecovery(STRATEGIES.RETRY, { id: 'task-1' }, {}, { delayMs: 1 });+ await executeRecovery(STRATEGIES.FALLBACK, { id: 'task-2' }, {});++ const stats = getStats();++ expect(stats.totalAttempts).toBeGreaterThan(0);+ expect(stats.byStrategy[STRATEGIES.RETRY]).toBeDefined();+ expect(stats.successRate).toBeDefined();+ });+ });++ describe('getHistory', () => {+ it('should return recovery history', async () => {+ await executeRecovery(STRATEGIES.RETRY, { id: 'task-1' }, {}, { delayMs: 1 });++ const history = getHistory();++ expect(history.length).toBeGreaterThan(0);+ expect(history[0].strategy).toBe(STRATEGIES.RETRY);+ });++ it('should filter by strategy', async () => {+ await executeRecovery(STRATEGIES.RETRY, { id: 'task-1' }, {}, { delayMs: 1 });+ await executeRecovery(STRATEGIES.FALLBACK, { id: 'task-2' }, {});++ const retryOnly = getHistory({ strategy: STRATEGIES.RETRY });++ expect(retryOnly.every(r => r.strategy === STRATEGIES.RETRY)).toBe(true);+ });++ it('should respect limit', async () => {+ for (let i = 0; i < 5; i++) {+ await executeRecovery(STRATEGIES.RETRY, { id: `task-${i}` }, {}, { delayMs: 1 });+ }++ const limited = getHistory({ limit: 2 });+ expect(limited.length).toBe(2);+ });+ });++ describe('resetAttempts', () => {+ it('should reset attempt counter for specific key', () => {+ recordAttempt('test-key');+ recordAttempt('test-key');+ expect(getAttemptCount('test-key')).toBe(2);++ resetAttempts('test-key');+ expect(getAttemptCount('test-key')).toBe(0);+ });+ });++ describe('clearAllAttempts', () => {+ it('should clear all attempt counters', () => {+ recordAttempt('key-1');+ recordAttempt('key-2');++ clearAllAttempts();++ expect(getAttemptCount('key-1')).toBe(0);+ expect(getAttemptCount('key-2')).toBe(0);+ });+ });+});diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.jsnew file mode 100644index 0000000000..0215a6a99d--- /dev/null+++ b/server/services/eventScheduler.js@@ -0,0 +1,482 @@+/**+ * Event Scheduler Service+ *+ * Event-driven scheduling with cron expressions and timeout-safe timers.+ * Replaces setInterval with more robust scheduling.+ */++import { cosEvents } from './cos.js'++// Maximum safe setTimeout value (2^31 - 1 ms, ~24.8 days)+const MAX_TIMEOUT = 2147483647++// Scheduled events storage+const scheduledEvents = new Map()++// Active timers+const activeTimers = new Map()++// Event history+const eventHistory = []+const MAX_HISTORY = 500++/**+ * Parse cron expression to next execution time+ * Supports: minute hour dayOfMonth month dayOfWeek+ *+ * Special values:+ * - '*' = any value+ * - 'number' = specific value+ * - 'start/step' = every step starting at start+ *+ * @param {string} cronExpr - Cron expression+ * @param {Date} from - Starting point (default: now)+ * @returns {Date} - Next execution time+ */+function parseCronToNextRun(cronExpr, from = new Date()) {+ const parts = cronExpr.trim().split(/\s+/)+ if (parts.length !== 5) {+ throw new Error(`Invalid cron expression: ${cronExpr}`)+ }++ const [minuteExpr, hourExpr, dayOfMonthExpr, monthExpr, dayOfWeekExpr] = parts++ // Simple implementation - find next matching time+ const next = new Date(from)+ next.setSeconds(0, 0)+ next.setMinutes(next.getMinutes() + 1) // Start from next minute++ // Maximum search: 2 years+ const maxDate = new Date(from)+ maxDate.setFullYear(maxDate.getFullYear() + 2)++ while (next < maxDate) {+ if (matchesCronField(next.getMonth() + 1, monthExpr) &&+ matchesCronField(next.getDate(), dayOfMonthExpr) &&+ matchesCronField(next.getDay(), dayOfWeekExpr) &&+ matchesCronField(next.getHours(), hourExpr) &&+ matchesCronField(next.getMinutes(), minuteExpr)) {+ return next+ }+ next.setMinutes(next.getMinutes() + 1)+ }++ return null // No match found within 2 years+}++/**+ * Check if a value matches a cron field expression+ * @param {number} value - Current value+ * @param {string} expr - Cron field expression+ * @returns {boolean} - True if matches+ */+function matchesCronField(value, expr) {+ if (expr === '*') return true++ // Handle comma-separated values+ if (expr.includes(',')) {+ return expr.split(',').some(part => matchesCronField(value, part.trim()))+ }++ // Handle ranges (e.g., 1-5)+ if (expr.includes('-')) {+ const [start, end] = expr.split('-').map(Number)+ return value >= start && value <= end+ }++ // Handle step values (e.g., */5 or 0/10)+ if (expr.includes('/')) {+ const [start, step] = expr.split('/')+ const startNum = start === '*' ? 0 : Number(start)+ const stepNum = Number(step)+ return (value - startNum) % stepNum === 0 && value >= startNum+ }++ // Direct value match+ return Number(expr) === value+}++/**+ * Create a timeout-safe timer+ * Handles values larger than MAX_TIMEOUT by chaining+ *+ * @param {Function} callback - Function to call+ * @param {number} delayMs - Delay in milliseconds+ * @param {string} eventId - Event identifier for tracking+ * @returns {Object} - Timer handle+ */+function createSafeTimer(callback, delayMs, eventId) {+ const clampedDelay = Math.min(delayMs, MAX_TIMEOUT)++ if (delayMs <= MAX_TIMEOUT) {+ // Simple case - use regular setTimeout+ const timerId = setTimeout(() => {+ activeTimers.delete(eventId)+ callback()+ }, clampedDelay)++ return { timerId, type: 'simple' }+ }++ // Chain timeouts for longer delays+ const remaining = delayMs - MAX_TIMEOUT+ const timerId = setTimeout(() => {+ // Schedule the next chunk+ const nextTimer = createSafeTimer(callback, remaining, eventId)+ activeTimers.set(eventId, nextTimer)+ }, MAX_TIMEOUT)++ return { timerId, type: 'chained', remaining }+}++/**+ * Schedule an event+ *+ * @param {Object} config - Event configuration+ * @param {string} config.id - Unique event identifier+ * @param {string} config.type - Event type (cron, interval, once)+ * @param {string} config.cron - Cron expression (for type: cron)+ * @param {number} config.intervalMs - Interval in ms (for type: interval)+ * @param {number} config.delayMs - Delay in ms (for type: once)+ * @param {Function} config.handler - Event handler function+ * @param {Object} config.metadata - Additional metadata+ * @returns {Object} - Scheduled event+ */+function schedule(config) {+ const { id, type, cron, intervalMs, delayMs, handler, metadata = {} } = config++ if (!id || !type || !handler) {+ throw new Error('Event requires id, type, and handler')+ }++ // Cancel existing event with same ID+ if (scheduledEvents.has(id)) {+ cancel(id)+ }++ const event = {+ id,+ type,+ cron,+ intervalMs,+ delayMs,+ handler,+ metadata,+ createdAt: Date.now(),+ nextRunAt: null,+ lastRunAt: null,+ runCount: 0,+ active: true+ }++ // Calculate next run time+ switch (type) {+ case 'cron':+ if (!cron) throw new Error('Cron type requires cron expression')+ event.nextRunAt = parseCronToNextRun(cron)?.getTime() || null+ break++ case 'interval':+ if (!intervalMs) throw new Error('Interval type requires intervalMs')+ event.nextRunAt = Date.now() + intervalMs+ break++ case 'once':+ if (!delayMs) throw new Error('Once type requires delayMs')+ event.nextRunAt = Date.now() + delayMs+ break++ default:+ throw new Error(`Unknown event type: ${type}`)+ }++ scheduledEvents.set(id, event)+ scheduleNextRun(event)++ console.log(`📅 Event scheduled: ${id} (${type}) - next run: ${event.nextRunAt ? new Date(event.nextRunAt).toISOString() : 'never'}`)+ cosEvents.emit('scheduler:scheduled', { id, type, nextRunAt: event.nextRunAt })++ return event+}++/**+ * Schedule the next run of an event+ * @param {Object} event - Event object+ */+function scheduleNextRun(event) {+ if (!event.active || !event.nextRunAt) return++ const delay = event.nextRunAt - Date.now()+ if (delay < 0) {+ // Already past - run immediately for non-recurring, or calculate next for recurring+ if (event.type === 'once') {+ runEvent(event)+ return+ }+ // Calculate next occurrence+ updateNextRunTime(event)+ scheduleNextRun(event)+ return+ }++ const timer = createSafeTimer(() => runEvent(event), delay, event.id)+ activeTimers.set(event.id, timer)+}++/**+ * Run an event+ * @param {Object} event - Event object+ */+async function runEvent(event) {+ const startTime = Date.now()++ event.lastRunAt = startTime+ event.runCount++++ let success = true+ let error = null++ try {+ await event.handler(event)+ } catch (err) {+ success = false+ error = err.message+ console.error(`⚠️ Event ${event.id} failed: ${err.message}`)+ }++ // Record in history+ eventHistory.unshift({+ eventId: event.id,+ type: event.type,+ runAt: startTime,+ duration: Date.now() - startTime,+ success,+ error+ })++ while (eventHistory.length > MAX_HISTORY) {+ eventHistory.pop()+ }++ // Emit completion+ cosEvents.emit('scheduler:ran', {+ id: event.id,+ success,+ runCount: event.runCount+ })++ // Schedule next run for recurring events+ if (event.active && event.type !== 'once') {+ updateNextRunTime(event)+ scheduleNextRun(event)+ } else if (event.type === 'once') {+ event.active = false+ activeTimers.delete(event.id)+ }+}++/**+ * Update the next run time for a recurring event+ * @param {Object} event - Event object+ */+function updateNextRunTime(event) {+ switch (event.type) {+ case 'cron':+ const nextDate = parseCronToNextRun(event.cron, new Date())+ event.nextRunAt = nextDate?.getTime() || null+ break++ case 'interval':+ event.nextRunAt = Date.now() + event.intervalMs+ break++ case 'once':+ event.nextRunAt = null+ break+ }+}++/**+ * Cancel a scheduled event+ * @param {string} id - Event identifier+ * @returns {boolean} - True if event was found and cancelled+ */+function cancel(id) {+ const event = scheduledEvents.get(id)+ if (!event) return false++ event.active = false++ const timer = activeTimers.get(id)+ if (timer) {+ clearTimeout(timer.timerId)+ activeTimers.delete(id)+ }++ scheduledEvents.delete(id)+ console.log(`📅 Event cancelled: ${id}`)+ cosEvents.emit('scheduler:cancelled', { id })++ return true+}++/**+ * Pause a scheduled event+ * @param {string} id - Event identifier+ * @returns {boolean} - True if event was found and paused+ */+function pause(id) {+ const event = scheduledEvents.get(id)+ if (!event) return false++ event.active = false++ const timer = activeTimers.get(id)+ if (timer) {+ clearTimeout(timer.timerId)+ activeTimers.delete(id)+ }++ console.log(`⏸️ Event paused: ${id}`)+ return true+}++/**+ * Resume a paused event+ * @param {string} id - Event identifier+ * @returns {boolean} - True if event was found and resumed+ */+function resume(id) {+ const event = scheduledEvents.get(id)+ if (!event) return false++ event.active = true+ updateNextRunTime(event)+ scheduleNextRun(event)++ console.log(`▶️ Event resumed: ${id}`)+ return true+}++/**+ * Get all scheduled events+ * @returns {Array} - All scheduled events+ */+function getScheduledEvents() {+ return Array.from(scheduledEvents.values()).map(e => ({+ id: e.id,+ type: e.type,+ active: e.active,+ nextRunAt: e.nextRunAt,+ lastRunAt: e.lastRunAt,+ runCount: e.runCount,+ metadata: e.metadata+ }))+}++/**+ * Get event by ID+ * @param {string} id - Event identifier+ * @returns {Object|null} - Event or null+ */+function getEvent(id) {+ const event = scheduledEvents.get(id)+ if (!event) return null++ return {+ id: event.id,+ type: event.type,+ active: event.active,+ cron: event.cron,+ intervalMs: event.intervalMs,+ nextRunAt: event.nextRunAt,+ lastRunAt: event.lastRunAt,+ runCount: event.runCount,+ metadata: event.metadata+ }+}++/**+ * Get event history+ * @param {Object} options - Filter options+ * @returns {Array} - Event history+ */+function getHistory(options = {}) {+ let history = [...eventHistory]++ if (options.eventId) {+ history = history.filter(h => h.eventId === options.eventId)+ }++ if (options.success !== undefined) {+ history = history.filter(h => h.success === options.success)+ }++ const limit = options.limit || 50+ return history.slice(0, limit)+}++/**+ * Get scheduler statistics+ * @returns {Object} - Scheduler stats+ */+function getStats() {+ const events = Array.from(scheduledEvents.values())+ const recent = eventHistory.slice(0, 100)++ return {+ totalEvents: events.length,+ activeEvents: events.filter(e => e.active).length,+ activeTimers: activeTimers.size,+ byType: events.reduce((acc, e) => {+ acc[e.type] = (acc[e.type] || 0) + 1+ return acc+ }, {}),+ totalRuns: eventHistory.length,+ recentSuccessRate: recent.length > 0+ ? ((recent.filter(h => h.success).length / recent.length) * 100).toFixed(1) + '%'+ : '100%'+ }+}++/**+ * Cancel all scheduled events+ * @returns {number} - Number of events cancelled+ */+function cancelAll() {+ const count = scheduledEvents.size++ for (const id of scheduledEvents.keys()) {+ cancel(id)+ }++ return count+}++/**+ * Trigger an event immediately (for testing or manual runs)+ * @param {string} id - Event identifier+ * @returns {Promise<boolean>} - True if event was found and triggered+ */+async function triggerNow(id) {+ const event = scheduledEvents.get(id)+ if (!event) return false++ await runEvent(event)+ return true+}++export {+ schedule,+ cancel,+ pause,+ resume,+ getScheduledEvents,+ getEvent,+ getHistory,+ getStats,+ cancelAll,+ triggerNow,+ parseCronToNextRun,+ MAX_TIMEOUT+}diff --git a/server/services/executionLanes.js b/server/services/executionLanes.jsnew file mode 100644index 0000000000..76c787b100--- /dev/null+++ b/server/services/executionLanes.js@@ -0,0 +1,440 @@+/**+ * Execution Lanes Service+ *+ * Lane-based concurrency control for agent execution.+ * Lanes: critical (1), standard (2), background (3)+ */++import { cosEvents } from './cos.js'++// Lane configuration+const LANES = {+ critical: {+ name: 'critical',+ maxConcurrent: 1,+ priority: 1,+ description: 'High-priority user tasks, blocking operations'+ },+ standard: {+ name: 'standard',+ maxConcurrent: 2,+ priority: 2,+ description: 'Normal task execution'+ },+ background: {+ name: 'background',+ maxConcurrent: 3,+ priority: 3,+ description: 'Self-improvement, idle work, non-urgent tasks'+ }+}++// Lane occupancy tracking+const laneOccupancy = {+ critical: new Map(), // agentId -> { taskId, startedAt, metadata }+ standard: new Map(),+ background: new Map()+}++// Queue for tasks waiting for lane availability+const waitingQueue = {+ critical: [],+ standard: [],+ background: []+}++// Statistics+const stats = {+ acquired: 0,+ released: 0,+ queued: 0,+ timeouts: 0,+ promotions: 0+}++/**+ * Get lane by name or determine from task priority+ * @param {string|Object} laneOrTask - Lane name or task object+ * @returns {string} - Lane name+ */+function determineLane(laneOrTask) {+ if (typeof laneOrTask === 'string') {+ return LANES[laneOrTask] ? laneOrTask : 'standard'+ }++ const task = laneOrTask+ const priority = task?.priority?.toUpperCase()++ switch (priority) {+ case 'URGENT':+ case 'CRITICAL':+ return 'critical'+ case 'HIGH':+ case 'MEDIUM':+ return 'standard'+ case 'LOW':+ case 'IDLE':+ return 'background'+ default:+ return task?.metadata?.isUserTask ? 'standard' : 'background'+ }+}++/**+ * Check if a lane has available capacity+ * @param {string} laneName - Lane name+ * @returns {boolean} - True if capacity available+ */+function hasCapacity(laneName) {+ const lane = LANES[laneName]+ if (!lane) return false++ const occupancy = laneOccupancy[laneName]+ return occupancy.size < lane.maxConcurrent+}++/**+ * Get current lane status+ * @param {string} laneName - Lane name+ * @returns {Object} - Lane status+ */+function getLaneStatus(laneName) {+ const lane = LANES[laneName]+ if (!lane) return null++ const occupancy = laneOccupancy[laneName]+ const queue = waitingQueue[laneName]++ return {+ name: lane.name,+ maxConcurrent: lane.maxConcurrent,+ currentOccupancy: occupancy.size,+ available: lane.maxConcurrent - occupancy.size,+ queueLength: queue.length,+ occupants: Array.from(occupancy.entries()).map(([agentId, data]) => ({+ agentId,+ taskId: data.taskId,+ startedAt: data.startedAt,+ runningMs: Date.now() - data.startedAt+ }))+ }+}++/**+ * Acquire a slot in a lane+ * @param {string} laneName - Lane name+ * @param {string} agentId - Agent identifier+ * @param {Object} metadata - Additional metadata (taskId, etc.)+ * @returns {Object} - Acquisition result+ */+function acquire(laneName, agentId, metadata = {}) {+ const lane = LANES[laneName]+ if (!lane) {+ return { success: false, error: `Unknown lane: ${laneName}` }+ }++ const occupancy = laneOccupancy[laneName]++ // Check if already in this lane+ if (occupancy.has(agentId)) {+ return { success: true, alreadyAcquired: true, lane: laneName }+ }++ // Check capacity+ if (occupancy.size >= lane.maxConcurrent) {+ return {+ success: false,+ error: 'Lane at capacity',+ lane: laneName,+ currentOccupancy: occupancy.size,+ maxConcurrent: lane.maxConcurrent+ }+ }++ // Acquire slot+ occupancy.set(agentId, {+ taskId: metadata.taskId,+ startedAt: Date.now(),+ metadata+ })++ stats.acquired++++ cosEvents.emit('lane:acquired', {+ lane: laneName,+ agentId,+ taskId: metadata.taskId,+ occupancy: occupancy.size+ })++ console.log(`🛤️ Lane acquired: ${agentId} → ${laneName} (${occupancy.size}/${lane.maxConcurrent})`)++ return {+ success: true,+ lane: laneName,+ position: occupancy.size+ }+}++/**+ * Release a lane slot+ * @param {string} agentId - Agent identifier+ * @returns {Object} - Release result+ */+function release(agentId) {+ for (const [laneName, occupancy] of Object.entries(laneOccupancy)) {+ if (occupancy.has(agentId)) {+ const data = occupancy.get(agentId)+ occupancy.delete(agentId)++ stats.released++++ const runningMs = Date.now() - data.startedAt++ cosEvents.emit('lane:released', {+ lane: laneName,+ agentId,+ taskId: data.taskId,+ runningMs,+ occupancy: occupancy.size+ })++ console.log(`🛤️ Lane released: ${agentId} ← ${laneName} (ran ${runningMs}ms)`)++ // Process waiting queue for this lane+ processWaitingQueue(laneName)++ return {+ success: true,+ lane: laneName,+ runningMs+ }+ }+ }++ return { success: false, error: 'Agent not in any lane' }+}++/**+ * Wait for lane availability (with timeout)+ * @param {string} laneName - Lane name+ * @param {string} agentId - Agent identifier+ * @param {Object} options - Wait options+ * @returns {Promise<Object>} - Acquisition result+ */+async function waitForLane(laneName, agentId, options = {}) {+ const { timeoutMs = 60000, metadata = {} } = options++ // Try immediate acquisition+ const immediate = acquire(laneName, agentId, metadata)+ if (immediate.success) return immediate++ // Add to waiting queue+ return new Promise((resolve) => {+ const queueEntry = {+ agentId,+ metadata,+ resolve,+ enqueuedAt: Date.now()+ }++ waitingQueue[laneName].push(queueEntry)+ stats.queued++++ console.log(`⏳ Queued for lane: ${agentId} → ${laneName} (position ${waitingQueue[laneName].length})`)++ // Set timeout+ const timeoutId = setTimeout(() => {+ const idx = waitingQueue[laneName].indexOf(queueEntry)+ if (idx !== -1) {+ waitingQueue[laneName].splice(idx, 1)+ stats.timeouts+++ resolve({+ success: false,+ error: 'Lane wait timeout',+ lane: laneName,+ waitedMs: timeoutMs+ })+ }+ }, timeoutMs)++ queueEntry.timeoutId = timeoutId+ })+}++/**+ * Process waiting queue when a lane slot becomes available+ * @param {string} laneName - Lane name+ */+function processWaitingQueue(laneName) {+ const queue = waitingQueue[laneName]+ if (queue.length === 0) return++ const lane = LANES[laneName]+ const occupancy = laneOccupancy[laneName]++ while (queue.length > 0 && occupancy.size < lane.maxConcurrent) {+ const entry = queue.shift()+ clearTimeout(entry.timeoutId)++ const result = acquire(laneName, entry.agentId, entry.metadata)+ if (result.success) {+ result.waitedMs = Date.now() - entry.enqueuedAt+ entry.resolve(result)+ } else {+ // Failed to acquire despite capacity - shouldn't happen+ entry.resolve(result)+ }+ }+}++/**+ * Promote a task to a higher priority lane+ * @param {string} agentId - Agent identifier+ * @param {string} targetLane - Target lane (must be higher priority)+ * @returns {Object} - Promotion result+ */+function promote(agentId, targetLane) {+ const targetLaneConfig = LANES[targetLane]+ if (!targetLaneConfig) {+ return { success: false, error: `Unknown lane: ${targetLane}` }+ }++ // Find current lane+ let currentLane = null+ for (const [laneName, occupancy] of Object.entries(laneOccupancy)) {+ if (occupancy.has(agentId)) {+ currentLane = laneName+ break+ }+ }++ if (!currentLane) {+ return { success: false, error: 'Agent not in any lane' }+ }++ // Check if promotion makes sense+ if (LANES[currentLane].priority <= targetLaneConfig.priority) {+ return { success: false, error: 'Target lane is not higher priority' }+ }++ // Check target capacity+ if (!hasCapacity(targetLane)) {+ return { success: false, error: 'Target lane at capacity' }+ }++ // Move agent+ const data = laneOccupancy[currentLane].get(agentId)+ laneOccupancy[currentLane].delete(agentId)+ laneOccupancy[targetLane].set(agentId, data)++ stats.promotions++++ console.log(`⬆️ Lane promotion: ${agentId} ${currentLane} → ${targetLane}`)++ // Process queue for old lane+ processWaitingQueue(currentLane)++ return {+ success: true,+ fromLane: currentLane,+ toLane: targetLane+ }+}++/**+ * Get overall lane statistics+ * @returns {Object} - Lane statistics+ */+function getStats() {+ const laneStats = {}++ for (const laneName of Object.keys(LANES)) {+ laneStats[laneName] = getLaneStatus(laneName)+ }++ const totalOccupancy = Object.values(laneOccupancy)+ .reduce((sum, map) => sum + map.size, 0)+ const totalCapacity = Object.values(LANES)+ .reduce((sum, lane) => sum + lane.maxConcurrent, 0)+ const totalQueued = Object.values(waitingQueue)+ .reduce((sum, queue) => sum + queue.length, 0)++ return {+ lanes: laneStats,+ totalOccupancy,+ totalCapacity,+ utilizationPercent: ((totalOccupancy / totalCapacity) * 100).toFixed(1) + '%',+ totalQueued,+ ...stats+ }+}++/**+ * Get agent's current lane+ * @param {string} agentId - Agent identifier+ * @returns {string|null} - Lane name or null+ */+function getAgentLane(agentId) {+ for (const [laneName, occupancy] of Object.entries(laneOccupancy)) {+ if (occupancy.has(agentId)) {+ return laneName+ }+ }+ return null+}++/**+ * Force release all agents from a lane (for emergencies)+ * @param {string} laneName - Lane name+ * @returns {number} - Number of agents released+ */+function clearLane(laneName) {+ const occupancy = laneOccupancy[laneName]+ if (!occupancy) return 0++ const count = occupancy.size+ const agents = Array.from(occupancy.keys())++ for (const agentId of agents) {+ release(agentId)+ }++ console.log(`🧹 Cleared lane ${laneName}: ${count} agents`)+ return count+}++/**+ * Update lane configuration dynamically+ * @param {string} laneName - Lane name+ * @param {Object} config - New configuration+ * @returns {Object} - Updated lane config+ */+function updateLaneConfig(laneName, config) {+ const lane = LANES[laneName]+ if (!lane) return null++ if (config.maxConcurrent !== undefined) {+ lane.maxConcurrent = config.maxConcurrent++ // Process queue if we increased capacity+ processWaitingQueue(laneName)+ }++ return { ...lane }+}++export {+ LANES,+ determineLane,+ hasCapacity,+ getLaneStatus,+ acquire,+ release,+ waitForLane,+ promote,+ getStats,+ getAgentLane,+ clearLane,+ updateLaneConfig+}diff --git a/server/services/executionLanes.test.js b/server/services/executionLanes.test.jsnew file mode 100644index 0000000000..8a1638d87b--- /dev/null+++ b/server/services/executionLanes.test.js@@ -0,0 +1,333 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import {+ LANES,+ determineLane,+ hasCapacity,+ getLaneStatus,+ acquire,+ release,+ waitForLane,+ promote,+ getStats,+ getAgentLane,+ clearLane,+ updateLaneConfig+} from './executionLanes.js';++// Mock the cosEvents+vi.mock('./cos.js', () => ({+ cosEvents: {+ emit: vi.fn()+ }+}));++describe('Execution Lanes Service', () => {+ beforeEach(() => {+ // Clear all lanes before each test+ clearLane('critical');+ clearLane('standard');+ clearLane('background');+ });++ describe('LANES', () => {+ it('should have all required lanes', () => {+ expect(LANES.critical).toBeDefined();+ expect(LANES.standard).toBeDefined();+ expect(LANES.background).toBeDefined();+ });++ it('should have correct max concurrent values', () => {+ expect(LANES.critical.maxConcurrent).toBe(1);+ expect(LANES.standard.maxConcurrent).toBe(2);+ expect(LANES.background.maxConcurrent).toBe(3);+ });++ it('should have priority ordering', () => {+ expect(LANES.critical.priority).toBeLessThan(LANES.standard.priority);+ expect(LANES.standard.priority).toBeLessThan(LANES.background.priority);+ });+ });++ describe('determineLane', () => {+ it('should return lane name when given string', () => {+ expect(determineLane('critical')).toBe('critical');+ expect(determineLane('standard')).toBe('standard');+ expect(determineLane('background')).toBe('background');+ });++ it('should default to standard for invalid lane name', () => {+ expect(determineLane('invalid')).toBe('standard');+ });++ it('should determine critical for URGENT/CRITICAL priority', () => {+ expect(determineLane({ priority: 'URGENT' })).toBe('critical');+ expect(determineLane({ priority: 'CRITICAL' })).toBe('critical');+ });++ it('should determine standard for HIGH/MEDIUM priority', () => {+ expect(determineLane({ priority: 'HIGH' })).toBe('standard');+ expect(determineLane({ priority: 'MEDIUM' })).toBe('standard');+ });++ it('should determine background for LOW/IDLE priority', () => {+ expect(determineLane({ priority: 'LOW' })).toBe('background');+ expect(determineLane({ priority: 'IDLE' })).toBe('background');+ });++ it('should use isUserTask for default priority', () => {+ expect(determineLane({ metadata: { isUserTask: true } })).toBe('standard');+ expect(determineLane({ metadata: { isUserTask: false } })).toBe('background');+ expect(determineLane({})).toBe('background');+ });+ });++ describe('hasCapacity', () => {+ it('should return true for empty lanes', () => {+ expect(hasCapacity('critical')).toBe(true);+ expect(hasCapacity('standard')).toBe(true);+ expect(hasCapacity('background')).toBe(true);+ });++ it('should return false for unknown lane', () => {+ expect(hasCapacity('unknown')).toBe(false);+ });++ it('should return false when lane is at capacity', () => {+ acquire('critical', 'agent-1');+ expect(hasCapacity('critical')).toBe(false);+ });++ it('should return true when lane has capacity', () => {+ acquire('standard', 'agent-1');+ expect(hasCapacity('standard')).toBe(true); // Can hold 2+ });+ });++ describe('getLaneStatus', () => {+ it('should return lane status', () => {+ const status = getLaneStatus('standard');++ expect(status.name).toBe('standard');+ expect(status.maxConcurrent).toBe(2);+ expect(status.currentOccupancy).toBe(0);+ expect(status.available).toBe(2);+ });++ it('should return null for unknown lane', () => {+ expect(getLaneStatus('unknown')).toBeNull();+ });++ it('should include occupant details', () => {+ acquire('standard', 'agent-1', { taskId: 'task-1' });+ const status = getLaneStatus('standard');++ expect(status.occupants.length).toBe(1);+ expect(status.occupants[0].agentId).toBe('agent-1');+ expect(status.occupants[0].taskId).toBe('task-1');+ });+ });++ describe('acquire', () => {+ it('should acquire a lane slot', () => {+ const result = acquire('standard', 'agent-1', { taskId: 'task-1' });++ expect(result.success).toBe(true);+ expect(result.lane).toBe('standard');+ });++ it('should fail for unknown lane', () => {+ const result = acquire('unknown', 'agent-1');++ expect(result.success).toBe(false);+ expect(result.error).toContain('Unknown lane');+ });++ it('should fail when lane is at capacity', () => {+ acquire('critical', 'agent-1');+ const result = acquire('critical', 'agent-2');++ expect(result.success).toBe(false);+ expect(result.error).toBe('Lane at capacity');+ });++ it('should return success if already acquired', () => {+ acquire('standard', 'agent-1');+ const result = acquire('standard', 'agent-1');++ expect(result.success).toBe(true);+ expect(result.alreadyAcquired).toBe(true);+ });+ });++ describe('release', () => {+ it('should release a lane slot', () => {+ acquire('standard', 'agent-1');+ const result = release('agent-1');++ expect(result.success).toBe(true);+ expect(result.lane).toBe('standard');+ expect(result.runningMs).toBeGreaterThanOrEqual(0);+ });++ it('should fail for agent not in any lane', () => {+ const result = release('nonexistent-agent');++ expect(result.success).toBe(false);+ expect(result.error).toBe('Agent not in any lane');+ });++ it('should free up capacity', () => {+ acquire('critical', 'agent-1');+ expect(hasCapacity('critical')).toBe(false);++ release('agent-1');+ expect(hasCapacity('critical')).toBe(true);+ });+ });++ describe('waitForLane', () => {+ it('should acquire immediately if capacity available', async () => {+ const result = await waitForLane('standard', 'agent-1', {+ metadata: { taskId: 'task-1' }+ });++ expect(result.success).toBe(true);+ });++ it('should timeout when lane stays at capacity', async () => {+ acquire('critical', 'agent-1');++ const result = await waitForLane('critical', 'agent-2', {+ timeoutMs: 100+ });++ expect(result.success).toBe(false);+ expect(result.error).toBe('Lane wait timeout');+ });++ it('should acquire when slot becomes available', async () => {+ acquire('critical', 'agent-1');++ // Start waiting+ const waitPromise = waitForLane('critical', 'agent-2', {+ timeoutMs: 1000+ });++ // Release after short delay+ setTimeout(() => release('agent-1'), 50);++ const result = await waitPromise;+ expect(result.success).toBe(true);+ expect(result.waitedMs).toBeGreaterThan(0);+ });+ });++ describe('promote', () => {+ it('should promote agent to higher priority lane', () => {+ acquire('background', 'agent-1', { taskId: 'task-1' });+ const result = promote('agent-1', 'standard');++ expect(result.success).toBe(true);+ expect(result.fromLane).toBe('background');+ expect(result.toLane).toBe('standard');+ });++ it('should fail for unknown target lane', () => {+ acquire('standard', 'agent-1');+ const result = promote('agent-1', 'unknown');++ expect(result.success).toBe(false);+ });++ it('should fail if agent not in any lane', () => {+ const result = promote('nonexistent', 'critical');++ expect(result.success).toBe(false);+ expect(result.error).toBe('Agent not in any lane');+ });++ it('should fail if target is lower priority', () => {+ acquire('critical', 'agent-1');+ const result = promote('agent-1', 'background');++ expect(result.success).toBe(false);+ expect(result.error).toBe('Target lane is not higher priority');+ });++ it('should fail if target lane at capacity', () => {+ acquire('critical', 'agent-1');+ acquire('standard', 'agent-2');+ const result = promote('agent-2', 'critical');++ expect(result.success).toBe(false);+ expect(result.error).toBe('Target lane at capacity');+ });+ });++ describe('getStats', () => {+ it('should return overall statistics', () => {+ acquire('standard', 'agent-1');+ acquire('background', 'agent-2');++ const stats = getStats();++ expect(stats.totalOccupancy).toBe(2);+ expect(stats.totalCapacity).toBe(6); // 1 + 2 + 3+ expect(stats.lanes.standard.currentOccupancy).toBe(1);+ expect(stats.lanes.background.currentOccupancy).toBe(1);+ });++ it('should track acquired/released counts', () => {+ acquire('standard', 'agent-1');+ release('agent-1');++ const stats = getStats();+ expect(stats.acquired).toBeGreaterThan(0);+ expect(stats.released).toBeGreaterThan(0);+ });+ });++ describe('getAgentLane', () => {+ it('should return lane for agent', () => {+ acquire('standard', 'agent-1');+ expect(getAgentLane('agent-1')).toBe('standard');+ });++ it('should return null for unknown agent', () => {+ expect(getAgentLane('nonexistent')).toBeNull();+ });+ });++ describe('clearLane', () => {+ it('should clear all agents from lane', () => {+ acquire('standard', 'agent-1');+ acquire('standard', 'agent-2');++ const count = clearLane('standard');++ expect(count).toBe(2);+ expect(hasCapacity('standard')).toBe(true);+ expect(getLaneStatus('standard').currentOccupancy).toBe(0);+ });++ it('should return 0 for unknown lane', () => {+ expect(clearLane('unknown')).toBe(0);+ });+ });++ describe('updateLaneConfig', () => {+ it('should update lane max concurrent', () => {+ const originalMax = LANES.standard.maxConcurrent;+ updateLaneConfig('standard', { maxConcurrent: 5 });++ expect(LANES.standard.maxConcurrent).toBe(5);++ // Restore+ updateLaneConfig('standard', { maxConcurrent: originalMax });+ });++ it('should return null for unknown lane', () => {+ expect(updateLaneConfig('unknown', {})).toBeNull();+ });+ });+});diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.jsnew file mode 100644index 0000000000..1d112d7693--- /dev/null+++ b/server/services/lmStudioManager.js@@ -0,0 +1,406 @@+/**+ * LM Studio Manager Service+ *+ * Manages local LM Studio models for free local thinking.+ * Provides model discovery, loading, unloading, and downloading.+ */++import { cosEvents } from './cos.js'++// Default LM Studio configuration+const DEFAULT_CONFIG = {+ baseUrl: 'http://localhost:1234',+ timeout: 30000,+ defaultThinkingModel: 'gpt-oss-20b'+}++// Cached state+let config = { ...DEFAULT_CONFIG }+let isAvailable = null+let loadedModels = []+let availableModels = []+let lastCheckAt = null++// Status tracking+const status = {+ lastError: null,+ lastSuccessAt: null,+ consecutiveErrors: 0+}++/**+ * Make a request to LM Studio API+ * @param {string} endpoint - API endpoint+ * @param {Object} options - Fetch options+ * @returns {Promise<*>} - Response data+ */+async function lmStudioRequest(endpoint, options = {}) {+ const url = `${config.baseUrl}${endpoint}`+ const controller = new AbortController()+ const timeoutId = setTimeout(() => controller.abort(), options.timeout || config.timeout)++ const response = await fetch(url, {+ ...options,+ signal: controller.signal,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ }).finally(() => clearTimeout(timeoutId))++ if (!response.ok) {+ throw new Error(`LM Studio API error: ${response.status} ${response.statusText}`)+ }++ return response.json()+}++/**+ * Check if LM Studio is available+ * @returns {Promise<boolean>} - True if available+ */+async function checkLMStudioAvailable() {+ const now = Date.now()++ // Use cached result if recent (within 30 seconds)+ if (lastCheckAt && now - lastCheckAt < 30000 && isAvailable !== null) {+ return isAvailable+ }++ try {+ await lmStudioRequest('/v1/models', { timeout: 5000 })+ isAvailable = true+ status.lastSuccessAt = now+ status.consecutiveErrors = 0+ status.lastError = null+ lastCheckAt = now+ return true+ } catch (err) {+ isAvailable = false+ status.lastError = err.message+ status.consecutiveErrors+++ lastCheckAt = now+ return false+ }+}++/**+ * Get currently loaded models+ * @param {boolean} forceRefresh - Force refresh from API+ * @returns {Promise<Array>} - Loaded models+ */+async function getLoadedModels(forceRefresh = false) {+ if (!forceRefresh && loadedModels.length > 0) {+ return loadedModels+ }++ const available = await checkLMStudioAvailable()+ if (!available) {+ return []+ }++ try {+ const response = await lmStudioRequest('/v1/models')+ loadedModels = (response.data || []).map(model => ({+ id: model.id,+ object: model.object,+ created: model.created,+ ownedBy: model.owned_by+ }))+ return loadedModels+ } catch (err) {+ console.error(`⚠️ Failed to get LM Studio models: ${err.message}`)+ return []+ }+}++/**+ * Get available models in LM Studio catalog+ * Note: This requires LM Studio's /lmstudio.* endpoints if available+ * @returns {Promise<Array>} - Available models+ */+async function getAvailableModels() {+ const available = await checkLMStudioAvailable()+ if (!available) {+ return []+ }++ // LM Studio doesn't have a public catalog API by default+ // Return loaded models as available for now+ return getLoadedModels(true)+}++/**+ * Download a model from LM Studio catalog+ * Note: Requires LM Studio API support for downloads+ *+ * @param {string} modelId - Model identifier to download+ * @returns {Promise<Object>} - Download result+ */+async function downloadModel(modelId) {+ const available = await checkLMStudioAvailable()+ if (!available) {+ return {+ success: false,+ error: 'LM Studio not available'+ }+ }++ // LM Studio doesn't have a public download API+ // This would need to be implemented via LM Studio's developer API+ console.log(`📥 Model download requested: ${modelId}`)+ cosEvents.emit('lmstudio:downloadRequested', { modelId })++ return {+ success: false,+ error: 'Model downloading not yet supported via API',+ modelId,+ instruction: 'Please download the model manually via LM Studio UI'+ }+}++/**+ * Load a model into LM Studio memory+ * @param {string} modelId - Model identifier to load+ * @returns {Promise<Object>} - Load result+ */+async function loadModel(modelId) {+ const available = await checkLMStudioAvailable()+ if (!available) {+ return { success: false, error: 'LM Studio not available' }+ }++ try {+ // Try to make a test completion to trigger model loading+ await lmStudioRequest('/v1/chat/completions', {+ method: 'POST',+ body: JSON.stringify({+ model: modelId,+ messages: [{ role: 'user', content: 'test' }],+ max_tokens: 1+ }),+ timeout: 60000 // Loading can take a while+ })++ // Refresh loaded models+ await getLoadedModels(true)++ console.log(`📦 Model loaded: ${modelId}`)+ cosEvents.emit('lmstudio:modelLoaded', { modelId })++ return { success: true, modelId }+ } catch (err) {+ console.error(`⚠️ Failed to load model ${modelId}: ${err.message}`)+ return { success: false, error: err.message, modelId }+ }+}++/**+ * Unload a model from LM Studio memory+ * Note: Requires LM Studio API support for unloading+ *+ * @param {string} modelId - Model identifier to unload+ * @returns {Promise<Object>} - Unload result+ */+async function unloadModel(modelId) {+ const available = await checkLMStudioAvailable()+ if (!available) {+ return { success: false, error: 'LM Studio not available' }+ }++ // LM Studio doesn't have a public unload API+ console.log(`📤 Model unload requested: ${modelId}`)+ cosEvents.emit('lmstudio:unloadRequested', { modelId })++ return {+ success: false,+ error: 'Model unloading not yet supported via API',+ modelId,+ instruction: 'Please unload the model manually via LM Studio UI'+ }+}++/**+ * Get the recommended thinking model+ * @returns {Promise<string|null>} - Model ID or null if none available+ */+async function getRecommendedThinkingModel() {+ const models = await getLoadedModels()++ if (models.length === 0) {+ return null+ }++ // Prefer specific thinking-optimized models+ const preferredModels = [+ 'gpt-oss-20b',+ 'deepseek-r1',+ 'qwen2.5-coder',+ 'codellama',+ 'mistral',+ 'llama'+ ]++ for (const preferred of preferredModels) {+ const match = models.find(m =>+ m.id.toLowerCase().includes(preferred.toLowerCase())+ )+ if (match) return match.id+ }++ // Return first available model+ return models[0]?.id || null+}++/**+ * Make a quick completion request for local thinking+ * @param {string} prompt - Prompt text+ * @param {Object} options - Completion options+ * @returns {Promise<Object>} - Completion result+ */+async function quickCompletion(prompt, options = {}) {+ const available = await checkLMStudioAvailable()+ if (!available) {+ return { success: false, error: 'LM Studio not available' }+ }++ const model = options.model || await getRecommendedThinkingModel()+ if (!model) {+ return { success: false, error: 'No model available' }+ }++ try {+ const response = await lmStudioRequest('/v1/chat/completions', {+ method: 'POST',+ body: JSON.stringify({+ model,+ messages: [+ ...(options.systemPrompt ? [{ role: 'system', content: options.systemPrompt }] : []),+ { role: 'user', content: prompt }+ ],+ max_tokens: options.maxTokens || 512,+ temperature: options.temperature ?? 0.7,+ stream: false+ }),+ timeout: options.timeout || 30000+ })++ const content = response.choices?.[0]?.message?.content || ''++ return {+ success: true,+ content,+ model,+ usage: response.usage+ }+ } catch (err) {+ return { success: false, error: err.message, model }+ }+}++/**+ * Get embeddings from local model+ * @param {string} text - Text to embed+ * @param {Object} options - Embedding options+ * @returns {Promise<Object>} - Embedding result+ */+async function getEmbeddings(text, options = {}) {+ const available = await checkLMStudioAvailable()+ if (!available) {+ return { success: false, error: 'LM Studio not available' }+ }++ const model = options.model || 'text-embedding-nomic-embed-text-v2-moe'++ try {+ const response = await lmStudioRequest('/v1/embeddings', {+ method: 'POST',+ body: JSON.stringify({+ model,+ input: text+ }),+ timeout: options.timeout || 10000+ })++ const embedding = response.data?.[0]?.embedding || []++ return {+ success: true,+ embedding,+ model,+ dimensions: embedding.length+ }+ } catch (err) {+ return { success: false, error: err.message, model }+ }+}++/**+ * Get LM Studio status+ * @returns {Promise<Object>} - Status information+ */+async function getStatus() {+ const available = await checkLMStudioAvailable()+ const models = available ? await getLoadedModels() : []++ return {+ available,+ baseUrl: config.baseUrl,+ loadedModels: models.length,+ models: models.map(m => m.id),+ recommendedThinkingModel: available ? await getRecommendedThinkingModel() : null,+ lastCheckAt: lastCheckAt ? new Date(lastCheckAt).toISOString() : null,+ lastSuccessAt: status.lastSuccessAt ? new Date(status.lastSuccessAt).toISOString() : null,+ lastError: status.lastError,+ consecutiveErrors: status.consecutiveErrors+ }+}++/**+ * Update configuration+ * @param {Object} newConfig - New configuration+ * @returns {Object} - Updated configuration+ */+function updateConfig(newConfig) {+ if (newConfig.baseUrl) {+ config.baseUrl = newConfig.baseUrl+ isAvailable = null // Force recheck+ lastCheckAt = null+ }++ if (newConfig.timeout) {+ config.timeout = newConfig.timeout+ }++ if (newConfig.defaultThinkingModel) {+ config.defaultThinkingModel = newConfig.defaultThinkingModel+ }++ return { ...config }+}++/**+ * Reset cached state+ */+function resetCache() {+ isAvailable = null+ loadedModels = []+ availableModels = []+ lastCheckAt = null+}++export {+ checkLMStudioAvailable,+ getLoadedModels,+ getAvailableModels,+ downloadModel,+ loadModel,+ unloadModel,+ getRecommendedThinkingModel,+ quickCompletion,+ getEmbeddings,+ getStatus,+ updateConfig,+ resetCache,+ DEFAULT_CONFIG+}diff --git a/server/services/localThinking.js b/server/services/localThinking.jsnew file mode 100644index 0000000000..cd6e8656bd--- /dev/null+++ b/server/services/localThinking.js@@ -0,0 +1,339 @@+/**+ * Local Thinking Service+ *+ * Uses LM Studio for free local analysis and thinking.+ * Decides when to escalate to cloud providers.+ */++import * as lmStudio from './lmStudioManager.js'+import { cosEvents } from './cos.js'++// Task complexity thresholds for escalation+const COMPLEXITY_THRESHOLDS = {+ simple: 0.3, // Local model can handle+ medium: 0.6, // Local might work, cloud preferred+ complex: 0.8, // Cloud recommended+ advanced: 1.0 // Cloud required+}++// Keywords that suggest higher complexity+const COMPLEXITY_KEYWORDS = {+ high: [+ 'refactor', 'architect', 'design', 'security', 'audit',+ 'optimize', 'performance', 'migration', 'integrate',+ 'test coverage', 'comprehensive', 'entire codebase'+ ],+ medium: [+ 'implement', 'feature', 'fix bug', 'update', 'modify',+ 'add functionality', 'improve', 'enhance'+ ],+ low: [+ 'format', 'rename', 'typo', 'comment', 'simple',+ 'minor', 'quick', 'small', 'straightforward'+ ]+}++// Usage tracking+const stats = {+ localAnalyses: 0,+ cloudEscalations: 0,+ localSuccesses: 0,+ localFailures: 0+}++/**+ * Analyze a task to determine complexity and requirements+ * @param {Object} task - Task to analyze+ * @returns {Promise<Object>} - Analysis result+ */+async function analyzeTask(task) {+ const description = task.description || ''++ // Quick keyword-based complexity estimate+ const keywordComplexity = estimateComplexityFromKeywords(description)++ // Check if LM Studio is available for deeper analysis+ const lmAvailable = await lmStudio.checkLMStudioAvailable()++ if (!lmAvailable) {+ return {+ complexity: keywordComplexity,+ escalateToCloud: keywordComplexity > COMPLEXITY_THRESHOLDS.medium,+ reason: 'LM Studio unavailable, using keyword analysis',+ localAnalysis: false,+ suggestions: []+ }+ }++ // Use local model for deeper analysis+ stats.localAnalyses++++ const analysisPrompt = `Analyze this task and respond with JSON only:+Task: ${description.substring(0, 500)}++Respond with:+{+ "complexity": 0.0-1.0 (how complex is this task),+ "requiresCodeUnderstanding": true/false,+ "requiresMultiFileChanges": true/false,+ "requiresArchitecturalDecisions": true/false,+ "suggestedApproach": "brief approach",+ "potentialRisks": ["risk1", "risk2"]+}`++ const result = await lmStudio.quickCompletion(analysisPrompt, {+ maxTokens: 256,+ temperature: 0.3,+ systemPrompt: 'You are a code analysis assistant. Respond only with valid JSON.'+ })++ if (!result.success) {+ stats.localFailures+++ return {+ complexity: keywordComplexity,+ escalateToCloud: keywordComplexity > COMPLEXITY_THRESHOLDS.medium,+ reason: `Local analysis failed: ${result.error}`,+ localAnalysis: false,+ suggestions: []+ }+ }++ stats.localSuccesses++++ // Parse local model response+ let analysis+ try {+ // Extract JSON from response+ const jsonMatch = result.content.match(/\{[\s\S]*\}/)+ analysis = jsonMatch ? JSON.parse(jsonMatch[0]) : null+ } catch (err) {+ analysis = null+ }++ if (!analysis) {+ return {+ complexity: keywordComplexity,+ escalateToCloud: keywordComplexity > COMPLEXITY_THRESHOLDS.medium,+ reason: 'Could not parse local analysis',+ localAnalysis: true,+ rawResponse: result.content,+ suggestions: []+ }+ }++ const complexity = analysis.complexity || keywordComplexity++ // Determine if cloud escalation is needed+ const needsCloud = shouldEscalateToCloud({+ complexity,+ requiresCodeUnderstanding: analysis.requiresCodeUnderstanding,+ requiresMultiFileChanges: analysis.requiresMultiFileChanges,+ requiresArchitecturalDecisions: analysis.requiresArchitecturalDecisions+ })++ if (needsCloud) {+ stats.cloudEscalations+++ }++ return {+ complexity,+ escalateToCloud: needsCloud,+ reason: needsCloud+ ? 'Task requires advanced reasoning'+ : 'Task suitable for local execution',+ localAnalysis: true,+ suggestedApproach: analysis.suggestedApproach,+ potentialRisks: analysis.potentialRisks || [],+ suggestions: analysis.potentialRisks || []+ }+}++/**+ * Estimate complexity from keywords+ * @param {string} text - Text to analyze+ * @returns {number} - Complexity score 0-1+ */+function estimateComplexityFromKeywords(text) {+ const lower = text.toLowerCase()++ let score = 0.5 // Default medium++ // Check high complexity keywords+ for (const keyword of COMPLEXITY_KEYWORDS.high) {+ if (lower.includes(keyword)) {+ score = Math.max(score, 0.8)+ }+ }++ // Check medium complexity keywords+ for (const keyword of COMPLEXITY_KEYWORDS.medium) {+ if (lower.includes(keyword)) {+ score = Math.max(score, 0.5)+ }+ }++ // Check low complexity keywords+ for (const keyword of COMPLEXITY_KEYWORDS.low) {+ if (lower.includes(keyword)) {+ score = Math.min(score, 0.3)+ }+ }++ // Length-based adjustment+ if (text.length > 500) score = Math.min(score + 0.1, 1)+ if (text.length > 1000) score = Math.min(score + 0.1, 1)++ return score+}++/**+ * Determine if a task should escalate to cloud+ * @param {Object} analysis - Task analysis+ * @returns {boolean} - True if should escalate+ */+function shouldEscalateToCloud(analysis) {+ // Always escalate very complex tasks+ if (analysis.complexity > COMPLEXITY_THRESHOLDS.complex) {+ return true+ }++ // Escalate if requires architectural decisions+ if (analysis.requiresArchitecturalDecisions) {+ return true+ }++ // Escalate if requires multi-file changes and is moderately complex+ if (analysis.requiresMultiFileChanges && analysis.complexity > COMPLEXITY_THRESHOLDS.medium) {+ return true+ }++ return false+}++/**+ * Classify a memory using local model+ * @param {string} content - Memory content+ * @returns {Promise<Object>} - Classification result+ */+async function classifyMemory(content) {+ const lmAvailable = await lmStudio.checkLMStudioAvailable()++ if (!lmAvailable) {+ return {+ success: false,+ error: 'LM Studio unavailable'+ }+ }++ const classifyPrompt = `Classify this memory into one of: fact, learning, preference, observation, decision, context.+Also extract relevant tags.++Memory: ${content.substring(0, 300)}++Respond with JSON only:+{+ "type": "fact|learning|preference|observation|decision|context",+ "category": "codebase|patterns|bugs|performance|other",+ "tags": ["tag1", "tag2"],+ "importance": 0.0-1.0+}`++ const result = await lmStudio.quickCompletion(classifyPrompt, {+ maxTokens: 128,+ temperature: 0.3,+ systemPrompt: 'You are a memory classification assistant. Respond only with valid JSON.'+ })++ if (!result.success) {+ return { success: false, error: result.error }+ }++ try {+ const jsonMatch = result.content.match(/\{[\s\S]*\}/)+ const classification = jsonMatch ? JSON.parse(jsonMatch[0]) : null++ return {+ success: true,+ ...classification+ }+ } catch (err) {+ return {+ success: false,+ error: 'Could not parse classification',+ rawResponse: result.content+ }+ }+}++/**+ * Quick completion for simple local tasks+ * @param {string} prompt - Prompt+ * @param {Object} options - Options+ * @returns {Promise<Object>} - Completion result+ */+async function quickCompletion(prompt, options = {}) {+ return lmStudio.quickCompletion(prompt, options)+}++/**+ * Get thinking service statistics+ * @returns {Object} - Statistics+ */+function getStats() {+ const lmStats = {+ localAnalyses: stats.localAnalyses,+ cloudEscalations: stats.cloudEscalations,+ localSuccesses: stats.localSuccesses,+ localFailures: stats.localFailures,+ localSuccessRate: stats.localAnalyses > 0+ ? ((stats.localSuccesses / stats.localAnalyses) * 100).toFixed(1) + '%'+ : '0%',+ escalationRate: stats.localAnalyses > 0+ ? ((stats.cloudEscalations / stats.localAnalyses) * 100).toFixed(1) + '%'+ : '0%'+ }++ return lmStats+}++/**+ * Reset statistics+ */+function resetStats() {+ stats.localAnalyses = 0+ stats.cloudEscalations = 0+ stats.localSuccesses = 0+ stats.localFailures = 0+}++/**+ * Pre-analyze a batch of tasks+ * @param {Array} tasks - Tasks to analyze+ * @returns {Promise<Array>} - Analysis results+ */+async function analyzeTaskBatch(tasks) {+ const results = []++ for (const task of tasks) {+ const analysis = await analyzeTask(task)+ results.push({+ taskId: task.id,+ description: task.description?.substring(0, 50),+ ...analysis+ })+ }++ return results+}++export {+ analyzeTask,+ estimateComplexityFromKeywords,+ shouldEscalateToCloud,+ classifyMemory,+ quickCompletion,+ getStats,+ resetStats,+ analyzeTaskBatch,+ COMPLEXITY_THRESHOLDS+}diff --git a/server/services/memory.js b/server/services/memory.jsindex a03eba6f02..d89833a99b 100644--- a/server/services/memory.js+++ b/server/services/memory.js@@ -14,6 +14,7 @@ import { cosEvents, updateAgent } from './cos.js';import { findTopK, findAboveThreshold, clusterBySimilarity, cosineSimilarity } from '../lib/vectorMath.js';import * as notifications from './notifications.js';import { readJSONFile } from '../lib/fileUtils.js';+import * as memoryBM25 from './memoryBM25.js';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -209,6 +210,15 @@ export async function createMemory(data, embedding = null) {await saveEmbeddings(embeddings);}+ // Index in BM25 for text search (async, non-blocking)+ memoryBM25.indexMemory({+ id: memory.id,+ content: memory.content,+ type: memory.type,+ tags: memory.tags,+ source: memory.sourceAppId+ }).catch(err => console.error(`⚠️ BM25 index error: ${err.message}`));+console.log(`🧠 Memory created: ${memory.type} - ${memory.summary.substring(0, 50)}...`);cosEvents.emit('memory:created', { id, type: memory.type, summary: memory.summary });@@ -324,6 +334,17 @@ export async function updateMemory(id, updates) {await saveIndex(index);}+ // Update BM25 index if content changed+ if (updates.content || updates.tags) {+ memoryBM25.indexMemory({+ id: memory.id,+ content: memory.content,+ type: memory.type,+ tags: memory.tags,+ source: memory.sourceAppId+ }).catch(err => console.error(`⚠️ BM25 index error: ${err.message}`));+ }+console.log(`🧠 Memory updated: ${id}`);cosEvents.emit('memory:updated', { id, updates });@@ -376,6 +397,10 @@ export async function deleteMemory(id, hard = false) {const embeddings = await loadEmbeddings();delete embeddings.vectors[id];await saveEmbeddings(embeddings);++ // Remove from BM25 index+ memoryBM25.removeMemoryFromIndex(id)+ .catch(err => console.error(`⚠️ BM25 remove error: ${err.message}`));} else {// Soft delete - mark as archivedawait updateMemory(id, { status: 'archived' });@@ -473,6 +498,10 @@ export async function rejectMemory(id) {delete embeddings.vectors[id];await saveEmbeddings(embeddings);+ // Remove from BM25 index+ memoryBM25.removeMemoryFromIndex(id)+ .catch(err => console.error(`⚠️ BM25 remove error: ${err.message}`));+console.log(`🧠 Memory rejected: ${id}`);cosEvents.emit('memory:rejected', { id });@@ -527,6 +556,119 @@ export async function searchMemories(queryEmbedding, options = {}) {return { total: results.length, memories: results };}+/**+ * Hybrid search combining BM25 text matching and vector similarity+ * Uses Reciprocal Rank Fusion (RRF) to merge rankings+ *+ * @param {string} query - Text query for BM25+ * @param {number[]} queryEmbedding - Vector embedding for semantic search+ * @param {Object} options - Search options+ * @returns {Promise<{total: number, memories: Array}>}+ */+export async function hybridSearchMemories(query, queryEmbedding, options = {}) {+ const { limit = 20, minRelevance = 0.5, bm25Weight = 0.4, vectorWeight = 0.6 } = options++ const index = await loadIndex()+ const embeddings = await loadEmbeddings()+ const indexMap = new Map(index.memories.map(m => [m.id, m]))++ // Get BM25 results+ const bm25Results = query+ ? await memoryBM25.searchBM25(query, { limit: limit * 2, threshold: 0.05 })+ : []++ // Get vector results+ let vectorResults = []+ if (queryEmbedding && Object.keys(embeddings.vectors).length > 0) {+ const similar = findAboveThreshold(queryEmbedding, embeddings.vectors, minRelevance * 0.5)+ vectorResults = similar.slice(0, limit * 2).map(r => ({+ id: r.id,+ score: r.similarity+ }))+ }++ // Apply Reciprocal Rank Fusion (RRF)+ // RRF score = sum(1 / (k + rank)) across all rankings+ const RRF_K = 60 // Standard RRF constant+ const rrfScores = new Map()++ // Add BM25 contributions+ bm25Results.forEach((result, rank) => {+ const current = rrfScores.get(result.id) || { bm25Rank: null, vectorRank: null, rrfScore: 0 }+ current.bm25Rank = rank + 1+ current.rrfScore += bm25Weight / (RRF_K + rank + 1)+ rrfScores.set(result.id, current)+ })++ // Add vector contributions+ vectorResults.forEach((result, rank) => {+ const current = rrfScores.get(result.id) || { bm25Rank: null, vectorRank: null, rrfScore: 0 }+ current.vectorRank = rank + 1+ current.rrfScore += vectorWeight / (RRF_K + rank + 1)+ rrfScores.set(result.id, current)+ })++ // Filter and sort by RRF score+ let results = Array.from(rrfScores.entries())+ .map(([id, data]) => {+ const meta = indexMap.get(id)+ if (!meta || meta.status !== 'active') return null++ // Apply type/category/tag/app filters+ if (options.types?.length > 0 && !options.types.includes(meta.type)) return null+ if (options.categories?.length > 0 && !options.categories.includes(meta.category)) return null+ if (options.tags?.length > 0 && !meta.tags.some(t => options.tags.includes(t))) return null+ if (options.appId && meta.sourceAppId !== options.appId) return null++ return {+ ...meta,+ rrfScore: data.rrfScore,+ bm25Rank: data.bm25Rank,+ vectorRank: data.vectorRank,+ searchMethod: data.bm25Rank && data.vectorRank ? 'hybrid' :+ data.bm25Rank ? 'bm25' : 'vector'+ }+ })+ .filter(Boolean)+ .sort((a, b) => b.rrfScore - a.rrfScore)+ .slice(0, limit)++ return { total: results.length, memories: results }+}++/**+ * Rebuild the BM25 index from all memories+ * Call this after bulk imports or to fix index inconsistencies+ */+export async function rebuildBM25Index() {+ const index = await loadIndex()+ const activeMemories = index.memories.filter(m => m.status === 'active')++ // Load full content for each memory+ const documents = []+ for (const meta of activeMemories) {+ const memory = await loadMemory(meta.id)+ if (memory) {+ documents.push({+ id: memory.id,+ content: memory.content,+ type: memory.type,+ tags: memory.tags,+ source: memory.sourceAppId+ })+ }+ }++ return memoryBM25.rebuildIndex(documents)+}++/**+ * Get BM25 index statistics+ */+export async function getBM25Stats() {+ return memoryBM25.getStats()+}+/*** Get timeline data (memories grouped by date)*/@@ -903,3 +1045,10 @@ export function invalidateCaches() {indexCache = null;embeddingsCache = null;}++/**+ * Flush BM25 index to disk+ */+export async function flushBM25Index() {+ return memoryBM25.flush();+}diff --git a/server/services/memoryBM25.js b/server/services/memoryBM25.jsnew file mode 100644index 0000000000..b6041e93fe--- /dev/null+++ b/server/services/memoryBM25.js@@ -0,0 +1,247 @@+/**+ * BM25 Index Manager for Memory System+ *+ * Manages the BM25 inverted index for text-based memory search.+ * Complements the vector-based semantic search with keyword matching.+ */++import { promises as fs } from 'fs'+import path from 'path'+import {+ buildInvertedIndex,+ addDocument,+ removeDocument,+ search,+ createEmptyIndex,+ serializeIndex,+ deserializeIndex,+ getIndexStats+} from '../lib/bm25.js'++const DATA_DIR = path.join(process.cwd(), 'data', 'cos', 'memory')+const INDEX_FILE = path.join(DATA_DIR, 'bm25-index.json')++// In-memory cache of the index+let indexCache = null+let isDirty = false++/**+ * Ensure the data directory exists+ */+async function ensureDataDir() {+ await fs.mkdir(DATA_DIR, { recursive: true })+}++/**+ * Load the BM25 index from disk+ * @returns {Promise<Object>} - The BM25 index+ */+async function loadIndex() {+ if (indexCache) return indexCache++ await ensureDataDir()++ const exists = await fs.access(INDEX_FILE).then(() => true).catch(() => false)++ if (!exists) {+ indexCache = createEmptyIndex()+ return indexCache+ }++ const data = await fs.readFile(INDEX_FILE, 'utf-8')+ indexCache = deserializeIndex(JSON.parse(data))+ return indexCache+}++/**+ * Save the BM25 index to disk+ * @returns {Promise<void>}+ */+async function saveIndex() {+ if (!indexCache || !isDirty) return++ await ensureDataDir()+ const serialized = serializeIndex(indexCache)+ await fs.writeFile(INDEX_FILE, JSON.stringify(serialized, null, 2))+ isDirty = false++ console.log(`💾 BM25 index saved: ${indexCache.totalDocs} docs, ${Object.keys(indexCache.terms).length} terms`)+}++/**+ * Build or rebuild the entire index from memories+ * @param {Array<{id: string, content: string, type: string, tags: string[]}>} memories+ * @returns {Promise<Object>} - Index statistics+ */+async function rebuildIndex(memories) {+ await ensureDataDir()++ // Convert memories to documents for indexing+ const documents = memories.map(m => ({+ id: m.id,+ text: buildIndexableText(m)+ }))++ indexCache = buildInvertedIndex(documents)+ isDirty = true++ await saveIndex()++ console.log(`🔄 BM25 index rebuilt: ${indexCache.totalDocs} memories indexed`)+ return getIndexStats(indexCache)+}++/**+ * Build indexable text from a memory object+ * Combines content, type, and tags for better matching+ *+ * @param {Object} memory - Memory object+ * @returns {string} - Text for indexing+ */+function buildIndexableText(memory) {+ const parts = []++ if (memory.content) {+ parts.push(memory.content)+ }++ if (memory.type) {+ parts.push(memory.type)+ }++ if (memory.tags && Array.isArray(memory.tags)) {+ parts.push(memory.tags.join(' '))+ }++ if (memory.source) {+ parts.push(memory.source)+ }++ return parts.join(' ')+}++/**+ * Add or update a memory in the index+ * @param {Object} memory - Memory object with id, content, type, tags+ * @returns {Promise<void>}+ */+async function indexMemory(memory) {+ const index = await loadIndex()++ const text = buildIndexableText(memory)+ addDocument(index, memory.id, text)+ isDirty = true++ // Save periodically (every 10 changes) or on explicit flush+ if (isDirty && index.totalDocs % 10 === 0) {+ await saveIndex()+ }+}++/**+ * Remove a memory from the index+ * @param {string} memoryId - Memory ID to remove+ * @returns {Promise<void>}+ */+async function removeMemoryFromIndex(memoryId) {+ const index = await loadIndex()+ removeDocument(index, memoryId)+ isDirty = true+}++/**+ * Search memories using BM25 text matching+ *+ * @param {string} query - Search query+ * @param {Object} options - Search options+ * @param {number} options.limit - Maximum results (default 20)+ * @param {number} options.threshold - Minimum score threshold (default 0.1)+ * @returns {Promise<Array<{id: string, score: number}>>} - Ranked memory IDs with scores+ */+async function searchBM25(query, options = {}) {+ const { limit = 20, threshold = 0.1 } = options++ const index = await loadIndex()+ const results = search(query, index, { limit, threshold })++ return results.map(r => ({+ id: r.docId,+ score: r.score+ }))+}++/**+ * Get index statistics+ * @returns {Promise<Object>} - Index statistics+ */+async function getStats() {+ const index = await loadIndex()+ return {+ ...getIndexStats(index),+ isDirty,+ indexFile: INDEX_FILE+ }+}++/**+ * Flush pending changes to disk+ * @returns {Promise<void>}+ */+async function flush() {+ await saveIndex()+}++/**+ * Clear the entire index+ * @returns {Promise<void>}+ */+async function clearIndex() {+ indexCache = createEmptyIndex()+ isDirty = true+ await saveIndex()+ console.log('🗑️ BM25 index cleared')+}++/**+ * Check if a memory exists in the index+ * @param {string} memoryId - Memory ID+ * @returns {Promise<boolean>}+ */+async function hasMemory(memoryId) {+ const index = await loadIndex()+ return index.docIds.has(memoryId)+}++/**+ * Batch index multiple memories efficiently+ * @param {Array<Object>} memories - Memories to index+ * @returns {Promise<number>} - Number of memories indexed+ */+async function batchIndex(memories) {+ const index = await loadIndex()++ for (const memory of memories) {+ const text = buildIndexableText(memory)+ addDocument(index, memory.id, text)+ }++ isDirty = true+ await saveIndex()++ return memories.length+}++export {+ loadIndex,+ saveIndex,+ rebuildIndex,+ indexMemory,+ removeMemoryFromIndex,+ searchBM25,+ getStats,+ flush,+ clearIndex,+ hasMemory,+ batchIndex,+ buildIndexableText+}diff --git a/server/services/memoryRetriever.js b/server/services/memoryRetriever.jsindex 1f14436294..dda02e155a 100644--- a/server/services/memoryRetriever.js+++ b/server/services/memoryRetriever.js@@ -5,10 +5,13 @@* Combines semantic search with importance scoring.*/-import { getMemories, searchMemories, getMemory } from './memory.js';+import { getMemories, searchMemories, hybridSearchMemories, getMemory } from './memory.js';import { generateQueryEmbedding, estimateTokens, truncateToTokens } from './memoryEmbeddings.js';import { DEFAULT_MEMORY_CONFIG } from './memory.js';+// Search mode preference+const SEARCH_MODE = 'hybrid'; // 'hybrid' | 'vector' | 'bm25'+/*** Get relevant memories for a task* Returns formatted text ready for injection into agent prompt@@ -20,28 +23,38 @@ export async function getRelevantMemories(task, options = {}) {const memories = [];let tokenCount = 0;- // 1. Semantic search based on task description+ // 1. Search based on task description (hybrid BM25 + vector or vector-only)if (task.description) {const queryEmbedding = await generateQueryEmbedding(task.description);+ let searchResults = { memories: [] };- if (queryEmbedding) {- const searchResults = await searchMemories(queryEmbedding, {+ if (SEARCH_MODE === 'hybrid' && queryEmbedding) {+ // Use hybrid BM25 + vector search with reciprocal rank fusion+ searchResults = await hybridSearchMemories(task.description, queryEmbedding, {+ limit: 20,+ minRelevance,+ bm25Weight: 0.4,+ vectorWeight: 0.6+ });+ } else if (queryEmbedding) {+ // Fallback to vector-only search+ 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;- }+ 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.rrfScore || result.similarity || 0.5,+ source: result.searchMethod || 'semantic'+ });+ tokenCount += tokens;}}}diff --git a/server/services/missions.js b/server/services/missions.jsnew file mode 100644index 0000000000..aac4cce8b5--- /dev/null+++ b/server/services/missions.js@@ -0,0 +1,420 @@+/**+ * Missions Service+ *+ * Long-term goals with sub-tasks and app ownership.+ * Enables proactive task generation when user queue is empty.+ */++import { promises as fs } from 'fs'+import path from 'path'+import { v4 as uuidv4 } from 'uuid'+import { cosEvents } from './cos.js'++const DATA_DIR = path.join(process.cwd(), 'data', 'cos', 'missions')++// In-memory cache+let missionsCache = null++/**+ * Ensure data directory exists+ */+async function ensureDataDir() {+ await fs.mkdir(DATA_DIR, { recursive: true })+}++/**+ * Load all missions+ * @returns {Promise<Array>} - All missions+ */+async function loadMissions() {+ if (missionsCache) return missionsCache++ await ensureDataDir()++ const files = await fs.readdir(DATA_DIR).catch(() => [])+ const missions = []++ for (const file of files) {+ if (!file.endsWith('.json')) continue++ const filePath = path.join(DATA_DIR, file)+ const content = await fs.readFile(filePath, 'utf-8').catch(() => null)+ if (content) {+ const mission = JSON.parse(content)+ missions.push(mission)+ }+ }++ missionsCache = missions+ return missions+}++/**+ * Save a mission to disk+ * @param {Object} mission - Mission object+ */+async function saveMission(mission) {+ await ensureDataDir()+ const filePath = path.join(DATA_DIR, `${mission.id}.json`)+ await fs.writeFile(filePath, JSON.stringify(mission, null, 2))++ // Update cache+ if (missionsCache) {+ const idx = missionsCache.findIndex(m => m.id === mission.id)+ if (idx !== -1) {+ missionsCache[idx] = mission+ } else {+ missionsCache.push(mission)+ }+ }+}++/**+ * Create a new mission+ * @param {Object} data - Mission data+ * @returns {Promise<Object>} - Created mission+ */+async function createMission(data) {+ const now = new Date().toISOString()++ const mission = {+ id: data.id || uuidv4(),+ appId: data.appId,+ name: data.name,+ description: data.description || '',+ goals: data.goals || [],+ subTasks: data.subTasks || [],+ progress: 0,+ status: 'active', // active, paused, completed, archived+ priority: data.priority || 'medium',+ autonomyLevel: data.autonomyLevel || 'full', // full, notify, approval-required+ createdAt: now,+ updatedAt: now,+ lastReviewedAt: null,+ completedAt: null,+ metrics: {+ tasksGenerated: 0,+ tasksCompleted: 0,+ successRate: 0+ }+ }++ await saveMission(mission)++ console.log(`🎯 Mission created: ${mission.name} (${mission.appId})`)+ cosEvents.emit('mission:created', { id: mission.id, appId: mission.appId })++ return mission+}++/**+ * Get mission by ID+ * @param {string} id - Mission ID+ * @returns {Promise<Object|null>} - Mission or null+ */+async function getMission(id) {+ const missions = await loadMissions()+ return missions.find(m => m.id === id) || null+}++/**+ * Get missions for an app+ * @param {string} appId - App identifier+ * @returns {Promise<Array>} - App missions+ */+async function getMissionsForApp(appId) {+ const missions = await loadMissions()+ return missions.filter(m => m.appId === appId && m.status === 'active')+}++/**+ * Get all active missions+ * @returns {Promise<Array>} - Active missions+ */+async function getActiveMissions() {+ const missions = await loadMissions()+ return missions.filter(m => m.status === 'active')+}++/**+ * Update a mission+ * @param {string} id - Mission ID+ * @param {Object} updates - Updates to apply+ * @returns {Promise<Object|null>} - Updated mission or null+ */+async function updateMission(id, updates) {+ const mission = await getMission(id)+ if (!mission) return null++ const updatableFields = [+ 'name', 'description', 'goals', 'subTasks', 'progress',+ 'status', 'priority', 'autonomyLevel', 'lastReviewedAt',+ 'completedAt', 'metrics'+ ]++ for (const field of updatableFields) {+ if (updates[field] !== undefined) {+ mission[field] = updates[field]+ }+ }++ mission.updatedAt = new Date().toISOString()+ await saveMission(mission)++ cosEvents.emit('mission:updated', { id: mission.id, updates })+ return mission+}++/**+ * Add a sub-task to a mission+ * @param {string} missionId - Mission ID+ * @param {Object} subTask - Sub-task data+ * @returns {Promise<Object|null>} - Updated mission or null+ */+async function addSubTask(missionId, subTask) {+ const mission = await getMission(missionId)+ if (!mission) return null++ const task = {+ id: uuidv4(),+ description: subTask.description,+ status: 'pending', // pending, in_progress, completed, failed+ priority: subTask.priority || 'medium',+ createdAt: new Date().toISOString(),+ completedAt: null,+ result: null+ }++ mission.subTasks.push(task)+ mission.metrics.tasksGenerated+++ mission.updatedAt = new Date().toISOString()++ await saveMission(mission)+ return mission+}++/**+ * Complete a sub-task+ * @param {string} missionId - Mission ID+ * @param {string} subTaskId - Sub-task ID+ * @param {Object} result - Task result+ * @returns {Promise<Object|null>} - Updated mission or null+ */+async function completeSubTask(missionId, subTaskId, result = {}) {+ const mission = await getMission(missionId)+ if (!mission) return null++ const subTask = mission.subTasks.find(t => t.id === subTaskId)+ if (!subTask) return null++ subTask.status = result.success === false ? 'failed' : 'completed'+ subTask.completedAt = new Date().toISOString()+ subTask.result = result++ // Update metrics+ if (subTask.status === 'completed') {+ mission.metrics.tasksCompleted+++ }+ mission.metrics.successRate = mission.metrics.tasksGenerated > 0+ ? (mission.metrics.tasksCompleted / mission.metrics.tasksGenerated) * 100+ : 0++ // Calculate progress+ const completed = mission.subTasks.filter(t => t.status === 'completed').length+ const total = mission.subTasks.length+ mission.progress = total > 0 ? (completed / total) * 100 : 0++ // Check if mission is complete+ if (mission.progress >= 100 && mission.goals.length > 0) {+ mission.status = 'completed'+ mission.completedAt = new Date().toISOString()+ console.log(`🎉 Mission completed: ${mission.name}`)+ cosEvents.emit('mission:completed', { id: mission.id })+ }++ mission.updatedAt = new Date().toISOString()+ await saveMission(mission)++ return mission+}++/**+ * Generate a task from a mission (for proactive execution)+ * @param {string} missionId - Mission ID+ * @returns {Promise<Object|null>} - Generated task or null+ */+async function generateMissionTask(missionId) {+ const mission = await getMission(missionId)+ if (!mission || mission.status !== 'active') return null++ // Find pending sub-tasks+ const pendingSubTasks = mission.subTasks.filter(t => t.status === 'pending')++ if (pendingSubTasks.length > 0) {+ // Return first pending sub-task as a COS task+ const subTask = pendingSubTasks[0]+ subTask.status = 'in_progress'+ await saveMission(mission)++ return {+ id: `mission-${mission.id}-${subTask.id}`,+ description: subTask.description,+ metadata: {+ missionId: mission.id,+ missionName: mission.name,+ subTaskId: subTask.id,+ appId: mission.appId,+ autonomyLevel: mission.autonomyLevel,+ isMissionTask: true+ },+ priority: subTask.priority,+ autoApprove: mission.autonomyLevel === 'full'+ }+ }++ // No pending sub-tasks - might need to generate new ones based on goals+ // This would typically involve AI analysis of the mission goals+ return null+}++/**+ * Generate proactive tasks from all active missions+ * @param {Object} options - Generation options+ * @returns {Promise<Array>} - Generated tasks+ */+async function generateProactiveTasks(options = {}) {+ const { maxTasks = 3 } = options+ const missions = await getActiveMissions()+ const tasks = []++ for (const mission of missions) {+ if (tasks.length >= maxTasks) break++ // Skip recently reviewed missions+ if (mission.lastReviewedAt) {+ const lastReview = new Date(mission.lastReviewedAt).getTime()+ const hoursSinceReview = (Date.now() - lastReview) / (1000 * 60 * 60)+ if (hoursSinceReview < 1) continue // Wait at least 1 hour between reviews+ }++ const task = await generateMissionTask(mission.id)+ if (task) {+ tasks.push(task)+ }+ }++ return tasks+}++/**+ * Record mission review (updates lastReviewedAt)+ * @param {string} missionId - Mission ID+ * @returns {Promise<Object|null>} - Updated mission or null+ */+async function recordMissionReview(missionId) {+ return updateMission(missionId, {+ lastReviewedAt: new Date().toISOString()+ })+}++/**+ * Get mission statistics+ * @returns {Promise<Object>} - Mission statistics+ */+async function getStats() {+ const missions = await loadMissions()++ const byStatus = {}+ let totalProgress = 0+ let totalTasks = 0+ let completedTasks = 0++ for (const mission of missions) {+ byStatus[mission.status] = (byStatus[mission.status] || 0) + 1+ totalProgress += mission.progress+ totalTasks += mission.subTasks.length+ completedTasks += mission.subTasks.filter(t => t.status === 'completed').length+ }++ return {+ totalMissions: missions.length,+ byStatus,+ averageProgress: missions.length > 0+ ? (totalProgress / missions.length).toFixed(1) + '%'+ : '0%',+ totalSubTasks: totalTasks,+ completedSubTasks: completedTasks,+ overallCompletion: totalTasks > 0+ ? ((completedTasks / totalTasks) * 100).toFixed(1) + '%'+ : '0%'+ }+}++/**+ * Delete a mission+ * @param {string} id - Mission ID+ * @returns {Promise<boolean>} - True if deleted+ */+async function deleteMission(id) {+ const filePath = path.join(DATA_DIR, `${id}.json`)+ await fs.unlink(filePath).catch(() => {})++ if (missionsCache) {+ missionsCache = missionsCache.filter(m => m.id !== id)+ }++ console.log(`🗑️ Mission deleted: ${id}`)+ cosEvents.emit('mission:deleted', { id })+ return true+}++/**+ * Archive completed missions+ * @returns {Promise<number>} - Number of missions archived+ */+async function archiveCompletedMissions() {+ const missions = await loadMissions()+ let archived = 0++ for (const mission of missions) {+ if (mission.status === 'completed' && mission.completedAt) {+ const completedDate = new Date(mission.completedAt).getTime()+ const daysSinceCompletion = (Date.now() - completedDate) / (1000 * 60 * 60 * 24)++ if (daysSinceCompletion > 7) {+ await updateMission(mission.id, { status: 'archived' })+ archived+++ }+ }+ }++ if (archived > 0) {+ console.log(`📦 Archived ${archived} completed missions`)+ }++ return archived+}++/**+ * Invalidate cache (call after external changes)+ */+function invalidateCache() {+ missionsCache = null+}++export {+ createMission,+ getMission,+ getMissionsForApp,+ getActiveMissions,+ updateMission,+ addSubTask,+ completeSubTask,+ generateMissionTask,+ generateProactiveTasks,+ recordMissionReview,+ getStats,+ deleteMission,+ archiveCompletedMissions,+ invalidateCache+}diff --git a/server/services/missions.test.js b/server/services/missions.test.jsnew file mode 100644index 0000000000..615bb73c59--- /dev/null+++ b/server/services/missions.test.js@@ -0,0 +1,375 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { promises as fs } from 'fs';+import path from 'path';++// Mock cosEvents before import+vi.mock('./cos.js', () => ({+ cosEvents: {+ emit: vi.fn()+ }+}));++import {+ createMission,+ getMission,+ getMissionsForApp,+ getActiveMissions,+ updateMission,+ addSubTask,+ completeSubTask,+ generateMissionTask,+ generateProactiveTasks,+ recordMissionReview,+ getStats,+ deleteMission,+ archiveCompletedMissions,+ invalidateCache+} from './missions.js';++const DATA_DIR = path.join(process.cwd(), 'data', 'cos', 'missions');++describe('Missions Service', () => {+ beforeEach(async () => {+ invalidateCache();+ // Clean up test missions+ const files = await fs.readdir(DATA_DIR).catch(() => []);+ for (const file of files) {+ if (file.startsWith('test-')) {+ await fs.unlink(path.join(DATA_DIR, file)).catch(() => {});+ }+ }+ });++ afterEach(() => {+ invalidateCache();+ });++ describe('createMission', () => {+ it('should create a new mission with defaults', async () => {+ const mission = await createMission({+ id: 'test-mission-1',+ appId: 'test-app',+ name: 'Test Mission'+ });++ expect(mission.id).toBe('test-mission-1');+ expect(mission.appId).toBe('test-app');+ expect(mission.name).toBe('Test Mission');+ expect(mission.status).toBe('active');+ expect(mission.progress).toBe(0);+ expect(mission.autonomyLevel).toBe('full');++ await deleteMission('test-mission-1');+ });++ it('should set custom fields', async () => {+ const mission = await createMission({+ id: 'test-mission-2',+ appId: 'test-app',+ name: 'Test Mission',+ description: 'Test description',+ goals: ['Goal 1', 'Goal 2'],+ priority: 'high',+ autonomyLevel: 'approval-required'+ });++ expect(mission.description).toBe('Test description');+ expect(mission.goals).toEqual(['Goal 1', 'Goal 2']);+ expect(mission.priority).toBe('high');+ expect(mission.autonomyLevel).toBe('approval-required');++ await deleteMission('test-mission-2');+ });+ });++ describe('getMission', () => {+ it('should retrieve a mission by ID', async () => {+ const created = await createMission({+ id: 'test-get-mission',+ appId: 'test-app',+ name: 'Get Test'+ });++ const retrieved = await getMission('test-get-mission');+ expect(retrieved).not.toBeNull();+ expect(retrieved.id).toBe('test-get-mission');++ await deleteMission('test-get-mission');+ });++ it('should return null for non-existent mission', async () => {+ const result = await getMission('nonexistent');+ expect(result).toBeNull();+ });+ });++ describe('getMissionsForApp', () => {+ it('should get missions for a specific app', async () => {+ await createMission({+ id: 'test-app-mission-1',+ appId: 'specific-app',+ name: 'Mission 1'+ });+ await createMission({+ id: 'test-app-mission-2',+ appId: 'specific-app',+ name: 'Mission 2'+ });+ await createMission({+ id: 'test-app-mission-3',+ appId: 'other-app',+ name: 'Mission 3'+ });++ const missions = await getMissionsForApp('specific-app');+ expect(missions.length).toBe(2);+ expect(missions.every(m => m.appId === 'specific-app')).toBe(true);++ await deleteMission('test-app-mission-1');+ await deleteMission('test-app-mission-2');+ await deleteMission('test-app-mission-3');+ });+ });++ describe('updateMission', () => {+ it('should update mission fields', async () => {+ await createMission({+ id: 'test-update-mission',+ appId: 'test-app',+ name: 'Update Test'+ });++ const updated = await updateMission('test-update-mission', {+ progress: 50,+ status: 'paused'+ });++ expect(updated.progress).toBe(50);+ expect(updated.status).toBe('paused');++ await deleteMission('test-update-mission');+ });++ it('should return null for non-existent mission', async () => {+ const result = await updateMission('nonexistent', { progress: 50 });+ expect(result).toBeNull();+ });+ });++ describe('addSubTask', () => {+ it('should add a sub-task to a mission', async () => {+ await createMission({+ id: 'test-subtask-mission',+ appId: 'test-app',+ name: 'SubTask Test'+ });++ const updated = await addSubTask('test-subtask-mission', {+ description: 'Sub-task 1',+ priority: 'high'+ });++ expect(updated.subTasks.length).toBe(1);+ expect(updated.subTasks[0].description).toBe('Sub-task 1');+ expect(updated.subTasks[0].status).toBe('pending');+ expect(updated.metrics.tasksGenerated).toBe(1);++ await deleteMission('test-subtask-mission');+ });+ });++ describe('completeSubTask', () => {+ it('should mark sub-task as completed', async () => {+ await createMission({+ id: 'test-complete-mission',+ appId: 'test-app',+ name: 'Complete Test'+ });++ const withTask = await addSubTask('test-complete-mission', {+ description: 'Task to complete'+ });++ const subTaskId = withTask.subTasks[0].id;+ const updated = await completeSubTask('test-complete-mission', subTaskId, {+ success: true,+ output: 'Task completed'+ });++ expect(updated.subTasks[0].status).toBe('completed');+ expect(updated.metrics.tasksCompleted).toBe(1);+ expect(updated.progress).toBe(100);++ await deleteMission('test-complete-mission');+ });++ it('should mark sub-task as failed', async () => {+ await createMission({+ id: 'test-fail-mission',+ appId: 'test-app',+ name: 'Fail Test'+ });++ const withTask = await addSubTask('test-fail-mission', {+ description: 'Task to fail'+ });++ const subTaskId = withTask.subTasks[0].id;+ const updated = await completeSubTask('test-fail-mission', subTaskId, {+ success: false,+ error: 'Task failed'+ });++ expect(updated.subTasks[0].status).toBe('failed');+ expect(updated.metrics.tasksCompleted).toBe(0);++ await deleteMission('test-fail-mission');+ });+ });++ describe('generateMissionTask', () => {+ it('should generate task from pending sub-task', async () => {+ await createMission({+ id: 'test-generate-mission',+ appId: 'test-app',+ name: 'Generate Test'+ });++ await addSubTask('test-generate-mission', {+ description: 'Pending task',+ priority: 'high'+ });++ const task = await generateMissionTask('test-generate-mission');++ expect(task).not.toBeNull();+ expect(task.description).toBe('Pending task');+ expect(task.metadata.missionId).toBe('test-generate-mission');+ expect(task.metadata.isMissionTask).toBe(true);++ await deleteMission('test-generate-mission');+ });++ it('should return null for mission with no pending tasks', async () => {+ await createMission({+ id: 'test-no-pending-mission',+ appId: 'test-app',+ name: 'No Pending Test'+ });++ const task = await generateMissionTask('test-no-pending-mission');+ expect(task).toBeNull();++ await deleteMission('test-no-pending-mission');+ });+ });++ describe('generateProactiveTasks', () => {+ it('should generate tasks from active missions', async () => {+ await createMission({+ id: 'test-proactive-1',+ appId: 'test-app',+ name: 'Proactive 1'+ });++ await addSubTask('test-proactive-1', {+ description: 'Proactive task 1'+ });++ const tasks = await generateProactiveTasks({ maxTasks: 5 });+ expect(tasks.length).toBeGreaterThanOrEqual(1);++ await deleteMission('test-proactive-1');+ });++ it('should respect maxTasks limit', async () => {+ await createMission({+ id: 'test-proactive-limit',+ appId: 'test-app',+ name: 'Limit Test'+ });++ await addSubTask('test-proactive-limit', { description: 'Task 1' });+ await addSubTask('test-proactive-limit', { description: 'Task 2' });+ await addSubTask('test-proactive-limit', { description: 'Task 3' });++ const tasks = await generateProactiveTasks({ maxTasks: 1 });+ expect(tasks.length).toBeLessThanOrEqual(1);++ await deleteMission('test-proactive-limit');+ });+ });++ describe('recordMissionReview', () => {+ it('should update lastReviewedAt', async () => {+ await createMission({+ id: 'test-review-mission',+ appId: 'test-app',+ name: 'Review Test'+ });++ const updated = await recordMissionReview('test-review-mission');+ expect(updated.lastReviewedAt).not.toBeNull();++ await deleteMission('test-review-mission');+ });+ });++ describe('getStats', () => {+ it('should return mission statistics', async () => {+ await createMission({+ id: 'test-stats-mission',+ appId: 'test-app',+ name: 'Stats Test'+ });++ const stats = await getStats();+ expect(stats).toHaveProperty('totalMissions');+ expect(stats).toHaveProperty('byStatus');+ expect(stats).toHaveProperty('averageProgress');++ await deleteMission('test-stats-mission');+ });+ });++ describe('deleteMission', () => {+ it('should delete a mission', async () => {+ await createMission({+ id: 'test-delete-mission',+ appId: 'test-app',+ name: 'Delete Test'+ });++ const deleted = await deleteMission('test-delete-mission');+ expect(deleted).toBe(true);++ const retrieved = await getMission('test-delete-mission');+ expect(retrieved).toBeNull();+ });+ });++ describe('archiveCompletedMissions', () => {+ it('should archive old completed missions', async () => {+ // Create a mission and mark it completed+ await createMission({+ id: 'test-archive-mission',+ appId: 'test-app',+ name: 'Archive Test'+ });++ await updateMission('test-archive-mission', {+ status: 'completed',+ completedAt: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString() // 8 days ago+ });++ const archived = await archiveCompletedMissions();+ expect(archived).toBeGreaterThanOrEqual(0);++ const mission = await getMission('test-archive-mission');+ if (mission) {+ expect(mission.status).toBe('archived');+ await deleteMission('test-archive-mission');+ }+ });+ });+});diff --git a/server/services/sessionDelta.js b/server/services/sessionDelta.jsnew file mode 100644index 0000000000..ba9c96b1a6--- /dev/null+++ b/server/services/sessionDelta.js@@ -0,0 +1,348 @@+/**+ * Session Delta Tracker+ *+ * Tracks changes (deltas) within agent sessions for efficient memory and context updates.+ * Inspired by OpenClaw's session delta tracking pattern.+ *+ * Tracks per session:+ * - pendingBytes: Bytes of data pending processing+ * - pendingMessages: Count of messages pending processing+ * - newMemories: Memories created this session+ * - modifiedMemories: Memories updated this session+ * - toolCalls: Tool calls made this session+ */++// In-memory session delta storage+const sessions = new Map()++// Session TTL (2 hours)+const SESSION_TTL_MS = 2 * 60 * 60 * 1000++// Cleanup interval (15 minutes)+const CLEANUP_INTERVAL_MS = 15 * 60 * 1000++let cleanupTimer = null++/**+ * Create a new session delta tracker+ * @returns {Object} - Fresh session delta object+ */+function createSessionDelta() {+ return {+ createdAt: Date.now(),+ lastActivityAt: Date.now(),+ pendingBytes: 0,+ pendingMessages: 0,+ processedBytes: 0,+ processedMessages: 0,+ newMemories: [],+ modifiedMemories: [],+ toolCalls: [],+ events: []+ }+}++/**+ * Get or create session delta+ * @param {string} sessionId - Session identifier (usually agentId)+ * @returns {Object} - Session delta object+ */+function getSession(sessionId) {+ if (!sessions.has(sessionId)) {+ sessions.set(sessionId, createSessionDelta())+ }+ const session = sessions.get(sessionId)+ session.lastActivityAt = Date.now()+ return session+}++/**+ * Add pending bytes to session+ * @param {string} sessionId - Session ID+ * @param {number} bytes - Bytes to add+ */+function addPendingBytes(sessionId, bytes) {+ const session = getSession(sessionId)+ session.pendingBytes += bytes+ session.pendingMessages+++}++/**+ * Mark bytes as processed+ * @param {string} sessionId - Session ID+ * @param {number} bytes - Bytes processed+ */+function markBytesProcessed(sessionId, bytes) {+ const session = getSession(sessionId)+ session.pendingBytes = Math.max(0, session.pendingBytes - bytes)+ session.pendingMessages = Math.max(0, session.pendingMessages - 1)+ session.processedBytes += bytes+ session.processedMessages+++}++/**+ * Record a new memory created in this session+ * @param {string} sessionId - Session ID+ * @param {string} memoryId - Memory ID+ * @param {string} type - Memory type+ */+function recordNewMemory(sessionId, memoryId, type) {+ const session = getSession(sessionId)+ session.newMemories.push({+ id: memoryId,+ type,+ createdAt: Date.now()+ })+}++/**+ * Record a memory modification in this session+ * @param {string} sessionId - Session ID+ * @param {string} memoryId - Memory ID+ * @param {string} changeType - Type of change (update, archive, etc.)+ */+function recordModifiedMemory(sessionId, memoryId, changeType) {+ const session = getSession(sessionId)+ session.modifiedMemories.push({+ id: memoryId,+ changeType,+ modifiedAt: Date.now()+ })+}++/**+ * Record a tool call in this session+ * @param {string} sessionId - Session ID+ * @param {string} toolName - Name of tool called+ * @param {Object} metadata - Optional metadata about the call+ */+function recordToolCall(sessionId, toolName, metadata = {}) {+ const session = getSession(sessionId)+ session.toolCalls.push({+ tool: toolName,+ calledAt: Date.now(),+ ...metadata+ })+}++/**+ * Record a custom event in this session+ * @param {string} sessionId - Session ID+ * @param {string} eventType - Event type+ * @param {Object} data - Event data+ */+function recordEvent(sessionId, eventType, data = {}) {+ const session = getSession(sessionId)+ session.events.push({+ type: eventType,+ timestamp: Date.now(),+ data+ })+}++/**+ * Get session summary+ * @param {string} sessionId - Session ID+ * @returns {Object} - Session summary+ */+function getSessionSummary(sessionId) {+ if (!sessions.has(sessionId)) {+ return null+ }++ const session = sessions.get(sessionId)+ return {+ sessionId,+ createdAt: session.createdAt,+ lastActivityAt: session.lastActivityAt,+ durationMs: session.lastActivityAt - session.createdAt,+ pending: {+ bytes: session.pendingBytes,+ messages: session.pendingMessages+ },+ processed: {+ bytes: session.processedBytes,+ messages: session.processedMessages+ },+ memories: {+ new: session.newMemories.length,+ modified: session.modifiedMemories.length+ },+ toolCalls: session.toolCalls.length,+ events: session.events.length+ }+}++/**+ * Get all pending data for a session+ * @param {string} sessionId - Session ID+ * @returns {Object} - Pending data+ */+function getPendingDelta(sessionId) {+ if (!sessions.has(sessionId)) {+ return { bytes: 0, messages: 0 }+ }++ const session = sessions.get(sessionId)+ return {+ bytes: session.pendingBytes,+ messages: session.pendingMessages+ }+}++/**+ * Get memories created in this session+ * @param {string} sessionId - Session ID+ * @returns {Array} - New memory references+ */+function getNewMemories(sessionId) {+ if (!sessions.has(sessionId)) return []+ return [...sessions.get(sessionId).newMemories]+}++/**+ * Get tool call history for this session+ * @param {string} sessionId - Session ID+ * @returns {Array} - Tool calls+ */+function getToolCalls(sessionId) {+ if (!sessions.has(sessionId)) return []+ return [...sessions.get(sessionId).toolCalls]+}++/**+ * End a session and return final summary+ * @param {string} sessionId - Session ID+ * @returns {Object} - Final session summary+ */+function endSession(sessionId) {+ const summary = getSessionSummary(sessionId)+ sessions.delete(sessionId)+ return summary+}++/**+ * Clean up expired sessions+ * @returns {number} - Number of sessions cleaned up+ */+function cleanupExpiredSessions() {+ const now = Date.now()+ let cleaned = 0++ for (const [sessionId, session] of sessions.entries()) {+ if (now - session.lastActivityAt > SESSION_TTL_MS) {+ sessions.delete(sessionId)+ cleaned+++ }+ }++ if (cleaned > 0) {+ console.log(`🧹 Cleaned up ${cleaned} expired session deltas`)+ }++ return cleaned+}++/**+ * Start periodic cleanup+ */+function startCleanupTimer() {+ if (cleanupTimer) return++ cleanupTimer = setInterval(() => {+ cleanupExpiredSessions()+ }, CLEANUP_INTERVAL_MS)++ // Don't prevent process exit+ cleanupTimer.unref()+}++/**+ * Stop periodic cleanup+ */+function stopCleanupTimer() {+ if (cleanupTimer) {+ clearInterval(cleanupTimer)+ cleanupTimer = null+ }+}++/**+ * Get all active sessions+ * @returns {Array<string>} - Active session IDs+ */+function getActiveSessions() {+ return Array.from(sessions.keys())+}++/**+ * Get total stats across all sessions+ * @returns {Object} - Aggregate statistics+ */+function getGlobalStats() {+ let totalPendingBytes = 0+ let totalPendingMessages = 0+ let totalProcessedBytes = 0+ let totalProcessedMessages = 0+ let totalNewMemories = 0+ let totalToolCalls = 0++ for (const session of sessions.values()) {+ totalPendingBytes += session.pendingBytes+ totalPendingMessages += session.pendingMessages+ totalProcessedBytes += session.processedBytes+ totalProcessedMessages += session.processedMessages+ totalNewMemories += session.newMemories.length+ totalToolCalls += session.toolCalls.length+ }++ return {+ activeSessions: sessions.size,+ pending: {+ bytes: totalPendingBytes,+ messages: totalPendingMessages+ },+ processed: {+ bytes: totalProcessedBytes,+ messages: totalProcessedMessages+ },+ totalNewMemories,+ totalToolCalls+ }+}++/**+ * Reset a session's pending counters+ * @param {string} sessionId - Session ID+ */+function resetPending(sessionId) {+ if (!sessions.has(sessionId)) return++ const session = sessions.get(sessionId)+ session.pendingBytes = 0+ session.pendingMessages = 0+}++// Start cleanup on module load+startCleanupTimer()++export {+ getSession,+ addPendingBytes,+ markBytesProcessed,+ recordNewMemory,+ recordModifiedMemory,+ recordToolCall,+ recordEvent,+ getSessionSummary,+ getPendingDelta,+ getNewMemories,+ getToolCalls,+ endSession,+ cleanupExpiredSessions,+ startCleanupTimer,+ stopCleanupTimer,+ getActiveSessions,+ getGlobalStats,+ resetPending+}diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 5bbe4ea0cb..d1d4ee457c 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -26,6 +26,9 @@ import { extractAndStoreMemories } from './memoryExtractor.js';import { getDigitalTwinForPrompt } from './digital-twin.js';import { suggestModelTier } from './taskLearning.js';import { readJSONFile } from '../lib/fileUtils.js';+import { createToolExecution, startExecution, updateExecution, completeExecution, errorExecution, getExecution, getStats as getToolStats } from './toolStateMachine.js';+import { resolveThinkingLevel, getModelForLevel, isLocalPreferred } from './thinkingLevels.js';+import { determineLane, acquire, release, hasCapacity, waitForLane } from './executionLanes.js';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -57,17 +60,18 @@ function extractTaskTypeKey(task) {* Select optimal model for a task based on complexity analysis and historical performance* User can override by specifying Model: and/or Provider: in task metadata*- * Enhanced with learning-based model suggestions:- * - Uses historical success rates to suggest heavier models for struggling task types- * - Automatically upgrades model tier when task type has <60% success rate+ * Enhanced with:+ * - Thinking levels hierarchy (task → agent → provider)+ * - Learning-based model suggestions from historical success rates+ * - Automatic upgrades when task type has <60% success rate*/-async function selectModelForTask(task, provider) {+async function selectModelForTask(task, provider, agent = {}) {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+ // Check for user-specified model preference (highest priority)const userModel = task.metadata?.model;const userProvider = task.metadata?.provider;@@ -81,6 +85,24 @@ async function selectModelForTask(task, provider) {};}+ // Check thinking level hierarchy (task → agent → provider)+ // This resolves the appropriate thinking level based on configuration hierarchy+ const thinkingResult = resolveThinkingLevel(task, agent, provider);+ if (thinkingResult.resolvedFrom !== 'default') {+ const modelFromLevel = getModelForLevel(thinkingResult.level, provider);+ if (modelFromLevel) {+ const isLocal = isLocalPreferred(thinkingResult.level);+ console.log(`🧠 Thinking level: ${thinkingResult.level} → ${modelFromLevel} (from ${thinkingResult.resolvedFrom}${isLocal ? ', local-preferred' : ''})`);+ return {+ model: modelFromLevel,+ tier: thinkingResult.level,+ reason: `thinking-level-${thinkingResult.resolvedFrom}`,+ thinkingLevel: thinkingResult.level,+ localPreferred: isLocal+ };+ }+ }+// Image/visual analysis → would route to gemini if availableif (/image|screenshot|visual|photo|picture/.test(desc)) {return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'visual-analysis' };@@ -653,11 +675,45 @@ async function syncRunnerAgents() {export async function spawnAgentForTask(task) {const agentId = `agent-${uuidv4().slice(0, 8)}`;+ // Determine execution lane and acquire slot+ const laneName = determineLane(task);+ if (!hasCapacity(laneName)) {+ // Wait for lane availability (max 30 seconds)+ const laneResult = await waitForLane(laneName, agentId, { timeoutMs: 30000, metadata: { taskId: task.id } });+ if (!laneResult.success) {+ emitLog('warning', `Lane ${laneName} unavailable for task ${task.id}, deferring`, { taskId: task.id, lane: laneName });+ cosEvents.emit('agent:deferred', { taskId: task.id, reason: 'lane-capacity', lane: laneName });+ return null;+ }+ } else {+ const laneResult = acquire(laneName, agentId, { taskId: task.id });+ if (!laneResult.success) {+ emitLog('warning', `Failed to acquire lane ${laneName}: ${laneResult.error}`, { taskId: task.id });+ return null;+ }+ }++ // Create tool execution for state tracking+ const toolExecution = createToolExecution('agent-spawn', agentId, {+ taskId: task.id,+ lane: laneName,+ priority: task.priority+ });+ startExecution(toolExecution.id);++ // Helper to cleanup on early exit+ const cleanupOnError = (error) => {+ release(agentId);+ errorExecution(toolExecution.id, { message: error });+ completeExecution(toolExecution.id, { success: false });+ };+// Get configurationconst config = await getConfig();let provider = await getActiveProvider();if (!provider) {+ cleanupOnError('No active AI provider configured');cosEvents.emit('agent:error', { taskId: task.id, error: 'No active AI provider configured' });return null;}@@ -687,9 +743,11 @@ export async function spawnAgentForTask(task) {provider = fallbackResult.provider;} else {// No fallback available - emit error and defer task+ const errorMsg = `Provider ${provider.id} unavailable (${status.message}) and no fallback available`;+ cleanupOnError(errorMsg);cosEvents.emit('agent:error', {taskId: task.id,- error: `Provider ${provider.id} unavailable (${status.message}) and no fallback available`,+ error: errorMsg,providerId: provider.id,providerStatus: status});@@ -785,15 +843,15 @@ export async function spawnAgentForTask(task) {// Build CLI-specific spawn configurationconst cliConfig = buildCliSpawnConfig(provider, selectedModel);- emitLog('success', `Spawning agent for task ${task.id}`, { agentId, model: selectedModel, mode: useRunner ? 'runner' : 'direct', cli: cliConfig.command });+ emitLog('success', `Spawning agent for task ${task.id}`, { agentId, model: selectedModel, mode: useRunner ? 'runner' : 'direct', cli: cliConfig.command, lane: laneName });// Use CoS Runner if available, otherwise spawn directlyif (useRunner) {- return spawnViaRunner(agentId, task, prompt, workspacePath, selectedModel, provider, runId, cliConfig);+ return spawnViaRunner(agentId, task, prompt, workspacePath, selectedModel, provider, runId, cliConfig, toolExecution.id, laneName);}// Direct spawn mode (fallback)- return spawnDirectly(agentId, task, prompt, workspacePath, selectedModel, provider, runId, cliConfig, agentDir);+ return spawnDirectly(agentId, task, prompt, workspacePath, selectedModel, provider, runId, cliConfig, agentDir, toolExecution.id, laneName);}/**@@ -830,7 +888,7 @@ async function waitForRunnerStability() {/*** Spawn agent via CoS Runner (isolated PM2 process)*/-async function spawnViaRunner(agentId, task, prompt, workspacePath, model, provider, runId, cliConfig) {+async function spawnViaRunner(agentId, task, prompt, workspacePath, model, provider, runId, cliConfig, executionId, laneName) {// Wait for runner to be stable to prevent orphaned agents during rolling restartsawait waitForRunnerStability();@@ -843,7 +901,9 @@ async function spawnViaRunner(agentId, task, prompt, workspacePath, model, proviproviderId: provider.id,hasStartedWorking: false,startedAt: Date.now(),- initializationTimeout: null+ initializationTimeout: null,+ executionId,+ laneName};runnerAgents.set(agentId, agentInfo);@@ -885,7 +945,22 @@ async function handleAgentCompletion(agentId, exitCode, success, duration) {return;}- const { task, runId, model } = agent;+ const { task, runId, model, executionId, laneName } = agent;++ // Release execution lane+ if (laneName) {+ release(agentId);+ }++ // Complete tool execution tracking+ if (executionId) {+ if (success) {+ completeExecution(executionId, { success: true, duration });+ } else {+ errorExecution(executionId, { message: `Agent exited with code ${exitCode}`, code: exitCode });+ completeExecution(executionId, { success: false });+ }+ }// Read output from agent directoryconst agentDir = join(AGENTS_DIR, agentId);@@ -954,7 +1029,7 @@ async function handleAgentCompletion(agentId, exitCode, success, duration) {/*** Spawn agent directly (fallback when runner not available)*/-async function spawnDirectly(agentId, task, prompt, workspacePath, model, provider, runId, cliConfig, agentDir) {+async function spawnDirectly(agentId, task, prompt, workspacePath, model, provider, runId, cliConfig, agentDir, executionId, laneName) {const fullCommand = `${cliConfig.command} ${cliConfig.args.join(' ')} <<< "${(task.description || '').substring(0, 100)}..."`;// Ensure workspacePath is valid@@ -988,7 +1063,9 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, providstartedAt: Date.now(),runId,pid: claudeProcess.pid,- providerId: provider.id+ providerId: provider.id,+ executionId,+ laneName});// Store PID in persisted state for zombie detection@@ -1031,6 +1108,18 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, providclaudeProcess.on('error', async (err) => {clearTimeout(initializationTimeout);console.error(`❌ Agent ${agentId} spawn error: ${err.message}`);++ // Release execution lane+ if (laneName) {+ release(agentId);+ }++ // Complete tool execution tracking with error+ if (executionId) {+ errorExecution(executionId, { message: err.message, category: 'spawn-error' });+ completeExecution(executionId, { success: false });+ }+cosEvents.emit('agent:error', { agentId, error: err.message });await completeAgent(agentId, { success: false, error: err.message });await completeAgentRun(runId, outputBuffer, 1, 0, { message: err.message, category: 'spawn-error' });@@ -1044,6 +1133,21 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, providconst agentData = activeAgents.get(agentId);const duration = Date.now() - (agentData?.startedAt || Date.now());+ // Release execution lane+ if (agentData?.laneName) {+ release(agentId);+ }++ // Complete tool execution tracking+ if (agentData?.executionId) {+ if (success) {+ completeExecution(agentData.executionId, { success: true, duration });+ } else {+ errorExecution(agentData.executionId, { message: `Agent exited with code ${code}`, code });+ completeExecution(agentData.executionId, { success: false });+ }+ }+await writeFile(outputFile, outputBuffer).catch(() => {});const errorAnalysis = success ? null : analyzeAgentFailure(outputBuffer, task, model);diff --git a/server/services/thinkingLevels.js b/server/services/thinkingLevels.jsnew file mode 100644index 0000000000..d7f673dd9b--- /dev/null+++ b/server/services/thinkingLevels.js@@ -0,0 +1,344 @@+/**+ * Thinking Levels Service+ *+ * Dynamic model selection based on thinking levels.+ * Hierarchy: task → hooks → agent → provider defaults+ */++import { cosEvents } from './cos.js'++// Thinking level definitions+const THINKING_LEVELS = {+ off: {+ name: 'off',+ model: null,+ maxTokens: 0,+ description: 'No extended thinking, use defaults'+ },+ minimal: {+ name: 'minimal',+ model: 'local-small',+ maxTokens: 256,+ localPreferred: true,+ description: 'Quick local analysis only'+ },+ low: {+ name: 'low',+ model: 'local-medium',+ maxTokens: 1024,+ localPreferred: true,+ description: 'Basic reasoning with local model'+ },+ medium: {+ name: 'medium',+ model: 'provider-default',+ maxTokens: 4096,+ localPreferred: false,+ description: 'Standard cloud model thinking'+ },+ high: {+ name: 'high',+ model: 'provider-heavy',+ maxTokens: 8192,+ localPreferred: false,+ description: 'Advanced reasoning with heavy model'+ },+ xhigh: {+ name: 'xhigh',+ model: 'opus',+ maxTokens: 16384,+ localPreferred: false,+ description: 'Maximum reasoning with Opus'+ }+}++// Default thresholds for automatic level selection+const AUTO_THRESHOLDS = {+ contextLength: {+ minimal: 500,+ low: 1000,+ medium: 3000,+ high: 6000,+ xhigh: 10000+ },+ complexity: {+ minimal: 0.2,+ low: 0.4,+ medium: 0.6,+ high: 0.8,+ xhigh: 0.95+ }+}++// Task type to default level mapping+const TASK_TYPE_LEVELS = {+ // Simple tasks+ 'format': 'minimal',+ 'rename': 'minimal',+ 'typo': 'minimal',+ 'comment': 'low',++ // Medium tasks+ 'fix-bug': 'medium',+ 'implement': 'medium',+ 'update': 'medium',++ // Complex tasks+ 'refactor': 'high',+ 'security': 'high',+ 'optimize': 'high',+ 'architect': 'xhigh',+ 'audit': 'xhigh',+ 'migration': 'xhigh'+}++// Usage tracking+const levelUsage = {+ off: 0,+ minimal: 0,+ low: 0,+ medium: 0,+ high: 0,+ xhigh: 0+}++/**+ * Resolve thinking level for a task+ * Checks hierarchy: task metadata → hooks → agent config → provider defaults+ *+ * @param {Object} task - Task object+ * @param {Object} agent - Agent configuration+ * @param {Object} provider - Provider configuration+ * @returns {Object} - Resolved thinking level configuration+ */+function resolveThinkingLevel(task, agent = {}, provider = {}) {+ let level = 'medium' // Default++ // 1. Check task metadata for explicit level+ if (task?.metadata?.thinkingLevel) {+ level = task.metadata.thinkingLevel+ }+ // 2. Check task priority+ else if (task?.priority) {+ const priority = task.priority.toUpperCase()+ if (priority === 'URGENT' || priority === 'CRITICAL') {+ level = 'high'+ } else if (priority === 'LOW' || priority === 'IDLE') {+ level = 'low'+ }+ }+ // 3. Check task type+ else if (task?.metadata?.taskType) {+ level = TASK_TYPE_LEVELS[task.metadata.taskType] || level+ }+ // 4. Check agent default+ else if (agent?.defaultThinkingLevel) {+ level = agent.defaultThinkingLevel+ }+ // 5. Check provider default+ else if (provider?.defaultThinkingLevel) {+ level = provider.defaultThinkingLevel+ }++ // Validate level+ if (!THINKING_LEVELS[level]) {+ level = 'medium'+ }++ // Track usage+ levelUsage[level]++++ const config = THINKING_LEVELS[level]++ cosEvents.emit('thinking:levelResolved', {+ taskId: task?.id,+ level,+ model: config.model,+ source: determineSource(task, agent, provider)+ })++ return {+ level,+ ...config,+ resolvedFrom: determineSource(task, agent, provider)+ }+}++/**+ * Determine where the level was resolved from+ */+function determineSource(task, agent, provider) {+ if (task?.metadata?.thinkingLevel) return 'task'+ if (task?.priority) return 'priority'+ if (task?.metadata?.taskType) return 'taskType'+ if (agent?.defaultThinkingLevel) return 'agent'+ if (provider?.defaultThinkingLevel) return 'provider'+ return 'default'+}++/**+ * Suggest thinking level based on task analysis+ * @param {Object} analysis - Task analysis from localThinking+ * @returns {string} - Suggested level+ */+function suggestLevel(analysis) {+ const complexity = analysis.complexity || 0.5++ // Find appropriate level based on complexity+ for (const [level, threshold] of Object.entries(AUTO_THRESHOLDS.complexity).reverse()) {+ if (complexity >= threshold) {+ return level+ }+ }++ return 'minimal'+}++/**+ * Suggest thinking level based on context length+ * @param {number} contextLength - Context length in characters+ * @returns {string} - Suggested level+ */+function suggestLevelFromContext(contextLength) {+ for (const [level, threshold] of Object.entries(AUTO_THRESHOLDS.contextLength).reverse()) {+ if (contextLength >= threshold) {+ return level+ }+ }++ return 'minimal'+}++/**+ * Get model for a thinking level+ * @param {string} level - Thinking level name+ * @param {Object} provider - Provider config for model mapping+ * @returns {string|null} - Model identifier+ */+function getModelForLevel(level, provider = {}) {+ const config = THINKING_LEVELS[level]+ if (!config) return null++ const modelKey = config.model++ switch (modelKey) {+ case null:+ return provider.defaultModel || null+ case 'local-small':+ return 'lmstudio' // Will use LM Studio+ case 'local-medium':+ return 'lmstudio'+ case 'provider-default':+ return provider.defaultModel || 'claude-3-5-sonnet-20241022'+ case 'provider-heavy':+ return provider.heavyModel || 'claude-3-5-sonnet-20241022'+ case 'opus':+ return 'claude-opus-4-20250514'+ default:+ return modelKey+ }+}++/**+ * Check if level prefers local execution+ * @param {string} level - Thinking level+ * @returns {boolean} - True if local preferred+ */+function isLocalPreferred(level) {+ const config = THINKING_LEVELS[level]+ return config?.localPreferred || false+}++/**+ * Upgrade thinking level by one step+ * @param {string} currentLevel - Current level+ * @returns {string} - Upgraded level+ */+function upgradeLevel(currentLevel) {+ const levels = Object.keys(THINKING_LEVELS)+ const currentIndex = levels.indexOf(currentLevel)++ if (currentIndex === -1) return 'medium'+ if (currentIndex >= levels.length - 1) return currentLevel++ return levels[currentIndex + 1]+}++/**+ * Downgrade thinking level by one step+ * @param {string} currentLevel - Current level+ * @returns {string} - Downgraded level+ */+function downgradeLevel(currentLevel) {+ const levels = Object.keys(THINKING_LEVELS)+ const currentIndex = levels.indexOf(currentLevel)++ if (currentIndex === -1) return 'medium'+ if (currentIndex <= 0) return currentLevel++ return levels[currentIndex - 1]+}++/**+ * Get thinking level statistics+ * @returns {Object} - Usage statistics+ */+function getStats() {+ const total = Object.values(levelUsage).reduce((a, b) => a + b, 0)++ return {+ usage: { ...levelUsage },+ total,+ distribution: Object.entries(levelUsage).reduce((acc, [level, count]) => {+ acc[level] = total > 0 ? ((count / total) * 100).toFixed(1) + '%' : '0%'+ return acc+ }, {}),+ levels: Object.keys(THINKING_LEVELS),+ thresholds: AUTO_THRESHOLDS+ }+}++/**+ * Reset usage statistics+ */+function resetStats() {+ for (const level of Object.keys(levelUsage)) {+ levelUsage[level] = 0+ }+}++/**+ * Update auto thresholds+ * @param {string} thresholdType - 'contextLength' or 'complexity'+ * @param {Object} newThresholds - New threshold values+ */+function updateThresholds(thresholdType, newThresholds) {+ if (AUTO_THRESHOLDS[thresholdType]) {+ Object.assign(AUTO_THRESHOLDS[thresholdType], newThresholds)+ }+}++/**+ * Get all thinking levels+ * @returns {Object} - All level configurations+ */+function getLevels() {+ return { ...THINKING_LEVELS }+}++export {+ THINKING_LEVELS,+ AUTO_THRESHOLDS,+ TASK_TYPE_LEVELS,+ resolveThinkingLevel,+ suggestLevel,+ suggestLevelFromContext,+ getModelForLevel,+ isLocalPreferred,+ upgradeLevel,+ downgradeLevel,+ getStats,+ resetStats,+ updateThresholds,+ getLevels+}diff --git a/server/services/thinkingLevels.test.js b/server/services/thinkingLevels.test.jsnew file mode 100644index 0000000000..2c3bf8d1c2--- /dev/null+++ b/server/services/thinkingLevels.test.js@@ -0,0 +1,326 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import {+ THINKING_LEVELS,+ AUTO_THRESHOLDS,+ TASK_TYPE_LEVELS,+ resolveThinkingLevel,+ suggestLevel,+ suggestLevelFromContext,+ getModelForLevel,+ isLocalPreferred,+ upgradeLevel,+ downgradeLevel,+ getStats,+ resetStats,+ getLevels+} from './thinkingLevels.js';++// Mock the cosEvents+vi.mock('./cos.js', () => ({+ cosEvents: {+ emit: vi.fn()+ }+}));++describe('Thinking Levels Service', () => {+ beforeEach(() => {+ resetStats();+ });++ describe('THINKING_LEVELS', () => {+ it('should have all required levels', () => {+ expect(THINKING_LEVELS.off).toBeDefined();+ expect(THINKING_LEVELS.minimal).toBeDefined();+ expect(THINKING_LEVELS.low).toBeDefined();+ expect(THINKING_LEVELS.medium).toBeDefined();+ expect(THINKING_LEVELS.high).toBeDefined();+ expect(THINKING_LEVELS.xhigh).toBeDefined();+ });++ it('should have increasing maxTokens as level increases', () => {+ expect(THINKING_LEVELS.minimal.maxTokens).toBeLessThan(THINKING_LEVELS.low.maxTokens);+ expect(THINKING_LEVELS.low.maxTokens).toBeLessThan(THINKING_LEVELS.medium.maxTokens);+ expect(THINKING_LEVELS.medium.maxTokens).toBeLessThan(THINKING_LEVELS.high.maxTokens);+ expect(THINKING_LEVELS.high.maxTokens).toBeLessThan(THINKING_LEVELS.xhigh.maxTokens);+ });++ it('should mark minimal and low as localPreferred', () => {+ expect(THINKING_LEVELS.minimal.localPreferred).toBe(true);+ expect(THINKING_LEVELS.low.localPreferred).toBe(true);+ expect(THINKING_LEVELS.medium.localPreferred).toBe(false);+ });+ });++ describe('AUTO_THRESHOLDS', () => {+ it('should have contextLength thresholds', () => {+ expect(AUTO_THRESHOLDS.contextLength).toBeDefined();+ expect(AUTO_THRESHOLDS.contextLength.minimal).toBeDefined();+ expect(AUTO_THRESHOLDS.contextLength.xhigh).toBeDefined();+ });++ it('should have complexity thresholds', () => {+ expect(AUTO_THRESHOLDS.complexity).toBeDefined();+ expect(AUTO_THRESHOLDS.complexity.minimal).toBeLessThan(AUTO_THRESHOLDS.complexity.xhigh);+ });+ });++ describe('TASK_TYPE_LEVELS', () => {+ it('should map simple tasks to low levels', () => {+ expect(TASK_TYPE_LEVELS.format).toBe('minimal');+ expect(TASK_TYPE_LEVELS.typo).toBe('minimal');+ });++ it('should map complex tasks to high levels', () => {+ expect(TASK_TYPE_LEVELS.architect).toBe('xhigh');+ expect(TASK_TYPE_LEVELS.audit).toBe('xhigh');+ });+ });++ describe('resolveThinkingLevel', () => {+ it('should use task metadata thinkingLevel if present', () => {+ const task = { id: 'task-1', metadata: { thinkingLevel: 'high' } };+ const result = resolveThinkingLevel(task);++ expect(result.level).toBe('high');+ expect(result.resolvedFrom).toBe('task');+ });++ it('should use priority for CRITICAL/URGENT tasks', () => {+ const task = { id: 'task-1', priority: 'CRITICAL' };+ const result = resolveThinkingLevel(task);++ expect(result.level).toBe('high');+ expect(result.resolvedFrom).toBe('priority');+ });++ it('should use priority for LOW tasks', () => {+ const task = { id: 'task-1', priority: 'LOW' };+ const result = resolveThinkingLevel(task);++ expect(result.level).toBe('low');+ });++ it('should use taskType mapping', () => {+ const task = { id: 'task-1', metadata: { taskType: 'architect' } };+ const result = resolveThinkingLevel(task);++ expect(result.level).toBe('xhigh');+ });++ it('should use agent default if no task-level config', () => {+ const task = { id: 'task-1' };+ const agent = { defaultThinkingLevel: 'low' };+ const result = resolveThinkingLevel(task, agent);++ expect(result.level).toBe('low');+ expect(result.resolvedFrom).toBe('agent');+ });++ it('should use provider default as fallback', () => {+ const task = { id: 'task-1' };+ const provider = { defaultThinkingLevel: 'minimal' };+ const result = resolveThinkingLevel(task, {}, provider);++ expect(result.level).toBe('minimal');+ expect(result.resolvedFrom).toBe('provider');+ });++ it('should default to medium if nothing specified', () => {+ const task = { id: 'task-1' };+ const result = resolveThinkingLevel(task);++ expect(result.level).toBe('medium');+ expect(result.resolvedFrom).toBe('default');+ });++ it('should fallback to medium for invalid levels', () => {+ const task = { id: 'task-1', metadata: { thinkingLevel: 'invalid-level' } };+ const result = resolveThinkingLevel(task);++ expect(result.level).toBe('medium');+ });++ it('should include level configuration in result', () => {+ const task = { id: 'task-1', metadata: { thinkingLevel: 'high' } };+ const result = resolveThinkingLevel(task);++ expect(result.model).toBe('provider-heavy');+ expect(result.maxTokens).toBe(8192);+ });+ });++ describe('suggestLevel', () => {+ it('should suggest higher levels for higher complexity', () => {+ const lowComplexity = suggestLevel({ complexity: 0.2 });+ const highComplexity = suggestLevel({ complexity: 0.9 });++ expect(['minimal', 'low'].includes(lowComplexity)).toBe(true);+ expect(['high', 'xhigh'].includes(highComplexity)).toBe(true);+ });++ it('should return minimal for very low complexity', () => {+ const result = suggestLevel({ complexity: 0.1 });+ expect(result).toBe('minimal');+ });++ it('should handle missing complexity', () => {+ const result = suggestLevel({});+ expect(result).toBeDefined();+ });+ });++ describe('suggestLevelFromContext', () => {+ it('should suggest minimal for short context', () => {+ const result = suggestLevelFromContext(100);+ expect(result).toBe('minimal');+ });++ it('should suggest higher levels for longer context', () => {+ const short = suggestLevelFromContext(500);+ const long = suggestLevelFromContext(10000);++ expect(['minimal', 'low'].includes(short)).toBe(true);+ expect(long).toBe('xhigh');+ });+ });++ describe('getModelForLevel', () => {+ it('should return lmstudio for local levels', () => {+ expect(getModelForLevel('minimal')).toBe('lmstudio');+ expect(getModelForLevel('low')).toBe('lmstudio');+ });++ it('should return provider default for medium', () => {+ const provider = { defaultModel: 'custom-model' };+ expect(getModelForLevel('medium', provider)).toBe('custom-model');+ });++ it('should return provider heavy for high', () => {+ const provider = { heavyModel: 'heavy-model' };+ expect(getModelForLevel('high', provider)).toBe('heavy-model');+ });++ it('should return opus for xhigh', () => {+ expect(getModelForLevel('xhigh')).toBe('claude-opus-4-20250514');+ });++ it('should return null for invalid level', () => {+ expect(getModelForLevel('invalid')).toBeNull();+ });++ it('should return provider default when level is off', () => {+ const provider = { defaultModel: 'default' };+ expect(getModelForLevel('off', provider)).toBe('default');+ });+ });++ describe('isLocalPreferred', () => {+ it('should return true for minimal and low', () => {+ expect(isLocalPreferred('minimal')).toBe(true);+ expect(isLocalPreferred('low')).toBe(true);+ });++ it('should return false for medium and above', () => {+ expect(isLocalPreferred('medium')).toBe(false);+ expect(isLocalPreferred('high')).toBe(false);+ expect(isLocalPreferred('xhigh')).toBe(false);+ });++ it('should return false for invalid level', () => {+ expect(isLocalPreferred('invalid')).toBe(false);+ });+ });++ describe('upgradeLevel', () => {+ it('should upgrade to next level', () => {+ expect(upgradeLevel('minimal')).toBe('low');+ expect(upgradeLevel('low')).toBe('medium');+ expect(upgradeLevel('medium')).toBe('high');+ expect(upgradeLevel('high')).toBe('xhigh');+ });++ it('should not upgrade beyond xhigh', () => {+ expect(upgradeLevel('xhigh')).toBe('xhigh');+ });++ it('should return medium for invalid level', () => {+ expect(upgradeLevel('invalid')).toBe('medium');+ });+ });++ describe('downgradeLevel', () => {+ it('should downgrade to previous level', () => {+ expect(downgradeLevel('xhigh')).toBe('high');+ expect(downgradeLevel('high')).toBe('medium');+ expect(downgradeLevel('medium')).toBe('low');+ expect(downgradeLevel('low')).toBe('minimal');+ });++ it('should not downgrade below off', () => {+ expect(downgradeLevel('off')).toBe('off');+ });++ it('should return medium for invalid level', () => {+ expect(downgradeLevel('invalid')).toBe('medium');+ });+ });++ describe('getStats', () => {+ it('should return usage statistics', () => {+ resolveThinkingLevel({ id: 't1', metadata: { thinkingLevel: 'high' } });+ resolveThinkingLevel({ id: 't2', metadata: { thinkingLevel: 'high' } });+ resolveThinkingLevel({ id: 't3', metadata: { thinkingLevel: 'low' } });++ const stats = getStats();++ expect(stats.usage.high).toBe(2);+ expect(stats.usage.low).toBe(1);+ expect(stats.total).toBe(3);+ });++ it('should calculate distribution percentages', () => {+ resolveThinkingLevel({ id: 't1', metadata: { thinkingLevel: 'medium' } });+ resolveThinkingLevel({ id: 't2', metadata: { thinkingLevel: 'medium' } });++ const stats = getStats();++ expect(stats.distribution.medium).toBe('100.0%');+ });++ it('should return all levels', () => {+ const stats = getStats();+ expect(stats.levels).toContain('off');+ expect(stats.levels).toContain('xhigh');+ });+ });++ describe('resetStats', () => {+ it('should reset all usage counters to 0', () => {+ resolveThinkingLevel({ id: 't1', metadata: { thinkingLevel: 'high' } });+ resetStats();++ const stats = getStats();+ expect(stats.total).toBe(0);+ expect(stats.usage.high).toBe(0);+ });+ });++ describe('getLevels', () => {+ it('should return all level configurations', () => {+ const levels = getLevels();++ expect(levels.off).toBeDefined();+ expect(levels.xhigh).toBeDefined();+ expect(Object.keys(levels).length).toBe(6);+ });++ it('should return all level configurations', () => {+ const levels = getLevels();++ // Verify it returns a new object (shallow copy)+ const levels2 = getLevels();+ expect(levels).not.toBe(levels2); // Different object references+ expect(levels.off).toEqual(levels2.off); // Same content+ });+ });+});diff --git a/server/services/toolStateMachine.js b/server/services/toolStateMachine.jsnew file mode 100644index 0000000000..3afee98bfa--- /dev/null+++ b/server/services/toolStateMachine.js@@ -0,0 +1,431 @@+/**+ * Tool State Machine+ *+ * Manages tool execution lifecycle with defined states and transitions.+ * Provides structured error recovery and execution tracking.+ */++import { v4 as uuidv4 } from 'uuid'+import { cosEvents } from './cos.js'++// Tool execution states+const STATES = {+ IDLE: 'idle',+ START: 'start',+ RUNNING: 'running',+ UPDATE: 'update',+ END: 'end',+ ERROR: 'error',+ RECOVERED: 'recovered'+}++// Valid state transitions+const TRANSITIONS = {+ [STATES.IDLE]: [STATES.START],+ [STATES.START]: [STATES.RUNNING, STATES.ERROR],+ [STATES.RUNNING]: [STATES.UPDATE, STATES.END, STATES.ERROR],+ [STATES.UPDATE]: [STATES.RUNNING, STATES.END, STATES.ERROR],+ [STATES.END]: [],+ [STATES.ERROR]: [STATES.RECOVERED, STATES.END],+ [STATES.RECOVERED]: [STATES.RUNNING, STATES.ERROR]+}++// In-memory execution storage+const executions = new Map()++// Execution history (limited to last 1000)+const executionHistory = []+const MAX_HISTORY = 1000++/**+ * Create a new tool execution+ * @param {string} toolId - Tool identifier+ * @param {string} agentId - Agent running the tool+ * @param {Object} metadata - Additional execution metadata+ * @returns {Object} - Execution object+ */+function createToolExecution(toolId, agentId, metadata = {}) {+ const executionId = uuidv4()+ const now = Date.now()++ const execution = {+ id: executionId,+ toolId,+ agentId,+ state: STATES.IDLE,+ stateHistory: [{ state: STATES.IDLE, timestamp: now }],+ startedAt: null,+ completedAt: null,+ duration: null,+ input: metadata.input || null,+ output: null,+ error: null,+ recoveryAttempts: 0,+ metadata,+ createdAt: now+ }++ executions.set(executionId, execution)+ return execution+}++/**+ * Transition to a new state+ * @param {string} executionId - Execution ID+ * @param {string} newState - Target state+ * @param {Object} data - State-specific data+ * @returns {Object} - Updated execution or null if invalid+ */+function transitionState(executionId, newState, data = {}) {+ const execution = executions.get(executionId)+ if (!execution) return null++ const currentState = execution.state+ const validTransitions = TRANSITIONS[currentState] || []++ if (!validTransitions.includes(newState)) {+ console.error(`⚠️ Invalid state transition: ${currentState} → ${newState} for execution ${executionId}`)+ return null+ }++ const now = Date.now()++ // Update state+ execution.state = newState+ execution.stateHistory.push({ state: newState, timestamp: now, data })++ // Handle state-specific logic+ switch (newState) {+ case STATES.START:+ execution.startedAt = now+ break++ case STATES.RUNNING:+ if (data.input) execution.input = data.input+ break++ case STATES.UPDATE:+ if (data.progress) execution.progress = data.progress+ if (data.partialOutput) execution.partialOutput = data.partialOutput+ break++ case STATES.END:+ execution.completedAt = now+ execution.duration = now - (execution.startedAt || execution.createdAt)+ if (data.output !== undefined) execution.output = data.output+ archiveExecution(execution)+ break++ case STATES.ERROR:+ execution.error = {+ message: data.error?.message || data.message || 'Unknown error',+ code: data.error?.code || data.code,+ stack: data.error?.stack,+ timestamp: now+ }+ break++ case STATES.RECOVERED:+ execution.recoveryAttempts+++ execution.error = null+ break+ }++ // Emit state change event+ cosEvents.emit('tool:stateChange', {+ executionId,+ toolId: execution.toolId,+ agentId: execution.agentId,+ fromState: currentState,+ toState: newState,+ timestamp: now+ })++ return execution+}++/**+ * Start a tool execution+ * @param {string} executionId - Execution ID+ * @param {Object} input - Tool input+ * @returns {Object} - Updated execution+ */+function startExecution(executionId, input = null) {+ const started = transitionState(executionId, STATES.START)+ if (!started) return null++ return transitionState(executionId, STATES.RUNNING, { input })+}++/**+ * Update execution progress+ * @param {string} executionId - Execution ID+ * @param {Object} data - Progress data+ * @returns {Object} - Updated execution+ */+function updateExecution(executionId, data) {+ const execution = executions.get(executionId)+ if (!execution) return null++ // Only update if running+ if (execution.state !== STATES.RUNNING && execution.state !== STATES.UPDATE) {+ return execution+ }++ return transitionState(executionId, STATES.UPDATE, data)+}++/**+ * Complete a tool execution+ * @param {string} executionId - Execution ID+ * @param {*} output - Tool output+ * @returns {Object} - Completed execution+ */+function completeExecution(executionId, output = null) {+ const execution = executions.get(executionId)+ if (!execution) return null++ // Can complete from RUNNING, UPDATE, or ERROR states+ if (execution.state === STATES.ERROR) {+ // Completing from error state means we gave up+ return transitionState(executionId, STATES.END, { output, wasError: true })+ }++ if (execution.state === STATES.UPDATE) {+ // Go back to running first, then end+ transitionState(executionId, STATES.RUNNING)+ }++ return transitionState(executionId, STATES.END, { output })+}++/**+ * Mark execution as errored+ * @param {string} executionId - Execution ID+ * @param {Error|Object} error - Error details+ * @returns {Object} - Updated execution+ */+function errorExecution(executionId, error) {+ return transitionState(executionId, STATES.ERROR, { error })+}++/**+ * Attempt recovery from error state+ * @param {string} executionId - Execution ID+ * @param {string} strategy - Recovery strategy name+ * @returns {Object} - Recovered execution or null+ */+function recoverExecution(executionId, strategy) {+ const execution = executions.get(executionId)+ if (!execution || execution.state !== STATES.ERROR) return null++ const MAX_RECOVERY_ATTEMPTS = 3+ if (execution.recoveryAttempts >= MAX_RECOVERY_ATTEMPTS) {+ console.log(`⚠️ Max recovery attempts (${MAX_RECOVERY_ATTEMPTS}) reached for ${executionId}`)+ return null+ }++ const recovered = transitionState(executionId, STATES.RECOVERED, { strategy })+ if (recovered) {+ transitionState(executionId, STATES.RUNNING)+ }++ return recovered+}++/**+ * Archive completed execution to history+ * @param {Object} execution - Completed execution+ */+function archiveExecution(execution) {+ // Add to history+ executionHistory.unshift({+ id: execution.id,+ toolId: execution.toolId,+ agentId: execution.agentId,+ startedAt: execution.startedAt,+ completedAt: execution.completedAt,+ duration: execution.duration,+ success: !execution.error,+ recoveryAttempts: execution.recoveryAttempts+ })++ // Trim history+ while (executionHistory.length > MAX_HISTORY) {+ executionHistory.pop()+ }++ // Remove from active executions after a delay+ setTimeout(() => {+ executions.delete(execution.id)+ }, 60000) // Keep for 1 minute for debugging+}++/**+ * Get execution by ID+ * @param {string} executionId - Execution ID+ * @returns {Object|null} - Execution object+ */+function getExecution(executionId) {+ return executions.get(executionId) || null+}++/**+ * Get all active executions for an agent+ * @param {string} agentId - Agent ID+ * @returns {Array} - Active executions+ */+function getAgentExecutions(agentId) {+ const results = []+ for (const execution of executions.values()) {+ if (execution.agentId === agentId) {+ results.push(execution)+ }+ }+ return results+}++/**+ * Get execution history+ * @param {Object} options - Filter options+ * @returns {Array} - Execution history+ */+function getExecutionHistory(options = {}) {+ let history = [...executionHistory]++ if (options.agentId) {+ history = history.filter(e => e.agentId === options.agentId)+ }++ if (options.toolId) {+ history = history.filter(e => e.toolId === options.toolId)+ }++ if (options.success !== undefined) {+ history = history.filter(e => e.success === options.success)+ }++ const limit = options.limit || 100+ return history.slice(0, limit)+}++/**+ * Get execution statistics+ * @returns {Object} - Statistics+ */+function getStats() {+ const active = Array.from(executions.values())+ const byState = {}++ for (const execution of active) {+ byState[execution.state] = (byState[execution.state] || 0) + 1+ }++ const recentHistory = executionHistory.slice(0, 100)+ const successCount = recentHistory.filter(e => e.success).length+ const avgDuration = recentHistory.length > 0+ ? recentHistory.reduce((sum, e) => sum + (e.duration || 0), 0) / recentHistory.length+ : 0++ return {+ activeExecutions: active.length,+ byState,+ historySize: executionHistory.length,+ recentSuccessRate: recentHistory.length > 0 ? successCount / recentHistory.length : 1,+ avgDurationMs: Math.round(avgDuration)+ }+}++/**+ * Clean up stale executions+ * @param {number} maxAgeMs - Maximum age in milliseconds+ * @returns {number} - Number of executions cleaned+ */+function cleanupStaleExecutions(maxAgeMs = 3600000) {+ const now = Date.now()+ let cleaned = 0++ for (const [id, execution] of executions.entries()) {+ const age = now - execution.createdAt+ if (age > maxAgeMs && execution.state !== STATES.END) {+ // Force complete stale executions+ transitionState(id, STATES.ERROR, { error: { message: 'Execution timeout' } })+ transitionState(id, STATES.END, { wasTimeout: true })+ cleaned+++ }+ }++ if (cleaned > 0) {+ console.log(`🧹 Cleaned ${cleaned} stale tool executions`)+ }++ return cleaned+}++/**+ * Create a wrapped tool executor with state machine+ * @param {string} toolId - Tool identifier+ * @param {Function} toolFn - Actual tool function+ * @returns {Function} - Wrapped tool function+ */+function wrapToolWithStateMachine(toolId, toolFn) {+ return async function wrappedTool(agentId, input, metadata = {}) {+ const execution = createToolExecution(toolId, agentId, { ...metadata, input })++ const started = startExecution(execution.id, input)+ if (!started) {+ return { success: false, error: 'Failed to start execution' }+ }++ let result+ let lastError++ // Retry loop with recovery+ const maxAttempts = 3+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {+ const current = getExecution(execution.id)+ if (!current || current.state === STATES.END) break++ try {+ result = await toolFn(input)+ completeExecution(execution.id, result)+ return { success: true, output: result, executionId: execution.id }+ } catch (error) {+ lastError = error+ errorExecution(execution.id, error)++ if (attempt < maxAttempts) {+ const recovered = recoverExecution(execution.id, 'retry')+ if (!recovered) break+ console.log(`🔄 Tool ${toolId} retry attempt ${attempt + 1}/${maxAttempts}`)+ }+ }+ }++ // Final failure+ completeExecution(execution.id, null)+ return {+ success: false,+ error: lastError?.message || 'Tool execution failed',+ executionId: execution.id+ }+ }+}++export {+ STATES,+ TRANSITIONS,+ createToolExecution,+ transitionState,+ startExecution,+ updateExecution,+ completeExecution,+ errorExecution,+ recoverExecution,+ getExecution,+ getAgentExecutions,+ getExecutionHistory,+ getStats,+ cleanupStaleExecutions,+ wrapToolWithStateMachine+}diff --git a/server/services/toolStateMachine.test.js b/server/services/toolStateMachine.test.jsnew file mode 100644index 0000000000..673a617e4f--- /dev/null+++ b/server/services/toolStateMachine.test.js@@ -0,0 +1,335 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import {+ STATES,+ TRANSITIONS,+ createToolExecution,+ transitionState,+ startExecution,+ updateExecution,+ completeExecution,+ errorExecution,+ recoverExecution,+ getExecution,+ getAgentExecutions,+ getExecutionHistory,+ getStats,+ cleanupStaleExecutions,+ wrapToolWithStateMachine+} from './toolStateMachine.js';++// Mock the cosEvents to prevent actual event emission+vi.mock('./cos.js', () => ({+ cosEvents: {+ emit: vi.fn()+ }+}));++describe('Tool State Machine', () => {+ describe('STATES', () => {+ it('should have all required states', () => {+ expect(STATES.IDLE).toBe('idle');+ expect(STATES.START).toBe('start');+ expect(STATES.RUNNING).toBe('running');+ expect(STATES.UPDATE).toBe('update');+ expect(STATES.END).toBe('end');+ expect(STATES.ERROR).toBe('error');+ expect(STATES.RECOVERED).toBe('recovered');+ });+ });++ describe('TRANSITIONS', () => {+ it('should define valid transitions from IDLE', () => {+ expect(TRANSITIONS[STATES.IDLE]).toContain(STATES.START);+ });++ it('should define valid transitions from START', () => {+ expect(TRANSITIONS[STATES.START]).toContain(STATES.RUNNING);+ expect(TRANSITIONS[STATES.START]).toContain(STATES.ERROR);+ });++ it('should define valid transitions from RUNNING', () => {+ expect(TRANSITIONS[STATES.RUNNING]).toContain(STATES.UPDATE);+ expect(TRANSITIONS[STATES.RUNNING]).toContain(STATES.END);+ expect(TRANSITIONS[STATES.RUNNING]).toContain(STATES.ERROR);+ });++ it('should have no transitions from END (terminal state)', () => {+ expect(TRANSITIONS[STATES.END]).toEqual([]);+ });++ it('should allow recovery from ERROR', () => {+ expect(TRANSITIONS[STATES.ERROR]).toContain(STATES.RECOVERED);+ expect(TRANSITIONS[STATES.ERROR]).toContain(STATES.END);+ });+ });++ describe('createToolExecution', () => {+ it('should create execution with correct initial state', () => {+ const execution = createToolExecution('tool-1', 'agent-1');++ expect(execution.toolId).toBe('tool-1');+ expect(execution.agentId).toBe('agent-1');+ expect(execution.state).toBe(STATES.IDLE);+ expect(execution.id).toBeDefined();+ });++ it('should include metadata when provided', () => {+ const metadata = { input: 'test input', custom: 'value' };+ const execution = createToolExecution('tool-1', 'agent-1', metadata);++ expect(execution.input).toBe('test input');+ expect(execution.metadata.custom).toBe('value');+ });++ it('should initialize state history', () => {+ const execution = createToolExecution('tool-1', 'agent-1');++ expect(execution.stateHistory).toBeDefined();+ expect(execution.stateHistory.length).toBe(1);+ expect(execution.stateHistory[0].state).toBe(STATES.IDLE);+ });+ });++ describe('transitionState', () => {+ it('should transition to valid next state', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ const result = transitionState(execution.id, STATES.START);++ expect(result).not.toBeNull();+ expect(result.state).toBe(STATES.START);+ });++ it('should reject invalid transitions', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ // IDLE cannot go directly to END+ const result = transitionState(execution.id, STATES.END);++ expect(result).toBeNull();+ });++ it('should update state history', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ transitionState(execution.id, STATES.START);++ const updated = getExecution(execution.id);+ expect(updated.stateHistory.length).toBe(2);+ });++ it('should return null for non-existent execution', () => {+ const result = transitionState('nonexistent', STATES.START);+ expect(result).toBeNull();+ });+ });++ describe('startExecution', () => {+ it('should transition through START to RUNNING', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ const result = startExecution(execution.id, { data: 'test' });++ expect(result).not.toBeNull();+ expect(result.state).toBe(STATES.RUNNING);+ expect(result.startedAt).toBeDefined();+ });++ it('should store input when provided', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ const result = startExecution(execution.id, { key: 'value' });++ expect(result.input).toEqual({ key: 'value' });+ });+ });++ describe('updateExecution', () => {+ it('should update progress during execution', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ startExecution(execution.id);+ const result = updateExecution(execution.id, { progress: 0.5 });++ expect(result.state).toBe(STATES.UPDATE);+ expect(result.progress).toBe(0.5);+ });++ it('should not update if not running', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ // Still in IDLE state+ const result = updateExecution(execution.id, { progress: 0.5 });++ expect(result.state).toBe(STATES.IDLE);+ });+ });++ describe('completeExecution', () => {+ it('should transition to END with output', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ startExecution(execution.id);+ const result = completeExecution(execution.id, { result: 'success' });++ expect(result.state).toBe(STATES.END);+ expect(result.output).toEqual({ result: 'success' });+ expect(result.completedAt).toBeDefined();+ expect(result.duration).toBeDefined();+ });++ it('should calculate duration', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ startExecution(execution.id);++ // Small delay to ensure measurable duration+ const result = completeExecution(execution.id, 'done');++ expect(result.duration).toBeGreaterThanOrEqual(0);+ });+ });++ describe('errorExecution', () => {+ it('should transition to ERROR state', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ startExecution(execution.id);+ const result = errorExecution(execution.id, new Error('Test error'));++ expect(result.state).toBe(STATES.ERROR);+ expect(result.error.message).toBe('Test error');+ });++ it('should store error details', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ startExecution(execution.id);+ const error = { message: 'Custom error', code: 'ERR_TEST' };+ const result = errorExecution(execution.id, error);++ expect(result.error.code).toBe('ERR_TEST');+ });+ });++ describe('recoverExecution', () => {+ it('should recover from ERROR state', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ startExecution(execution.id);+ errorExecution(execution.id, new Error('Test'));+ const result = recoverExecution(execution.id, 'retry');++ expect(result).not.toBeNull();+ expect(result.recoveryAttempts).toBe(1);+ });++ it('should track recovery attempts', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ startExecution(execution.id);+ errorExecution(execution.id, new Error('Test'));+ recoverExecution(execution.id, 'retry');++ // Transition to running, then error again+ errorExecution(execution.id, new Error('Test 2'));+ const result = recoverExecution(execution.id, 'retry');++ expect(result.recoveryAttempts).toBe(2);+ });++ it('should fail after max recovery attempts', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ startExecution(execution.id);++ // Exhaust recovery attempts+ for (let i = 0; i < 3; i++) {+ errorExecution(execution.id, new Error('Test'));+ recoverExecution(execution.id, 'retry');+ }++ errorExecution(execution.id, new Error('Final'));+ const result = recoverExecution(execution.id, 'retry');++ expect(result).toBeNull();+ });++ it('should not recover from non-ERROR state', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ startExecution(execution.id);+ // Currently in RUNNING, not ERROR+ const result = recoverExecution(execution.id, 'retry');++ expect(result).toBeNull();+ });+ });++ describe('getExecution', () => {+ it('should return execution by id', () => {+ const execution = createToolExecution('tool-1', 'agent-1');+ const found = getExecution(execution.id);++ expect(found).not.toBeNull();+ expect(found.id).toBe(execution.id);+ });++ it('should return null for non-existent id', () => {+ const result = getExecution('nonexistent-id');+ expect(result).toBeNull();+ });+ });++ describe('getAgentExecutions', () => {+ it('should return all executions for an agent', () => {+ createToolExecution('tool-1', 'agent-A');+ createToolExecution('tool-2', 'agent-A');+ createToolExecution('tool-3', 'agent-B');++ const agentAExecutions = getAgentExecutions('agent-A');+ expect(agentAExecutions.length).toBe(2);+ });++ it('should return empty array for unknown agent', () => {+ const result = getAgentExecutions('unknown-agent');+ expect(result).toEqual([]);+ });+ });++ describe('getStats', () => {+ it('should return execution statistics', () => {+ const stats = getStats();++ expect(stats.activeExecutions).toBeDefined();+ expect(stats.byState).toBeDefined();+ expect(stats.historySize).toBeDefined();+ expect(stats.recentSuccessRate).toBeDefined();+ expect(stats.avgDurationMs).toBeDefined();+ });+ });++ describe('wrapToolWithStateMachine', () => {+ it('should wrap a function with state machine', async () => {+ const mockTool = vi.fn().mockResolvedValue('result');+ const wrapped = wrapToolWithStateMachine('test-tool', mockTool);++ const result = await wrapped('agent-1', 'input');++ expect(result.success).toBe(true);+ expect(result.output).toBe('result');+ expect(result.executionId).toBeDefined();+ expect(mockTool).toHaveBeenCalledWith('input');+ });++ it('should handle tool errors with retry', async () => {+ let callCount = 0;+ const mockTool = vi.fn().mockImplementation(() => {+ callCount++;+ if (callCount < 2) throw new Error('Retry me');+ return Promise.resolve('success after retry');+ });++ const wrapped = wrapToolWithStateMachine('test-tool', mockTool);+ const result = await wrapped('agent-1', 'input');++ expect(result.success).toBe(true);+ expect(callCount).toBe(2);+ });++ it('should return error after max retries', async () => {+ const mockTool = vi.fn().mockRejectedValue(new Error('Always fails'));+ const wrapped = wrapToolWithStateMachine('test-tool', mockTool);++ const result = await wrapped('agent-1', 'input');++ expect(result.success).toBe(false);+ expect(result.error).toBe('Always fails');+ });+ });+});