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: harden persistent mind lifecycle races (#5064)
[._.]/ Adam Eivyb59d753554ba
diff --git a/server/services/cos.js b/server/services/cos.jsindex 865df4f6a1..f1f65b7e37 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -237,6 +237,11 @@ export async function updateConfig(updates) {return state.config;});cosEvents.emit('config:changed', config);+ if (isDaemonRunning() && updates.domainAutonomy !== undefined) {+ const mode = getDomainMode(config, 'cos');+ if (mode === 'execute') await handlePersistentMindGlobalResume();+ else await handlePersistentMindGlobalPause(`CoS autonomy changed to ${mode}`);+ }return config;}diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex f9be7b97c4..310100df8a 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -2412,6 +2412,12 @@ describe('persistent mind — default-off CoS state integration (#5064)', () =>activeTurn: null,});});++ it('suspends and re-arms the mind when the CoS autonomy mode changes', () => {+ const updateFn = extractFnBody(COS_SRC, COS_SRC.indexOf('export async function updateConfig'));+ expect(updateFn).toMatch(/mode === 'execute'[\s\S]*handlePersistentMindGlobalResume\(\)/);+ expect(updateFn).toMatch(/handlePersistentMindGlobalPause\(`CoS autonomy changed to \$\{mode\}`\)/);+ });});describe('pending-merge sweep — own timer, not the evaluation cadence (#3630)', () => {diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.jsindex 9ea9bc92a3..ac7db459ce 100644--- a/server/services/persistentMindSupervisor.js+++ b/server/services/persistentMindSupervisor.js@@ -21,7 +21,7 @@ import {requeuePersistentMindWake,takeNextPersistentMindWake,} from '../lib/persistentMind.js';-import { loadState, saveState, withStateLock } from './cosState.js';+import { isDaemonRunning, loadState, saveState, withStateLock } from './cosState.js';import { cosEvents, emitLog } from './cosEvents.js';import { schedule, cancel } from './eventScheduler.js';import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';@@ -35,6 +35,7 @@ let turnAdapter = null;let activeRun = null;let activeAbortController = null;let runtimeGeneration = 0;+let supervisorStopping = false;const nowIso = () => new Date().toISOString();const errorMessage = (error) => String(error?.message || error || 'Persistent mind turn failed')@@ -65,6 +66,7 @@ function emitMindStatus(state) {}function armWatchdog() {+ if (supervisorStopping || !isDaemonRunning()) return;schedule({id: PERSISTENT_MIND_WATCHDOG_EVENT_ID,type: 'interval',@@ -77,14 +79,26 @@ function armWatchdog() {async function scheduleNextWake() {const root = await loadState();const state = normalizePersistentMindState(root.persistentMind);- const dueAt = nextPersistentMindWakeAt(state);cancel(PERSISTENT_MIND_WAKE_EVENT_ID);+ if (supervisorStopping || !isDaemonRunning() || root.paused || getDomainMode(root.config, 'cos') !== 'execute') return;+ const dueAt = nextPersistentMindWakeAt(state);if (dueAt == null || activeRun) return;schedule({id: PERSISTENT_MIND_WAKE_EVENT_ID,type: 'once',delayMs: Math.max(1, dueAt - Date.now()),- handler: () => drainPersistentMind(),+ handler: async () => {+ await drainPersistentMind({ rearm: false });+ // eventScheduler removes a one-shot's timer handle after its handler+ // resolves. Replacing the same id inside the handler would make the new+ // timer live but uncancellable, so defer the replacement one event-loop+ // turn until that cleanup is complete.+ setImmediate(() => {+ scheduleNextWake().catch((error) => {+ console.error(`❌ Failed to re-arm persistent mind wake: ${error.message}`);+ });+ });+ },metadata: { description: 'Persistent CoS mind next eligible wake' },});}@@ -112,10 +126,12 @@ function quietSelfWake(turnId, notBefore = Date.now() + PERSISTENT_MIND_LIMITS.M};}-async function interruptActiveTurn(reason, status, { retry = false } = {}) {- runtimeGeneration += 1;- activeAbortController?.abort(reason);+async function interruptActiveTurn(reason, status, { retry = false, expectedTurnId = null } = {}) {const result = await mutateMindState((mind) => {+ if (expectedTurnId && mind.activeTurn?.id !== expectedTurnId) {+ return { mind, value: false };+ }+ const interrupted = Boolean(mind.activeTurn);let next = mind;if (mind.activeTurn) next = requeuePersistentMindWake(next, mind.activeTurn.wake);const failureCount = retry ? next.failureCount + 1 : next.failureCount;@@ -131,10 +147,15 @@ async function interruptActiveTurn(reason, status, { retry = false } = {}) {? new Date(Date.now() + persistentMindBackoffMs(failureCount)).toISOString(): null,},+ value: interrupted,};});+ if (result.value) {+ runtimeGeneration += 1;+ activeAbortController?.abort(reason);+ }emitMindStatus(result.state);- return result.state;+ return { state: result.state, interrupted: result.value === true };}async function parkActiveTurn(turnId, reason, status = 'waiting', retryAt = null) {@@ -160,6 +181,7 @@ async function parkActiveTurn(turnId, reason, status = 'waiting', retryAt = nullasync function claimNextTurn() {const result = await mutateMindState((mind, root) => {+ if (supervisorStopping || !isDaemonRunning()) return { mind, value: null };if (!mind.enabled || !mind.started || mind.activeTurn || mind.status === 'paused') return { mind, value: null };if (root.paused || getDomainMode(root.config, 'cos') !== 'execute') return { mind, value: null };const selected = takeNextPersistentMindWake(mind);@@ -190,6 +212,16 @@ async function claimNextTurn() {return result.value;}+async function turnCanContinue(turnId, generation, signal) {+ if (supervisorStopping || !isDaemonRunning() || generation !== runtimeGeneration || signal.aborted) return false;+ const state = await getPersistentMindState();+ return !supervisorStopping+ && isDaemonRunning()+ && generation === runtimeGeneration+ && !signal.aborted+ && state.activeTurn?.id === turnId;+}+async function recordTurnProfile(turnId, prepared) {await mutateMindState((mind) => {if (mind.activeTurn?.id !== turnId) return { mind };@@ -226,7 +258,7 @@ async function completeTurn(turnId, result, generation) {if (generation !== runtimeGeneration) return;const completedAt = nowIso();const updated = await mutateMindState((mind) => {- if (mind.activeTurn?.id !== turnId) return { mind };+ if (mind.activeTurn?.id !== turnId) return { mind, value: false };const messageId = mind.activeTurn.wake.kind === 'message'? mind.activeTurn.wake.message.id: null;@@ -260,8 +292,10 @@ async function completeTurn(turnId, result, generation) {status: hasQueuedMessages ? 'waiting' : 'idle',pauseReason: null,},+ value: true,};});+ if (!updated.value) return;emitMindStatus(updated.state);cosEvents.emit('persistent-mind:turn-completed', {turnId,@@ -270,6 +304,7 @@ async function completeTurn(turnId, result, generation) {}async function runOnePersistentMindTurn() {+ if (supervisorStopping || !isDaemonRunning()) return;if (!turnAdapter) {const updated = await mutateMindState((mind) => ({mind: mind.enabled && mind.started@@ -288,9 +323,25 @@ async function runOnePersistentMindTurn() {const root = await loadState();const mind = normalizePersistentMindState(root.persistentMind);+ if (supervisorStopping || !isDaemonRunning()) return;if (!mind.enabled || !mind.started || mind.status === 'paused') return;if (root.paused || getDomainMode(root.config, 'cos') !== 'execute') return;+ const runningAgents = Object.values(root.agents || {}).filter((agent) => agent.status === 'running').length;+ const maxConcurrentAgents = Number(root.config?.maxConcurrentAgents);+ if (Number.isSafeInteger(maxConcurrentAgents) && runningAgents >= maxConcurrentAgents) {+ const updated = await mutateMindState((current) => ({+ mind: {+ ...current,+ status: 'waiting',+ pauseReason: `CoS agent capacity exhausted (${runningAgents}/${maxConcurrentAgents})`,+ nextEligibleWakeAt: new Date(Date.now() + PERSISTENT_MIND_LIMITS.BACKOFF_BASE_MS).toISOString(),+ },+ }));+ emitMindStatus(updated.state);+ return;+ }+let budget;try {budget = await getDomainBudgetStatus('cos');@@ -334,11 +385,13 @@ async function runOnePersistentMindTurn() {// `prepare` must resolve the exact configured provider. The supervisor never// follows a fallback chain: an unavailable pin is a visible degraded state.const prepared = await turnAdapter.prepare({ wake: turn.wake, signal: controller.signal });+ if (!await turnCanContinue(turn.id, generation, controller.signal)) return;if (!prepared?.ok || !prepared.provider) {await parkActiveTurn(turn.id, prepared?.error || 'Persistent mind provider is unavailable', 'degraded', prepared?.retryAt || null);return;}await recordTurnProfile(turn.id, prepared);+ if (!await turnCanContinue(turn.id, generation, controller.signal)) return;const latestRoot = await loadState();const slot = await acquireLocalEndpointProviderSlot(prepared.provider, latestRoot.agents, turn.id);@@ -347,6 +400,7 @@ async function runOnePersistentMindTurn() {return;}release = slot.release;+ if (!await turnCanContinue(turn.id, generation, controller.signal)) return;runStartedAt = Date.now();const result = await turnAdapter.run({turnId: turn.id,@@ -449,7 +503,7 @@ export async function startPersistentMind() {}export async function pausePersistentMind(reason = 'Paused by user') {- const state = await interruptActiveTurn(reason, 'paused');+ const { state } = await interruptActiveTurn(reason, 'paused');cancel(PERSISTENT_MIND_WAKE_EVENT_ID);return { success: true, state };}@@ -551,13 +605,13 @@ export async function requestPersistentMindWake({ sourceTurnId, reason, notBeforreturn result.value;}-export async function drainPersistentMind() {+export async function drainPersistentMind({ rearm = true } = {}) {if (activeRun) return activeRun;const run = runOnePersistentMindTurn();activeRun = run.finally(async () => {activeRun = null;activeAbortController = null;- await scheduleNextWake();+ if (rearm) await scheduleNextWake();});return activeRun;}@@ -565,12 +619,16 @@ export async function drainPersistentMind() {export async function checkPersistentMindWatchdog() {const state = await getPersistentMindState();if (!persistentMindTurnIsStale(state)) return { interrupted: false };- await interruptActiveTurn('Persistent mind turn heartbeat expired', 'interrupted', { retry: true });- await scheduleNextWake();- return { interrupted: true };+ const result = await interruptActiveTurn('Persistent mind turn heartbeat expired', 'interrupted', {+ retry: true,+ expectedTurnId: state.activeTurn.id,+ });+ if (result.interrupted) await scheduleNextWake();+ return { interrupted: result.interrupted };}export async function initializePersistentMindSupervisor() {+ supervisorStopping = false;const recovered = await mutateMindState((mind) => {if (!mind.enabled || !mind.started) return { mind };let next = mind;@@ -606,7 +664,7 @@ export async function handlePersistentMindGlobalPause(reason = 'Chief of Staff pcancel(PERSISTENT_MIND_WAKE_EVENT_ID);return state;}- return interruptActiveTurn(reason, 'waiting');+ return (await interruptActiveTurn(reason, 'waiting')).state;}export async function handlePersistentMindGlobalResume() {@@ -614,13 +672,14 @@ export async function handlePersistentMindGlobalResume() {}export async function shutdownPersistentMindSupervisor() {+ supervisorStopping = true;runtimeGeneration += 1;activeAbortController?.abort('Chief of Staff daemon stopped');cancel(PERSISTENT_MIND_WAKE_EVENT_ID);cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);const state = await getPersistentMindState();if (!state.activeTurn) return state;- return interruptActiveTurn('Chief of Staff daemon stopped', 'interrupted', { retry: true });+ return (await interruptActiveTurn('Chief of Staff daemon stopped', 'interrupted', { retry: true })).state;}export function __resetPersistentMindSupervisorForTests() {@@ -628,6 +687,7 @@ export function __resetPersistentMindSupervisorForTests() {activeRun = null;activeAbortController = null;runtimeGeneration = 0;+ supervisorStopping = false;cancel(PERSISTENT_MIND_WAKE_EVENT_ID);cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);}diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsindex 75d6407980..cf87731135 100644--- a/server/services/persistentMindSupervisor.test.js+++ b/server/services/persistentMindSupervisor.test.js@@ -8,12 +8,14 @@ const mock = vi.hoisted(() => ({budget: { withinBudget: true, exceeded: null },recordUsage: vi.fn(async () => {}),acquireSlot: vi.fn(async () => ({ ok: true, release: vi.fn() })),+ daemonRunning: true,}));vi.mock('./cosState.js', () => ({loadState: vi.fn(async () => mock.root),saveState: vi.fn(async (state) => { mock.root = state; }),withStateLock: vi.fn(async (fn) => fn()),+ isDaemonRunning: vi.fn(() => mock.daemonRunning),}));vi.mock('./cosEvents.js', () => ({@@ -42,7 +44,7 @@ const supervisor = await import('./persistentMindSupervisor.js');const makeRoot = () => ({paused: false,- config: { domainAutonomy: { cos: 'execute' } },+ config: { domainAutonomy: { cos: 'execute' }, maxConcurrentAgents: 3 },agents: {},persistentMind: createDefaultPersistentMindState(),});@@ -60,6 +62,7 @@ describe('persistent mind supervisor', () => {mock.scheduled.clear();mock.emitted.length = 0;mock.budget = { withinBudget: true, exceeded: null };+ mock.daemonRunning = true;mock.recordUsage.mockClear();mock.acquireSlot.mockReset();mock.acquireSlot.mockResolvedValue({ ok: true, release: vi.fn() });@@ -177,6 +180,25 @@ describe('persistent mind supervisor', () => {expect(mock.root.persistentMind.nextEligibleWakeAt).not.toBeNull();});+ it('holds queued work durably when ordinary CoS agents fill the global capacity', async () => {+ const prepare = vi.fn();+ const run = vi.fn();+ await supervisor.registerPersistentMindTurnAdapter({ prepare, run });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Wait for a global slot.' });+ mock.root.config.maxConcurrentAgents = 1;+ mock.root.agents = { 'agent-1': { status: 'running' } };++ await supervisor.drainPersistentMind();++ expect(prepare).not.toHaveBeenCalled();+ expect(run).not.toHaveBeenCalled();+ expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-1']);+ expect(mock.root.persistentMind.pauseReason).toBe('CoS agent capacity exhausted (1/1)');+ expect(mock.root.persistentMind.nextEligibleWakeAt).not.toBeNull();+ });+it('requeues a claimed message when the shared local endpoint has no slot', async () => {const run = vi.fn();await supervisor.registerPersistentMindTurnAdapter({@@ -196,6 +218,73 @@ describe('persistent mind supervisor', () => {expect(mock.root.persistentMind.pauseReason).toContain('at capacity');});+ it('does not schedule or run a wake while the CoS lifecycle gate is closed', async () => {+ const run = vi.fn();+ await supervisor.registerPersistentMindTurnAdapter({+ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' } })),+ run,+ });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ mock.scheduled.clear();+ mock.root.paused = true;++ await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Wait for resume.' });+ await supervisor.drainPersistentMind();++ expect(run).not.toHaveBeenCalled();+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID)).toBe(false);+ expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-1']);++ mock.root.paused = false;+ mock.daemonRunning = false;+ await supervisor.handlePersistentMindGlobalResume();+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID)).toBe(false);+ });++ it('re-arms a fired one-shot only after the scheduler can finish cleaning it up', async () => {+ await supervisor.registerPersistentMindTurnAdapter({+ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' } })),+ run: vi.fn(async () => ({})),+ });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ const firstWake = mock.scheduled.get(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID);++ await firstWake.handler();+ // Mirrors eventScheduler's one-shot cleanup immediately after await handler().+ mock.scheduled.delete(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID);+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID)).toBe(false);+ await new Promise((resolve) => setImmediate(resolve));++ const replacement = mock.scheduled.get(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID);+ expect(replacement).toBeDefined();+ expect(replacement).not.toBe(firstWake);+ });++ it('does not start a turn when cancellation lands while provider preparation is pending', async () => {+ const prepared = deferred();+ const run = vi.fn();+ await supervisor.registerPersistentMindTurnAdapter({+ prepare: vi.fn(() => prepared.promise),+ run,+ });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Cancel before inference.' });+ const drain = supervisor.drainPersistentMind();+ await vi.waitFor(() => expect(mock.root.persistentMind.activeTurn).not.toBeNull());++ await supervisor.pausePersistentMind();+ prepared.resolve({ ok: true, provider: { id: 'example-cloud' } });+ await drain;++ expect(run).not.toHaveBeenCalled();+ expect(mock.acquireSlot).not.toHaveBeenCalled();+ expect(mock.root.persistentMind.status).toBe('paused');+ expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-1']);+ });+it('watchdog interruption aborts and requeues a stale turn without starting a second copy', async () => {const run = vi.fn(({ signal }) => new Promise((resolve, reject) => {signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true });@@ -222,6 +311,41 @@ describe('persistent mind supervisor', () => {expect(mock.root.persistentMind.status).toBe('interrupted');});+ it('does not interrupt a replacement turn when a stale watchdog snapshot loses the race', async () => {+ mock.root.persistentMind = {+ ...createDefaultPersistentMindState(),+ enabled: true,+ started: true,+ status: 'thinking',+ activeTurn: {+ id: 'turn-stale',+ wake: { kind: 'self', id: 'wake-stale', reason: 'stale', sourceTurnId: 'turn-0', createdAt: new Date(1).toISOString(), notBefore: null },+ startedAt: new Date(1).toISOString(),+ heartbeatAt: new Date(1).toISOString(),+ providerId: 'example-cloud',+ model: null,+ effort: null,+ },+ };+ const originalWithStateLock = (await import('./cosState.js')).withStateLock;+ let replaced = false;+ originalWithStateLock.mockImplementationOnce(async (fn) => {+ mock.root.persistentMind.activeTurn = {+ ...mock.root.persistentMind.activeTurn,+ id: 'turn-replacement',+ heartbeatAt: new Date().toISOString(),+ };+ replaced = true;+ return fn();+ });++ await expect(supervisor.checkPersistentMindWatchdog()).resolves.toEqual({ interrupted: false });++ expect(replaced).toBe(true);+ expect(mock.root.persistentMind.activeTurn.id).toBe('turn-replacement');+ expect(mock.root.persistentMind.status).toBe('thinking');+ });+it('coalesces self-wakes and rejects a recursive wake without a completed source turn', async () => {mock.root.persistentMind = {...createDefaultPersistentMindState(),