Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(mods): handshake in the generated helper; ENOENT-only missing; doctor reports the rollout switch (ADR-404)

ruv24c9c4a8d82a
diff --git a/plugins/ruflo-mods/README.md b/plugins/ruflo-mods/README.md
index 5af39e8b63..1cc57d842d 100644
--- a/plugins/ruflo-mods/README.md
+++ b/plugins/ruflo-mods/README.md
@@ -21,7 +21,7 @@ The classic `hook-handler.cjs` hooks stay installed and remain the fallback. The
## Options
-Set these in the plugin's config:
+Claude Code reads a plugin's options from `pluginConfigs["ruflo-mods@ruflo"].options` in user settings, `--settings` or managed settings. Project settings are not read for this. Every option has a default:
| Option | Default | Effect |
|---|---|---|
diff --git a/plugins/ruflo-mods/hooks/files.ts b/plugins/ruflo-mods/hooks/files.ts
index 58de3440b0..14105d4b2d 100644
--- a/plugins/ruflo-mods/hooks/files.ts
+++ b/plugins/ruflo-mods/hooks/files.ts
@@ -18,7 +18,12 @@ export type Read<T> =
| { readonly kind: 'ok'; readonly value: T }
| { readonly kind: 'error'; readonly message: string }
-export const isMissing = (error: unknown) => /ENOENT|no such file|not found/i.test(String((error as Error)?.message ?? error))
+/**
+ * Only ENOENT is "missing" (`$.fs.stat` rejects ENOENT for a missing path).
+ * Anything else is an error: for the guard that means failing closed, so a
+ * loosely matched message must never read as "no policy here".
+ */
+export const isMissing = (error: unknown) => /\bENOENT\b/.test(String((error as Error)?.message ?? error))
/**
* A reader that parses a project file once per change: one `$.fs.stat` per
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
new file mode 100644
index 0000000000..0f220330a0
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.ts
@@ -0,0 +1,60 @@
+/**
+ * ADR-404 — the CLI surface through the built binary: `init --mods`,
+ * `doctor --component mods`, and `mods status|uninstall`. Skipped where the
+ * CLI is not built, as the other bin-level tests are (#2952).
+ */
+import { describe, it, expect } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { delimiter, join } from 'node:path';
+import { tmpdir } from 'node:os';
+
+const CLI_BIN = fileURLToPath(new URL('../../bin/cli.js', import.meta.url));
+const CLI_BUILT = existsSync(CLI_BIN);
+
+function isolated() {
+ const home = mkdtempSync(join(tmpdir(), 'ruflo-mods-bin-home-'));
+ const cwd = mkdtempSync(join(tmpdir(), 'ruflo-mods-bin-'));
+ const bin = join(home, 'bin');
+ mkdirSync(bin, { recursive: true });
+ writeFileSync(join(bin, 'codex'), '#!/bin/sh\nexit 1\n');
+ chmodSync(join(bin, 'codex'), 0o755);
+ const env = { ...process.env, HOME: home, USERPROFILE: home, CODEX_HOME: join(home, '.codex'), PATH: `${bin}${delimiter}${process.env.PATH ?? ''}`, CI: '1' };
+ const run = (...args: string[]) => execFileSync(process.execPath, [CLI_BIN, ...args], { cwd, env, encoding: 'utf8', timeout: 120_000 });
+ return { home, cwd, run, done: () => { rmSync(home, { recursive: true, force: true }); rmSync(cwd, { recursive: true, force: true }); } };
+}
+
+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', () => {
+ 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.
+ const shared = JSON.parse(readFileSync(join(t.cwd, '.claude', 'settings.json'), 'utf8'));
+ expect(JSON.stringify(shared.hooks.UserPromptSubmit)).toContain('hook-handler.cjs');
+
+ expect(t.run('doctor', '--component', 'mods')).toContain('ruflo mods (ADR-404)');
+ const status = JSON.parse(t.run('mods', 'status', '--json').replace(/^[^[]*/, ''));
+ expect(status.find((f: { name: string }) => f.name === 'ruflo-mods plugin').status).toBe('pass');
+
+ t.run('mods', 'uninstall');
+ expect(JSON.parse(readFileSync(join(t.cwd, '.claude', 'settings.local.json'), 'utf8'))).toEqual({});
+ } finally {
+ t.done();
+ }
+ });
+
+ it('bare init does not enable the mod (opt-in)', () => {
+ 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);
+ 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 d3a884dda1..2639567183 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-cli.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-cli.test.ts
@@ -123,14 +123,14 @@ describe('ADR-404 mods probe and doctor', () => {
expect(finding('last mod start').status).toBe('pass');
});
- it('reports function hooks off, and the cached rollout switch when Claude Code serves it off', () => {
+ it('the rollout switch decides; the enable variable is reported, never sufficient', () => {
expect(finding('function hooks').status).toBe('warn');
writeFileSync(join(home, '.claude.json'), JSON.stringify({ cachedGrowthBookFeatures: { tengu_plugin_hooks_modules: false } }));
const f = finding('function hooks', { [ENABLE_ENV]: '1' });
expect(f.status).toBe('warn');
- expect(f.message).toContain('rollout switch cached OFF');
+ expect(f.message).toContain('serves function hooks OFF');
writeFileSync(join(home, '.claude.json'), JSON.stringify({ cachedGrowthBookFeatures: { tengu_plugin_hooks_modules: true } }));
- expect(finding('function hooks', { [ENABLE_ENV]: '1' }).status).toBe('pass');
+ expect(finding('function hooks', {}).status).toBe('pass'); // observed: loads with the variable unset while served on
});
it('reports a refusal by allowManagedModsOnly', () => {
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
index 1feb1edb08..ca8e11d9bc 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
@@ -200,6 +200,16 @@ describe('ADR-404 no double fire with the real classic hooks', () => {
expect(r.stderr).toContain('[BLOCKED]');
});
+ it('the helper the refresh fallback generates honours the handshake too', async () => {
+ const { generateHookHandler } = await import('../../src/init/helpers-generator.js');
+ const helper = join(project, '.claude', 'helpers', 'hook-handler.cjs');
+ writeFileSync(helper, generateHookHandler());
+ expect(readFileSync(helper, 'utf8')).toContain('RUFLO_MODS_OWNS');
+ expect(classic('route', { prompt: 'implement the api' }, { RUFLO_MODS_OWNS: 'route' }).stdout.trim()).toBe('');
+ expect(classic('route', { prompt: 'implement the api' }, {}).stdout).toContain('Primary Recommendation');
+ expect(classic('pre-bash', { tool_input: { command: 'rm -rf /' } }, { RUFLO_MODS_OWNS: 'pre-bash' }).status).toBe(1);
+ });
+
it('hook-handler exports the ownership check it applies', () => {
const require = (id: string) => execFileSync(process.execPath, ['-e', `const h=require(${JSON.stringify(id)});process.stdout.write(JSON.stringify([h.ownedByMod('route',{RUFLO_MODS_OWNS:' route '}),h.ownedByMod('session-end',{RUFLO_MODS_OWNS:'session-end'}),h.ownedByMod('post-edit',{})]))`], { encoding: 'utf8' });
expect(JSON.parse(require(join(PKG_HELPERS, 'hook-handler.cjs')))).toEqual([true, false, false]);
diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.ts
index 23f95a8904..28aa5f2d41 100644
--- a/v3/@claude-flow/cli/src/init/helpers-generator.ts
+++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts
@@ -538,7 +538,19 @@ export function generateHookHandler(): string {
' });',
'}',
'',
+ // ADR-404: same handshake as the shipped hook-handler.cjs, so a helper
+ // regenerated by the refresh fallback still hands route/post-edit to the mod.
+ '// ADR-404: the ruflo mod names the events it runs in-process in',
+ '// RUFLO_MODS_OWNS; only side-effect events hand over, guards always run.',
+ "const MOD_OWNABLE_EVENTS = new Set(['route', 'post-edit']);",
+ 'function ownedByMod(cmd, env) {',
+ ' env = env || process.env;',
+ ' if (!MOD_OWNABLE_EVENTS.has(cmd)) return false;',
+ " return String(env.RUFLO_MODS_OWNS || '').split(',').some(function (owned) { return owned.trim() === cmd; });",
+ '}',
+ '',
'async function main() {',
+ ' if (ownedByMod(command)) return;',
' let stdinData = "";',
' try { stdinData = await readStdin(); } catch (e) { /* ignore */ }',
' let hookInput = {};',
diff --git a/v3/@claude-flow/cli/src/mods/probe.ts b/v3/@claude-flow/cli/src/mods/probe.ts
index 802c85b0c6..841b1a6b05 100644
--- a/v3/@claude-flow/cli/src/mods/probe.ts
+++ b/v3/@claude-flow/cli/src/mods/probe.ts
@@ -78,15 +78,17 @@ export function probeMods(inputs: ProbeInputs): Finding[] {
return false;
}
});
+ // Observed on Claude Code 2.1.282 (ADR-404): the server-side rollout switch
+ // decides. Served on, an installed mod loaded with ENABLE_ENV unset; served
+ // off, it did not load with ENABLE_ENV=1. The variable is reported, never
+ // treated as sufficient.
const rollout = get(readJson(join(home, '.claude.json')), 'cachedGrowthBookFeatures', 'tengu_plugin_hooks_modules');
- const enableMsg = `${ENABLE_ENV}: ${envOn ? 'set in this environment' : settingsOn ? 'set in settings env' : 'not set'}`;
- const rolloutMsg = rollout === false ? '; Claude Code rollout switch cached OFF for this account' : rollout === true ? '; rollout switch cached on' : '';
- findings.push({
- name: 'function hooks',
- status: (envOn || settingsOn) && rollout !== false ? 'pass' : 'warn',
- message: enableMsg + rolloutMsg + (rollout === undefined ? ' (rollout switch not cached; unverified)' : ''),
- ...(envOn || settingsOn ? {} : { fix: `export ${ENABLE_ENV}=1 (or: ruflo mods install)` }),
- });
+ const enableMsg = `${ENABLE_ENV} ${envOn ? 'set in this environment' : settingsOn ? 'set in settings env' : 'not set'}`;
+ findings.push(rollout === true
+ ? { name: 'function hooks', status: 'pass', message: `Claude Code rollout switch cached on; ${enableMsg}` }
+ : rollout === false
+ ? { name: 'function hooks', status: 'warn', message: `Claude Code serves function hooks OFF for this account (cached); the mod will not load and classic hooks keep every event; ${enableMsg}` }
+ : { name: 'function hooks', status: 'warn', message: `rollout switch not cached (unverified whether the mod can load); ${enableMsg}`, fix: `export ${ENABLE_ENV}=1 and start Claude Code once` });
// 3. Refused by policy?
const managed = readJson(inputs.managedPath ?? managedSettingsPath());
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 6a147a50bd..dc39a2d8f9 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
@@ -17,7 +17,10 @@ Claude Code now offers mods: a plugin whose `hooks/hooks.json` names a hooks mod
Each fact was checked against Claude Code 2.1.282 (`claude plugin validate`, `claude plugin test`, a debug log of a live `claude -p` session) or read from the upstream `mods/` sources and declarations.
- A hooks module runs in its own environment: no Node, no fs, no network, no process. Everything goes through `$`. `claude plugin validate` refuses an import outside the plugin folder ("it is outside the plugin's folder"). It also refuses `$` passed to anything other than a top-level function of the same file, because the engine reads a module's `$` uses off its source.
-- Installed plugins' modules load only with `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1` in the process environment. On top of that, a server-side rollout switch must serve on (`tengu_plugin_hooks_modules`). On this account the switch flipped off and on twice in one afternoon. While it was off, `claude plugin test` refused to run and a live session logged "hooks module not loaded … the rollout switch served off".
+- Whether a module loads is decided by a server-side rollout switch (`tengu_plugin_hooks_modules`, cached in `~/.claude.json`). On this account it flipped off and on twice in one afternoon.
+ - **While it served off**, `claude plugin test` refused to run, and a live session with `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1` logged "hooks module not loaded … the rollout switch served off".
+ - **While it served on**, the plugin loaded with the variable unset, both from `--plugin-dir` and installed from the marketplace. That was tested with an isolated `CLAUDE_CONFIG_DIR`, a local marketplace and `claude plugin install ruflo-mods@ruflo`.
+ - **The variable** is therefore neither required nor sufficient on 2.1.282. `ruflo mods install` writes it anyway, as the CLI's messages ask for it, and `ruflo mods doctor` reports the switch as what decides.
- `sec-default`, seated outermost for managed or Team/Enterprise organizations, continues past the user tier on `prompt.context`, `prompt.section`, `prompt.compose`, `settings.read` and `classic.*`. A person's plugins keep `prompt.submit` and its additive `context`. On `tool.check` it re-runs the chain without the user tier when a user-tier plugin loosened a verdict that a settings deny rule decided. Its `allowManagedModsOnly` option refuses user-tier modules at `plugin.register`.
- `$.env.set` sets a variable on the Claude Code process and on everything it starts afterwards, settings hooks included.
- `$.fs.read` rejects files over 4 MiB, and `$.fs.stat` rejects a missing path with ENOENT.
@@ -90,7 +93,17 @@ Ruflo loads in the user tier. Under `sec-default`:
| Suite | Where | Result |
|---|---|---|
| Claude Code kit (`claude plugin test`), real engine | `plugins/ruflo-mods/tests` | 7/7 pass (ran while the rollout switch served on) |
-| Harness faithful to the declarations (vitest) | `v3/@claude-flow/cli/__tests__/mods` | 84/84 pass |
+| Harness faithful to the declarations (vitest) | `v3/@claude-flow/cli/__tests__/mods` | 87/87 pass |
+| Existing CLI suite | `v3/@claude-flow/cli` | Same failures as `origin/main` in the same environment (4 memory tests), plus `helper-signing` until the manifest is re-signed |
+
+Live runs, Claude Code 2.1.282 with `claude -p`:
+
+1. **`/ruflo-mods` via `--plugin-dir`.** The module was admitted at user tier and wrote its heartbeat. It owned nothing, correctly: this machine's user settings run an older `$HOME` hook-handler.
+2. **Enforce-mode projection denying `echo forbidden*`.** The engine logged `tool.check Bash: allow -> deny by plugin ruflo-mods: ruflo policy: denied-by:no-forbidden-echo`. The allowed command still ran.
+3. **Rollout switch off.** The module was refused and the session finished on the classic path.
+4. **Installed plugin.** Installed from a local marketplace into an isolated config, it loaded and owned `route, post-edit` (no classic hooks configured there).
+
+No live prompt was routed by an owning mod, because the isolated config has no credentials for a model call.
| Typecheck against the declarations (`tsc`, strict) | `plugins/ruflo-mods/tsconfig.json` | clean |
| `claude plugin validate` | plugin and marketplace | pass |
| Plugin smoke contract (static security) | `plugins/ruflo-mods/scripts/smoke.sh` | 9/9 |