fix(swarm): reconcile orphan entries on swarm-state.json load (#1799) (#1809)

`.claude-flow/swarm/swarm-state.json` was retaining entries with
`status: "running"` indefinitely after the host process exited.
Each `claude-flow start --daemon` registered a new swarm; nothing ever
reconciled those entries against PID liveness or heartbeat TTL, so
crashed/exited orchestrators left permanent ghost registrations.
Reporter measured three orphan swarms accumulated in a single afternoon
on Windows v3.7.0-alpha.8.

Two changes in `swarm-tools.ts`:

  1. `swarm_init` now records `pid: process.pid` on the new
     `SwarmState`. Backward compatible — the field is optional.

  2. `loadSwarmStore()` runs `reconcileOrphanSwarms()` on every read
     and persists if anything changed. Reconciliation marks any
     `status: 'running'` entry as `terminated` (with a
     `terminationReason`) when:

       - PID-based: `pid` is set and the process is dead
         (ESRCH from `process.kill(pid, 0)`; EPERM still counts as
         alive — different user but live)
       - TTL fallback: pre-#1799 entries with no `pid` are reaped
         when `updatedAt` is older than 24h (conservative; live but
         long-idle swarms can recover by writing a heartbeat)

`swarm_status` and `swarm_health` no longer return the ghost entries
the reporter complained about. Cost is sub-millisecond (one kill(0)
syscall per running entry).

Closes #1799.
This commit is contained in:
rUv authored and GitHub committed 2026-05-06 16:52:26 -04:00
1 parent 3eb6b4d656
commit c42aa265a0
1 file changed
+79 -3
@@ -24,6 +24,16 @@ interface SwarmState {
config: Record<string, unknown>;
createdAt: string;
updatedAt: string;
/**
* #1799 — process that initialized this swarm. Used by reconciliation
* on `loadSwarmStore()` to detect orphan entries whose host process has
* already exited (common on Windows where backgrounded daemons don't
* always survive shell exit). Optional for backward compat with
* pre-#1799 stores.
*/
pid?: number;
/** Reason set when status was forced to 'terminated' by reconciliation. */
terminationReason?: string;
}
interface SwarmStore {
@@ -46,14 +56,77 @@ function ensureSwarmDir(): void {
}
}
/**
* #1799 — return true when `pid` belongs to a live process. process.kill(pid, 0)
* with signal 0 is the documented liveness probe: ESRCH ⇒ dead, EPERM ⇒ alive
* but owned by another user (still alive — don't reap), success ⇒ alive.
*/
function isPidAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (e) {
return (e as NodeJS.ErrnoException).code === 'EPERM';
}
}
/**
* #1799 — Walk swarms with status='running' and mark orphans as 'terminated':
*
* - PID-based: if `pid` is set and the process is dead, the swarm is an
* orphan (host crashed / shell exited / daemon backgrounded poorly).
* - TTL fallback: pre-#1799 entries have no `pid`; reap them when their
* `updatedAt` is older than 24h. This is conservative — long-idle but
* legitimately running swarms can recover by writing a heartbeat.
*
* Mutates `store` in place; returns the count for the caller to decide
* whether to persist.
*/
const ORPHAN_TTL_MS = 24 * 60 * 60 * 1000;
function reconcileOrphanSwarms(store: SwarmStore): number {
let reconciled = 0;
const nowIso = new Date().toISOString();
const nowMs = Date.now();
for (const swarm of Object.values(store.swarms)) {
if (swarm.status !== 'running') continue;
let orphanReason: string | null = null;
if (typeof swarm.pid === 'number') {
if (!isPidAlive(swarm.pid)) {
orphanReason = `host process ${swarm.pid} exited`;
}
} else {
const ageMs = nowMs - new Date(swarm.updatedAt).getTime();
if (Number.isFinite(ageMs) && ageMs > ORPHAN_TTL_MS) {
orphanReason = `no pid recorded and heartbeat is ${Math.round(ageMs / 3600000)}h stale`;
}
}
if (orphanReason) {
swarm.status = 'terminated';
swarm.terminationReason = orphanReason;
swarm.updatedAt = nowIso;
reconciled++;
}
}
return reconciled;
}
function loadSwarmStore(): SwarmStore {
let store: SwarmStore = { swarms: {}, version: '3.0.0' };
try {
const path = getSwarmStatePath();
if (existsSync(path)) {
return JSON.parse(readFileSync(path, 'utf-8'));
store = JSON.parse(readFileSync(path, 'utf-8'));
}
} catch { /* return default */ }
return { swarms: {}, version: '3.0.0' };
} catch { /* fall through with default */ }
// #1799 — reconcile orphans on every load and persist if anything changed.
// Cheap (process.kill(pid, 0) is sub-millisecond) and means
// `swarm_status`/`swarm_health` never see ghost "running" entries.
const reconciled = reconcileOrphanSwarms(store);
if (reconciled > 0) {
try { saveSwarmStore(store); } catch { /* best-effort */ }
}
return store;
}
function saveSwarmStore(store: SwarmStore): void {
@@ -123,6 +196,9 @@ export const swarmTools: MCPTool[] = [
},
createdAt: now,
updatedAt: now,
// #1799 — record host PID so subsequent loads can detect orphans
// when this process exits without a graceful swarm_shutdown.
pid: process.pid,
};
const store = loadSwarmStore();