Skip to content

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

refactor: remove dead code and extract createCachedStore utility

Adam Eivyb2664d5ac032
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 38ca8e7dd5..097d507841 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1779,13 +1779,10 @@ export const getCalendarEvents = (params = {}) => {
const str = new URLSearchParams(Object.entries(params).filter(([, v]) => v != null)).toString();
return request(`/calendar/events${str ? `?${str}` : ''}`);
};
-export const getCalendarEvent = (accountId, eventId) => request(`/calendar/events/${accountId}/${eventId}`);
export const getCalendarTokenStatus = () => request('/calendar/debug/token-status');
export const testCalendarToken = (provider) => request('/calendar/debug/test-token', { method: 'POST', body: JSON.stringify({ provider }) });
export const clearCalendarToken = (provider) => request('/calendar/debug/clear-token', { method: 'POST', body: JSON.stringify({ provider }) });
-export const getSubcalendars = (accountId) => request(`/calendar/accounts/${accountId}/subcalendars`);
export const updateSubcalendars = (accountId, data) => request(`/calendar/accounts/${accountId}/subcalendars`, { method: 'PUT', body: JSON.stringify(data) });
-export const pushSyncCalendar = (accountId, data) => request(`/calendar/sync/${accountId}/push`, { method: 'POST', body: JSON.stringify(data) });
export const mcpSyncGoogleCalendar = (accountId) => request(`/calendar/sync/${accountId}/google`, { method: 'POST' });
export const mcpDiscoverCalendars = (accountId) => request(`/calendar/sync/${accountId}/discover`, { method: 'POST' });
export const getGoogleAuthStatus = () => request('/calendar/google/auth/status');
@@ -1795,7 +1792,6 @@ export const clearGoogleAuth = () => request('/calendar/google/auth/clear', { me
export const apiSyncGoogleCalendar = (accountId) => request(`/calendar/sync/${accountId}/api`, { method: 'POST' });
export const apiDiscoverCalendars = (accountId) => request(`/calendar/sync/${accountId}/discover-api`, { method: 'POST' });
export const startGoogleAutoConfig = () => request('/calendar/google/auto-configure/start', { method: 'POST' });
-export const captureGoogleCredentials = () => request('/calendar/google/auto-configure/capture', { method: 'POST' });
export const runGoogleAutoConfig = (email) => request('/calendar/google/auto-configure/run', { method: 'POST', body: JSON.stringify({ email }) });
export const getDailyReview = (date) => request(`/calendar/review/${date}`);
export const confirmDailyReviewEvent = (date, data) => request(`/calendar/review/${date}/confirm`, { method: 'POST', body: JSON.stringify(data) });
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index 58a8ec9915..e555e08e74 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -4,7 +4,8 @@
* Shared utilities for file operations used across services.
*/
-import { mkdir, readFile } from 'fs/promises';
+import { mkdir, readFile, writeFile } from 'fs/promises';
+import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
@@ -299,6 +300,52 @@ export async function readJSONLFile(filePath, { logErrors = false } = {}) {
* Time constants in milliseconds.
* Single source of truth — import these instead of declaring inline.
*/
+/**
+ * Create a cached JSON file store with TTL-based invalidation.
+ * Eliminates the repeated cache/load/save/invalidate pattern across services.
+ *
+ * @param {string} filePath - Path to the JSON file
+ * @param {*} defaultValue - Default value when file doesn't exist
+ * @param {Object} options
+ * @param {number} [options.ttl=2000] - Cache TTL in milliseconds
+ * @param {string} [options.context=''] - Context label for error logging
+ * @returns {{ load, save, invalidateCache }}
+ */
+export function createCachedStore(filePath, defaultValue, { ttl = 2000, context = '' } = {}) {
+ let cache = null;
+ let cacheTimestamp = 0;
+ const dir = dirname(filePath);
+
+ const load = async () => {
+ const now = Date.now();
+ if (cache && (now - cacheTimestamp) < ttl) return cache;
+ await ensureDir(dir);
+ if (!existsSync(filePath)) {
+ cache = structuredClone(defaultValue);
+ cacheTimestamp = now;
+ return cache;
+ }
+ const content = await readFile(filePath, 'utf-8');
+ cache = safeJSONParse(content, structuredClone(defaultValue), { context });
+ cacheTimestamp = now;
+ return cache;
+ };
+
+ const save = async (data) => {
+ await ensureDir(dir);
+ await writeFile(filePath, JSON.stringify(data, null, 2));
+ cache = data;
+ cacheTimestamp = Date.now();
+ };
+
+ const invalidateCache = () => {
+ cache = null;
+ cacheTimestamp = 0;
+ };
+
+ return { load, save, invalidateCache };
+}
+
export const HOUR = 60 * 60 * 1000;
export const DAY = 24 * HOUR;
diff --git a/server/services/agentGateway.js b/server/services/agentGateway.js
deleted file mode 100644
index 5a730eccf4..0000000000
--- a/server/services/agentGateway.js
+++ /dev/null
@@ -1,333 +0,0 @@
-/**
- * Agent Gateway Service
- *
- * Centralized communication hub for agent operations.
- * Provides request deduplication, caching, and coordination.
- */
-
-import { cosEvents } from './cosEvents.js'
-
-// Request deduplication cache
-const pendingRequests = new Map()
-
-// Response cache with TTL and size cap
-const responseCache = new Map()
-const CACHE_TTL_MS = 10 * 60 * 1000 // 10 minutes
-const MAX_CACHE_SIZE = 1000
-
-// 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 (evict oldest if at capacity)
- if (cacheable && result) {
- if (responseCache.size >= MAX_CACHE_SIZE) {
- // Evict oldest entry (first key in insertion order)
- const oldest = responseCache.keys().next().value
- responseCache.delete(oldest)
- }
- 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/agentPersonalities.js b/server/services/agentPersonalities.js
index 58a0b12b49..c25c0ec754 100644
--- a/server/services/agentPersonalities.js
+++ b/server/services/agentPersonalities.js
@@ -6,60 +6,19 @@
* how they interact on social platforms.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { existsSync } from 'fs';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';
import EventEmitter from 'events';
-import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { PATHS, createCachedStore } from '../lib/fileUtils.js';
-const AGENTS_DIR = PATHS.agentPersonalities;
-const AGENTS_FILE = join(AGENTS_DIR, 'agents.json');
+const AGENTS_FILE = join(PATHS.agentPersonalities, 'agents.json');
+const store = createCachedStore(AGENTS_FILE, { agents: {} }, { context: 'agentPersonalities' });
+const loadAgents = store.load;
+const saveAgents = store.save;
// Event emitter for agent personality changes
export const agentPersonalityEvents = new EventEmitter();
-
-// In-memory cache
-let cache = null;
-let cacheTimestamp = 0;
-const CACHE_TTL_MS = 2000;
-
-async function ensureAgentsDir() {
- await ensureDir(AGENTS_DIR);
-}
-
-async function loadAgents() {
- const now = Date.now();
-
- if (cache && (now - cacheTimestamp) < CACHE_TTL_MS) {
- return cache;
- }
-
- await ensureAgentsDir();
-
- if (!existsSync(AGENTS_FILE)) {
- cache = { agents: {} };
- cacheTimestamp = now;
- return cache;
- }
-
- const content = await readFile(AGENTS_FILE, 'utf-8');
- cache = safeJSONParse(content, { agents: {} }, { context: 'agentPersonalities' });
- cacheTimestamp = now;
- return cache;
-}
-
-async function saveAgents(data) {
- await ensureAgentsDir();
- await writeFile(AGENTS_FILE, JSON.stringify(data, null, 2));
- cache = data;
- cacheTimestamp = Date.now();
-}
-
-export function invalidateCache() {
- cache = null;
- cacheTimestamp = 0;
-}
+export const invalidateCache = store.invalidateCache;
export function notifyChanged(action = 'update', agentId = null) {
agentPersonalityEvents.emit('changed', { action, agentId, timestamp: Date.now() });
diff --git a/server/services/agentRunCache.js b/server/services/agentRunCache.js
deleted file mode 100644
index 62cd58da52..0000000000
--- a/server/services/agentRunCache.js
+++ /dev/null
@@ -1,390 +0,0 @@
-/**
- * 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.js
deleted file mode 100644
index d94b904aba..0000000000
--- a/server/services/agentRunCache.test.js
+++ /dev/null
@@ -1,337 +0,0 @@
-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/automationScheduler.js b/server/services/automationScheduler.js
index fde7a219f5..0c5f8a0752 100644
--- a/server/services/automationScheduler.js
+++ b/server/services/automationScheduler.js
@@ -5,65 +5,25 @@
* Uses the eventScheduler pattern for reliable cron/interval/random scheduling.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { existsSync } from 'fs';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';
import EventEmitter from 'events';
-import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { PATHS, createCachedStore } from '../lib/fileUtils.js';
import * as eventScheduler from './eventScheduler.js';
import * as agentActivity from './agentActivity.js';
-const AGENTS_DIR = PATHS.agentPersonalities;
-const SCHEDULES_FILE = join(AGENTS_DIR, 'schedules.json');
+const SCHEDULES_FILE = join(PATHS.agentPersonalities, 'schedules.json');
+const store = createCachedStore(SCHEDULES_FILE, { schedules: {} }, { context: 'automation schedules' });
+const loadSchedules = store.load;
+const saveSchedules = store.save;
// Event emitter for schedule changes
export const scheduleEvents = new EventEmitter();
-// In-memory cache
-let cache = null;
-let cacheTimestamp = 0;
-const CACHE_TTL_MS = 2000;
-
// Track active scheduled events
const activeSchedules = new Map();
-async function ensureSchedulesDir() {
- await ensureDir(AGENTS_DIR);
-}
-
-async function loadSchedules() {
- const now = Date.now();
-
- if (cache && (now - cacheTimestamp) < CACHE_TTL_MS) {
- return cache;
- }
-
- await ensureSchedulesDir();
-
- if (!existsSync(SCHEDULES_FILE)) {
- cache = { schedules: {} };
- cacheTimestamp = now;
- return cache;
- }
-
- const content = await readFile(SCHEDULES_FILE, 'utf-8');
- cache = safeJSONParse(content, { schedules: {} }, { logError: true, context: 'automation schedules' });
- cacheTimestamp = now;
- return cache;
-}
-
-async function saveSchedules(data) {
- await ensureSchedulesDir();
- await writeFile(SCHEDULES_FILE, JSON.stringify(data, null, 2));
- cache = data;
- cacheTimestamp = Date.now();
-}
-
-export function invalidateCache() {
- cache = null;
- cacheTimestamp = 0;
-}
+export const invalidateCache = store.invalidateCache;
export function notifyChanged(action = 'update', scheduleId = null) {
scheduleEvents.emit('changed', { action, scheduleId, timestamp: Date.now() });
diff --git a/server/services/errorRecovery.js b/server/services/errorRecovery.js
deleted file mode 100644
index cf4f48a4fa..0000000000
--- a/server/services/errorRecovery.js
+++ /dev/null
@@ -1,515 +0,0 @@
-/**
- * Error Recovery Service
- *
- * Analyzes errors and selects appropriate recovery strategies.
- * Provides structured error handling for agent operations.
- */
-
-import { cosEvents } from './cosEvents.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.js
deleted file mode 100644
index 2d726c88e2..0000000000
--- a/server/services/errorRecovery.test.js
+++ /dev/null
@@ -1,389 +0,0 @@
-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/localThinking.js b/server/services/localThinking.js
index 300e03aeed..8b9657997d 100644
--- a/server/services/localThinking.js
+++ b/server/services/localThinking.js
@@ -306,34 +306,11 @@ function resetStats() {
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/platformAccounts.js b/server/services/platformAccounts.js
index b7edc4d42d..209188a065 100644
--- a/server/services/platformAccounts.js
+++ b/server/services/platformAccounts.js
@@ -6,60 +6,19 @@
* credentials and status tracking.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { existsSync } from 'fs';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';
import EventEmitter from 'events';
-import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { PATHS, createCachedStore } from '../lib/fileUtils.js';
-const AGENTS_DIR = PATHS.agentPersonalities;
-const ACCOUNTS_FILE = join(AGENTS_DIR, 'accounts.json');
+const ACCOUNTS_FILE = join(PATHS.agentPersonalities, 'accounts.json');
+const store = createCachedStore(ACCOUNTS_FILE, { accounts: {} }, { context: 'platformAccounts' });
+const loadAccounts = store.load;
+const saveAccounts = store.save;
// Event emitter for account changes
export const platformAccountEvents = new EventEmitter();
-
-// In-memory cache
-let cache = null;
-let cacheTimestamp = 0;
-const CACHE_TTL_MS = 2000;
-
-async function ensureAccountsDir() {
- await ensureDir(AGENTS_DIR);
-}
-
-async function loadAccounts() {
- const now = Date.now();
-
- if (cache && (now - cacheTimestamp) < CACHE_TTL_MS) {
- return cache;
- }
-
- await ensureAccountsDir();
-
- if (!existsSync(ACCOUNTS_FILE)) {
- cache = { accounts: {} };
- cacheTimestamp = now;
- return cache;
- }
-
- const content = await readFile(ACCOUNTS_FILE, 'utf-8');
- cache = safeJSONParse(content, { accounts: {} }, { context: 'platformAccounts' });
- cacheTimestamp = now;
- return cache;
-}
-
-async function saveAccounts(data) {
- await ensureAccountsDir();
- await writeFile(ACCOUNTS_FILE, JSON.stringify(data, null, 2));
- cache = data;
- cacheTimestamp = Date.now();
-}
-
-export function invalidateCache() {
- cache = null;
- cacheTimestamp = 0;
-}
+export const invalidateCache = store.invalidateCache;
export function notifyChanged(action = 'update', accountId = null) {
platformAccountEvents.emit('changed', { action, accountId, timestamp: Date.now() });
diff --git a/server/services/sessionDelta.js b/server/services/sessionDelta.js
deleted file mode 100644
index ba9c96b1a6..0000000000
--- a/server/services/sessionDelta.js
+++ /dev/null
@@ -1,348 +0,0 @@
-/**
- * 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/socialAccounts.js b/server/services/socialAccounts.js
index 5b61d4adb8..8207a9de1c 100644
--- a/server/services/socialAccounts.js
+++ b/server/services/socialAccounts.js
@@ -9,21 +9,16 @@
* - Future account management automation
*/
-import { writeFile } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';
import EventEmitter from 'events';
-import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { PATHS, createCachedStore } from '../lib/fileUtils.js';
const DATA_FILE = join(PATHS.digitalTwin, 'social-accounts.json');
+const store = createCachedStore(DATA_FILE, { accounts: {} }, { context: 'socialAccounts' });
export const socialAccountEvents = new EventEmitter();
-// In-memory cache
-let cache = null;
-let cacheTimestamp = 0;
-const CACHE_TTL_MS = 2000;
-
// Supported platform definitions
export const PLATFORMS = {
github: {
@@ -126,30 +121,9 @@ export const PLATFORMS = {
}
};
-async function loadAccounts() {
- const now = Date.now();
- if (cache && (now - cacheTimestamp) < CACHE_TTL_MS) {
- return cache;
- }
-
- await ensureDir(PATHS.digitalTwin);
-
- cache = await readJSONFile(DATA_FILE, { accounts: {} });
- cacheTimestamp = now;
- return cache;
-}
-
-async function saveAccounts(data) {
- await ensureDir(PATHS.digitalTwin);
- await writeFile(DATA_FILE, JSON.stringify(data, null, 2));
- cache = data;
- cacheTimestamp = Date.now();
-}
-
-export function invalidateCache() {
- cache = null;
- cacheTimestamp = 0;
-}
+const loadAccounts = store.load;
+const saveAccounts = store.save;
+export const invalidateCache = store.invalidateCache;
export function notifyChanged(action = 'update', accountId = null) {
socialAccountEvents.emit('changed', { action, accountId, timestamp: Date.now() });
diff --git a/server/services/taskClassifier.js b/server/services/taskClassifier.js
deleted file mode 100644
index fc0780ab9f..0000000000
--- a/server/services/taskClassifier.js
+++ /dev/null
@@ -1,240 +0,0 @@
-/**
- * Task Classifier Service
- *
- * Analyzes tasks and their outputs to determine if they can be auto-approved
- * or require user confirmation.
- */
-
-// Classification categories with auto-approve rules
-const CLASSIFICATION_RULES = {
- // Auto-approvable categories (small, safe changes)
- autoApprove: {
- 'formatting': {
- patterns: [/format|lint|prettier|eslint|style/i],
- maxLines: 100,
- description: 'Code formatting and linting fixes'
- },
- 'dry-violations': {
- patterns: [/dry|duplicate|extract.*function|refactor.*common/i],
- maxLines: 50,
- description: 'Removing code duplication'
- },
- 'dead-code': {
- patterns: [/dead.*code|unused|remove.*unused/i],
- maxLines: 30,
- description: 'Removing unused code'
- },
- 'typo-fix': {
- patterns: [/typo|spelling|grammar|comment/i],
- maxLines: 20,
- description: 'Fixing typos and comments'
- },
- 'import-cleanup': {
- patterns: [/import|require|module.*cleanup/i],
- maxLines: 30,
- description: 'Cleaning up imports'
- },
- 'documentation': {
- patterns: [/doc|readme|jsdoc|add.*comment/i],
- maxLines: 100,
- description: 'Documentation updates'
- }
- },
-
- // Always require approval (risky changes)
- requireApproval: {
- 'security': {
- pattern: /security|auth|password|token|credential|secret|key|permission/i,
- reason: 'Security-related changes require manual review'
- },
- 'database': {
- pattern: /database|migration|schema|sql|query|prisma/i,
- reason: 'Database changes require manual review'
- },
- 'api-change': {
- pattern: /api.*change|endpoint.*change|route.*change|breaking.*change/i,
- reason: 'API changes may affect consumers'
- },
- 'dependency': {
- pattern: /package\.json|dependency|upgrade.*version|npm.*install/i,
- reason: 'Dependency changes require verification'
- },
- 'architecture': {
- pattern: /architect|restructure|rewrite|major.*refactor/i,
- reason: 'Architectural changes need approval'
- },
- 'config': {
- pattern: /config.*change|environment|\.env|ecosystem\.config/i,
- reason: 'Configuration changes require review'
- },
- 'deployment': {
- pattern: /deploy|production|release|publish/i,
- reason: 'Deployment changes need approval'
- }
- }
-};
-
-/**
- * Classify a task to determine if it can be auto-approved
- *
- * @param {Object} task - The task to classify
- * @param {Object} analysisResult - Optional analysis result with line counts
- * @param {Object} config - Config with autoFixThresholds
- * @returns {Object} Classification result
- */
-export function classifyTask(task, analysisResult = null, config = null) {
- const description = (task.description || '').toLowerCase();
- const totalLines = analysisResult?.linesChanged || 0;
- const maxAllowedLines = config?.autoFixThresholds?.maxLinesChanged || 50;
- const allowedCategories = config?.autoFixThresholds?.allowedCategories || [];
-
- // Check for required approval patterns first (these always need approval)
- for (const [category, rule] of Object.entries(CLASSIFICATION_RULES.requireApproval)) {
- if (rule.pattern.test(description)) {
- return {
- autoApprove: false,
- category,
- reason: rule.reason,
- confidence: 'high'
- };
- }
- }
-
- // Check for auto-approvable patterns
- for (const [category, rule] of Object.entries(CLASSIFICATION_RULES.autoApprove)) {
- for (const pattern of rule.patterns) {
- if (pattern.test(description)) {
- // Check if category is in allowed list
- if (!allowedCategories.includes(category)) {
- return {
- autoApprove: false,
- category,
- reason: `Category '${category}' not in auto-approve list`,
- confidence: 'medium'
- };
- }
-
- // Check line count threshold
- const categoryMaxLines = Math.min(rule.maxLines, maxAllowedLines);
- if (totalLines > categoryMaxLines) {
- return {
- autoApprove: false,
- category,
- reason: `Changes exceed auto-approve limit (${totalLines} > ${categoryMaxLines} lines)`,
- confidence: 'medium'
- };
- }
-
- return {
- autoApprove: true,
- category,
- reason: rule.description,
- confidence: 'high',
- maxLines: categoryMaxLines
- };
- }
- }
- }
-
- // Default: require approval for unknown categories
- return {
- autoApprove: false,
- category: 'unknown',
- reason: 'Task does not match auto-approve patterns',
- confidence: 'low'
- };
-}
-
-/**
- * Classify findings from an idle code review
- *
- * @param {Array} findings - Array of findings from review
- * @param {Object} config - Config with autoFixThresholds
- * @returns {Array} Classified findings
- */
-export function classifyReviewFindings(findings, config = null) {
- return findings.map(finding => {
- const classification = classifyTask(
- { description: finding.description || finding.title },
- { linesChanged: finding.estimatedLines || 0 },
- config
- );
- return {
- ...finding,
- ...classification
- };
- });
-}
-
-/**
- * Get classification rules for UI display
- */
-export function getClassificationRules() {
- return {
- autoApprove: Object.entries(CLASSIFICATION_RULES.autoApprove).map(([key, value]) => ({
- category: key,
- patterns: value.patterns.map(p => p.toString()),
- maxLines: value.maxLines,
- description: value.description
- })),
- requireApproval: Object.entries(CLASSIFICATION_RULES.requireApproval).map(([key, value]) => ({
- category: key,
- pattern: value.pattern.toString(),
- reason: value.reason
- }))
- };
-}
-
-/**
- * Check if a task description suggests it's an idle review task
- */
-export function isIdleReviewTask(task) {
- const description = (task.description || '').toLowerCase();
- return (
- description.includes('[idle review]') ||
- description.includes('autonomous code review') ||
- task.metadata?.reviewType === 'idle' ||
- task.metadata?.autoGenerated === true
- );
-}
-
-/**
- * Estimate complexity of a task based on description
- */
-export function estimateTaskComplexity(task) {
- const description = (task.description || '').toLowerCase();
-
- // High complexity indicators
- const highComplexity = [
- /multiple.*file/i,
- /across.*codebase/i,
- /refactor.*entire/i,
- /restructure/i,
- /migration/i,
- /integration/i
- ];
-
- // Low complexity indicators
- const lowComplexity = [
- /single.*file/i,
- /one.*line/i,
- /simple/i,
- /typo/i,
- /comment/i,
- /rename/i
- ];
-
- for (const pattern of highComplexity) {
- if (pattern.test(description)) {
- return { level: 'high', reason: 'Task involves multiple files or significant changes' };
- }
- }
-
- for (const pattern of lowComplexity) {
- if (pattern.test(description)) {
- return { level: 'low', reason: 'Task is simple and localized' };
- }
- }
-
- return { level: 'medium', reason: 'Standard complexity task' };
-}
diff --git a/server/services/taskClassifier.test.js b/server/services/taskClassifier.test.js
deleted file mode 100644
index 5294c5e33a..0000000000
--- a/server/services/taskClassifier.test.js
+++ /dev/null
@@ -1,557 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- classifyTask,
- classifyReviewFindings,
- getClassificationRules,
- isIdleReviewTask,
- estimateTaskComplexity
-} from './taskClassifier.js';
-
-describe('Task Classifier Service', () => {
- describe('classifyTask', () => {
- const defaultConfig = {
- autoFixThresholds: {
- maxLinesChanged: 50,
- allowedCategories: ['formatting', 'dry-violations', 'dead-code', 'typo-fix', 'import-cleanup', 'documentation']
- }
- };
-
- describe('auto-approve patterns', () => {
- it('should auto-approve formatting tasks within line limit', () => {
- const task = { description: 'Format code with prettier' };
- const analysis = { linesChanged: 30 };
-
- const result = classifyTask(task, analysis, defaultConfig);
-
- expect(result.autoApprove).toBe(true);
- expect(result.category).toBe('formatting');
- expect(result.confidence).toBe('high');
- });
-
- it('should auto-approve lint fixes', () => {
- const task = { description: 'Fix ESLint errors' };
- const analysis = { linesChanged: 20 };
-
- const result = classifyTask(task, analysis, defaultConfig);
-
- expect(result.autoApprove).toBe(true);
- expect(result.category).toBe('formatting');
- });
-
- it('should auto-approve DRY violation fixes', () => {
- const task = { description: 'Remove duplicate code in helpers' };
- const analysis = { linesChanged: 25 };
-
- const result = classifyTask(task, analysis, defaultConfig);
-
- expect(result.autoApprove).toBe(true);
- expect(result.category).toBe('dry-violations');
- });
-
- it('should auto-approve dead code removal', () => {
- const task = { description: 'Remove unused functions' };
- const analysis = { linesChanged: 15 };
-
- const result = classifyTask(task, analysis, defaultConfig);
-
- expect(result.autoApprove).toBe(true);
- expect(result.category).toBe('dead-code');
- });
-
- it('should auto-approve typo fixes', () => {
- const task = { description: 'Fix typo in error message' };
- const analysis = { linesChanged: 5 };
-
- const result = classifyTask(task, analysis, defaultConfig);
-
- expect(result.autoApprove).toBe(true);
- expect(result.category).toBe('typo-fix');
- });
-
- it('should auto-approve import cleanup', () => {
- // "import" keyword triggers import-cleanup pattern
- const task = { description: 'Fix broken import statements' };
- const analysis = { linesChanged: 20 };
-
- const result = classifyTask(task, analysis, defaultConfig);
-
- expect(result.autoApprove).toBe(true);
- expect(result.category).toBe('import-cleanup');
- });
-
- it('should auto-approve documentation updates', () => {
- // "doc" keyword triggers documentation pattern (not "comment" which triggers typo-fix)
- const task = { description: 'Update the documentation' };
- const analysis = { linesChanged: 50 };
-
- const result = classifyTask(task, analysis, defaultConfig);
-
- expect(result.autoApprove).toBe(true);
- expect(result.category).toBe('documentation');
- });
- });
-
- describe('line limit enforcement', () => {
- it('should reject auto-approve when exceeding category line limit', () => {
- const task = { description: 'Fix typo in comments' };
- const analysis = { linesChanged: 25 }; // typo-fix limit is 20
-
- const result = classifyTask(task, analysis, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('typo-fix');
- expect(result.reason).toContain('exceed auto-approve limit');
- });
-
- it('should reject auto-approve when exceeding global max lines', () => {
- const configWithLowLimit = {
- autoFixThresholds: {
- maxLinesChanged: 10,
- allowedCategories: ['formatting']
- }
- };
- const task = { description: 'Format all files' };
- const analysis = { linesChanged: 15 };
-
- const result = classifyTask(task, analysis, configWithLowLimit);
-
- expect(result.autoApprove).toBe(false);
- expect(result.reason).toContain('exceed');
- });
-
- it('should use category line limit if lower than global', () => {
- const task = { description: 'Remove dead code' };
- const analysis = { linesChanged: 40 }; // dead-code limit is 30
-
- const result = classifyTask(task, analysis, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- });
- });
-
- describe('category allowlist enforcement', () => {
- it('should reject categories not in allowlist', () => {
- const restrictedConfig = {
- autoFixThresholds: {
- maxLinesChanged: 100,
- allowedCategories: ['typo-fix'] // Only typo-fix allowed
- }
- };
- const task = { description: 'Format code' };
- const analysis = { linesChanged: 10 };
-
- const result = classifyTask(task, analysis, restrictedConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.reason).toContain('not in auto-approve list');
- });
- });
-
- describe('require-approval patterns (high priority)', () => {
- it('should require approval for security-related tasks', () => {
- const task = { description: 'Update authentication logic' };
-
- const result = classifyTask(task, null, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('security');
- expect(result.confidence).toBe('high');
- });
-
- it('should require approval for password handling', () => {
- const task = { description: 'Change password validation' };
-
- const result = classifyTask(task, null, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('security');
- });
-
- it('should require approval for database changes', () => {
- const task = { description: 'Update database schema' };
-
- const result = classifyTask(task, null, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('database');
- });
-
- it('should require approval for migrations', () => {
- const task = { description: 'Create prisma migration' };
-
- const result = classifyTask(task, null, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('database');
- });
-
- it('should require approval for API changes', () => {
- const task = { description: 'Make breaking change to API' };
-
- const result = classifyTask(task, null, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('api-change');
- });
-
- it('should require approval for dependency updates', () => {
- const task = { description: 'Update package.json dependencies' };
-
- const result = classifyTask(task, null, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('dependency');
- });
-
- it('should require approval for architecture changes', () => {
- const task = { description: 'Restructure the entire module' };
-
- const result = classifyTask(task, null, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('architecture');
- });
-
- it('should require approval for config changes', () => {
- const task = { description: 'Modify ecosystem.config settings' };
-
- const result = classifyTask(task, null, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('config');
- });
-
- it('should require approval for deployment tasks', () => {
- const task = { description: 'Deploy to production' };
-
- const result = classifyTask(task, null, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('deployment');
- });
- });
-
- describe('priority of require-approval over auto-approve', () => {
- it('should require approval even if description also matches auto-approve', () => {
- // Task mentions both security (require) and typo (auto)
- const task = { description: 'Fix typo in security token' };
-
- const result = classifyTask(task, { linesChanged: 1 }, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('security');
- });
- });
-
- describe('unknown category handling', () => {
- it('should default to require approval for unknown patterns', () => {
- const task = { description: 'Do something completely unrelated' };
-
- const result = classifyTask(task, null, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('unknown');
- expect(result.confidence).toBe('low');
- });
- });
-
- describe('empty/null handling', () => {
- it('should handle task with no description', () => {
- const task = {};
-
- const result = classifyTask(task, null, defaultConfig);
-
- expect(result.autoApprove).toBe(false);
- expect(result.category).toBe('unknown');
- });
-
- it('should handle null analysis result', () => {
- const task = { description: 'Format code' };
-
- const result = classifyTask(task, null, defaultConfig);
-
- // Should still work without analysis (line count = 0)
- expect(result.category).toBe('formatting');
- });
-
- it('should handle null config', () => {
- const task = { description: 'Format code' };
- const analysis = { linesChanged: 10 };
-
- // Should use defaults
- const result = classifyTask(task, analysis, null);
-
- expect(result.category).toBe('formatting');
- expect(result.autoApprove).toBe(false); // No allowed categories in null config
- });
- });
- });
-
- describe('classifyReviewFindings', () => {
- const defaultConfig = {
- autoFixThresholds: {
- maxLinesChanged: 50,
- allowedCategories: ['typo-fix', 'dead-code']
- }
- };
-
- it('should classify array of findings', () => {
- const findings = [
- { title: 'Fix typo', estimatedLines: 5 },
- { title: 'Security issue', estimatedLines: 10 }
- ];
-
- const results = classifyReviewFindings(findings, defaultConfig);
-
- expect(results).toHaveLength(2);
- expect(results[0].autoApprove).toBe(true);
- expect(results[0].category).toBe('typo-fix');
- expect(results[1].autoApprove).toBe(false);
- expect(results[1].category).toBe('security');
- });
-
- it('should preserve original finding data', () => {
- const findings = [
- { title: 'Fix typo', estimatedLines: 5, file: 'test.js', line: 42 }
- ];
-
- const results = classifyReviewFindings(findings, defaultConfig);
-
- expect(results[0].file).toBe('test.js');
- expect(results[0].line).toBe(42);
- });
-
- it('should handle findings with description instead of title', () => {
- const findings = [
- { description: 'Remove dead code', estimatedLines: 10 }
- ];
-
- const results = classifyReviewFindings(findings, defaultConfig);
-
- expect(results[0].category).toBe('dead-code');
- });
- });
-
- describe('getClassificationRules', () => {
- it('should return both auto-approve and require-approval rules', () => {
- const rules = getClassificationRules();
-
- expect(rules).toHaveProperty('autoApprove');
- expect(rules).toHaveProperty('requireApproval');
- expect(Array.isArray(rules.autoApprove)).toBe(true);
- expect(Array.isArray(rules.requireApproval)).toBe(true);
- });
-
- it('should include all auto-approve categories', () => {
- const rules = getClassificationRules();
- const categories = rules.autoApprove.map(r => r.category);
-
- expect(categories).toContain('formatting');
- expect(categories).toContain('dry-violations');
- expect(categories).toContain('dead-code');
- expect(categories).toContain('typo-fix');
- expect(categories).toContain('import-cleanup');
- expect(categories).toContain('documentation');
- });
-
- it('should include all require-approval categories', () => {
- const rules = getClassificationRules();
- const categories = rules.requireApproval.map(r => r.category);
-
- expect(categories).toContain('security');
- expect(categories).toContain('database');
- expect(categories).toContain('api-change');
- expect(categories).toContain('dependency');
- expect(categories).toContain('architecture');
- expect(categories).toContain('config');
- expect(categories).toContain('deployment');
- });
-
- it('should include max lines for auto-approve rules', () => {
- const rules = getClassificationRules();
-
- rules.autoApprove.forEach(rule => {
- expect(rule.maxLines).toBeDefined();
- expect(typeof rule.maxLines).toBe('number');
- });
- });
-
- it('should include reason for require-approval rules', () => {
- const rules = getClassificationRules();
-
- rules.requireApproval.forEach(rule => {
- expect(rule.reason).toBeDefined();
- expect(typeof rule.reason).toBe('string');
- });
- });
- });
-
- describe('isIdleReviewTask', () => {
- it('should identify tasks with [Idle Review] in description', () => {
- const task = { description: '[Idle Review] Check codebase' };
-
- expect(isIdleReviewTask(task)).toBe(true);
- });
-
- it('should identify tasks with autonomous code review in description', () => {
- const task = { description: 'Autonomous code review of the project' };
-
- expect(isIdleReviewTask(task)).toBe(true);
- });
-
- it('should identify tasks with reviewType: idle metadata', () => {
- const task = {
- description: 'Review something',
- metadata: { reviewType: 'idle' }
- };
-
- expect(isIdleReviewTask(task)).toBe(true);
- });
-
- it('should identify tasks with autoGenerated: true metadata', () => {
- const task = {
- description: 'Some generated task',
- metadata: { autoGenerated: true }
- };
-
- expect(isIdleReviewTask(task)).toBe(true);
- });
-
- it('should return false for regular user tasks', () => {
- const task = {
- description: 'Fix the login bug',
- metadata: {}
- };
-
- expect(isIdleReviewTask(task)).toBe(false);
- });
-
- it('should handle task with no description', () => {
- const task = { metadata: {} };
-
- expect(isIdleReviewTask(task)).toBe(false);
- });
- });
-
- describe('estimateTaskComplexity', () => {
- describe('high complexity detection', () => {
- it('should detect multi-file tasks', () => {
- const task = { description: 'Update multiple files across codebase' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('high');
- });
-
- it('should detect codebase-wide tasks', () => {
- const task = { description: 'Refactor pattern across codebase' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('high');
- });
-
- it('should detect restructuring tasks', () => {
- const task = { description: 'Restructure the component hierarchy' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('high');
- });
-
- it('should detect migration tasks', () => {
- const task = { description: 'Migration to new API version' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('high');
- });
-
- it('should detect integration tasks', () => {
- const task = { description: 'Integration with external service' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('high');
- });
- });
-
- describe('low complexity detection', () => {
- it('should detect single-file tasks', () => {
- const task = { description: 'Update single file' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('low');
- });
-
- it('should detect one-line changes', () => {
- const task = { description: 'Change one line in config' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('low');
- });
-
- it('should detect simple tasks', () => {
- const task = { description: 'Simple fix for button' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('low');
- });
-
- it('should detect typo tasks', () => {
- const task = { description: 'Fix typo in message' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('low');
- });
-
- it('should detect comment tasks', () => {
- const task = { description: 'Add comment to function' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('low');
- });
-
- it('should detect rename tasks', () => {
- const task = { description: 'Rename variable foo to bar' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('low');
- });
- });
-
- describe('medium complexity (default)', () => {
- it('should return medium for standard tasks', () => {
- const task = { description: 'Implement user authentication' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('medium');
- });
-
- it('should return medium for tasks without complexity indicators', () => {
- const task = { description: 'Add new feature to dashboard' };
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('medium');
- });
- });
-
- describe('empty/null handling', () => {
- it('should handle task with no description', () => {
- const task = {};
-
- const result = estimateTaskComplexity(task);
-
- expect(result.level).toBe('medium');
- });
- });
- });
-});