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): honor shared worker reservations in agent pools (#4245)

Rudy Mizrahi Celekli1e718a9874db
diff --git a/v3/@claude-flow/swarm/__tests__/agent-pool.shared-reservations.test.ts b/v3/@claude-flow/swarm/__tests__/agent-pool.shared-reservations.test.ts
new file mode 100644
index 0000000000..c9500611a3
--- /dev/null
+++ b/v3/@claude-flow/swarm/__tests__/agent-pool.shared-reservations.test.ts
@@ -0,0 +1,148 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createAgentPool, type AgentPool } from '../src/agent-pool.js';
+import { createUnifiedSwarmCoordinator, type UnifiedSwarmCoordinator } from '../src/unified-coordinator.js';
+import type { MessageBus } from '../src/message-bus.js';
+import type { AgentPoolConfig } from '../src/types.js';
+
+let pools: AgentPool[];
+let coordinator: UnifiedSwarmCoordinator | undefined;
+beforeEach(() => { pools = []; coordinator = undefined; });
+afterEach(async () => {
+ await coordinator?.shutdown();
+ for (const pool of pools) await pool.shutdown();
+});
+async function pool(config: Partial<AgentPoolConfig> = {}) {
+ const result = createAgentPool({ minSize: 1, maxSize: 1, ...config });
+ pools.push(result);
+ await result.initialize();
+ return result;
+}
+const ownedTask = { id: 'active-task', swarmId: 'fixture', sequence: 1, priority: 'normal' as const };
+const task = () => ({
+ type: 'coding' as const, name: 'Shared reservation', description: '',
+ priority: 'normal' as const, dependencies: [], input: {}, timeoutMs: 5000,
+ retries: 0, maxRetries: 0, metadata: {},
+});
+
+describe('AgentPool shared reservation state', () => {
+ it('does not lease a worker marked busy by another coordinator path', async () => {
+ const target = await pool();
+ const [agent] = target.getAllAgents();
+ agent.status = 'busy';
+ expect(target.getAvailableCount()).toBe(0);
+ expect(target.getBusyCount()).toBe(1);
+ expect(target.getUtilization()).toBe(1);
+ expect(target.getAvailableAgents()).toEqual([]);
+ expect(target.getBusyAgents()).toEqual([agent]);
+ expect(target.getState()).toMatchObject({ availableAgents: [], busyAgents: [agent.id.id] });
+ expect(await target.acquire()).toBeUndefined();
+ });
+
+ it('treats an idle worker with an outstanding task as reserved', async () => {
+ const target = await pool();
+ const [agent] = target.getAllAgents();
+ agent.currentTask = ownedTask;
+ expect(await target.acquire()).toBeUndefined();
+ expect(agent.currentTask).toBe(ownedTask);
+ expect(target.getPoolStats()).toMatchObject({ available: 0, busy: 1 });
+ });
+
+ it('respects an existing reservation when adding a shared worker', async () => {
+ const donor = await pool();
+ const agent = (await donor.acquire())!;
+ agent.currentTask = ownedTask;
+ const target = await pool({ minSize: 0 });
+ await target.add(agent);
+ expect(target.getPoolStats()).toMatchObject({ available: 0, busy: 1 });
+ expect(await target.acquire()).toBeUndefined();
+ });
+
+ it('does not scale down a shared worker that acquired a task elsewhere', async () => {
+ const donor = await pool();
+ const [agent] = donor.getAllAgents();
+ const target = await pool({ minSize: 0 });
+ await target.add(agent);
+ agent.currentTask = ownedTask;
+ await target.scale(-1);
+ expect(target.getTotalCount()).toBe(1);
+ expect(agent.currentTask).toBe(ownedTask);
+ });
+
+ it.each(['error', 'terminated', 'initializing'] as const)('does not lease a worker whose status became %s', async status => {
+ const target = await pool();
+ const [agent] = target.getAllAgents();
+ agent.status = status;
+ expect(target.getAvailableCount()).toBe(0);
+ expect(target.getBusyCount()).toBe(0);
+ expect(await target.acquire()).toBeUndefined();
+ });
+
+ it('retains existing available-worker order and makes a released worker reusable', async () => {
+ const target = await pool({ minSize: 2, maxSize: 2 });
+ const [first, second] = target.getAllAgents();
+ expect((await target.acquire())!.id.id).toBe(first.id.id);
+ first.currentTask = ownedTask;
+ await target.release(first.id.id);
+ expect(first.currentTask).toBeUndefined();
+ expect((await target.acquire())!.id.id).toBe(second.id.id);
+ expect(target.getAvailableAgents()).toEqual([first]);
+ });
+
+ it('routes domain work to the actual idle canonical worker and observes global completion release', async () => {
+ coordinator = createUnifiedSwarmCoordinator();
+ await coordinator.initialize();
+ const pending = await coordinator.submitTask(task());
+ const first = await coordinator.spawnAgent({ type: 'coder' });
+ const second = await coordinator.spawnAgent({ type: 'coder' });
+ const running = await coordinator.submitTask(task());
+ const chosen = await coordinator.assignTaskToDomain(pending, first.domain);
+ expect(chosen).toBe(second.agentId);
+ expect(coordinator.getTask(running)!.assignedTo!.id).toBe(first.agentId);
+ expect(coordinator.getAgent(second.agentId)!.currentTask!.id).toBe(pending);
+ const transport = (coordinator as unknown as { messageBus: MessageBus }).messageBus;
+ await transport.send({
+ type: 'task_complete', from: first.agentId, to: first.agentId,
+ priority: 'normal', requiresAck: false, ttlMs: 5000,
+ payload: { taskId: running, result: 'done' },
+ });
+ for (let i = 0; i < 4; i++) await new Promise<void>(setImmediate);
+ expect(coordinator.getTask(running)!.status).toBe('completed');
+ expect(coordinator.getDomainPool(first.domain)!.getAvailableAgents().map(agent => agent.id.id))
+ .toContain(first.agentId);
+ });
+
+ it('does not treat a foreign-domain owner as a reservation in the requested domain', async () => {
+ coordinator = createUnifiedSwarmCoordinator();
+ await coordinator.initialize();
+ const first = await coordinator.spawnAgent({ type: 'coder' });
+ const second = await coordinator.spawnAgent({ type: 'coder', domain: 'security' });
+ const id = await coordinator.submitTask(task());
+ expect(coordinator.getTask(id)!.assignedTo!.id).toBe(first.agentId);
+ expect(await coordinator.assignTaskToDomain(id, 'security')).toBe(second.agentId);
+ // Retargeting does not prove that the previous worker stopped execution.
+ expect(coordinator.getAgent(first.agentId)).toMatchObject({ status: 'busy', currentTask: { id } });
+ expect(coordinator.getAgent(second.agentId)).toMatchObject({ status: 'busy', currentTask: { id } });
+ expect(coordinator.getDomainPool(first.domain)!.getAvailableAgents().map(agent => agent.id.id))
+ .not.toContain(first.agentId);
+ expect(coordinator.getMetrics().completedTasks).toBe(0);
+ expect(coordinator.getAgent(first.agentId)!.metrics.tasksCompleted).toBe(0);
+ });
+
+ it('does not globally reassign a worker whose status report says idle while it still owns a task', async () => {
+ coordinator = createUnifiedSwarmCoordinator();
+ await coordinator.initialize();
+ const { agentId } = await coordinator.spawnAgent({ type: 'coder' });
+ const first = await coordinator.submitTask(task());
+ const transport = (coordinator as unknown as { messageBus: MessageBus }).messageBus;
+ await transport.send({
+ type: 'status_update', from: agentId, to: agentId, priority: 'normal',
+ requiresAck: false, ttlMs: 5000, payload: { status: 'idle' },
+ });
+ for (let i = 0; i < 4; i++) await new Promise<void>(setImmediate);
+ expect(coordinator.getAgent(agentId)).toMatchObject({ status: 'idle', currentTask: { id: first } });
+ expect(coordinator.getAvailableAgents()).toEqual([]);
+ const second = await coordinator.submitTask(task());
+ expect(coordinator.getTask(second)!.status).toBe('queued');
+ expect(coordinator.getAgent(agentId)!.currentTask!.id).toBe(first);
+ });
+});
diff --git a/v3/@claude-flow/swarm/src/agent-pool.ts b/v3/@claude-flow/swarm/src/agent-pool.ts
index 09f1343cba..f16826334b 100644
--- a/v3/@claude-flow/swarm/src/agent-pool.ts
+++ b/v3/@claude-flow/swarm/src/agent-pool.ts
@@ -96,6 +96,7 @@ export class AgentPool extends EventEmitter implements IAgentPool {
}
async acquire(): Promise<AgentState | undefined> {
+ this.reconcileReservations();
// Try to get an available agent
const availableId = this.available.values().next().value as string | undefined;
@@ -178,7 +179,7 @@ export class AgentPool extends EventEmitter implements IAgentPool {
};
this.pooledAgents.set(agent.id.id, pooled);
- this.available.add(agent.id.id);
+ this.reconcileReservations();
this.emit('agent.added', { agentId: agent.id.id });
}
@@ -198,6 +199,8 @@ export class AgentPool extends EventEmitter implements IAgentPool {
}
async scale(delta: number): Promise<void> {
+ this.reconcileReservations();
+
// Explicit-roster pools cannot grow/shrink themselves; a caller that wants
// a domain member must add a registered agent through the coordinator.
if (!this.config.autoScale) {
@@ -253,6 +256,7 @@ export class AgentPool extends EventEmitter implements IAgentPool {
}
getState(): AgentPoolState {
+ this.reconcileReservations();
return {
id: `pool_${this.config.name}`,
config: { ...this.config },
@@ -269,10 +273,12 @@ export class AgentPool extends EventEmitter implements IAgentPool {
}
getAvailableCount(): number {
+ this.reconcileReservations();
return this.available.size;
}
getBusyCount(): number {
+ this.reconcileReservations();
return this.busy.size;
}
@@ -281,12 +287,28 @@ export class AgentPool extends EventEmitter implements IAgentPool {
}
getUtilization(): number {
+ this.reconcileReservations();
if (this.pooledAgents.size === 0) return 0;
return this.busy.size / this.pooledAgents.size;
}
// ===== PRIVATE METHODS =====
+ private reconcileReservations(): void {
+ // Coordinator paths share these AgentState objects. Their current ownership
+ // must win over cached pool membership, including before scale-down.
+ for (const [id, { agent }] of this.pooledAgents) {
+ if (agent.status === 'idle' && !agent.currentTask) {
+ this.busy.delete(id);
+ this.available.add(id);
+ } else {
+ this.available.delete(id);
+ if (agent.status === 'busy' || agent.currentTask) this.busy.add(id);
+ else this.busy.delete(id);
+ }
+ }
+ }
+
private async createPooledAgent(): Promise<AgentState | undefined> {
if (this.pooledAgents.size >= this.config.maxSize) {
return undefined;
@@ -455,12 +477,14 @@ export class AgentPool extends EventEmitter implements IAgentPool {
}
getAvailableAgents(): AgentState[] {
+ this.reconcileReservations();
return Array.from(this.available)
.map(id => this.pooledAgents.get(id)?.agent)
.filter((a): a is AgentState => a !== undefined);
}
getBusyAgents(): AgentState[] {
+ this.reconcileReservations();
return Array.from(this.busy)
.map(id => this.pooledAgents.get(id)?.agent)
.filter((a): a is AgentState => a !== undefined);
@@ -490,6 +514,7 @@ export class AgentPool extends EventEmitter implements IAgentPool {
avgHealth: number;
avgUsageCount: number;
} {
+ this.reconcileReservations();
const agents = Array.from(this.pooledAgents.values());
const avgHealth = agents.length > 0
? agents.reduce((sum, p) => sum + p.agent.health, 0) / agents.length
@@ -502,7 +527,7 @@ export class AgentPool extends EventEmitter implements IAgentPool {
total: this.pooledAgents.size,
available: this.available.size,
busy: this.busy.size,
- utilization: this.getUtilization(),
+ utilization: agents.length > 0 ? this.busy.size / agents.length : 0,
avgHealth,
avgUsageCount,
};
diff --git a/v3/@claude-flow/swarm/src/unified-coordinator.ts b/v3/@claude-flow/swarm/src/unified-coordinator.ts
index 6c99e2d714..95736d9e76 100644
--- a/v3/@claude-flow/swarm/src/unified-coordinator.ts
+++ b/v3/@claude-flow/swarm/src/unified-coordinator.ts
@@ -392,7 +392,7 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
}
getAvailableAgents(): AgentState[] {
- return this.getAllAgents().filter(a => a.status === 'idle');
+ return this.getAllAgents().filter(a => a.status === 'idle' && !a.currentTask);
}
// ===== TASK MANAGEMENT =====
@@ -1162,8 +1162,12 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
throw new Error(`Domain pool ${domain} not found`);
}
- // Try to acquire an agent from the domain pool
- const agent = await pool.acquire();
+ // A global assignment can already own this task in the requested domain.
+ // Transfer that reservation rather than trying to acquire the busy owner twice.
+ const owner = task.assignedTo && this.state.agents.get(task.assignedTo.id);
+ const sameReservation = owner?.status === 'busy' && owner.currentTask?.id === taskId &&
+ this.agentDomainMap.get(owner.id.id) === domain;
+ const agent = sameReservation ? owner : await pool.acquire();
if (!agent) {
// Add to domain queue if no agents available
const queue = this.domainTaskQueues.get(domain) || [];
@@ -1185,6 +1189,8 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
task.status = 'assigned';
task.assignedTo = agent.id;
task.startedAt = new Date();
+ agent.status = 'busy';
+ agent.currentTask = task.id;
// Track assignment
const assignment: TaskAssignment = {
@@ -1691,13 +1697,16 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
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);
+ // Membership, not current busy/available bucket: by the time this runs,
+ // the caller (handleTaskComplete/handleTaskFail/cancelTask) has already
+ // reset the shared AgentState to idle, and AgentPool's busy/available
+ // sets self-heal from that live status on every read (reconcileReservations).
+ // Checking getBusyAgents() here would therefore always read this agent as
+ // already-available and skip the release entirely. A generic assignment
+ // can share the same domain map without ever being a pool member; only
+ // skip release for those (releasing them would add an already-available
+ // agent back to the pool and trigger an unnecessary scale-down decision).
+ const poolOwnsAgent = pool?.getAgent(agentId) !== undefined;
if (!poolOwnsAgent) return;
try {