π 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(migrate): correct removed-agent install suggestion and add 'migrate fix --agents' restore (#2985) (#2986)
Chris Phillipsondbd88254e358
diff --git a/v3/@claude-flow/cli/__tests__/migrate-agent-detection.test.ts b/v3/@claude-flow/cli/__tests__/migrate-agent-detection.test.tsindex c9e2b7e876..c72759a0e9 100644--- a/v3/@claude-flow/cli/__tests__/migrate-agent-detection.test.ts+++ b/v3/@claude-flow/cli/__tests__/migrate-agent-detection.test.ts@@ -57,7 +57,10 @@ describe('detectRemovedAgentGaps', () => {[...REMOVED_AGENTS.map(a => a.basename)].sort());for (const gap of gaps) {- expect(gap.installCommand).toBe(`ruflo plugins install ${gap.plugin}`);+ // #2985: must be the Claude Code marketplace command β `ruflo plugins+ // install` targets the npm-package plugin system and cannot install+ // these marketplace plugins.+ expect(gap.installCommand).toBe(`/plugin install ${gap.plugin}@ruflo`);}});diff --git a/v3/@claude-flow/cli/__tests__/migrate-agent-restore.test.ts b/v3/@claude-flow/cli/__tests__/migrate-agent-restore.test.tsnew file mode 100644index 0000000000..99665397e6--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/migrate-agent-restore.test.ts@@ -0,0 +1,132 @@+/**+ * #2985 β `ruflo migrate fix --agents` restore path.+ *+ * Same isolation discipline as migrate-agent-detection.test.ts: every test+ * gets a temp project and temp home, and the GitHub fallback is exercised+ * through an injected fetchImpl β no test touches the network or depends on+ * what is installed on the machine running the suite.+ */+import { describe, it, expect, vi } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { restoreRemovedAgents } from '../src/commands/migrate-agent-restore.js';+import type { RemovedAgentGap } from '../src/commands/migrate-agent-detection.js';++const CODER_GAP: RemovedAgentGap = {+ agent: 'coder.md',+ plugin: 'ruflo-core',+ installCommand: '/plugin install ruflo-core@ruflo',+};++const GOAL_GAP: RemovedAgentGap = {+ agent: 'goal-planner.md',+ plugin: 'ruflo-goals',+ installCommand: '/plugin install ruflo-goals@ruflo',+};++const PLUGIN_AGENT_CONTENT = [+ '---',+ 'name: coder',+ 'description: Implementation specialist',+ '---',+ 'Use mcp__plugin_ruflo-core_ruflo__memory_store to persist decisions.',+ '',+].join('\n');++function project(): string {+ return mkdtempSync(join(tmpdir(), 'migrate-agent-restore-'));+}++function emptyHome(): string {+ return mkdtempSync(join(tmpdir(), 'migrate-agent-restore-home-'));+}++function homeWithMarketplaceClone(plugin: string, basename: string, content: string): string {+ const home = emptyHome();+ const agentsDir = join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'plugins', plugin, 'agents');+ mkdirSync(agentsDir, { recursive: true });+ writeFileSync(join(agentsDir, basename), content);+ return home;+}++function failingFetch(): typeof fetch {+ return vi.fn(async () => ({ ok: false, status: 404, text: async () => '' })) as unknown as typeof fetch;+}++describe('restoreRemovedAgents', () => {+ it('restores from the marketplace clone, rewrites the namespace, and records provenance', async () => {+ const cwd = project();+ const homeDir = homeWithMarketplaceClone('ruflo-core', 'coder.md', PLUGIN_AGENT_CONTENT);++ const results = await restoreRemovedAgents(cwd, [CODER_GAP], { homeDir, fetchImpl: failingFetch() });++ expect(results).toEqual([+ expect.objectContaining({ agent: 'coder.md', status: 'restored', source: 'marketplace-clone' }),+ ]);+ const written = readFileSync(join(cwd, '.claude', 'agents', 'core', 'coder.md'), 'utf-8');+ expect(written).toContain('mcp__claude-flow__memory_store');+ expect(written).not.toContain('mcp__plugin_ruflo-core_ruflo__');+ expect(written).toContain('restored by `ruflo migrate fix --agents`');+ // Provenance lands after the frontmatter block, not before it.+ expect(written.startsWith('---\n')).toBe(true);+ });++ it('falls back to the GitHub tag URL, then main, when no local source exists', async () => {+ const cwd = project();+ const homeDir = emptyHome();+ const urls: string[] = [];+ const fetchImpl = vi.fn(async (url: string) => {+ urls.push(url);+ if (url.includes('/v9.9.9/')) return { ok: false, status: 404, text: async () => '' };+ return { ok: true, status: 200, text: async () => PLUGIN_AGENT_CONTENT };+ }) as unknown as typeof fetch;++ const results = await restoreRemovedAgents(cwd, [GOAL_GAP], { homeDir, fetchImpl, version: '9.9.9' });++ expect(results[0]).toEqual(+ expect.objectContaining({ agent: 'goal-planner.md', status: 'restored', source: 'github-main' })+ );+ expect(urls[0]).toBe('https://raw.githubusercontent.com/ruvnet/ruflo/v9.9.9/plugins/ruflo-goals/agents/goal-planner.md');+ expect(urls[1]).toBe('https://raw.githubusercontent.com/ruvnet/ruflo/main/plugins/ruflo-goals/agents/goal-planner.md');+ // goal-planner restores to its original init category.+ expect(existsSync(join(cwd, '.claude', 'agents', 'goal', 'goal-planner.md'))).toBe(true);+ });++ it('never overwrites an existing file', async () => {+ const cwd = project();+ const homeDir = homeWithMarketplaceClone('ruflo-core', 'coder.md', PLUGIN_AGENT_CONTENT);+ const dest = join(cwd, '.claude', 'agents', 'core');+ mkdirSync(dest, { recursive: true });+ writeFileSync(join(dest, 'coder.md'), 'hand-authored β do not touch\n');++ const results = await restoreRemovedAgents(cwd, [CODER_GAP], { homeDir, fetchImpl: failingFetch() });++ expect(results[0]).toEqual(expect.objectContaining({ agent: 'coder.md', status: 'skipped' }));+ expect(readFileSync(join(dest, 'coder.md'), 'utf-8')).toBe('hand-authored β do not touch\n');+ });++ it('reports failure with the marketplace-install alternative when offline and no local source', async () => {+ const cwd = project();+ const homeDir = emptyHome();+ const fetchImpl = vi.fn(async () => {+ throw new Error('network unreachable');+ }) as unknown as typeof fetch;++ const results = await restoreRemovedAgents(cwd, [CODER_GAP], { homeDir, fetchImpl });++ expect(results[0].status).toBe('failed');+ expect(results[0].error).toContain('/plugin install ruflo-core@ruflo');+ expect(existsSync(join(cwd, '.claude', 'agents', 'core', 'coder.md'))).toBe(false);+ });++ it('dry-run resolves and reports without writing', async () => {+ const cwd = project();+ const homeDir = homeWithMarketplaceClone('ruflo-core', 'coder.md', PLUGIN_AGENT_CONTENT);++ const results = await restoreRemovedAgents(cwd, [CODER_GAP], { homeDir, fetchImpl: failingFetch(), dryRun: true });++ expect(results[0]).toEqual(expect.objectContaining({ status: 'restored', source: 'marketplace-clone' }));+ expect(existsSync(join(cwd, '.claude', 'agents', 'core', 'coder.md'))).toBe(false);+ });+});diff --git a/v3/@claude-flow/cli/src/commands/migrate-agent-detection.ts b/v3/@claude-flow/cli/src/commands/migrate-agent-detection.tsindex 2cbffb07d3..c43d50ece2 100644--- a/v3/@claude-flow/cli/src/commands/migrate-agent-detection.ts+++ b/v3/@claude-flow/cli/src/commands/migrate-agent-detection.ts@@ -133,7 +133,11 @@ export function detectRemovedAgentGaps(gaps.push({agent: basename,plugin,- installCommand: `ruflo plugins install ${plugin}`,+ // #2985: these are Claude Code *marketplace* plugins. `ruflo plugins+ // install` targets a different system (the npm-package PluginManager β+ // see the module header) and cannot install them; the marketplace+ // command below is the one that satisfies the registry check above.+ installCommand: `/plugin install ${plugin}@ruflo`,});}diff --git a/v3/@claude-flow/cli/src/commands/migrate-agent-restore.ts b/v3/@claude-flow/cli/src/commands/migrate-agent-restore.tsnew file mode 100644index 0000000000..d39385e234--- /dev/null+++ b/v3/@claude-flow/cli/src/commands/migrate-agent-restore.ts@@ -0,0 +1,249 @@+/**+ * ADR-382 Part B follow-up (#2985) β `ruflo migrate fix --agents`: actually+ * restore the agents ADR-128 Phase 2 removed from the init template, instead+ * of only pointing at them.+ *+ * Content resolution order (first hit wins):+ * 1. The Claude Code marketplace clone, when present β+ * ~/.claude/plugins/marketplaces/ruflo/plugins/<plugin>/agents/<basename>+ * 2. A repo checkout at the project root (dogfood / development) β+ * <cwd>/plugins/<plugin>/agents/<basename>+ * 3. GitHub raw, pinned to this CLI's own version tag (v<version>), falling+ * back to `main` when the tag predates the file. Requires network; the+ * failure message says so explicitly.+ *+ * npm-track consideration: plugin agent bodies reference the+ * `mcp__plugin_ruflo-core_ruflo__*` tool namespace, which only resolves when+ * ruflo-core is installed as a Claude Code marketplace plugin. A user+ * reaching for this command is on the npm track (otherwise the owning plugin+ * would cover the gap and no restore would be offered), so restored copies+ * are rewritten to the canonical `claude-flow` server key (#2206). The+ * rewrite is annotated in a provenance comment inside the restored file.+ *+ * Kept in a sibling module (not migrate.ts) for the same reason as+ * migrate-agent-detection.ts β migrate.ts is over the 500-line budget.+ */+import * as fs from 'fs';+import * as path from 'path';+import * as os from 'os';+import { fileURLToPath } from 'node:url';+import type { RemovedAgentGap } from './migrate-agent-detection.js';++// Same local-reader pattern as mcp-tools/system-tools.ts β avoids importing+// from ../index.js (cycle risk) just for a version string.+function getPackageVersion(): string | undefined {+ try {+ const dir = path.dirname(fileURLToPath(import.meta.url));+ for (const depth of ['../..', '../../..']) {+ const pkgPath = path.join(dir, depth, 'package.json');+ if (fs.existsSync(pkgPath)) {+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));+ if (pkg.name?.includes('claude-flow') || pkg.name === 'ruflo') {+ return pkg.version;+ }+ }+ }+ return undefined;+ } catch {+ return undefined;+ }+}++/** Marketplace plugin namespace prefix β resolves only under a marketplace install. */+const PLUGIN_NAMESPACE_PREFIX = 'mcp__plugin_ruflo-core_ruflo__';+/** Canonical npm-track namespace for the same server (key `claude-flow`, #2206). */+const CANONICAL_NAMESPACE_PREFIX = 'mcp__claude-flow__';++/**+ * Where each removed agent lived in the init template before ADR-128 Phase 2+ * deleted it (see the ADR's Gap 2 table). Restoring to the original category+ * keeps category-based tooling (e.g. `--agents=<cat>` style filters) working.+ */+const RESTORE_CATEGORY: Record<string, string> = {+ 'coder.md': 'core',+ 'researcher.md': 'core',+ 'reviewer.md': 'core',+ 'tester.md': 'core',+ 'memory-specialist.md': 'v3',+ 'security-auditor.md': 'v3',+ 'sparc-orchestrator.md': 'v3',+ 'adr-architect.md': 'v3',+ 'goal-planner.md': 'goal',+};++const GITHUB_RAW_BASE = 'https://raw.githubusercontent.com/ruvnet/ruflo';++export type RestoreSource = 'marketplace-clone' | 'repo-checkout' | 'github-tag' | 'github-main';++export interface RestoreResult {+ agent: string;+ plugin: string;+ status: 'restored' | 'skipped' | 'failed';+ /** Where the content came from (set when status === 'restored'). */+ source?: RestoreSource;+ /** Project-relative path written (set when status === 'restored' | 'skipped'). */+ path?: string;+ /** Human-readable failure reason (set when status === 'failed'). */+ error?: string;+}++export interface RestoreRemovedAgentsOptions {+ /** Test injection: overrides os.homedir() for the marketplace-clone probe. */+ homeDir?: string;+ /** Test injection: overrides global fetch for the GitHub fallback. */+ fetchImpl?: typeof fetch;+ /** CLI version used to pin the GitHub tag (e.g. "3.38.1" -> tag v3.38.1). */+ version?: string;+ /** Report what would be written without writing. */+ dryRun?: boolean;+}++function findFileRecursive(dir: string, basename: string, depth: number): string | null {+ if (depth > 4) return null;+ let entries: fs.Dirent[];+ try {+ entries = fs.readdirSync(dir, { withFileTypes: true });+ } catch {+ return null;+ }+ for (const entry of entries) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ const hit = findFileRecursive(full, basename, depth + 1);+ if (hit) return hit;+ } else if (entry.isFile() && entry.name === basename) {+ return full;+ }+ }+ return null;+}++function readLocalCandidate(root: string, plugin: string, basename: string): string | null {+ const agentsDir = path.join(root, 'plugins', plugin, 'agents');+ const hit = findFileRecursive(agentsDir, basename, 0);+ if (!hit) return null;+ try {+ return fs.readFileSync(hit, 'utf-8');+ } catch {+ return null;+ }+}++async function fetchGithubCandidate(+ fetchImpl: typeof fetch,+ ref: string,+ plugin: string,+ basename: string+): Promise<string | null> {+ const url = `${GITHUB_RAW_BASE}/${ref}/plugins/${plugin}/agents/${basename}`;+ try {+ const res = await fetchImpl(url);+ if (!res.ok) return null;+ return await res.text();+ } catch {+ return null;+ }+}++/**+ * Rewrite the marketplace-plugin tool namespace to the canonical npm-track+ * one and record provenance right after the frontmatter block, so a reader+ * (or a future dedup pass) can tell a restored copy from a hand-authored+ * agent. Inserting after the closing `---` keeps frontmatter parseable.+ */+function adaptForNpmTrack(content: string, plugin: string, source: RestoreSource): string {+ const rewritten = content.split(PLUGIN_NAMESPACE_PREFIX).join(CANONICAL_NAMESPACE_PREFIX);+ const provenance =+ `<!-- restored by \`ruflo migrate fix --agents\` from plugins/${plugin} ` ++ `(canonical per ADR-128; source: ${source}); MCP namespace rewritten to the ` ++ `canonical claude-flow server key (#2206, #2985) -->`;+ const fmClose = rewritten.indexOf('\n---', rewritten.startsWith('---') ? 3 : 0);+ if (rewritten.startsWith('---') && fmClose !== -1) {+ const insertAt = rewritten.indexOf('\n', fmClose + 1);+ if (insertAt !== -1) {+ return rewritten.slice(0, insertAt + 1) + provenance + '\n' + rewritten.slice(insertAt + 1);+ }+ }+ return provenance + '\n' + rewritten;+}++async function resolveContent(+ cwd: string,+ homeDir: string,+ fetchImpl: typeof fetch,+ version: string | undefined,+ plugin: string,+ basename: string+): Promise<{ content: string; source: RestoreSource } | null> {+ const marketplaceRoot = path.join(homeDir, '.claude', 'plugins', 'marketplaces', 'ruflo');+ const fromMarketplace = readLocalCandidate(marketplaceRoot, plugin, basename);+ if (fromMarketplace !== null) return { content: fromMarketplace, source: 'marketplace-clone' };++ const fromCheckout = readLocalCandidate(cwd, plugin, basename);+ if (fromCheckout !== null) return { content: fromCheckout, source: 'repo-checkout' };++ if (version) {+ const fromTag = await fetchGithubCandidate(fetchImpl, `v${version}`, plugin, basename);+ if (fromTag !== null) return { content: fromTag, source: 'github-tag' };+ }+ const fromMain = await fetchGithubCandidate(fetchImpl, 'main', plugin, basename);+ if (fromMain !== null) return { content: fromMain, source: 'github-main' };++ return null;+}++/**+ * Restore each gap's agent file into <cwd>/.claude/agents/<category>/.+ * Never overwrites an existing file (detection already excludes present+ * basenames anywhere under .claude/agents/, but re-check defensively).+ */+export async function restoreRemovedAgents(+ cwd: string,+ gaps: RemovedAgentGap[],+ options: RestoreRemovedAgentsOptions = {}+): Promise<RestoreResult[]> {+ const homeDir = options.homeDir ?? os.homedir();+ const fetchImpl = options.fetchImpl ?? fetch;+ const version = options.version ?? getPackageVersion();+ const results: RestoreResult[] = [];++ for (const gap of gaps) {+ const category = RESTORE_CATEGORY[gap.agent] ?? 'core';+ const relPath = path.join('.claude', 'agents', category, gap.agent);+ const destPath = path.join(cwd, relPath);++ if (fs.existsSync(destPath)) {+ results.push({ agent: gap.agent, plugin: gap.plugin, status: 'skipped', path: relPath });+ continue;+ }++ const resolved = await resolveContent(cwd, homeDir, fetchImpl, version, gap.plugin, gap.agent);+ if (!resolved) {+ results.push({+ agent: gap.agent,+ plugin: gap.plugin,+ status: 'failed',+ error:+ 'no local marketplace clone or repo checkout, and GitHub fetch failed ' ++ '(offline?) β install the owning plugin instead: ' ++ `/plugin install ${gap.plugin}@ruflo`,+ });+ continue;+ }++ const adapted = adaptForNpmTrack(resolved.content, gap.plugin, resolved.source);+ if (!options.dryRun) {+ fs.mkdirSync(path.dirname(destPath), { recursive: true });+ fs.writeFileSync(destPath, adapted, 'utf-8');+ }+ results.push({+ agent: gap.agent,+ plugin: gap.plugin,+ status: 'restored',+ source: resolved.source,+ path: relPath,+ });+ }++ return results;+}diff --git a/v3/@claude-flow/cli/src/commands/migrate.ts b/v3/@claude-flow/cli/src/commands/migrate.tsindex ea8edbf27a..e16d1bea6b 100644--- a/v3/@claude-flow/cli/src/commands/migrate.ts+++ b/v3/@claude-flow/cli/src/commands/migrate.ts@@ -8,6 +8,7 @@ import { output } from '../output.js';import * as fs from 'fs';import * as path from 'path';import { detectRemovedAgentGaps, type RemovedAgentMapping } from './migrate-agent-detection.js';+import { restoreRemovedAgents } from './migrate-agent-restore.js';// Migration targetsconst MIGRATION_TARGETS = [@@ -188,6 +189,9 @@ const statusCommand: Command = {output.printInfo(`${removedAgentGaps.length} agent(s) removed by ADR-128 are missing from .claude/agents/ and not covered by an installed plugin.`);+ output.printInfo(+ 'Run "ruflo migrate fix --agents" to restore them from their canonical plugin content, or install the owning plugin.'+ );}return { success: true, data: { components, needsMigration, removedAgentGaps } };@@ -755,16 +759,88 @@ const breakingCommand: Command = {}};+// Fix command β apply remediations that `status` can only point at (#2985).+// Logic lives in migrate-agent-restore.ts (migrate.ts is over the 500-line+// budget; same split as migrate-agent-detection.ts).+const fixCommand: Command = {+ name: 'fix',+ description: 'Apply fixes for gaps detected by "migrate status"',+ options: [+ {+ name: 'agents',+ description: 'Restore agents removed by ADR-128 from their canonical plugin content',+ type: 'boolean',+ default: false+ },+ {+ name: 'dry-run',+ short: 'd',+ description: 'Show what would be restored without writing',+ type: 'boolean',+ default: false+ }+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const cwd = ctx.cwd || process.cwd();++ if (!ctx.flags.agents) {+ output.printInfo('Nothing selected. Pass --agents to restore ADR-128-removed agents.');+ return { success: true };+ }++ const gaps = detectRemovedAgentGaps(cwd, REMOVED_AGENTS);+ if (gaps.length === 0) {+ output.printSuccess('No removed-agent gaps to fix β every agent is present or covered by an installed plugin.');+ return { success: true, data: { results: [] } };+ }++ const dryRun = Boolean(ctx.flags['dry-run']);+ const results = await restoreRemovedAgents(cwd, gaps, { dryRun });++ if (ctx.flags.format === 'json') {+ output.printJson({ dryRun, results });+ return { success: results.every(r => r.status !== 'failed'), data: { dryRun, results } };+ }++ output.writeln();+ output.writeln(output.bold(dryRun ? 'Restore Plan (dry run)' : 'Restored Agents'));+ output.printTable({+ columns: [+ { key: 'agent', header: 'Agent', width: 24 },+ { key: 'status', header: 'Status', width: 10 },+ { key: 'detail', header: dryRun ? 'Would write' : 'Detail', width: 44 }+ ],+ data: results.map(r => ({+ agent: r.agent,+ status: r.status === 'failed' ? output.warning(r.status) : r.status,+ detail: r.status === 'failed' ? output.dim(r.error ?? '') : output.dim(`${r.path ?? ''}${r.source ? ` (from ${r.source})` : ''}`)+ })),+ border: false+ });++ const failed = results.filter(r => r.status === 'failed');+ output.writeln();+ if (failed.length > 0) {+ output.printWarning(`${failed.length} agent(s) could not be restored β install the owning plugin instead (see table).`);+ } else if (!dryRun) {+ output.printSuccess(`${results.filter(r => r.status === 'restored').length} agent(s) restored. Re-run "ruflo migrate status" to verify.`);+ }++ return { success: failed.length === 0, data: { dryRun, results } };+ }+};+// Main migrate commandexport const migrateCommand: Command = {name: 'migrate',description: 'V2 to V3 migration tools',- subcommands: [statusCommand, runCommand, verifyCommand, rollbackCommand, breakingCommand],+ subcommands: [statusCommand, runCommand, verifyCommand, rollbackCommand, breakingCommand, fixCommand],options: [],examples: [{ command: 'claude-flow migrate status', description: 'Check migration status' },{ command: 'claude-flow migrate run --dry-run', description: 'Preview migration' },- { command: 'claude-flow migrate run -t all', description: 'Run full migration' }+ { command: 'claude-flow migrate run -t all', description: 'Run full migration' },+ { command: 'claude-flow migrate fix --agents', description: 'Restore ADR-128-removed agents' }],action: async (ctx: CommandContext): Promise<CommandResult> => {output.writeln();@@ -778,7 +854,8 @@ export const migrateCommand: Command = {`${output.highlight('run')} - Run migration`,`${output.highlight('verify')} - Verify migration integrity`,`${output.highlight('rollback')} - Rollback to previous version`,- `${output.highlight('breaking')} - Show breaking changes`+ `${output.highlight('breaking')} - Show breaking changes`,+ `${output.highlight('fix')} - Apply fixes for detected gaps (--agents)`]);return { success: true };