Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: make completed agent cache load resilient to file errors
Adam Eivy984fd3aaf4c7
diff --git a/.changelog/v0.16.x.md b/.changelog/v0.16.x.mdindex 53c0185222..3fc84564b6 100644--- a/.changelog/v0.16.x.md+++ b/.changelog/v0.16.x.md@@ -16,6 +16,11 @@ Agent persistence, reliability, and decision transparency improvements.- **`deleteAgent()` now cleans up disk files** -- previously only removed from state, leaving orphaned metadata directories; now removes the agent directory entirely- **`clearCompletedAgents()` now cleans up disk files** -- previously only cleared state, leaving metadata files that would reappear on next cache load; now removes all completed agent directories+### Agent cache load made resilient to individual file errors+- **JSON parse errors no longer crash the entire cache load** -- a single corrupt `metadata.json` file previously caused `Promise.all` to reject, leaving the cache permanently empty (showing only agents from `state.json`). Now uses `Promise.allSettled` and per-file try/catch so bad files are skipped while all others load+- **Failed cache loads can now be retried** -- the cache Map is built locally and only promoted to the module-level variable after successful loading; if `readdir` or another system call fails, the cache stays `null` and the next API call will re-attempt the load+- **Diagnostic logging** -- cache load now reports count of skipped/unreadable files alongside recovered count+### Full agent recovery from disk- **38 agents with missing metadata recovered** -- agent directories created before metadata persistence was added now get reconstructed `metadata.json` files on first cache load, using directory timestamps as completion dates- **8 agents with legacy metadata format normalized** -- older metadata files using `agentId` instead of `id` and missing `status` field are now properly loaded into the cachediff --git a/server/services/cos.js b/server/services/cos.jsindex 4ad452f0a2..6106263e08 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -76,11 +76,17 @@ let completedAgentCache = null;async function loadCompletedAgentCache() {if (completedAgentCache) return completedAgentCache;- completedAgentCache = new Map();- if (!existsSync(AGENTS_DIR)) return completedAgentCache;+ if (!existsSync(AGENTS_DIR)) {+ completedAgentCache = new Map();+ return completedAgentCache;+ }+ // Build into a local Map — only assign to module-level cache on success+ // so a failed load can be retried on the next call+ const cache = new Map();const entries = await readdir(AGENTS_DIR, { withFileTypes: true });let recovered = 0;+ let skipped = 0;const metadataReads = entries.filter(e => e.isDirectory() && e.name.startsWith('agent-')).map(async (entry) => {@@ -90,15 +96,16 @@ async function loadCompletedAgentCache() {if (existsSync(metaPath)) {const content = await readFile(metaPath, 'utf-8').catch(() => null);- if (!content) return;- const raw = JSON.parse(content);+ if (!content) { skipped++; return; }+ let raw;+ try { raw = JSON.parse(content); } catch { skipped++; return; }// Normalize legacy format: agentId → id, missing status → completedconst id = raw.id || raw.agentId || agentId;- const status = raw.status || (raw.completedAt ? 'completed' : 'completed');+ const status = raw.status || 'completed';if (status !== 'running') {const { output, ...rest } = raw;- completedAgentCache.set(id, { ...rest, id, status });+ cache.set(id, { ...rest, id, status });}return;}@@ -123,15 +130,19 @@ async function loadCompletedAgentCache() {// Persist the reconstructed metadata so future loads are fastawait writeFile(metaPath, JSON.stringify(reconstructed, null, 2)).catch(() => {});- completedAgentCache.set(agentId, reconstructed);+ cache.set(agentId, reconstructed);recovered++;});- await Promise.all(metadataReads);- const msg = recovered > 0- ? `📂 Loaded ${completedAgentCache.size} completed agents from disk (recovered ${recovered} missing metadata)`- : `📂 Loaded ${completedAgentCache.size} completed agents from disk`;- console.log(msg);+ // Use allSettled so individual file errors don't abort the entire load+ await Promise.allSettled(metadataReads);++ // Only assign to module-level cache after successful build+ completedAgentCache = cache;+ const parts = [`📂 Loaded ${cache.size} completed agents from disk`];+ if (recovered > 0) parts.push(`recovered ${recovered} missing metadata`);+ if (skipped > 0) parts.push(`skipped ${skipped} unreadable`);+ console.log(parts.length > 1 ? `${parts[0]} (${parts.slice(1).join(', ')})` : parts[0]);return completedAgentCache;}