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(hive-mind): dispatch submitted tasks to workers and record results (#3524)

rUvfa61df2ef2aa
diff --git a/v3/@claude-flow/cli/__tests__/hive-mind-work.test.ts b/v3/@claude-flow/cli/__tests__/hive-mind-work.test.ts
new file mode 100644
index 0000000000..a307583258
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/hive-mind-work.test.ts
@@ -0,0 +1,130 @@
+/**
+ * Hive-mind task dispatch, end to end over the real task + hive-mind tools.
+ *
+ * Before `hive-mind work`, a submitted task stayed `pending` and its worker
+ * `idle` forever: nothing claimed the row, and task_assign/task_complete only
+ * synced `.claude-flow/agents/store.json` while hive workers live in
+ * `.claude-flow/agents.json`. Separately, `spawn --claude` passed
+ * `~/.claude.json` as `--mcp-config`, which Claude rejects ("mcpServers:
+ * Invalid input") wherever that file has no top-level `mcpServers`.
+ */
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const state = vi.hoisted(() => ({ cwd: '' }));
+vi.mock('../src/mcp-tools/types.js', () => ({ getProjectCwd: () => state.cwd }));
+vi.mock('../src/mcp-client.js', async () => {
+ const { taskTools } = await import('../src/mcp-tools/task-tools.js');
+ const { hiveMindTools } = await import('../src/mcp-tools/hive-mind-tools.js');
+ const tools = [...taskTools, ...hiveMindTools];
+ return {
+ MCPClientError: class extends Error {},
+ callMCPTool: async (name: string, input: any) => tools.find((t) => t.name === name)!.handler(input ?? {}),
+ };
+});
+
+import { callMCPTool } from '../src/mcp-client.js';
+import { resolveWorkerMcpConfig, workOnce, type TaskRunner } from '../src/commands/hive-mind-worker.js';
+
+const call = (name: string, input: any = {}): Promise<any> => callMCPTool(name, input) as Promise<any>;
+const tmp = (p: string) => (state.cwd = mkdtempSync(join(tmpdir(), p)));
+afterEach(() => {
+ if (state.cwd) rmSync(state.cwd, { recursive: true, force: true });
+});
+
+async function hiveWithOneTask() {
+ await call('hive-mind_init', {});
+ const spawned = await call('hive-mind_spawn', { count: 1 });
+ const task = await call('task_create', { type: 'hive-mind', description: 'List the files', tags: ['hive-mind', 'timeout:42s'] });
+ return { workerId: spawned.workers[0].agentId as string, taskId: task.taskId as string };
+}
+
+const worker = async (id: string) => (await call('hive-mind_status')).workers.find((w: any) => w.id === id);
+
+describe('hive-mind work', () => {
+ it('assigns a pending task to an idle worker, runs it, and records the result', async () => {
+ tmp('ruflo-hive-work-');
+ const { workerId, taskId } = await hiveWithOneTask();
+ let seen: { prompt: string; timeoutMs: number; busy?: string } | undefined;
+ const runner: TaskRunner = async (prompt, opts) => {
+ // Observed mid-run: the worker is busy on exactly this task.
+ seen = { prompt, timeoutMs: opts.timeoutMs, busy: (await worker(workerId)).status };
+ return { ok: true, output: 'a.txt b.txt', exitCode: 0, durationMs: 5, sessionId: 's-1' };
+ };
+
+ const r = await workOnce({ cwd: state.cwd, mcpConfig: '/x.json', runner });
+
+ expect(r).toMatchObject({ dispatched: true, taskId, workerId, status: 'completed' });
+ expect(seen).toMatchObject({ busy: 'busy', timeoutMs: 42_000 });
+ expect(seen!.prompt).toContain('List the files');
+ const done = await call('task_status', { taskId });
+ expect(done.status).toBe('completed');
+ expect(done.assignedTo).toEqual([workerId]);
+ expect(done.result).toMatchObject({ worker: workerId, output: 'a.txt b.txt', sessionId: 's-1' });
+ expect(await worker(workerId)).toMatchObject({ status: 'idle', tasksCompleted: 1 });
+ });
+
+ it('records a failed run and frees the worker', async () => {
+ tmp('ruflo-hive-fail-');
+ const { workerId, taskId } = await hiveWithOneTask();
+ const runner: TaskRunner = async () => ({ ok: false, output: 'boom', exitCode: 1, durationMs: 1 });
+
+ const r = await workOnce({ cwd: state.cwd, mcpConfig: '/x.json', runner });
+
+ expect(r).toMatchObject({ dispatched: true, status: 'failed' });
+ const failed = await call('task_status', { taskId });
+ expect(failed.status).toBe('failed');
+ expect(failed.result).toMatchObject({ output: 'boom', exitCode: 1 });
+ expect(await worker(workerId)).toMatchObject({ status: 'idle', currentTask: null });
+ });
+
+ it('does nothing, successfully, when the queue is empty or no worker is idle', async () => {
+ tmp('ruflo-hive-empty-');
+ await call('hive-mind_init', {});
+ const runner = vi.fn<TaskRunner>();
+ expect(await workOnce({ cwd: state.cwd, mcpConfig: '/x.json', runner })).toMatchObject({ dispatched: false });
+ await call('task_create', { type: 'hive-mind', description: 'x' });
+ expect(await workOnce({ cwd: state.cwd, mcpConfig: '/x.json', runner })).toMatchObject({
+ dispatched: false,
+ reason: expect.stringContaining('No idle hive worker'),
+ });
+ expect(runner).not.toHaveBeenCalled();
+ });
+});
+
+describe('resolveWorkerMcpConfig', () => {
+ const ruflo = { command: '/node', args: ['/cli.js', 'mcp', 'start'] };
+ const resolve = (home: string, explicit?: string) =>
+ resolveWorkerMcpConfig({ explicit, cwd: state.cwd, home, outDir: join(state.cwd, 'out'), swarmId: 's1', rufloServer: ruflo });
+ const servers = (p: string) => JSON.parse(readFileSync(p, 'utf8')).mcpServers;
+
+ it('never passes a Claude state file through; generates a config with a ruflo server', () => {
+ const home = tmp('ruflo-mcpcfg-');
+ // A fresh desktop's ~/.claude.json: no top-level mcpServers.
+ writeFileSync(join(home, '.claude.json'), JSON.stringify({ numStartups: 3, projects: {} }));
+ const path = resolve(home);
+ expect(path).toBe(join(state.cwd, 'out', 'mcp-s1.json'));
+ expect(servers(path)).toEqual({ ruflo: { ...ruflo, env: { CLAUDE_FLOW_CWD: state.cwd } } });
+ });
+
+ it('keeps servers found in a source config and adds ruflo alongside them', () => {
+ const home = tmp('ruflo-mcpcfg-');
+ writeFileSync(join(state.cwd, '.mcp.json'), JSON.stringify({ mcpServers: { other: { command: 'x' } } }));
+ expect(Object.keys(servers(resolve(home))).sort()).toEqual(['other', 'ruflo']);
+ });
+
+ it('extracts project-scoped servers from ~/.claude.json and keeps an existing ruflo entry', () => {
+ const home = tmp('ruflo-mcpcfg-');
+ const mine = { command: 'npx', args: ['ruflo', 'mcp', 'start'] };
+ writeFileSync(join(home, '.claude.json'), JSON.stringify({ projects: { [state.cwd]: { mcpServers: { ruflo: mine } } } }));
+ expect(servers(resolve(home))).toEqual({ ruflo: mine });
+ });
+
+ it('uses an explicit --mcp-config verbatim', () => {
+ const home = tmp('ruflo-mcpcfg-');
+ expect(resolve(home, '/given.json')).toBe('/given.json');
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/hive-mind-worker.ts b/v3/@claude-flow/cli/src/commands/hive-mind-worker.ts
new file mode 100644
index 0000000000..711766bbd4
--- /dev/null
+++ b/v3/@claude-flow/cli/src/commands/hive-mind-worker.ts
@@ -0,0 +1,297 @@
+/**
+ * Hive-mind worker execution: the MCP config handed to a spawned Claude, and
+ * `hive-mind work`, which actually runs a queued task.
+ *
+ * Before this, `hive-mind task` only wrote a `pending` row to the task store.
+ * Workers are records, not processes, and nothing ever claimed the row: the
+ * task stayed pending and the worker stayed idle forever. `work` is the missing
+ * consumer — claim one task, assign it to an idle hive worker, run it through
+ * `claude -p`, and record the outcome.
+ */
+
+import type { Command, CommandContext, CommandResult } from '../types.js';
+import { output } from '../output.js';
+import { callMCPTool, MCPClientError } from '../mcp-client.js';
+import { spawn as childSpawn } from 'child_process';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { resolveClaudeLaunchCommand } from '../runtime/claude-command.js';
+
+type ServerMap = Record<string, unknown>;
+
+/** The server key the hive-mind prompt addresses (`mcp__ruflo__*`). */
+const RUFLO_SERVER = 'ruflo';
+
+function readServers(path: string, cwd: string): ServerMap | null {
+ try {
+ if (!existsSync(path)) return null;
+ const parsed = JSON.parse(readFileSync(path, 'utf-8')) as Record<string, unknown>;
+ const isMap = (v: unknown): v is ServerMap =>
+ !!v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length > 0;
+ if (isMap(parsed.mcpServers)) return parsed.mcpServers;
+ // ~/.claude.json keeps project-scoped servers under projects[<cwd>].
+ const project = (parsed.projects as Record<string, { mcpServers?: unknown }> | undefined)?.[cwd];
+ if (isMap(project?.mcpServers)) return project.mcpServers;
+ } catch {
+ // Unreadable or not JSON: not a usable config.
+ }
+ return null;
+}
+
+export interface WorkerMcpConfigOptions {
+ /** `--mcp-config` from the caller; used verbatim when given. */
+ explicit?: string;
+ cwd: string;
+ home: string;
+ /** Where the generated config is written (e.g. `.hive-mind/sessions`). */
+ outDir: string;
+ swarmId: string;
+ /** The ruflo MCP server to register when no source config provides one. */
+ rufloServer: { command: string; args: string[] };
+}
+
+/**
+ * The MCP config file to pass to a spawned Claude.
+ *
+ * A source file is never passed through as-is. `~/.claude.json` is Claude
+ * Code's whole state file; on a machine where it has no top-level
+ * `mcpServers` (a fresh desktop), Claude exits at startup with "Invalid MCP
+ * configuration: mcpServers: Invalid input", before any task can run. And a
+ * config lacking a `ruflo` server leaves the worker without the tools its
+ * prompt names. So the servers are extracted, a `ruflo` server is guaranteed,
+ * and the result is written as a config Claude is known to accept.
+ */
+export function resolveWorkerMcpConfig(opts: WorkerMcpConfigOptions): string {
+ if (opts.explicit) return opts.explicit;
+ const candidates = [join(opts.cwd, '.mcp.json')];
+ if (opts.home) candidates.push(join(opts.home, '.claude.json'), join(opts.home, '.claude', 'mcp.json'));
+ let servers: ServerMap = {};
+ for (const c of candidates) {
+ const found = readServers(c, opts.cwd);
+ if (found) {
+ servers = found;
+ break;
+ }
+ }
+ if (!servers[RUFLO_SERVER]) {
+ servers = {
+ ...servers,
+ [RUFLO_SERVER]: {
+ command: opts.rufloServer.command,
+ args: opts.rufloServer.args,
+ // The MCP server keys its stores off this, so the worker's tool calls
+ // land in the same task/agent stores as the CLI that dispatched it.
+ env: { CLAUDE_FLOW_CWD: opts.cwd },
+ },
+ };
+ }
+ mkdirSync(opts.outDir, { recursive: true });
+ const path = join(opts.outDir, `mcp-${opts.swarmId}.json`);
+ writeFileSync(path, JSON.stringify({ mcpServers: servers }, null, 2), 'utf-8');
+ return path;
+}
+
+/**
+ * The ruflo MCP server as launched by THIS cli, so a worker and the CLI that
+ * dispatched it share one version and one store format. `@latest` could
+ * resolve to a different release mid-session.
+ */
+export function currentRufloServer(): { command: string; args: string[] } {
+ const entry = process.argv[1];
+ return entry
+ ? { command: process.execPath, args: [entry, 'mcp', 'start'] }
+ : { command: 'npx', args: ['-y', '@claude-flow/cli@latest', 'mcp', 'start'] };
+}
+
+export interface RunOutcome {
+ ok: boolean;
+ output: string;
+ exitCode: number | null;
+ sessionId?: string;
+ costUsd?: number;
+ durationMs: number;
+}
+
+export type TaskRunner = (prompt: string, opts: { mcpConfig: string; timeoutMs: number; cwd: string }) => Promise<RunOutcome>;
+
+/** Run one prompt through `claude -p` and parse its JSON result. */
+export const runWithClaude: TaskRunner = (prompt, opts) =>
+ new Promise((resolve) => {
+ const started = Date.now();
+ const launch = resolveClaudeLaunchCommand();
+ if (!launch) {
+ resolve({ ok: false, output: 'Claude Code CLI not found in PATH', exitCode: null, durationMs: 0 });
+ return;
+ }
+ // The prompt goes on stdin, not argv: a task description has no length
+ // bound and `--mcp-config` is variadic (#1780).
+ const child = childSpawn(
+ launch.command,
+ [...launch.argsPrefix, '-p', '--output-format', 'json', `--mcp-config=${opts.mcpConfig}`],
+ { cwd: opts.cwd, stdio: ['pipe', 'pipe', 'pipe'] },
+ );
+ let stdout = '';
+ let stderr = '';
+ child.stdout.on('data', (d) => (stdout += d));
+ child.stderr.on('data', (d) => (stderr += d));
+ const timer = setTimeout(() => child.kill('SIGTERM'), opts.timeoutMs);
+ child.on('error', (e) => {
+ clearTimeout(timer);
+ resolve({ ok: false, output: e.message, exitCode: null, durationMs: Date.now() - started });
+ });
+ child.on('close', (code, signal) => {
+ clearTimeout(timer);
+ const durationMs = Date.now() - started;
+ try {
+ const r = JSON.parse(stdout) as { is_error?: boolean; result?: string; session_id?: string; total_cost_usd?: number };
+ resolve({
+ ok: code === 0 && !r.is_error,
+ output: r.result ?? '',
+ exitCode: code,
+ sessionId: r.session_id,
+ costUsd: r.total_cost_usd,
+ durationMs,
+ });
+ } catch {
+ const why = signal === 'SIGTERM' ? `timed out after ${opts.timeoutMs}ms` : (stderr || stdout).trim().slice(-2000);
+ resolve({ ok: false, output: why, exitCode: code, durationMs });
+ }
+ });
+ child.stdin.end(prompt);
+ });
+
+interface TaskView {
+ taskId: string;
+ description: string;
+ status: string;
+ tags?: string[];
+ createdAt: string;
+}
+
+export interface WorkOnceOptions {
+ cwd: string;
+ mcpConfig: string;
+ runner: TaskRunner;
+ taskId?: string;
+ workerId?: string;
+ defaultTimeoutMs?: number;
+}
+
+export type WorkOnceResult =
+ | { dispatched: false; reason: string }
+ | { dispatched: true; taskId: string; workerId: string; status: 'completed' | 'failed'; outcome: RunOutcome };
+
+function timeoutFromTags(tags: string[] | undefined, fallback: number): number {
+ const tag = tags?.find((t) => /^timeout:\d+s$/.test(t));
+ return tag ? Number(tag.slice('timeout:'.length, -1)) * 1000 : fallback;
+}
+
+/**
+ * One dispatch cycle: the oldest pending hive task goes to an idle hive worker,
+ * runs, and its outcome is recorded on the task. Every state change goes
+ * through the MCP task tools, so the store is the same one `hive-mind status`
+ * and `task status` read.
+ */
+export async function workOnce(opts: WorkOnceOptions): Promise<WorkOnceResult> {
+ let taskId = opts.taskId;
+ if (!taskId) {
+ const listed = await callMCPTool<{ tasks: TaskView[] }>('task_list', { status: 'pending', type: 'hive-mind', limit: 1000 });
+ const oldest = [...(listed.tasks ?? [])].sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];
+ if (!oldest) return { dispatched: false, reason: 'No pending hive-mind tasks' };
+ taskId = oldest.taskId;
+ }
+ const task = await callMCPTool<TaskView>('task_status', { taskId });
+ if (task.status !== 'pending') {
+ return { dispatched: false, reason: `Task ${taskId} is ${task.status}, not pending` };
+ }
+
+ let workerId = opts.workerId;
+ if (!workerId) {
+ const hive = await callMCPTool<{ workers?: Array<{ id: string; status: string }> }>('hive-mind_status', {});
+ workerId = hive.workers?.find((w) => w.status === 'idle')?.id;
+ if (!workerId) return { dispatched: false, reason: 'No idle hive worker — run "hive-mind spawn" first' };
+ }
+
+ await callMCPTool('task_assign', { taskId, agentIds: [workerId] });
+ const prompt =
+ `You are hive-mind worker ${workerId}. Complete this task, then reply with ` +
+ `the result only.\n\nTask ${taskId}:\n${task.description}`;
+ const outcome = await opts.runner(prompt, {
+ mcpConfig: opts.mcpConfig,
+ timeoutMs: timeoutFromTags(task.tags, opts.defaultTimeoutMs ?? 300_000),
+ cwd: opts.cwd,
+ });
+ const result = {
+ worker: workerId,
+ output: outcome.output,
+ exitCode: outcome.exitCode,
+ durationMs: outcome.durationMs,
+ ...(outcome.sessionId ? { sessionId: outcome.sessionId } : {}),
+ ...(outcome.costUsd !== undefined ? { costUsd: outcome.costUsd } : {}),
+ };
+ if (outcome.ok) {
+ await callMCPTool('task_complete', { taskId, result });
+ return { dispatched: true, taskId, workerId, status: 'completed', outcome };
+ }
+ await callMCPTool('task_update', { taskId, status: 'failed', result });
+ return { dispatched: true, taskId, workerId, status: 'failed', outcome };
+}
+
+export const workCommand: Command = {
+ name: 'work',
+ description: 'Run the next pending hive task on an idle worker via Claude Code and record the result',
+ options: [
+ { name: 'task', description: 'Run this task id instead of the oldest pending one', type: 'string' },
+ { name: 'worker', description: 'Assign to this worker id instead of the first idle one', type: 'string' },
+ { name: 'mcp-config', description: 'MCP config for the worker (default: generated, with the ruflo server)', type: 'string' },
+ ],
+ examples: [
+ { command: 'claude-flow hive-mind work', description: 'Run the oldest pending hive task' },
+ { command: 'claude-flow hive-mind work --task task-123', description: 'Run a specific task' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const cwd = ctx.cwd || process.cwd();
+ try {
+ const mcpConfig = resolveWorkerMcpConfig({
+ explicit: ctx.flags.mcpConfig as string | undefined,
+ cwd,
+ home: process.env.HOME || process.env.USERPROFILE || '',
+ outDir: join(cwd, '.hive-mind', 'sessions'),
+ swarmId: 'worker',
+ rufloServer: currentRufloServer(),
+ });
+ const r = await workOnce({
+ cwd,
+ mcpConfig,
+ runner: runWithClaude,
+ taskId: ctx.flags.task as string | undefined,
+ workerId: ctx.flags.worker as string | undefined,
+ });
+ if (ctx.flags.format === 'json') {
+ output.printJson(r);
+ } else if (!r.dispatched) {
+ output.printInfo(r.reason);
+ } else {
+ output.printBox(
+ [
+ `Task ID: ${r.taskId}`,
+ `Worker: ${r.workerId}`,
+ `Status: ${r.status}`,
+ `Duration: ${r.outcome.durationMs}ms`,
+ '',
+ r.outcome.output.slice(0, 2000),
+ ].join('\n'),
+ r.status === 'completed' ? 'Task Completed' : 'Task Failed',
+ );
+ output.writeln(output.dim(` Full record: claude-flow task status ${r.taskId}`));
+ }
+ // Nothing to do is not an error; a task that ran and failed is.
+ const failed = r.dispatched && r.status === 'failed';
+ return { success: !failed, exitCode: failed ? 1 : 0, data: r };
+ } catch (error) {
+ const msg = error instanceof MCPClientError ? error.message : String(error);
+ output.printError(`Work error: ${msg}`);
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
diff --git a/v3/@claude-flow/cli/src/commands/hive-mind.ts b/v3/@claude-flow/cli/src/commands/hive-mind.ts
index 66ca259ff7..674f02f8bc 100644
--- a/v3/@claude-flow/cli/src/commands/hive-mind.ts
+++ b/v3/@claude-flow/cli/src/commands/hive-mind.ts
@@ -12,7 +12,7 @@ import { select, confirm, input } from '../prompt.js';
import { callMCPTool, MCPClientError } from '../mcp-client.js';
import { spawn as childSpawn } from 'child_process';
import { mkdir, writeFile } from 'fs/promises';
-import { existsSync } from 'fs';
+import { resolveWorkerMcpConfig, currentRufloServer, workCommand } from './hive-mind-worker.js';
import { join } from 'path';
import { resolveClaudeLaunchCommand } from '../runtime/claude-command.js';
import { getHiveTokenForCli } from '../mcp-tools/hive-mind-tools.js';
@@ -252,39 +252,25 @@ async function spawnClaudeCodeInstance(
const claudeArgs: string[] = [];
// #1748 Issue 2 — pass --mcp-config so the spawned worker actually has
- // mcp__ruflo__* tools registered. Before this, the coordination prompt
- // referenced tools the worker didn't know about and exited silently.
- // Resolution order:
- // 1. explicit --mcp-config <path> flag passed by the caller
- // 2. ./.mcp.json in cwd (project-local Ruflo MCP config)
- // 3. ~/.claude.json or ~/.claude/mcp.json (user-global)
- // If none found, we still spawn but warn — that's the pre-fix behavior
- // and the user's debug log will surface the missing tools.
- const explicitMcpConfig = flags['mcp-config'] as string | undefined;
- let mcpConfigPath: string | undefined = explicitMcpConfig;
- if (!mcpConfigPath) {
- const candidates = [
- join(process.cwd(), '.mcp.json'),
- join(process.env.HOME || process.env.USERPROFILE || '', '.claude.json'),
- join(process.env.HOME || process.env.USERPROFILE || '', '.claude', 'mcp.json'),
- ];
- for (const c of candidates) {
- try {
- if (c && existsSync(c)) { mcpConfigPath = c; break; }
- } catch { /* continue */ }
- }
- }
- if (mcpConfigPath) {
- // #1780 — Claude Code's `--mcp-config` is variadic; passing it as two
- // argv tokens (`--mcp-config`, `<path>`) lets a later positional (the
- // hive-mind prompt) be slurped as a second config file, producing
- // `ENAMETOOLONG: name too long, open` once the prompt exceeds PATH_MAX.
- // Use `=`-syntax so the flag stays attached to its single value.
- claudeArgs.push(`--mcp-config=${mcpConfigPath}`);
- output.printInfo(`Spawned worker MCP config: ${mcpConfigPath}`);
- } else {
- output.printWarning('No .mcp.json or ~/.claude.json found — spawned worker will not have mcp__ruflo__* tools (#1748 Issue 2). Pass --mcp-config <path> or run "ruflo init" to generate one.');
- }
+ // mcp__ruflo__* tools registered. The config is always a generated file
+ // that Claude accepts; see resolveWorkerMcpConfig for why a source
+ // config (notably ~/.claude.json) is never passed through as-is.
+ // The parser stores flags camelCased (#2269), so read both forms.
+ const mcpConfigPath = resolveWorkerMcpConfig({
+ explicit: (flags['mcp-config'] ?? flags.mcpConfig) as string | undefined,
+ cwd: process.cwd(),
+ home: process.env.HOME || process.env.USERPROFILE || '',
+ outDir: sessionsDir,
+ swarmId,
+ rufloServer: currentRufloServer(),
+ });
+ // #1780 — Claude Code's `--mcp-config` is variadic; passing it as two
+ // argv tokens (`--mcp-config`, `<path>`) lets a later positional (the
+ // hive-mind prompt) be slurped as a second config file, producing
+ // `ENAMETOOLONG: name too long, open` once the prompt exceeds PATH_MAX.
+ // Use `=`-syntax so the flag stays attached to its single value.
+ claudeArgs.push(`--mcp-config=${mcpConfigPath}`);
+ output.printInfo(`Spawned worker MCP config: ${mcpConfigPath}`);
// Check for non-interactive mode
const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;
@@ -1069,7 +1055,8 @@ const taskCommand: Command = {
output.writeln();
output.printSuccess('Task submitted to hive');
- output.writeln(output.dim(` Track with: claude-flow hive-mind task-status ${result.taskId}`));
+ output.writeln(output.dim(` Run it with: claude-flow hive-mind work --task ${result.taskId}`));
+ output.writeln(output.dim(` Track with: claude-flow task status ${result.taskId}`));
return { success: true, data: result };
} catch (error) {
@@ -1366,7 +1353,7 @@ export const hiveMindCommand: Command = {
name: 'hive-mind',
aliases: ['hive'],
description: 'Queen-led consensus-based multi-agent coordination',
- subcommands: [initCommand, spawnCommand, statusCommand, taskCommand, joinCommand, leaveCommand, consensusCommand, broadcastCommand, memorySubCommand, optimizeMemoryCommand, shutdownCommand],
+ subcommands: [initCommand, spawnCommand, statusCommand, taskCommand, workCommand, joinCommand, leaveCommand, consensusCommand, broadcastCommand, memorySubCommand, optimizeMemoryCommand, shutdownCommand],
options: [],
examples: [
{ command: 'claude-flow hive-mind init -t hierarchical-mesh', description: 'Initialize hive' },
@@ -1386,6 +1373,7 @@ export const hiveMindCommand: Command = {
`${output.highlight('spawn')} - Spawn worker agents (use --claude to launch Claude Code)`,
`${output.highlight('status')} - Show hive status`,
`${output.highlight('task')} - Submit task to hive`,
+ `${output.highlight('work')} - Run the next pending task on an idle worker`,
`${output.highlight('join')} - Join an agent to the hive`,
`${output.highlight('leave')} - Remove an agent from the hive`,
`${output.highlight('consensus')} - Manage consensus proposals`,
diff --git a/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts
index 152ee9cbe6..37e07c3884 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts
@@ -67,6 +67,52 @@ function saveTaskStore(store: TaskStore): void {
writeFileSync(getTaskPath(), JSON.stringify(store, null, 2), 'utf-8');
}
+type AgentRow = Record<string, unknown>;
+
+/**
+ * Apply an agent-state change to every store that holds the agent.
+ *
+ * `hive-mind_spawn` keeps its workers in `.claude-flow/agents.json`, not the
+ * canonical `.claude-flow/agents/store.json` (#1916). Syncing only the
+ * canonical store meant assigning a task to a hive worker never marked it
+ * busy, and completing one never counted it: `hive-mind status` showed the
+ * worker idle with 0 completed while its task sat in the queue.
+ */
+function updateAgents(agentIds: string[], mutate: (agent: AgentRow) => void): void {
+ if (agentIds.length === 0) return;
+ const paths = [
+ join(getProjectCwd(), STORAGE_DIR, 'agents', 'store.json'),
+ join(getProjectCwd(), STORAGE_DIR, 'agents.json'),
+ ];
+ for (const path of paths) {
+ try {
+ if (!existsSync(path)) continue;
+ const store = JSON.parse(readFileSync(path, 'utf-8')) as { agents?: Record<string, AgentRow> };
+ if (!store.agents) continue;
+ let touched = false;
+ for (const id of agentIds) {
+ if (store.agents[id]) {
+ mutate(store.agents[id]);
+ touched = true;
+ }
+ }
+ if (touched) writeFileSync(path, JSON.stringify(store, null, 2), 'utf-8');
+ } catch {
+ // Best-effort agent sync: a corrupt agent store must not fail the task op.
+ }
+ }
+}
+
+/** Return agents still holding `taskId` to idle. */
+function releaseAgents(agentIds: string[], taskId: string): void {
+ updateAgents(agentIds, (agent) => {
+ if (agent.currentTask === taskId) {
+ agent.status = 'idle';
+ agent.currentTask = null;
+ }
+ });
+}
+
export const taskTools: MCPTool[] = [
{
name: 'task_create',
@@ -260,28 +306,13 @@ export const taskTools: MCPTool[] = [
saveTaskStore(store);
// Sync assigned agents back to idle and increment taskCount
- if (task.assignedTo.length > 0) {
- const agentStorePath = join(getProjectCwd(), STORAGE_DIR, 'agents', 'store.json');
- try {
- let agentStore: { agents: Record<string, Record<string, unknown>> } = { agents: {} };
- if (existsSync(agentStorePath)) {
- agentStore = JSON.parse(readFileSync(agentStorePath, 'utf-8'));
- }
- for (const agentId of task.assignedTo) {
- if (agentStore.agents[agentId]) {
- if (agentStore.agents[agentId].currentTask === taskId) {
- agentStore.agents[agentId].status = 'idle';
- agentStore.agents[agentId].currentTask = null;
- }
- agentStore.agents[agentId].taskCount =
- ((agentStore.agents[agentId].taskCount as number) || 0) + 1;
- }
- }
- writeFileSync(agentStorePath, JSON.stringify(agentStore, null, 2), 'utf-8');
- } catch {
- // Best-effort agent sync
+ updateAgents(task.assignedTo, (agent) => {
+ if (agent.currentTask === taskId) {
+ agent.status = 'idle';
+ agent.currentTask = null;
}
- }
+ agent.taskCount = ((agent.taskCount as number) || 0) + 1;
+ });
return {
taskId: task.taskId,
@@ -309,6 +340,7 @@ export const taskTools: MCPTool[] = [
status: { type: 'string', description: 'New status' },
progress: { type: 'number', description: 'Progress percentage (0-100)' },
assignTo: { type: 'array', items: { type: 'string' }, description: 'Agent IDs to assign' },
+ result: { type: 'object', description: 'Result data (e.g. the failure of a failed task)' },
},
required: ['taskId'],
},
@@ -328,6 +360,12 @@ export const taskTools: MCPTool[] = [
if (newStatus === 'in_progress' && !task.startedAt) {
task.startedAt = new Date().toISOString();
}
+ // A failed task frees its workers, as task_complete and task_cancel do;
+ // otherwise a worker whose run failed stays `busy` forever.
+ if (newStatus === 'failed') {
+ task.completedAt = new Date().toISOString();
+ releaseAgents(task.assignedTo, taskId);
+ }
}
if (typeof input.progress === 'number') {
task.progress = Math.min(100, Math.max(0, input.progress as number));
@@ -335,6 +373,9 @@ export const taskTools: MCPTool[] = [
if (input.assignTo) {
task.assignedTo = input.assignTo as string[];
}
+ if (input.result && typeof input.result === 'object') {
+ task.result = input.result as Record<string, unknown>;
+ }
saveTaskStore(store);
return {
@@ -381,40 +422,19 @@ export const taskTools: MCPTool[] = [
const previouslyAssigned = [...task.assignedTo];
- // Load agent store to sync worker state
- const agentStorePath = join(getProjectCwd(), STORAGE_DIR, 'agents', 'store.json');
- let agentStore: { agents: Record<string, Record<string, unknown>> } = { agents: {} };
- try {
- if (existsSync(agentStorePath)) {
- agentStore = JSON.parse(readFileSync(agentStorePath, 'utf-8'));
- }
- } catch { /* ignore */ }
-
if (input.unassign) {
// Revert previously assigned agents to idle
- for (const agentId of previouslyAssigned) {
- if (agentStore.agents[agentId]?.currentTask === taskId) {
- agentStore.agents[agentId].status = 'idle';
- agentStore.agents[agentId].currentTask = null;
- }
- }
+ releaseAgents(previouslyAssigned, taskId);
task.assignedTo = [];
} else {
const agentIds = (input.agentIds as string[]) || [];
// Revert old agents to idle
- for (const agentId of previouslyAssigned) {
- if (!agentIds.includes(agentId) && agentStore.agents[agentId]?.currentTask === taskId) {
- agentStore.agents[agentId].status = 'idle';
- agentStore.agents[agentId].currentTask = null;
- }
- }
+ releaseAgents(previouslyAssigned.filter((id) => !agentIds.includes(id)), taskId);
// Set new agents to active
- for (const agentId of agentIds) {
- if (agentStore.agents[agentId]) {
- agentStore.agents[agentId].status = 'busy';
- agentStore.agents[agentId].currentTask = taskId;
- }
- }
+ updateAgents(agentIds, (agent) => {
+ agent.status = 'busy';
+ agent.currentTask = taskId;
+ });
task.assignedTo = agentIds;
// Auto-transition task to in_progress if pending
if (task.status === 'pending' && agentIds.length > 0) {
@@ -426,12 +446,6 @@ export const taskTools: MCPTool[] = [
}
saveTaskStore(store);
- // Save agent store
- const agentDir = join(getProjectCwd(), STORAGE_DIR, 'agents');
- if (!existsSync(agentDir)) {
- mkdirSync(agentDir, { recursive: true });
- }
- writeFileSync(agentStorePath, JSON.stringify(agentStore, null, 2), 'utf-8');
return {
taskId: task.taskId,
@@ -471,20 +485,7 @@ export const taskTools: MCPTool[] = [
task.completedAt = new Date().toISOString();
task.result = { cancelReason: input.reason || 'Cancelled by user' };
saveTaskStore(store);
- const agentStorePath = join(getProjectCwd(), STORAGE_DIR, 'agents', 'store.json');
- try {
- if (existsSync(agentStorePath)) {
- const agents = JSON.parse(readFileSync(agentStorePath, 'utf-8'));
- for (const agentId of task.assignedTo) {
- if (agents.agents[agentId]?.currentTask === taskId) {
- agents.agents[agentId].status = 'idle';
- agents.agents[agentId].currentTask = null;
- }
- }
- writeFileSync(agentStorePath, JSON.stringify(agents, null, 2), 'utf-8');
- }
- } catch { /* best-effort agent sync, as in task_complete */ }
-
+ releaseAgents(task.assignedTo, taskId);
return {
success: true,