Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

fix(swarm): release domain-pool agents after terminal tasks (#4247)

ordinary being1e23cebe9aca
diff --git a/v3/@claude-flow/swarm/__tests__/domain-pool-agent-release.test.ts b/v3/@claude-flow/swarm/__tests__/domain-pool-agent-release.test.ts
new file mode 100644
index 0000000000..be43bfd26f
--- /dev/null
+++ b/v3/@claude-flow/swarm/__tests__/domain-pool-agent-release.test.ts
@@ -0,0 +1,235 @@
+/**
+ * Regression: domain-pool agents were never released on terminal task
+ * transitions.
+ *
+ * UnifiedSwarmCoordinator.assignTaskToDomain() draws the agent from
+ * AgentPool.acquire(), which moves that agent into the pool's `busy` set.
+ * handleTaskComplete()/handleTaskFail()/cancelTask() only reset the shared
+ * AgentState; they never called releaseAgentToDomain(). AgentPool.release()
+ * is the only operation that removes the id from `busy`, so each finished
+ * task permanently consumed one slot. Once the domain pool was full,
+ * pool.acquire() returned undefined and assignTaskToDomain() appended every
+ * further task to domainTaskQueues, where it stayed forever:
+ * releaseAgentToDomain() (the only queue-draining path) had no callers in
+ * src/.
+ *
+ * These are public-path regressions: agents are registered and tasks routed
+ * through spawnAgent()/assignTaskToDomain(), and the terminal message is the
+ * same task_complete/task_fail/cancel signal an agent sends through the
+ * message bus. The private handlers are invoked directly because the class
+ * exposes no public completion method (existing wait tests use the same
+ * pattern).
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import {
+ UnifiedSwarmCoordinator,
+ createUnifiedSwarmCoordinator,
+} from '../src/unified-coordinator.js';
+import type { TaskDefinition } from '../src/types.js';
+
+const DOMAIN = 'core' as const;
+const POOL_SIZE = 5;
+
+function createCoordinator(): UnifiedSwarmCoordinator {
+ return createUnifiedSwarmCoordinator({
+ maxAgents: 20,
+ maxTasks: 100,
+ heartbeatIntervalMs: 1000,
+ healthCheckIntervalMs: 2000,
+ taskTimeoutMs: 10000,
+ topology: { type: 'hierarchical', maxAgents: 20 },
+ consensus: {
+ algorithm: 'raft',
+ threshold: 0.66,
+ timeoutMs: 5000,
+ maxRounds: 5,
+ requireQuorum: true,
+ },
+ });
+}
+
+function taskData(name: string) {
+ return {
+ type: 'coding' as const,
+ name,
+ description: name,
+ priority: 'normal' as const,
+ dependencies: [],
+ input: {},
+ timeoutMs: 5000,
+ retries: 0,
+ maxRetries: 3,
+ metadata: {},
+ };
+}
+
+async function completeTask(
+ coordinator: UnifiedSwarmCoordinator,
+ agentId: string,
+ taskId: string
+): Promise<void> {
+ (coordinator as unknown as {
+ handleTaskComplete(agentId: string, data: { taskId: string; result: unknown }): void;
+ }).handleTaskComplete(agentId, { taskId, result: { ok: true } });
+ await flushRelease();
+}
+
+async function failTask(
+ coordinator: UnifiedSwarmCoordinator,
+ agentId: string,
+ taskId: string
+): Promise<void> {
+ (coordinator as unknown as {
+ handleTaskFail(agentId: string, data: { taskId: string; error: string }): void;
+ }).handleTaskFail(agentId, { taskId, error: 'worker failed' });
+ await flushRelease();
+}
+
+/** Let the fire-and-forget release settle before asserting pool state. */
+async function flushRelease(): Promise<void> {
+ await new Promise(resolve => setTimeout(resolve, 0));
+}
+
+describe('UnifiedSwarmCoordinator domain pool release', () => {
+ let coordinator: UnifiedSwarmCoordinator;
+
+ beforeEach(async () => {
+ coordinator = createCoordinator();
+ await coordinator.initialize();
+ });
+
+ afterEach(async () => {
+ await coordinator.shutdown();
+ });
+
+ async function assignTasks(count: number): Promise<string[]> {
+ // Submit before spawning so submitTask() cannot auto-assign the task to a
+ // generic idle agent; every assignment in this test then goes through the
+ // domain pool, which is the ownership path under test.
+ const taskIds: string[] = [];
+ for (let i = 0; i < count; i++) {
+ taskIds.push(await coordinator.submitTask(taskData(`task-${i}`)));
+ }
+
+ for (let i = 0; i < POOL_SIZE; i++) {
+ await coordinator.spawnAgent({ type: 'coder', domain: DOMAIN });
+ }
+
+ for (let i = 0; i < Math.min(count, POOL_SIZE); i++) {
+ expect(await coordinator.assignTaskToDomain(taskIds[i], DOMAIN)).toBeDefined();
+ }
+ return taskIds;
+ }
+
+ function poolStats() {
+ return coordinator.getDomainPool(DOMAIN)!.getState();
+ }
+
+ it('returns a completed agent to the domain pool', async () => {
+ const taskIds = await assignTasks(POOL_SIZE);
+ const completedAgentId = coordinator.getTask(taskIds[0])!.assignedTo!.id;
+
+ expect(poolStats().busyAgents).toContain(completedAgentId);
+
+ await completeTask(coordinator, completedAgentId, taskIds[0]);
+
+ const state = poolStats();
+ expect(state.busyAgents).not.toContain(completedAgentId);
+ expect(state.availableAgents).toContain(completedAgentId);
+ expect(state.busyAgents).toHaveLength(POOL_SIZE - 1);
+ expect(state.availableAgents).toHaveLength(1);
+ });
+
+ it('dispatches a queued domain task into the released slot', async () => {
+ const taskIds = await assignTasks(POOL_SIZE + 1);
+
+ expect(await coordinator.assignTaskToDomain(taskIds[POOL_SIZE], DOMAIN)).toBeUndefined();
+ expect(coordinator.getTask(taskIds[POOL_SIZE])?.status).toBe('queued');
+
+ const completedAgentId = coordinator.getTask(taskIds[0])!.assignedTo!.id;
+ await completeTask(coordinator, completedAgentId, taskIds[0]);
+
+ const queuedTask = coordinator.getTask(taskIds[POOL_SIZE])!;
+ expect(queuedTask.status).toBe('assigned');
+ expect(queuedTask.assignedTo?.id).toBe(completedAgentId);
+
+ const state = poolStats();
+ expect(state.busyAgents).toHaveLength(POOL_SIZE);
+ expect(state.availableAgents).toHaveLength(0);
+ expect(coordinator.getStatus().domains.find(d => d.name === DOMAIN)?.tasksQueued).toBe(0);
+ });
+
+ it('drains a one-agent domain queue without scaling its only agent away', async () => {
+ const taskIds = [
+ await coordinator.submitTask({ ...taskData('queen-0'), type: 'coordination' }),
+ await coordinator.submitTask({ ...taskData('queen-1'), type: 'coordination' }),
+ ];
+ const { agentId } = await coordinator.spawnAgent({ type: 'queen', domain: 'queen' });
+
+ expect(await coordinator.assignTaskToDomain(taskIds[0], 'queen')).toBe(agentId);
+ expect(await coordinator.assignTaskToDomain(taskIds[1], 'queen')).toBeUndefined();
+ expect(coordinator.getTask(taskIds[1])?.status).toBe('queued');
+
+ await completeTask(coordinator, agentId, taskIds[0]);
+
+ const queuedTask = coordinator.getTask(taskIds[1])!;
+ expect(queuedTask.status).toBe('assigned');
+ expect(queuedTask.assignedTo?.id).toBe(agentId);
+ expect(coordinator.getAgent(agentId)).toBeDefined();
+ expect(coordinator.getDomainPool('queen')!.getState()).toMatchObject({
+ busyAgents: [agentId],
+ availableAgents: [],
+ });
+ });
+
+ it('returns an agent whose task failed terminally to the domain pool', async () => {
+ const taskIds = await assignTasks(POOL_SIZE);
+ const failedAgentId = coordinator.getTask(taskIds[0])!.assignedTo!.id;
+
+ const task = coordinator.getTask(taskIds[0]) as TaskDefinition;
+ task.retries = task.maxRetries;
+
+ await failTask(coordinator, failedAgentId, taskIds[0]);
+
+ expect(coordinator.getTask(taskIds[0])?.status).toBe('failed');
+
+ const state = poolStats();
+ expect(state.busyAgents).not.toContain(failedAgentId);
+ expect(state.availableAgents).toContain(failedAgentId);
+ expect(state.busyAgents).toHaveLength(POOL_SIZE - 1);
+ });
+
+ it('returns an agent whose task was cancelled to the domain pool', async () => {
+ const taskIds = await assignTasks(POOL_SIZE);
+ const cancelledAgentId = coordinator.getTask(taskIds[0])!.assignedTo!.id;
+
+ await coordinator.cancelTask(taskIds[0]);
+
+ expect(coordinator.getTask(taskIds[0])?.status).toBe('cancelled');
+
+ const state = poolStats();
+ expect(state.busyAgents).not.toContain(cancelledAgentId);
+ expect(state.availableAgents).toContain(cancelledAgentId);
+ expect(state.busyAgents).toHaveLength(POOL_SIZE - 1);
+ });
+
+ it('does not resurrect a cancelled task still sitting in a domain queue', async () => {
+ const taskIds = await assignTasks(POOL_SIZE + 1);
+
+ expect(await coordinator.assignTaskToDomain(taskIds[POOL_SIZE], DOMAIN)).toBeUndefined();
+ await coordinator.cancelTask(taskIds[POOL_SIZE]);
+ expect(coordinator.getTask(taskIds[POOL_SIZE])?.status).toBe('cancelled');
+
+ const completedAgentId = coordinator.getTask(taskIds[0])!.assignedTo!.id;
+ await completeTask(coordinator, completedAgentId, taskIds[0]);
+
+ const cancelledTask = coordinator.getTask(taskIds[POOL_SIZE])!;
+ expect(cancelledTask.status).toBe('cancelled');
+ expect(cancelledTask.assignedTo).toBeUndefined();
+
+ const state = poolStats();
+ expect(state.busyAgents).toHaveLength(POOL_SIZE - 1);
+ expect(state.availableAgents).toContain(completedAgentId);
+ });
+});
diff --git a/v3/@claude-flow/swarm/src/agent-pool.ts b/v3/@claude-flow/swarm/src/agent-pool.ts
index e4a1c1130c..09f1343cba 100644
--- a/v3/@claude-flow/swarm/src/agent-pool.ts
+++ b/v3/@claude-flow/swarm/src/agent-pool.ts
@@ -142,7 +142,7 @@ export class AgentPool extends EventEmitter implements IAgentPool {
return undefined;
}
- async release(agentId: string): Promise<void> {
+ async release(agentId: string, options: { rescale?: boolean } = {}): Promise<void> {
const pooled = this.pooledAgents.get(agentId);
if (!pooled) {
return;
@@ -157,8 +157,13 @@ export class AgentPool extends EventEmitter implements IAgentPool {
this.emit('agent.released', { agentId });
- // Check if we need to scale down
- await this.checkScaling();
+ // Check if we need to scale down. Callers that are about to dispatch a
+ // queued task into this just-freed slot pass rescale:false, because a
+ // scale-down here can remove the only available agent (e.g. the queen
+ // pool's maxSize 1) before the dispatch runs.
+ if (options.rescale !== false) {
+ await this.checkScaling();
+ }
}
async add(agent: AgentState): Promise<void> {
diff --git a/v3/@claude-flow/swarm/src/types.ts b/v3/@claude-flow/swarm/src/types.ts
index 8fd7d61ae9..0bf05ca807 100644
--- a/v3/@claude-flow/swarm/src/types.ts
+++ b/v3/@claude-flow/swarm/src/types.ts
@@ -358,6 +358,7 @@ export type SwarmEventType =
| 'agent.heartbeat'
| 'agent.domain_assigned'
| 'agent.domain_pool_full'
+ | 'agent.domain_release_failed'
| 'task.created'
| 'task.assigned'
| 'task.started'
@@ -532,7 +533,7 @@ export interface IMessageBus {
export interface IAgentPool {
initialize(config: AgentPoolConfig): Promise<void>;
acquire(): Promise<AgentState | undefined>;
- release(agentId: string): Promise<void>;
+ release(agentId: string, options?: { rescale?: boolean }): Promise<void>;
add(agent: AgentState): Promise<void>;
remove(agentId: string): Promise<void>;
scale(delta: number): Promise<void>;
diff --git a/v3/@claude-flow/swarm/src/unified-coordinator.ts b/v3/@claude-flow/swarm/src/unified-coordinator.ts
index a6d78ce377..6c99e2d714 100644
--- a/v3/@claude-flow/swarm/src/unified-coordinator.ts
+++ b/v3/@claude-flow/swarm/src/unified-coordinator.ts
@@ -475,6 +475,14 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
taskId,
reason: 'cancelled',
});
+
+ // A domain-pool agent stays in AgentPool.busy until it is explicitly
+ // released. Cancel is a terminal transition, so return its slot (and
+ // dispatch the next queued task for that domain) now that the guard
+ // above has confirmed this call ended a non-terminal task.
+ if (task.assignedTo) {
+ await this.releaseDomainAgent(task.assignedTo.id);
+ }
}
getTask(taskId: string): TaskDefinition | undefined {
@@ -921,6 +929,17 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
agentId,
result: data.result,
});
+
+ // Domain pool ownership is separate from AgentState.status: acquire()
+ // leaves the agent in AgentPool.busy until release() is called, and
+ // nothing in the completion path used to call it. Without this, every
+ // completed task permanently consumed one slot; once a domain pool was
+ // full, assignTaskToDomain() queued tasks forever because
+ // releaseAgentToDomain() had no callers. The guard above already
+ // confirmed this is a transition out of a non-terminal state, so a
+ // duplicate/late completion cannot free an agent already working on a
+ // reassigned task.
+ void this.releaseDomainAgent(agentId);
}
}
@@ -952,6 +971,12 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
agentId,
error: data.error,
});
+
+ // Terminal failure ends this agent's pool ownership. Retries are left
+ // untouched: handleTaskFail() re-queues them through assignTask(),
+ // which may hand the task back to the same agent, so releasing here
+ // would race that re-assignment.
+ void this.releaseDomainAgent(agentId);
}
}
}
@@ -1622,17 +1647,66 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
const domain = this.agentDomainMap.get(agentId);
if (!domain) return;
+ // Read the queue before releasing: if a task is waiting, the just-freed
+ // slot must be handed to it before AgentPool.checkScaling() can remove
+ // the agent (a one-agent domain such as queen would otherwise scale to 0
+ // and the subsequent acquire() would create an unregistered pool agent).
+ const queue = this.domainTaskQueues.get(domain) || [];
+ const hasAssignableTask = queue.some(taskId => {
+ const task = this.state.tasks.get(taskId);
+ return task !== undefined && (task.status === 'queued' || task.status === 'created');
+ });
const pool = this.domainPools.get(domain);
if (pool) {
- await pool.release(agentId);
+ await pool.release(agentId, { rescale: !hasAssignableTask });
}
- // Check if there are queued tasks for this domain
- const queue = this.domainTaskQueues.get(domain) || [];
+ // Drain the next task that is still assignable. Cancelled or timed-out
+ // ids can remain in the queue; resurrecting one here would turn a
+ // terminal task back into 'assigned' and send it to a worker.
if (queue.length > 0) {
- const nextTaskId = queue.shift()!;
+ let nextTaskId: string | undefined;
+ while (queue.length > 0) {
+ const candidateId = queue.shift()!;
+ const candidate = this.state.tasks.get(candidateId);
+ if (candidate && (candidate.status === 'queued' || candidate.status === 'created')) {
+ nextTaskId = candidateId;
+ break;
+ }
+ }
this.domainTaskQueues.set(domain, queue);
- await this.assignTaskToDomain(nextTaskId, domain);
+ if (nextTaskId) {
+ await this.assignTaskToDomain(nextTaskId, domain);
+ }
+ }
+ }
+
+ /**
+ * Fire-and-forget release used by synchronous task handlers. A pool
+ * bookkeeping failure must not turn a completed/failed task into an
+ * unhandled rejection, but it must stay observable.
+ */
+ private async releaseDomainAgent(agentId: string): Promise<void> {
+ const domain = this.agentDomainMap.get(agentId);
+ if (!domain) return;
+
+ const pool = this.domainPools.get(domain);
+ // Only agents acquired from this pool are in its busy set. A generic
+ // assignment can share the same domain map; releasing it here would add
+ // an already-available agent back to the pool (and trigger an
+ // unnecessary scale-down decision).
+ const poolOwnsAgent = pool
+ ?.getBusyAgents()
+ .some(agent => agent.id.id === agentId);
+ if (!poolOwnsAgent) return;
+
+ try {
+ await this.releaseAgentToDomain(agentId);
+ } catch (error) {
+ this.emitEvent('agent.domain_release_failed', {
+ agentId,
+ error: error instanceof Error ? error.message : String(error),
+ });
}
}