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(memory): prevent mutex deadlock on error, extract shared createMutex utility
Adam Eivybf29dad587ba
diff --git a/.changelog/v0.16.x.md b/.changelog/v0.16.x.mdindex bb13b88352..7b4f0d02f7 100644--- a/.changelog/v0.16.x.md+++ b/.changelog/v0.16.x.md@@ -15,6 +15,10 @@ Agent persistence, reliability, and decision transparency improvements.## Fixes+### Async mutex deadlock bug in memory service+- **`withMemoryLock` deadlocked on error** -- the promise-based mutex in `memory.js` called `resolve()` after `await fn()` with no `try/finally`, so if `fn()` threw, the lock was never released and all subsequent memory operations would hang forever+- **Extracted shared `createMutex()` utility** -- both `cos.js` and `memory.js` had identical inline mutex implementations; moved to `server/lib/asyncMutex.js` with guaranteed `try/finally` release+### Agent history now persists across state resets- **Completed agents no longer disappear** -- previously, all agent history was stored only in `state.json`; if the state file was reset or corrupted, all completed agents vanished from the UI despite metadata files existing on disk- **Added disk-backed agent cache** -- `getAgents()` now merges in-memory state (running agents) with persisted metadata files from `data/cos/agents/{id}/metadata.json`, so completed agents always survive state resetsdiff --git a/server/lib/asyncMutex.js b/server/lib/asyncMutex.jsnew file mode 100644index 0000000000..3b4a40227b--- /dev/null+++ b/server/lib/asyncMutex.js@@ -0,0 +1,19 @@+/**+ * Creates a simple async mutex (promise-based lock).+ * Returns a `withLock(fn)` function that serializes async operations.+ * Uses try/finally to guarantee the lock is always released, even on error.+ */+export function createMutex() {+ let lock = Promise.resolve();+ return async function withLock(fn) {+ const release = lock;+ let resolve;+ lock = new Promise(r => { resolve = r; });+ await release;+ try {+ return await fn();+ } finally {+ resolve();+ }+ };+}diff --git a/server/services/cos.js b/server/services/cos.jsindex 44c0e0ad22..f09e17f0c5 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -18,6 +18,7 @@ import { isAppOnCooldown, getNextAppForReview, markAppReviewStarted, markIdleRevimport { getActiveApps } from './apps.js';import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights } from './taskLearning.js';import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats } from './eventScheduler.js';+import { createMutex } from '../lib/asyncMutex.js';import { generateProactiveTasks as generateMissionTasks, getStats as getMissionStats } from './missions.js';import { getDueJobs, generateTaskFromJob, recordJobExecution } from './autonomousJobs.js';import { formatDuration } from '../lib/fileUtils.js';@@ -147,18 +148,7 @@ async function loadCompletedAgentCache() {}// Mutex lock for state operations to prevent race conditions-let stateLock = Promise.resolve();-async function withStateLock(fn) {- const release = stateLock;- let resolve;- stateLock = new Promise(r => { resolve = r; });- await release;- try {- return await fn();- } finally {- resolve();- }-}+const withStateLock = createMutex();/*** Default configurationdiff --git a/server/services/memory.js b/server/services/memory.jsindex 17430d730b..25918d5e18 100644--- a/server/services/memory.js+++ b/server/services/memory.js@@ -15,6 +15,7 @@ import { findTopK, findAboveThreshold, clusterBySimilarity, cosineSimilarity } fimport * as notifications from './notifications.js';import { readJSONFile } from '../lib/fileUtils.js';import * as memoryBM25 from './memoryBM25.js';+import { createMutex } from '../lib/asyncMutex.js';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -44,16 +45,7 @@ let indexCache = null;let embeddingsCache = null;// Mutex lock for state operations-let memoryLock = Promise.resolve();-async function withMemoryLock(fn) {- const release = memoryLock;- let resolve;- memoryLock = new Promise(r => { resolve = r; });- await release;- const result = await fn();- resolve();- return result;-}+const withMemoryLock = createMutex();/*** Ensure memory directories exist