π 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(cli): load ruflo plugins in headless claude -p workers (ADR-510) (#4586)
rUv76845f22d320
diff --git a/plugins/ruflo-mods/README.md b/plugins/ruflo-mods/README.mdindex 9006921f4b..39afd59b75 100644--- a/plugins/ruflo-mods/README.md+++ b/plugins/ruflo-mods/README.md@@ -50,6 +50,38 @@ Settings alone are not always enough. Claude Code loads these plugins from its l- **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.+## Headless workers and the Agent SDK (ADR-510)++A headless `claude -p` on a fresh config loads no marketplace plugins, so ruflo hands its own workers the plugin folders.++- **ruflo's workers pass `--plugin-dir`.** The background worker daemon, `hive-mind work` and `hive-mind spawn --claude --non-interactive` add `--plugin-dir <folder>` for each plugin in the worker profile (default: ruflo-mods) and set `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1` unless you set it. `RUFLO_HEADLESS_PLUGINS=ruflo-mods,ruflo-swarm` changes the profile; `none` turns it off. A plugin that cannot be found is logged once (`plugin <name> not found; worker runs without it`) and recorded on the worker's result; the worker still runs.+- **Where the folders come from**, in order: a `--source local` checkout that Claude Code itself records in your user-level `known_marketplaces.json` (added through an interactive, trusted start), the marketplace clone, then the install cache (`plugins/cache/ruflo/<name>/<version>`). A folder without `.claude-plugin/plugin.json` is reported missing, never used. A project's own `.claude/settings.json` or `settings.local.json` never chooses the folder, and a relative path is ignored: `--plugin-dir` loads without a trust prompt, so a cloned repository must not be able to swap its own code in for your ruflo-mods.+- **`ruflo plugins paths [--json]`** prints the same resolution, for your own `claude -p` scripts.+- **`ruflo doctor --component headless-plugins`** runs `claude -p --plugin-dir <ruflo-mods> --output-format stream-json --verbose "reply ok"` (haiku, 60 s) in a throwaway project and reports whether the init event lists ruflo-mods, whether `plugin_errors` is empty, and whether the mod's heartbeat (`.claude-flow/mods/session.json`) was written. It spends one small model call, so a bare `ruflo doctor` does not run it; without any model credential it is skipped.++### Using ruflo plugins from the Agent SDK++The Agent SDK takes plugins only as `{ type: "local", path }`, and skips a path that does not exist without an error. Build the list from `ruflo plugins paths --json`, then check the session's init message:++```ts+import { execFileSync } from "node:child_process";+import { query } from "@anthropic-ai/claude-agent-sdk";++const { resolved, missing } = JSON.parse(execFileSync("npx", ["ruflo", "plugins", "paths", "--json"], { encoding: "utf8" }));+if (missing.length) console.warn("ruflo plugins not found:", missing);++for await (const msg of query({+ prompt: "reply ok",+ options: { plugins: resolved.map((p) => ({ type: "local", path: p.path })), env: { ...process.env, CLAUDE_CODE_ENABLE_FUNCTION_HOOKS: "1" } },+})) {+ if (msg.type === "system" && msg.subtype === "init") {+ console.log("plugins:", msg.plugins, "errors:", msg.plugin_errors ?? []);+ }+}+```++**Unverified:** whether function-hook mods (ruflo-mods' guard, routing and learning loop) run under the SDK is not documented, and ruflo has no SDK dependency to test it with. Skills, commands and agents load; check for the heartbeat file above to see whether the hooks ran in your setup.+## Flags- `--no-plugin-install` writes settings only and runs no `claude` command.diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-headless-plugins.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-headless-plugins.test.tsnew file mode 100644index 0000000000..b8e29c0378--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/mods/mods-headless-plugins.test.ts@@ -0,0 +1,239 @@+/**+ * ADR-510 β loading ruflo plugins in headless `claude -p` workers.+ *+ * - resolvePluginPaths: each source in order (local checkout, clone, cache),+ * a missing manifest, a CLAUDE_CONFIG_DIR override, and that the project's+ * own settings (or a relative path) never choose the folder.+ * - withHeadlessPlugins: adds --plugin-dir + CLAUDE_CODE_ENABLE_FUNCTION_HOOKS,+ * never duplicates a caller's own flag, keeps a caller's env value, logs a+ * missing plugin once and reports it.+ * - the doctor check, with an injected runner (no claude, no API key).+ *+ * Mock-first: a fake filesystem; nothing here reads the real ~/.claude.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { join } from 'node:path';++import { resolvePluginPaths, type PluginFs } from '../../src/mods/plugin-paths.js';+import { existingPluginDirs, resetHeadlessPluginWarnings, withHeadlessPlugins, workerProfile } from '../../src/mods/headless-plugins.js';+import { checkHeadlessPlugins, findInitEvent, hasModelCredential, HEARTBEAT, type HeadlessRunner } from '../../src/mods/headless-check.js';++const HOME = '/home/u';+const CFG = join(HOME, '.claude');+const ROOT = '/work/proj';+const CHECKOUT = '/src/ruflo';+const CLONE = join(CFG, 'plugins', 'marketplaces', 'ruflo');+const cacheDir = (cfg: string, v: string) => join(cfg, 'plugins', 'cache', 'ruflo', 'ruflo-mods', v);+const manifestIn = (dir: string) => join(dir, '.claude-plugin', 'plugin.json');++/** Fake fs: files (with text), plus directory listings derived from every path. */+function fakeFs(files: Record<string, unknown>, dirs: string[] = []): PluginFs {+ const all = [...Object.keys(files), ...dirs];+ const exists = new Set(all);+ for (const p of all) {+ let d = p;+ while (d !== '/' && d !== '.') {+ d = join(d, '..');+ exists.add(d);+ }+ }+ return {+ exists: (p) => exists.has(p),+ readText: (p) => (p in files ? (typeof files[p] === 'string' ? (files[p] as string) : JSON.stringify(files[p])) : undefined),+ list: (p) => [...new Set(all.filter((x) => x.startsWith(`${p}/`)).map((x) => x.slice(p.length + 1).split('/')[0]!))],+ };+}++const knownLocal = { [join(CFG, 'plugins', 'known_marketplaces.json')]: { ruflo: { source: { source: 'directory', path: CHECKOUT }, installLocation: CHECKOUT } } };+const inCheckout = { [manifestIn(join(CHECKOUT, 'plugins', 'ruflo-mods'))]: '{}' };+const inClone = { [manifestIn(join(CLONE, 'plugins', 'ruflo-mods'))]: '{}' };+const opts = (fs: PluginFs, env: NodeJS.ProcessEnv = {}) => ({ projectRoot: ROOT, env, home: HOME, fs });++describe('ADR-510 resolvePluginPaths', () => {+ it('prefers a directory marketplace Claude Code knows (user-level) over the clone and the cache', () => {+ const fs = fakeFs({ ...knownLocal, ...inCheckout, ...inClone, [manifestIn(cacheDir(CFG, '0.8.0'))]: '{}' }, [CHECKOUT]);+ expect(resolvePluginPaths(['ruflo-mods'], opts(fs))).toEqual({+ resolved: [{ name: 'ruflo-mods', path: join(CHECKOUT, 'plugins', 'ruflo-mods'), source: 'local' }],+ missing: [],+ });+ });++ it("never lets the project's own settings choose the folder (committed settings.json or settings.local.json)", () => {+ const EVIL = join(ROOT, 'x');+ const inRepo = { [manifestIn(join(EVIL, 'plugins', 'ruflo-mods'))]: '{}' };+ for (const declared of [EVIL, './x']) {+ const entry = { extraKnownMarketplaces: { ruflo: { source: { source: 'directory', path: declared } } } };+ for (const file of ['settings.json', 'settings.local.json']) {+ const settings = { [join(ROOT, '.claude', file)]: entry };+ // With a clone present: the clone wins, never the repo.+ const withClone = resolvePluginPaths(['ruflo-mods'], opts(fakeFs({ ...settings, ...inRepo, ...inClone }, [CLONE])));+ expect(withClone.resolved).toEqual([{ name: 'ruflo-mods', path: join(CLONE, 'plugins', 'ruflo-mods'), source: 'clone' }]);+ // With only the cache: the cache wins.+ const withCache = resolvePluginPaths(['ruflo-mods'], opts(fakeFs({ ...settings, ...inRepo, [manifestIn(cacheDir(CFG, '0.8.0'))]: '{}' })));+ expect(withCache.resolved[0]).toMatchObject({ source: 'cache', path: cacheDir(CFG, '0.8.0') });+ // With nothing installed: missing, and the repo folder is not even mentioned.+ const nothing = resolvePluginPaths(['ruflo-mods'], opts(fakeFs({ ...settings, ...inRepo })));+ expect(nothing.resolved).toEqual([]);+ expect(nothing.missing[0]!.reason).not.toContain(ROOT);+ }+ }+ });++ it('a relative directory path, even in known_marketplaces.json, is rejected', () => {+ const rel = { [join(CFG, 'plugins', 'known_marketplaces.json')]: { ruflo: { source: { source: 'directory', path: './x' } } } };+ const fs = fakeFs({ ...rel, [manifestIn(join(ROOT, 'x', 'plugins', 'ruflo-mods'))]: '{}', [manifestIn(join('x', 'plugins', 'ruflo-mods'))]: '{}', [manifestIn(cacheDir(CFG, '0.8.0'))]: '{}' });+ expect(resolvePluginPaths(['ruflo-mods'], opts(fs)).resolved[0]).toMatchObject({ source: 'cache' });+ });++ it('falls back to the marketplace clone, honouring marketplace.json source', () => {+ const fs = fakeFs({ ...inClone }, [CLONE]);+ expect(resolvePluginPaths(['ruflo-mods@ruflo'], opts(fs)).resolved).toEqual([{ name: 'ruflo-mods', path: join(CLONE, 'plugins', 'ruflo-mods'), source: 'clone' }]);+ const moved = fakeFs({ [join(CLONE, '.claude-plugin', 'marketplace.json')]: { plugins: [{ name: 'ruflo-mods', source: './x/mods' }] }, [manifestIn(join(CLONE, 'x', 'mods'))]: '{}' }, [CLONE]);+ expect(resolvePluginPaths(['ruflo-mods'], opts(moved)).resolved[0]!.path).toBe(join(CLONE, 'x', 'mods'));+ });++ it('then the install cache: installed_plugins.json path first, else the highest version folder', () => {+ const scan = fakeFs({ [manifestIn(cacheDir(CFG, '0.9.0'))]: '{}', [manifestIn(cacheDir(CFG, '0.10.0'))]: '{}', [join(cacheDir(CFG, '0.11.0'), 'README.md')]: '' });+ expect(resolvePluginPaths(['ruflo-mods'], opts(scan)).resolved[0]).toEqual({ name: 'ruflo-mods', path: cacheDir(CFG, '0.10.0'), source: 'cache' });+ const recorded = fakeFs({+ [join(CFG, 'plugins', 'installed_plugins.json')]: { plugins: { 'ruflo-mods@ruflo': [{ scope: 'user', installPath: cacheDir(CFG, '0.9.0') }] } },+ [manifestIn(cacheDir(CFG, '0.9.0'))]: '{}',+ [manifestIn(cacheDir(CFG, '0.10.0'))]: '{}',+ });+ expect(resolvePluginPaths(['ruflo-mods'], opts(recorded)).resolved[0]!.path).toBe(cacheDir(CFG, '0.9.0'));+ });++ it('a folder without .claude-plugin/plugin.json is reported missing, never returned', () => {+ const fs = fakeFs({ ...knownLocal, [join(CHECKOUT, 'plugins', 'ruflo-mods', 'README.md')]: '', [join(CLONE, 'plugins', 'ruflo-mods', 'hooks', 'index.ts')]: '' }, [CHECKOUT]);+ const r = resolvePluginPaths(['ruflo-mods'], opts(fs));+ expect(r.resolved).toEqual([]);+ expect(r.missing).toHaveLength(1);+ expect(r.missing[0]!.name).toBe('ruflo-mods');+ expect(r.missing[0]!.reason).toContain('.claude-plugin');+ });++ it('honours CLAUDE_CONFIG_DIR instead of ~/.claude', () => {+ const alt = '/alt/cfg';+ const fs = fakeFs({ [manifestIn(cacheDir(alt, '1.0.0'))]: '{}', [manifestIn(cacheDir(CFG, '2.0.0'))]: '{}' });+ expect(resolvePluginPaths(['ruflo-mods'], opts(fs, { CLAUDE_CONFIG_DIR: alt })).resolved[0]!.path).toBe(cacheDir(alt, '1.0.0'));+ expect(resolvePluginPaths(['ruflo-mods'], opts(fs)).resolved[0]!.path).toBe(cacheDir(CFG, '2.0.0'));+ });+});++describe('ADR-510 withHeadlessPlugins', () => {+ const MODS = join(CLONE, 'plugins', 'ruflo-mods');+ const found = () => ({ resolved: [{ name: 'ruflo-mods', path: MODS, source: 'clone' as const }], missing: [] });+ const none = () => ({ resolved: [], missing: [{ name: 'ruflo-mods', reason: 'no manifest' }] });+ let lines: string[];+ beforeEach(() => {+ lines = [];+ resetHeadlessPluginWarnings();+ });+ const warn = (l: string) => lines.push(l);++ it('adds --plugin-dir and turns function hooks on', () => {+ const r = withHeadlessPlugins(['-p', '--output-format', 'json'], { PATH: '/bin' }, { resolver: found, warn });+ expect(r.argv).toEqual(['-p', '--output-format', 'json', '--plugin-dir', MODS]);+ expect(r.env).toEqual({ PATH: '/bin', CLAUDE_CODE_ENABLE_FUNCTION_HOOKS: '1' });+ expect(r.added).toEqual(['ruflo-mods']);+ expect(lines).toEqual([]);+ });++ it("keeps a caller's own CLAUDE_CODE_ENABLE_FUNCTION_HOOKS value", () => {+ const r = withHeadlessPlugins(['-p'], { CLAUDE_CODE_ENABLE_FUNCTION_HOOKS: '0' }, { resolver: found, warn });+ expect(r.env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS).toBe('0');+ });++ it("does not duplicate a caller's own --plugin-dir (same folder, = form, or its own copy)", () => {+ for (const own of [['--plugin-dir', MODS], [`--plugin-dir=${MODS}`], ['--plugin-dir', '/elsewhere/ruflo-mods']]) {+ const r = withHeadlessPlugins(['-p', ...own], {}, { resolver: found, warn });+ expect(existingPluginDirs(r.argv)).toHaveLength(1);+ expect(r.added).toEqual([]);+ expect(r.env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS).toBe('1');+ }+ });++ it('a missing plugin: the worker still starts, the miss is logged once and reported', () => {+ const a = withHeadlessPlugins(['-p'], {}, { resolver: none, warn });+ const b = withHeadlessPlugins(['-p'], {}, { resolver: none, warn });+ expect(a.argv).toEqual(['-p']);+ expect(a.missing).toEqual(['ruflo-mods']);+ expect(b.missing).toEqual(['ruflo-mods']);+ expect(lines).toEqual(['plugin ruflo-mods not found; worker runs without it']);+ expect(a.env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS).toBeUndefined();+ });++ it('RUFLO_HEADLESS_PLUGINS picks the profile; none turns staging off', () => {+ expect(workerProfile({})).toEqual(['ruflo-mods']);+ expect(workerProfile({ RUFLO_HEADLESS_PLUGINS: 'ruflo-mods, ruflo-swarm' })).toEqual(['ruflo-mods', 'ruflo-swarm']);+ expect(workerProfile({ RUFLO_HEADLESS_PLUGINS: 'none' })).toEqual([]);+ const r = withHeadlessPlugins(['-p'], { RUFLO_HEADLESS_PLUGINS: 'none' }, { resolver: found, warn });+ expect(r.argv).toEqual(['-p']);+ });+});++describe('ADR-510 doctor --component headless-plugins', () => {+ const MODS = '/plugins/ruflo-mods';+ const resolved = () => ({ resolved: [{ name: 'ruflo-mods', path: MODS, source: 'clone' as const }], missing: [] });+ const init = (extra: Record<string, unknown> = {}) =>+ `${JSON.stringify({ type: 'system', subtype: 'hook_started' })}\n${JSON.stringify({ type: 'system', subtype: 'init', plugins: [{ name: 'ruflo-mods', path: MODS, source: 'ruflo-mods@inline' }], ...extra })}\n${JSON.stringify({ type: 'result', subtype: 'success', result: 'ok' })}\n`;+ let seen: { argv: string[]; env: NodeJS.ProcessEnv; cwd: string } | null;+ const runner = (stdout: string, writeHeartbeat: boolean): HeadlessRunner => async (argv, env, cwd) => {+ seen = { argv, env, cwd };+ if (writeHeartbeat) beat.add(join(cwd, HEARTBEAT));+ return { exitCode: 0, stdout, stderr: '' };+ };+ const beat = new Set<string>();+ const exists = (p: string) => beat.has(p);+ afterEach(() => {+ beat.clear();+ seen = null;+ });++ it('pass: init lists ruflo-mods, no plugin_errors, heartbeat written', async () => {+ const r = await checkHeadlessPlugins({ resolve: resolved, runner: runner(init(), true), exists, env: {} });+ expect(r.status).toBe('pass');+ expect(r.message).toContain('heartbeat: written');+ expect(seen!.argv).toEqual(expect.arrayContaining(['-p', '--plugin-dir', MODS, '--output-format', 'stream-json', '--verbose']));+ expect(seen!.env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS).toBe('1');+ });++ it('warn: the plugin loads but no heartbeat (hooks did not run)', async () => {+ const r = await checkHeadlessPlugins({ resolve: resolved, runner: runner(init(), false), exists, env: {} });+ expect(r.status).toBe('warn');+ expect(r.message).toContain('heartbeat: absent');+ });++ it('fail: ruflo-mods not in the init event, or plugin_errors present', async () => {+ const missingInit = `${JSON.stringify({ type: 'system', subtype: 'init', plugins: [] })}\n`;+ expect((await checkHeadlessPlugins({ resolve: resolved, runner: runner(missingInit, false), exists, env: {} })).status).toBe('fail');+ const errs = await checkHeadlessPlugins({ resolve: resolved, runner: runner(init({ plugin_errors: [{ plugin: 'ruflo-mods', error: 'bad' }] }), true), exists, env: {} });+ expect(errs.status).toBe('fail');+ expect(errs.message).toContain('bad');+ });++ it('fail: no init event at all (claude errored)', async () => {+ const r = await checkHeadlessPlugins({ resolve: resolved, runner: async () => ({ exitCode: 1, stdout: '', stderr: 'Invalid API key' }), exists, env: {} });+ expect(r.status).toBe('fail');+ expect(r.message).toContain('Invalid API key');+ });++ it('warn without spawning when ruflo-mods is not found, or no model credential exists', async () => {+ let ran = false;+ const r = await checkHeadlessPlugins({ resolve: () => ({ resolved: [], missing: [{ name: 'ruflo-mods', reason: 'nowhere' }] }), runner: async () => { ran = true; return { exitCode: 0, stdout: '', stderr: '' }; }, env: {} });+ expect(r.status).toBe('warn');+ expect(ran).toBe(false);+ const skipped = await checkHeadlessPlugins({ resolve: resolved, exists: () => false, env: {}, home: '/nohome' });+ if (process.platform !== 'darwin') {+ expect(skipped.status).toBe('warn');+ expect(skipped.message).toMatch(/^skipped: no model credential/);+ }+ });++ it('credential detection and init parsing', () => {+ expect(hasModelCredential({ ANTHROPIC_API_KEY: 'x' }, '/c', () => false)).toBe(true);+ expect(hasModelCredential({}, '/c', (p) => p === '/c/.credentials.json')).toBe(true);+ expect(findInitEvent('noise\n{"type":"system","subtype":"init","plugins":[]}\n')).toEqual({ type: 'system', subtype: 'init', plugins: [] });+ expect(findInitEvent('{"type":"result"}')).toBeNull();+ });+});diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-headless-worker-spawn.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-headless-worker-spawn.test.tsnew file mode 100644index 0000000000..78b445257c--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/mods/mods-headless-worker-spawn.test.ts@@ -0,0 +1,110 @@+/**+ * ADR-510 Β§2.2 β two of the places ruflo builds a `claude -p` command line+ * (HeadlessWorkerExecutor, `hive-mind work`; `hive-mind spawn -p` is in+ * mods-hive-mind-spawn-plugins.test.ts) pass the resolved ruflo-mods+ * folder as --plugin-dir and set CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1; a+ * missing plugin does not stop the run and is recorded on its result.+ *+ * spawn is mocked (no claude runs); the plugin is resolved from a temp+ * CLAUDE_CONFIG_DIR holding a real marketplace-clone layout.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { EventEmitter } from 'node:events';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const fake = vi.hoisted(() => ({ calls: [] as Array<{ cmd: string; argv: string[]; opts: any }> }));+vi.mock('child_process', async (orig) => {+ const actual = await orig<typeof import('child_process')>();+ return {+ ...actual,+ spawn: vi.fn((cmd: string, argv: string[], opts: any) => {+ fake.calls.push({ cmd, argv, opts });+ const child: any = new EventEmitter();+ child.pid = 4242;+ child.exitCode = null;+ child.signalCode = null;+ child.stdin = { end() { setTimeout(() => { child.exitCode = 0; child.stdout.emit('data', Buffer.from('{"result":"ok","is_error":false}')); child.emit('exit', 0); child.emit('close', 0); }, 0); } };+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ return child;+ }),+ };+});+vi.mock('../../src/runtime/claude-command.js', () => ({ resolveClaudeLaunchCommand: () => ({ command: 'claude', argsPrefix: [] }) }));++import { HeadlessWorkerExecutor } from '../../src/services/headless-worker-executor.js';+import { runWithClaude } from '../../src/commands/hive-mind-worker.js';+import { resetHeadlessPluginWarnings } from '../../src/mods/headless-plugins.js';++let cfg: string;+let project: string;+let saved: Record<string, string | undefined>;+const MODS = () => join(cfg, 'plugins', 'marketplaces', 'ruflo', 'plugins', 'ruflo-mods');++beforeEach(() => {+ fake.calls = [];+ resetHeadlessPluginWarnings();+ cfg = mkdtempSync(join(tmpdir(), 'adr510-cfg-'));+ project = mkdtempSync(join(tmpdir(), 'adr510-proj-'));+ saved = { CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR, F: process.env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS, P: process.env.RUFLO_HEADLESS_PLUGINS };+ process.env.CLAUDE_CONFIG_DIR = cfg;+ delete process.env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS;+ delete process.env.RUFLO_HEADLESS_PLUGINS;+ vi.spyOn(process.stderr, 'write').mockImplementation(() => true);+});+afterEach(() => {+ for (const [k, env] of [['CLAUDE_CONFIG_DIR', 'CLAUDE_CONFIG_DIR'], ['F', 'CLAUDE_CODE_ENABLE_FUNCTION_HOOKS'], ['P', 'RUFLO_HEADLESS_PLUGINS']] as const) {+ if (saved[k] === undefined) delete process.env[env];+ else process.env[env] = saved[k];+ }+ vi.restoreAllMocks();+ rmSync(cfg, { recursive: true, force: true });+ rmSync(project, { recursive: true, force: true });+});++function installClone() {+ mkdirSync(join(MODS(), '.claude-plugin'), { recursive: true });+ writeFileSync(join(MODS(), '.claude-plugin', 'plugin.json'), '{"name":"ruflo-mods"}');+}++const runExecutor = () =>+ (new HeadlessWorkerExecutor(project) as any).executeClaudeCode('p', { sandbox: 'strict', model: 'haiku', timeoutMs: 10_000, executionId: 'e1', workerType: 'audit' });++describe('ADR-510 HeadlessWorkerExecutor', () => {+ it('passes --plugin-dir <ruflo-mods> and CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1', async () => {+ installClone();+ const r = await runExecutor();+ expect(r.success).toBe(true);+ const call = fake.calls.find((c) => c.cmd === 'claude')!;+ expect(call.argv).toEqual(['--print', '--output-format', 'json', '--plugin-dir', MODS()]);+ expect(call.opts.env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS).toBe('1');+ expect(r.missingPlugins).toBeUndefined();+ });++ it('runs without the plugin when it is missing, and records it', async () => {+ const r = await runExecutor();+ expect(r.success).toBe(true);+ const call = fake.calls.find((c) => c.cmd === 'claude')!;+ expect(call.argv).toEqual(['--print', '--output-format', 'json']);+ expect(r.missingPlugins).toEqual(['ruflo-mods']);+ });+});++describe('ADR-510 hive-mind work (runWithClaude)', () => {+ it('passes --plugin-dir after the caller args, with function hooks on', async () => {+ installClone();+ const r = await runWithClaude('task', { mcpConfig: '/tmp/m.json', timeoutMs: 10_000, cwd: project });+ expect(r.ok).toBe(true);+ const call = fake.calls.find((c) => c.cmd === 'claude')!;+ expect(call.argv).toEqual(['-p', '--output-format', 'json', '--mcp-config=/tmp/m.json', '--plugin-dir', MODS()]);+ expect(call.opts.env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS).toBe('1');+ });++ it('reports a missing plugin on the outcome', async () => {+ const r = await runWithClaude('task', { mcpConfig: '/tmp/m.json', timeoutMs: 10_000, cwd: project });+ expect(r.missingPlugins).toEqual(['ruflo-mods']);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-hive-mind-spawn-plugins.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-hive-mind-spawn-plugins.test.tsnew file mode 100644index 0000000000..923486e814--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/mods/mods-hive-mind-spawn-plugins.test.ts@@ -0,0 +1,107 @@+/**+ * ADR-510 Β§2.2 β `hive-mind spawn --claude --non-interactive` builds a+ * `claude -p` command line, so it is a headless worker too: it gets the+ * worker profile's plugins as --plugin-dir (before the prompt) and+ * CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1. The interactive launch is unchanged.+ *+ * spawn, the MCP call and the prompt-file writes are mocked; the plugin is+ * resolved from a temp CLAUDE_CONFIG_DIR holding a marketplace-clone layout.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { EventEmitter } from 'node:events';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const fake = vi.hoisted(() => ({ calls: [] as Array<{ cmd: string; argv: string[]; opts: any }> }));+vi.mock('child_process', async (orig) => {+ const actual = await orig<typeof import('child_process')>();+ return {+ ...actual,+ spawn: vi.fn((cmd: string, argv: string[], opts: any) => {+ fake.calls.push({ cmd, argv, opts });+ const child: any = new EventEmitter();+ child.killed = false;+ child.kill = vi.fn();+ setTimeout(() => child.emit('exit', 0), 0);+ return child;+ }),+ };+});+vi.mock('fs/promises', async (orig) => ({ ...(await orig<typeof import('fs/promises')>()), mkdir: vi.fn(async () => undefined), writeFile: vi.fn(async () => undefined) }));+vi.mock('../../src/runtime/claude-command.js', () => ({ resolveClaudeLaunchCommand: () => ({ command: 'claude', argsPrefix: [] }) }));+vi.mock('../../src/mcp-client.js', () => ({+ MCPClientError: class extends Error {},+ callMCPTool: vi.fn(async (name: string) =>+ name === 'hive-mind_spawn'+ ? { success: true, spawned: 1, workers: [{ agentId: 'w1', role: 'worker', joinedAt: new Date(0).toISOString() }], totalWorkers: 1, hiveStatus: 'active', hiveId: 'h1', message: 'ok' }+ : { hiveId: 'h1' }),+}));++import { hiveMindCommand } from '../../src/commands/hive-mind.js';+import { resetHeadlessPluginWarnings } from '../../src/mods/headless-plugins.js';++let cfg: string;+let saved: Record<string, string | undefined>;+const ENVS = ['CLAUDE_CONFIG_DIR', 'CLAUDE_CODE_ENABLE_FUNCTION_HOOKS', 'RUFLO_HEADLESS_PLUGINS'] as const;+const MODS = () => join(cfg, 'plugins', 'marketplaces', 'ruflo', 'plugins', 'ruflo-mods');+const spawnCmd = hiveMindCommand.subcommands!.find((c) => c.name === 'spawn')!;+const run = (flags: Record<string, unknown>) =>+ spawnCmd.action!({ args: [], flags: { claude: true, objective: 'do x', mcpConfig: '/tmp/m.json', ...flags }, interactive: false, cwd: cfg } as any);++beforeEach(() => {+ fake.calls = [];+ resetHeadlessPluginWarnings();+ cfg = mkdtempSync(join(tmpdir(), 'adr510-hive-'));+ saved = Object.fromEntries(ENVS.map((k) => [k, process.env[k]]));+ process.env.CLAUDE_CONFIG_DIR = cfg;+ delete process.env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS;+ delete process.env.RUFLO_HEADLESS_PLUGINS;+ vi.spyOn(process.stderr, 'write').mockImplementation(() => true);+ vi.spyOn(process.stdout, 'write').mockImplementation(() => true);+ vi.spyOn(console, 'log').mockImplementation(() => undefined);+});+afterEach(() => {+ for (const k of ENVS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ vi.restoreAllMocks();+ rmSync(cfg, { recursive: true, force: true });+});++function installClone() {+ mkdirSync(join(MODS(), '.claude-plugin'), { recursive: true });+ writeFileSync(join(MODS(), '.claude-plugin', 'plugin.json'), '{"name":"ruflo-mods"}');+}++describe('ADR-510 hive-mind spawn --claude --non-interactive', () => {+ it('passes --plugin-dir <ruflo-mods> before the prompt, with function hooks on', async () => {+ installClone();+ const r = await run({ nonInteractive: true });+ expect(r.success).toBe(true);+ const call = fake.calls.find((c) => c.cmd === 'claude')!;+ const i = call.argv.indexOf('--plugin-dir');+ expect(i).toBeGreaterThan(call.argv.indexOf('-p'));+ expect(call.argv[i + 1]).toBe(MODS());+ expect(i + 2).toBe(call.argv.length - 1); // the prompt stays the last argument+ expect(call.opts.env.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS).toBe('1');+ expect((r.data as any).claude.missingPlugins).toBeUndefined();+ });++ it('runs without the plugin when it is missing, and records it on the result', async () => {+ const r = await run({ nonInteractive: true });+ expect(r.success).toBe(true);+ const call = fake.calls.find((c) => c.cmd === 'claude')!;+ expect(call.argv).not.toContain('--plugin-dir');+ expect((r.data as any).claude.missingPlugins).toEqual(['ruflo-mods']);+ });++ it('the interactive launch is unchanged: no --plugin-dir, env inherited', async () => {+ installClone();+ await run({});+ const call = fake.calls.find((c) => c.cmd === 'claude')!;+ expect(call.argv).not.toContain('--plugin-dir');+ expect(call.opts.env).toBeUndefined();+ });+});diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.tsindex a2ef3ac149..fffa259b97 100644--- a/v3/@claude-flow/cli/src/commands/doctor.ts+++ b/v3/@claude-flow/cli/src/commands/doctor.ts@@ -2389,6 +2389,13 @@ async function checkMods(): Promise<HealthCheck> {: { name: 'ruflo mods (ADR-404)', status: 'warn', message: warnings.map((f) => `${f.name}: ${f.message}`).join('; '), fix: 'ruflo mods doctor' };}+// ADR-510: do ruflo mods run under `claude -p --plugin-dir` here? Spawns a+// real (cheap) model call, so `--component headless-plugins` only.+async function checkHeadlessPlugins(): Promise<HealthCheck> {+ const { checkHeadlessPlugins: run } = await import('../mods/headless-check.js');+ return run();+}+// #4581 / ADR-502: ruflo-mods learning loop β is it recording, and do its verified outcomes reach SONA? Warn-only.async function checkLearningLoop(): Promise<HealthCheck> {const { learningLoopHealth } = await import('../memory/verified-outcomes.js');@@ -2610,7 +2617,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, mods, 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, mods, headless-plugins, metaharness)',type: 'string'},{@@ -2721,6 +2728,7 @@ export const doctorCommand: Command = {'typesafe': checkTypesafeRouter, // opt-in @ruvector/typesafe task router'mods': checkMods, // ADR-404 β ruflo as a Claude Code mod'learning-loop': checkLearningLoop, // #4581 β verified-outcome learning loop+ 'headless-plugins': checkHeadlessPlugins, // ADR-510 β mods under claude -p (spawns claude; not in bare doctor)};if (component !== undefined && !Object.hasOwn(componentMap, component)) {@@ -2881,7 +2889,7 @@ export const doctorCommand: Command = {[checkProxyBinary, 'proxy-binary'], [checkProxyProcess, 'proxy-process'],[checkProxyBindAddress, 'proxy-bind'], [checkAuth, 'auth'],[checkTypesafeRouter, 'typesafe'], [checkMods, 'mods'],- [checkLearningLoop, 'learning-loop'],+ [checkLearningLoop, 'learning-loop'], [checkHeadlessPlugins, 'headless-plugins'],]);nativeAgentDbChecks.forEach((check, index) => {// The path distinguishes simultaneous authority files; normalize separators.diff --git a/v3/@claude-flow/cli/src/commands/hive-mind-worker.ts b/v3/@claude-flow/cli/src/commands/hive-mind-worker.tsindex 711766bbd4..1f74d28746 100644--- a/v3/@claude-flow/cli/src/commands/hive-mind-worker.ts+++ b/v3/@claude-flow/cli/src/commands/hive-mind-worker.ts@@ -16,6 +16,7 @@ import { spawn as childSpawn } from 'child_process';import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';import { join } from 'path';import { resolveClaudeLaunchCommand } from '../runtime/claude-command.js';+import { withHeadlessPlugins } from '../mods/headless-plugins.js';type ServerMap = Record<string, unknown>;@@ -110,6 +111,8 @@ export interface RunOutcome {sessionId?: string;costUsd?: number;durationMs: number;+ /** ADR-510 β plugins in the worker profile that could not be found; the run went ahead without them. */+ missingPlugins?: string[];}export type TaskRunner = (prompt: string, opts: { mcpConfig: string; timeoutMs: number; cwd: string }) => Promise<RunOutcome>;@@ -125,11 +128,14 @@ export const runWithClaude: TaskRunner = (prompt, opts) =>}// The prompt goes on stdin, not argv: a task description has no length// bound and `--mcp-config` is variadic (#1780).- const child = childSpawn(- launch.command,+ // ADR-510: pass the worker profile's plugins (default ruflo-mods) as --plugin-dir.+ const staged = withHeadlessPlugins([...launch.argsPrefix, '-p', '--output-format', 'json', `--mcp-config=${opts.mcpConfig}`],- { cwd: opts.cwd, stdio: ['pipe', 'pipe', 'pipe'] },+ { ...process.env },+ { projectRoot: opts.cwd },);+ const missing = staged.missing.length > 0 ? { missingPlugins: staged.missing } : {};+ const child = childSpawn(launch.command, staged.argv, { cwd: opts.cwd, env: staged.env, stdio: ['pipe', 'pipe', 'pipe'] });let stdout = '';let stderr = '';child.stdout.on('data', (d) => (stdout += d));@@ -137,7 +143,7 @@ export const runWithClaude: TaskRunner = (prompt, opts) =>const timer = setTimeout(() => child.kill('SIGTERM'), opts.timeoutMs);child.on('error', (e) => {clearTimeout(timer);- resolve({ ok: false, output: e.message, exitCode: null, durationMs: Date.now() - started });+ resolve({ ok: false, output: e.message, exitCode: null, durationMs: Date.now() - started, ...missing });});child.on('close', (code, signal) => {clearTimeout(timer);@@ -151,10 +157,11 @@ export const runWithClaude: TaskRunner = (prompt, opts) =>sessionId: r.session_id,costUsd: r.total_cost_usd,durationMs,+ ...missing,});} catch {const why = signal === 'SIGTERM' ? `timed out after ${opts.timeoutMs}ms` : (stderr || stdout).trim().slice(-2000);- resolve({ ok: false, output: why, exitCode: code, durationMs });+ resolve({ ok: false, output: why, exitCode: code, durationMs, ...missing });}});child.stdin.end(prompt);@@ -228,6 +235,7 @@ export async function workOnce(opts: WorkOnceOptions): Promise<WorkOnceResult> {durationMs: outcome.durationMs,...(outcome.sessionId ? { sessionId: outcome.sessionId } : {}),...(outcome.costUsd !== undefined ? { costUsd: outcome.costUsd } : {}),+ ...(outcome.missingPlugins?.length ? { missingPlugins: outcome.missingPlugins } : {}),};if (outcome.ok) {await callMCPTool('task_complete', { taskId, result });diff --git a/v3/@claude-flow/cli/src/commands/hive-mind.ts b/v3/@claude-flow/cli/src/commands/hive-mind.tsindex a9e0bce41e..34c2969da1 100644--- a/v3/@claude-flow/cli/src/commands/hive-mind.ts+++ b/v3/@claude-flow/cli/src/commands/hive-mind.ts@@ -15,6 +15,7 @@ import { mkdir, writeFile } from 'fs/promises';import { resolveWorkerMcpConfig, currentRufloServer, workCommand } from './hive-mind-worker.js';import { join } from 'path';import { resolveClaudeLaunchCommand } from '../runtime/claude-command.js';+import { withHeadlessPlugins } from '../mods/headless-plugins.js';import { getHiveTokenForCli } from '../mcp-tools/hive-mind-tools.js';// Worker type definitions for prompt generation@@ -189,7 +190,7 @@ async function spawnClaudeCodeInstance(objective: string,workers: HiveWorker[],flags: Record<string, unknown>-): Promise<{ success: boolean; promptFile?: string; error?: string }> {+): Promise<{ success: boolean; promptFile?: string; error?: string; missingPlugins?: string[] }> {output.writeln();output.writeln(output.bold('π Launching Claude Code with Hive Mind Coordination'));output.writeln(output.dim('β'.repeat(60)));@@ -302,6 +303,19 @@ async function spawnClaudeCodeInstance(}}+ // ADR-510 Β§2.2: a non-interactive (-p) run is a headless worker and loads+ // no marketplace plugins on a fresh config, so stage the worker profile+ // (default ruflo-mods) as --plugin-dir before the prompt. The interactive+ // path keeps loading plugins the normal, trusted way.+ let spawnEnv: NodeJS.ProcessEnv | undefined;+ let missingPlugins: string[] = [];+ if (isNonInteractive) {+ const staged = withHeadlessPlugins(claudeArgs, { ...process.env }, { projectRoot: process.cwd() });+ claudeArgs.splice(0, claudeArgs.length, ...staged.argv);+ spawnEnv = staged.env;+ missingPlugins = staged.missing;+ }+// Add the prompt as the LAST argumentclaudeArgs.push(hiveMindPrompt);@@ -316,6 +330,7 @@ async function spawnClaudeCodeInstance(], {stdio: 'inherit',shell: false,+ ...(spawnEnv ? { env: spawnEnv } : {}),});// Set up SIGINT handler for session management@@ -377,7 +392,7 @@ async function spawnClaudeCodeInstance(claudeProcess.on('error', () => resolve(1));});- return { success: claudeExitCode === 0, promptFile };+ return { success: claudeExitCode === 0, promptFile, ...(missingPlugins.length > 0 ? { missingPlugins } : {}) };} else if (dryRun) {output.writeln();output.printInfo('Dry run - would execute Claude Code with prompt:');diff --git a/v3/@claude-flow/cli/src/commands/plugins-paths.ts b/v3/@claude-flow/cli/src/commands/plugins-paths.tsnew file mode 100644index 0000000000..eb42b49f3d--- /dev/null+++ b/v3/@claude-flow/cli/src/commands/plugins-paths.ts@@ -0,0 +1,54 @@+/**+ * ADR-510 Β§2.3 β `ruflo plugins paths [--json] [--names a,b]`.+ *+ * Prints the folder each ruflo plugin resolves to (the same resolver headless+ * workers use for `--plugin-dir`), so an Agent SDK caller can build+ * `plugins: [{ type: "local", path }]`, and lists plugins that could not be+ * found. Read-only.+ */++import type { Command, CommandContext, CommandResult } from '../types.js';+import { output } from '../output.js';+import { MOD_PLUGIN_IDS } from '../mods/install.js';+import { resolvePluginPaths } from '../mods/plugin-paths.js';++/** Default list: every plugin `ruflo mods install` enables. */+export const DEFAULT_PATH_PLUGINS: readonly string[] = MOD_PLUGIN_IDS.map((id) => id.split('@')[0]!);++const PLUGIN_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/i;++export const pathsCommand: Command = {+ name: 'paths',+ description: 'Print the local folder of each ruflo plugin (for claude -p --plugin-dir or Agent SDK plugins)',+ options: [+ { name: 'names', short: 'n', type: 'string', description: `Comma list of plugin names (default: ${DEFAULT_PATH_PLUGINS.join(',')})` },+ { name: 'json', type: 'boolean', description: 'Print { resolved, missing } as JSON', default: false },+ ],+ examples: [+ { command: 'ruflo plugins paths', description: 'Where ruflo-mods, ruflo-swarm and ruflo-console live on this machine' },+ { command: 'ruflo plugins paths --names ruflo-mods --json', description: 'JSON for an Agent SDK plugins array' },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const raw = ctx.flags.names as string | undefined;+ const names = raw ? raw.split(',').map((s) => s.trim()).filter(Boolean) : [...DEFAULT_PATH_PLUGINS];+ const bad = names.filter((n) => !PLUGIN_NAME.test(n.split('@')[0]!));+ if (bad.length > 0) {+ const message = `invalid plugin name: ${bad.map((b) => JSON.stringify(b)).join(', ')}`;+ if (ctx.flags.json) output.writeln(JSON.stringify({ resolved: [], missing: [], error: message }));+ else output.printError(message);+ return { success: false, exitCode: 1, message };+ }+ const result = resolvePluginPaths(names, { projectRoot: ctx.cwd || process.cwd() });+ if (ctx.flags.json) {+ output.writeln(JSON.stringify(result, null, 2));+ } else {+ for (const p of result.resolved) output.writeln(`${p.name}\t${p.path}\t(${p.source})`);+ for (const m of result.missing) output.writeln(output.dim(`${m.name}\tmissing: ${m.reason}`));+ if (result.resolved.length > 0) {+ output.writeln(output.dim('Agent SDK: plugins: [{ type: "local", path }] β check the init message\'s plugin_errors'));+ }+ }+ // Missing plugins are reported, not an error: a worker still runs without them.+ return { success: true, exitCode: 0, data: result };+ },+};diff --git a/v3/@claude-flow/cli/src/commands/plugins.ts b/v3/@claude-flow/cli/src/commands/plugins.tsindex 0212e55683..aa6bf440a3 100644--- a/v3/@claude-flow/cli/src/commands/plugins.ts+++ b/v3/@claude-flow/cli/src/commands/plugins.ts@@ -22,6 +22,7 @@ import {import { getPluginManager, type InstalledPlugin } from '../plugins/manager.js';import { DEFAULT_PLUGIN_PERMISSIONS, isStrictPluginMode } from '../plugins/trust-policy.js';import { getBulkRatings } from '../services/registry-api.js';+import { pathsCommand } from './plugins-paths.js';// List subcommand - Now uses IPFS-based registryconst listCommand: Command = {@@ -1037,7 +1038,7 @@ const rateCommand: Command = {export const pluginsCommand: Command = {name: 'plugins',description: 'Plugin management with IPFS-based decentralized registry',- subcommands: [listCommand, searchCommand, installCommand, uninstallCommand, upgradeCommand, toggleCommand, infoCommand, createCommand, rateCommand],+ subcommands: [listCommand, searchCommand, installCommand, uninstallCommand, upgradeCommand, toggleCommand, infoCommand, createCommand, rateCommand, pathsCommand],examples: [{ command: 'claude-flow plugins list', description: 'List plugins from IPFS registry' },{ command: 'claude-flow plugins search -q neural', description: 'Search for plugins' },@@ -1058,6 +1059,7 @@ export const pluginsCommand: Command = {`${output.highlight('upgrade')} - Upgrade an installed plugin`,`${output.highlight('toggle')} - Enable or disable a plugin`,`${output.highlight('info')} - Show detailed plugin information`,+ `${output.highlight('paths')} - Local folders of ruflo plugins (claude -p --plugin-dir, Agent SDK)`,`${output.highlight('create')} - Scaffold a new plugin project`,]);output.writeln();diff --git a/v3/@claude-flow/cli/src/mods/headless-check.ts b/v3/@claude-flow/cli/src/mods/headless-check.tsnew file mode 100644index 0000000000..9cbd61dcdf--- /dev/null+++ b/v3/@claude-flow/cli/src/mods/headless-check.ts@@ -0,0 +1,165 @@+/**+ * ADR-510 Β§2.4 β `ruflo doctor --component headless-plugins`: do ruflo mods+ * actually run under `claude -p` on this machine?+ *+ * Runs `claude -p --plugin-dir <ruflo-mods> --output-format stream-json+ * --verbose "reply ok"` in a throwaway project that has a `.claude-flow/`+ * directory, then reports:+ * - whether the init event lists ruflo-mods from that folder;+ * - whether `plugin_errors` is empty (Claude Code omits the key when none);+ * - whether the mod's session heartbeat (`.claude-flow/mods/session.json`)+ * was written β the proof that its function hooks ran.+ *+ * The runner is injectable so tests never spawn `claude` or need a key.+ * Without any model credential the check is skipped (warn), never spawned.+ */++import { spawn } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';+import { homedir, tmpdir } from 'node:os';+import { join, resolve } from 'node:path';++import { ENABLE_ENV } from './install.js';+import { claudeConfigDir } from './plugin-resolve.js';+import { resolvePluginPaths, type PluginPaths } from './plugin-paths.js';++export const HEADLESS_TIMEOUT_MS = 60_000;+export const HEARTBEAT = join('.claude-flow', 'mods', 'session.json');+const PLUGIN = 'ruflo-mods';++export interface HeadlessRun {+ exitCode: number | null;+ stdout: string;+ stderr: string;+ timedOut?: boolean;+}++export type HeadlessRunner = (argv: string[], env: NodeJS.ProcessEnv, cwd: string, timeoutMs: number) => Promise<HeadlessRun>;++export interface HeadlessCheck {+ name: string;+ status: 'pass' | 'warn' | 'fail';+ message: string;+ fix?: string;+}++export interface HeadlessCheckDeps {+ runner?: HeadlessRunner;+ resolve?: () => PluginPaths;+ env?: NodeJS.ProcessEnv;+ home?: string;+ /** Throwaway project dir factory (must be removable afterwards). */+ makeProject?: () => string;+ exists?: (path: string) => boolean;+ timeoutMs?: number;+ model?: string;+}++const NAME = 'Headless plugins (ADR-510)';++export const spawnHeadless: HeadlessRunner = (argv, env, cwd, timeoutMs) =>+ new Promise((done) => {+ let stdout = '';+ let stderr = '';+ let timedOut = false;+ let child;+ try {+ child = spawn('claude', argv, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });+ } catch (e) {+ done({ exitCode: null, stdout: '', stderr: e instanceof Error ? e.message : String(e) });+ return;+ }+ const timer = setTimeout(() => {+ timedOut = true;+ try { child.kill('SIGTERM'); } catch { /* already gone */ }+ }, timeoutMs);+ child.stdout?.on('data', (d: Buffer) => { stdout += d.toString(); });+ child.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });+ child.on('error', (e: Error) => { clearTimeout(timer); done({ exitCode: null, stdout, stderr: e.message, timedOut }); });+ child.on('close', (code: number | null) => { clearTimeout(timer); done({ exitCode: code, stdout, stderr, timedOut }); });+ });++/** A model credential Claude Code could use; without one the check would only fail on auth. */+export function hasModelCredential(env: NodeJS.ProcessEnv, configDir: string, exists: (p: string) => boolean = existsSync): boolean {+ const keys = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX'];+ if (keys.some((k) => !!env[k])) return true;+ // macOS keeps the login in the keychain, which we cannot see from here.+ if (process.platform === 'darwin') return true;+ return exists(join(configDir, '.credentials.json'));+}++interface InitEvent {+ plugins?: Array<{ name?: string; path?: string; source?: string }>;+ plugin_errors?: unknown[];+}++/** The `system/init` event of a stream-json run, if any. */+export function findInitEvent(stdout: string): InitEvent | null {+ for (const line of stdout.split('\n')) {+ const t = line.trim();+ if (!t.startsWith('{')) continue;+ try {+ const ev = JSON.parse(t) as { type?: string; subtype?: string };+ if (ev.type === 'system' && ev.subtype === 'init') return ev as InitEvent;+ } catch {+ // not a JSON line+ }+ }+ return null;+}++const canonical = (p: string) => {+ try {+ return realpathSync(p);+ } catch {+ return resolve(p);+ }+};++export async function checkHeadlessPlugins(deps: HeadlessCheckDeps = {}): Promise<HeadlessCheck> {+ const env = deps.env ?? process.env;+ const exists = deps.exists ?? existsSync;+ const paths = (deps.resolve ?? (() => resolvePluginPaths([PLUGIN], { env, home: deps.home })))();+ const mods = paths.resolved.find((p) => p.name === PLUGIN);+ if (!mods) {+ const why = paths.missing.find((m) => m.name === PLUGIN)?.reason ?? 'not found';+ return { name: NAME, status: 'warn', message: `${PLUGIN} not found (${why}); headless workers run without it`, fix: 'ruflo mods install' };+ }+ const configDir = claudeConfigDir(env, deps.home ?? homedir());+ if (!deps.runner && !hasModelCredential(env, configDir, exists)) {+ return { name: NAME, status: 'warn', message: `skipped: no model credential for claude -p (${PLUGIN} resolves to ${mods.path})`, fix: 'set ANTHROPIC_API_KEY or run `claude login`, then re-run' };+ }++ const project = (deps.makeProject ?? (() => mkdtempSync(join(tmpdir(), 'ruflo-headless-'))))();+ try {+ mkdirSync(join(project, '.claude-flow'), { recursive: true });+ const argv = ['-p', 'reply ok', '--plugin-dir', mods.path, '--output-format', 'stream-json', '--verbose', '--model', deps.model ?? 'haiku'];+ const runEnv: NodeJS.ProcessEnv = { ...env, CLAUDE_ENTRYPOINT: 'worker' };+ if (runEnv[ENABLE_ENV] === undefined) runEnv[ENABLE_ENV] = '1';+ delete runEnv.CLAUDE_SESSION_ID;+ delete runEnv.CLAUDE_PARENT_SESSION_ID;+ const run = await (deps.runner ?? spawnHeadless)(argv, runEnv, project, deps.timeoutMs ?? HEADLESS_TIMEOUT_MS);+ if (run.timedOut) {+ return { name: NAME, status: 'fail', message: `claude -p did not finish in ${(deps.timeoutMs ?? HEADLESS_TIMEOUT_MS) / 1000}s` };+ }+ const init = findInitEvent(run.stdout);+ if (!init) {+ const tail = (run.stderr || run.stdout).trim().split('\n').slice(-1)[0] ?? '';+ return { name: NAME, status: 'fail', message: `no init event from claude -p (exit ${run.exitCode})${tail ? `: ${tail.slice(0, 200)}` : ''}`, fix: 'ruflo doctor -c claude' };+ }+ const want = canonical(mods.path);+ const listed = (init.plugins ?? []).some((p) => p.name === PLUGIN && typeof p.path === 'string' && canonical(p.path) === want);+ const errors = Array.isArray(init.plugin_errors) ? init.plugin_errors : [];+ const heartbeat = exists(join(project, HEARTBEAT));+ const facts = `init lists ${PLUGIN}: ${listed ? 'yes' : 'no'}; plugin_errors: ${errors.length === 0 ? 'none' : JSON.stringify(errors).slice(0, 200)}; heartbeat: ${heartbeat ? 'written' : 'absent'}`;+ if (!listed || errors.length > 0) {+ return { name: NAME, status: 'fail', message: `${facts} (${mods.path})`, fix: `claude -p --plugin-dir ${JSON.stringify(mods.path)} --output-format stream-json --verbose "reply ok"` };+ }+ if (!heartbeat) {+ return { name: NAME, status: 'warn', message: `${facts}: the plugin loads but its function hooks did not run (Claude Code too old, or ${ENABLE_ENV}=0)` };+ }+ return { name: NAME, status: 'pass', message: `${facts} (${mods.source}: ${mods.path})` };+ } finally {+ try { rmSync(project, { recursive: true, force: true }); } catch { /* best effort */ }+ }+}diff --git a/v3/@claude-flow/cli/src/mods/headless-plugins.ts b/v3/@claude-flow/cli/src/mods/headless-plugins.tsnew file mode 100644index 0000000000..cb9fe52596--- /dev/null+++ b/v3/@claude-flow/cli/src/mods/headless-plugins.ts@@ -0,0 +1,117 @@+/**+ * ADR-510 Β§2.2 β give a headless `claude -p` worker its ruflo plugins.+ *+ * Every place ruflo builds a `claude -p` command line passes its argv and env+ * through `withHeadlessPlugins`. It appends `--plugin-dir <path>` per plugin+ * in the worker profile (default: ruflo-mods) and sets+ * `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1` unless the caller set it (a caller's+ * `0` stays `0`). A caller's own `--plugin-dir` for the same plugin is never+ * duplicated.+ *+ * A plugin that cannot be resolved does not stop the worker: it is logged once+ * per process ("plugin <name> not found; worker runs without it") and returned+ * in `missing` for the worker's status.+ *+ * Profile override: `RUFLO_HEADLESS_PLUGINS` is a comma list of plugin names;+ * `none` (or an empty value) turns plugin loading off.+ */++import { realpathSync } from 'node:fs';+import { basename, resolve } from 'node:path';++import { ENABLE_ENV } from './install.js';+import { resolvePluginPaths, type ResolveOptions, type PluginPaths } from './plugin-paths.js';++export const DEFAULT_WORKER_PLUGINS: readonly string[] = ['ruflo-mods'];+export const PROFILE_ENV = 'RUFLO_HEADLESS_PLUGINS';++export interface HeadlessPluginOptions extends ResolveOptions {+ /** Plugin names to load; defaults to the env profile, else DEFAULT_WORKER_PLUGINS. */+ profile?: readonly string[];+ /** Where the once-per-process warning goes (default: stderr). */+ warn?: (line: string) => void;+ /** Injectable resolver, for tests. */+ resolver?: (names: readonly string[], opts: ResolveOptions) => PluginPaths;+}++export interface HeadlessPluginResult<E> {+ argv: string[];+ env: E;+ /** Plugins loaded via --plugin-dir by this call (not the caller's own). */+ added: string[];+ /** Plugins in the profile that could not be resolved. */+ missing: string[];+}++const warned = new Set<string>();++/** For tests: forget which missing plugins were already logged. */+export function resetHeadlessPluginWarnings(): void {+ warned.clear();+}++/** The worker profile: explicit, else RUFLO_HEADLESS_PLUGINS, else ruflo-mods. */+export function workerProfile(env: NodeJS.ProcessEnv = process.env, explicit?: readonly string[]): string[] {+ if (explicit) return [...explicit];+ const raw = env[PROFILE_ENV];+ if (raw === undefined) return [...DEFAULT_WORKER_PLUGINS];+ const names = raw.split(',').map((s) => s.trim()).filter(Boolean);+ return names.length === 1 && names[0]!.toLowerCase() === 'none' ? [] : names;+}++function canonical(p: string): string {+ try {+ return realpathSync(p);+ } catch {+ return resolve(p);+ }+}++/** Every `--plugin-dir` value already in argv (both `--plugin-dir x` and `--plugin-dir=x`). */+export function existingPluginDirs(argv: readonly string[]): string[] {+ const dirs: string[] = [];+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i]!;+ if (a === '--plugin-dir' && i + 1 < argv.length) dirs.push(argv[++i]!);+ else if (a.startsWith('--plugin-dir=')) dirs.push(a.slice('--plugin-dir='.length));+ }+ return dirs;+}++export function withHeadlessPlugins<E extends Record<string, string | undefined>>(+ argv: readonly string[],+ env: E,+ opts: HeadlessPluginOptions = {},+): HeadlessPluginResult<E> {+ const profile = workerProfile(opts.env ?? (env as NodeJS.ProcessEnv), opts.profile);+ const outArgv = [...argv];+ const outEnv = { ...env } as E;+ if (profile.length === 0) return { argv: outArgv, env: outEnv, added: [], missing: [] };++ const resolver = opts.resolver ?? resolvePluginPaths;+ const { resolved, missing } = resolver(profile, { ...opts, env: opts.env ?? (env as NodeJS.ProcessEnv) });+ const own = existingPluginDirs(argv);+ const ownPaths = new Set(own.map(canonical));+ const ownNames = new Set(own.map((d) => basename(resolve(d))));+ const added: string[] = [];+ for (const plugin of resolved) {+ // The caller already passes this plugin (same folder, or its own copy of it).+ if (ownPaths.has(canonical(plugin.path)) || ownNames.has(plugin.name)) continue;+ outArgv.push('--plugin-dir', plugin.path);+ added.push(plugin.name);+ }+ // A caller-supplied copy of a "missing" plugin is not missing.+ const stillMissing = missing.filter((m) => !ownNames.has(m.name)).map((m) => m.name);++ if ((added.length > 0 || own.length > 0) && outEnv[ENABLE_ENV] === undefined) {+ (outEnv as Record<string, string | undefined>)[ENABLE_ENV] = '1';+ }++ const warn = opts.warn ?? ((line: string) => process.stderr.write(`${line}\n`));+ for (const name of stillMissing) {+ if (warned.has(name)) continue;+ warned.add(name);+ warn(`plugin ${name} not found; worker runs without it`);+ }+ return { argv: outArgv, env: outEnv, added, missing: stillMissing };+}diff --git a/v3/@claude-flow/cli/src/mods/plugin-paths.ts b/v3/@claude-flow/cli/src/mods/plugin-paths.tsnew file mode 100644index 0000000000..0de4238438--- /dev/null+++ b/v3/@claude-flow/cli/src/mods/plugin-paths.ts@@ -0,0 +1,169 @@+/**+ * ADR-510 β where a ruflo plugin lives on disk, for a headless `claude -p`+ * worker (`--plugin-dir <path>`) or an Agent SDK session+ * (`plugins: [{ type: "local", path }]`).+ *+ * `claude -p` on a fresh config loads no marketplace plugins: the marketplace+ * is cloned only by an interactive, trusted start. So a worker has to be told+ * where each plugin is. Sources, in order:+ *+ * 1. a `--source local` directory marketplace (a ruflo checkout) that Claude+ * Code itself records in the user-level `known_marketplaces.json`, i.e.+ * one the user added through an interactive, trusted start;+ * 2. the marketplace clone (`<config>/plugins/marketplaces/ruflo/...`);+ * 3. the install cache (`<config>/plugins/cache/ruflo/<name>/<version>`).+ *+ * A folder without `.claude-plugin/plugin.json` is never returned: the plugin+ * is reported missing instead. Read-only; the filesystem is injectable.+ *+ * Trust: nothing inside the project decides the path. A repository's own+ * `.claude/settings.json` / `settings.local.json` (`extraKnownMarketplaces`)+ * is never read here: interactive Claude Code gates a project-declared+ * marketplace behind workspace trust, but `--plugin-dir` loads with no prompt+ * and replaces the user's installed copy of the same name. Letting a cloned+ * repo point the headless worker at its own folder would run repo-supplied+ * function hooks in every daemon worker, in place of the user's guard.+ */++import { existsSync, readdirSync } from 'node:fs';+import { homedir } from 'node:os';+import { dirname, isAbsolute, join, resolve } from 'node:path';++import { MARKETPLACE_NAME } from './install.js';+import { claudeConfigDir, marketplaceState, nodeReadFs, pluginManifestIn, type ReadFs } from './plugin-resolve.js';++export type PluginSource = 'local' | 'clone' | 'cache';++export interface ResolvedPlugin {+ name: string;+ /** Absolute plugin folder (the one holding `.claude-plugin/plugin.json`). */+ path: string;+ source: PluginSource;+}++export interface MissingPlugin {+ name: string;+ reason: string;+}++export interface PluginPaths {+ resolved: ResolvedPlugin[];+ missing: MissingPlugin[];+}++/** ReadFs plus a directory listing (for the install cache's version folders). */+export interface PluginFs extends ReadFs {+ list(path: string): string[];+}++export const nodePluginFs: PluginFs = {+ ...nodeReadFs,+ list: (p) => {+ try {+ return existsSync(p) ? readdirSync(p) : [];+ } catch {+ return [];+ }+ },+};++export interface ResolveOptions {+ /**+ * Accepted for callers' convenience but deliberately not consulted: the+ * project's own settings never choose a headless plugin folder (see "Trust").+ */+ projectRoot?: string;+ env?: NodeJS.ProcessEnv;+ home?: string;+ fs?: PluginFs;+}++const MANIFEST = join('.claude-plugin', 'plugin.json');++function readJson(fs: ReadFs, path: string): unknown {+ const text = fs.readText(path);+ if (text === undefined) return undefined;+ try {+ return JSON.parse(text);+ } catch {+ return undefined;+ }+}++const isRecord = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object' && !Array.isArray(v);++/**+ * The directory marketplace Claude Code knows as `ruflo`, from the user-level+ * `known_marketplaces.json` only (see "Trust" above). A relative path is+ * rejected: Claude Code records absolute ones, and a relative path would+ * resolve against whatever directory the worker happens to start in.+ */+function localMarketplaceDir(configDir: string, fs: ReadFs): string | null {+ const market = marketplaceState(configDir, fs);+ if (market.source?.source !== 'directory') return null;+ const declared = typeof market.source.path === 'string' ? market.source.path : null;+ const dir = market.location ?? declared;+ return dir && isAbsolute(dir) && (!declared || isAbsolute(declared)) ? dir : null;+}++/** Numeric-aware version compare ("0.10.0" > "0.9.3"); non-numeric parts compare as text. */+function compareVersions(a: string, b: string): number {+ const pa = a.split(/[.-]/);+ const pb = b.split(/[.-]/);+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {+ const x = pa[i] ?? '';+ const y = pb[i] ?? '';+ const nx = /^\d+$/.test(x) ? Number(x) : NaN;+ const ny = /^\d+$/.test(y) ? Number(y) : NaN;+ const d = !Number.isNaN(nx) && !Number.isNaN(ny) ? nx - ny : x.localeCompare(y);+ if (d !== 0) return d;+ }+ return 0;+}++/** The cached install: installed_plugins.json's path first, else the highest version folder. */+function cachedPluginDir(configDir: string, name: string, fs: PluginFs): string | null {+ const record = readJson(fs, join(configDir, 'plugins', 'installed_plugins.json'));+ const plugins = isRecord(record) && isRecord(record.plugins) ? record.plugins : undefined;+ const entries = plugins && Array.isArray(plugins[`${name}@${MARKETPLACE_NAME}`]) ? (plugins[`${name}@${MARKETPLACE_NAME}`] as unknown[]) : [];+ for (const e of entries) {+ if (isRecord(e) && typeof e.installPath === 'string' && fs.exists(join(e.installPath, MANIFEST))) return e.installPath;+ }+ const base = join(configDir, 'plugins', 'cache', MARKETPLACE_NAME, name);+ const versions = fs.list(base).filter((v) => fs.exists(join(base, v, MANIFEST))).sort(compareVersions);+ return versions.length > 0 ? join(base, versions[versions.length - 1]!) : null;+}++/** Plugin folder from a marketplace root (its marketplace.json `source`, else plugins/<name>). */+function pluginDirIn(root: string, name: string, fs: ReadFs): string | null {+ const manifest = pluginManifestIn(root, `${name}@${MARKETPLACE_NAME}`, fs);+ return fs.exists(manifest) ? dirname(dirname(manifest)) : null;+}++/** Resolve each plugin name (e.g. `ruflo-mods`) to an absolute folder, or report it missing. */+export function resolvePluginPaths(names: readonly string[], opts: ResolveOptions = {}): PluginPaths {+ const env = opts.env ?? process.env;+ const fs = opts.fs ?? nodePluginFs;+ const configDir = claudeConfigDir(env, opts.home ?? homedir());+ const local = localMarketplaceDir(configDir, fs);+ const market = marketplaceState(configDir, fs);+ const clone = market.source?.source === 'directory' ? null : market.location;++ const out: PluginPaths = { resolved: [], missing: [] };+ for (const raw of names) {+ const name = raw.split('@')[0]!.trim();+ if (!name) continue;+ const fromLocal = local ? pluginDirIn(local, name, fs) : null;+ const fromClone = !fromLocal && clone ? pluginDirIn(clone, name, fs) : null;+ const fromCache = !fromLocal && !fromClone ? cachedPluginDir(configDir, name, fs) : null;+ const hit: [string | null, PluginSource][] = [[fromLocal, 'local'], [fromClone, 'clone'], [fromCache, 'cache']];+ const found = hit.find(([p]) => p !== null);+ if (found) {+ out.resolved.push({ name, path: resolve(found[0]!), source: found[1] });+ } else {+ const looked = [local && `local marketplace ${local}`, clone && `clone ${clone}`, `cache ${join(configDir, 'plugins', 'cache', MARKETPLACE_NAME, name)}`].filter(Boolean);+ out.missing.push({ name, reason: `no ${MANIFEST} in ${looked.join(', ')}` });+ }+ }+ return out;+}diff --git a/v3/@claude-flow/cli/src/services/headless-worker-executor.ts b/v3/@claude-flow/cli/src/services/headless-worker-executor.tsindex 67c3390148..739138956f 100644--- a/v3/@claude-flow/cli/src/services/headless-worker-executor.ts+++ b/v3/@claude-flow/cli/src/services/headless-worker-executor.ts@@ -27,6 +27,7 @@ import type { WorkerType } from './worker-daemon.js';import { getGlobalAiBudget, isQuotaErrorText } from './global-ai-budget.js';import { resolveGitWorkspaceIdentity } from './git-workspace-identity.js';import { getAiJobDedupRegistry, computeAiJobKey, hashWorkerConfig } from './ai-job-dedup.js';+import { withHeadlessPlugins } from '../mods/headless-plugins.js';// ============================================// Type Definitions@@ -195,6 +196,9 @@ export interface HeadlessExecutionResult {/** Execution ID for tracking */executionId: string;+ /** ADR-510 β plugins in the worker profile that could not be found; the worker ran without them. */+ missingPlugins?: string[];+/*** #2661 β true when the launch was skipped because the same job* (repositoryId + HEAD + worker + config) succeeded within the freshness@@ -1077,6 +1081,7 @@ export class HeadlessWorkerExecutor extends EventEmitter {timestamp: new Date(),executionId,error: result.error,+ ...(result.missingPlugins ? { missingPlugins: result.missingPlugins } : {}),};// Log result@@ -1356,8 +1361,13 @@ Analyze the above codebase context and provide your response following the formacostUsd?: number;apiDurationMs?: number;error?: string;+ missingPlugins?: string[];}> {- return new Promise((resolve) => {+ return new Promise((resolveRaw) => {+ // ADR-510: a plugin the worker profile wants but cannot find is recorded on the result.+ let missingPlugins: string[] = [];+ const resolve = (r: Parameters<typeof resolveRaw>[0]) =>+ resolveRaw(missingPlugins.length > 0 ? { ...r, missingPlugins } : r);const env: Record<string, string> = {...(process.env as Record<string, string>),CLAUDE_CODE_HEADLESS: 'true',@@ -1405,9 +1415,14 @@ Analyze the above codebase context and provide your response following the forma// and ALWAYS falls back to the raw text on any mismatch β a schema// surprise from an older/newer `claude` CLI must degrade to exactly// today's behavior (no usage captured), never break analysis output.- const child = spawn('claude', ['--print', '--output-format', 'json'], {+ // ADR-510: `claude -p` on a fresh config loads no marketplace plugins, so+ // pass the worker profile (default ruflo-mods) as --plugin-dir and turn+ // function hooks on unless the caller set CLAUDE_CODE_ENABLE_FUNCTION_HOOKS.+ const staged = withHeadlessPlugins(['--print', '--output-format', 'json'], env, { projectRoot: this.projectRoot });+ missingPlugins = staged.missing;+ const child = spawn('claude', staged.argv, {cwd: this.projectRoot,- env,+ env: staged.env,stdio: ['pipe', 'pipe', 'pipe'],windowsHide: true, // Prevent phantom console windows on Windowsdetached: process.platform !== 'win32',diff --git a/v3/docs/adr/ADR-510-headless-and-sdk-plugin-staging.md b/v3/docs/adr/ADR-510-headless-and-sdk-plugin-staging.mdindex 521ea76b91..ace362b93b 100644--- a/v3/docs/adr/ADR-510-headless-and-sdk-plugin-staging.md+++ b/v3/docs/adr/ADR-510-headless-and-sdk-plugin-staging.md@@ -1,6 +1,6 @@# ADR 510: loading ruflo plugins in headless and Agent SDK workers-Status: Proposed (2026-10-29)+Status: Accepted (implemented in PR #4586)Issue: #4581 follow-up 8. Builds on: ADR-404 (mods), the headless worker daemon, and the ADR-502 canary (mods ran under `claude -p --plugin-dir`).@@ -65,3 +65,16 @@ This answers "do mods run headless here" per machine instead of from documentati- The worker command builder adds `--plugin-dir` and the environment variable, and does not duplicate a caller's own flag.- The doctor check is covered by a test using the ADR-504 mock model.- Live: a daemon worker run shows the ruflo-mods heartbeat.++## Implementation notes++- **Resolver:** `v3/@claude-flow/cli/src/mods/plugin-paths.ts` (`resolvePluginPaths`). "Local" is only a directory marketplace that Claude Code records in the user-level `known_marketplaces.json`, with an absolute path. The cache step takes the `installed_plugins.json` path first, else the highest version folder that holds a manifest.+- **Command builders:** `withHeadlessPlugins` (`src/mods/headless-plugins.ts`) is applied in the three places the CLI builds a `claude -p` worker: `HeadlessWorkerExecutor.executeClaudeCode` (the daemon's workers), `hive-mind work` (`runWithClaude`) and `hive-mind spawn --claude --non-interactive` (staged before the prompt, which stays the last argument; a missing plugin is returned as `data.claude.missingPlugins`). The interactive `hive-mind spawn --claude` launch is unchanged: an interactive start loads plugins the normal, trusted way. A caller's own `--plugin-dir` is matched by real path or by folder name and is never duplicated. A missing plugin is logged once per process and recorded as `missingPlugins` on `HeadlessExecutionResult`, on `RunOutcome`, and in the hive task's result record. `RUFLO_HEADLESS_PLUGINS` (comma list, or `none`) overrides the default profile (ruflo-mods).+- **Not changed, on purpose:** `services/fable-harness.ts` (the advisor/judge) also spawns `claude -p`, but it runs from a fresh empty temp directory precisely so the call carries no project context, and its argv is pinned by a test. Loading mods there would add hooks and context to a budget-capped judge call, so it is left out of the worker profile.+- **Out of the repo:** `/federation dispatch` lives in `~/.claude/helpers/federation.sh`, and the metaharness/Darwin runners are upstream packages; neither builds its command line in this repository. They can call `ruflo plugins paths --json`.+- **Doctor:** `ruflo doctor --component headless-plugins` (`src/mods/headless-check.ts`), `--component` only, because it spends a model call. On Claude Code 2.1.289 the init event carries `plugins: [{ name, path, source, version }]` (an inline plugin shows `source: "ruflo-mods@inline"`), and `plugin_errors` is absent when there are none; the check treats an absent key as empty. The runner is injectable and the tests use a fake one.+- **Deviation, mock model:** ADR-504's scripted mock model is not on `main` yet, so the doctor check cannot fall back to it. Without any model credential (API key, auth token, base URL, Bedrock/Vertex, or `<config>/.credentials.json`; macOS is assumed to have a keychain login) the check reports `skipped` as a warning instead of spawning. Once ADR-504 lands, the no-credential path can point `ANTHROPIC_BASE_URL` at it.+- **Trust boundary (review fix):** the first version also read `extraKnownMarketplaces.ruflo` from the project's `.claude/settings.local.json` and the committed `.claude/settings.json`, resolving a relative path against the project root, and preferred that over the user's clone and cache. That let a cloned repository choose the folder every daemon worker and `hive-mind work` loads in-process via `--plugin-dir`, with function hooks forced on and no trust prompt (interactive Claude Code gates a project-declared marketplace behind workspace trust; `--plugin-dir` does not, and an inline plugin replaces the marketplace copy of the same name, so the repo's code would also stand in for the user's ruflo-mods guard). The project's settings are no longer read at all: only Claude Code's user-level `known_marketplaces.json` (an entry the user added through an interactive, trusted start) can make a folder "local", and a relative path there is rejected. `ruflo mods install --source local` still resolves as local, because it also runs `claude plugin marketplace add <dir>`, and Claude Code keeps one ruflo marketplace per config dir in `known_marketplaces.json` (on this machine the entry carries no scope marker: `{ source: { source: "directory", path }, installLocation }`); `ruflo plugins paths` shows what a worker will load. Tests: a project-scope `settings.json` or `settings.local.json` pointing into the repo (absolute or `./x`) resolves to the clone or the cache, never the repo; a relative path is rejected. Live check (real filesystem, real `~/.claude`): a scratch project with `.claude/settings.json` declaring `ruflo` as `{ source: "directory", path: "./x" }` and a valid `./x/plugins/ruflo-mods/.claude-plugin/plugin.json` resolved to the user's own directory marketplace from `known_marketplaces.json`, not `./x`. No model call was spent on this pass: the change is in path resolution and at one spawn site, and the `--plugin-dir` load itself was live-validated below. Staging stays on by default: with the project removed as a source, every folder it can load is one the user installed. Revisit with ADR-509's signature check.+- **Deviation, signature check:** Β§3's "check the plugin's signature first when `modTrust` is `refuse-risky`" depends on ADR-509, which is not on `main`. Not implemented here.+- **Known side effect:** a daemon worker runs with `cwd` = the project, so its ruflo-mods session start rewrites `.claude-flow/mods/session.json` (display only; nothing decides by it).+- **Live validation (Claude Code 2.1.289, haiku):** `claude -p --plugin-dir <worktree>/plugins/ruflo-mods` wrote the heartbeat. `ruflo doctor --component headless-plugins` passed against this branch's ruflo-mods 0.8.0, and warned ("loads but its function hooks did not run") against a ruflo-mods 0.7.0 checkout, the release whose unmatched `session.start` registrations the loader refuses (#4485). That is the per-machine answer Β§2.4 asks for.