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): stop domain pools from creating unregistered agents (#4246)

ordinary beingc357c3d85ba6
diff --git a/v3/@claude-flow/swarm/__tests__/domain-pool-no-autoscale.test.ts b/v3/@claude-flow/swarm/__tests__/domain-pool-no-autoscale.test.ts
new file mode 100644
index 0000000000..12f673fa03
--- /dev/null
+++ b/v3/@claude-flow/swarm/__tests__/domain-pool-no-autoscale.test.ts
@@ -0,0 +1,172 @@
+/**
+ * Regression: domain pools must not synthesize agents that the coordinator
+ * does not know about.
+ *
+ * AgentPool.acquire() used to scale up whenever it had no available agent.
+ * For a domain pool that produced a `*-domain-pool_agent_N` that was absent
+ * from UnifiedSwarmCoordinator.state.agents, topology, message-bus
+ * subscriptions and the consensus engine. The coordinator then assigned a
+ * task to that id and sent it a message, but handleAgentMessage() drops
+ * reports from unknown agents, so the task could only wait for its timeout.
+ * The same scale-up also ran on a normal acquire when utilization crossed
+ * scaleUpThreshold, inflating the fixed 15-agent roster with invisible agents.
+ *
+ * Domain pools are explicit rosters: membership is created by spawnAgent()/
+ * registerAgentWithDomain() and removed by the coordinator. They now set
+ * autoScale:false and healthChecks:false, so the pool never creates, removes
+ * or replaces members on its own.
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import {
+ UnifiedSwarmCoordinator,
+ createUnifiedSwarmCoordinator,
+} from '../src/unified-coordinator.js';
+import { AgentPool, createAgentPool } from '../src/agent-pool.js';
+
+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: {},
+ };
+}
+
+describe('domain pools do not auto-create or auto-remove agents', () => {
+ let coordinator: UnifiedSwarmCoordinator;
+
+ beforeEach(async () => {
+ coordinator = createCoordinator();
+ await coordinator.initialize();
+ });
+
+ afterEach(async () => {
+ await coordinator.shutdown();
+ });
+
+ it('queues a task instead of acquiring a pool-only agent from an empty domain', async () => {
+ const taskId = await coordinator.submitTask(taskData('empty-pool'));
+
+ expect(await coordinator.assignTaskToDomain(taskId, 'core')).toBeUndefined();
+
+ expect(coordinator.getTask(taskId)?.status).toBe('queued');
+ expect(coordinator.getDomainPool('core')!.getPoolStats().total).toBe(0);
+ expect(coordinator.getStatus().domains.find(d => d.name === 'core')?.agentCount).toBe(0);
+ });
+
+ it('does not scale a one-agent domain up to a second, unregistered agent', async () => {
+ const { agentId } = await coordinator.spawnAgent({ type: 'coder', domain: 'core' });
+ const first = await coordinator.submitTask(taskData('first'));
+ const second = await coordinator.submitTask(taskData('second'));
+
+ expect(await coordinator.assignTaskToDomain(first, 'core')).toBe(agentId);
+ expect(await coordinator.assignTaskToDomain(second, 'core')).toBeUndefined();
+
+ expect(coordinator.getTask(second)?.status).toBe('queued');
+ expect(coordinator.getDomainPool('core')!.getPoolStats()).toMatchObject({
+ total: 1,
+ busy: 1,
+ available: 0,
+ });
+ expect(coordinator.getAgentsByDomain('core')).toHaveLength(1);
+ });
+
+ it('still registers explicitly spawned agents in the domain pool', async () => {
+ const hierarchy = await coordinator.spawnFullHierarchy();
+
+ expect(hierarchy.size).toBe(15);
+ expect(coordinator.getDomainPool('queen')!.getPoolStats().total).toBe(1);
+ expect(coordinator.getDomainPool('security')!.getPoolStats().total).toBe(3);
+ expect(coordinator.getDomainPool('core')!.getPoolStats().total).toBe(5);
+ expect(coordinator.getDomainPool('integration')!.getPoolStats().total).toBe(3);
+ expect(coordinator.getDomainPool('support')!.getPoolStats().total).toBe(3);
+ });
+
+ it('keeps auto-scaling for type-based pools (default behavior)', async () => {
+ const pool: AgentPool = createAgentPool({
+ name: 'worker-test-pool',
+ type: 'worker',
+ minSize: 0,
+ maxSize: 2,
+ scaleUpThreshold: 0.8,
+ scaleDownThreshold: 0.2,
+ cooldownMs: 30000,
+ healthCheckIntervalMs: 2000,
+ healthChecks: false,
+ });
+ await pool.initialize();
+
+ const agent = await pool.acquire();
+ expect(agent).toBeDefined();
+ expect(pool.getPoolStats().total).toBe(1);
+
+ await pool.shutdown();
+ });
+
+ it('does not seed minSize agents when the pool does not own membership', async () => {
+ const pool: AgentPool = createAgentPool({
+ name: 'external-roster-pool',
+ type: 'worker',
+ minSize: 1,
+ maxSize: 2,
+ scaleUpThreshold: 0.8,
+ scaleDownThreshold: 0.2,
+ cooldownMs: 30000,
+ healthCheckIntervalMs: 2000,
+ autoScale: false,
+ healthChecks: false,
+ });
+ await pool.initialize();
+
+ expect(pool.getPoolStats().total).toBe(0);
+ expect(await pool.acquire()).toBeUndefined();
+
+ await pool.shutdown();
+ });
+
+ it('ignores explicit scale() calls when the pool does not own membership', async () => {
+ const pool: AgentPool = createAgentPool({
+ name: 'external-roster-scale-pool',
+ type: 'worker',
+ minSize: 0,
+ maxSize: 2,
+ scaleUpThreshold: 0.8,
+ scaleDownThreshold: 0.2,
+ cooldownMs: 30000,
+ healthCheckIntervalMs: 2000,
+ autoScale: false,
+ healthChecks: false,
+ });
+ await pool.initialize();
+
+ await pool.scale(1);
+ expect(pool.getPoolStats().total).toBe(0);
+
+ await pool.shutdown();
+ });
+});
diff --git a/v3/@claude-flow/swarm/src/agent-pool.ts b/v3/@claude-flow/swarm/src/agent-pool.ts
index bdf2e3eeb1..e4a1c1130c 100644
--- a/v3/@claude-flow/swarm/src/agent-pool.ts
+++ b/v3/@claude-flow/swarm/src/agent-pool.ts
@@ -44,6 +44,8 @@ export class AgentPool extends EventEmitter implements IAgentPool {
scaleDownThreshold: config.scaleDownThreshold ?? 0.2,
cooldownMs: config.cooldownMs ?? 30000,
healthCheckIntervalMs: config.healthCheckIntervalMs ?? SWARM_CONSTANTS.DEFAULT_HEALTH_CHECK_INTERVAL_MS,
+ autoScale: config.autoScale ?? true,
+ healthChecks: config.healthChecks ?? true,
};
}
@@ -52,15 +54,22 @@ export class AgentPool extends EventEmitter implements IAgentPool {
this.config = { ...this.config, ...config };
}
- // Start with minimum pool size - create agents in parallel
+ // Start with minimum pool size - create agents in parallel. Pools whose
+ // membership is externally owned (domain pools) must start empty even if a
+ // caller supplied minSize; explicit add()/spawnAgent() is the only way in.
+ const initialSize = this.config.autoScale ? this.config.minSize : 0;
const createPromises = Array.from(
- { length: this.config.minSize },
+ { length: initialSize },
() => this.createPooledAgent()
);
await Promise.all(createPromises);
- // Start health checks
- this.startHealthChecks();
+ // Start health checks only when the pool owns liveness. Domain pools
+ // explicitly disable this; UnifiedSwarmCoordinator.checkHeartbeats()
+ // remains the authority for their agents.
+ if (this.config.healthChecks) {
+ this.startHealthChecks();
+ }
this.emit('initialized', {
poolName: this.config.name,
@@ -108,8 +117,11 @@ export class AgentPool extends EventEmitter implements IAgentPool {
}
}
- // No available agents, try to scale up
- if (this.pooledAgents.size < this.config.maxSize) {
+ // No available agents, try to scale up. Pools that do not own their
+ // membership (domain pools) must never synthesize an agent here: it would
+ // not exist in the coordinator's state/topology/bus and could never report
+ // task completion.
+ if (this.config.autoScale && this.pooledAgents.size < this.config.maxSize) {
const agent = await this.createPooledAgent();
if (agent) {
const pooled = this.pooledAgents.get(agent.id.id)!;
@@ -181,6 +193,12 @@ export class AgentPool extends EventEmitter implements IAgentPool {
}
async scale(delta: number): Promise<void> {
+ // 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) {
+ return;
+ }
+
const now = new Date();
// Check cooldown
@@ -342,6 +360,13 @@ export class AgentPool extends EventEmitter implements IAgentPool {
}
private async checkScaling(): Promise<void> {
+ // Explicit-roster pools (domain pools) never resize themselves. Scaling
+ // them up creates agents the coordinator does not know about; scaling them
+ // down removes agents the coordinator still lists.
+ if (!this.config.autoScale) {
+ return;
+ }
+
const utilization = this.getUtilization();
if (utilization >= this.config.scaleUpThreshold &&
diff --git a/v3/@claude-flow/swarm/src/types.ts b/v3/@claude-flow/swarm/src/types.ts
index b8952ea457..8fd7d61ae9 100644
--- a/v3/@claude-flow/swarm/src/types.ts
+++ b/v3/@claude-flow/swarm/src/types.ts
@@ -394,6 +394,19 @@ export interface AgentPoolConfig {
scaleDownThreshold: number;
cooldownMs: number;
healthCheckIntervalMs: number;
+ /**
+ * Allow acquire()/checkScaling() to create or remove agents automatically.
+ * Domain pools must keep this false: their membership is owned explicitly by
+ * UnifiedSwarmCoordinator (spawnAgent/registerAgentWithDomain), so a
+ * pool-created agent would be absent from state.agents, topology, the message
+ * bus and the consensus engine, and could never report task completion.
+ */
+ autoScale?: boolean;
+ /**
+ * Run the pool's own heartbeat-based replacement loop. Domain pools set this
+ * false because the coordinator owns domain-agent liveness/recovery.
+ */
+ healthChecks?: boolean;
}
export interface AgentPoolState {
diff --git a/v3/@claude-flow/swarm/src/unified-coordinator.ts b/v3/@claude-flow/swarm/src/unified-coordinator.ts
index 9e6bdb7c3d..a6d78ce377 100644
--- a/v3/@claude-flow/swarm/src/unified-coordinator.ts
+++ b/v3/@claude-flow/swarm/src/unified-coordinator.ts
@@ -672,6 +672,12 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
scaleDownThreshold: 0.2,
cooldownMs: 30000,
healthCheckIntervalMs: this.config.healthCheckIntervalMs,
+ // Domain membership is an explicit 15-agent roster. Letting the pool
+ // create/remove agents would desynchronize it from state.agents,
+ // topology, message subscriptions and consensus (and produce agents
+ // whose task_complete reports are silently ignored).
+ autoScale: false,
+ healthChecks: false,
});
await pool.initialize();