🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(swarm): make ephemeral agent termination idempotent (#4323)
ordinary beingce509ccb8494
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.tsindex f1470bfabb..4ef197a3f1 100644--- a/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.ts+++ b/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.ts@@ -11,7 +11,11 @@ import { delimiter, join } from 'node:path';import { tmpdir } from 'node:os';const CLI_BIN = fileURLToPath(new URL('../../bin/cli.js', import.meta.url));-const CLI_BUILT = existsSync(CLI_BIN);+// bin/cli.js is a source wrapper that imports ../dist/src/index.js. Checking+// only the wrapper made this suite run (and fail) on a source-only checkout+// where the CLI was never built; wait for the actual dist entry point.+const CLI_DIST = fileURLToPath(new URL('../../dist/src/index.js', import.meta.url));+const CLI_BUILT = existsSync(CLI_BIN) && existsSync(CLI_DIST);function isolated() {const home = mkdtempSync(join(tmpdir(), 'ruflo-mods-bin-home-'));diff --git a/v3/@claude-flow/swarm/__tests__/federation-agent-idempotency.test.ts b/v3/@claude-flow/swarm/__tests__/federation-agent-idempotency.test.tsnew file mode 100644index 0000000000..9bb15bedfe--- /dev/null+++ b/v3/@claude-flow/swarm/__tests__/federation-agent-idempotency.test.ts@@ -0,0 +1,101 @@+/**+ * Regression: FederationHub's ephemeral-agent terminal accounting was not+ * idempotent.+ *+ * terminateAgent() had no settled guard, completeAgent() counted before its+ * delayed 'terminated' transition, and unregisterSwarm()/shutdown() re-ran+ * terminateAgent() for agents that were already completing/terminated. A+ * repeated call could increment completedAgents/failedAgents and+ * totalAgentLifespanMs more than once for one agent.+ */++import { describe, it, expect, beforeEach, afterEach } from 'vitest';+// Import the TS source explicitly: src/federation-hub.js is a stale tracked+// build artifact that would otherwise shadow the implementation under test.+import { createFederationHub, type FederationHub } from '../src/federation-hub.ts';++describe('FederationHub ephemeral agent idempotency', () => {+ let hub: FederationHub;++ beforeEach(async () => {+ hub = createFederationHub({+ federationId: 'test-fed',+ defaultTTL: 60000,+ syncIntervalMs: 60000,+ autoCleanup: false,+ });+ await hub.initialize();+ hub.registerSwarm({+ swarmId: 'swarm-1',+ name: 'swarm-1',+ capabilities: ['test'],+ maxAgents: 10,+ currentAgents: 0,+ status: 'active',+ });+ });++ afterEach(async () => {+ await hub.shutdown();+ });++ async function spawn(): Promise<string> {+ const result = await hub.spawnEphemeralAgent({+ swarmId: 'swarm-1',+ type: 'worker',+ task: 'test task',+ });+ expect(result.agentId).toBeTruthy();+ return result.agentId;+ }++ it('counts a repeated terminateAgent call once', async () => {+ let completedEvents = 0;+ hub.on('event', event => {+ if (event.type === 'agent_completed') completedEvents++;+ });++ const agentId = await spawn();+ expect(await hub.terminateAgent(agentId)).toBe(true);+ expect(await hub.terminateAgent(agentId)).toBe(true);++ expect(hub.getStats().completedAgents).toBe(1);+ expect(hub.getStats().failedAgents).toBe(0);+ expect(completedEvents).toBe(1);+ });++ it('does not double-count completeAgent followed by terminateAgent', async () => {+ const agentId = await spawn();+ expect(hub.completeAgent(agentId, { ok: true })).toBe(true);+ expect(await hub.terminateAgent(agentId)).toBe(true);++ expect(hub.getStats().completedAgents).toBe(1);+ expect(hub.getStats().failedAgents).toBe(0);+ });++ it('does not double-count a repeated completeAgent call', async () => {+ const agentId = await spawn();+ expect(hub.completeAgent(agentId)).toBe(true);+ expect(hub.completeAgent(agentId)).toBe(true);++ expect(hub.getStats().completedAgents).toBe(1);+ });++ it('does not count unregisterSwarm termination again', async () => {+ const agentId = await spawn();+ hub.completeAgent(agentId);+ expect(hub.unregisterSwarm('swarm-1')).toBe(true);++ expect(hub.getStats().completedAgents).toBe(1);+ expect(hub.getStats().failedAgents).toBe(0);+ });++ it('counts a repeated failed termination once', async () => {+ const agentId = await spawn();+ await hub.terminateAgent(agentId, new Error('failed'));+ await hub.terminateAgent(agentId, new Error('failed again'));++ expect(hub.getStats().failedAgents).toBe(1);+ expect(hub.getStats().completedAgents).toBe(0);+ });+});diff --git a/v3/@claude-flow/swarm/__tests__/message-bus.event-driven.test.ts b/v3/@claude-flow/swarm/__tests__/message-bus.event-driven.test.tsindex 0cfeb8848c..27bb108d0a 100644--- a/v3/@claude-flow/swarm/__tests__/message-bus.event-driven.test.ts+++ b/v3/@claude-flow/swarm/__tests__/message-bus.event-driven.test.ts@@ -16,6 +16,17 @@ import { MessageBus, createMessageBus } from '../src/message-bus.js';describe('MessageBus - event-driven dispatch (dream-cycle 2026-09-30)', () => {let bus: MessageBus;+ /** Wait for a condition without assuming a fixed scheduler delay. */+ async function waitFor(predicate: () => boolean, timeoutMs = 2000): Promise<void> {+ const started = Date.now();+ while (!predicate()) {+ if (Date.now() - started > timeoutMs) {+ throw new Error(`condition not met within ${timeoutMs}ms`);+ }+ await new Promise(resolve => setTimeout(resolve, 5));+ }+ }+afterEach(async () => {await bus.shutdown();});@@ -211,8 +222,10 @@ describe('MessageBus - event-driven dispatch (dream-cycle 2026-09-30)', () => {ttlMs: 60000,});- // Let the first attempt fail (retry now pending), then shut down.- await new Promise((resolve) => setTimeout(resolve, 2));+ // Let the first attempt fail (retry now pending), then shut down. Wait for+ // the actual invocation instead of assuming a 2ms scheduler delay: under a+ // loaded full-suite worker the first setImmediate can arrive later.+ await waitFor(() => invocations === 1);expect(invocations).toBe(1);await bus.shutdown();await new Promise((resolve) => setTimeout(resolve, 100));diff --git a/v3/@claude-flow/swarm/src/federation-hub.ts b/v3/@claude-flow/swarm/src/federation-hub.tsindex 4d17454109..c8340345cb 100644--- a/v3/@claude-flow/swarm/src/federation-hub.ts+++ b/v3/@claude-flow/swarm/src/federation-hub.ts@@ -516,6 +516,12 @@ export class FederationHub extends EventEmitter {completeAgent(agentId: EphemeralAgentId, result?: unknown): boolean {const agent = this.ephemeralAgents.get(agentId);if (!agent) return false;+ // Completion is a terminal accounting event. A repeated call (e.g. a+ // retried MCP request or unregisterSwarm racing the completion timeout)+ // must not count the same agent twice.+ if (agent.status === 'completing' || agent.status === 'terminated') {+ return true;+ }const oldStatus = agent.status;agent.status = 'completing';@@ -546,11 +552,23 @@ export class FederationHub extends EventEmitter {async terminateAgent(agentId: EphemeralAgentId, error?: Error): Promise<boolean> {const agent = this.ephemeralAgents.get(agentId);if (!agent) return false;+ // Repeated termination (shutdown, unregisterSwarm, TTL cleanup, or a+ // duplicate caller) must be idempotent: statistics and lifecycle events+ // describe the agent once, not once per call.+ if (agent.status === 'terminated') return true;const oldStatus = agent.status;+ const completionAlreadyCounted = agent.status === 'completing' || agent.completedAt !== undefined;+agent.status = 'terminated';this.updateAgentStatusIndex(agent, oldStatus);- agent.completedAt = new Date();+ agent.completedAt = agent.completedAt ?? new Date();++ if (completionAlreadyCounted) {+ // completeAgent() already counted the successful completion and may+ // still have its own delayed agent_completed notification pending.+ return true;+ }if (error) {agent.error = error;