diff --git a/v3/@claude-flow/cli/__tests__/stale-mcp-key-2369.test.ts b/v3/@claude-flow/cli/__tests__/stale-mcp-key-2369.test.ts new file mode 100644 index 0000000000..fe6f9d1bd5 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/stale-mcp-key-2369.test.ts @@ -0,0 +1,140 @@ +/** + * Regression tests for #2369 (and the batchable companions #2370 / #2371). + * + * All three bugs are the same shape: the rename from `claude-flow` to `ruflo` + * left three runtime call sites referencing the deprecated dist-tag + * `claude-flow@v3alpha` (or `claude-flow@alpha`), each of which silently + * routes users / workers / detectors to a pre-rename build that lacks + * autopilot, browser, wasm-agent, and other current MCP tools. + * + * The tests pin the runtime contracts so a future grep-and-replace can't + * silently undo the fix. + */ + +import { describe, it, expect } from 'vitest'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +// Strip block comments AND line comments so the sanity sweeps only see +// runtime code. The fix commits intentionally cite the deprecated dist-tag +// in their explanatory comments — that's documentation, not the bug. +// The tests must not flag it. +function stripComments(text: string): string { + return text + .replace(/\/\*[\s\S]*?\*\//g, '') + .replace(/\/\/.*$/gm, ''); +} + +describe('#2369 — stale MCP key handling in init', () => { + // We test the runtime by reading the compiled source for the predicates + // we want to pin. Spinning up the full executor for these cases would + // run the rest of `init` (skills/agents/helpers) which is overkill. + const executorSrc = fs.readFileSync( + path.resolve(__dirname, '../src/init/executor.ts'), + 'utf-8', + ); + + it('detectExistingRufloMCP recognises the legacy `claude-flow@alpha` key at the top level', () => { + expect(executorSrc).toMatch(/'claude-flow@alpha'\s+in\s+servers/); + }); + + it('detectExistingRufloMCP recognises the legacy `claude-flow@v3alpha` key at the top level', () => { + expect(executorSrc).toMatch(/'claude-flow@v3alpha'\s+in\s+servers/); + }); + + it('detectExistingRufloMCP also recognises legacy keys in project-scoped registrations', () => { + // The project-scoped path needs the same widening — pin both. + expect(executorSrc).toMatch(/'claude-flow@alpha'\s+in\s+mcp/); + expect(executorSrc).toMatch(/'claude-flow@v3alpha'\s+in\s+mcp/); + }); + + it('writeMCPConfig surfaces a loud message naming the deprecated key when an existing local .mcp.json uses one (Scenario A)', () => { + // The Scenario A guard must read the local file, detect a stale key, + // and push a `skipped` line that NAMES the deprecated key (so the + // user can find it). Pin both the message shape and the inclusion of + // the "deprecated key" phrase, since silent skip is the bug. + expect(executorSrc).toMatch(/uses deprecated key/); + expect(executorSrc).toMatch(/claude-flow@alpha/); + expect(executorSrc).toMatch(/claude-flow@v3alpha/); + }); +}); + +describe('#2370 — swarm.ts MCP-down hint references the current package', () => { + const swarmSrc = fs.readFileSync( + path.resolve(__dirname, '../src/commands/swarm.ts'), + 'utf-8', + ); + const swarmCode = stripComments(swarmSrc); + + it('does not reference the deprecated `claude-flow@v3alpha` dist-tag in code (comments OK)', () => { + expect(swarmCode).not.toMatch(/claude-flow@v3alpha/); + }); + + it('points users at `ruflo@latest` with the `-y` flag (forces fresh fetch)', () => { + expect(swarmSrc).toMatch(/npx -y ruflo@latest/); + }); + + it('uses the `--` separator before the npx invocation (avoids claude-mcp flag ambiguity)', () => { + expect(swarmSrc).toMatch(/claude mcp add claude-flow -- npx -y ruflo@latest/); + }); +}); + +describe('#2371 — ContainerWorkerPool spawns workers with the current package', () => { + const poolSrc = fs.readFileSync( + path.resolve(__dirname, '../src/services/container-worker-pool.ts'), + 'utf-8', + ); + const poolCode = stripComments(poolSrc); + + it('does not spawn workers via the deprecated `claude-flow@v3alpha` dist-tag in code (comments OK)', () => { + expect(poolCode).not.toMatch(/claude-flow@v3alpha/); + }); + + it('spawns workers via `ruflo@latest` with `-y` so npx never falls back to a stale local install', () => { + // The argv array must contain the three tokens in order. Match the + // structure rather than the exact whitespace so trivial reformatting + // doesn't break the test. + expect(poolSrc).toMatch(/['"]npx['"]\s*,\s*['"]-y['"]\s*,\s*['"]ruflo@latest['"]/); + }); +}); + +describe('Sanity — no other runtime source references the deprecated dist-tags', () => { + // Sweep the runtime source tree once. This is a low-cost guard against + // a future contributor reintroducing the stale string via copy-paste. + // Doc paths (CLAUDE.md, README.md, ADRs) are intentionally excluded — + // they may legitimately reference legacy syntax for historical context. + const srcRoot = path.resolve(__dirname, '../src'); + + function walk(dir: string, acc: string[] = []): string[] { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) walk(full, acc); + else if (entry.isFile() && /\.(ts|js|mjs|cjs)$/.test(entry.name)) acc.push(full); + } + return acc; + } + + it('no runtime .ts/.js code references `claude-flow@v3alpha` (comments and legacy-key recognition lists are OK)', () => { + const offenders: string[] = []; + for (const file of walk(srcRoot)) { + const text = fs.readFileSync(file, 'utf-8'); + const code = stripComments(text); + // Strip the legitimate appearances: + // (a) the legacy-key recognition list in detectExistingRufloMCP + // (b) the staleKeys array in writeMCPConfig + const stripped = code + .replace(/'claude-flow@v3alpha'\s+in\s+\w+/g, '') + .replace(/\['claude-flow@alpha',\s*'claude-flow@v3alpha'\]/g, ''); + if (/claude-flow@v3alpha/.test(stripped)) offenders.push(path.relative(srcRoot, file)); + } + expect(offenders).toEqual([]); + }); +}); + +// Force this file to be treated as a module so test isolation works under +// the project's vitest config without a tsconfig export tweak. +export {}; + +// Keep imports referenced even though we use them only for type-side checks. +void os; diff --git a/v3/@claude-flow/cli/src/commands/swarm.ts b/v3/@claude-flow/cli/src/commands/swarm.ts index d14374620b..2222080d78 100644 --- a/v3/@claude-flow/cli/src/commands/swarm.ts +++ b/v3/@claude-flow/cli/src/commands/swarm.ts @@ -511,7 +511,11 @@ const startCommand: Command = { } catch (err) { spinner.fail('MCP swarm_init failed — swarm metadata saved locally only'); output.writeln(output.dim(` Error: ${err instanceof Error ? err.message : String(err)}`)); - output.writeln(output.dim(' The MCP server may not be running. Start it with: claude mcp add claude-flow npx claude-flow@v3alpha mcp start')); + // #2370: the old hint referenced the deprecated `claude-flow@v3alpha` + // dist-tag which now resolves to a pre-rename package. Use the current + // `ruflo@latest` and force a fresh fetch with `-y` so npx doesn't pick + // a stale local install. + output.writeln(output.dim(' The MCP server may not be running. Start it with: claude mcp add claude-flow -- npx -y ruflo@latest mcp start')); } // Persist swarm state to disk so `swarm status` can read it diff --git a/v3/@claude-flow/cli/src/init/executor.ts b/v3/@claude-flow/cli/src/init/executor.ts index f061a5dcec..eba4738dda 100644 --- a/v3/@claude-flow/cli/src/init/executor.ts +++ b/v3/@claude-flow/cli/src/init/executor.ts @@ -839,7 +839,17 @@ function detectExistingRufloMCP(targetDir: string): string | null { // 'claude-flow', a second `ruflo init` must still recognise the existing install. if (parsed.mcpServers && typeof parsed.mcpServers === 'object') { const servers = parsed.mcpServers as Record; - if ('claude-flow' in servers || 'ruflo' in servers) return candidate; + // #2369: also recognise the legacy dist-tag keys generated by + // pre-rename installs (claude-flow ≤ 2.x). Without these the + // detection walks parent dirs, doesn't match, and writes a NEW + // claude-flow-keyed config — both servers then run under + // different prefixes producing duplicate-tool noise. + if ( + 'claude-flow' in servers || + 'ruflo' in servers || + 'claude-flow@alpha' in servers || + 'claude-flow@v3alpha' in servers + ) return candidate; } // (b) #1840: Claude Code project-scoped registrations under // parsed.projects[].mcpServers. Match by @@ -853,7 +863,13 @@ function detectExistingRufloMCP(targetDir: string): string | null { const projectMcp = (projectVal as { mcpServers?: unknown }).mcpServers; if (!projectMcp || typeof projectMcp !== 'object') continue; const mcp = projectMcp as Record; - if (!('claude-flow' in mcp) && !('ruflo' in mcp)) continue; + // #2369: legacy dist-tag keys also count as already-registered. + if ( + !('claude-flow' in mcp) && + !('ruflo' in mcp) && + !('claude-flow@alpha' in mcp) && + !('claude-flow@v3alpha' in mcp) + ) continue; if (targetAncestors.has(normalizeProjectKey(projectKey))) { return `${candidate} (projects[${projectKey}])`; } @@ -885,6 +901,27 @@ async function writeMCPConfig( const mcpPath = path.join(targetDir, '.mcp.json'); if (fs.existsSync(mcpPath) && !options.force) { + // #2369: an existing .mcp.json from a pre-rename install is the most + // common cause of "autopilot tools missing after init" reports. Parse + // the existing file and surface a loud, specific message naming the + // stale key so users know to either delete the file or re-run with + // --force. Without this they get a silent skip and no warning. + try { + const parsed = JSON.parse(fs.readFileSync(mcpPath, 'utf-8')) as { mcpServers?: Record }; + const servers = parsed?.mcpServers; + if (servers && typeof servers === 'object') { + const staleKeys = ['claude-flow@alpha', 'claude-flow@v3alpha'].filter(k => k in servers); + if (staleKeys.length > 0) { + result.skipped.push( + `.mcp.json (existing file uses deprecated key '${staleKeys[0]}' — autopilot/browser/wasm-agent tools will be missing; ` + + `delete .mcp.json and re-run, or re-run with --force to overwrite)` + ); + return; + } + } + } catch { + // Existing file isn't valid JSON — fall through to the generic skip. + } result.skipped.push('.mcp.json'); return; } diff --git a/v3/@claude-flow/cli/src/services/container-worker-pool.ts b/v3/@claude-flow/cli/src/services/container-worker-pool.ts index 617eea0125..bc3b1327e2 100644 --- a/v3/@claude-flow/cli/src/services/container-worker-pool.ts +++ b/v3/@claude-flow/cli/src/services/container-worker-pool.ts @@ -631,12 +631,18 @@ export class ContainerWorkerPool extends EventEmitter { } /** - * Build worker command for container execution + * Build worker command for container execution. + * + * #2371: the old command spawned `npx claude-flow@v3alpha daemon trigger`, + * which (a) referenced a deprecated dist-tag pointing at the pre-rename + * package, and (b) omitted `-y`, so npx could silently fall back to a + * locally-installed stale `claude-flow` without fetching the published + * version. Workers were running pre-autopilot / pre-browser builds. + * Use the current `ruflo@latest` and force a fresh resolution with `-y`. */ private buildWorkerCommand(options: ContainerExecutionOptions): string[] { - // Use npx to run claude-flow daemon trigger return [ - 'npx', 'claude-flow@v3alpha', + 'npx', '-y', 'ruflo@latest', 'daemon', 'trigger', '-w', options.workerType, '--headless',