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

fix: prevent duplicate agent recovery on restart

[._.]/ Adam Eivy30e582a43f8f
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index 0c6ae84451..af923f39c9 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -200,8 +200,8 @@ describe('recovery output-hook dispatch (#3182)', () => {
describe('recovery path wiring (#3182)', () => {
it('dispatches before orphan cleanup marks the agent complete', () => {
- const start = MANAGEMENT_SOURCE.indexOf('export async function cleanupOrphanedAgents');
- const body = MANAGEMENT_SOURCE.slice(start, start + 7_000);
+ const start = MANAGEMENT_SOURCE.indexOf('async function runCleanupOrphanedAgents');
+ const body = MANAGEMENT_SOURCE.slice(start, start + 12_000);
expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeGreaterThan(-1);
expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeLessThan(body.indexOf('await completeAgent(agent.id'));
});
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index b2c5db6189..e80479d39f 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -50,6 +50,13 @@ const MAX_ORPHAN_RETRIES = 3;
// Minimum cooldown between orphan retries (30 minutes)
const ORPHAN_RETRY_COOLDOWN_MS = 30 * 60 * 1000;
+// Startup has two callers for this sweep: cos.start() awaits it before the
+// first dequeue, while the spawner's delayed safety sweep runs shortly after
+// its event wiring. Keep the whole sweep single-flight so both callers cannot
+// read the same running agent and each requeue it (which would emit duplicate
+// wakeups and dispatch the same claim task twice).
+let orphanCleanupPromise = null;
+
/**
* Map a failed runner-op result (`{ error?, status? }`) to a ServerError.
* A genuine runner 404 — the agent is gone / the runner restarted out of sync
@@ -946,7 +953,16 @@ async function retireStrandedPausedAgents(agents) {
}
}
-export async function cleanupOrphanedAgents() {
+export function cleanupOrphanedAgents() {
+ if (!orphanCleanupPromise) {
+ orphanCleanupPromise = runCleanupOrphanedAgents().finally(() => {
+ orphanCleanupPromise = null;
+ });
+ }
+ return orphanCleanupPromise;
+}
+
+async function runCleanupOrphanedAgents() {
// Was `await import('./cos.js')` destructuring all four of these (#3450). The
// deferral bought nothing — this module already imports `./cos.js` statically
// at the top, so the module was loaded either way — while routing two agent
@@ -972,8 +988,17 @@ export async function cleanupOrphanedAgents() {
}
// Get list of agents actively running in the CoS Runner
+ const runnerProbe = await getActiveAgentsFromRunner().then(
+ (agents) => Array.isArray(agents)
+ ? { available: true, agents }
+ : { available: false, agents: [] },
+ (err) => {
+ emitLog('debug', `Runner agent recovery probe unavailable: ${err.message}`);
+ return { available: false, agents: [] };
+ },
+ );
const runnerActiveIds = new Set();
- const runnerAgentsList = await getActiveAgentsFromRunner().catch(() => []);
+ const runnerAgentsList = runnerProbe.agents;
for (const agent of runnerAgentsList) {
runnerActiveIds.add(agent.id);
}
@@ -990,6 +1015,22 @@ export async function cleanupOrphanedAgents() {
if (agent.status === 'running') {
const inRemoteRunner = runnerActiveIds.has(agent.id);
+ // A runner-owned agent may still be alive while the runner is booting or
+ // reconnecting. Its absence from a failed probe is not evidence that the
+ // process died. Leave the durable record in_progress so the next
+ // connection can re-adopt it; requeueing here would race a second claim
+ // agent onto the same work. Old records use `useRunner`, while newer
+ // records carry the more precise executionMode.
+ const executionMode = agent.metadata?.executionMode;
+ const runnerOwned = agent.metadata?.useRunner === true
+ || agent.metadata?.useRunner === 'true'
+ || executionMode === 'runner'
+ || executionMode === 'runner-tui';
+ if (!runnerProbe.available && runnerOwned) {
+ emitLog('debug', `Skipping orphan cleanup for runner-owned agent ${agent.id} — runner is unavailable`, { agentId: agent.id });
+ continue;
+ }
+
if (!isAgentOwnedLocally(agent.id) && !inRemoteRunner) {
// Before marking as orphaned, check if the process is actually still running
if (agent.pid) {
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 58349e7f83..680c11537d 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -117,7 +117,7 @@ import { updateRun, getProject } from './creativeDirector/local.js';
import { advanceAfterPlanStepSettled } from './creativeDirector/planAdvance.js';
import { advanceAfterSceneSettled } from './creativeDirector/completionHook.js';
import { updateTask, addTask, getTaskById, getAllTasks, reviveBlockedTask } from './cos.js';
-import { pauseAgentViaRunner, terminateAgentViaRunner } from './cosRunnerClient.js';
+import { pauseAgentViaRunner, terminateAgentViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
import * as shellService from './shell.js';
import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';
import { completeAgentRun } from './agentRunTracking.js';
@@ -125,6 +125,55 @@ import { committedDuringRun } from '../lib/gitCommitProbe.js';
import { activeAgents, runnerAgents, pausedAgents } from './agentState.js';
import { hasPauseReleaseAdapter, resolvePausedTaskResume, retirePausedAgent } from '../lib/taskPauseHold.js';
+describe('cleanupOrphanedAgents — startup recovery coordination', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('shares one in-flight sweep between concurrent startup callers', async () => {
+ let releaseProbe;
+ const probe = new Promise((resolve) => { releaseProbe = resolve; });
+ getAgents.mockReturnValueOnce(probe);
+
+ const first = cleanupOrphanedAgents();
+ await Promise.resolve();
+ const second = cleanupOrphanedAgents();
+
+ expect(second).toBe(first);
+ releaseProbe([]);
+ await Promise.all([first, second]);
+ expect(getAgents).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not reap runner-owned agents while the runner probe is unavailable', async () => {
+ getAgents.mockResolvedValueOnce([{
+ id: 'agent-runner',
+ status: 'running',
+ taskId: 'task-1',
+ metadata: { useRunner: true, executionMode: 'runner' },
+ }]);
+ getActiveAgentsFromRunner.mockRejectedValueOnce(new Error('runner is booting'));
+
+ await cleanupOrphanedAgents();
+
+ expect(markAgentComplete).not.toHaveBeenCalled();
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
+ it('treats a malformed runner probe as unavailable', async () => {
+ getAgents.mockResolvedValueOnce([{
+ id: 'agent-runner',
+ status: 'running',
+ taskId: 'task-1',
+ metadata: { useRunner: true, executionMode: 'runner-tui' },
+ }]);
+ getActiveAgentsFromRunner.mockResolvedValueOnce({ agents: [] });
+
+ await cleanupOrphanedAgents();
+
+ expect(markAgentComplete).not.toHaveBeenCalled();
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+});
+
describe('settleOrphanedCreativeDirectorRun — reap a dead CD agent run (#2705)', () => {
beforeEach(() => vi.clearAllMocks());
diff --git a/server/services/cos.js b/server/services/cos.js
index 775b571146..04964fb777 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -105,6 +105,13 @@ const RECENT_COMPLETION_GRACE_MS = 60_000;
// sub-second; this is generous cover for a slow worktree/JIRA provisioning step.
const SPAWN_CLAIM_GRACE_MS = 60_000;
+// Boot can reach the auto-start path from more than one initializer while the
+// server and runner settle. A boolean check is not sufficient: both callers
+// can observe the daemon as stopped before either one sets the in-memory flag.
+// Share the entire startup promise so recovery, scheduling, and the initial
+// dequeue happen exactly once.
+let daemonStartPromise = null;
+
// Internal imports for functions used in this module
import { pruneOldAgentArchives, loadAgentIndex } from './cosAgentIndex.js';
import { archiveStaleAgents as _archiveStaleAgents } from './cosAgentArchive.js';
@@ -277,7 +284,16 @@ export async function updateConfig(updates) {
/**
* Start the CoS daemon
*/
-export async function start() {
+export function start() {
+ if (!daemonStartPromise) {
+ daemonStartPromise = runStart().finally(() => {
+ daemonStartPromise = null;
+ });
+ }
+ return daemonStartPromise;
+}
+
+async function runStart() {
if (isDaemonRunning()) {
emitLog('warn', 'CoS already running');
return { success: false, error: 'Already running' };
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index de1ac14b54..59fa2187d8 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -2475,3 +2475,11 @@ describe('pending-merge sweep — own timer, not the evaluation cadence (#3630)'
expect(hours).toBe(6);
});
});
+
+describe('CoS startup — single-flight recovery', () => {
+ it('shares the full boot promise across concurrent start callers', () => {
+ expect(COS_SRC).toMatch(/let daemonStartPromise = null/);
+ expect(COS_SRC).toMatch(/daemonStartPromise = runStart\(\)\.finally\(\(\) => \{\s*daemonStartPromise = null;/);
+ expect(COS_SRC).toMatch(/export function start\(\) \{[\s\S]*?return daemonStartPromise;\s*\}/);
+ });
+});