π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(swarm): report a real swarm id, and make `swarm stop` usable without one (#3253)
rUvc20b71f7b7b7
diff --git a/v3/@claude-flow/cli/__tests__/commands.test.ts b/v3/@claude-flow/cli/__tests__/commands.test.tsindex 9f2db96af6..eb684741fa 100644--- a/v3/@claude-flow/cli/__tests__/commands.test.ts+++ b/v3/@claude-flow/cli/__tests__/commands.test.ts@@ -4,6 +4,9 @@*/import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { agentCommand } from '../src/commands/agent.js';import { swarmCommand } from '../src/commands/swarm.js';import { memoryCommand } from '../src/commands/memory.js';@@ -486,12 +489,22 @@ describe('Swarm Commands', () => {expect(result.data).toHaveProperty('stopped', true);});- it('should fail without swarm ID', async () => {+ it('should fail without swarm ID when none is persisted', async () => {const stopCmd = swarmCommand.subcommands?.find(c => c.name === 'stop');- const result = await stopCmd!.action!(ctx);-- expect(result.success).toBe(false);+ // Bare `swarm stop` now defaults to the persisted swarm, so this has to+ // run somewhere with no swarm state β the `swarm start` test above+ // writes a real `.swarm/state.json` into the package directory.+ const originalCwd = process.cwd();+ const isolated = mkdtempSync(join(tmpdir(), 'ruflo-swarm-stop-'));+ try {+ process.chdir(isolated);+ const result = await stopCmd!.action!(ctx);+ expect(result.success).toBe(false);+ } finally {+ process.chdir(originalCwd);+ rmSync(isolated, { recursive: true, force: true });+ }});});diff --git a/v3/@claude-flow/cli/__tests__/swarm-status-id-and-stop.test.ts b/v3/@claude-flow/cli/__tests__/swarm-status-id-and-stop.test.tsnew file mode 100644index 0000000000..e6d47fbd38--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/swarm-status-id-and-stop.test.ts@@ -0,0 +1,338 @@+/**+ * Regression guards for two `swarm` defects reproduced on a live desktop+ * running ruflo v3.38.21:+ *+ * 1. `swarm status --format json` emitted the literal string+ * 'no-active-swarm' as the value of `id` while also reporting+ * `hasActiveSwarm: true` and 9 agents. The id is persisted by three+ * writers under two keys (`.swarm/state.json` `id` from `swarm init`,+ * `.swarm/state.json` `swarmId` from `swarm start`, and+ * `.claude-flow/swarm/swarm-state.json` from MCP `swarm_init`) and the+ * reader checked only the first.+ * 2. `swarm stop` with no argument always failed, and no CLI surface handed+ * out an id to pass (there is no `swarm list` subcommand).+ *+ * Exercised via real execFileSync against bin/cli.js in temp cwds, matching+ * the harness in hooks-metrics-swarm-backup-2797-2798-2799.test.ts.+ */++import { describe, it, expect } from 'vitest';+import { execFileSync } from 'node:child_process';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const CLI = join(__dirname, '..', 'bin', 'cli.js');++function run(args: string[], cwd: string): { stdout: string; exit: number } {+ try {+ const stdout = execFileSync('node', [CLI, ...args], {+ cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'],+ });+ return { stdout, exit: 0 };+ } catch (err) {+ const e = err as { status?: number; stdout?: Buffer; stderr?: Buffer };+ return { stdout: (e.stdout?.toString() ?? '') + (e.stderr?.toString() ?? ''), exit: e.status ?? -1 };+ }+}++function statusJson(cwd: string): Record<string, unknown> {+ const { stdout } = run(['swarm', 'status', '--format', 'json'], cwd);+ return JSON.parse(stdout.slice(stdout.indexOf('{')));+}++/** `.swarm/state.json` as written by `swarm start`. */+function writeStartState(cwd: string, swarmId: string): void {+ mkdirSync(join(cwd, '.swarm'), { recursive: true });+ writeFileSync(join(cwd, '.swarm', 'state.json'), JSON.stringify({+ swarmId,+ objective: 'test objective',+ strategy: 'development',+ status: 'initialized',+ agents: 3,+ startedAt: new Date().toISOString(),+ }, null, 2));+}++/** `.claude-flow/swarm/swarm-state.json` as written by MCP `swarm_init`. */+function writeMcpState(cwd: string, swarmId: string): void {+ mkdirSync(join(cwd, '.claude-flow', 'swarm'), { recursive: true });+ writeFileSync(join(cwd, '.claude-flow', 'swarm', 'swarm-state.json'), JSON.stringify({+ version: '3.0.0',+ swarms: {+ [swarmId]: {+ swarmId,+ topology: 'hierarchical',+ maxAgents: 8,+ status: 'running',+ agents: ['agent-1'],+ tasks: [],+ config: {},+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ },+ },+ }, null, 2));+}++/**+ * The exact on-disk fixture captured from the live desktop (machine+ * 8dd713ae391948) whose `swarm status --format json` returned the sentinel:+ * `.swarm/state.json` carrying `swarmId` and NO `id`, no `topology`,+ * `status: "initialized"`, `.claude-flow/swarm/` never created, and 9 agents+ * registered. Produced by the console wizard running CLI `swarm init` then+ * `swarm start` with the MCP server unavailable, so only `start`'s write β+ * which uses the key `swarmId` β survived.+ */+function writeLiveDesktopFixture(cwd: string): void {+ mkdirSync(join(cwd, '.swarm'), { recursive: true });+ writeFileSync(join(cwd, '.swarm', 'state.json'), JSON.stringify({+ swarmId: 'swarm-mtultyxy',+ objective: 'ruOS console wizard deployment',+ strategy: 'specialized',+ status: 'initialized',+ agents: 9,+ agentPlan: [{ role: 'Coordinator', type: 'coordinator', count: 1, purpose: 'Orchestrate workflow' }],+ startedAt: new Date().toISOString(),+ parallel: true,+ }, null, 2));++ // Agents present, registered the way `agent spawn` registers them.+ mkdirSync(join(cwd, '.claude-flow', 'agents'), { recursive: true });+ const agents: Record<string, { status: string }> = {};+ for (let i = 1; i <= 9; i++) agents[`agent-${i}`] = { status: 'active' };+ writeFileSync(join(cwd, '.claude-flow', 'agents', 'store.json'), JSON.stringify({ agents }, null, 2));+ // Deliberately NO .claude-flow/swarm/ β the MCP store never existed.+}++describe('live desktop fixture (machine 8dd713ae391948)', () => {+ it('resolves swarmId with no `id` key and no MCP store at all', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-live-'));+ try {+ writeLiveDesktopFixture(wd);+ expect(existsSync(join(wd, '.claude-flow', 'swarm'))).toBe(false);++ const status = statusJson(wd);+ expect(status.id).toBe('swarm-mtultyxy');+ expect(JSON.stringify(status)).not.toContain('no-active-swarm');+ expect(status.hasActiveSwarm).toBe(true);+ expect(status.agents).toMatchObject({ total: 9, active: 9 });+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);++ it('bare `swarm stop` targets that swarm', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-live-'));+ try {+ writeLiveDesktopFixture(wd);+ const { stdout, exit } = run(['swarm', 'stop'], wd);+ expect(exit).toBe(0);+ expect(stdout).toContain('swarm-mtultyxy');+ const state = JSON.parse(readFileSync(join(wd, '.swarm', 'state.json'), 'utf-8'));+ expect(state.status).toBe('stopped');+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);+});++describe('swarm status reports an honest id', () => {+ it('emits null β not a sentinel string β when there is no swarm', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-id-'));+ try {+ const status = statusJson(wd);+ expect(status.id).toBeNull();+ expect(JSON.stringify(status)).not.toContain('no-active-swarm');+ expect(status.hasActiveSwarm).toBe(false);+ expect(status.status).toBe('idle');+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);++ it('resolves the id `swarm start` persists as `swarmId`', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-id-'));+ try {+ writeStartState(wd, 'swarm-from-start');+ const status = statusJson(wd);+ expect(status.id).toBe('swarm-from-start');+ expect(status.hasActiveSwarm).toBe(true);+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);++ it('resolves the id MCP `swarm_init` persists, with no .swarm/state.json', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-id-'));+ try {+ // No agents spawned yet, so neither the CLI state file nor the agent+ // store exists β the payload must still agree with itself.+ writeMcpState(wd, 'swarm-from-mcp');+ const status = statusJson(wd);+ expect(status.id).toBe('swarm-from-mcp');+ expect(status.hasActiveSwarm).toBe(true);++ // ...and the human view must print the swarm, not bail out early.+ const human = run(['swarm', 'status'], wd).stdout;+ expect(human).toContain('Swarm Status: swarm-from-mcp');+ expect(human).not.toContain('No active swarm');+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);++ it('does not let a stopped state file shadow a live MCP swarm', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-id-'));+ try {+ writeStartState(wd, 'swarm-already-stopped');+ writeFileSync(join(wd, '.swarm', 'state.json'), JSON.stringify({+ id: 'swarm-already-stopped',+ swarmId: 'swarm-already-stopped',+ status: 'stopped',+ stoppedAt: new Date().toISOString(),+ }, null, 2));+ writeMcpState(wd, 'swarm-still-running');+ expect(statusJson(wd).id).toBe('swarm-still-running');+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);++ it('a stopped state file does not claim an active swarm it cannot name', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-id-'));+ try {+ mkdirSync(join(wd, '.swarm'), { recursive: true });+ writeFileSync(join(wd, '.swarm', 'state.json'), JSON.stringify({+ id: 'swarm-x', swarmId: 'swarm-x', status: 'stopped',+ }, null, 2));++ // All three fields must agree that this swarm is not active.+ const status = statusJson(wd);+ expect(status.id).toBeNull();+ expect(status.hasActiveSwarm).toBe(false);+ expect(status.status).toBe('stopped');+ expect(run(['swarm', 'status'], wd).stdout).toContain('No active swarm');+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);++ it('a stopped state file still reports genuinely live agents', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-id-'));+ try {+ mkdirSync(join(wd, '.swarm'), { recursive: true });+ writeFileSync(join(wd, '.swarm', 'state.json'), JSON.stringify({+ id: 'swarm-x', swarmId: 'swarm-x', status: 'stopped',+ }, null, 2));+ mkdirSync(join(wd, '.claude-flow', 'agents'), { recursive: true });+ writeFileSync(join(wd, '.claude-flow', 'agents', 'store.json'),+ JSON.stringify({ agents: { a1: { status: 'active' } } }, null, 2));++ // Agents are real activity, so `hasActiveSwarm` stays true even though no+ // swarm id resolves β "agents running, no swarm registered" is a genuine+ // state, not a contradiction. A stopped file must not mask it.+ const status = statusJson(wd);+ expect(status.hasActiveSwarm).toBe(true);+ expect(status.agents).toMatchObject({ total: 1, active: 1 });+ // Observed reality wins over the file's recorded intent.+ expect(status.status).toBe('running');+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);++ it('prefers an explicitly supplied id over the persisted one', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-id-'));+ try {+ writeStartState(wd, 'swarm-from-start');+ const { stdout } = run(['swarm', 'status', 'swarm-explicit', '--format', 'json'], wd);+ expect(JSON.parse(stdout.slice(stdout.indexOf('{'))).id).toBe('swarm-explicit');+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);+});++describe('swarm stop works without an argument', () => {+ it('stops the persisted swarm and records it in the state file', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-stop-'));+ try {+ writeStartState(wd, 'swarm-from-start');+ const { stdout, exit } = run(['swarm', 'stop'], wd);+ expect(exit).toBe(0);+ expect(stdout).toContain('swarm-from-start');+ const state = JSON.parse(readFileSync(join(wd, '.swarm', 'state.json'), 'utf-8'));+ expect(state.status).toBe('stopped');+ expect(state.stoppedAt).toBeTruthy();+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);++ it('resolves an MCP-only swarm id', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-stop-'));+ try {+ writeMcpState(wd, 'swarm-from-mcp');+ const { stdout, exit } = run(['swarm', 'stop'], wd);+ expect(exit).toBe(0);+ expect(stdout).toContain('swarm-from-mcp');+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);++ it('stops the live MCP swarm, not the id in a stopped state file', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-stop-'));+ try {+ mkdirSync(join(wd, '.swarm'), { recursive: true });+ writeFileSync(join(wd, '.swarm', 'state.json'), JSON.stringify({+ id: 'swarm-already-stopped',+ swarmId: 'swarm-already-stopped',+ status: 'stopped',+ stoppedAt: new Date().toISOString(),+ }, null, 2));+ writeMcpState(wd, 'swarm-still-running');++ const { stdout, exit } = run(['swarm', 'stop'], wd);+ expect(exit).toBe(0);+ expect(stdout).toContain('swarm-still-running');+ expect(stdout).not.toContain('swarm-already-stopped');++ const store = JSON.parse(readFileSync(join(wd, '.claude-flow', 'swarm', 'swarm-state.json'), 'utf-8'));+ expect(store.swarms['swarm-still-running'].status).toBe('terminated');++ // Nothing live is left, so a second bare stop must say so rather than+ // report success against the stale local id again.+ const second = run(['swarm', 'stop'], wd);+ expect(second.exit).toBe(1);+ expect(second.stdout).toContain('No swarm found to stop');+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);++ it('still honours an explicit id argument', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-stop-'));+ try {+ writeStartState(wd, 'swarm-from-start');+ const { stdout, exit } = run(['swarm', 'stop', 'swarm-explicit'], wd);+ expect(exit).toBe(0);+ expect(stdout).toContain('swarm-explicit');+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);++ it('fails with guidance on how to find an id when there is nothing to stop', () => {+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-swarm-stop-'));+ try {+ const { stdout, exit } = run(['swarm', 'stop'], wd);+ expect(exit).toBe(1);+ expect(stdout).toContain('No swarm found to stop');+ expect(stdout).toContain('swarm status --format json');+ } finally {+ rmSync(wd, { recursive: true, force: true });+ }+ }, 60_000);+});diff --git a/v3/@claude-flow/cli/src/commands/swarm.ts b/v3/@claude-flow/cli/src/commands/swarm.tsindex 74190267fb..82a13794cf 100644--- a/v3/@claude-flow/cli/src/commands/swarm.ts+++ b/v3/@claude-flow/cli/src/commands/swarm.ts@@ -11,6 +11,56 @@ import { swarmJoinCommand } from './agntcy/swarm-join.js';import * as fs from 'fs';import * as path from 'path';+// Read the CLI-side swarm state file (`.swarm/state.json`), written by+// `swarm init` and rewritten by `swarm start` / `swarm stop`.+function readLocalSwarmState(): Record<string, unknown> | null {+ const swarmStateFile = path.join(process.cwd(), '.swarm', 'state.json');+ if (!fs.existsSync(swarmStateFile)) return null;+ try {+ return JSON.parse(fs.readFileSync(swarmStateFile, 'utf-8'));+ } catch {+ // Ignore parse errors+ return null;+ }+}++// Resolve the id of the current swarm. Three writers persist it, under two+// different keys and in two different files:+//+// `.swarm/state.json` `id` β `swarm init`+// `.swarm/state.json` `swarmId` β `swarm start`+// `.claude-flow/swarm/swarm-state.json` `swarms[id].swarmId` β MCP `swarm_init`+//+// The status payload used to read only the first key of the first file, so a+// Claude Code session (which drives the MCP path) reported an active swarm+// with agents but no usable id. Check every writer, most local first.+function resolveSwarmId(swarmState?: Record<string, unknown> | null): string | null {+ // A state file left behind by a previous `swarm stop` must not shadow a+ // swarm that is still live in the MCP store β otherwise `stop` names the+ // dead id while `swarm_shutdown`'s own "most recent running" fallback+ // terminates a different swarm.+ if (swarmState?.status !== 'stopped') {+ const fromState = swarmState?.id ?? swarmState?.swarmId;+ if (typeof fromState === 'string' && fromState) return fromState;+ }++ try {+ const storePath = path.join(process.cwd(), '.claude-flow', 'swarm', 'swarm-state.json');+ if (!fs.existsSync(storePath)) return null;+ const store = JSON.parse(fs.readFileSync(storePath, 'utf-8')) as {+ swarms?: Record<string, { swarmId?: string; status?: string; updatedAt?: string }>;+ };+ // Most recently updated swarm that has not been shut down.+ const live = Object.values(store.swarms ?? {})+ .filter(swarm => swarm.status !== 'terminated')+ .sort((a, b) => new Date(b.updatedAt ?? 0).getTime() - new Date(a.updatedAt ?? 0).getTime());+ return live[0]?.swarmId ?? null;+ } catch {+ // Ignore β an unreadable MCP store just means no id to resolve.+ return null;+ }+}+// Get dynamic swarm status from memory/session filesfunction getSwarmStatus(swarmId?: string) {const swarmDir = path.join(process.cwd(), '.swarm');@@ -21,16 +71,7 @@ function getSwarmStatus(swarmId?: string) {];// Check for active swarm state file- const swarmStateFile = path.join(swarmDir, 'state.json');- let swarmState: Record<string, unknown> | null = null;-- if (fs.existsSync(swarmStateFile)) {- try {- swarmState = JSON.parse(fs.readFileSync(swarmStateFile, 'utf-8'));- } catch {- // Ignore parse errors- }- }+ const swarmState = readLocalSwarmState();// Count active agents from process fileslet activeAgents = 0;@@ -175,11 +216,24 @@ function getSwarmStatus(swarmId?: string) {} else if (completedTasks > 0 && pendingTasks === 0 && inProgressTasks === 0) {status = 'completed';} else if (swarmState) {- status = 'ready';+ // The file's own lifecycle state wins over the "a file exists, so we are+ // ready" default β a swarm explicitly recorded as stopped is not ready.+ // Live agents still win above: they are observed reality, whereas the file+ // records an intent that may be stale.+ status = swarmState.status === 'stopped' ? 'stopped' : 'ready';}+ // Resolve once β the id also settles whether there is a swarm to report.+ // An MCP `swarm_init` with no agents spawned yet leaves no `.swarm/state.json`+ // and no agent store, so without this the payload contradicted itself:+ // a real `id` alongside `hasActiveSwarm: false`.+ const resolvedId = swarmId || resolveSwarmId(swarmState);+return {- id: swarmId || (swarmState as Record<string, string>)?.id || 'no-active-swarm',+ // `null` when genuinely unknown β never a sentinel string. `status` and+ // `hasActiveSwarm` already carry the "no active swarm" fact, and a+ // consumer reading `.id` must get an id or nothing.+ id: resolvedId,topology: (swarmState as Record<string, string>)?.topology || 'none',status,objective: (swarmState as Record<string, string>)?.objective || 'No active objective',@@ -272,7 +326,13 @@ function getSwarmStatus(swarmId?: string) {}return { consensusRounds, messagesSent, conflictsResolved };})(),- hasActiveSwarm: !!swarmState || totalAgents > 0+ // A state file left behind by `swarm stop` is not an active swarm β without+ // this it claimed one it could not name (`id: null`, zero agents), which is+ // the same contradiction from the other side. Live agents or a resolvable+ // id still count, so a stopped file never masks real activity.+ hasActiveSwarm: (!!swarmState && swarmState.status !== 'stopped')+ || totalAgents > 0+ || resolvedId !== null};}@@ -646,6 +706,9 @@ const startCommand: Command = {if (!fs.existsSync(swarmDir)) fs.mkdirSync(swarmDir, { recursive: true });const executionState = {+ // `id` mirrors what `swarm init` writes so both files share one key;+ // `swarmId` stays for existing files and readers.+ id: swarmId,swarmId,objective,strategy,@@ -701,7 +764,7 @@ const statusCommand: Command = {return { success: true, data: status };}- output.writeln(output.bold(`Swarm Status: ${status.id}`));+ output.writeln(output.bold(`Swarm Status: ${status.id ?? output.dim('unknown id')}`));output.writeln();// Progress bar@@ -785,11 +848,17 @@ const stopCommand: Command = {}],action: async (ctx: CommandContext): Promise<CommandResult> => {- const swarmId = ctx.args[0];+ // Bare `swarm stop` used to hard-fail, and no CLI surface handed out an+ // id to pass (there is no `swarm list`). Default to the persisted swarm;+ // an explicit argument still wins.+ const swarmId = ctx.args[0] || resolveSwarmId(readLocalSwarmState());const force = ctx.flags.force as boolean;if (!swarmId) {- output.printError('Swarm ID is required');+ output.printError('No swarm found to stop');+ output.writeln(output.dim(' Find an id with: claude-flow swarm status --format json (the "id" field)'));+ output.writeln(output.dim(' Or pass one: claude-flow swarm stop <swarm-id>'));+ output.writeln(output.dim(' Or start one: claude-flow swarm init'));return { success: false, exitCode: 1 };}@@ -855,12 +924,15 @@ const scaleCommand: Command = {}],action: async (ctx: CommandContext): Promise<CommandResult> => {- const swarmId = ctx.args[0];+ // Same resolution as `stop` β the id is persisted, so don't demand it.+ const swarmId = ctx.args[0] || resolveSwarmId(readLocalSwarmState());const targetAgents = ctx.flags.agents as number;const agentType = ctx.flags.type as string;if (!swarmId) {- output.printError('Swarm ID is required');+ output.printError('No swarm found to scale');+ output.writeln(output.dim(' Find an id with: claude-flow swarm status --format json (the "id" field)'));+ output.writeln(output.dim(' Or pass one: claude-flow swarm scale <swarm-id> --agents N'));return { success: false, exitCode: 1 };}