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

feat(mods): default-on in ruflo init, init upgrade --mods, three mod plugins (ADR-404 amendment 1)

ruvdcceb3258596
diff --git a/plugins/ruflo-mods/README.md b/plugins/ruflo-mods/README.md
index f8279ede36..0c82c2362b 100644
--- a/plugins/ruflo-mods/README.md
+++ b/plugins/ruflo-mods/README.md
@@ -1,25 +1,44 @@
# ruflo-mods
-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).
+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), including Amendment 1 (default-on in `ruflo init`).
```bash
-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 init # new projects: mods on by default, in the committed .claude/settings.json
+ruflo init upgrade --mods # existing projects: merge the same keys (never overwrites yours) and install
+ruflo mods install # just this checkout (.claude/settings.local.json); --scope project for the team
+ruflo mods doctor # marketplace fresh? plugins loadable? function hooks on? what does it own?
+ruflo mods uninstall # remove exactly what ruflo added, from every settings file it wrote
```
-`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:
+These enable `ruflo-mods@ruflo`, `ruflo-swarm@ruflo` and `ruflo-console@ruflo`, the `ruflo` marketplace and `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1`. A key you already set is left as it is: a plugin you set to `false` stays off. `ruflo init --no-mods` writes none of it.
+
+What loads:
+
+- **ruflo-mods and ruflo-console** run only where function hooks are on. With them off, or with Claude Code's rollout switch off, they do nothing, and the classic hooks keep every event.
+- **ruflo-swarm's** commands, skills and agents load regardless. Its live pane needs function hooks.
+- **ruflo-console** is reported as "pending" until it is released in the marketplace.
+
+When a `claude` binary is on PATH, init and install also do what you would do by hand, in the project directory:
```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`)
+claude plugin marketplace update ruflo # or, first time: claude plugin marketplace add ruvnet/ruflo --scope <scope>
+claude plugin install ruflo-mods@ruflo --scope <scope>
+claude plugin install ruflo-swarm@ruflo --scope <scope>
```
-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.
+Settings alone are not always enough. Claude Code loads these plugins from its local clone of the `ruflo` marketplace (`~/.claude/plugins/marketplaces/ruflo`, or under `$CLAUDE_CONFIG_DIR`).
+
+- **No clone yet.** An interactive, trusted session clones it on start. A headless `claude -p` run does not.
+- **A stale clone.** A clone from before ruflo-mods shipped has no `plugins/ruflo-mods`, so Claude Code skips the enabled plugin without a word, and `/ruflo-mods` is an unknown command. It does not refresh the clone on start. `ruflo mods doctor` and `ruflo doctor` report this as a failure, with the exact commands above.
+- **Why `claude plugin install` too.** It keeps a cached copy that still loads if the clone goes stale later.
+
+Flags:
- `--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.
+- `--dry-run` (`mods install`) prints the settings and the `claude` commands without running either.
+- If `claude` is missing or a step fails, the manual commands are printed and the exit code is 0. Pass `--strict` (`mods install`) to exit 1 instead.
+- Under `VITEST` or `CI`, init skips the `claude` step and prints the commands.
+- Claude Code reformats `.claude/settings.json` (key order) when it installs at project scope. The content is unchanged.
In a session, `/ruflo-mods` reports what the mod owns, routed, recorded and tightened.
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 dd0a19b847..4f9531a956 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
@@ -26,45 +26,52 @@ function isolated() {
}
describe.skipIf(!CLI_BUILT)('ADR-404 mods through the built CLI', () => {
- it('init --mods enables the plugin beside the classic hooks; doctor and mods status report it', () => {
+ it('bare init enables the mod plugins in the committed settings beside the classic hooks; uninstall reverses exactly', () => {
const t = isolated();
try {
- t.run('init', '--mods', '--no-signup', '--no-global', '--no-codex-detect');
- const local = JSON.parse(readFileSync(join(t.cwd, '.claude', 'settings.local.json'), 'utf8'));
- expect(local.enabledPlugins['ruflo-mods@ruflo']).toBe(true);
- // Classic hooks are untouched: still the default and the fallback.
+ // VITEST is in the spawned env, so init skips the claude step and prints the manual commands.
+ const out = t.run('init', '--no-signup', '--no-global', '--no-codex-detect');
+ expect(out).toContain('claude plugin step skipped (VITEST set)');
+ expect(out).toContain('claude plugin install ruflo-mods@ruflo --scope project');
+ expect(out).toContain('with them off, or the rollout switch off, they do nothing and the classic hooks keep every event');
const shared = JSON.parse(readFileSync(join(t.cwd, '.claude', 'settings.json'), 'utf8'));
+ for (const id of ['ruflo-mods@ruflo', 'ruflo-swarm@ruflo', 'ruflo-console@ruflo']) expect(shared.enabledPlugins[id]).toBe(true);
+ expect(shared.extraKnownMarketplaces.ruflo.source).toEqual({ source: 'github', repo: 'ruvnet/ruflo' });
+ expect(shared.env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS).toBe('1');
+ // Classic hooks are untouched: still the default and the fallback.
expect(JSON.stringify(shared.hooks.UserPromptSubmit)).toContain('hook-handler.cjs');
+ expect(existsSync(join(t.cwd, '.claude', 'settings.local.json'))).toBe(false);
- // 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');
+ // No marketplace clone in this isolated config yet: a warning (Claude
+ // Code clones it at its next interactive start), not a failure.
const status = JSON.parse(t.run('mods', 'status', '--json').replace(/^[^[]*/, ''));
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') });
+ expect(named('ruflo marketplace')).toMatchObject({ status: 'warn', fix: expect.stringContaining('--scope project') });
+ expect(t.run('doctor', '--component', 'mods')).toContain('ruflo mods (ADR-404)');
+ const before = { ...shared };
+ for (const k of ['enabledPlugins', 'extraKnownMarketplaces']) delete (before as Record<string, unknown>)[k];
+ const env = { ...shared.env };
+ delete env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS;
+ if (Object.keys(env).length) (before as Record<string, unknown>).env = env;
+ else delete (before as Record<string, unknown>).env;
t.run('mods', 'uninstall');
- expect(JSON.parse(readFileSync(join(t.cwd, '.claude', 'settings.local.json'), 'utf8'))).toEqual({});
+ expect(JSON.parse(readFileSync(join(t.cwd, '.claude', 'settings.json'), 'utf8'))).toEqual(before);
} finally {
t.done();
}
});
- it('bare init does not enable the mod (opt-in)', () => {
+ it('init --no-mods writes none of the mod keys', () => {
const t = isolated();
try {
- t.run('init', '--no-signup', '--no-global', '--no-codex-detect');
- expect(existsSync(join(t.cwd, '.claude', 'settings.local.json'))).toBe(false);
+ t.run('init', '--no-mods', '--no-signup', '--no-global', '--no-codex-detect');
+ const shared = JSON.parse(readFileSync(join(t.cwd, '.claude', 'settings.json'), 'utf8'));
+ expect(shared.enabledPlugins?.['ruflo-mods@ruflo']).toBeUndefined();
+ expect(shared.extraKnownMarketplaces?.ruflo).toBeUndefined();
+ expect(shared.env?.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS).toBeUndefined();
+ expect(existsSync(join(t.cwd, '.claude-flow', 'mods', 'install.json'))).toBe(false);
expect(t.run('doctor', '--component', 'mods')).toContain('not enabled; classic hooks handle every event');
} finally {
t.done();
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 fa3cde4dd7..b4233399a2 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-cli.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-cli.test.ts
@@ -7,11 +7,10 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { installMod, uninstallMod, withModEnabled, withModRemoved, ENABLE_ENV, MOD_PLUGIN_ID } from '../../src/mods/install.js';
+import { installMod, readRecord, uninstallMod, withModEnabled, withModRemoved, ENABLE_ENV, MOD_PLUGIN_ID, MOD_PLUGIN_IDS } from '../../src/mods/install.js';
import { projectionOf, syncPolicyProjection, PROJECTION_RELATIVE } from '../../src/mods/policy-projection.js';
-import { probeMods, type Finding } from '../../src/mods/probe.js';
+import { probeMods } 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';
import { parseProjection } from '../../../../../plugins/ruflo-mods/hooks/guard/policy';
@@ -30,38 +29,76 @@ const finding = (name: string, env: NodeJS.ProcessEnv = {}, managedPath = join(h
probeMods({ projectRoot: root, home, env, managedPath, installs: [] }).find((f) => f.name === name)!;
describe('ADR-404 mods install / uninstall', () => {
- it('enables the plugin, the marketplace and the early-access switch in settings.local.json', () => {
+ const none = { plugins: [], marketplace: false, env: false };
+
+ it('enables every mod plugin, the marketplace and the early-access switch', () => {
const r = installMod(root, 'local');
const s = read(join(root, '.claude', 'settings.local.json'));
- expect(s.enabledPlugins[MOD_PLUGIN_ID]).toBe(true);
+ for (const id of MOD_PLUGIN_IDS) expect(s.enabledPlugins[id]).toBe(true);
+ expect(MOD_PLUGIN_IDS).toEqual(['ruflo-mods@ruflo', 'ruflo-swarm@ruflo', 'ruflo-console@ruflo']);
expect(s.extraKnownMarketplaces.ruflo.source).toEqual({ source: 'github', repo: 'ruvnet/ruflo' });
expect(s.env[ENABLE_ENV]).toBe('1');
- expect(r.added).toEqual({ plugin: true, marketplace: true, env: true });
+ expect(r.added).toEqual({ plugins: [...MOD_PLUGIN_IDS], marketplace: true, env: true });
});
- it('keeps everything a person set, backs up, and uninstall removes only what install added', () => {
+ it('keeps everything a person set (a false plugin, their env value), backs up, and uninstall removes only what install added', () => {
const file = join(root, '.claude', 'settings.json');
mkdirSync(join(root, '.claude'), { recursive: true });
- const before = { hooks: { Stop: [] }, env: { KEEP: 'x' }, extraKnownMarketplaces: { ruflo: { source: { source: 'directory', path: '/mine' } } }, enabledPlugins: { other: true } };
+ const before = {
+ hooks: { Stop: [] },
+ env: { KEEP: 'x', [ENABLE_ENV]: '0' },
+ extraKnownMarketplaces: { ruflo: { source: { source: 'directory', path: '/mine' } } },
+ enabledPlugins: { other: true, 'ruflo-swarm@ruflo': false },
+ };
writeFileSync(file, JSON.stringify(before));
const r = installMod(root, 'project');
expect(r.backup && existsSync(r.backup)).toBe(true);
- expect(read(file).extraKnownMarketplaces.ruflo.source.source).toBe('directory'); // never replaced
+ expect(r.added).toEqual({ plugins: ['ruflo-mods@ruflo', 'ruflo-console@ruflo'], marketplace: false, env: false });
+ const after = read(file);
+ expect(after.extraKnownMarketplaces.ruflo.source.source).toBe('directory'); // never replaced
+ expect(after.enabledPlugins['ruflo-swarm@ruflo']).toBe(false); // their decision
+ expect(after.env).toEqual({ KEEP: 'x', [ENABLE_ENV]: '0' });
+ expect(after.hooks).toEqual({ Stop: [] });
uninstallMod(root);
expect(read(file)).toEqual(before);
expect(existsSync(join(root, '.claude-flow', 'mods', 'install.json'))).toBe(false);
});
- it('a second install keeps the first record of what ruflo added', () => {
- installMod(root, 'local');
+ it('a re-run adds nothing, rewrites nothing, and keeps the record of what ruflo added', () => {
installMod(root, 'local');
+ const file = join(root, '.claude', 'settings.local.json');
+ const text = readFileSync(file, 'utf8');
+ const again = installMod(root, 'local');
+ expect(again.added).toEqual(none);
+ expect(again.backup).toBeUndefined();
+ expect(readFileSync(file, 'utf8')).toBe(text);
uninstallMod(root);
+ expect(read(file)).toEqual({});
+ });
+
+ it('records each settings file separately: init (project) beside a standalone local install', () => {
+ installMod(root, 'local');
+ installMod(root, 'project');
+ expect(Object.keys(readRecord(root)!.files).sort()).toEqual([join(root, '.claude', 'settings.json'), join(root, '.claude', 'settings.local.json')]);
+ expect(uninstallMod(root).settingsFiles).toHaveLength(2);
+ expect(read(join(root, '.claude', 'settings.json'))).toEqual({});
expect(read(join(root, '.claude', 'settings.local.json'))).toEqual({});
});
+ it('reads a 3.50.0 (v1) record: uninstall still removes what it added', () => {
+ const file = join(root, '.claude', 'settings.local.json');
+ mkdirSync(join(root, '.claude'), { recursive: true });
+ writeFileSync(file, JSON.stringify({ enabledPlugins: { [MOD_PLUGIN_ID]: true, mine: true }, env: { [ENABLE_ENV]: '1' } }));
+ mkdirSync(join(root, '.claude-flow', 'mods'), { recursive: true });
+ writeFileSync(join(root, '.claude-flow', 'mods', 'install.json'), JSON.stringify({ version: 1, settingsFile: file, installedAt: 'x', added: { plugin: true, marketplace: false, env: true } }));
+ expect(readRecord(root)!.files[file]).toEqual({ plugins: [MOD_PLUGIN_ID], marketplace: false, env: true });
+ uninstallMod(root);
+ expect(read(file)).toEqual({ enabledPlugins: { mine: true } });
+ });
+
it('dry run writes nothing', () => {
const r = installMod(root, 'local', true);
- expect(r.next.enabledPlugins).toEqual({ [MOD_PLUGIN_ID]: true });
+ expect(Object.keys(r.next.enabledPlugins!)).toEqual([...MOD_PLUGIN_IDS]);
expect(existsSync(join(root, '.claude'))).toBe(false);
});
@@ -75,7 +112,7 @@ describe('ADR-404 mods install / uninstall', () => {
it('never follows an install record outside the project .claude folder', () => {
mkdirSync(join(root, '.claude-flow', 'mods'), { recursive: true });
for (const target of [join(home, 'settings.json'), join(root, '.claude-flow', 'x.json'), join(root, '.claude', '..', '..', 'evil.json')]) {
- writeFileSync(join(root, '.claude-flow', 'mods', 'install.json'), JSON.stringify({ version: 1, settingsFile: target, installedAt: 'x', added: { plugin: true, marketplace: true, env: true } }));
+ writeFileSync(join(root, '.claude-flow', 'mods', 'install.json'), JSON.stringify({ version: 2, installedAt: 'x', files: { [target]: { plugins: [MOD_PLUGIN_ID], marketplace: true, env: true } } }));
expect(() => uninstallMod(root)).toThrow(/outside/);
}
});
@@ -83,7 +120,7 @@ describe('ADR-404 mods install / uninstall', () => {
it('pure halves round-trip', () => {
const s = { enabledPlugins: { [MOD_PLUGIN_ID]: true } };
const { next, added } = withModEnabled(s);
- expect(added.plugin).toBe(false);
+ expect(added.plugins).not.toContain(MOD_PLUGIN_ID);
expect(withModRemoved(next, added)).toEqual(s);
});
});
@@ -163,82 +200,6 @@ describe('ADR-404 mods probe and doctor', () => {
expect(finding('policy projection')).toMatchObject({ status: 'warn', fix: 'ruflo mods sync-policy' });
});
- 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;
- 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);
- });
- });
});
describe('ADR-404 claude installs', () => {
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-commands.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-commands.test.ts
new file mode 100644
index 0000000000..fb104f05e2
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-commands.test.ts
@@ -0,0 +1,190 @@
+/**
+ * ADR-404 β€” `ruflo mods install|status|doctor|uninstall` and
+ * `ruflo init upgrade --mods` in-process, against a stand-in `claude` on an
+ * isolated PATH, HOME and CLAUDE_CONFIG_DIR. Never the real ~/.claude or a
+ * real claude.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { MOD_PLUGIN_ID } from '../../src/mods/install.js';
+import type { Finding } from '../../src/mods/probe.js';
+import { modsCommand } from '../../src/commands/mods.js';
+import { initCommand } from '../../src/commands/init.js';
+
+let root: string;
+let home: string;
+const saved = { PATH: process.env.PATH, HOME: process.env.HOME, CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR, VITEST: process.env.VITEST, CI: process.env.CI };
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'ruflo-mods-cmd-'));
+ home = mkdtempSync(join(tmpdir(), 'ruflo-mods-cmd-home-'));
+ mkdirSync(join(home, 'bin'), { recursive: true });
+ process.env.PATH = join(home, '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;
+ }
+ rmSync(root, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+});
+
+const read = (p: string) => JSON.parse(readFileSync(p, 'utf8'));
+const sub = (cmd: typeof modsCommand, name: string) => cmd.subcommands!.find((s) => s.name === name)!;
+const ctx = (flags: Record<string, unknown> = {}) => ({ args: [], flags: { projectRoot: root, ...flags }, cwd: root, interactive: false }) as any;
+const findings = async () => (await sub(modsCommand, 'status').action!(ctx({ json: true }))).data as Finding[];
+const status = (all: Finding[], name: string) => all.find((f) => f.name === name)?.status;
+
+/**
+ * A stand-in claude. `marketplace add|update` leaves a clone carrying
+ * ruflo-mods and ruflo-swarm (not ruflo-console: pending), or, with
+ * mode 'stale', a clone without any of them; `install <id>` records it the
+ * way Claude Code does. Every argv is logged.
+ */
+function fakeClaude(mode: 'ok' | 'stale' | 'fail') {
+ const cfg = join(home, 'cfg', 'plugins');
+ const node = String.raw`
+const fs = require('fs'), path = require('path');
+const [, , ...argv] = process.argv;
+fs.appendFileSync(${JSON.stringify(join(home, 'calls'))}, argv.join(' ') + '\n');
+const cfg = ${JSON.stringify(cfg)};
+if (${JSON.stringify(mode)} === 'fail') { process.stderr.write('network down\n'); process.exit(1); }
+if (argv[1] === 'marketplace') {
+ const clone = path.join(cfg, 'marketplaces', 'ruflo');
+ fs.mkdirSync(path.join(clone, 'plugins'), { recursive: true });
+ if (${JSON.stringify(mode)} === 'ok') for (const p of ['ruflo-mods', 'ruflo-swarm']) {
+ fs.mkdirSync(path.join(clone, 'plugins', p, '.claude-plugin'), { recursive: true });
+ fs.writeFileSync(path.join(clone, 'plugins', p, '.claude-plugin', 'plugin.json'), '{}');
+ }
+ fs.writeFileSync(path.join(cfg, 'known_marketplaces.json'), JSON.stringify({ ruflo: { installLocation: clone } }));
+}
+if (argv[1] === 'install') {
+ const file = path.join(cfg, 'installed_plugins.json');
+ const rec = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : { version: 2, plugins: {} };
+ const dir = path.join(cfg, 'cache', argv[2]);
+ fs.mkdirSync(dir, { recursive: true });
+ rec.plugins[argv[2]] = [{ scope: argv[4], installPath: dir, projectPath: process.cwd() }];
+ fs.writeFileSync(file, JSON.stringify(rec));
+}
+`;
+ writeFileSync(join(home, 'bin', 'claude'), `#!${process.execPath}\n${node}`, { 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 ')) : []);
+
+describe('ADR-404 ruflo mods install (standalone)', () => {
+ it('--no-plugin-install writes settings only; status reports, doctor stays green until a clone exists', async () => {
+ fakeClaude('ok');
+ expect((await sub(modsCommand, 'install').action!(ctx({ pluginInstall: false }))).success).toBe(true);
+ expect(calls()).toEqual([]);
+ expect((await sub(modsCommand, 'install').action!(ctx({ scope: 'global' }))).success).toBe(false);
+ const all = await findings();
+ // No clone yet: Claude Code clones it at its next interactive start β€” a warning, not a failure.
+ expect(status(all, 'ruflo marketplace')).toBe('warn');
+ expect((await sub(modsCommand, 'doctor').action!(ctx({ json: true }))).success).toBe(true);
+ expect((await sub(modsCommand, 'uninstall').action!(ctx())).success).toBe(true);
+ expect(read(join(root, '.claude', 'settings.local.json'))).toEqual({});
+ });
+
+ it('adds the marketplace at the scope, installs every plugin the clone carries, reports ruflo-console pending', async () => {
+ fakeClaude('ok');
+ const r = await sub(modsCommand, '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',
+ 'plugin install ruflo-swarm@ruflo --scope local',
+ ]);
+ const all = await findings();
+ expect(status(all, 'plugin ruflo-mods@ruflo')).toBe('pass');
+ expect(status(all, 'plugin ruflo-swarm@ruflo')).toBe('pass');
+ expect(all.find((f) => f.name === 'plugin ruflo-console@ruflo')).toMatchObject({ status: 'warn', message: expect.stringContaining('pending') });
+ // A re-run: the marketplace is known now, so it is updated, not re-added.
+ await sub(modsCommand, 'install').action!(ctx());
+ expect(calls()[3]).toBe('plugin marketplace update ruflo');
+ });
+
+ it('the reported bug: a stale clone fails doctor; install refreshes it and doctor passes', async () => {
+ fakeClaude('stale');
+ expect(await sub(modsCommand, 'install').action!(ctx())).toMatchObject({ success: true, data: { resolvable: false } });
+ let all = await findings();
+ expect(all.find((f) => f.name === 'plugin ruflo-mods@ruflo')).toMatchObject({ status: 'fail', message: expect.stringContaining('/ruflo-mods is an unknown command') });
+ expect((await sub(modsCommand, 'doctor').action!(ctx({ json: true }))).exitCode).toBe(1);
+ fakeClaude('ok');
+ expect(await sub(modsCommand, 'install').action!(ctx())).toMatchObject({ success: true, data: { resolvable: true } });
+ all = await findings();
+ expect(all.filter((f) => f.status === 'fail')).toEqual([]);
+ expect((await sub(modsCommand, 'doctor').action!(ctx({ json: true }))).success).toBe(true);
+ });
+
+ it('a failed repair prints the manual commands; exit 1 only with --strict', async () => {
+ fakeClaude('fail');
+ expect(await sub(modsCommand, 'install').action!(ctx())).toMatchObject({ success: true, data: { resolvable: false } });
+ expect(await sub(modsCommand, '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(modsCommand, '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);
+ });
+});
+
+describe('ADR-404 amendment: ruflo init upgrade --mods', () => {
+ const upgrade = sub(initCommand, 'upgrade');
+ const settingsFile = () => join(root, '.claude', 'settings.json');
+ const userSettings = {
+ hooks: { PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: 'echo mine' }] }] },
+ env: { MY_VAR: 'keep' },
+ enabledPlugins: { 'mine@elsewhere': true, 'ruflo-swarm@ruflo': false },
+ permissions: { allow: ['Bash(ls)'] },
+ };
+ beforeEach(() => {
+ mkdirSync(join(root, '.claude'), { recursive: true });
+ writeFileSync(settingsFile(), JSON.stringify(userSettings, null, 2));
+ });
+
+ it('merges the mod keys into the committed settings, keeps every user key, installs at project scope; a re-run changes nothing', async () => {
+ delete process.env.VITEST;
+ delete process.env.CI;
+ fakeClaude('ok');
+ expect((await upgrade.action!(ctx({ mods: true }))).success).toBe(true);
+ const after = read(settingsFile());
+ expect(after.hooks).toEqual(userSettings.hooks);
+ expect(after.permissions).toEqual(userSettings.permissions);
+ expect(after.env).toEqual({ MY_VAR: 'keep', CLAUDE_CODE_ENABLE_FUNCTION_HOOKS: '1' });
+ expect(after.enabledPlugins).toEqual({ 'mine@elsewhere': true, 'ruflo-swarm@ruflo': false, 'ruflo-mods@ruflo': true, 'ruflo-console@ruflo': true });
+ expect(after.extraKnownMarketplaces.ruflo.source).toEqual({ source: 'github', repo: 'ruvnet/ruflo' });
+ expect(calls()).toContain('plugin install ruflo-mods@ruflo --scope project');
+ // A plugin the user set to false is never installed (claude plugin install would flip it on).
+ expect(calls().join('\n')).not.toContain('ruflo-swarm');
+
+ const text = readFileSync(settingsFile(), 'utf8');
+ const again = await upgrade.action!(ctx({ mods: true }));
+ expect(readFileSync(settingsFile(), 'utf8')).toBe(text);
+ expect((again.data as { settingsUpdated?: string[] }).settingsUpdated ?? []).not.toContain('env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS = "1"');
+
+ await sub(modsCommand, 'uninstall').action!(ctx());
+ expect(read(settingsFile())).toEqual(userSettings);
+ });
+
+ it('--add-missing and --settings include mods; --no-mods opts out', async () => {
+ expect((await upgrade.action!(ctx({ settings: true, mods: false }))).success).toBe(true);
+ expect(read(settingsFile()).enabledPlugins[MOD_PLUGIN_ID]).toBeUndefined();
+ expect((await upgrade.action!(ctx({ settings: true }))).success).toBe(true);
+ expect(read(settingsFile()).enabledPlugins[MOD_PLUGIN_ID]).toBe(true);
+ });
+
+ it('under a test runner (VITEST) the claude step is skipped, never run', async () => {
+ fakeClaude('ok');
+ const r = await upgrade.action!(ctx({ mods: true }));
+ expect(r.success).toBe(true);
+ expect(calls()).toEqual([]);
+ });
+});
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
index 8c6671d001..843b517aa7 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-plugin-resolve.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-plugin-resolve.test.ts
@@ -1,30 +1,33 @@
/**
- * 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.
+ * ADR-404 β€” whether Claude Code can load the enabled ruflo mod plugins
+ * (marketplace clone missing, stale, fresh; plugin pending; cached install),
+ * and the repair `mods install` / `init` run. Mock-first: a fake filesystem
+ * and a fake execFile; nothing here reads the real ~/.claude or runs claude.
*/
import { describe, it, expect } from 'vitest';
import { join } from 'node:path';
import {
claudeConfigDir,
+ cloneHas,
installedState,
marketplaceState,
+ pluginManifestIn,
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 { repairPluginInstall, INSTALL_TIMEOUT_MS, MARKETPLACE_TIMEOUT_MS, type Exec } from '../../src/mods/plugin-repair.js';
+import { MOD_PLUGINS } from '../../src/mods/install.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');
+const manifest = (name: string) => join(CLONE, 'plugins', name, '.claude-plugin', 'plugin.json');
-/** A fake filesystem: paths that exist, and the text of the JSON files among them. */
+/** A fake filesystem: paths that exist, and the text of the files among them. */
function fakeFs(files: Record<string, unknown>, dirs: string[] = []): ReadFs {
const exists = new Set([...Object.keys(files), ...dirs]);
return {
@@ -34,29 +37,25 @@ function fakeFs(files: Record<string, unknown>, dirs: string[] = []): ReadFs {
}
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 fresh = { [manifest('ruflo-mods')]: '{}', [manifest('ruflo-swarm')]: '{}' };
+const staleOnlySwarm = { [manifest('ruflo-swarm')]: '{}' };
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 }] } },
});
+const byName = (findings: ReturnType<typeof resolveFindings>) => Object.fromEntries(findings.map((f) => [f.name, f]));
-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 });
+describe('ADR-404 plugin resolution: the marketplace clone', () => {
+ it('missing, then found via known_marketplaces.json, else the default clone path', () => {
+ expect(marketplaceState(CFG, fakeFs({}))).toEqual({ known: false, location: null });
+ expect(marketplaceState(CFG, fakeFs(known, [CLONE]))).toEqual({ known: true, location: CLONE });
+ expect(marketplaceState(CFG, fakeFs({}, [CLONE]))).toEqual({ known: false, location: CLONE });
});
- 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("finds a plugin through the clone's marketplace.json source, else plugins/<name>", () => {
+ const catalog = { [join(CLONE, '.claude-plugin', 'marketplace.json')]: { plugins: [{ name: 'ruflo-mods', source: './elsewhere/mods' }] } };
+ expect(pluginManifestIn(CLONE, 'ruflo-mods@ruflo', fakeFs(catalog))).toBe(join(CLONE, 'elsewhere', 'mods', '.claude-plugin', 'plugin.json'));
+ expect(pluginManifestIn(CLONE, 'ruflo-swarm@ruflo', fakeFs(catalog))).toBe(manifest('ruflo-swarm'));
+ expect(cloneHas({ known: true, location: CLONE }, 'ruflo-mods@ruflo', fakeFs(fresh))).toBe(true);
});
it('respects CLAUDE_CONFIG_DIR', () => {
@@ -67,119 +66,132 @@ describe('ADR-404 plugin resolution: marketplace clone', () => {
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);
+ expect(installedState(ROOT, CFG, 'ruflo-mods@ruflo', fakeFs(installedHere(), [CACHE]))).toMatchObject({ installed: true, scope: 'local' });
+ expect(installedState('/work/other', CFG, 'ruflo-mods@ruflo', fakeFs(installedHere(), [CACHE])).installed).toBe(false);
+ expect(installedState(ROOT, CFG, 'ruflo-mods@ruflo', 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);
+ it('user scope counts everywhere; a malformed record is not installed', () => {
+ expect(installedState('/x', CFG, 'ruflo-mods@ruflo', fakeFs(installedHere({ scope: 'user', projectPath: undefined }), [CACHE])).installed).toBe(true);
+ expect(installedState(ROOT, CFG, 'ruflo-mods@ruflo', 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: a stale clone and no cached install FAILS with the exact commands', () => {
+ const f = byName(resolveFindings(ROOT, 'local', CFG, fakeFs({ ...known, ...staleOnlySwarm }, [CLONE])));
+ expect(f['plugin ruflo-mods@ruflo']).toMatchObject({ status: 'fail', message: expect.stringContaining('/ruflo-mods is an unknown command') });
+ expect(f['plugin ruflo-mods@ruflo']!.fix).toBe(`cd "${ROOT}" && claude plugin marketplace update ruflo && claude plugin install ruflo-mods@ruflo --scope local && claude plugin install ruflo-swarm@ruflo --scope local`);
+ expect(f['plugin ruflo-swarm@ruflo']!.status).toBe('pass');
+ });
- 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('a plugin not yet in the marketplace is pending (warn), never a failure', () => {
+ const f = byName(resolveFindings(ROOT, 'project', CFG, fakeFs({ ...known, ...fresh }, [CLONE])));
+ expect(f['plugin ruflo-console@ruflo']).toMatchObject({ status: 'warn', message: expect.stringContaining('pending') });
+ expect(MOD_PLUGINS.find((p) => p.id === 'ruflo-console@ruflo')!.required).toBe(false);
});
- it('missing clone: the fix adds the marketplace at the same scope', () => {
+ it('no clone yet: warn (Claude Code clones it at its next interactive start); the fix adds it 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');
+ expect(f['ruflo marketplace']).toMatchObject({ status: 'warn', message: expect.stringContaining('headless -p runs do not') });
+ expect(f['ruflo marketplace']!.fix).toContain('claude plugin marketplace add ruvnet/ruflo --scope project');
+ expect(Object.values(f).some((x) => x.status === 'fail')).toBe(false);
});
- 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('a fresh clone loads the plugin without any install record', () => {
+ const f = byName(resolveFindings(ROOT, 'local', CFG, fakeFs({ ...known, ...fresh }, [CLONE])));
+ expect(f['plugin ruflo-mods@ruflo']).toMatchObject({ status: 'pass', message: 'loads from the marketplace clone' });
});
- 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('a stale clone with a cached install still loads: warn, not fail', () => {
+ const f = byName(resolveFindings(ROOT, 'local', CFG, fakeFs({ ...known, ...staleOnlySwarm, ...installedHere() }, [CLONE, CACHE])));
+ expect(f['plugin ruflo-mods@ruflo']!.status).toBe('warn');
});
- 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('only plugins enabled in settings are checked', () => {
+ const f = byName(resolveFindings(ROOT, 'local', CFG, fakeFs({ ...known, ...fresh }, [CLONE]), ['ruflo-mods@ruflo']));
+ expect(Object.keys(f)).toEqual(['ruflo marketplace', 'plugin ruflo-mods@ruflo']);
});
- it('repairCommands quotes the project root', () => {
- expect(repairCommands('/a b/c', 'local', true)[0]).toBe('cd "/a b/c"');
+ it('repairCommands quotes the project root and installs only required plugins', () => {
+ const cmds = repairCommands('/a b/c', 'local', true);
+ expect(cmds[0]).toBe('cd "/a b/c"');
+ expect(cmds.join('\n')).not.toContain('ruflo-console');
});
});
-describe('ADR-404 mods status distinguishes enabled-in-settings from resolvable', () => {
+describe('ADR-404 mods status distinguishes enabled-in-settings from loadable', () => {
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');
+ const probe = () => probeMods({ projectRoot: root, home: root, env: {}, managedPath: join(root, 'none'), installs: [], configDir: CFG, fs: fakeFs({ ...known, ...staleOnlySwarm }, [CLONE]) });
+ expect(probe().map((f) => f.name)).not.toContain('plugin ruflo-mods@ruflo');
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') });
+ expect(findings.find((f) => f.name === 'plugin ruflo-mods@ruflo')).toMatchObject({ status: 'fail', fix: expect.stringContaining('--scope local') });
+ expect(findings.map((f) => f.name)).not.toContain('plugin ruflo-swarm@ruflo'); // not enabled here
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});
-describe('ADR-404 repair on install', () => {
+describe('ADR-404 repair', () => {
type Call = { file: string; args: readonly string[]; cwd: string; timeout: number };
- const fakeExec = (codes: number[]) => {
+ /** Exit codes in call order; after the marketplace step the clone holds `afterMarket`. */
+ const harness = (codes: number[], afterMarket: Record<string, unknown>) => {
const calls: Call[] = [];
+ let files: Record<string, unknown> = {};
+ const fs: ReadFs = { exists: (p) => fakeFs(files, files === afterMarket ? [CLONE] : []).exists(p), readText: (p) => fakeFs(files).readText(p) };
const exec: Exec = async (file, args, opts) => {
calls.push({ file, args, cwd: opts.cwd, timeout: opts.timeout });
const code = codes[calls.length - 1] ?? 0;
+ if (args[1] === 'marketplace' && code === 0) files = afterMarket;
return { code, stdout: code === 0 ? 'ok' : '', stderr: code === 0 ? '' : 'Marketplace not reachable' };
};
- return { exec, calls };
+ return { exec, calls, fs };
};
- 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: {} });
+ it('adds the unknown marketplace at the scope, then installs what the clone carries; ruflo-console is pending', async () => {
+ const { exec, calls, fs } = harness([], { ...known, ...fresh });
+ const r = await repairPluginInstall({ projectRoot: ROOT, scope: 'project', configDir: CFG, claude: '/bin/claude', exec, env: {}, fs });
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 },
+ expect(calls.map((c) => [c.args.join(' '), c.cwd, c.timeout])).toEqual([
+ ['plugin marketplace add ruvnet/ruflo --scope project', ROOT, MARKETPLACE_TIMEOUT_MS],
+ ['plugin install ruflo-mods@ruflo --scope project', ROOT, INSTALL_TIMEOUT_MS],
+ ['plugin install ruflo-swarm@ruflo --scope project', ROOT, INSTALL_TIMEOUT_MS],
]);
+ expect(r.steps.at(-1)).toMatchObject({ state: 'pending', argv: ['plugin', 'install', 'ruflo-console@ruflo', '--scope', 'project'] });
+ expect(calls.flatMap((c) => c.args)).not.toContain('-y');
});
- 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('a required plugin still missing after the update is a failure', async () => {
+ const { exec, fs } = harness([], { ...known, ...staleOnlySwarm });
+ const r = await repairPluginInstall({ projectRoot: ROOT, scope: 'local', configDir: CFG, claude: '/bin/claude', exec, env: {}, fs });
+ expect(r.ok).toBe(false);
+ expect(r.steps.find((s) => s.argv.includes('ruflo-mods@ruflo'))).toMatchObject({ state: 'failed' });
});
- 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('a failed marketplace step stops everything; a failed install is collected and the rest still run', async () => {
+ const first = harness([1], { ...known, ...fresh });
+ const stop = await repairPluginInstall({ projectRoot: ROOT, scope: 'local', configDir: CFG, claude: '/bin/claude', exec: first.exec, env: {}, fs: first.fs });
+ expect(stop.ok).toBe(false);
+ expect(first.calls).toHaveLength(1);
+ const second = harness([0, 1, 0], { ...known, ...fresh });
+ const collected = await repairPluginInstall({ projectRoot: ROOT, scope: 'local', configDir: CFG, claude: '/bin/claude', exec: second.exec, env: {}, fs: second.fs });
+ expect(collected.ok).toBe(false);
+ expect(second.calls).toHaveLength(3);
});
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' }] });
+ const r = await repairPluginInstall({ projectRoot: ROOT, scope: 'local', configDir: CFG, claude: '/missing', exec, env: {}, fs: fakeFs({}) });
+ expect(r).toMatchObject({ ok: false, steps: [{ state: 'failed', output: 'spawn ENOENT' }] });
});
});
diff --git a/v3/@claude-flow/cli/scripts/e2e-mods-init.sh b/v3/@claude-flow/cli/scripts/e2e-mods-init.sh
new file mode 100755
index 0000000000..18f7ab584a
--- /dev/null
+++ b/v3/@claude-flow/cli/scripts/e2e-mods-init.sh
@@ -0,0 +1,203 @@
+#!/usr/bin/env bash
+# ADR-404 Amendment 1 β€” end-to-end check of mods default-on in `ruflo init`,
+# against the BUILT CLI and the real `claude`, with an isolated HOME and
+# CLAUDE_CONFIG_DIR per scenario (never the real ~/.claude). Needs network
+# (it clones github.com/ruvnet/ruflo) and is not part of `npm test`.
+#
+# bash scripts/e2e-mods-init.sh # scenarios 1-4 and 6
+# E2E_LIVE=1 bash scripts/e2e-mods-init.sh # also 5: a live interactive session in tmux
+#
+# The live scenario copies ONLY ~/.claude/.credentials.json into the isolated
+# config dir for the session and shreds it on exit. Prints one PASS/FAIL line
+# per assertion and exits 1 if any failed.
+set -uo pipefail
+
+CLI_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+CLI="$CLI_DIR/bin/cli.js"
+[[ -f "$CLI_DIR/dist/src/index.js" ]] || { echo "build the CLI first (npm run build)"; exit 2; }
+CLAUDE_BIN="${CLAUDE_BIN:-$(command -v claude || true)}"
+[[ -x "$CLAUDE_BIN" ]] || { echo "no claude binary (set CLAUDE_BIN)"; exit 2; }
+NODE_BIN="$(command -v node)"
+STALE_TAG="${STALE_TAG:-v3.38.21}"
+REAL_CREDS="${REAL_CREDS:-$HOME/.claude/.credentials.json}"
+
+WORK="$(mktemp -d "${TMPDIR:-/tmp}/ruflo-e2e-mods.XXXXXX")"
+CREDS=()
+cleanup() {
+ for c in "${CREDS[@]}"; do [[ -f "$c" ]] && { shred -u "$c" 2>/dev/null || rm -f "$c"; }; done
+ tmux -L ruflo-e2e-mods kill-server 2>/dev/null || true
+ # The initialized projects' classic hooks start npx children (statusline,
+ # funnel refresh); stop any still running in the scratch tree before removing it.
+ for p in /proc/[0-9]*; do [[ "$(readlink "$p/cwd" 2>/dev/null)" == "$WORK"* ]] && kill "${p#/proc/}" 2>/dev/null; done
+ [[ -n "${E2E_KEEP:-}" ]] || { sleep 1; chmod -R u+w "$WORK" 2>/dev/null; rm -rf "$WORK"; }
+}
+trap cleanup EXIT
+unset CI VITEST CLAUDE_CONFIG_DIR
+
+# Two PATHs: one where `claude` resolves, one where it does not. Both hold a
+# fail-fast `codex` stub so init never runs a real `codex plugin marketplace add`.
+mkdir -p "$WORK/bin-with" "$WORK/bin-without"
+for d in bin-with bin-without; do printf '#!/bin/sh\nexit 1\n' > "$WORK/$d/codex"; chmod +x "$WORK/$d/codex"; ln -s "$NODE_BIN" "$WORK/$d/node"; done
+ln -s "$CLAUDE_BIN" "$WORK/bin-with/claude"
+BASE_PATH="/usr/local/bin:/usr/bin:/bin"
+if PATH="$WORK/bin-without:$BASE_PATH" command -v claude >/dev/null; then echo "a claude is on $BASE_PATH; the negative scenario cannot run"; exit 2; fi
+
+fails=0
+pass() { echo "PASS $1"; }
+fail() { echo "FAIL $1"; fails=$((fails + 1)); }
+check() { if eval "$2"; then pass "$1"; else fail "$1"; fi; }
+section() { echo; echo "== $1"; }
+
+# One isolated world per scenario: HOME, CLAUDE_CONFIG_DIR, project.
+world() {
+ local name="$1"
+ W="$WORK/$name"; mkdir -p "$W/home" "$W/cfg" "$W/proj"
+ export HOME="$W/home" CLAUDE_CONFIG_DIR="$W/cfg" USERPROFILE="$W/home" CODEX_HOME="$W/home/.codex"
+ export PATH="$WORK/bin-with:$BASE_PATH"
+}
+ruflo() { (cd "$W/proj" && "$NODE_BIN" "$CLI" "$@"); }
+cc() { (cd "$W/proj" && claude "$@"); }
+# js <expr using s (settings.json), L (plugin list)>: evaluates to true/false.
+js() { "$NODE_BIN" -e "
+ const fs = require('fs');
+ const rd = (p) => { try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return undefined; } };
+ const s = rd('$W/proj/.claude/settings.json') ?? {};
+ const L = rd('$W/plugin-list.json') ?? [];
+ const canon = (v) => Array.isArray(v) ? v.map(canon) : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon(v[k])])) : v;
+ const same = (a, b) => JSON.stringify(canon(a)) === JSON.stringify(canon(b));
+ const has = (id) => L.some((p) => p.id === id && p.enabled !== false);
+ process.exit(($1) ? 0 : 1);"; }
+
+MODS="['ruflo-mods@ruflo','ruflo-swarm@ruflo','ruflo-console@ruflo']"
+
+# ---------------------------------------------------------------------------
+section "1. fresh ruflo init (mods default-on, plugin install at project scope)"
+world fresh
+ruflo init --no-signup --no-global --no-codex-detect > "$W/init.log" 2>&1; rc=$?
+check "init exits 0" "[[ $rc -eq 0 ]]"
+check "settings.json enables all three plugins" "js \"$MODS.every((id) => s.enabledPlugins?.[id] === true)\""
+check "settings.json declares extraKnownMarketplaces.ruflo" "js \"s.extraKnownMarketplaces?.ruflo?.source?.repo === 'ruvnet/ruflo'\""
+check "settings.json sets CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1" "js \"s.env?.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS === '1'\""
+check "classic hooks still written" "js \"JSON.stringify(s.hooks ?? {}).includes('hook-handler.cjs')\""
+check "init ran marketplace add at project scope" "grep -q 'βœ“ claude plugin marketplace add ruvnet/ruflo --scope project' '$W/init.log'"
+check "init installed ruflo-mods and ruflo-swarm" "grep -q 'βœ“ claude plugin install ruflo-mods@ruflo --scope project' '$W/init.log' && grep -q 'βœ“ claude plugin install ruflo-swarm@ruflo --scope project' '$W/init.log'"
+check "init reports ruflo-console pending" "grep -q 'ruflo-console@ruflo --scope project (pending' '$W/init.log'"
+check "init states what loads and the rollout-switch fallback" "grep -q 'rollout switch off, they do nothing and the classic hooks keep every event' '$W/init.log'"
+cc plugin list --json > "$W/plugin-list.json" 2>/dev/null
+check "claude plugin list: ruflo-mods@ruflo installed and enabled" "js \"has('ruflo-mods@ruflo')\""
+check "claude plugin list: ruflo-swarm@ruflo installed and enabled" "js \"has('ruflo-swarm@ruflo')\""
+ruflo mods status --json > "$W/status.json" 2>/dev/null
+check "mods status: ruflo-console reported pending" "grep -A3 'plugin ruflo-console@ruflo' '$W/status.json' | grep -q pending"
+ruflo mods doctor > "$W/doctor.log" 2>&1; rc=$?
+check "mods doctor exits 0" "[[ $rc -eq 0 ]]"
+FRESH_W="$W"
+
+# ---------------------------------------------------------------------------
+section "2. stale marketplace clone ($STALE_TAG, before ruflo-mods) β€” doctor fails, upgrade repairs"
+world stale
+mkdir -p "$W/proj/.claude"
+echo '{}' > "$W/proj/.claude/settings.json"
+claude plugin marketplace add ruvnet/ruflo > "$W/seed.log" 2>&1
+CLONE="$W/cfg/plugins/marketplaces/ruflo"
+git -C "$CLONE" fetch -q --depth=1 origin tag "$STALE_TAG" && git -C "$CLONE" reset -q --hard "$STALE_TAG"
+check "seeded clone is $STALE_TAG without plugins/ruflo-mods" "[[ ! -e '$CLONE/plugins/ruflo-mods' ]]"
+ruflo init upgrade --mods --no-plugin-install > "$W/settings-only.log" 2>&1 # what 3.50.0 left behind: settings only
+ruflo mods doctor > "$W/doctor-stale.log" 2>&1; rc=$?
+check "mods doctor exits 1 on the stale clone" "[[ $rc -eq 1 ]]"
+check "doctor names the stale clone and the unknown command" "grep -q 'is stale' '$W/doctor-stale.log' && grep -q '/ruflo-mods is an unknown command' '$W/doctor-stale.log'"
+check "doctor prints the exact fix" "grep -q 'claude plugin marketplace update ruflo && claude plugin install ruflo-mods@ruflo --scope project' '$W/doctor-stale.log'"
+ruflo doctor --component mods > "$W/doctor-component.log" 2>&1; rc=$?
+check "ruflo doctor --component mods exits 1 too" "[[ $rc -eq 1 ]]"
+ruflo init upgrade --mods > "$W/repair.log" 2>&1
+check "upgrade --mods ran marketplace update" "grep -q 'βœ“ claude plugin marketplace update ruflo' '$W/repair.log'"
+check "the refreshed clone carries plugins/ruflo-mods" "[[ -f '$CLONE/plugins/ruflo-mods/.claude-plugin/plugin.json' ]]"
+ruflo mods doctor > "$W/doctor-after.log" 2>&1; rc=$?
+check "mods doctor exits 0 after the repair" "[[ $rc -eq 0 ]]"
+cc plugin list --json > "$W/plugin-list.json" 2>/dev/null
+check "claude plugin list now has ruflo-mods@ruflo" "js \"has('ruflo-mods@ruflo')\""
+
+# ---------------------------------------------------------------------------
+section "3. ruflo init upgrade --mods on an existing project keeps every user key"
+world upgrade
+mkdir -p "$W/proj/.claude"
+cat > "$W/proj/.claude/settings.json" <<'JSON'
+{
+ "hooks": { "PreToolUse": [{ "matcher": "Bash", "hooks": [{ "type": "command", "command": "echo mine" }] }] },
+ "env": { "MY_VAR": "keep" },
+ "enabledPlugins": { "mine@elsewhere": true, "ruflo-swarm@ruflo": false },
+ "permissions": { "allow": ["Bash(ls)"] }
+}
+JSON
+cp "$W/proj/.claude/settings.json" "$W/user.json"
+ruflo init upgrade --mods > "$W/upgrade1.log" 2>&1
+U="$W/user.json"
+check "user hooks, permissions and MY_VAR unchanged" "js \"same(s.hooks, rd('$U').hooks) && same(s.permissions, rd('$U').permissions) && s.env.MY_VAR === 'keep'\""
+check "mine@elsewhere kept; ruflo-swarm left false (the user's choice)" "js \"s.enabledPlugins['mine@elsewhere'] === true && s.enabledPlugins['ruflo-swarm@ruflo'] === false\""
+check "only the new keys added (mods, console, marketplace, env)" "js \"s.enabledPlugins['ruflo-mods@ruflo'] === true && s.enabledPlugins['ruflo-console@ruflo'] === true && s.extraKnownMarketplaces.ruflo && s.env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS === '1'\""
+check "ruflo-swarm (user set false) was not installed" "! grep -q 'plugin install ruflo-swarm@ruflo' '$W/upgrade1.log'"
+check "upgrade reports what it added" "grep -q 'enabledPlugins\[\"ruflo-mods@ruflo\"\] = true' '$W/upgrade1.log'"
+cp "$W/proj/.claude/settings.json" "$W/after1.json"
+ruflo init upgrade --mods > "$W/upgrade2.log" 2>&1
+check "re-run: settings JSON-equal (idempotent)" "js \"same(s, rd('$W/after1.json'))\""
+check "re-run: reports nothing changed" "grep -q 'already enabled' '$W/upgrade2.log'"
+
+# ---------------------------------------------------------------------------
+section "4. --no-mods writes nothing; mods uninstall reverses exactly"
+world nomods
+ruflo init --no-mods --no-signup --no-global --no-codex-detect > "$W/init.log" 2>&1
+check "--no-mods: no mod plugin, marketplace or env key" "js \"!s.enabledPlugins?.['ruflo-mods@ruflo'] && !s.extraKnownMarketplaces?.ruflo && !s.env?.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS\""
+check "--no-mods: no install record" "[[ ! -e '$W/proj/.claude-flow/mods/install.json' ]]"
+W="$WORK/upgrade"
+ruflo mods uninstall > "$W/uninstall.log" 2>&1
+check "uninstall after upgrade: settings JSON-equal to the user's original" "js \"same(s, rd('$W/user.json'))\""
+
+# ---------------------------------------------------------------------------
+section "6. no claude on PATH: init succeeds and prints the manual commands"
+world noclaude
+export PATH="$WORK/bin-without:$BASE_PATH"
+ruflo init --no-signup --no-global --no-codex-detect > "$W/init.log" 2>&1; rc=$?
+check "init exits 0 without claude" "[[ $rc -eq 0 ]]"
+check "settings still enable the plugins" "js \"s.enabledPlugins?.['ruflo-mods@ruflo'] === true\""
+check "init prints the manual commands" "grep -q 'No runnable claude binary on PATH' '$W/init.log' && grep -q 'claude plugin install ruflo-mods@ruflo --scope project' '$W/init.log'"
+
+# ---------------------------------------------------------------------------
+section "5. live load in an interactive session (E2E_LIVE=1)"
+if [[ -z "${E2E_LIVE:-}" ]]; then
+ echo "SKIP live session not requested (set E2E_LIVE=1; needs ~/.claude/.credentials.json and tmux)"
+fi
+if [[ -n "${E2E_LIVE:-}" ]]; then
+ W="$FRESH_W"
+ export HOME="$W/home" CLAUDE_CONFIG_DIR="$W/cfg" PATH="$WORK/bin-with:$BASE_PATH"
+ install -m 600 "$REAL_CREDS" "$W/cfg/.credentials.json" && CREDS+=("$W/cfg/.credentials.json")
+ "$NODE_BIN" -e "const f='$W/cfg/.claude.json',fs=require('fs');let j={};try{j=JSON.parse(fs.readFileSync(f))}catch{};Object.assign(j,{hasCompletedOnboarding:true,theme:'dark'});fs.writeFileSync(f,JSON.stringify(j))"
+ rm -f "$W/proj/.claude-flow/mods/session.json"
+ tmux -L ruflo-e2e-mods new-session -d -s ruflo-e2e-mods -x 200 -y 50 -c "$W/proj" "HOME='$W/home' CLAUDE_CONFIG_DIR='$W/cfg' PATH='$PATH' claude; echo CLAUDE-EXITED \$?; sleep 600"
+ pane() { tmux -L ruflo-e2e-mods capture-pane -p -t ruflo-e2e-mods; }
+ # Answer the first-start dialogs (folder trust, the project's MCP server,
+ # browser tools); the session starts, and the mod writes its heartbeat, after them.
+ for _ in $(seq 1 240); do
+ sleep 2
+ p="$(pane)"
+ if grep -q 'Yes, I trust this folder' <<<"$p"; then tmux -L ruflo-e2e-mods send-keys -t ruflo-e2e-mods Down; sleep 0.5; tmux -L ruflo-e2e-mods send-keys -t ruflo-e2e-mods Enter
+ elif grep -q 'Select any you wish to enable' <<<"$p"; then tmux -L ruflo-e2e-mods send-keys -t ruflo-e2e-mods Escape
+ elif grep -q 'New MCP server found' <<<"$p"; then tmux -L ruflo-e2e-mods send-keys -t ruflo-e2e-mods Enter # default: continue without it
+ elif grep -q 'Claude in Chrome' <<<"$p"; then tmux -L ruflo-e2e-mods send-keys -t ruflo-e2e-mods Escape
+ elif grep -q 'Select login method' <<<"$p"; then echo "login prompt: credentials not accepted"; break
+ elif grep -q 'CLAUDE-EXITED' <<<"$p"; then echo "claude exited:"; grep -v '^\s*$' <<<"$p" | tail -8; break
+ elif [[ -f "$W/proj/.claude-flow/mods/session.json" ]] && grep -q '❯' <<<"$p"; then break
+ fi
+ done
+ check "live: the mod wrote its heartbeat (.claude-flow/mods/session.json)" "[[ -f '$W/proj/.claude-flow/mods/session.json' ]]"
+ tmux -L ruflo-e2e-mods send-keys -t ruflo-e2e-mods '/ruflo-mods' Enter
+ for _ in $(seq 1 15); do sleep 2; pane > "$W/live-pane.txt"; grep -q 'owns:' "$W/live-pane.txt" && break; done
+ check "live: /ruflo-mods answers (owns: …)" "grep -q 'owns:' '$W/live-pane.txt'"
+ check "live: no 'Unknown command: /ruflo-mods'" "! grep -q 'Unknown command: /ruflo-mods' '$W/live-pane.txt'"
+ sed -n '/ruflo-mods/,$p' "$W/live-pane.txt" | grep -v '^\s*$' | head -14
+ ruflo mods doctor > "$W/doctor-live.log" 2>&1
+ check "live: mods doctor reports the last mod start" "grep -q 'βœ“ last mod start' '$W/doctor-live.log'"
+ tmux -L ruflo-e2e-mods kill-server
+fi
+
+echo
+echo "$fails failure(s)"
+[[ $fails -eq 0 ]]
diff --git a/v3/@claude-flow/cli/src/commands/init.ts b/v3/@claude-flow/cli/src/commands/init.ts
index 3b32af492a..a29b2746d3 100644
--- a/v3/@claude-flow/cli/src/commands/init.ts
+++ b/v3/@claude-flow/cli/src/commands/init.ts
@@ -866,16 +866,17 @@ const initClaudeAction = async (ctx: CommandContext): Promise<CommandResult> =>
}
}
- // ADR-404 β€” opt into the Claude Code mod path. Additive: the classic
- // hooks just written stay the default and the fallback.
- if (ctx.flags.mods === true) {
+ // ADR-404 (amended: mods default-on in init) β€” enable the ruflo mod
+ // plugins in the committed .claude/settings.json, then install them with
+ // claude. Additive: the classic hooks just written stay the fallback.
+ // --no-mods opts out; --no-plugin-install writes settings only.
+ if (ctx.flags.mods !== false) {
output.writeln();
try {
- const { installMod } = await import('../mods/install.js');
- const installed = installMod(ctx.cwd, 'local');
- output.writeln(output.success(` βœ“ ruflo-mods enabled in ${installed.settingsFile} (early access; run "ruflo mods doctor")`));
+ const { applyMods } = await import('../mods/apply.js');
+ await applyMods(ctx.cwd, { scope: 'project', pluginInstall: ctx.flags.pluginInstall !== false && ctx.flags['plugin-install'] !== false, skipInTestEnv: true });
} catch (err) {
- output.writeln(output.warning(` ruflo-mods not enabled: ${err instanceof Error ? err.message : String(err)}`));
+ output.writeln(output.warning(` ruflo mods not enabled: ${err instanceof Error ? err.message : String(err)}`));
}
}
@@ -1457,14 +1458,27 @@ const upgradeCommand: Command = {
{
name: 'settings',
short: 's',
- description: 'Merge new settings (Agent Teams, hooks) into existing settings.json',
+ description: 'Merge new settings (Agent Teams, hooks, ruflo mods) into existing settings.json',
type: 'boolean',
default: false,
},
+ {
+ // ADR-404 amendment β€” the same merge + plugin install as `ruflo init`.
+ name: 'mods',
+ description: 'Merge the ruflo mod plugins into .claude/settings.json and install them (also implied by --add-missing and --settings; --no-mods to skip)',
+ type: 'boolean',
+ },
+ {
+ name: 'plugin-install',
+ description: 'With mods: run claude plugin install (--no-plugin-install to merge settings only)',
+ type: 'boolean',
+ default: true,
+ },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const addMissing = (ctx.flags['add-missing'] || ctx.flags.addMissing) as boolean;
const upgradeSettings = (ctx.flags.settings) as boolean;
+ const upgradeMods = ctx.flags.mods === true || (ctx.flags.mods !== false && (addMissing || upgradeSettings));
output.writeln();
output.writeln(output.bold('Upgrading RuFlo'));
@@ -1501,6 +1515,15 @@ const upgradeCommand: Command = {
spinner.succeed('Upgrade complete!');
output.writeln();
+ // ADR-404 amendment β€” merge the mod plugins without clobbering: only
+ // keys that are absent are added, and each is reported.
+ if (upgradeMods) {
+ const { applyMods, describeAdded } = await import('../mods/apply.js');
+ const mods = await applyMods(ctx.cwd, { scope: 'project', pluginInstall: ctx.flags.pluginInstall !== false && ctx.flags['plugin-install'] !== false, skipInTestEnv: true });
+ result.settingsUpdated = [...(result.settingsUpdated ?? []), ...describeAdded(mods.install.added)];
+ output.writeln();
+ }
+
// Show what was updated
if (result.updated.length > 0) {
output.printBox(
@@ -1683,11 +1706,17 @@ export const initCommand: Command = {
default: false,
},
{
- // ADR-404 β€” Claude Code function hooks are early access; opt-in only.
+ // ADR-404 amendment β€” on by default; nothing loads where function hooks are off.
name: 'mods',
- description: 'Also enable the ruflo Claude Code mod (function hooks, early access); classic hooks stay as fallback',
+ description: 'Enable the ruflo mod plugins in .claude/settings.json (default on; --no-mods to skip); classic hooks stay as fallback',
type: 'boolean',
- default: false,
+ default: true,
+ },
+ {
+ name: 'plugin-install',
+ description: 'With mods: refresh the ruflo marketplace and claude plugin install the mods (--no-plugin-install to write settings only)',
+ type: 'boolean',
+ default: true,
},
{
name: 'with-embeddings',
diff --git a/v3/@claude-flow/cli/src/commands/mods.ts b/v3/@claude-flow/cli/src/commands/mods.ts
index 3f8b710a2c..77ef9d3f67 100644
--- a/v3/@claude-flow/cli/src/commands/mods.ts
+++ b/v3/@claude-flow/cli/src/commands/mods.ts
@@ -2,7 +2,7 @@
* `ruflo mods` β€” opt into running ruflo as a Claude Code mod (ADR-404,
* Claude Code function hooks, early access).
*
- * install/uninstall edit one settings file and record what they added;
+ * install/uninstall edit settings files and record what they added;
* status/doctor report what can be known from outside a session; sync-policy
* rewrites the policy projection the mod's tool check reads. Classic hooks
* are never removed: they stay the default and the fallback.
@@ -10,11 +10,9 @@
import type { Command, CommandContext, CommandResult } from '../types.js';
import { output } from '../output.js';
-import { installMod, uninstallMod, type Scope } from '../mods/install.js';
+import { 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';
+import { applyMods } from '../mods/apply.js';
function projectRoot(ctx: CommandContext): string {
return (ctx.flags.projectRoot as string | undefined) ?? (ctx.flags['project-root'] as string | undefined) ?? ctx.cwd ?? process.cwd();
@@ -32,13 +30,13 @@ const rootOption = { name: 'project-root', description: 'Project root (default:
const installSub: Command = {
name: 'install',
- description: 'Enable the ruflo-mods plugin for this project (opt-in; classic hooks stay as fallback)',
+ description: 'Enable the ruflo mod plugins (ruflo-mods, ruflo-swarm, ruflo-console) for this project; classic hooks stay as fallback',
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 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 },
+ { name: 'strict', description: 'Exit 1 when a required plugin could not be made loadable', type: 'boolean', default: false },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const scope = (ctx.flags.scope as string | undefined) ?? 'local';
@@ -46,63 +44,18 @@ const installSub: Command = {
output.printError(`--scope must be local or project, got ${scope}`);
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})` : ''}`);
- 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 } };
+ const result = await applyMods(projectRoot(ctx), {
+ scope: scope as Scope,
+ dryRun: ctx.flags.dryRun === true || ctx.flags['dry-run'] === true,
+ pluginInstall: ctx.flags.pluginInstall !== false && ctx.flags['plugin-install'] !== false,
+ });
+ if (result.install.dryRun) return { success: true, data: result };
+ if (result.resolvable) output.writeln('Restart Claude Code, then run /ruflo-mods in a session to see what the mod owns. Check with: ruflo mods doctor');
+ const data = { ...result.install, resolvable: result.resolvable };
+ return result.resolvable || ctx.flags.strict !== true ? { success: true, data } : { success: false, exitCode: 1, data };
},
};
-/**
- * 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)',
@@ -113,7 +66,7 @@ const uninstallSub: Command = {
output.printWarning('No install record (.claude-flow/mods/install.json): nothing ruflo added to remove.');
return { success: true, data: result };
}
- output.printSuccess(`${result.dryRun ? 'Would remove' : 'Removed'} ruflo-mods from ${result.settingsFile}`);
+ output.printSuccess(`${result.dryRun ? 'Would remove' : 'Removed'} what ruflo mods added from ${result.settingsFiles.join(', ')}`);
return { success: true, data: result };
},
};
@@ -170,9 +123,10 @@ export const modsCommand: Command = {
syncPolicySub,
],
examples: [
- { command: 'ruflo mods install', description: 'Enable for this project (settings.local.json) and install the plugin with claude' },
+ { command: 'ruflo mods install', description: 'Enable the mod plugins for this checkout (settings.local.json) and install them with claude' },
+ { command: 'ruflo mods install --scope project', description: 'Same, in the committed settings.json (what ruflo init does)' },
{ 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 doctor', description: 'Marketplace fresh? Plugins loadable? Function hooks on? Refused by policy?' },
{ command: 'ruflo mods uninstall', description: 'Remove only what install added' },
],
action: statusSub.action,
diff --git a/v3/@claude-flow/cli/src/mods/apply.ts b/v3/@claude-flow/cli/src/mods/apply.ts
new file mode 100644
index 0000000000..04fb05e1a9
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mods/apply.ts
@@ -0,0 +1,120 @@
+/**
+ * Turn the ruflo mods on for a project (ADR-404): merge the settings, sync the
+ * policy projection, then make the plugins loadable with `claude`. One path
+ * for `ruflo mods install`, `ruflo init` and `ruflo init upgrade --mods`.
+ */
+
+import { homedir } from 'node:os';
+
+import { output } from '../output.js';
+import { installMod, MOD_PLUGINS, type Added, type InstallResult, type ModPlugin, type Scope } from './install.js';
+import { findClaudeBinary, installArgv, marketplaceArgv, repairPluginInstall, type Exec } from './plugin-repair.js';
+import { claudeConfigDir, marketplaceState, repairCommands, resolveFindings } from './plugin-resolve.js';
+
+export interface ApplyOptions {
+ scope: Scope;
+ dryRun?: boolean;
+ /** Run `claude plugin marketplace …` and `claude plugin install …` (default true). */
+ pluginInstall?: boolean;
+ /**
+ * Skip the `claude` step under a test runner or CI (VITEST / CI set): an
+ * init there must never clone from GitHub into whatever config dir is live.
+ */
+ skipInTestEnv?: boolean;
+ /** Injectable for tests. */
+ exec?: Exec;
+}
+
+export interface ApplyResult {
+ install: InstallResult;
+ /** Whether every required plugin was left loadable (true when the step was skipped by request). */
+ resolvable: boolean;
+ /** Why the `claude` step did not run, when it did not. */
+ skipped?: string;
+}
+
+/** One line per thing a run added; empty on a re-run. */
+export function describeAdded(added: Added): string[] {
+ return [
+ ...added.plugins.map((id) => `enabledPlugins["${id}"] = true`),
+ ...(added.marketplace ? ['extraKnownMarketplaces.ruflo = github ruvnet/ruflo'] : []),
+ ...(added.env ? ['env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS = "1"'] : []),
+ ];
+}
+
+/** What default-on means, said exactly (ADR-404 amendment). */
+export const LOAD_NOTE = [
+ 'ruflo-mods and ruflo-console run only where Claude Code function hooks are on: with them off, or the rollout switch off, they do nothing and the classic hooks keep every event.',
+ "ruflo-swarm's commands, skills and agents load regardless; its live pane needs function hooks.",
+];
+
+async function syncPolicyQuietly(root: string): Promise<void> {
+ try {
+ const { loadPolicyState } = await import('../services/policy-runtime.js');
+ const { syncPolicyProjection } = await import('./policy-projection.js');
+ const result = syncPolicyProjection(root, loadPolicyState(root));
+ if (result.action !== 'unchanged') output.writeln(`policy projection: ${result.action} (${result.path})`);
+ } catch (error) {
+ output.printWarning(`policy projection not synced: ${(error as Error).message}`);
+ }
+}
+
+function printManual(root: string, scope: Scope, known: boolean, plugins: readonly ModPlugin[]): void {
+ output.writeln('Run these to make the plugins loadable:');
+ for (const line of repairCommands(root, scope, known, plugins)) output.writeln(` ${line}`);
+}
+
+export async function applyMods(root: string, opts: ApplyOptions): Promise<ApplyResult> {
+ const install = installMod(root, opts.scope, opts.dryRun === true);
+ const configDir = claudeConfigDir(process.env, homedir());
+ const known = marketplaceState(configDir).known;
+ const lines = describeAdded(install.added);
+ // Only what is enabled in the file: `claude plugin install` would flip a
+ // plugin someone set to false back to true.
+ const enabled = (install.next.enabledPlugins ?? {}) as Record<string, unknown>;
+ const plugins = MOD_PLUGINS.filter((p) => enabled[p.id] === true);
+
+ if (install.dryRun) {
+ output.writeln(`Would write ${install.settingsFile}:`);
+ output.printJson(install.next);
+ if (opts.pluginInstall !== false) {
+ output.writeln('Would run:');
+ for (const argv of [marketplaceArgv(opts.scope, known), ...plugins.map((p) => installArgv(p.id, opts.scope))]) output.writeln(` claude ${argv.join(' ')}`);
+ }
+ return { install, resolvable: true };
+ }
+
+ await syncPolicyQuietly(root);
+ if (lines.length) {
+ output.printSuccess(`ruflo mods enabled in ${install.settingsFile}${install.backup ? ` (backup: ${install.backup})` : ''}`);
+ for (const line of lines) output.writeln(` + ${line}`);
+ } else {
+ output.printSuccess(`ruflo mods already enabled in ${install.settingsFile} (nothing changed)`);
+ }
+ for (const line of LOAD_NOTE) output.writeln(output.dim(line));
+
+ if (opts.pluginInstall === false) return { install, resolvable: true, skipped: '--no-plugin-install' };
+ if (opts.skipInTestEnv && (process.env.VITEST || process.env.CI)) {
+ output.writeln(output.dim(`claude plugin step skipped (${process.env.VITEST ? 'VITEST' : 'CI'} set).`));
+ printManual(root, opts.scope, known, plugins);
+ return { install, resolvable: false, skipped: 'test or CI environment' };
+ }
+ const claude = findClaudeBinary(process.env, homedir());
+ if (!claude) {
+ output.printWarning('No runnable claude binary on PATH: the plugins are enabled in settings, not installed.');
+ printManual(root, opts.scope, known, plugins);
+ return { install, resolvable: false, skipped: 'no claude on PATH' };
+ }
+
+ const repair = await repairPluginInstall({ projectRoot: root, scope: opts.scope, configDir, claude, plugins, exec: opts.exec });
+ for (const step of repair.steps) {
+ const mark = step.state === 'ok' ? output.success('βœ“') : step.state === 'pending' ? output.warning('…') : output.error('βœ—');
+ output.writeln(`${mark} claude ${step.argv.join(' ')}${step.state === 'pending' ? ' (pending: not in the ruflo marketplace yet)' : ''}`);
+ if (step.state === 'failed' && step.output) output.writeln(output.dim(` ${step.output.split('\n').slice(-3).join('\n ')}`));
+ }
+ const failed = resolveFindings(root, opts.scope, configDir, undefined, plugins.map((p) => p.id)).filter((f) => f.status === 'fail');
+ if (repair.ok && failed.length === 0) return { install, resolvable: true };
+ for (const f of failed) output.writeln(`${output.error('βœ—')} ${f.name}: ${f.message}`);
+ printManual(root, opts.scope, marketplaceState(configDir).known, plugins);
+ return { install, resolvable: false };
+}
diff --git a/v3/@claude-flow/cli/src/mods/install.ts b/v3/@claude-flow/cli/src/mods/install.ts
index 2f02ff7383..b98a476220 100644
--- a/v3/@claude-flow/cli/src/mods/install.ts
+++ b/v3/@claude-flow/cli/src/mods/install.ts
@@ -1,14 +1,16 @@
/**
- * `ruflo mods install|uninstall` (ADR-404): enable the ruflo-mods plugin for
- * one project, opt-in, and take back exactly what was added.
+ * `ruflo mods install|uninstall` (ADR-404): enable the ruflo mods for one
+ * project, and take back exactly what was added.
*
- * Writes three keys of a Claude Code settings file (`.claude/settings.local.json`
- * by default, so the early-access feature is one person's choice, not the
- * repository's): `enabledPlugins["ruflo-mods@ruflo"]`, the `ruflo` entry of
+ * Writes three kinds of key in a Claude Code settings file: one
+ * `enabledPlugins` entry per plugin in MOD_PLUGINS, the `ruflo` entry of
* `extraKnownMarketplaces` when absent, and `env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS`.
- * What was added is recorded in `.claude-flow/mods/install.json`, so uninstall
- * removes those and nothing a person set themselves. Classic hooks are never
- * touched: they stay the fallback (the mod takes an event over at runtime only).
+ * `ruflo init` writes them to the committed `.claude/settings.json` (project
+ * scope); a standalone `ruflo mods install` defaults to
+ * `.claude/settings.local.json`. What was added is recorded per settings file
+ * in `.claude-flow/mods/install.json`, so uninstall removes those and nothing
+ * a person set themselves. Classic hooks are never touched: they stay the
+ * fallback (a mod takes an event over at runtime only).
*/
import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
@@ -20,13 +22,37 @@ export const MARKETPLACE_SOURCE = { source: { source: 'github', repo: 'ruvnet/ru
export const ENABLE_ENV = 'CLAUDE_CODE_ENABLE_FUNCTION_HOOKS';
export const INSTALL_RECORD = join('.claude-flow', 'mods', 'install.json');
+export interface ModPlugin {
+ id: string;
+ /**
+ * Missing from a ruflo marketplace clone means the clone is stale (a
+ * failure). A plugin not yet released on main is `required: false`: missing
+ * is "pending", never a failure. Flip it once the plugin lands.
+ */
+ required: boolean;
+}
+
+/** Every plugin `ruflo mods install` and `ruflo init` enable. The one list to edit. */
+export const MOD_PLUGINS: readonly ModPlugin[] = [
+ { id: MOD_PLUGIN_ID, required: true },
+ { id: 'ruflo-swarm@ruflo', required: true },
+ { id: 'ruflo-console@ruflo', required: false }, // pending: feat/ruflo-console-mod
+];
+export const MOD_PLUGIN_IDS: readonly string[] = MOD_PLUGINS.map((p) => p.id);
+
export type Scope = 'local' | 'project';
+export interface Added {
+ plugins: string[];
+ marketplace: boolean;
+ env: boolean;
+}
+
export interface InstallRecord {
- version: 1;
- settingsFile: string;
+ version: 2;
installedAt: string;
- added: { plugin: boolean; marketplace: boolean; env: boolean };
+ /** What install added, per settings file it wrote. */
+ files: Record<string, Added>;
}
type Settings = Record<string, unknown> & {
@@ -58,28 +84,31 @@ function writeJson(path: string, value: unknown): void {
renameSync(tmp, path);
}
-/** The settings after install, and what install added (pure). */
-export function withModEnabled(settings: Settings): { next: Settings; added: InstallRecord['added'] } {
+const nothingAdded = (a: Added) => a.plugins.length === 0 && !a.marketplace && !a.env;
+
+/** The settings after install, and what install added (pure). Existing values are kept. */
+export function withModEnabled(settings: Settings, plugins: readonly string[] = MOD_PLUGIN_IDS): { next: Settings; added: Added } {
const next: Settings = { ...settings };
- const plugins = isRecord(settings.enabledPlugins) ? { ...settings.enabledPlugins } : {};
+ const enabled = isRecord(settings.enabledPlugins) ? { ...settings.enabledPlugins } : {};
const markets = isRecord(settings.extraKnownMarketplaces) ? { ...settings.extraKnownMarketplaces } : {};
const env = isRecord(settings.env) ? { ...settings.env } : {};
- const added = {
- plugin: plugins[MOD_PLUGIN_ID] !== true,
+ // A plugin a person set to false is their decision: never flipped.
+ const added: Added = {
+ plugins: plugins.filter((id) => !(id in enabled)),
marketplace: !(MARKETPLACE_NAME in markets),
- env: env[ENABLE_ENV] !== '1',
+ env: !(ENABLE_ENV in env),
};
- plugins[MOD_PLUGIN_ID] = true;
+ for (const id of added.plugins) enabled[id] = true;
if (added.marketplace) markets[MARKETPLACE_NAME] = MARKETPLACE_SOURCE;
- env[ENABLE_ENV] = '1';
- next.enabledPlugins = plugins;
+ if (added.env) env[ENABLE_ENV] = '1';
+ next.enabledPlugins = enabled;
next.extraKnownMarketplaces = markets;
next.env = env;
return { next, added };
}
/** The settings after uninstall: only what the record says install added (pure). */
-export function withModRemoved(settings: Settings, added: InstallRecord['added']): Settings {
+export function withModRemoved(settings: Settings, added: Added): Settings {
const next: Settings = { ...settings };
const drop = (key: 'enabledPlugins' | 'extraKnownMarketplaces' | 'env', name: string) => {
const section = next[key];
@@ -89,7 +118,7 @@ export function withModRemoved(settings: Settings, added: InstallRecord['added']
if (Object.keys(copy).length === 0) delete next[key];
else next[key] = copy;
};
- if (added.plugin) drop('enabledPlugins', MOD_PLUGIN_ID);
+ for (const id of added.plugins) drop('enabledPlugins', id);
if (added.marketplace) drop('extraKnownMarketplaces', MARKETPLACE_NAME);
if (added.env) drop('env', ENABLE_ENV);
return next;
@@ -98,16 +127,17 @@ export function withModRemoved(settings: Settings, added: InstallRecord['added']
export interface InstallResult {
settingsFile: string;
backup?: string;
- added: InstallRecord['added'];
+ /** What this run added (empty on a re-run). */
+ added: Added;
dryRun: boolean;
next: Settings;
}
-export function installMod(projectRoot: string, scope: Scope, dryRun = false): InstallResult {
+export function installMod(projectRoot: string, scope: Scope, dryRun = false, plugins: readonly string[] = MOD_PLUGIN_IDS): InstallResult {
const settingsFile = settingsFileFor(projectRoot, scope);
const current = readSettingsFile(settingsFile);
- const { next, added } = withModEnabled(current);
- if (dryRun) return { settingsFile, added, dryRun, next };
+ const { next, added } = withModEnabled(current, plugins);
+ if (dryRun || nothingAdded(added)) return { settingsFile, added, dryRun, next };
let backup: string | undefined;
if (existsSync(settingsFile)) {
@@ -115,41 +145,58 @@ export function installMod(projectRoot: string, scope: Scope, dryRun = false): I
copyFileSync(settingsFile, backup);
}
writeJson(settingsFile, next);
- const recordPath = join(resolve(projectRoot), INSTALL_RECORD);
- const previous = readRecord(projectRoot);
- // A second install keeps the first record's claims: what ruflo added once
- // is still ruflo's to remove.
- const merged = previous && previous.settingsFile === settingsFile
- ? { plugin: previous.added.plugin || added.plugin, marketplace: previous.added.marketplace || added.marketplace, env: previous.added.env || added.env }
- : added;
- const record: InstallRecord = { version: 1, settingsFile, installedAt: new Date().toISOString(), added: merged };
- writeJson(recordPath, record);
- return { settingsFile, backup, added: merged, dryRun, next };
+ // What ruflo added once is still ruflo's to remove: merge into the record.
+ const record = readRecord(projectRoot) ?? { version: 2, installedAt: '', files: {} };
+ const before = record.files[settingsFile] ?? { plugins: [], marketplace: false, env: false };
+ record.files[settingsFile] = {
+ plugins: [...new Set([...before.plugins, ...added.plugins])],
+ marketplace: before.marketplace || added.marketplace,
+ env: before.env || added.env,
+ };
+ record.installedAt = new Date().toISOString();
+ writeJson(join(resolve(projectRoot), INSTALL_RECORD), record);
+ return { settingsFile, backup, added, dryRun, next };
}
+/** The install record, v1 (3.50.0: one file, ruflo-mods only) read as v2. */
export function readRecord(projectRoot: string): InstallRecord | null {
const path = join(resolve(projectRoot), INSTALL_RECORD);
if (!existsSync(path)) return null;
try {
- const parsed = JSON.parse(readFileSync(path, 'utf8')) as InstallRecord;
- return parsed && parsed.version === 1 && typeof parsed.settingsFile === 'string' && isRecord(parsed.added) ? parsed : null;
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;
+ if (parsed.version === 2 && isRecord(parsed.files)) {
+ const files: Record<string, Added> = {};
+ for (const [file, a] of Object.entries(parsed.files)) {
+ if (!isRecord(a)) continue;
+ files[file] = { plugins: Array.isArray(a.plugins) ? a.plugins.filter((p): p is string => typeof p === 'string') : [], marketplace: a.marketplace === true, env: a.env === true };
+ }
+ return { version: 2, installedAt: String(parsed.installedAt ?? ''), files };
+ }
+ if (parsed.version === 1 && typeof parsed.settingsFile === 'string' && isRecord(parsed.added)) {
+ const a = parsed.added;
+ return { version: 2, installedAt: String(parsed.installedAt ?? ''), files: { [parsed.settingsFile]: { plugins: a.plugin === true ? [MOD_PLUGIN_ID] : [], marketplace: a.marketplace === true, env: a.env === true } } };
+ }
+ return null;
} catch {
return null;
}
}
-export function uninstallMod(projectRoot: string, dryRun = false): { settingsFile?: string; removed: boolean; dryRun: boolean } {
+export function uninstallMod(projectRoot: string, dryRun = false): { settingsFiles: string[]; removed: boolean; dryRun: boolean } {
const record = readRecord(projectRoot);
- if (!record) return { removed: false, dryRun };
- // The record names the file; never follow it outside this project.
+ if (!record) return { settingsFiles: [], removed: false, dryRun };
+ // The record names the files; never follow one outside this project.
const root = resolve(projectRoot);
- if (!resolve(record.settingsFile).startsWith(join(root, '.claude') + sep)) {
- throw new Error(`install record names a settings file outside ${root}/.claude: ${record.settingsFile}`);
+ const settingsFiles = Object.keys(record.files);
+ for (const file of settingsFiles) {
+ if (!resolve(file).startsWith(join(root, '.claude') + sep)) {
+ throw new Error(`install record names a settings file outside ${root}/.claude: ${file}`);
+ }
}
- if (dryRun) return { settingsFile: record.settingsFile, removed: true, dryRun };
- if (existsSync(record.settingsFile)) {
- writeJson(record.settingsFile, withModRemoved(readSettingsFile(record.settingsFile), record.added));
+ if (dryRun) return { settingsFiles, removed: true, dryRun };
+ for (const file of settingsFiles) {
+ if (existsSync(file)) writeJson(file, withModRemoved(readSettingsFile(file), record.files[file]!));
}
unlinkSync(join(root, INSTALL_RECORD));
- return { settingsFile: record.settingsFile, removed: true, dryRun };
+ return { settingsFiles, removed: true, dryRun };
}
diff --git a/v3/@claude-flow/cli/src/mods/plugin-repair.ts b/v3/@claude-flow/cli/src/mods/plugin-repair.ts
index 83f5ae6e4d..78f13eb02c 100644
--- a/v3/@claude-flow/cli/src/mods/plugin-repair.ts
+++ b/v3/@claude-flow/cli/src/mods/plugin-repair.ts
@@ -1,11 +1,14 @@
/**
- * 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>`.
+ * After settings are written, make the mod plugins loadable the way a person
+ * would (ADR-404): refresh (or add) the `ruflo` marketplace clone, then
+ * `claude plugin install <id> --scope <scope>` for each plugin the clone
+ * carries. The refreshed clone is what makes a plugin load; the install adds
+ * a cached copy (and the `claude plugin list` entry) that survives a later
+ * stale clone.
*
* 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
+ * file ruflo 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.
*/
@@ -13,7 +16,8 @@
import { execFile } from 'node:child_process';
import { findClaudeInstalls } from './claude-installs.js';
-import { MARKETPLACE_NAME, MOD_PLUGIN_ID, type Scope } from './install.js';
+import { MARKETPLACE_NAME, MOD_PLUGINS, type ModPlugin, type Scope } from './install.js';
+import { cloneHas, marketplaceState, nodeReadFs, type ReadFs } from './plugin-resolve.js';
export const MARKETPLACE_TIMEOUT_MS = 150_000; // Claude Code's own clone timeout is 120s
export const INSTALL_TIMEOUT_MS = 60_000;
@@ -44,47 +48,70 @@ export function findClaudeBinary(env: NodeJS.ProcessEnv, home: string): string |
return process.platform === 'win32' && !first.path.toLowerCase().endsWith('.exe') ? null : first.path;
}
+export type StepState = 'ok' | 'failed' | 'pending';
+
export interface RepairStep {
argv: string[];
- ok: boolean;
+ state: StepState;
output: string;
}
export interface RepairOptions {
projectRoot: string;
scope: Scope;
- /** The marketplace is in known_marketplaces.json: update it, else add it. */
- marketplaceKnown: boolean;
+ /** Claude Code's config directory, read after the marketplace step to see what the clone carries. */
+ configDir: string;
claude: string;
+ plugins?: readonly ModPlugin[];
exec?: Exec;
env?: NodeJS.ProcessEnv;
+ fs?: ReadFs;
+}
+
+export function marketplaceArgv(scope: Scope, known: boolean): string[] {
+ return known ? ['plugin', 'marketplace', 'update', MARKETPLACE_NAME] : ['plugin', 'marketplace', 'add', 'ruvnet/ruflo', '--scope', scope];
}
-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],
- ];
+export function installArgv(id: string, scope: Scope): string[] {
+ return ['plugin', 'install', id, '--scope', scope];
}
-/** Runs the steps in order and stops at the first failure. */
+/**
+ * Marketplace first (a failure there stops everything: nothing below can
+ * work); then one install per plugin, every failure collected. A plugin the
+ * refreshed clone does not carry is pending when not required, a failure when
+ * required.
+ */
export async function repairPluginInstall(opts: RepairOptions): Promise<{ ok: boolean; steps: RepairStep[] }> {
const exec = opts.exec ?? nodeExec;
const env = opts.env ?? process.env;
+ const fs = opts.fs ?? nodeReadFs;
+ const plugins = opts.plugins ?? MOD_PLUGINS;
const steps: RepairStep[] = [];
- for (const argv of repairArgv(opts.scope, opts.marketplaceKnown)) {
- const timeout = argv[1] === 'marketplace' ? MARKETPLACE_TIMEOUT_MS : INSTALL_TIMEOUT_MS;
+ const run = async (argv: string[], timeout: number): Promise<boolean> => {
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 };
+ steps.push({ argv, state: result.code === 0 ? 'ok' : 'failed', output: `${result.stdout}${result.stderr}`.trim() });
+ return result.code === 0;
+ };
+
+ if (!(await run(marketplaceArgv(opts.scope, marketplaceState(opts.configDir, fs).known), MARKETPLACE_TIMEOUT_MS))) {
+ return { ok: false, steps };
+ }
+ const market = marketplaceState(opts.configDir, fs);
+ let ok = true;
+ for (const plugin of plugins) {
+ const argv = installArgv(plugin.id, opts.scope);
+ if (!cloneHas(market, plugin.id, fs)) {
+ steps.push({ argv, state: plugin.required ? 'failed' : 'pending', output: `${plugin.id} is not in the ruflo marketplace${plugin.required ? ' even after the update' : ' yet (pending)'}` });
+ ok &&= !plugin.required;
+ continue;
+ }
+ ok = (await run(argv, INSTALL_TIMEOUT_MS)) && ok;
}
- return { ok: true, steps };
+ return { ok, steps };
}
diff --git a/v3/@claude-flow/cli/src/mods/plugin-resolve.ts b/v3/@claude-flow/cli/src/mods/plugin-resolve.ts
index 372fd2f3c6..05810580f8 100644
--- a/v3/@claude-flow/cli/src/mods/plugin-resolve.ts
+++ b/v3/@claude-flow/cli/src/mods/plugin-resolve.ts
@@ -1,13 +1,16 @@
/**
- * Whether Claude Code can actually resolve the ruflo-mods plugin (ADR-404).
+ * Whether Claude Code can actually load the ruflo mod plugins (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.
+ * Observed live on Claude Code 2.1.287: an interactive, trusted session clones
+ * the `ruflo` marketplace a project declares and loads an enabled plugin
+ * straight from that clone (no install record needed); a headless `-p` run
+ * clones nothing. A clone from before ruflo-mods shipped has no
+ * `plugins/ruflo-mods`, and Claude Code skips the enabled plugin without a
+ * word: `/ruflo-mods` is an unknown command, and the clone is not refreshed
+ * on start. So the clone decides; an install record (`installed_plugins.json`,
+ * pointing into `plugins/cache/`) is a cached copy that still loads when the
+ * clone goes stale.
*
* Read-only. The config directory is `CLAUDE_CONFIG_DIR` when set, else
* `~/.claude`, as Claude Code itself resolves it.
@@ -16,11 +19,9 @@
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 { MARKETPLACE_NAME, MOD_PLUGINS, type ModPlugin, 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;
@@ -56,13 +57,13 @@ function isRecord(v: unknown): v is Record<string, unknown> {
return v !== null && typeof v === 'object' && !Array.isArray(v);
}
+const nameOf = (id: string) => id.split('@')[0]!;
+
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 {
@@ -70,8 +71,22 @@ export function marketplaceState(configDir: string, fs: ReadFs = nodeReadFs): Ma
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)) };
+ return { known: isRecord(entry), location: candidates.find((p) => fs.exists(p)) ?? null };
+}
+
+/** The plugin's manifest inside a clone: its marketplace.json `source`, else plugins/<name>. */
+export function pluginManifestIn(clone: string, id: string, fs: ReadFs = nodeReadFs): string {
+ const catalog = readJson(fs, join(clone, '.claude-plugin', 'marketplace.json'));
+ const listed = isRecord(catalog) && Array.isArray(catalog.plugins)
+ ? catalog.plugins.find((p) => isRecord(p) && p.name === nameOf(id))
+ : undefined;
+ const source = isRecord(listed) && typeof listed.source === 'string' ? listed.source : `./plugins/${nameOf(id)}`;
+ return join(clone, source, '.claude-plugin', 'plugin.json');
+}
+
+/** The clone carries this plugin. */
+export function cloneHas(market: MarketplaceState, id: string, fs: ReadFs = nodeReadFs): boolean {
+ return market.location !== null && fs.exists(pluginManifestIn(market.location, id, fs));
}
export interface InstalledState {
@@ -90,10 +105,10 @@ function sameDir(a: string, b: string): boolean {
}
/** 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 {
+export function installedState(projectRoot: string, configDir: string, id: 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[]) : [];
+ const entries = plugins && Array.isArray(plugins[id]) ? (plugins[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));
@@ -102,42 +117,62 @@ export function installedState(projectRoot: string, configDir: string, fs: ReadF
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[] {
+/** The exact commands that refresh the clone and install the plugins, for a person to run. */
+export function repairCommands(projectRoot: string, scope: Scope | 'user', known: boolean, plugins: readonly ModPlugin[] = MOD_PLUGINS): 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}`,
+ ...plugins.filter((p) => p.required).map((p) => `claude plugin install ${p.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).
+ * The marketplace finding plus one finding per plugin enabled in settings.
+ * A required plugin missing from the clone with no cached install is the
+ * failure Claude Code hides; a plugin not yet released is "pending".
*/
-export function resolveFindings(projectRoot: string, scope: Scope | 'user', configDir: string, fs: ReadFs = nodeReadFs): Finding[] {
+export function resolveFindings(
+ projectRoot: string,
+ scope: Scope | 'user',
+ configDir: string,
+ fs: ReadFs = nodeReadFs,
+ enabled: readonly string[] = MOD_PLUGINS.map((p) => p.id),
+): 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}` }
+ findings.push(market.location
+ ? { name: 'ruflo marketplace', status: 'pass', message: `cloned at ${market.location}` }
: {
- 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`,
+ name: 'ruflo marketplace',
+ status: 'warn',
+ message: `not cloned under ${join(configDir, 'plugins')}: Claude Code clones it at the next interactive start of a trusted session (headless -p runs do not)`,
fix,
});
+
+ for (const plugin of MOD_PLUGINS.filter((p) => enabled.includes(p.id))) {
+ const name = `plugin ${plugin.id}`;
+ const installed = installedState(projectRoot, configDir, plugin.id, fs);
+ const also = installed.installed ? `; also installed (${installed.scope} scope)` : '';
+ if (cloneHas(market, plugin.id, fs)) {
+ findings.push({ name, status: 'pass', message: `loads from the marketplace clone${also}` });
+ } else if (!market.location) {
+ findings.push(installed.installed
+ ? { name, status: 'pass', message: `installed (${installed.scope} scope, ${installed.installPath})` }
+ : { name, status: 'warn', message: plugin.required ? 'loads once Claude Code has cloned the marketplace' : 'pending: not released in the ruflo marketplace yet' });
+ } else if (!plugin.required) {
+ findings.push({ name, status: 'warn', message: `pending: not in the ruflo marketplace yet (${market.location})${also}` });
+ } else if (installed.installed) {
+ findings.push({ name, status: 'warn', message: `the clone at ${market.location} is stale (no ${nameOf(plugin.id)}); the cached install still loads`, fix });
+ } else {
+ findings.push({
+ name,
+ status: 'fail',
+ message: `the clone at ${market.location} is stale: it predates ${nameOf(plugin.id)}, so Claude Code skips the enabled plugin without a word${plugin.id.startsWith('ruflo-mods@') ? ' (/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 9d12cfc2ab..a56c545bf5 100644
--- a/v3/@claude-flow/cli/src/mods/probe.ts
+++ b/v3/@claude-flow/cli/src/mods/probe.ts
@@ -10,7 +10,7 @@ import { homedir, platform } from 'node:os';
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 { ENABLE_ENV, MOD_PLUGIN_ID, MOD_PLUGIN_IDS, readRecord, readSettingsFile, settingsFileFor } from './install.js';
import { claudeConfigDir, resolveFindings, type ReadFs } from './plugin-resolve.js';
import { PROJECTION_RELATIVE } from './policy-projection.js';
@@ -78,11 +78,18 @@ export function probeMods(inputs: ProbeInputs): Finding[] {
? { 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).
+ // 1a. Enabled is a request; Claude Code silently skips a plugin its
+ // marketplace clone does not carry (a clone older than the plugin).
if (enabledIn) {
const scope = enabledIn === files[0] ? 'local' : enabledIn === files[1] ? 'project' : 'user';
- findings.push(...resolveFindings(root, scope, configDir, inputs.fs));
+ const enabled = MOD_PLUGIN_IDS.filter((id) => files.some((f) => {
+ try {
+ return get(readSettingsFile(f), 'enabledPlugins', id) === true;
+ } catch {
+ return false;
+ }
+ }));
+ findings.push(...resolveFindings(root, scope, configDir, inputs.fs, enabled));
}
// 2. Function hooks switched on for installed plugins (early access).
diff --git a/v3/docs/adr/ADR-404-claude-code-mods-function-hooks.md b/v3/docs/adr/ADR-404-claude-code-mods-function-hooks.md
index a0f7daf53d..284d926dda 100644
--- a/v3/docs/adr/ADR-404-claude-code-mods-function-hooks.md
+++ b/v3/docs/adr/ADR-404-claude-code-mods-function-hooks.md
@@ -60,7 +60,7 @@ The mod is its own plugin rather than a module added to `ruflo-core`, for three
- **Removable.** Uninstalling the plugin leaves ruflo exactly as it was. This is the ADR 150 rule.
- **Separation.** `ruflo-core`'s classic `hooks.json` and the module never share a manifest.
-`ruflo mods install` (or `ruflo init --mods`) enables it:
+`ruflo mods install` (or `ruflo init --mods`) enables it. Amendment 1 (below) makes this the `ruflo init` default:
- **Where it writes.** It sets `enabledPlugins["ruflo-mods@ruflo"]`, the `ruflo` marketplace and `env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS` (for 2.1.277 to 2.1.286) in `.claude/settings.local.json` by default, so the choice is one person's, not the repository's.
- **What it records.** It notes what it added in `.claude-flow/mods/install.json`, and `ruflo mods uninstall` removes only that.
@@ -237,3 +237,40 @@ The remaining ruflo plugins (skills, agents, MCP-only) gain nothing from functio
- Reaches users through the marketplace `git pull`, not npm: `plugins/ruflo-mods`, `plugins/ruflo-plugin-creator` (0.3.0) and `plugins/ruflo-core` (`ruflo-hook.cjs`).
- `hook-handler.cjs` changed in both copies, so the helpers manifest must be re-signed at release.
- **API churn.** The API is early access. `claude plugin validate` and the kit tests are the gate, and the classic path is unaffected either way.
+
+## Amendment 1 (2026 10 01): mods default-on in `ruflo init`
+
+Status: Proposed. This amends "A separate, opt-in plugin" above. The plugin stays separate and removable; what changes is who turns it on.
+
+### Decision
+
+- **`ruflo init` enables the mods by default.** `--no-mods` opts out. It writes the committed `.claude/settings.json`, so the choice is the project's and teammates inherit it:
+ - `enabledPlugins` for every entry in `MOD_PLUGINS` (`v3/@claude-flow/cli/src/mods/install.ts`): `ruflo-mods@ruflo`, `ruflo-swarm@ruflo` and `ruflo-console@ruflo`;
+ - `extraKnownMarketplaces.ruflo` (github `ruvnet/ruflo`);
+ - `env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS = "1"`.
+
+ A key that is already present is never changed. A plugin someone set to `false` stays `false`, and an existing env value stays as it is.
+- **The plugins are installed too.** After writing settings, init runs `claude plugin marketplace update ruflo`, or `claude plugin marketplace add ruvnet/ruflo --scope project` when the marketplace is unknown. Then it runs `claude plugin install <id> --scope project` for each plugin the clone carries.
+ - The commands go through execFile with fixed argv: no shell, no `-y`, and bounded timeouts.
+ - `--no-plugin-install` skips this step. On a failure, init prints the exact manual commands.
+ - The step is skipped when `VITEST` or `CI` is set, so a test or CI init never clones from GitHub.
+- **Existing projects.** `ruflo init upgrade --mods` applies the same merge and install. `--add-missing` and `--settings` imply it, and `--no-mods` overrides them. Each key added is reported under "Settings Updated".
+- **Standalone.** `ruflo mods install` enables the same plugins in `.claude/settings.local.json` unless `--scope project` is given.
+- **Install record v2.** `.claude-flow/mods/install.json` now records what was added per settings file (`files: { <path>: { plugins, marketplace, env } }`). `ruflo mods uninstall` removes exactly that from each file. A v1 record from 3.50.0 is read as v2.
+- **Adding a plugin.** `MOD_PLUGINS` is the one list to edit. `required: false` marks a plugin that is not yet released on main (ruflo-console today). If such a plugin is missing from the marketplace, it is reported as "pending" and never fails a check.
+
+### Why default-on is safe, and where that argument stops
+
+- **For ruflo-mods and ruflo-console, nothing runs unless function hooks are on.** If the Claude Code binary predates mods, or is 2.1.277 to 2.1.286 without the variable, they stay off. So does a server-side rollout switch serving off (see "Which Claude Code loads mods, and when" above). In all those cases the plugin loads nothing and the classic `hook-handler.cjs` hooks keep every event, exactly as before. When they do load, the handshake gives the mod only the events the classic helper hands over.
+- **ruflo-swarm is not gated the same way.** Its commands, skills and agents load whether or not function hooks are on (its own `hooks/hooks.json` says so). Only its live pane is a mod. Default-on therefore adds ruflo-swarm's commands, skills and agents to every initialized project.
+- **The mods admitted are risky by the trust gate's own rule.** A live session printed "ruflo-swarm (ruflo-swarm@ruflo) loaded; process.run (runs host commands); on tool.call (can rewrite or answer tool calls); on * (sees every event)". Under the default `modTrust: observe` it loads and is named in the transcript.
+ - `refuse-risky` with `modTrustAllow` would gate it.
+ - `pluginConfigs` options are read only from user, `--settings` or managed settings, so init cannot set that per project.
+ - **Open question:** whether default-on should ship with `refuse-risky`. That is left to the maintainers.
+- **Network and trust surface.** A project-level `extraKnownMarketplaces.ruflo` makes each teammate's Claude Code clone `github.com/ruvnet/ruflo` on its first trusted interactive start.
+
+### Verified live (Claude Code 2.1.287, isolated `CLAUDE_CONFIG_DIR`)
+
+- **An interactive, trusted session loads plugins from the marketplace clone.** It clones the marketplace a project declares and loads an enabled plugin straight from that clone. No `installed_plugins.json` entry is needed. The mod's heartbeat was written and `/ruflo-mods` reported. A headless `claude -p` run on a fresh config clones and loads nothing.
+- **A stale clone is the failure.** A clone from before `plugins/ruflo-mods` existed (`6cfd88654`) gives "Unknown command: /ruflo-mods". No heartbeat is written, and Claude Code does not refresh the clone on start. This is the 3.50.0 field report, and the reason `ruflo mods doctor` and `ruflo doctor` now fail on it with the exact commands. A missing install record alone is not a failure. `claude plugin install` stays in the repair because its cached copy survives a later stale clone, and because `claude plugin list` shows it.
+- **Claude Code reformats the committed file.** `claude plugin marketplace add --scope project` and `claude plugin install --scope project` re-serialize `.claude/settings.json`: key order and formatting change, content does not.