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(cli): ruflo mods install|uninstall|status|doctor|sync-policy, init --mods, doctor check (ADR-404)

ruv73f530e9087a
diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.ts
index 188572b177..6253d190f2 100644
--- a/v3/@claude-flow/cli/src/commands/doctor.ts
+++ b/v3/@claude-flow/cli/src/commands/doctor.ts
@@ -2375,6 +2375,22 @@ async function checkMetaharness(): Promise<HealthCheck> {
}
}
+// ADR-404 β€” ruflo as a Claude Code mod (function hooks, early access). One
+// line in a bare `doctor`: whether the mod is enabled, can load (function
+// hooks on, not refused by allowManagedModsOnly) and has started; never a
+// failure, since the classic hooks are the default and the fallback.
+// `ruflo mods doctor` prints every finding.
+async function checkMods(): Promise<HealthCheck> {
+ const { probeMods } = await import('../mods/probe.js');
+ const findings = probeMods({ projectRoot: process.cwd() });
+ const enabled = findings.find((f) => f.name === 'ruflo-mods plugin')?.status === 'pass';
+ if (!enabled) return { name: 'ruflo mods (ADR-404)', status: 'pass', message: 'not enabled; classic hooks handle every event' };
+ const warnings = findings.filter((f) => f.status !== 'pass');
+ return warnings.length === 0
+ ? { name: 'ruflo mods (ADR-404)', status: 'pass', message: findings.find((f) => f.name === 'last mod start')?.message ?? 'enabled' }
+ : { name: 'ruflo mods (ADR-404)', status: 'warn', message: warnings.map((f) => `${f.name}: ${f.message}`).join('; '), fix: 'ruflo mods doctor' };
+}
+
// Opt-in @ruvector/typesafe task router (optional peer). `--component typesafe` only.
async function checkTypesafeRouter(): Promise<HealthCheck> {
const name = '@ruvector/typesafe router';
@@ -2584,7 +2600,7 @@ export const doctorCommand: Command = {
{
name: 'component',
short: 'c',
- description: 'Check specific component (version, node, npm, config, daemon, memory, api, git, mcp, mcp-overhead, claude, browser, disk, typescript, agentic-flow, encryption, federation, funnel, proxy, auth, typesafe, metaharness)',
+ description: 'Check specific component (version, node, npm, config, daemon, memory, api, git, mcp, mcp-overhead, claude, browser, disk, typescript, agentic-flow, encryption, federation, funnel, proxy, auth, typesafe, metaharness, mods)',
type: 'string'
},
{
@@ -2735,6 +2751,7 @@ export const doctorCommand: Command = {
checkFunnel, // ADR-305 β€” effective funnel state + deciding precedence source
checkProxySponsoredConsent, // ADR-313 β€” Meta LLM Proxy sponsored-downtime health
checkAuth, // ADR-306 β€” Cognitum identity (warn-only; never fails bare `ruflo doctor`)
+ checkMods, // ADR-404 β€” Claude Code mod path (warn-only)
];
// #2677: `--component memory` now runs the whole memory-health suite,
@@ -2789,6 +2806,7 @@ export const doctorCommand: Command = {
'proxy': [checkProxySponsoredConsent, checkProxyBinary, checkProxyProcess, checkProxyBindAddress],
'auth': checkAuth, // ADR-306
'typesafe': checkTypesafeRouter, // opt-in @ruvector/typesafe task router
+ 'mods': checkMods, // ADR-404 β€” ruflo as a Claude Code mod
};
let checksToRun = allChecks;
diff --git a/v3/@claude-flow/cli/src/commands/index.ts b/v3/@claude-flow/cli/src/commands/index.ts
index d868d9ff36..f454d50a08 100644
--- a/v3/@claude-flow/cli/src/commands/index.ts
+++ b/v3/@claude-flow/cli/src/commands/index.ts
@@ -97,6 +97,8 @@ const commandLoaders: Record<string, CommandLoader> = {
advisor: () => import('./advisor.js'),
// Ruflo verbs in Claude Code's spinnerVerbs rotation (ADR-318)
spinner: () => import('./spinner.js'),
+ // ruflo as a Claude Code mod: function hooks, early access (ADR-404)
+ mods: () => import('./mods.js'),
// Ruflo entries in Claude Code's companyAnnouncements startup rotation (ADR-319)
announcements: () => import('./announcements.js'),
// AGNTCY/Outshift runtime transport selection (ADR-324 Β§2) β€” optional,
diff --git a/v3/@claude-flow/cli/src/commands/init.ts b/v3/@claude-flow/cli/src/commands/init.ts
index 1abd4b2392..3b32af492a 100644
--- a/v3/@claude-flow/cli/src/commands/init.ts
+++ b/v3/@claude-flow/cli/src/commands/init.ts
@@ -866,6 +866,19 @@ 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) {
+ 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")`));
+ } catch (err) {
+ output.writeln(output.warning(` ruflo-mods not enabled: ${err instanceof Error ? err.message : String(err)}`));
+ }
+ }
+
if (!startDaemon && !startAll) {
const bin = (process.argv[1] || '').includes('ruflo') ? 'ruflo' : 'claude-flow';
output.writeln(output.bold('Next steps:'));
@@ -1669,6 +1682,13 @@ export const initCommand: Command = {
type: 'boolean',
default: false,
},
+ {
+ // ADR-404 β€” Claude Code function hooks are early access; opt-in only.
+ name: 'mods',
+ description: 'Also enable the ruflo Claude Code mod (function hooks, early access); classic hooks stay as fallback',
+ type: 'boolean',
+ default: false,
+ },
{
name: 'with-embeddings',
description: 'Initialize ONNX embedding subsystem with hyperbolic support',
diff --git a/v3/@claude-flow/cli/src/commands/mods.ts b/v3/@claude-flow/cli/src/commands/mods.ts
new file mode 100644
index 0000000000..2461fd19a0
--- /dev/null
+++ b/v3/@claude-flow/cli/src/commands/mods.ts
@@ -0,0 +1,133 @@
+/**
+ * `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;
+ * 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.
+ */
+
+import type { Command, CommandContext, CommandResult } from '../types.js';
+import { output } from '../output.js';
+import { installMod, uninstallMod, type Scope } from '../mods/install.js';
+import { probeMods, type Finding } from '../mods/probe.js';
+
+function projectRoot(ctx: CommandContext): string {
+ return (ctx.flags.projectRoot as string | undefined) ?? (ctx.flags['project-root'] as string | undefined) ?? ctx.cwd ?? process.cwd();
+}
+
+function printFindings(findings: Finding[]): void {
+ for (const f of findings) {
+ const mark = f.status === 'pass' ? output.success('βœ“') : f.status === 'warn' ? output.warning('!') : output.error('βœ—');
+ output.writeln(`${mark} ${f.name}: ${f.message}`);
+ if (f.fix && f.status !== 'pass') output.writeln(output.dim(` fix: ${f.fix}`));
+ }
+}
+
+const rootOption = { name: 'project-root', description: 'Project root (default: current directory)', type: 'string' as const };
+
+const installSub: Command = {
+ name: 'install',
+ description: 'Enable the ruflo-mods plugin for this project (opt-in; 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', type: 'boolean', default: false },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const scope = (ctx.flags.scope as string | undefined) ?? 'local';
+ if (scope !== 'local' && scope !== 'project') {
+ output.printError(`--scope must be local or project, got ${scope}`);
+ return { success: false, exitCode: 1 };
+ }
+ const root = projectRoot(ctx);
+ 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);
+ return { success: true, data: result };
+ }
+ await syncPolicy(root, true);
+ output.printSuccess(`ruflo-mods enabled in ${result.settingsFile}${result.backup ? ` (backup: ${result.backup})` : ''}`);
+ output.writeln('Restart Claude Code, then run /ruflo-mods in a session to see what the mod owns.');
+ output.writeln(output.dim('Early access: Claude Code loads it only where function hooks are on. Run `ruflo mods doctor`.'));
+ return { success: true, data: result };
+ },
+};
+
+const uninstallSub: Command = {
+ name: 'uninstall',
+ description: 'Remove what `ruflo mods install` added (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));
+ 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'} ruflo-mods from ${result.settingsFile}`);
+ return { success: true, data: result };
+ },
+};
+
+function findingsCommand(name: 'status' | 'doctor', description: string): Command {
+ return {
+ name,
+ description,
+ options: [rootOption, { name: 'json', description: 'Output as JSON', type: 'boolean', default: false }],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const findings = probeMods({ projectRoot: projectRoot(ctx) });
+ if (ctx.flags.json) output.printJson(findings);
+ else printFindings(findings);
+ const failed = findings.some((f) => f.status === 'fail');
+ // status reports; doctor gates (warnings are expected while early access is off).
+ return { success: !failed, exitCode: name === 'doctor' && failed ? 1 : 0, data: findings };
+ },
+ };
+}
+
+async function syncPolicy(root: string, quiet: boolean): Promise<boolean> {
+ try {
+ const { loadPolicyState } = await import('../services/policy-runtime.js');
+ const { syncPolicyProjection } = await import('../mods/policy-projection.js');
+ const result = syncPolicyProjection(root, loadPolicyState(root));
+ if (!quiet || result.action !== 'unchanged') output.writeln(`policy projection: ${result.action} (${result.path})`);
+ return true;
+ } catch (error) {
+ output.printWarning(`policy projection not synced: ${(error as Error).message}`);
+ return false;
+ }
+}
+
+const syncPolicySub: Command = {
+ name: 'sync-policy',
+ description: 'Rewrite the Claude Code policy projection from .claude-flow/policy/state.json',
+ options: [rootOption],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const ok = await syncPolicy(projectRoot(ctx), false);
+ return { success: ok, exitCode: ok ? 0 : 1 };
+ },
+};
+
+const statusSub = findingsCommand('status', 'Show whether the mod is enabled, can load, and what it owns');
+
+export const modsCommand: Command = {
+ name: 'mods',
+ description: 'Run ruflo as a Claude Code mod (function hooks, early access, ADR-404)',
+ subcommands: [
+ installSub,
+ uninstallSub,
+ statusSub,
+ findingsCommand('doctor', 'Check the mod path; exits 1 only on a failure'),
+ syncPolicySub,
+ ],
+ examples: [
+ { command: 'ruflo mods install', description: 'Enable for this project (settings.local.json)' },
+ { command: 'ruflo mods doctor', description: 'Function hooks on? Refused by policy? Handshake supported?' },
+ { command: 'ruflo mods uninstall', description: 'Remove only what install added' },
+ ],
+ action: statusSub.action,
+};
+
+export default modsCommand;
diff --git a/v3/@claude-flow/cli/src/mods/install.ts b/v3/@claude-flow/cli/src/mods/install.ts
new file mode 100644
index 0000000000..2f02ff7383
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mods/install.ts
@@ -0,0 +1,155 @@
+/**
+ * `ruflo mods install|uninstall` (ADR-404): enable the ruflo-mods plugin for
+ * one project, opt-in, 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
+ * `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).
+ */
+
+import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
+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;
+export const ENABLE_ENV = 'CLAUDE_CODE_ENABLE_FUNCTION_HOOKS';
+export const INSTALL_RECORD = join('.claude-flow', 'mods', 'install.json');
+
+export type Scope = 'local' | 'project';
+
+export interface InstallRecord {
+ version: 1;
+ settingsFile: string;
+ installedAt: string;
+ added: { plugin: boolean; marketplace: boolean; env: boolean };
+}
+
+type Settings = Record<string, unknown> & {
+ enabledPlugins?: Record<string, unknown>;
+ extraKnownMarketplaces?: Record<string, unknown>;
+ env?: Record<string, unknown>;
+};
+
+export function settingsFileFor(projectRoot: string, scope: Scope): string {
+ return join(resolve(projectRoot), '.claude', scope === 'local' ? 'settings.local.json' : 'settings.json');
+}
+
+function isRecord(v: unknown): v is Record<string, unknown> {
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
+}
+
+/** Reads a settings file; absent is `{}`, anything unparseable throws (never overwritten). */
+export function readSettingsFile(path: string): Settings {
+ if (!existsSync(path)) return {};
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'));
+ if (!isRecord(parsed)) throw new Error(`${path} is not a JSON object`);
+ return parsed as Settings;
+}
+
+function writeJson(path: string, value: unknown): void {
+ mkdirSync(dirname(path), { recursive: true });
+ const tmp = `${path}.${process.pid}.tmp`;
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
+ renameSync(tmp, path);
+}
+
+/** The settings after install, and what install added (pure). */
+export function withModEnabled(settings: Settings): { next: Settings; added: InstallRecord['added'] } {
+ const next: Settings = { ...settings };
+ const plugins = 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,
+ marketplace: !(MARKETPLACE_NAME in markets),
+ env: env[ENABLE_ENV] !== '1',
+ };
+ plugins[MOD_PLUGIN_ID] = true;
+ if (added.marketplace) markets[MARKETPLACE_NAME] = MARKETPLACE_SOURCE;
+ env[ENABLE_ENV] = '1';
+ next.enabledPlugins = plugins;
+ 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 {
+ const next: Settings = { ...settings };
+ const drop = (key: 'enabledPlugins' | 'extraKnownMarketplaces' | 'env', name: string) => {
+ const section = next[key];
+ if (!isRecord(section)) return;
+ const copy = { ...section };
+ delete copy[name];
+ if (Object.keys(copy).length === 0) delete next[key];
+ else next[key] = copy;
+ };
+ if (added.plugin) drop('enabledPlugins', MOD_PLUGIN_ID);
+ if (added.marketplace) drop('extraKnownMarketplaces', MARKETPLACE_NAME);
+ if (added.env) drop('env', ENABLE_ENV);
+ return next;
+}
+
+export interface InstallResult {
+ settingsFile: string;
+ backup?: string;
+ added: InstallRecord['added'];
+ dryRun: boolean;
+ next: Settings;
+}
+
+export function installMod(projectRoot: string, scope: Scope, dryRun = false): InstallResult {
+ const settingsFile = settingsFileFor(projectRoot, scope);
+ const current = readSettingsFile(settingsFile);
+ const { next, added } = withModEnabled(current);
+ if (dryRun) return { settingsFile, added, dryRun, next };
+
+ let backup: string | undefined;
+ if (existsSync(settingsFile)) {
+ backup = `${settingsFile}.bak-ruflo-mods-${Date.now()}`;
+ 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 };
+}
+
+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;
+ } catch {
+ return null;
+ }
+}
+
+export function uninstallMod(projectRoot: string, dryRun = false): { settingsFile?: 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.
+ 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}`);
+ }
+ if (dryRun) return { settingsFile: record.settingsFile, removed: true, dryRun };
+ if (existsSync(record.settingsFile)) {
+ writeJson(record.settingsFile, withModRemoved(readSettingsFile(record.settingsFile), record.added));
+ }
+ unlinkSync(join(root, INSTALL_RECORD));
+ return { settingsFile: record.settingsFile, removed: true, dryRun };
+}
diff --git a/v3/@claude-flow/cli/src/mods/policy-projection.ts b/v3/@claude-flow/cli/src/mods/policy-projection.ts
new file mode 100644
index 0000000000..9e7691e451
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mods/policy-projection.ts
@@ -0,0 +1,76 @@
+/**
+ * The policy projection the ruflo mod reads (ADR-404).
+ *
+ * A hooks module may read at most 4 MiB and cannot import @claude-flow/security,
+ * while `.claude-flow/policy/state.json` carries the whole receipt ledger
+ * (tens of MB on a busy project). So every policy state write also writes a
+ * small file holding only what the mod's `tool.check` needs: the mode and the
+ * rules that name a `claude-code.` action explicitly. Legacy mode, or no such
+ * rule, removes the file, and the mod then adds no policy of its own.
+ *
+ * The projection never authorizes anything: the mod only tightens Claude
+ * Code's own verdict with it, so a deleted or stale projection returns to the
+ * no-mod baseline and can never loosen a call. It is not a ledger and holds
+ * no receipts; issue #3602 (the ledger anchor) is untouched by it.
+ */
+
+import { existsSync, mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import type { PolicyRule, PolicyState } from '@claude-flow/security';
+
+export const PROJECTION_RELATIVE = join('.claude-flow', 'policy', 'claude-code.json');
+export const CLAUDE_CODE_ACTION_PREFIX = 'claude-code.';
+
+export interface PolicyProjection {
+ version: 1;
+ mode: PolicyState['mode'];
+ generatedAt: number;
+ rules: PolicyRule[];
+}
+
+/** Whether a rule names Claude Code tool calls explicitly (never via `*` or no actions). */
+export function targetsClaudeCode(rule: Pick<PolicyRule, 'actions'>): boolean {
+ return Array.isArray(rule.actions) && rule.actions.some((a) => typeof a === 'string' && a.startsWith(CLAUDE_CODE_ACTION_PREFIX));
+}
+
+/** The projection of a state, or null when there is nothing to project. */
+export function projectionOf(state: Pick<PolicyState, 'mode' | 'rules'>, now = Date.now()): PolicyProjection | null {
+ if (state.mode === 'legacy') return null;
+ const rules = (Array.isArray(state.rules) ? state.rules : []).filter(targetsClaudeCode).map((rule) => ({
+ id: rule.id,
+ effect: rule.effect,
+ actions: [...rule.actions],
+ ...(rule.enabled !== undefined ? { enabled: rule.enabled } : {}),
+ ...(rule.priority !== undefined ? { priority: rule.priority } : {}),
+ ...(rule.resources ? { resources: [...rule.resources] } : {}),
+ ...(rule.principals ? { principals: [...rule.principals] } : {}),
+ ...(rule.identityTypes ? { identityTypes: [...rule.identityTypes] } : {}),
+ ...(rule.roles ? { roles: [...rule.roles] } : {}),
+ ...(rule.environments ? { environments: [...rule.environments] } : {}),
+ ...(rule.constraints ? { constraints: { ...rule.constraints } } : {}),
+ }));
+ if (rules.length === 0) return null;
+ return { version: 1, mode: state.mode, generatedAt: now, rules };
+}
+
+export type ProjectionSync = { action: 'written' | 'removed' | 'unchanged'; path: string };
+
+/**
+ * Writes (atomically, owner-only) or removes the projection for a state.
+ * Throws on I/O failure; policy-runtime calls it after the state is safely
+ * written and keeps the state write's own result whatever happens here.
+ */
+export function syncPolicyProjection(projectRoot: string, state: Pick<PolicyState, 'mode' | 'rules'>): ProjectionSync {
+ const path = join(resolve(projectRoot), PROJECTION_RELATIVE);
+ const projection = projectionOf(state);
+ if (!projection) {
+ if (!existsSync(path)) return { action: 'unchanged', path };
+ unlinkSync(path);
+ return { action: 'removed', path };
+ }
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
+ writeFileSync(tmp, `${JSON.stringify(projection, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
+ renameSync(tmp, path);
+ return { action: 'written', path };
+}
diff --git a/v3/@claude-flow/cli/src/mods/probe.ts b/v3/@claude-flow/cli/src/mods/probe.ts
new file mode 100644
index 0000000000..802c85b0c6
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mods/probe.ts
@@ -0,0 +1,134 @@
+/**
+ * What can be known, from outside a Claude Code session, about whether the
+ * ruflo mod will load and what it will own (ADR-404). Every finding names its
+ * source; nothing here claims a live load it did not see. The one direct
+ * evidence of a load is the heartbeat the mod writes at session start.
+ */
+
+import { existsSync, readFileSync } from 'node:fs';
+import { homedir, platform } from 'node:os';
+import { join, resolve } from 'node:path';
+
+import { ENABLE_ENV, MOD_PLUGIN_ID, readRecord, readSettingsFile, settingsFileFor } from './install.js';
+import { PROJECTION_RELATIVE } from './policy-projection.js';
+
+export const HANDSHAKE_MARKER = 'RUFLO_MODS_OWNS';
+export const HEARTBEAT_RELATIVE = join('.claude-flow', 'mods', 'session.json');
+const SEC_DEFAULT_ID = 'cc-plugin-sec-default@builtin';
+
+export type Status = 'pass' | 'warn' | 'fail';
+export interface Finding {
+ name: string;
+ status: Status;
+ message: string;
+ fix?: string;
+}
+
+function readJson(path: string): unknown {
+ try {
+ return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function get(obj: unknown, ...keys: string[]): unknown {
+ return keys.reduce<unknown>((o, k) => (o !== null && typeof o === 'object' ? (o as Record<string, unknown>)[k] : undefined), obj);
+}
+
+/** Managed settings, where an organization sets sec-default's options. */
+export function managedSettingsPath(os = platform()): string {
+ if (os === 'darwin') return '/Library/Application Support/ClaudeCode/managed-settings.json';
+ if (os === 'win32') return 'C:\\ProgramData\\ClaudeCode\\managed-settings.json';
+ return '/etc/claude-code/managed-settings.json';
+}
+
+export interface ProbeInputs {
+ projectRoot: string;
+ home?: string;
+ env?: NodeJS.ProcessEnv;
+ managedPath?: string;
+}
+
+export function probeMods(inputs: ProbeInputs): Finding[] {
+ const root = resolve(inputs.projectRoot);
+ const home = inputs.home ?? homedir();
+ const env = inputs.env ?? process.env;
+ const findings: Finding[] = [];
+
+ // 1. Enabled for this project?
+ const files = [settingsFileFor(root, 'local'), settingsFileFor(root, 'project'), join(home, '.claude', 'settings.json')];
+ const enabledIn = files.find((f) => {
+ try {
+ return get(readSettingsFile(f), 'enabledPlugins', MOD_PLUGIN_ID) === true;
+ } catch {
+ return false;
+ }
+ });
+ findings.push(enabledIn
+ ? { name: 'ruflo-mods plugin', status: 'pass', message: `enabled in ${enabledIn}` }
+ : { name: 'ruflo-mods plugin', status: 'warn', message: 'not enabled; classic hooks handle every event', fix: 'ruflo mods install' });
+
+ // 2. Function hooks switched on for installed plugins (early access).
+ const envOn = env[ENABLE_ENV] === '1';
+ const settingsOn = files.some((f) => {
+ try {
+ return get(readSettingsFile(f), 'env', ENABLE_ENV) === '1';
+ } catch {
+ return false;
+ }
+ });
+ 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)` }),
+ });
+
+ // 3. Refused by policy?
+ const managed = readJson(inputs.managedPath ?? managedSettingsPath());
+ const managedOnly = get(managed, 'pluginConfigs', SEC_DEFAULT_ID, 'options', 'allowManagedModsOnly');
+ findings.push(managedOnly !== undefined && managedOnly !== false
+ ? { name: 'managed policy', status: 'warn', message: 'allowManagedModsOnly is set: Claude Code refuses user mods; classic hooks stay in charge' }
+ : { name: 'managed policy', status: 'pass', message: managed === undefined ? 'no managed settings' : 'user mods allowed (allowManagedModsOnly not set)' });
+
+ // 4. Every classic helper a hook could run honours the handshake (the mod's
+ // own rule, plugins/ruflo-mods/hooks/session.ts); else the mod stands down.
+ const helpers = [...new Set([join(root, '.claude', 'helpers', 'hook-handler.cjs'), join(home, '.claude', 'helpers', 'hook-handler.cjs')])].filter(existsSync);
+ const stale = helpers.filter((h) => {
+ try {
+ return !readFileSync(h, 'utf8').includes(HANDSHAKE_MARKER);
+ } catch {
+ return true;
+ }
+ });
+ findings.push(helpers.length === 0
+ ? { name: 'classic handshake', status: 'pass', message: 'no hook-handler.cjs: the mod owns route and post-edit outright' }
+ : stale.length === 0
+ ? { name: 'classic handshake', status: 'pass', message: `${helpers.join(', ')} hand route and post-edit to the mod while it runs` }
+ : { name: 'classic handshake', status: 'warn', message: `${stale.join(', ')} predate${stale.length === 1 ? 's' : ''} the handshake: the mod stands down and classic hooks keep route/post-edit`, fix: 'ruflo init --upgrade (refresh helpers in the project and in ~/.claude)' });
+
+ // 5. Policy projection.
+ const projectionPath = join(root, PROJECTION_RELATIVE);
+ const projection = readJson(projectionPath);
+ const stateMode = get(readJson(join(root, '.claude-flow', 'policy', 'state.json')), 'mode');
+ findings.push(projection !== undefined
+ ? { name: 'policy projection', status: 'pass', message: `${get(projection, 'mode')} mode, ${(get(projection, 'rules') as unknown[] | undefined)?.length ?? 0} claude-code rule(s)` }
+ : stateMode === 'enforce' || stateMode === 'observe'
+ ? { name: 'policy projection', status: 'warn', message: `policy is ${String(stateMode)} but no projection exists (no claude-code.* rules, or state written by an older CLI)`, fix: 'ruflo mods sync-policy' }
+ : { name: 'policy projection', status: 'pass', message: 'none (no ruflo policy for Claude Code tools)' });
+
+ // 6. Evidence of a load.
+ const beat = readJson(join(root, HEARTBEAT_RELATIVE));
+ const startedAt = get(beat, 'startedAt');
+ const owned = get(beat, 'owned');
+ findings.push(typeof startedAt === 'string'
+ ? { name: 'last mod start', status: 'pass', message: `${startedAt}, owning ${Array.isArray(owned) && owned.length ? owned.join(', ') : 'nothing'}` }
+ : { name: 'last mod start', status: enabledIn ? 'warn' : 'pass', message: 'the mod has not started in this project' + (enabledIn ? ' (restart Claude Code; check function hooks above)' : '') });
+
+ if (readRecord(root)) findings.push({ name: 'install record', status: 'pass', message: join(root, '.claude-flow', 'mods', 'install.json') });
+ return findings;
+}
diff --git a/v3/@claude-flow/cli/src/services/policy-runtime.ts b/v3/@claude-flow/cli/src/services/policy-runtime.ts
index 8102882834..1f75fede1d 100644
--- a/v3/@claude-flow/cli/src/services/policy-runtime.ts
+++ b/v3/@claude-flow/cli/src/services/policy-runtime.ts
@@ -35,6 +35,7 @@ import {
} from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { hostname, userInfo } from 'node:os';
+import { syncPolicyProjection } from '../mods/policy-projection.js';
const POLICY_DIR = join('.claude-flow', 'policy');
const POLICY_FILE = 'state.json';
@@ -240,6 +241,20 @@ function verifyStateAnchor(projectRoot: string, state: PolicyState | undefined):
}
async function writePolicyState(projectRoot: string, statePath: string, state: PolicyState): Promise<void> {
+ await writePolicyStateFiles(projectRoot, statePath, state);
+ // ADR-404: the ruflo mod reads Claude Code tool rules from a small
+ // projection, never from state.json. Written only after the state and its
+ // anchor are safely down; a failure here never fails the state write. A
+ // projection left stale by such a failure can only tighten, never loosen,
+ // a Claude Code verdict (the mod merges with `stricter`).
+ try {
+ syncPolicyProjection(projectRoot, state);
+ } catch (error) {
+ process.stderr.write(`[policy] claude-code projection not written: ${(error as Error).message}\n`);
+ }
+}
+
+async function writePolicyStateFiles(projectRoot: string, statePath: string, state: PolicyState): Promise<void> {
const anchorPath = trustPaths(projectRoot).anchor;
if (state.mode === 'enforce' || existsSync(anchorPath)) {
const key = trustKey(projectRoot, true)!;