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(mods): install the ruflo-mods plugin, and fail doctor when Claude Code cannot resolve it

ruv6b8558ad9943
diff --git a/plugins/ruflo-mods/README.md b/plugins/ruflo-mods/README.md
index 6e1e3f3729..f8279ede36 100644
--- a/plugins/ruflo-mods/README.md
+++ b/plugins/ruflo-mods/README.md
@@ -3,11 +3,24 @@
ruflo as a Claude Code mod (function hooks): on by default in Claude Code >= 2.1.287; from 2.1.277 with `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1`. Design and evidence: [ADR-404](../../v3/docs/adr/ADR-404-claude-code-mods-function-hooks.md).
```bash
-ruflo mods install # opt in for this project (.claude/settings.local.json)
-ruflo mods doctor # function hooks on? refused by policy? what does it own?
+ruflo mods install # opt in for this project (.claude/settings.local.json) and install the plugin
+ruflo mods doctor # plugin installed? function hooks on? refused by policy? what does it own?
ruflo mods uninstall # remove only what install added
```
+`ruflo mods install` writes `enabledPlugins["ruflo-mods@ruflo"]` and the `ruflo` marketplace into settings, then installs the plugin the way you would by hand, when a `claude` binary is on PATH:
+
+```bash
+claude plugin marketplace update ruflo # or, first time: claude plugin marketplace add ruvnet/ruflo --scope local
+claude plugin install ruflo-mods@ruflo --scope local # in the project directory (--scope project after `ruflo mods install --scope project`)
+```
+
+Settings alone are not enough. Claude Code installs from its local clone of the `ruflo` marketplace (`~/.claude/plugins/marketplaces/ruflo`, or under `$CLAUDE_CONFIG_DIR`), and a clone from before ruflo-mods shipped has no `plugins/ruflo-mods`. Claude Code then skips the enabled plugin without a word, and `/ruflo-mods` is an unknown command. `ruflo mods status` and `ruflo mods doctor` report this as two findings, `ruflo marketplace` and `ruflo-mods installed`, with the exact commands to run.
+
+- `--no-plugin-install` writes settings only and runs no `claude` command.
+- `--dry-run` prints the settings and the `claude` commands without running either.
+- If `claude` is missing or a step fails, install prints the manual commands and still exits 0. Pass `--strict` to exit 1 instead.
+
In a session, `/ruflo-mods` reports what the mod owns, routed, recorded and tightened.
## What it does
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.ts
index 0f220330a0..dd0a19b847 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.ts
@@ -20,7 +20,7 @@ function isolated() {
mkdirSync(bin, { recursive: true });
writeFileSync(join(bin, 'codex'), '#!/bin/sh\nexit 1\n');
chmodSync(join(bin, 'codex'), 0o755);
- const env = { ...process.env, HOME: home, USERPROFILE: home, CODEX_HOME: join(home, '.codex'), PATH: `${bin}${delimiter}${process.env.PATH ?? ''}`, CI: '1' };
+ const env = { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: join(home, '.claude'), CODEX_HOME: join(home, '.codex'), PATH: `${bin}${delimiter}${process.env.PATH ?? ''}`, CI: '1' };
const run = (...args: string[]) => execFileSync(process.execPath, [CLI_BIN, ...args], { cwd, env, encoding: 'utf8', timeout: 120_000 });
return { home, cwd, run, done: () => { rmSync(home, { recursive: true, force: true }); rmSync(cwd, { recursive: true, force: true }); } };
}
@@ -36,9 +36,22 @@ describe.skipIf(!CLI_BUILT)('ADR-404 mods through the built CLI', () => {
const shared = JSON.parse(readFileSync(join(t.cwd, '.claude', 'settings.json'), 'utf8'));
expect(JSON.stringify(shared.hooks.UserPromptSubmit)).toContain('hook-handler.cjs');
- expect(t.run('doctor', '--component', 'mods')).toContain('ruflo mods (ADR-404)');
+ // Enabled in settings, but this isolated HOME has no ruflo marketplace
+ // clone and nothing installed: Claude Code would skip the plugin, so
+ // doctor fails with the exact commands instead of reporting it fine.
+ let doctor: { status?: number; stdout?: string } = {};
+ try {
+ t.run('doctor', '--component', 'mods');
+ } catch (error) {
+ doctor = error as typeof doctor;
+ }
+ expect(doctor.status).toBe(1);
+ expect(doctor.stdout).toContain('ruflo mods (ADR-404)');
+ expect(doctor.stdout).toContain('ruflo-mods installed: not installed for this project');
const status = JSON.parse(t.run('mods', 'status', '--json').replace(/^[^[]*/, ''));
- expect(status.find((f: { name: string }) => f.name === 'ruflo-mods plugin').status).toBe('pass');
+ const named = (name: string) => status.find((f: { name: string }) => f.name === name);
+ expect(named('ruflo-mods plugin').status).toBe('pass'); // enabled in settings
+ expect(named('ruflo-mods installed')).toMatchObject({ status: 'fail', fix: expect.stringContaining('claude plugin install ruflo-mods@ruflo --scope local') });
t.run('mods', 'uninstall');
expect(JSON.parse(readFileSync(join(t.cwd, '.claude', 'settings.local.json'), 'utf8'))).toEqual({});
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-cli.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-cli.test.ts
index b29209ef5d..fa3cde4dd7 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-cli.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-cli.test.ts
@@ -9,7 +9,7 @@ import { join } from 'node:path';
import { installMod, uninstallMod, withModEnabled, withModRemoved, ENABLE_ENV, MOD_PLUGIN_ID } from '../../src/mods/install.js';
import { projectionOf, syncPolicyProjection, PROJECTION_RELATIVE } from '../../src/mods/policy-projection.js';
-import { probeMods } from '../../src/mods/probe.js';
+import { probeMods, type Finding } from '../../src/mods/probe.js';
import { findClaudeInstalls, judgeInstalls, versionLess } from '../../src/mods/claude-installs.js';
import { modsCommand } from '../../src/commands/mods.js';
import { setPolicyMode, upsertPolicyRule } from '../../src/services/policy-runtime.js';
@@ -163,15 +163,81 @@ describe('ADR-404 mods probe and doctor', () => {
expect(finding('policy projection')).toMatchObject({ status: 'warn', fix: 'ruflo mods sync-policy' });
});
- it('the command runs install, status, doctor and uninstall', async () => {
+ describe('the command', () => {
const sub = (name: string) => modsCommand.subcommands!.find((s) => s.name === name)!;
const ctx = (flags: Record<string, unknown> = {}) => ({ args: [], flags: { projectRoot: root, ...flags }, cwd: root, interactive: false }) as any;
- expect((await sub('install').action!(ctx())).success).toBe(true);
- expect((await sub('install').action!(ctx({ scope: 'global' }))).success).toBe(false);
- const doctor = await sub('doctor').action!(ctx({ json: true }));
- expect(doctor.exitCode).toBe(0);
- expect((await sub('uninstall').action!(ctx())).success).toBe(true);
- expect(read(join(root, '.claude', 'settings.local.json'))).toEqual({});
+ const saved = { PATH: process.env.PATH, HOME: process.env.HOME, CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR };
+ let bin: string;
+ // Never the real ~/.claude or a real claude: an isolated config dir, HOME and PATH.
+ beforeEach(() => {
+ bin = join(home, 'bin');
+ mkdirSync(bin, { recursive: true });
+ process.env.PATH = bin;
+ process.env.HOME = home;
+ process.env.CLAUDE_CONFIG_DIR = join(home, 'cfg');
+ });
+ afterEach(() => {
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ });
+ /** A stand-in claude: records its argv; with ok=true it installs the plugin the way Claude Code records it. */
+ const fakeClaude = (ok: boolean) => {
+ const cfg = join(home, 'cfg', 'plugins');
+ const script = ok
+ ? `#!/bin/sh
+echo "$@" >> "${home}/calls"
+case "$2" in
+ marketplace) /bin/mkdir -p "${cfg}/marketplaces/ruflo/plugins/ruflo-mods/.claude-plugin" && echo '{}' > "${cfg}/marketplaces/ruflo/plugins/ruflo-mods/.claude-plugin/plugin.json"
+ printf '{"ruflo":{"installLocation":"%s"}}' "${cfg}/marketplaces/ruflo" > "${cfg}/known_marketplaces.json" ;;
+ install) /bin/mkdir -p "${cfg}/cache/m" && printf '{"version":2,"plugins":{"ruflo-mods@ruflo":[{"scope":"local","installPath":"%s","projectPath":"%s"}]}}' "${cfg}/cache/m" "$(pwd)" > "${cfg}/installed_plugins.json" ;;
+esac
+`
+ : `#!/bin/sh\necho "$@" >> "${home}/calls"\necho "network down" >&2\nexit 1\n`;
+ writeFileSync(join(bin, 'claude'), script, { mode: 0o755 });
+ };
+ // Only the plugin commands; status also asks each claude its --version.
+ const calls = () => (existsSync(join(home, 'calls')) ? readFileSync(join(home, 'calls'), 'utf8').trim().split('\n').filter((l) => l.startsWith('plugin ')) : []);
+
+ it('runs install, status, doctor and uninstall (--no-plugin-install: settings only)', async () => {
+ fakeClaude(true);
+ expect((await sub('install').action!(ctx({ pluginInstall: false }))).success).toBe(true);
+ expect(calls()).toEqual([]);
+ expect((await sub('install').action!(ctx({ scope: 'global' }))).success).toBe(false);
+ // Enabled in settings but not resolvable: status reports (exit 0), doctor fails.
+ const status = await sub('status').action!(ctx({ json: true }));
+ expect(status.success).toBe(true);
+ expect((status.data as Finding[]).find((f) => f.name === 'ruflo-mods installed')!.status).toBe('fail');
+ expect((await sub('doctor').action!(ctx({ json: true }))).exitCode).toBe(1);
+ expect((await sub('uninstall').action!(ctx())).success).toBe(true);
+ expect(read(join(root, '.claude', 'settings.local.json'))).toEqual({});
+ });
+
+ it('install makes the plugin resolvable: adds the marketplace at the scope, installs, and doctor passes the check', async () => {
+ fakeClaude(true);
+ const r = await sub('install').action!(ctx());
+ expect(r).toMatchObject({ success: true, data: { resolvable: true } });
+ expect(calls()).toEqual(['plugin marketplace add ruvnet/ruflo --scope local', 'plugin install ruflo-mods@ruflo --scope local']);
+ const findings = (await sub('status').action!(ctx({ json: true }))).data as Finding[];
+ expect(findings.filter((f) => f.name === 'ruflo marketplace' || f.name === 'ruflo-mods installed').map((f) => f.status)).toEqual(['pass', 'pass']);
+ // Second run: the marketplace is known now, so it is updated, not re-added.
+ await sub('install').action!(ctx());
+ expect(calls()[2]).toBe('plugin marketplace update ruflo');
+ });
+
+ it('a failed repair prints the manual commands; exit 1 only with --strict', async () => {
+ fakeClaude(false);
+ expect(await sub('install').action!(ctx())).toMatchObject({ success: true, data: { resolvable: false } });
+ expect(await sub('install').action!(ctx({ strict: true }))).toMatchObject({ success: false, exitCode: 1 });
+ expect(calls()).toHaveLength(2); // stopped at the marketplace step each time
+ });
+
+ it('no claude on PATH: settings are still written, the repair is reported as manual', async () => {
+ const r = await sub('install').action!(ctx({ strict: true }));
+ expect(r).toMatchObject({ success: false, exitCode: 1, data: { resolvable: false } });
+ expect(read(join(root, '.claude', 'settings.local.json')).enabledPlugins[MOD_PLUGIN_ID]).toBe(true);
+ });
});
});
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-plugin-resolve.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-plugin-resolve.test.ts
new file mode 100644
index 0000000000..8c6671d001
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-plugin-resolve.test.ts
@@ -0,0 +1,185 @@
+/**
+ * ADR-404 — whether Claude Code can resolve the enabled ruflo-mods plugin
+ * (stale marketplace clone, nothing installed), and the repair `mods install`
+ * runs. Mock-first: a fake filesystem and a fake execFile; nothing here reads
+ * the real ~/.claude or runs a real claude.
+ */
+import { describe, it, expect } from 'vitest';
+import { join } from 'node:path';
+
+import {
+ claudeConfigDir,
+ installedState,
+ marketplaceState,
+ repairCommands,
+ resolveFindings,
+ MOD_PLUGIN_MANIFEST,
+ type ReadFs,
+} from '../../src/mods/plugin-resolve.js';
+import { repairArgv, repairPluginInstall, INSTALL_TIMEOUT_MS, MARKETPLACE_TIMEOUT_MS, type Exec } from '../../src/mods/plugin-repair.js';
+import { probeMods } from '../../src/mods/probe.js';
+
+const CFG = '/cfg';
+const ROOT = '/work/proj';
+const CLONE = join(CFG, 'plugins', 'marketplaces', 'ruflo');
+const CACHE = join(CFG, 'plugins', 'cache', 'ruflo', 'ruflo-mods', '0.1.0');
+
+/** A fake filesystem: paths that exist, and the text of the JSON files among them. */
+function fakeFs(files: Record<string, unknown>, dirs: string[] = []): ReadFs {
+ const exists = new Set([...Object.keys(files), ...dirs]);
+ return {
+ exists: (p) => exists.has(p),
+ readText: (p) => (p in files ? (typeof files[p] === 'string' ? (files[p] as string) : JSON.stringify(files[p])) : undefined),
+ };
+}
+
+const known = { [join(CFG, 'plugins', 'known_marketplaces.json')]: { ruflo: { source: { source: 'github', repo: 'ruvnet/ruflo' }, installLocation: CLONE } } };
+const freshClone = { [join(CLONE, MOD_PLUGIN_MANIFEST)]: '{"name":"ruflo-mods"}' };
+const installedHere = (entry: Record<string, unknown> = {}) => ({
+ [join(CFG, 'plugins', 'installed_plugins.json')]: { version: 2, plugins: { 'ruflo-mods@ruflo': [{ scope: 'local', installPath: CACHE, projectPath: ROOT, ...entry }] } },
+});
+
+describe('ADR-404 plugin resolution: marketplace clone', () => {
+ it('a missing clone: not known, no location', () => {
+ expect(marketplaceState(CFG, fakeFs({}))).toEqual({ known: false, location: null, hasMod: false });
+ });
+
+ it('a stale clone (predates ruflo-mods) is found but has no plugin', () => {
+ expect(marketplaceState(CFG, fakeFs(known, [CLONE]))).toEqual({ known: true, location: CLONE, hasMod: false });
+ });
+
+ it('a fresh clone carries plugins/ruflo-mods/.claude-plugin/plugin.json', () => {
+ expect(marketplaceState(CFG, fakeFs({ ...known, ...freshClone }, [CLONE]))).toEqual({ known: true, location: CLONE, hasMod: true });
+ });
+
+ it('follows installLocation from known_marketplaces.json, else the default clone path', () => {
+ const elsewhere = '/elsewhere/ruflo';
+ const fs = fakeFs({ [join(CFG, 'plugins', 'known_marketplaces.json')]: { ruflo: { installLocation: elsewhere } }, [join(elsewhere, MOD_PLUGIN_MANIFEST)]: '{}' }, [elsewhere]);
+ expect(marketplaceState(CFG, fs)).toMatchObject({ location: elsewhere, hasMod: true });
+ expect(marketplaceState(CFG, fakeFs({}, [CLONE]))).toMatchObject({ known: false, location: CLONE });
+ });
+
+ it('respects CLAUDE_CONFIG_DIR', () => {
+ expect(claudeConfigDir({ CLAUDE_CONFIG_DIR: '/x' }, '/home/u')).toBe('/x');
+ expect(claudeConfigDir({}, '/home/u')).toBe(join('/home/u', '.claude'));
+ });
+});
+
+describe('ADR-404 plugin resolution: installed for this project', () => {
+ it('local scope counts only for its own project, and only while its cache dir exists', () => {
+ expect(installedState(ROOT, CFG, fakeFs(installedHere(), [CACHE]))).toMatchObject({ installed: true, scope: 'local' });
+ expect(installedState('/work/other', CFG, fakeFs(installedHere(), [CACHE])).installed).toBe(false);
+ expect(installedState(ROOT, CFG, fakeFs(installedHere())).installed).toBe(false);
+ });
+
+ it('user scope counts everywhere', () => {
+ expect(installedState('/anywhere', CFG, fakeFs(installedHere({ scope: 'user', projectPath: undefined }), [CACHE])).installed).toBe(true);
+ });
+
+ it('no record, or a malformed one, is not installed', () => {
+ expect(installedState(ROOT, CFG, fakeFs({})).installed).toBe(false);
+ expect(installedState(ROOT, CFG, fakeFs({ [join(CFG, 'plugins', 'installed_plugins.json')]: '{ broken' })).installed).toBe(false);
+ });
+});
+
+describe('ADR-404 plugin resolution: findings', () => {
+ const byName = (findings: ReturnType<typeof resolveFindings>) => Object.fromEntries(findings.map((f) => [f.name, f]));
+
+ it('the reported bug: stale clone, nothing installed — both FAIL with the exact commands', () => {
+ const f = byName(resolveFindings(ROOT, 'local', CFG, fakeFs(known, [CLONE])));
+ expect(f['ruflo marketplace']).toMatchObject({ status: 'fail', message: expect.stringContaining('is stale') });
+ expect(f['ruflo-mods installed'].status).toBe('fail');
+ expect(f['ruflo-mods installed'].fix).toBe(`cd "${ROOT}" && claude plugin marketplace update ruflo && claude plugin install ruflo-mods@ruflo --scope local`);
+ });
+
+ it('missing clone: the fix adds the marketplace at the same scope', () => {
+ const f = byName(resolveFindings(ROOT, 'project', CFG, fakeFs({})));
+ expect(f['ruflo marketplace']).toMatchObject({ status: 'fail', message: expect.stringContaining('no local clone') });
+ expect(f['ruflo marketplace'].fix).toContain('claude plugin marketplace add ruvnet/ruflo --scope project');
+ });
+
+ it('fresh clone but not installed: marketplace passes, install fails', () => {
+ const f = byName(resolveFindings(ROOT, 'local', CFG, fakeFs({ ...known, ...freshClone }, [CLONE])));
+ expect(f['ruflo marketplace'].status).toBe('pass');
+ expect(f['ruflo-mods installed'].status).toBe('fail');
+ });
+
+ it('installed from the cache with a stale clone still loads: warn, not fail', () => {
+ const f = byName(resolveFindings(ROOT, 'local', CFG, fakeFs({ ...known, ...installedHere() }, [CLONE, CACHE])));
+ expect(f['ruflo marketplace'].status).toBe('warn');
+ expect(f['ruflo-mods installed'].status).toBe('pass');
+ });
+
+ it('fresh and installed: all pass', () => {
+ const findings = resolveFindings(ROOT, 'local', CFG, fakeFs({ ...known, ...freshClone, ...installedHere() }, [CLONE, CACHE]));
+ expect(findings.every((x) => x.status === 'pass')).toBe(true);
+ });
+
+ it('repairCommands quotes the project root', () => {
+ expect(repairCommands('/a b/c', 'local', true)[0]).toBe('cd "/a b/c"');
+ });
+});
+
+describe('ADR-404 mods status distinguishes enabled-in-settings from resolvable', () => {
+ it('probeMods adds the resolution findings only once the plugin is enabled', async () => {
+ const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const root = mkdtempSync(join(tmpdir(), 'ruflo-mods-resolve-'));
+ try {
+ const probe = () => probeMods({ projectRoot: root, home: root, env: {}, managedPath: join(root, 'none'), installs: [], configDir: CFG, fs: fakeFs(known, [CLONE]) });
+ expect(probe().map((f) => f.name)).not.toContain('ruflo-mods installed');
+ mkdirSync(join(root, '.claude'), { recursive: true });
+ writeFileSync(join(root, '.claude', 'settings.local.json'), JSON.stringify({ enabledPlugins: { 'ruflo-mods@ruflo': true } }));
+ const findings = probe();
+ expect(findings.find((f) => f.name === 'ruflo-mods plugin')!.message).toMatch(/^enabled in settings/);
+ expect(findings.find((f) => f.name === 'ruflo-mods installed')).toMatchObject({ status: 'fail', fix: expect.stringContaining('--scope local') });
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('ADR-404 repair on install', () => {
+ type Call = { file: string; args: readonly string[]; cwd: string; timeout: number };
+ const fakeExec = (codes: number[]) => {
+ const calls: Call[] = [];
+ const exec: Exec = async (file, args, opts) => {
+ calls.push({ file, args, cwd: opts.cwd, timeout: opts.timeout });
+ const code = codes[calls.length - 1] ?? 0;
+ return { code, stdout: code === 0 ? 'ok' : '', stderr: code === 0 ? '' : 'Marketplace not reachable' };
+ };
+ return { exec, calls };
+ };
+
+ it('known marketplace: update, then install at the scope, fixed argv in the project dir', async () => {
+ const { exec, calls } = fakeExec([0, 0]);
+ const r = await repairPluginInstall({ projectRoot: ROOT, scope: 'local', marketplaceKnown: true, claude: '/bin/claude', exec, env: {} });
+ expect(r.ok).toBe(true);
+ expect(calls).toEqual([
+ { file: '/bin/claude', args: ['plugin', 'marketplace', 'update', 'ruflo'], cwd: ROOT, timeout: MARKETPLACE_TIMEOUT_MS },
+ { file: '/bin/claude', args: ['plugin', 'install', 'ruflo-mods@ruflo', '--scope', 'local'], cwd: ROOT, timeout: INSTALL_TIMEOUT_MS },
+ ]);
+ });
+
+ it('unknown marketplace: add it at the same scope (never user settings), never with -y', () => {
+ const [add, install] = repairArgv('project', false);
+ expect(add).toEqual(['plugin', 'marketplace', 'add', 'ruvnet/ruflo', '--scope', 'project']);
+ expect([...add!, ...install!]).not.toContain('-y');
+ });
+
+ it('stops at the first failure and reports it', async () => {
+ const { exec, calls } = fakeExec([1]);
+ const r = await repairPluginInstall({ projectRoot: ROOT, scope: 'local', marketplaceKnown: true, claude: '/bin/claude', exec, env: {} });
+ expect(r.ok).toBe(false);
+ expect(calls).toHaveLength(1);
+ expect(r.steps[0]).toMatchObject({ ok: false, output: 'Marketplace not reachable' });
+ });
+
+ it('an exec that throws is a failed step, not a crash', async () => {
+ const exec: Exec = async () => {
+ throw new Error('spawn ENOENT');
+ };
+ const r = await repairPluginInstall({ projectRoot: ROOT, scope: 'local', marketplaceKnown: false, claude: '/missing', exec, env: {} });
+ expect(r).toMatchObject({ ok: false, steps: [{ ok: false, output: 'spawn ENOENT' }] });
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.ts
index 4ef391135d..da80b2eddf 100644
--- a/v3/@claude-flow/cli/src/commands/doctor.ts
+++ b/v3/@claude-flow/cli/src/commands/doctor.ts
@@ -2377,14 +2377,19 @@ async function checkMetaharness(): Promise<HealthCheck> {
// ADR-404 — ruflo as a Claude Code mod (function hooks, early access). One
// line in a bare `doctor`: whether the mod is enabled, can load (function
-// hooks on, not refused by allowManagedModsOnly) and has started; never a
-// failure, since the classic hooks are the default and the fallback.
-// `ruflo mods doctor` prints every finding.
+// hooks on, not refused by allowManagedModsOnly) and has started. Only an
+// opted-in project whose plugin Claude Code cannot resolve (stale ruflo
+// marketplace clone, nothing installed) fails: the classic hooks still run,
+// but the opt-in silently does nothing. `ruflo mods doctor` prints every finding.
async function checkMods(): Promise<HealthCheck> {
const { probeMods } = await import('../mods/probe.js');
const findings = probeMods({ projectRoot: process.cwd() });
const enabled = findings.find((f) => f.name === 'ruflo-mods plugin')?.status === 'pass';
if (!enabled) return { name: 'ruflo mods (ADR-404)', status: 'pass', message: 'not enabled; classic hooks handle every event' };
+ const failures = findings.filter((f) => f.status === 'fail');
+ if (failures.length > 0) {
+ return { name: 'ruflo mods (ADR-404)', status: 'fail', message: failures.map((f) => `${f.name}: ${f.message}`).join('; '), fix: failures[0]!.fix ?? 'ruflo mods doctor' };
+ }
const warnings = findings.filter((f) => f.status !== 'pass');
return warnings.length === 0
? { name: 'ruflo mods (ADR-404)', status: 'pass', message: findings.find((f) => f.name === 'last mod start')?.message ?? 'enabled' }
diff --git a/v3/@claude-flow/cli/src/commands/mods.ts b/v3/@claude-flow/cli/src/commands/mods.ts
index 2461fd19a0..3f8b710a2c 100644
--- a/v3/@claude-flow/cli/src/commands/mods.ts
+++ b/v3/@claude-flow/cli/src/commands/mods.ts
@@ -12,6 +12,9 @@ import type { Command, CommandContext, CommandResult } from '../types.js';
import { output } from '../output.js';
import { installMod, uninstallMod, type Scope } from '../mods/install.js';
import { probeMods, type Finding } from '../mods/probe.js';
+import { claudeConfigDir, marketplaceState, repairCommands, resolveFindings } from '../mods/plugin-resolve.js';
+import { findClaudeBinary, repairArgv, repairPluginInstall } from '../mods/plugin-repair.js';
+import { homedir } from 'node:os';
function projectRoot(ctx: CommandContext): string {
return (ctx.flags.projectRoot as string | undefined) ?? (ctx.flags['project-root'] as string | undefined) ?? ctx.cwd ?? process.cwd();
@@ -33,7 +36,9 @@ const installSub: Command = {
options: [
rootOption,
{ name: 'scope', description: 'local (.claude/settings.local.json, default) | project (.claude/settings.json)', type: 'string', default: 'local' },
- { name: 'dry-run', description: 'Show the settings that would be written', type: 'boolean', default: false },
+ { name: 'dry-run', description: 'Show the settings that would be written and the claude commands that would run', type: 'boolean', default: false },
+ { name: 'plugin-install', description: 'Refresh the ruflo marketplace and run `claude plugin install` (--no-plugin-install to only write settings)', type: 'boolean', default: true },
+ { name: 'strict', description: 'Exit 1 when the plugin could not be made resolvable', type: 'boolean', default: false },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const scope = (ctx.flags.scope as string | undefined) ?? 'local';
@@ -42,20 +47,62 @@ const installSub: Command = {
return { success: false, exitCode: 1 };
}
const root = projectRoot(ctx);
+ const pluginInstall = ctx.flags.pluginInstall !== false && ctx.flags['plugin-install'] !== false;
const result = installMod(root, scope as Scope, (ctx.flags.dryRun === true || ctx.flags['dry-run'] === true));
if (result.dryRun) {
output.writeln(`Would write ${result.settingsFile}:`);
output.printJson(result.next);
+ if (pluginInstall) {
+ const known = marketplaceState(claudeConfigDir(process.env, homedir())).known;
+ output.writeln('Would run:');
+ for (const argv of repairArgv(scope as Scope, known)) output.writeln(` claude ${argv.join(' ')}`);
+ }
return { success: true, data: result };
}
await syncPolicy(root, true);
output.printSuccess(`ruflo-mods enabled in ${result.settingsFile}${result.backup ? ` (backup: ${result.backup})` : ''}`);
- output.writeln('Restart Claude Code, then run /ruflo-mods in a session to see what the mod owns.');
- output.writeln(output.dim('Early access: Claude Code loads it only where function hooks are on. Run `ruflo mods doctor`.'));
- return { success: true, data: result };
+ const resolvable = pluginInstall ? await makeResolvable(root, scope as Scope) : true;
+ if (resolvable) {
+ output.writeln('Restart Claude Code, then run /ruflo-mods in a session to see what the mod owns.');
+ output.writeln(output.dim('Early access: Claude Code loads it only where function hooks are on. Run `ruflo mods doctor`.'));
+ }
+ const strict = ctx.flags.strict === true;
+ return resolvable || !strict ? { success: true, data: { ...result, resolvable } } : { success: false, exitCode: 1, data: { ...result, resolvable } };
},
};
+/**
+ * Settings alone are a request: Claude Code skips an enabled plugin missing
+ * from a stale marketplace clone. Install it the way a person would, then
+ * re-read Claude Code's own records; print the manual commands on any failure.
+ */
+async function makeResolvable(root: string, scope: Scope): Promise<boolean> {
+ const configDir = claudeConfigDir(process.env, homedir());
+ const known = marketplaceState(configDir).known;
+ const manual = () => {
+ output.writeln('Run these to make the plugin loadable:');
+ for (const line of repairCommands(root, scope, known)) output.writeln(` ${line}`);
+ };
+ const claude = findClaudeBinary(process.env, homedir());
+ if (!claude) {
+ output.printWarning('No runnable claude binary on PATH: the plugin is enabled in settings but not installed.');
+ manual();
+ return false;
+ }
+ const repair = await repairPluginInstall({ projectRoot: root, scope, marketplaceKnown: known, claude });
+ for (const step of repair.steps) {
+ const line = `claude ${step.argv.join(' ')}`;
+ output.writeln(step.ok ? `${output.success('✓')} ${line}` : `${output.error('✗')} ${line}`);
+ if (!step.ok && step.output) output.writeln(output.dim(` ${step.output.split('\n').slice(-3).join('\n ')}`));
+ }
+ const findings = resolveFindings(root, scope, configDir);
+ const failed = findings.filter((f) => f.status === 'fail');
+ if (repair.ok && failed.length === 0) return true;
+ printFindings(failed);
+ manual();
+ return false;
+}
+
const uninstallSub: Command = {
name: 'uninstall',
description: 'Remove what `ruflo mods install` added (classic hooks take every event back)',
@@ -81,8 +128,8 @@ function findingsCommand(name: 'status' | 'doctor', description: string): Comman
if (ctx.flags.json) output.printJson(findings);
else printFindings(findings);
const failed = findings.some((f) => f.status === 'fail');
- // status reports; doctor gates (warnings are expected while early access is off).
- return { success: !failed, exitCode: name === 'doctor' && failed ? 1 : 0, data: findings };
+ // status reports (exit 0); doctor gates on a failure (warnings are expected while early access is off).
+ return name === 'doctor' && failed ? { success: false, exitCode: 1, data: findings } : { success: true, data: findings };
},
};
}
@@ -123,7 +170,8 @@ export const modsCommand: Command = {
syncPolicySub,
],
examples: [
- { command: 'ruflo mods install', description: 'Enable for this project (settings.local.json)' },
+ { command: 'ruflo mods install', description: 'Enable for this project (settings.local.json) and install the plugin with claude' },
+ { command: 'ruflo mods install --no-plugin-install', description: 'Only write settings; run no claude command' },
{ command: 'ruflo mods doctor', description: 'Function hooks on? Refused by policy? Handshake supported?' },
{ command: 'ruflo mods uninstall', description: 'Remove only what install added' },
],
diff --git a/v3/@claude-flow/cli/src/mods/plugin-repair.ts b/v3/@claude-flow/cli/src/mods/plugin-repair.ts
new file mode 100644
index 0000000000..83f5ae6e4d
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mods/plugin-repair.ts
@@ -0,0 +1,90 @@
+/**
+ * After `ruflo mods install` writes settings, make the plugin resolvable the
+ * way a person would (ADR-404): refresh (or add) the `ruflo` marketplace
+ * clone, then `claude plugin install ruflo-mods@ruflo --scope <scope>`.
+ *
+ * Fixed argv through execFile, never a shell; each step bounded. The `add`
+ * step passes `--scope` so the marketplace is declared in the same settings
+ * file install already wrote, not in user settings. `~/.claude.json` is never
+ * touched by ruflo. No `-y`: a marketplace-declared command is never accepted
+ * on a person's behalf.
+ */
+
+import { execFile } from 'node:child_process';
+
+import { findClaudeInstalls } from './claude-installs.js';
+import { MARKETPLACE_NAME, MOD_PLUGIN_ID, type Scope } from './install.js';
+
+export const MARKETPLACE_TIMEOUT_MS = 150_000; // Claude Code's own clone timeout is 120s
+export const INSTALL_TIMEOUT_MS = 60_000;
+
+export interface ExecResult {
+ code: number;
+ stdout: string;
+ stderr: string;
+}
+
+export type Exec = (file: string, args: readonly string[], opts: { cwd: string; timeout: number; env: NodeJS.ProcessEnv }) => Promise<ExecResult>;
+
+export const nodeExec: Exec = (file, args, opts) =>
+ new Promise((done) => {
+ execFile(file, [...args], { ...opts, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024, windowsHide: true }, (error, stdout, stderr) => {
+ // error.code is the exit status, or a string (ENOENT, ...) when it never ran; a timeout kills it.
+ const status = (error as { code?: unknown } | null)?.code;
+ const code = !error ? 0 : typeof status === 'number' && status !== 0 ? status : 1;
+ done({ code, stdout: String(stdout), stderr: String(stderr) || (error ? error.message : '') });
+ });
+ });
+
+/** The `claude` a shell would run, when it can be exec'd without a shell. */
+export function findClaudeBinary(env: NodeJS.ProcessEnv, home: string): string | null {
+ const first = findClaudeInstalls(env, home, () => null)[0];
+ if (!first) return null;
+ // A .cmd shim needs a shell to run; ruflo never uses one.
+ return process.platform === 'win32' && !first.path.toLowerCase().endsWith('.exe') ? null : first.path;
+}
+
+export interface RepairStep {
+ argv: string[];
+ ok: boolean;
+ output: string;
+}
+
+export interface RepairOptions {
+ projectRoot: string;
+ scope: Scope;
+ /** The marketplace is in known_marketplaces.json: update it, else add it. */
+ marketplaceKnown: boolean;
+ claude: string;
+ exec?: Exec;
+ env?: NodeJS.ProcessEnv;
+}
+
+export function repairArgv(scope: Scope, marketplaceKnown: boolean): string[][] {
+ return [
+ marketplaceKnown
+ ? ['plugin', 'marketplace', 'update', MARKETPLACE_NAME]
+ : ['plugin', 'marketplace', 'add', 'ruvnet/ruflo', '--scope', scope],
+ ['plugin', 'install', MOD_PLUGIN_ID, '--scope', scope],
+ ];
+}
+
+/** Runs the steps in order and stops at the first failure. */
+export async function repairPluginInstall(opts: RepairOptions): Promise<{ ok: boolean; steps: RepairStep[] }> {
+ const exec = opts.exec ?? nodeExec;
+ const env = opts.env ?? process.env;
+ const steps: RepairStep[] = [];
+ for (const argv of repairArgv(opts.scope, opts.marketplaceKnown)) {
+ const timeout = argv[1] === 'marketplace' ? MARKETPLACE_TIMEOUT_MS : INSTALL_TIMEOUT_MS;
+ let result: ExecResult;
+ try {
+ result = await exec(opts.claude, argv, { cwd: opts.projectRoot, timeout, env });
+ } catch (error) {
+ result = { code: 1, stdout: '', stderr: (error as Error).message };
+ }
+ const ok = result.code === 0;
+ steps.push({ argv, ok, output: `${result.stdout}${result.stderr}`.trim() });
+ if (!ok) return { ok: false, steps };
+ }
+ return { ok: true, steps };
+}
diff --git a/v3/@claude-flow/cli/src/mods/plugin-resolve.ts b/v3/@claude-flow/cli/src/mods/plugin-resolve.ts
new file mode 100644
index 0000000000..372fd2f3c6
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mods/plugin-resolve.ts
@@ -0,0 +1,143 @@
+/**
+ * Whether Claude Code can actually resolve the ruflo-mods plugin (ADR-404).
+ *
+ * `enabledPlugins["ruflo-mods@ruflo"] = true` in settings is only a request.
+ * Claude Code loads the plugin from its own install record
+ * (`<config>/plugins/installed_plugins.json`, pointing into `plugins/cache/`),
+ * and installs it from its local clone of the `ruflo` marketplace
+ * (`known_marketplaces.json` → `installLocation`). A clone from before
+ * ruflo-mods shipped has no `plugins/ruflo-mods`, and Claude Code then skips
+ * the enabled plugin without a word: `/ruflo-mods` is an unknown command.
+ *
+ * Read-only. The config directory is `CLAUDE_CONFIG_DIR` when set, else
+ * `~/.claude`, as Claude Code itself resolves it.
+ */
+
+import { existsSync, readFileSync, realpathSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+
+import { MARKETPLACE_NAME, MOD_PLUGIN_ID, type Scope } from './install.js';
+import type { Finding } from './probe.js';
+
+export const MOD_PLUGIN_MANIFEST = join('plugins', 'ruflo-mods', '.claude-plugin', 'plugin.json');
+
+/** The two filesystem reads detection needs; injectable for tests. */
+export interface ReadFs {
+ exists(path: string): boolean;
+ readText(path: string): string | undefined;
+}
+
+export const nodeReadFs: ReadFs = {
+ exists: (p) => existsSync(p),
+ readText: (p) => {
+ try {
+ return readFileSync(p, 'utf8');
+ } catch {
+ return undefined;
+ }
+ },
+};
+
+export function claudeConfigDir(env: NodeJS.ProcessEnv, home: string): string {
+ return env.CLAUDE_CONFIG_DIR || join(home, '.claude');
+}
+
+function readJson(fs: ReadFs, path: string): unknown {
+ const text = fs.readText(path);
+ if (text === undefined) return undefined;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return undefined;
+ }
+}
+
+function isRecord(v: unknown): v is Record<string, unknown> {
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
+}
+
+export interface MarketplaceState {
+ /** Listed in known_marketplaces.json (so `marketplace update ruflo` works). */
+ known: boolean;
+ /** The local clone, when one exists on disk. */
+ location: string | null;
+ /** The clone carries plugins/ruflo-mods. */
+ hasMod: boolean;
+}
+
+export function marketplaceState(configDir: string, fs: ReadFs = nodeReadFs): MarketplaceState {
+ const known = readJson(fs, join(configDir, 'plugins', 'known_marketplaces.json'));
+ const entry = isRecord(known) ? known[MARKETPLACE_NAME] : undefined;
+ const declared = isRecord(entry) && typeof entry.installLocation === 'string' ? entry.installLocation : undefined;
+ const candidates = [declared, join(configDir, 'plugins', 'marketplaces', MARKETPLACE_NAME)].filter((p): p is string => !!p);
+ const location = candidates.find((p) => fs.exists(p)) ?? null;
+ return { known: isRecord(entry), location, hasMod: location !== null && fs.exists(join(location, MOD_PLUGIN_MANIFEST)) };
+}
+
+export interface InstalledState {
+ installed: boolean;
+ scope?: string;
+ installPath?: string;
+}
+
+function sameDir(a: string, b: string): boolean {
+ if (resolve(a) === resolve(b)) return true;
+ try {
+ return realpathSync(a) === realpathSync(b);
+ } catch {
+ return false;
+ }
+}
+
+/** Installed for this project: user scope anywhere, local/project scope for this root; its cache dir present. */
+export function installedState(projectRoot: string, configDir: string, fs: ReadFs = nodeReadFs): InstalledState {
+ const record = readJson(fs, join(configDir, 'plugins', 'installed_plugins.json'));
+ const plugins = isRecord(record) && isRecord(record.plugins) ? record.plugins : undefined;
+ const entries = plugins && Array.isArray(plugins[MOD_PLUGIN_ID]) ? (plugins[MOD_PLUGIN_ID] as unknown[]) : [];
+ for (const e of entries) {
+ if (!isRecord(e) || typeof e.installPath !== 'string' || !fs.exists(e.installPath)) continue;
+ const forHere = e.scope === 'user' || (typeof e.projectPath === 'string' && sameDir(e.projectPath, projectRoot));
+ if (forHere) return { installed: true, scope: String(e.scope), installPath: e.installPath };
+ }
+ return { installed: false };
+}
+
+/** The exact commands that make the plugin resolvable, for a person to run. */
+export function repairCommands(projectRoot: string, scope: Scope | 'user', known: boolean): string[] {
+ return [
+ `cd ${JSON.stringify(resolve(projectRoot))}`,
+ known ? `claude plugin marketplace update ${MARKETPLACE_NAME}` : `claude plugin marketplace add ruvnet/ruflo --scope ${scope}`,
+ `claude plugin install ${MOD_PLUGIN_ID} --scope ${scope}`,
+ ];
+}
+
+/**
+ * The two resolvability findings. A missing install record is the failure
+ * Claude Code hides; a stale clone fails only while nothing is installed
+ * (an install already in the plugin cache still loads).
+ */
+export function resolveFindings(projectRoot: string, scope: Scope | 'user', configDir: string, fs: ReadFs = nodeReadFs): Finding[] {
+ const market = marketplaceState(configDir, fs);
+ const installed = installedState(projectRoot, configDir, fs);
+ const fix = repairCommands(projectRoot, scope, market.known).join(' && ');
+ const findings: Finding[] = [];
+
+ if (market.hasMod) {
+ findings.push({ name: 'ruflo marketplace', status: 'pass', message: `${market.location} has ruflo-mods` });
+ } else {
+ const message = market.location
+ ? `${market.location} is stale: it predates ruflo-mods (no ${MOD_PLUGIN_MANIFEST}), so Claude Code cannot install the plugin`
+ : `no local clone of the ${MARKETPLACE_NAME} marketplace under ${join(configDir, 'plugins')}`;
+ findings.push({ name: 'ruflo marketplace', status: installed.installed ? 'warn' : 'fail', message, fix });
+ }
+
+ findings.push(installed.installed
+ ? { name: 'ruflo-mods installed', status: 'pass', message: `${installed.scope} scope, ${installed.installPath}` }
+ : {
+ name: 'ruflo-mods installed',
+ status: 'fail',
+ message: `not installed for this project (${join(configDir, 'plugins', 'installed_plugins.json')}): Claude Code skips an enabled plugin it cannot resolve, and /ruflo-mods is an unknown command`,
+ fix,
+ });
+ return findings;
+}
diff --git a/v3/@claude-flow/cli/src/mods/probe.ts b/v3/@claude-flow/cli/src/mods/probe.ts
index 1f99670e88..9d12cfc2ab 100644
--- a/v3/@claude-flow/cli/src/mods/probe.ts
+++ b/v3/@claude-flow/cli/src/mods/probe.ts
@@ -11,6 +11,7 @@ import { join, resolve } from 'node:path';
import { findClaudeInstalls, judgeInstalls, type ClaudeInstall } from './claude-installs.js';
import { ENABLE_ENV, MOD_PLUGIN_ID, readRecord, readSettingsFile, settingsFileFor } from './install.js';
+import { claudeConfigDir, resolveFindings, type ReadFs } from './plugin-resolve.js';
import { PROJECTION_RELATIVE } from './policy-projection.js';
export const HANDSHAKE_MARKER = 'RUFLO_MODS_OWNS';
@@ -51,16 +52,21 @@ export interface ProbeInputs {
managedPath?: string;
/** Claude Code binaries on PATH; discovered (each `--version` run) when absent. */
installs?: ClaudeInstall[];
+ /** Claude Code's config directory; CLAUDE_CONFIG_DIR, else ~/.claude, when absent. */
+ configDir?: string;
+ /** Reads for the plugin-resolution findings; the real filesystem when absent. */
+ fs?: ReadFs;
}
export function probeMods(inputs: ProbeInputs): Finding[] {
const root = resolve(inputs.projectRoot);
const home = inputs.home ?? homedir();
const env = inputs.env ?? process.env;
+ const configDir = inputs.configDir ?? claudeConfigDir(env, home);
const findings: Finding[] = [];
// 1. Enabled for this project?
- const files = [settingsFileFor(root, 'local'), settingsFileFor(root, 'project'), join(home, '.claude', 'settings.json')];
+ const files = [settingsFileFor(root, 'local'), settingsFileFor(root, 'project'), join(configDir, 'settings.json')];
const enabledIn = files.find((f) => {
try {
return get(readSettingsFile(f), 'enabledPlugins', MOD_PLUGIN_ID) === true;
@@ -69,9 +75,16 @@ export function probeMods(inputs: ProbeInputs): Finding[] {
}
});
findings.push(enabledIn
- ? { name: 'ruflo-mods plugin', status: 'pass', message: `enabled in ${enabledIn}` }
+ ? { name: 'ruflo-mods plugin', status: 'pass', message: `enabled in settings: ${enabledIn} (whether Claude Code can load it: see below)` }
: { name: 'ruflo-mods plugin', status: 'warn', message: 'not enabled; classic hooks handle every event', fix: 'ruflo mods install' });
+ // 1a. Enabled is a request; Claude Code silently skips a plugin it cannot
+ // resolve (a marketplace clone older than ruflo-mods, nothing installed).
+ if (enabledIn) {
+ const scope = enabledIn === files[0] ? 'local' : enabledIn === files[1] ? 'project' : 'user';
+ findings.push(...resolveFindings(root, scope, configDir, inputs.fs));
+ }
+
// 2. Function hooks switched on for installed plugins (early access).
const envOn = env[ENABLE_ENV] === '1';
const settingsOn = files.some((f) => {