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 failed and cancelled task workers (#4236)

Rudy Mizrahi Celekli6c7e1b1780ff
diff --git a/v3/@claude-flow/swarm/__tests__/task-orchestrator.worker-release.test.ts b/v3/@claude-flow/swarm/__tests__/task-orchestrator.worker-release.test.ts
new file mode 100644
index 0000000000..b4785789f7
--- /dev/null
+++ b/v3/@claude-flow/swarm/__tests__/task-orchestrator.worker-release.test.ts
@@ -0,0 +1,111 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import { AgentRegistry } from '../src/coordination/agent-registry.js';
+import { TaskOrchestrator } from '../src/coordination/task-orchestrator.js';
+import { EventBus } from '../src/shared/events.js';
+
+let registry: AgentRegistry;
+let orchestrator: TaskOrchestrator;
+let events: EventBus;
+beforeEach(async () => {
+ events = new EventBus();
+ registry = new AgentRegistry(events);
+ await registry.spawn('agent-6');
+ orchestrator = new TaskOrchestrator(events, registry);
+});
+
+function runningTask() {
+ const task = orchestrator.createTask({
+ type: 'implementation', title: 'Implement change', description: 'Regression fixture',
+ domain: 'core', phase: 'phase-2-core',
+ });
+ orchestrator.queueTask(task.id);
+ orchestrator.assignTask(task.id, 'agent-6');
+ orchestrator.startTask(task.id);
+ return task;
+}
+
+function expectReleased() {
+ expect(registry.getState('agent-6')).toMatchObject({ currentTask: null, status: 'idle' });
+ expect(registry.getState('agent-6')!.completedTasks).toEqual([]);
+ expect(registry.getState('agent-6')!.metrics.tasksCompleted).toBe(0);
+}
+
+describe('TaskOrchestrator worker ownership after non-success', () => {
+ it('releases the worker so the retry can be assigned to the same agent', () => {
+ const task = runningTask();
+ orchestrator.failTask(task.id, new Error('retryable'));
+ expectReleased();
+ expect(task).toMatchObject({ status: 'queued', assignedAgent: null });
+ expect(() => orchestrator.assignTask(task.id, 'agent-6')).not.toThrow();
+ orchestrator.startTask(task.id);
+ expect(registry.getState('agent-6')!.currentTask).toBe(task.id);
+ });
+
+ it('releases a terminally failed worker without counting a successful completion', () => {
+ const task = runningTask();
+ for (let attempt = 1; attempt <= task.metadata.maxRetries; attempt++) {
+ if (attempt > 1) {
+ orchestrator.assignTask(task.id, 'agent-6');
+ orchestrator.startTask(task.id);
+ }
+ orchestrator.failTask(task.id, new Error('permanent'));
+ }
+ expect(task.status).toBe('failed');
+ expectReleased();
+ expect(registry.getState('agent-6')!.metrics.tasksFailed).toBe(1);
+ expect(() => runningTask()).not.toThrow();
+ });
+
+ it('clears ownership on cancellation so an idle agent can accept another task', () => {
+ const task = runningTask();
+ orchestrator.cancelTask(task.id);
+ expect(task.status).toBe('cancelled');
+ expectReleased();
+ expect(() => runningTask()).not.toThrow();
+ });
+
+ it('keeps a rejected assignment queued without claiming a busy worker', () => {
+ const active = runningTask();
+ const queued = orchestrator.createTask({
+ type: 'implementation', title: 'Next', description: '',
+ domain: 'core', phase: 'phase-2-core',
+ });
+ orchestrator.queueTask(queued.id);
+ expect(() => orchestrator.assignTask(queued.id, 'agent-6')).toThrow('already has task');
+ expect(queued).toMatchObject({ status: 'queued', assignedAgent: null });
+ expect(registry.getState('agent-6')!.currentTask).toBe(active.id);
+ });
+
+ it('does not release another task when cancelling an old assignment again', () => {
+ const cancelled = runningTask();
+ orchestrator.cancelTask(cancelled.id);
+ const active = runningTask();
+ orchestrator.cancelTask(cancelled.id);
+ expect(registry.getState('agent-6')).toMatchObject({ currentTask: active.id, status: 'active' });
+ });
+
+ it('continues to count successful completion once', () => {
+ const task = runningTask();
+ orchestrator.completeTask(task.id, {
+ taskId: task.id, success: true, output: null, error: null, duration: 1,
+ metrics: { linesOfCode: 0, testsWritten: 0, testsPassed: 0, coveragePercent: 0, performanceImpact: 0 },
+ });
+ expect(registry.getState('agent-6')).toMatchObject({ currentTask: null, status: 'idle' });
+ expect(registry.getState('agent-6')!.completedTasks).toEqual([task.id]);
+ expect(registry.getState('agent-6')!.metrics.tasksCompleted).toBe(1);
+ expect(registry.getState('agent-6')!.metrics.tasksFailed).toBe(0);
+ });
+
+ it('exposes consistent ownership to synchronous assignment event observers', () => {
+ const observed: unknown[] = [];
+ events.subscribe('agent:status-changed', () => {
+ const state = registry.getState('agent-6')!;
+ if (state.status === 'active') {
+ const task = orchestrator.getTask(state.currentTask!)!;
+ observed.push({ status: task.status, assignedAgent: task.assignedAgent });
+ }
+ });
+ runningTask();
+ expect(observed).toEqual([{ status: 'assigned', assignedAgent: 'agent-6' }]);
+ });
+});
diff --git a/v3/@claude-flow/swarm/src/coordination/task-orchestrator.ts b/v3/@claude-flow/swarm/src/coordination/task-orchestrator.ts
index b5d0415f76..49d0075756 100644
--- a/v3/@claude-flow/swarm/src/coordination/task-orchestrator.ts
+++ b/v3/@claude-flow/swarm/src/coordination/task-orchestrator.ts
@@ -193,10 +193,23 @@ export class TaskOrchestrator implements ITaskOrchestrator {
throw new Error(`Task ${taskId} is blocked by dependencies`);
}
+ const previous = {
+ assignedAgent: task.assignedAgent,
+ status: task.status,
+ updatedAt: task.updatedAt,
+ blockedBy: task.blockedBy,
+ };
task.assignedAgent = agentId;
this.updateTaskStatus(taskId, 'assigned');
- this.agentRegistry.assignTask(agentId, taskId);
+ try {
+ // Status-change observers must see both sides of the assignment.
+ this.agentRegistry.assignTask(agentId, taskId);
+ } catch (error) {
+ // A busy or missing worker must not strand this task as assigned.
+ Object.assign(task, previous);
+ throw error;
+ }
this.eventBus.emitSync(taskAssignedEvent(taskId, agentId));
}
@@ -238,6 +251,7 @@ export class TaskOrchestrator implements ITaskOrchestrator {
failTask(taskId: TaskId, error: Error): void {
const task = this.getTaskOrThrow(taskId);
+ const assignedAgent = task.assignedAgent;
task.metadata.retryCount++;
@@ -255,6 +269,7 @@ export class TaskOrchestrator implements ITaskOrchestrator {
}
}
+ this.releaseWorker(task, assignedAgent);
this.eventBus.emitSync(taskFailedEvent(taskId, error));
}
@@ -265,10 +280,7 @@ export class TaskOrchestrator implements ITaskOrchestrator {
throw new Error(`Cannot cancel ${task.status} task ${taskId}`);
}
- if (task.assignedAgent) {
- this.agentRegistry.updateStatus(task.assignedAgent, 'idle');
- }
-
+ this.releaseWorker(task);
this.updateTaskStatus(taskId, 'cancelled');
}
@@ -476,6 +488,16 @@ export class TaskOrchestrator implements ITaskOrchestrator {
// Private Helpers
// ==========================================================================
+ private releaseWorker(task: TaskDefinition, agentId = task.assignedAgent): void {
+ if (!agentId) return;
+ const state = this.agentRegistry.getState(agentId);
+ // Only release a worker that still owns this task, never a later assignment.
+ if (state?.currentTask === task.id) {
+ state.currentTask = null;
+ this.agentRegistry.updateStatus(agentId, 'idle');
+ }
+ }
+
private getTaskOrThrow(taskId: TaskId): TaskDefinition {
const task = this.tasks.get(taskId);
if (!task) {