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 stale task owners on terminal states

马建彤31b2e2b7f0f8
diff --git a/v3/@claude-flow/swarm/__tests__/terminal-task-stale-owners.test.ts b/v3/@claude-flow/swarm/__tests__/terminal-task-stale-owners.test.ts
new file mode 100644
index 0000000000..80e731ed28
--- /dev/null
+++ b/v3/@claude-flow/swarm/__tests__/terminal-task-stale-owners.test.ts
@@ -0,0 +1,144 @@
+/**
+ * Regression: a task retargeted from one domain to another can legitimately
+ * have two AgentState owners. #4245 keeps the previous owner busy because a
+ * retarget does not prove that worker stopped executing. Once the task is
+ * terminal, however, the non-reporting owner is a stale reservation.
+ *
+ * handleTaskComplete()/handleTaskFail()/cancelTask() only cleared the
+ * reporting (or task.assignedTo) agent. The other owner kept
+ * currentTask === taskId forever, so it stayed busy and its domain-pool slot
+ * stayed reserved even though the task was completed/failed/cancelled.
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import {
+ UnifiedSwarmCoordinator,
+ createUnifiedSwarmCoordinator,
+} from '../src/unified-coordinator.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: {},
+ };
+}
+
+async function flush(): Promise<void> {
+ await new Promise(resolve => setTimeout(resolve, 0));
+}
+
+describe('terminal task clears stale owners', () => {
+ let coordinator: UnifiedSwarmCoordinator;
+ let firstAgentId: string;
+ let secondAgentId: string;
+ let taskId: string;
+
+ beforeEach(async () => {
+ coordinator = createCoordinator();
+ await coordinator.initialize();
+
+ const first = await coordinator.spawnAgent({ type: 'coder', domain: 'core' });
+ const second = await coordinator.spawnAgent({ type: 'coder', domain: 'security' });
+ firstAgentId = first.agentId;
+ secondAgentId = second.agentId;
+
+ taskId = await coordinator.submitTask(taskData('retargeted'));
+ expect(coordinator.getTask(taskId)?.assignedTo?.id).toBe(firstAgentId);
+
+ expect(await coordinator.assignTaskToDomain(taskId, 'security')).toBe(secondAgentId);
+ expect(coordinator.getAgent(firstAgentId)).toMatchObject({
+ status: 'busy',
+ currentTask: { id: taskId },
+ });
+ expect(coordinator.getAgent(secondAgentId)).toMatchObject({
+ status: 'busy',
+ currentTask: { id: taskId },
+ });
+ });
+
+ afterEach(async () => {
+ await flush();
+ await coordinator.shutdown();
+ });
+
+ it('releases the non-reporting owner on completion', async () => {
+ (coordinator as unknown as {
+ handleTaskComplete(agentId: string, data: { taskId: string; result: unknown }): void;
+ }).handleTaskComplete(secondAgentId, { taskId, result: { ok: true } });
+ await flush();
+
+ expect(coordinator.getTask(taskId)?.status).toBe('completed');
+ expect(coordinator.getMetrics().completedTasks).toBe(1);
+ expect(coordinator.getAgent(firstAgentId)).toMatchObject({
+ status: 'idle',
+ currentTask: undefined,
+ });
+ expect(coordinator.getAgent(secondAgentId)).toMatchObject({
+ status: 'idle',
+ currentTask: undefined,
+ });
+ expect(coordinator.getDomainPool('core')!.getState().availableAgents).toContain(firstAgentId);
+ expect(coordinator.getDomainPool('security')!.getState().availableAgents).toContain(secondAgentId);
+ });
+
+ it('releases the non-assigned owner on cancellation', async () => {
+ await coordinator.cancelTask(taskId);
+ await flush();
+
+ expect(coordinator.getTask(taskId)?.status).toBe('cancelled');
+ expect(coordinator.getAgent(firstAgentId)).toMatchObject({
+ status: 'idle',
+ currentTask: undefined,
+ });
+ expect(coordinator.getAgent(secondAgentId)).toMatchObject({
+ status: 'idle',
+ currentTask: undefined,
+ });
+ });
+
+ it('releases the non-reporting owner on terminal failure', async () => {
+ const task = coordinator.getTask(taskId)!;
+ task.retries = task.maxRetries;
+
+ (coordinator as unknown as {
+ handleTaskFail(agentId: string, data: { taskId: string; error: string }): void;
+ }).handleTaskFail(secondAgentId, { taskId, error: 'worker failed' });
+ await flush();
+
+ expect(coordinator.getTask(taskId)?.status).toBe('failed');
+ expect(coordinator.getAgent(firstAgentId)).toMatchObject({
+ status: 'idle',
+ currentTask: undefined,
+ });
+ expect(coordinator.getAgent(secondAgentId)).toMatchObject({
+ status: 'idle',
+ currentTask: undefined,
+ });
+ });
+});
diff --git a/v3/@claude-flow/swarm/src/unified-coordinator.ts b/v3/@claude-flow/swarm/src/unified-coordinator.ts
index 95736d9e76..3be0f28b00 100644
--- a/v3/@claude-flow/swarm/src/unified-coordinator.ts
+++ b/v3/@claude-flow/swarm/src/unified-coordinator.ts
@@ -483,6 +483,7 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
if (task.assignedTo) {
await this.releaseDomainAgent(task.assignedTo.id);
}
+ this.releaseStaleTaskOwners(taskId, task.assignedTo?.id);
}
getTask(taskId: string): TaskDefinition | undefined {
@@ -940,6 +941,7 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
// duplicate/late completion cannot free an agent already working on a
// reassigned task.
void this.releaseDomainAgent(agentId);
+ this.releaseStaleTaskOwners(data.taskId, agentId);
}
}
@@ -977,6 +979,7 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
// which may hand the task back to the same agent, so releasing here
// would race that re-assignment.
void this.releaseDomainAgent(agentId);
+ this.releaseStaleTaskOwners(data.taskId, agentId);
}
}
}
@@ -1719,6 +1722,26 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa
}
}
+ /**
+ * A task can have more than one AgentState pointing at it after
+ * assignTaskToDomain() retargets a generic reservation: #4245 deliberately
+ * keeps the previous owner busy because a retarget does not prove that
+ * worker stopped executing. Once the task is terminal, however, no other
+ * owner can still be working on it; any remaining currentTask reference is
+ * stale and would keep that agent (and its domain-pool slot) reserved
+ * forever. Clear and release every owner except the terminal reporter.
+ */
+ private releaseStaleTaskOwners(taskId: string, exceptAgentId?: string): void {
+ for (const [agentId, agent] of this.state.agents) {
+ if (agentId === exceptAgentId) continue;
+ if (agent.currentTask?.id !== taskId) continue;
+
+ agent.status = 'idle';
+ agent.currentTask = undefined;
+ void this.releaseDomainAgent(agentId);
+ }
+ }
+
// =============================================================================
// MCP-Compatible API Methods (agentic-flow@alpha compatibility)
// =============================================================================