π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(mods): uninstall what ruflo installed, --source local (directory marketplace), exact disclosure
ruv67206969b959
diff --git a/plugins/ruflo-mods/README.md b/plugins/ruflo-mods/README.mdindex 0c82c2362b..18e0980cc9 100644--- a/plugins/ruflo-mods/README.md+++ b/plugins/ruflo-mods/README.md@@ -3,20 +3,25 @@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 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 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 install --source local # dogfooding: load the mods live from this ruflo checkout (no clone)+ruflo mods doctor # marketplace source and freshness, plugins loadable, function hooks, what it owns+ruflo mods uninstall # claude plugin uninstall what ruflo installed; remove exactly the keys it added```-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.+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 and is never installed. `ruflo init --no-mods` writes none of it.-What loads:+## 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-swarm** loads its commands, skills and agents even without function hooks. With them on, it is also a mod that can run host commands (pane actions you start).- **ruflo-console** is reported as "pending" until it is released in the marketplace.+- **The ruflo marketplace is cloned on first use.** Each teammate's first trusted, interactive Claude Code start clones `github.com/ruvnet/ruflo`. A headless `claude -p` on a fresh config loads nothing. Once the marketplace is cloned, which `ruflo init` does, `claude -p` loads the mods too.+- **Optional hardening:** set `pluginConfigs["ruflo-mods@ruflo"].options.modTrust = "refuse-risky"` with `modTrustAllow` in user or managed settings. Project settings cannot set it. The default is `observe`, which names what each later mod can do and blocks nothing.++## Install and repairWhen a `claude` binary is on PATH, init and install also do what you would do by hand, in the project directory:@@ -26,19 +31,30 @@ claude plugin install ruflo-mods@ruflo --scope <scope>claude plugin install ruflo-swarm@ruflo --scope <scope>```-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`).+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`), with or without an install record.- **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:+`ruflo mods uninstall` runs `claude plugin uninstall <id> --scope <scope>` only for the plugins ruflo itself installed: ones that were not installed before and that ruflo enabled. It then removes exactly the settings keys ruflo added. Both are recorded in `.claude-flow/mods/install.json`.++## Dogfooding: `--source local`++`ruflo mods install --source local` declares the `ruflo` marketplace as a directory source pointing at a ruflo checkout: `--marketplace-path <dir>`, or by default the project root, which must hold the `ruflo` `.claude-plugin/marketplace.json`.++- **Live from the working tree.** Claude Code loads the plugins straight from that directory: no clone, nothing to go stale, and edits show on the next session. Verified on 2.1.287.+- **No `claude plugin install`.** Installing would pin a cached snapshot instead of the live tree.+- **One marketplace per config dir.** Claude Code keeps one `ruflo` marketplace per config dir, so switching it to a directory applies to every project on that machine. Switch back with `claude plugin marketplace add ruvnet/ruflo`.+- **Doctor** reports the source type, and warns when a project declares one source but Claude Code knows `ruflo` by another.++## Flags- `--no-plugin-install` writes settings only and runs no `claude` command.-- `--dry-run` (`mods install`) prints the settings and the `claude` commands without running either.+- `--dry-run` (`mods install`, `mods uninstall`) 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.+- Claude Code reformats `.claude/settings.json` (key order) when it installs at project scope. ruflo says so and leaves it: 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-commands.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-commands.test.tsindex fb104f05e2..a1dee0bd0b 100644--- a/v3/@claude-flow/cli/__tests__/mods/mods-commands.test.ts+++ b/v3/@claude-flow/cli/__tests__/mods/mods-commands.test.ts@@ -54,14 +54,23 @@ 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') {+if (argv[1] === 'marketplace' && argv[3] && argv[3].startsWith('/')) {+ fs.mkdirSync(cfg, { recursive: true });+ fs.writeFileSync(path.join(cfg, 'known_marketplaces.json'), JSON.stringify({ ruflo: { source: { source: 'directory', path: argv[3] }, installLocation: argv[3] } }));+} else 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 } }));+ fs.writeFileSync(path.join(cfg, 'known_marketplaces.json'), JSON.stringify({ ruflo: { source: { source: 'github', repo: 'ruvnet/ruflo' }, installLocation: clone } }));+}+if (argv[1] === 'uninstall') {+ const file = path.join(cfg, 'installed_plugins.json');+ const rec = JSON.parse(fs.readFileSync(file, 'utf8'));+ delete rec.plugins[argv[2]];+ fs.writeFileSync(file, JSON.stringify(rec));}if (argv[1] === 'install') {const file = path.join(cfg, 'installed_plugins.json');@@ -136,6 +145,66 @@ describe('ADR-404 ruflo mods install (standalone)', () => {});});+describe('ADR-404 mods uninstall: claude plugin uninstall exactly what ruflo installed', () => {+ it('uninstalls the plugins ruflo installed, never one installed before, then removes the settings keys', async () => {+ fakeClaude('ok');+ // ruflo-swarm was installed for this project before ruflo touched it.+ const cfg = join(home, 'cfg', 'plugins');+ mkdirSync(join(cfg, 'cache', 'pre'), { recursive: true });+ writeFileSync(join(cfg, 'installed_plugins.json'), JSON.stringify({ version: 2, plugins: { 'ruflo-swarm@ruflo': [{ scope: 'local', installPath: join(cfg, 'cache', 'pre'), projectPath: root }] } }));+ await sub(modsCommand, 'install').action!(ctx());+ expect(read(join(root, '.claude-flow', 'mods', 'install.json')).files[join(root, '.claude', 'settings.local.json')].claudeInstalled).toEqual(['ruflo-mods@ruflo']);+ const r = await sub(modsCommand, 'uninstall').action!(ctx());+ expect(r.success).toBe(true);+ expect(calls().filter((c) => c.includes(' uninstall '))).toEqual(['plugin uninstall ruflo-mods@ruflo --scope local']);+ expect(Object.keys(read(join(cfg, 'installed_plugins.json')).plugins)).toEqual(['ruflo-swarm@ruflo']);+ expect(read(join(root, '.claude', 'settings.local.json'))).toEqual({});+ });+});++describe('ADR-404 mods install --source local (dogfooding)', () => {+ const checkout = () => {+ const dir = join(home, 'ruflo-checkout');+ for (const p of ['ruflo-mods', 'ruflo-swarm']) {+ mkdirSync(join(dir, 'plugins', p, '.claude-plugin'), { recursive: true });+ writeFileSync(join(dir, 'plugins', p, '.claude-plugin', 'plugin.json'), '{}');+ }+ mkdirSync(join(dir, '.claude-plugin'), { recursive: true });+ writeFileSync(join(dir, '.claude-plugin', 'marketplace.json'), JSON.stringify({ name: 'ruflo', plugins: [] }));+ return dir;+ };++ it('declares a directory marketplace, adds it, installs nothing (plugins load live), and doctor reports the source', async () => {+ fakeClaude('ok');+ const dir = checkout();+ const r = await sub(modsCommand, 'install').action!(ctx({ source: 'local', marketplacePath: dir }));+ expect(r).toMatchObject({ success: true, data: { resolvable: true } });+ expect(read(join(root, '.claude', 'settings.local.json')).extraKnownMarketplaces.ruflo).toEqual({ source: { source: 'directory', path: dir } });+ expect(calls()).toEqual([`plugin marketplace add ${dir} --scope local`]);+ const all = await findings();+ expect(all.find((f) => f.name === 'ruflo marketplace')).toMatchObject({ status: 'pass', message: expect.stringContaining(`directory ${dir}`) });+ expect(status(all, 'plugin ruflo-mods@ruflo')).toBe('pass');+ });++ it('refuses a directory that is not the ruflo marketplace', async () => {+ const r = await sub(modsCommand, 'install').action!(ctx({ source: 'local', marketplacePath: home }));+ expect(r).toMatchObject({ success: false, exitCode: 1 });+ expect(existsSync(join(root, '.claude', 'settings.local.json'))).toBe(false);+ });++ it('warns when this project declares one source but Claude Code knows ruflo by another', async () => {+ fakeClaude('ok');+ await sub(modsCommand, 'install').action!(ctx()); // github, known+ const dir = checkout();+ const local = join(root, '.claude', 'settings.local.json');+ const s = read(local);+ s.extraKnownMarketplaces.ruflo = { source: { source: 'directory', path: dir } };+ writeFileSync(local, JSON.stringify(s));+ const all = await findings();+ expect(all.find((f) => f.name === 'ruflo marketplace')).toMatchObject({ status: 'warn', message: expect.stringContaining('one ruflo marketplace per config dir') });+ });+});+describe('ADR-404 amendment: ruflo init upgrade --mods', () => {const upgrade = sub(initCommand, 'upgrade');const settingsFile = () => join(root, '.claude', 'settings.json');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.tsindex 843b517aa7..a70770cc82 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@@ -47,7 +47,7 @@ const byName = (findings: ReturnType<typeof resolveFindings>) => Object.fromEntrdescribe('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(known, [CLONE]))).toEqual({ known: true, location: CLONE, source: { source: 'github', repo: 'ruvnet/ruflo' } });expect(marketplaceState(CFG, fakeFs({}, [CLONE]))).toEqual({ known: false, location: CLONE });});diff --git a/v3/@claude-flow/cli/scripts/e2e-mods-init.sh b/v3/@claude-flow/cli/scripts/e2e-mods-init.shindex 18f7ab584a..0ccae9e433 100755--- a/v3/@claude-flow/cli/scripts/e2e-mods-init.sh+++ b/v3/@claude-flow/cli/scripts/e2e-mods-init.sh@@ -4,12 +4,15 @@# 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+# bash scripts/e2e-mods-init.sh # every scenario but the live load+# RUFLO_E2E_LIVE=1 CLAUDE_CODE_OAUTH_TOKEN=β¦ bash scripts/e2e-mods-init.sh+# # also 5: a live `claude -p "/ruflo-mods"`#-# 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.+# The live load needs a logged-in Claude: CLAUDE_CODE_OAUTH_TOKEN (from+# `claude setup-token`) or ANTHROPIC_API_KEY in the environment. Nothing is+# copied from ~/.claude and no credential is ever printed. Without the opt-in+# the step is reported as SKIP. Prints one PASS/FAIL line per assertion and+# exits 1 if any failed.set -uo pipefailCLI_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"@@ -19,13 +22,10 @@ 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}"+REPO_ROOT="$(cd "$CLI_DIR/../../.." && pwd)"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@@ -161,43 +161,46 @@ check "settings still enable the plugins" "js \"s.enabledPlugins?.['ruflo-mods@rcheck "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+section "7. ruflo mods install --source local: this checkout as a directory marketplace (dogfooding)"+world local+ruflo mods install --source local --marketplace-path "$REPO_ROOT" > "$W/local.log" 2>&1; rc=$?+check "install --source local exits 0" "[[ $rc -eq 0 ]]"+check "settings.local.json declares a directory marketplace at the checkout" "$NODE_BIN -e \"const s=require('$W/proj/.claude/settings.local.json');process.exit(s.extraKnownMarketplaces.ruflo.source.source==='directory'&&s.extraKnownMarketplaces.ruflo.source.path==='$REPO_ROOT'?0:1)\""+check "ran marketplace add <checkout>, and no plugin install" "grep -q 'β claude plugin marketplace add $REPO_ROOT --scope local' '$W/local.log' && ! grep -q 'claude plugin install' '$W/local.log'"+check "nothing was cloned into the config dir" "[[ ! -e '$W/cfg/plugins/marketplaces/ruflo' ]]"+ruflo mods doctor > "$W/doctor-local.log" 2>&1; rc=$?+check "mods doctor exits 0 and reports the directory source" "[[ $rc -eq 0 ]] && grep -q 'ruflo marketplace: directory $REPO_ROOT' '$W/doctor-local.log'"+LOCAL_W="$W"++# ---------------------------------------------------------------------------+section "5. live load: claude -p \"/ruflo-mods\" in the initialized project (RUFLO_E2E_LIVE=1)"+if [[ -z "${RUFLO_E2E_LIVE:-}" ]]; then+ echo "SKIP live load: needs a logged-in Claude; set RUFLO_E2E_LIVE=1 with CLAUDE_CODE_OAUTH_TOKEN or ANTHROPIC_API_KEY"+elif [[ -z "${CLAUDE_CODE_OAUTH_TOKEN:-}${ANTHROPIC_API_KEY:-}" ]]; then+ fail "live load: RUFLO_E2E_LIVE=1 but neither CLAUDE_CODE_OAUTH_TOKEN nor ANTHROPIC_API_KEY is set"+else+ for target in "$FRESH_W" "$LOCAL_W"; do+ W="$target"; export HOME="$W/home" CLAUDE_CONFIG_DIR="$W/cfg" PATH="$WORK/bin-with:$BASE_PATH"+ label="$(basename "$W")"+ rm -f "$W/proj/.claude-flow/mods/session.json"+ (cd "$W/proj" && timeout 180 claude -p "/ruflo-mods" < /dev/null > "$W/live.txt" 2>&1)+ check "live ($label): /ruflo-mods answers in claude -p (owns: β¦)" "grep -q 'owns:' '$W/live.txt'"+ check "live ($label): the mod wrote its heartbeat" "[[ -f '$W/proj/.claude-flow/mods/session.json' ]]"+ sed -n '1,3p' "$W/live.txt" | sed 's/^/ /'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-serverfi+# ---------------------------------------------------------------------------+section "8. mods uninstall on the initialized project: claude plugin uninstall + settings keys"+W="$FRESH_W"; export HOME="$W/home" CLAUDE_CONFIG_DIR="$W/cfg" PATH="$WORK/bin-with:$BASE_PATH"+ruflo mods uninstall > "$W/uninstall.log" 2>&1; rc=$?+check "uninstall exits 0" "[[ $rc -eq 0 ]]"+check "ran claude plugin uninstall for ruflo-mods and ruflo-swarm at project scope" "grep -q 'β claude plugin uninstall ruflo-mods@ruflo --scope project' '$W/uninstall.log' && grep -q 'β claude plugin uninstall ruflo-swarm@ruflo --scope project' '$W/uninstall.log'"+cc plugin list --json > "$W/plugin-list.json" 2>/dev/null+check "claude plugin list no longer has ruflo-mods or ruflo-swarm" "js \"!has('ruflo-mods@ruflo') && !has('ruflo-swarm@ruflo')\""+check "settings.json has none of the mod keys" "js \"!s.enabledPlugins?.['ruflo-mods@ruflo'] && !s.extraKnownMarketplaces?.ruflo && !s.env?.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS\""+check "classic hooks still there" "js \"JSON.stringify(s.hooks ?? {}).includes('hook-handler.cjs')\""+echoecho "$fails failure(s)"[[ $fails -eq 0 ]]diff --git a/v3/@claude-flow/cli/src/commands/mods.ts b/v3/@claude-flow/cli/src/commands/mods.tsindex 77ef9d3f67..21bca84c40 100644--- a/v3/@claude-flow/cli/src/commands/mods.ts+++ b/v3/@claude-flow/cli/src/commands/mods.ts@@ -10,9 +10,27 @@import type { Command, CommandContext, CommandResult } from '../types.js';import { output } from '../output.js';-import { uninstallMod, type Scope } from '../mods/install.js';+import { existsSync, readFileSync } from 'node:fs';+import { join, resolve } from 'node:path';++import { directoryMarketplace, MARKETPLACE_NAME, type MarketplaceEntry, type Scope } from '../mods/install.js';import { probeMods, type Finding } from '../mods/probe.js';-import { applyMods } from '../mods/apply.js';+import { applyMods, removeMods } from '../mods/apply.js';++/**+ * `--source local` / `--marketplace-path <dir>`: a ruflo checkout as a+ * directory marketplace (dogfooding). It must be a ruflo marketplace.+ */+function localMarketplace(dir: string): MarketplaceEntry | string {+ const catalog = join(resolve(dir), '.claude-plugin', 'marketplace.json');+ if (!existsSync(catalog)) return `${dir} has no .claude-plugin/marketplace.json`;+ try {+ if ((JSON.parse(readFileSync(catalog, 'utf8')) as { name?: unknown }).name !== MARKETPLACE_NAME) return `${catalog} is not the ${MARKETPLACE_NAME} marketplace`;+ } catch {+ return `${catalog} is not JSON`;+ }+ return directoryMarketplace(dir);+}function projectRoot(ctx: CommandContext): string {return (ctx.flags.projectRoot as string | undefined) ?? (ctx.flags['project-root'] as string | undefined) ?? ctx.cwd ?? process.cwd();@@ -37,6 +55,8 @@ const installSub: Command = {{ 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 a required plugin could not be made loadable', type: 'boolean', default: false },+ { name: 'source', description: 'github (ruvnet/ruflo, default) | local (a ruflo checkout as a directory marketplace: plugins load live from it)', type: 'string', default: 'github' },+ { name: 'marketplace-path', description: 'With --source local: the ruflo checkout (default: the project root)', type: 'string' },],action: async (ctx: CommandContext): Promise<CommandResult> => {const scope = (ctx.flags.scope as string | undefined) ?? 'local';@@ -44,8 +64,24 @@ const installSub: Command = {output.printError(`--scope must be local or project, got ${scope}`);return { success: false, exitCode: 1 };}+ const source = (ctx.flags.source as string | undefined) ?? 'github';+ const path = (ctx.flags.marketplacePath ?? ctx.flags['marketplace-path']) as string | undefined;+ if (source !== 'github' && source !== 'local') {+ output.printError(`--source must be github or local, got ${source}`);+ return { success: false, exitCode: 1 };+ }+ let marketplace: MarketplaceEntry | undefined;+ if (source === 'local' || path) {+ const local = localMarketplace(path ?? projectRoot(ctx));+ if (typeof local === 'string') {+ output.printError(`--source local: ${local}`);+ return { success: false, exitCode: 1 };+ }+ marketplace = local;+ }const result = await applyMods(projectRoot(ctx), {scope: scope as Scope,+ marketplace,dryRun: ctx.flags.dryRun === true || ctx.flags['dry-run'] === true,pluginInstall: ctx.flags.pluginInstall !== false && ctx.flags['plugin-install'] !== false,});@@ -58,16 +94,17 @@ const installSub: Command = {const uninstallSub: Command = {name: 'uninstall',- description: 'Remove what `ruflo mods install` added (classic hooks take every event back)',+ description: 'Remove what `ruflo mods install` added, and claude plugin uninstall what it installed (classic hooks take every event back)',options: [rootOption, { name: 'dry-run', description: 'Show what would be removed', type: 'boolean', default: false }],action: async (ctx: CommandContext): Promise<CommandResult> => {- const result = uninstallMod(projectRoot(ctx), (ctx.flags.dryRun === true || ctx.flags['dry-run'] === true));+ const result = await removeMods(projectRoot(ctx), { dryRun: ctx.flags.dryRun === true || ctx.flags['dry-run'] === true });if (!result.removed) {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'} what ruflo mods added from ${result.settingsFiles.join(', ')}`);- return { success: true, data: result };+ if (result.uninstalled.length) output.writeln(`claude plugin uninstall: ${result.uninstalled.join(', ')}`);+ return { success: result.failed.length === 0, exitCode: result.failed.length ? 1 : 0, data: result };},};@@ -126,6 +163,7 @@ export const modsCommand: Command = {{ 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 install --source local', description: 'Dogfood: load the mods live from this ruflo checkout (directory marketplace)' },{ 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' },],diff --git a/v3/@claude-flow/cli/src/mods/apply.ts b/v3/@claude-flow/cli/src/mods/apply.tsindex 04fb05e1a9..56c6e6166b 100644--- a/v3/@claude-flow/cli/src/mods/apply.ts+++ b/v3/@claude-flow/cli/src/mods/apply.ts@@ -1,15 +1,31 @@/**- * 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`.+ * Turn the ruflo mods on (or off) 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 its wizard)+ * and `ruflo init upgrade --mods`; `removeMods` is `ruflo mods uninstall`.*/+import { readFileSync } from 'node:fs';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';+import {+ installMod,+ MARKETPLACE_NAME,+ MARKETPLACE_SOURCE,+ MOD_PLUGINS,+ readRecord,+ recordClaudeInstalled,+ scopeOfSettingsFile,+ uninstallMod,+ type Added,+ type InstallResult,+ type MarketplaceEntry,+ type ModPlugin,+ type Scope,+} from './install.js';+import { findClaudeBinary, installArgv, marketplaceArgv, repairPluginInstall, uninstallArgv, uninstallPlugins, type Exec, type RepairStep } from './plugin-repair.js';+import { claudeConfigDir, describeSource, installedState, marketplaceState, repairCommands, resolveFindings, sameSource } from './plugin-resolve.js';export interface ApplyOptions {scope: Scope;@@ -21,6 +37,8 @@ export interface ApplyOptions {* init there must never clone from GitHub into whatever config dir is live.*/skipInTestEnv?: boolean;+ /** The marketplace to declare when the settings have none (default github ruvnet/ruflo). */+ marketplace?: MarketplaceEntry;/** Injectable for tests. */exec?: Exec;}@@ -37,15 +55,17 @@ export interface ApplyResult {export function describeAdded(added: Added): string[] {return [...added.plugins.map((id) => `enabledPlugins["${id}"] = true`),- ...(added.marketplace ? ['extraKnownMarketplaces.ruflo = github ruvnet/ruflo'] : []),+ ...(added.marketplace ? ['extraKnownMarketplaces.ruflo'] : []),...(added.env ? ['env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS = "1"'] : []),];}-/** What default-on means, said exactly (ADR-404 amendment). */+/** What default-on means, said exactly (ADR-404 Amendment 1). */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.",+ "ruflo-swarm's commands, skills and agents load without function hooks; with them on, ruflo-swarm is also a mod that can run host commands (pane actions you start).",+ "Each teammate's first trusted interactive Claude Code start clones github.com/ruvnet/ruflo; a headless claude -p on a fresh config loads nothing.",+ 'Optional hardening: pluginConfigs["ruflo-mods@ruflo"].options.modTrust = "refuse-risky" with modTrustAllow, in user or managed settings (project settings cannot set it).',];async function syncPolicyQuietly(root: string): Promise<void> {@@ -59,27 +79,58 @@ async function syncPolicyQuietly(root: string): Promise<void> {}}-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}`);+function printSteps(steps: readonly RepairStep[]): void {+ for (const step of 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 canon = (v: unknown): unknown =>+ Array.isArray(v) ? v.map(canon) : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon((v as Record<string, unknown>)[k])])) : v;++function readText(path: string): string | undefined {+ try {+ return readFileSync(path, 'utf8');+ } catch {+ return undefined;+ }+}++/** Claude Code re-serializes settings it touches; say so, never fight it. */+function noteRewrite(file: string, before: string | undefined): void {+ const after = readText(file);+ if (before === undefined || after === undefined || before === after) return;+ try {+ output.writeln(output.dim(JSON.stringify(canon(JSON.parse(before))) === JSON.stringify(canon(JSON.parse(after)))+ ? `Claude Code reformatted ${file} (key order and layout only; content unchanged).`+ : `Claude Code also changed ${file}; review it before committing.`));+ } catch {+ // Not ours to judge further.+ }}export async function applyMods(root: string, opts: ApplyOptions): Promise<ApplyResult> {- const install = installMod(root, opts.scope, opts.dryRun === true);+ const install = installMod(root, opts.scope, opts.dryRun === true, undefined, opts.marketplace ?? MARKETPLACE_SOURCE);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);+ const plugins: ModPlugin[] = MOD_PLUGINS.filter((p) => enabled[p.id] === true);+ // The marketplace the file declares wins: a person's own declaration is kept and used.+ const declared = (install.next.extraKnownMarketplaces as Record<string, MarketplaceEntry> | undefined)?.[MARKETPLACE_NAME] ?? MARKETPLACE_SOURCE;+ const market = marketplaceState(configDir);+ const known = market.known && sameSource(market.source, declared.source);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(' ')}`);+ const installs = declared.source.source === 'directory' ? [] : plugins.map((p) => installArgv(p.id, opts.scope));+ for (const argv of [marketplaceArgv(opts.scope, known, declared), ...installs]) output.writeln(` claude ${argv.join(' ')}`);}return { install, resolvable: true };}@@ -91,30 +142,79 @@ export async function applyMods(root: string, opts: ApplyOptions): Promise<Apply} else {output.printSuccess(`ruflo mods already enabled in ${install.settingsFile} (nothing changed)`);}+ output.writeln(` marketplace: ${describeSource(declared.source)}`);+ if (opts.marketplace && !sameSource(opts.marketplace.source, declared.source)) {+ output.printWarning(`extraKnownMarketplaces.ruflo was already set (${describeSource(declared.source)}); left as it is.`);+ }for (const line of LOAD_NOTE) output.writeln(output.dim(line));+ const manual = (k = known) => {+ output.writeln('Run these to make the plugins loadable:');+ for (const line of repairCommands(root, opts.scope, k, plugins, declared)) output.writeln(` ${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);+ manual();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);+ manual();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 ')}`));+ if (declared.source.source === 'directory' && market.known && !sameSource(market.source, declared.source)) {+ output.printWarning(`Claude Code keeps one ruflo marketplace per config dir: it now switches from ${describeSource(market.source)} to ${describeSource(declared.source)} for every project on this machine. Switch back with: claude plugin marketplace add ruvnet/ruflo`);}- const failed = resolveFindings(root, opts.scope, configDir, undefined, plugins.map((p) => p.id)).filter((f) => f.status === 'fail');+ // Never claim (and so never uninstall) a plugin that was installed before, or one ruflo did not enable.+ const before = new Set(plugins.filter((p) => installedState(root, configDir, p.id).installed).map((p) => p.id));+ const textBefore = readText(install.settingsFile);+ const repair = await repairPluginInstall({ projectRoot: root, scope: opts.scope, configDir, claude, plugins, marketplace: declared, exec: opts.exec });+ printSteps(repair.steps);+ if (declared.source.source === 'directory' && repair.ok) output.writeln(output.dim(`Directory marketplace: plugins load live from ${declared.source.path} (no clone, no install).`));+ const enabledByRuflo = new Set(readRecord(root)?.files[install.settingsFile]?.plugins ?? []);+ const ours = repair.steps+ .filter((st) => st.state === 'ok' && st.argv[1] === 'install')+ .map((st) => st.argv[2]!)+ .filter((id) => !before.has(id) && enabledByRuflo.has(id));+ recordClaudeInstalled(root, install.settingsFile, ours);+ noteRewrite(install.settingsFile, textBefore);++ const failed = resolveFindings(root, opts.scope, configDir, undefined, plugins.map((p) => p.id), declared).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);+ const now = marketplaceState(configDir);+ manual(now.known && sameSource(now.source, declared.source));return { install, resolvable: false };}++/**+ * `ruflo mods uninstall`: `claude plugin uninstall` exactly the plugins ruflo+ * installed, then remove exactly the settings keys it added.+ */+export async function removeMods(root: string, opts: { dryRun?: boolean; exec?: Exec } = {}): Promise<{ settingsFiles: string[]; removed: boolean; dryRun: boolean; uninstalled: string[]; failed: string[] }> {+ const record = readRecord(root);+ const plan = Object.entries(record?.files ?? {}).map(([file, added]) => ({ file, scope: scopeOfSettingsFile(file), ids: added.claudeInstalled ?? [] }));+ const uninstalled: string[] = [];+ const failed: string[] = [];+ if (opts.dryRun) {+ for (const p of plan) for (const id of p.ids) output.writeln(`Would run: claude ${uninstallArgv(id, p.scope).join(' ')}`);+ } else if (plan.some((p) => p.ids.length)) {+ const claude = findClaudeBinary(process.env, homedir());+ for (const p of plan.filter((x) => x.ids.length)) {+ if (!claude) {+ output.printWarning('No runnable claude binary on PATH; run these to remove what ruflo installed:');+ for (const id of p.ids) output.writeln(` cd ${JSON.stringify(root)} && claude ${uninstallArgv(id, p.scope).join(' ')}`);+ failed.push(...p.ids);+ continue;+ }+ const result = await uninstallPlugins({ projectRoot: root, scope: p.scope, ids: p.ids, claude, exec: opts.exec });+ printSteps(result.steps);+ for (const st of result.steps) (st.state === 'ok' ? uninstalled : failed).push(st.argv[2]!);+ }+ }+ const result = uninstallMod(root, opts.dryRun === true);+ return { ...result, uninstalled, failed };+}diff --git a/v3/@claude-flow/cli/src/mods/install.ts b/v3/@claude-flow/cli/src/mods/install.tsindex b98a476220..d9adc5b7fb 100644--- a/v3/@claude-flow/cli/src/mods/install.ts+++ b/v3/@claude-flow/cli/src/mods/install.ts@@ -19,6 +19,13 @@ import { dirname, join, resolve, sep } from 'node:path';export const MOD_PLUGIN_ID = 'ruflo-mods@ruflo';export const MARKETPLACE_NAME = 'ruflo';export const MARKETPLACE_SOURCE = { source: { source: 'github', repo: 'ruvnet/ruflo' } } as const;++/** An `extraKnownMarketplaces` entry: github ruvnet/ruflo, or a local ruflo checkout (dogfooding). */+export type MarketplaceEntry = { source: { source: 'github'; repo: string } | { source: 'directory'; path: string } };++export function directoryMarketplace(path: string): MarketplaceEntry {+ return { source: { source: 'directory', path: resolve(path) } };+}export const ENABLE_ENV = 'CLAUDE_CODE_ENABLE_FUNCTION_HOOKS';export const INSTALL_RECORD = join('.claude-flow', 'mods', 'install.json');@@ -46,6 +53,12 @@ export interface Added {plugins: string[];marketplace: boolean;env: boolean;+ /**+ * Plugins ruflo itself installed with `claude plugin install` (absent+ * before, enabled by ruflo); uninstall runs `claude plugin uninstall` for+ * exactly these.+ */+ claudeInstalled?: string[];}export interface InstallRecord {@@ -87,7 +100,7 @@ function writeJson(path: string, value: unknown): void {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 } {+export function withModEnabled(settings: Settings, plugins: readonly string[] = MOD_PLUGIN_IDS, marketplace: MarketplaceEntry = MARKETPLACE_SOURCE): { next: Settings; added: Added } {const next: Settings = { ...settings };const enabled = isRecord(settings.enabledPlugins) ? { ...settings.enabledPlugins } : {};const markets = isRecord(settings.extraKnownMarketplaces) ? { ...settings.extraKnownMarketplaces } : {};@@ -99,7 +112,7 @@ export function withModEnabled(settings: Settings, plugins: readonly string[] =env: !(ENABLE_ENV in env),};for (const id of added.plugins) enabled[id] = true;- if (added.marketplace) markets[MARKETPLACE_NAME] = MARKETPLACE_SOURCE;+ if (added.marketplace) markets[MARKETPLACE_NAME] = marketplace;if (added.env) env[ENABLE_ENV] = '1';next.enabledPlugins = enabled;next.extraKnownMarketplaces = markets;@@ -133,10 +146,16 @@ export interface InstallResult {next: Settings;}-export function installMod(projectRoot: string, scope: Scope, dryRun = false, plugins: readonly string[] = MOD_PLUGIN_IDS): InstallResult {+export function installMod(+ projectRoot: string,+ scope: Scope,+ dryRun = false,+ plugins: readonly string[] = MOD_PLUGIN_IDS,+ marketplace: MarketplaceEntry = MARKETPLACE_SOURCE,+): InstallResult {const settingsFile = settingsFileFor(projectRoot, scope);const current = readSettingsFile(settingsFile);- const { next, added } = withModEnabled(current, plugins);+ const { next, added } = withModEnabled(current, plugins, marketplace);if (dryRun || nothingAdded(added)) return { settingsFile, added, dryRun, next };let backup: string | undefined;@@ -152,6 +171,7 @@ export function installMod(projectRoot: string, scope: Scope, dryRun = false, plplugins: [...new Set([...before.plugins, ...added.plugins])],marketplace: before.marketplace || added.marketplace,env: before.env || added.env,+ claudeInstalled: before.claudeInstalled ?? [],};record.installedAt = new Date().toISOString();writeJson(join(resolve(projectRoot), INSTALL_RECORD), record);@@ -168,7 +188,8 @@ export function readRecord(projectRoot: string): InstallRecord | null {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 };+ const strings = (v: unknown) => (Array.isArray(v) ? v.filter((p): p is string => typeof p === 'string') : []);+ files[file] = { plugins: strings(a.plugins), marketplace: a.marketplace === true, env: a.env === true, claudeInstalled: strings(a.claudeInstalled) };}return { version: 2, installedAt: String(parsed.installedAt ?? ''), files };}@@ -182,6 +203,20 @@ export function readRecord(projectRoot: string): InstallRecord | null {}}+/** Note plugins ruflo installed with `claude plugin install` for one settings file. */+export function recordClaudeInstalled(projectRoot: string, settingsFile: string, ids: readonly string[]): void {+ const record = readRecord(projectRoot);+ const entry = record?.files[settingsFile];+ if (!record || !entry || ids.length === 0) return;+ entry.claudeInstalled = [...new Set([...(entry.claudeInstalled ?? []), ...ids])];+ writeJson(join(resolve(projectRoot), INSTALL_RECORD), record);+}++/** The scope a recorded settings file was written at. */+export function scopeOfSettingsFile(file: string): Scope {+ return file.endsWith('settings.local.json') ? 'local' : 'project';+}+export function uninstallMod(projectRoot: string, dryRun = false): { settingsFiles: string[]; removed: boolean; dryRun: boolean } {const record = readRecord(projectRoot);if (!record) return { settingsFiles: [], removed: false, dryRun };diff --git a/v3/@claude-flow/cli/src/mods/plugin-repair.ts b/v3/@claude-flow/cli/src/mods/plugin-repair.tsindex 78f13eb02c..f3e00fdbee 100644--- a/v3/@claude-flow/cli/src/mods/plugin-repair.ts+++ b/v3/@claude-flow/cli/src/mods/plugin-repair.ts@@ -16,8 +16,8 @@import { execFile } from 'node:child_process';import { findClaudeInstalls } from './claude-installs.js';-import { MARKETPLACE_NAME, MOD_PLUGINS, type ModPlugin, type Scope } from './install.js';-import { cloneHas, marketplaceState, nodeReadFs, type ReadFs } from './plugin-resolve.js';+import { MARKETPLACE_NAME, MARKETPLACE_SOURCE, MOD_PLUGINS, type MarketplaceEntry, type ModPlugin, type Scope } from './install.js';+import { cloneHas, marketplaceState, nodeReadFs, sameSource, type ReadFs } from './plugin-resolve.js';export const MARKETPLACE_TIMEOUT_MS = 150_000; // Claude Code's own clone timeout is 120sexport const INSTALL_TIMEOUT_MS = 60_000;@@ -63,13 +63,26 @@ export interface RepairOptions {configDir: string;claude: string;plugins?: readonly ModPlugin[];+ /** The marketplace the settings declare (default github ruvnet/ruflo). */+ marketplace?: MarketplaceEntry;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];+/**+ * `update` when Claude Code already knows ruflo by the wanted source; else+ * `add` it at the scope, which also switches a ruflo marketplace known by+ * another source (Claude Code keeps one per config dir).+ */+export function marketplaceArgv(scope: Scope, known: boolean, wanted: MarketplaceEntry = MARKETPLACE_SOURCE): string[] {+ if (known) return ['plugin', 'marketplace', 'update', MARKETPLACE_NAME];+ const from = wanted.source.source === 'directory' ? wanted.source.path : wanted.source.repo;+ return ['plugin', 'marketplace', 'add', from, '--scope', scope];+}++export function uninstallArgv(id: string, scope: Scope): string[] {+ return ['plugin', 'uninstall', id, '--scope', scope];}export function installArgv(id: string, scope: Scope): string[] {@@ -99,10 +112,19 @@ export async function repairPluginInstall(opts: RepairOptions): Promise<{ ok: boreturn result.code === 0;};- if (!(await run(marketplaceArgv(opts.scope, marketplaceState(opts.configDir, fs).known), MARKETPLACE_TIMEOUT_MS))) {+ const wanted = opts.marketplace ?? MARKETPLACE_SOURCE;+ const before = marketplaceState(opts.configDir, fs);+ if (!(await run(marketplaceArgv(opts.scope, before.known && sameSource(before.source, wanted.source), wanted), MARKETPLACE_TIMEOUT_MS))) {return { ok: false, steps };}const market = marketplaceState(opts.configDir, fs);+ // A directory marketplace loads each plugin live from the working tree;+ // an install would pin a cached snapshot of it instead.+ if (wanted.source.source === 'directory') {+ const missing = plugins.filter((p) => p.required && !cloneHas(market, p.id, fs));+ for (const p of missing) steps.push({ argv: installArgv(p.id, opts.scope), state: 'failed', output: `${p.id} is not in ${wanted.source.path}` });+ return { ok: missing.length === 0, steps };+ }let ok = true;for (const plugin of plugins) {const argv = installArgv(plugin.id, opts.scope);@@ -115,3 +137,20 @@ export async function repairPluginInstall(opts: RepairOptions): Promise<{ ok: bo}return { ok, steps };}++/** `claude plugin uninstall` for each id, every failure collected. */+export async function uninstallPlugins(opts: { projectRoot: string; scope: Scope; ids: readonly string[]; claude: string; exec?: Exec; env?: NodeJS.ProcessEnv }): Promise<{ ok: boolean; steps: RepairStep[] }> {+ const exec = opts.exec ?? nodeExec;+ const steps: RepairStep[] = [];+ for (const id of opts.ids) {+ const argv = uninstallArgv(id, opts.scope);+ let result: ExecResult;+ try {+ result = await exec(opts.claude, argv, { cwd: opts.projectRoot, timeout: INSTALL_TIMEOUT_MS, env: opts.env ?? process.env });+ } catch (error) {+ result = { code: 1, stdout: '', stderr: (error as Error).message };+ }+ steps.push({ argv, state: result.code === 0 ? 'ok' : 'failed', output: `${result.stdout}${result.stderr}`.trim() });+ }+ return { ok: steps.every((st) => st.state === 'ok'), steps };+}diff --git a/v3/@claude-flow/cli/src/mods/plugin-resolve.ts b/v3/@claude-flow/cli/src/mods/plugin-resolve.tsindex 05810580f8..a0ac9d35f6 100644--- a/v3/@claude-flow/cli/src/mods/plugin-resolve.ts+++ b/v3/@claude-flow/cli/src/mods/plugin-resolve.ts@@ -19,7 +19,7 @@import { existsSync, readFileSync, realpathSync } from 'node:fs';import { join, resolve } from 'node:path';-import { MARKETPLACE_NAME, MOD_PLUGINS, type ModPlugin, type Scope } from './install.js';+import { MARKETPLACE_NAME, MARKETPLACE_SOURCE, MOD_PLUGINS, type MarketplaceEntry, type ModPlugin, type Scope } from './install.js';import type { Finding } from './probe.js';/** The two filesystem reads detection needs; injectable for tests. */@@ -62,8 +62,23 @@ 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. */+ /** The local clone (or, for a directory source, the directory), when it exists on disk. */location: string | null;+ /** The source Claude Code knows the marketplace by, when known. */+ source?: MarketplaceEntry['source'];+}++/** "github ruvnet/ruflo" or "directory /path" (a working tree: no clone, nothing to go stale). */+export function describeSource(source: unknown): string {+ if (!isRecord(source)) return 'unknown source';+ if (source.source === 'directory') return `directory ${String(source.path)}`;+ if (source.source === 'github') return `github ${String(source.repo)}`;+ return String(source.source ?? 'unknown source');+}++export function sameSource(a: unknown, b: unknown): boolean {+ if (!isRecord(a) || !isRecord(b) || a.source !== b.source) return false;+ return a.source === 'directory' ? resolve(String(a.path)) === resolve(String(b.path)) : a.repo === b.repo;}export function marketplaceState(configDir: string, fs: ReadFs = nodeReadFs): MarketplaceState {@@ -71,7 +86,8 @@ export function marketplaceState(configDir: string, fs: ReadFs = nodeReadFs): Maconst 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);- return { known: isRecord(entry), location: candidates.find((p) => fs.exists(p)) ?? null };+ const source = isRecord(entry) && isRecord(entry.source) ? (entry.source as MarketplaceEntry['source']) : undefined;+ return { known: isRecord(entry), location: candidates.find((p) => fs.exists(p)) ?? null, source };}/** The plugin's manifest inside a clone: its marketplace.json `source`, else plugins/<name>. */@@ -117,12 +133,26 @@ export function installedState(projectRoot: string, configDir: string, id: strinreturn { installed: false };}-/** 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[] {+/**+ * The exact commands that refresh the marketplace and install the plugins,+ * for a person to run. `known` is true only when Claude Code already knows+ * the marketplace by the wanted source (then an update suffices). A+ * directory source loads live from the working tree: nothing to install.+ */+export function repairCommands(+ projectRoot: string,+ scope: Scope | 'user',+ known: boolean,+ plugins: readonly ModPlugin[] = MOD_PLUGINS,+ wanted: MarketplaceEntry = MARKETPLACE_SOURCE,+): string[] {+ const dir = wanted.source.source === 'directory' ? wanted.source.path : null;return [`cd ${JSON.stringify(resolve(projectRoot))}`,- known ? `claude plugin marketplace update ${MARKETPLACE_NAME}` : `claude plugin marketplace add ruvnet/ruflo --scope ${scope}`,- ...plugins.filter((p) => p.required).map((p) => `claude plugin install ${p.id} --scope ${scope}`),+ known+ ? `claude plugin marketplace update ${MARKETPLACE_NAME}`+ : `claude plugin marketplace add ${dir ? JSON.stringify(dir) : 'ruvnet/ruflo'} --scope ${scope}`,+ ...(dir ? [] : plugins.filter((p) => p.required).map((p) => `claude plugin install ${p.id} --scope ${scope}`)),];}@@ -137,13 +167,24 @@ export function resolveFindings(configDir: string,fs: ReadFs = nodeReadFs,enabled: readonly string[] = MOD_PLUGINS.map((p) => p.id),+ declared?: unknown,): Finding[] {const market = marketplaceState(configDir, fs);- const fix = repairCommands(projectRoot, scope, market.known).join(' && ');+ const wanted = (isRecord(declared) && isRecord(declared.source) ? declared : MARKETPLACE_SOURCE) as MarketplaceEntry;+ const matches = market.known && sameSource(market.source, wanted.source);+ const fix = repairCommands(projectRoot, scope, matches, MOD_PLUGINS.filter((p) => enabled.includes(p.id)), wanted).join(' && ');const findings: Finding[] = [];+ const kind = market.source?.source === 'directory' ? 'directory (loads live from the working tree)' : `cloned at ${market.location}`;- findings.push(market.location- ? { name: 'ruflo marketplace', status: 'pass', message: `cloned at ${market.location}` }+ findings.push(market.location && market.known && !sameSource(market.source, wanted.source)+ ? {+ name: 'ruflo marketplace',+ status: 'warn',+ message: `this project declares ${describeSource(wanted.source)}, but Claude Code knows ruflo as ${describeSource(market.source)} (one ruflo marketplace per config dir)`,+ fix,+ }+ : market.location+ ? { name: 'ruflo marketplace', status: 'pass', message: `${describeSource(market.source ?? wanted.source)}: ${kind}` }: {name: 'ruflo marketplace',status: 'warn',diff --git a/v3/@claude-flow/cli/src/mods/probe.ts b/v3/@claude-flow/cli/src/mods/probe.tsindex a56c545bf5..72b2a53fe0 100644--- a/v3/@claude-flow/cli/src/mods/probe.ts+++ b/v3/@claude-flow/cli/src/mods/probe.ts@@ -89,7 +89,15 @@ export function probeMods(inputs: ProbeInputs): Finding[] {return false;}}));- findings.push(...resolveFindings(root, scope, configDir, inputs.fs, enabled));+ // The marketplace the first settings file declaring one names (local wins, as in Claude Code).+ const declared = files.map((f) => {+ try {+ return get(readSettingsFile(f), 'extraKnownMarketplaces', 'ruflo');+ } catch {+ return undefined;+ }+ }).find((d) => d !== undefined);+ findings.push(...resolveFindings(root, scope, configDir, inputs.fs, enabled, declared));}// 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.mdindex 284d926dda..3172dc72c6 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@@ -256,7 +256,14 @@ Status: Proposed. This amends "A separate, opt-in plugin" above. The plugin stay- 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.+- **Install record v2.** `.claude-flow/mods/install.json` now records, per settings file, what was added (`files: { <path>: { plugins, marketplace, env, claudeInstalled } }`). A v1 record from 3.50.0 is read as v2.+ - `claudeInstalled` lists the plugins ruflo installed with `claude plugin install`: ones absent from Claude Code's install record before, and enabled by ruflo.+ - `ruflo mods uninstall` runs `claude plugin uninstall <id> --scope <scope>` for exactly those, then removes exactly the recorded keys. A plugin someone installed before is never uninstalled.+- **Dogfooding: `ruflo mods install --source local`.** Optionally with `--marketplace-path <dir>`, it declares `extraKnownMarketplaces.ruflo` as a `directory` source pointing at a ruflo checkout.+ - The repair runs `claude plugin marketplace add <dir> --scope <scope>` and no `plugin install`: an install would pin a cached snapshot instead of the live tree.+ - The directory must hold the `ruflo` `.claude-plugin/marketplace.json`.+ - Doctor reports the source type, and warns when a project declares one source while Claude Code knows `ruflo` by another.+ - Claude Code keeps one `ruflo` marketplace per config dir, so the switch applies machine-wide. Install says so and prints how to switch back.- **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@@ -266,11 +273,17 @@ Status: Proposed. This amends "A separate, opt-in plugin" above. The plugin stay- **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.+ - **Decision (for now):** keep `observe`. Init writes no user or managed settings. Init output, the plugin README and this ADR name `refuse-risky` + `modTrustAllow` (in user or managed settings) as the opt-in hardening.+ - **Open question:** whether default-on should eventually ship with `refuse-risky`.+- **What a teammate sees.** With function hooks on, ruflo-swarm is also a mod that can run host commands (pane actions the user starts). Each teammate's first trusted interactive start clones `github.com/ruvnet/ruflo`. A headless `claude -p` on a fresh config loads nothing. Init prints all of this.- **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.+- **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. ruflo reports it ("reformatted, content unchanged") and does not rewrite it back.+- **`claude plugin install` flips a disabled plugin on.** A plugin set to `false` becomes `true`. So the repair installs only plugins that are `true` in the settings file.+- **`claude plugin uninstall --scope project` edits settings too.** It removes the plugin's `enabledPlugins` entry itself.+- **Headless runs load once the marketplace is known.** After `ruflo init` has added the marketplace to the config dir, `claude -p "/ruflo-mods"` loads the mod and prints its report. This is the e2e live check. It authenticates with `CLAUDE_CODE_OAUTH_TOKEN`; no credential file is copied.+- **A directory marketplace works, live.** A `directory` source loaded `ruflo-mods` in `claude -p` with no install record. An edit to the directory showed on the next run with no update or install in between. It was verified with a marker string changed between two runs.