🌊 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
fix(security): migration-safe hive-mind gating by caller transport (ADR-476, #3338)
ruv8f4b47af1615
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fd93dc9664..389e649c82 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Security++- **Hive-mind gating that keeps local users working (ADR-476, #3338)** — `hive-mind_init` no longer returns `hiveToken`, and `spawn`, `consensus` `propose`, `broadcast`, `shutdown`, `memory` `set`/`delete` and `optimize-memory` (plus the existing `join`/`leave`/`vote`) now require an operator credential from **remote** callers (HTTP/WebSocket MCP). Local stdio MCP, `ruflo mcp exec`, the `hive-mind` CLI and in-process callers need no credential and no extra step. Remote clients set `RUFLO_HIVE_BOOTSTRAP_SECRET` (or read `.claude-flow/hive-mind/bootstrap.secret`, created 0600 by the first local `hive-mind init`) and send it as `bootstrapSecret`; `RUFLO_HIVE_REQUIRE_AUTH=1` applies the same rule to stdio on bridged servers. `state.json` is now written 0600 atomically and the hive directory 0700. Migration: clients that read `hiveToken` from the `init` response must drop that (it is `undefined`); over stdio they omit it everywhere. This is a speed bump, not a boundary, against a local prompt-injected agent that can read the files.+## [3.34.0] - 2026-07-31### Addeddiff --git a/docs/USERGUIDE.md b/docs/USERGUIDE.mdindex 10d52ef3f3..678d92ecdd 100644--- a/docs/USERGUIDE.md+++ b/docs/USERGUIDE.md@@ -1710,6 +1710,8 @@ npx ruflo hive-mind memory # Collective memory statsnpx ruflo hive-mind sessions # List active sessions```+**Access control (ADR-476).** Local use needs nothing extra: `hive-mind init`, the stdio MCP server, `ruflo mcp exec` and the CLI subcommands manage their own hive. `init` writes `.claude-flow/hive-mind/bootstrap.secret` (0600) and never prints or returns the hive token. Clients that reach the MCP server over **HTTP/WebSocket** are refused for `init`, `spawn`, `consensus` propose/vote, `broadcast`, `shutdown`, `join`, `leave`, `memory` set/delete and `optimize-memory` unless the operator hands them the secret: set `RUFLO_HIVE_BOOTSTRAP_SECRET` (16+ chars) on the server, then send it as `bootstrapSecret` in each call. If you bridge a stdio server onto a network, set `RUFLO_HIVE_REQUIRE_AUTH=1`. Against a local agent that can read the project directory this is a speed bump, not a boundary.+**Performance:** Fast batch spawning with parallel agent coordination</details>diff --git a/v3/@claude-flow/cli/__tests__/hive-mind-consensus-sybil-vote.test.ts b/v3/@claude-flow/cli/__tests__/hive-mind-consensus-sybil-vote.test.tsindex 80101fcb11..f798e56fdb 100644--- a/v3/@claude-flow/cli/__tests__/hive-mind-consensus-sybil-vote.test.ts+++ b/v3/@claude-flow/cli/__tests__/hive-mind-consensus-sybil-vote.test.ts@@ -21,29 +21,30 @@* call makes literally zero state change (no membership write, no vote* write), verified below by reloading state fresh from disk (simulating a* process restart/reopen) after each denial.- *- * Round 2 review feedback (#3339) correctly pointed out that requireHiveToken- * alone doesn't "establish authorization" while hive-mind_init -- the- * credential-issuance point -- was itself reachable by any caller (either to- * mint the very first token, or to have the current one echoed back on- * re-init). hive-mind_init now requires its own same-machine `bootstrapSecret`- * (see getOrCreateBootstrapSecret()), and no longer returns `hiveToken` in its- * response at all -- tests below read it via `getHiveTokenForCli()` instead,- * the same same-machine accessor the CLI itself uses.*/import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { mkdtempSync, rmSync, readFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { hiveMindTools, getHiveTokenForCli, getHiveBootstrapSecretForCli } from '../src/mcp-tools/hive-mind-tools.js';+import { hiveMindTools, getHiveTokenForCli } from '../src/mcp-tools/hive-mind-tools.js';++// ADR-476: these tests model an UNTRUSTED remote (HTTP) caller -- the only+// caller class the capability token is a boundary for. Local stdio/CLI+// callers need no token (see hive-mind-gate-matrix.test.ts).+const REMOTE = { sessionId: 'sybil-test', transport: 'http' };function tool(name: string) {const t = hiveMindTools.find(t => t.name === name);if (!t) throw new Error(`tool not found: ${name}`);- return t;+ return { ...t, handler: (input: Record<string, unknown>) => t.handler(input, REMOTE) };}+// init is performed as the local operator (no context); the token is then+// read the same way the CLI reads it -- init never returns it (ADR-476).+const localInit = (input: Record<string, unknown>) =>+ hiveMindTools.find(t => t.name === 'hive-mind_init')!.handler(input);+// Reads the persisted state file directly -- a fresh read from disk, not// anything cached in-process, so it stands in for "the process restarted// and reopened the hive" between a denied call and this check.@@ -69,10 +70,7 @@ describe('hive-mind_consensus / join / leave capability-token authentication', (});async function initHive(strategy: 'raft' | 'byzantine' | 'quorum'): Promise<string> {- const init = await tool('hive-mind_init').handler({- consensus: strategy,- bootstrapSecret: getHiveBootstrapSecretForCli(),- }) as any;+ const init = await localInit({ consensus: strategy }) as any;expect(init.success).toBe(true);expect(init.hiveToken).toBeUndefined();const token = getHiveTokenForCli();diff --git a/v3/@claude-flow/cli/__tests__/hive-mind-gate-dispatch-contract.test.ts b/v3/@claude-flow/cli/__tests__/hive-mind-gate-dispatch-contract.test.tsnew file mode 100644index 0000000000..1e0541e7ca--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/hive-mind-gate-dispatch-contract.test.ts@@ -0,0 +1,44 @@+/**+ * ADR-476 contract: the hive-mind gate trusts only the server-built+ * `context.transport`. Each dispatcher that reaches callMCPTool must label+ * itself, or remote callers would be classified by omission. If one of these+ * assertions breaks, a dispatcher changed and the gate's caller+ * classification must be re-verified.+ */+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++const src = (p: string) => readFileSync(join(__dirname, '..', 'src', p), 'utf-8');++describe('hive-mind gate: dispatchers label their transport', () => {+ const server = src('mcp-server.ts');++ it('the stdio loop passes transport: stdio', () => {+ expect(server).toMatch(/callMCPTool\(toolName, toolParams, \{ sessionId, transport: 'stdio' \}\)/);+ });++ it('the HTTP/WebSocket handler passes http or websocket, never stdio/cli', () => {+ const m = server.match(/transport: this\.options\.transport === 'websocket' \? 'websocket' : 'http'/);+ expect(m).not.toBeNull();+ const httpBlock = server.slice(server.indexOf('private async startHttpServer'));+ expect(httpBlock).not.toMatch(/transport: 'stdio'|transport: 'cli'/);+ });++ it('both shipped stdio entry points (bin/mcp-server.js, bin/cli.js) pass transport: stdio', () => {+ for (const bin of ['mcp-server.js', 'cli.js']) {+ const text = readFileSync(join(__dirname, '..', 'bin', bin), 'utf-8');+ expect(text, bin).toMatch(/callMCPTool\(toolName, toolParams, \{ sessionId, transport: 'stdio' \}\)/);+ }+ });++ it('`mcp exec` is the local CLI', () => {+ expect(src('commands/mcp.ts')).toMatch(/transport: 'cli'/);+ });++ it('client-supplied tool arguments are never consulted for the caller class', () => {+ const tools = src('mcp-tools/hive-mind-tools.ts');+ const classify = tools.slice(tools.indexOf('function classifyCaller'), tools.indexOf('function constantTimeEqual'));+ expect(classify).not.toMatch(/input/);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/hive-mind-gate-matrix.test.ts b/v3/@claude-flow/cli/__tests__/hive-mind-gate-matrix.test.tsnew file mode 100644index 0000000000..332d0cd40c--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/hive-mind-gate-matrix.test.ts@@ -0,0 +1,321 @@+/**+ * ADR-476 -- hive-mind gate behaviour matrix (caller type x credential).+ *+ * caller no cred wrong cred operator secret hiveToken+ * local (no context / stdio/cli) ok ok ok ok+ * remote (http / websocket) refused refused ok ok*+ * remote w/ no secret configured refused refused refused ok*+ * RUFLO_HIVE_REQUIRE_AUTH=1 (any) treated as remote+ * (* every gated tool except hive-mind_init, which takes only the secret)+ *+ * The caller class comes from the server-built `context.transport`, never from+ * a tool argument.+ */++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, rmSync, readFileSync, readdirSync, statSync, existsSync, writeFileSync, mkdirSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const cryptoSpy = vi.hoisted(() => ({ calls: [] as Array<[number, number]> }));+vi.mock('node:crypto', async () => {+ const actual = await vi.importActual<typeof import('node:crypto')>('node:crypto');+ return {+ ...actual,+ timingSafeEqual: (a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView) => {+ cryptoSpy.calls.push([a.byteLength, b.byteLength]);+ return actual.timingSafeEqual(a, b);+ },+ };+});++import { hiveMindTools, getHiveTokenForCli } from '../src/mcp-tools/hive-mind-tools.js';++const SECRET = 'operator-secret-0123456789abcdef';+const posix = process.platform !== 'win32';++type Ctx = Record<string, unknown> | undefined;+const LOCAL_CTXS: Array<[string, Ctx]> = [+ ['in-process (no context)', undefined],+ ['stdio MCP', { sessionId: 's', transport: 'stdio' }],+ ['CLI mcp exec', { sessionId: 's', transport: 'cli' }],+];+const REMOTE_CTXS: Array<[string, Ctx]> = [+ ['http', { sessionId: 's', transport: 'http' }],+ ['websocket', { sessionId: 's', transport: 'websocket' }],+ ['context naming no transport', { sessionId: 's' }],+ ['spoofed transport string', { sessionId: 's', transport: 'stdio-but-not-really' }],+];++const raw = (name: string) => hiveMindTools.find((t) => t.name === name)!;+const run = (name: string, input: Record<string, unknown>, ctx: Ctx) =>+ raw(name).handler(input, ctx) as Promise<any>;++/** Every gated operation, with a predicate for "this call was refused". */+interface Op {+ name: string;+ tool: string;+ tokenAllowed: boolean;+ input: (cred: Record<string, unknown>) => Record<string, unknown>;+ refused: (r: any) => boolean;+}+const op = (name: string, tool: string, tokenAllowed: boolean, input: Op['input'], refused: Op['refused']): Op => ({ name, tool, tokenAllowed, input, refused });+const failedFlag = (r: any) => r?.success === false || typeof r?.error === 'string';+const OPS: Op[] = [+ op('init', 'hive-mind_init', false, (c) => ({ consensus: 'raft', ...c }), failedFlag),+ op('join', 'hive-mind_join', true, (c) => ({ agentId: 'w-join', ...c }), failedFlag),+ op('spawn', 'hive-mind_spawn', true, (c) => ({ count: 1, ...c }), failedFlag),+ op('propose', 'hive-mind_consensus', true, (c) => ({ action: 'propose', type: 't', value: 'v', strategy: 'raft', ...c }), failedFlag),+ op('broadcast', 'hive-mind_broadcast', true, (c) => ({ message: 'hi', ...c }), failedFlag),+ op('memory set', 'hive-mind_memory', true, (c) => ({ action: 'set', key: 'k', value: 'v', ...c }), failedFlag),+ op('memory delete', 'hive-mind_memory', true, (c) => ({ action: 'delete', key: 'k', ...c }), failedFlag),+ op('optimize-memory', 'hive-mind_optimize-memory', true, (c) => ({ ...c }), (r) => typeof r?.error === 'string'),+ op('shutdown', 'hive-mind_shutdown', true, (c) => ({ force: true, ...c }), failedFlag),+];++describe('hive-mind gate matrix (ADR-476)', () => {+ let dir: string;+ let prevCwd: string | undefined;+ const hiveDir = () => join(dir, '.claude-flow', 'hive-mind');++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'hive-gate-'));+ prevCwd = process.env.CLAUDE_FLOW_CWD;+ process.env.CLAUDE_FLOW_CWD = dir;+ delete process.env.RUFLO_HIVE_BOOTSTRAP_SECRET;+ delete process.env.RUFLO_HIVE_REQUIRE_AUTH;+ cryptoSpy.calls.length = 0;+ });+ afterEach(() => {+ delete process.env.RUFLO_HIVE_BOOTSTRAP_SECRET;+ delete process.env.RUFLO_HIVE_REQUIRE_AUTH;+ if (prevCwd === undefined) delete process.env.CLAUDE_FLOW_CWD;+ else process.env.CLAUDE_FLOW_CWD = prevCwd;+ rmSync(dir, { recursive: true, force: true });+ });++ /** Local operator init (what `hive-mind init` / a stdio client does). */+ async function localInit() {+ const r = await run('hive-mind_init', { consensus: 'raft' }, undefined);+ expect(r.success).toBe(true);+ return getHiveTokenForCli() as string;+ }++ describe('local callers keep working with no extra step', () => {+ for (const [label, ctx] of LOCAL_CTXS) {+ it(`${label}: init, join, spawn, propose, broadcast, memory set/delete, optimize, shutdown all succeed with no credential`, async () => {+ for (const o of OPS) {+ if (o.name === 'shutdown') continue;+ const r = await run(o.tool, o.input({}), ctx);+ expect(o.refused(r), `${o.name} refused for ${label}: ${JSON.stringify(r)}`).toBe(false);+ }+ const r = await run('hive-mind_shutdown', { force: true }, ctx);+ expect(r.success).toBe(true);+ });+ }++ it('a local MCP client can init, then join and vote with no token ever shown to it', async () => {+ const ctx = { sessionId: 's', transport: 'stdio' };+ const init = await run('hive-mind_init', {}, ctx);+ expect(init.success).toBe(true);+ expect(init.hiveToken).toBeUndefined();+ expect((await run('hive-mind_join', { agentId: 'w1' }, ctx)).success).toBe(true);+ const p = await run('hive-mind_consensus', { action: 'propose', type: 't', value: 1, strategy: 'raft' }, ctx);+ const v = await run('hive-mind_consensus', { action: 'vote', proposalId: p.proposalId, vote: true, voterId: 'w1' }, ctx);+ expect(v.error).toBeUndefined();+ });+ });++ describe('remote callers (no file access) are refused for every gated tool', () => {+ for (const o of OPS) {+ for (const [label, ctx] of REMOTE_CTXS) {+ it(`${o.name} via ${label}: no credential, wrong secret and wrong token are refused and change nothing`, async () => {+ process.env.RUFLO_HIVE_BOOTSTRAP_SECRET = SECRET;+ await localInit();+ const before = readFileSync(join(hiveDir(), 'state.json'), 'utf-8');+ const attempts: Array<Record<string, unknown>> = [+ {},+ { bootstrapSecret: 'x'.repeat(SECRET.length) },+ { bootstrapSecret: 'short' },+ { hiveToken: 'forged' },+ { bootstrapSecret: '' },+ ];+ for (const cred of attempts) {+ const r = await run(o.tool, o.input(cred), ctx);+ expect(o.refused(r), `${o.name}/${label}/${JSON.stringify(cred)} -> ${JSON.stringify(r)}`).toBe(true);+ }+ expect(readFileSync(join(hiveDir(), 'state.json'), 'utf-8')).toBe(before);+ });+ }+ }++ it('remote callers cannot init a brand-new hive: nothing is written to disk', async () => {+ process.env.RUFLO_HIVE_BOOTSTRAP_SECRET = SECRET;+ const r = await run('hive-mind_init', {}, { sessionId: 's', transport: 'http' });+ expect(r.success).toBe(false);+ expect(existsSync(join(hiveDir(), 'state.json'))).toBe(false);+ });++ it('a remote call never creates the secret file (only a local init does)', async () => {+ await run('hive-mind_init', { bootstrapSecret: 'guess' }, { sessionId: 's', transport: 'http' });+ expect(existsSync(join(hiveDir(), 'bootstrap.secret'))).toBe(false);+ });++ it('with no secret configured anywhere, even an attacker-chosen secret is refused', async () => {+ const r = await run('hive-mind_init', { bootstrapSecret: 'anything-long-enough-0123' }, { sessionId: 's', transport: 'http' });+ expect(r.success).toBe(false);+ });+ });++ describe('remote callers the operator has given the secret to', () => {+ const HTTP = { sessionId: 's', transport: 'http' };++ for (const o of OPS) {+ it(`${o.name}: accepted with the operator secret (env)`, async () => {+ process.env.RUFLO_HIVE_BOOTSTRAP_SECRET = SECRET;+ await localInit();+ const r = await run(o.tool, o.input({ bootstrapSecret: SECRET }), HTTP);+ expect(o.refused(r), JSON.stringify(r)).toBe(false);+ });+ if (o.tokenAllowed) {+ it(`${o.name}: accepted with the hiveToken`, async () => {+ const token = await localInit();+ const r = await run(o.tool, o.input({ hiveToken: token }), HTTP);+ expect(o.refused(r), JSON.stringify(r)).toBe(false);+ });+ }+ }++ it('works with the file-based secret too (no env), once a local init created it', async () => {+ await localInit();+ const fileSecret = readFileSync(join(hiveDir(), 'bootstrap.secret'), 'utf-8').trim();+ const r = await run('hive-mind_spawn', { count: 1, bootstrapSecret: fileSecret }, HTTP);+ expect(r.success).toBe(true);+ });+ });++ describe('secret sources', () => {+ const HTTP = { sessionId: 's', transport: 'http' };++ it('env overrides the file: the file value stops working, the env value works', async () => {+ await localInit();+ const fileSecret = readFileSync(join(hiveDir(), 'bootstrap.secret'), 'utf-8').trim();+ process.env.RUFLO_HIVE_BOOTSTRAP_SECRET = SECRET;+ expect((await run('hive-mind_spawn', { bootstrapSecret: fileSecret }, HTTP)).success).toBe(false);+ expect((await run('hive-mind_spawn', { bootstrapSecret: SECRET }, HTTP)).success).toBe(true);+ });++ it('an env secret shorter than 16 chars is ignored (cannot be a weak shared password)', async () => {+ process.env.RUFLO_HIVE_BOOTSTRAP_SECRET = 'abc';+ await localInit();+ expect((await run('hive-mind_spawn', { bootstrapSecret: 'abc' }, HTTP)).success).toBe(false);+ });++ it('a local init does not overwrite an existing secret file', async () => {+ mkdirSync(hiveDir(), { recursive: true });+ writeFileSync(join(hiveDir(), 'bootstrap.secret'), 'pre-existing-operator-secret-xyz');+ await localInit();+ expect(readFileSync(join(hiveDir(), 'bootstrap.secret'), 'utf-8')).toBe('pre-existing-operator-secret-xyz');+ });++ it('a local init is satisfied by an env secret and writes no file', async () => {+ process.env.RUFLO_HIVE_BOOTSTRAP_SECRET = SECRET;+ await localInit();+ expect(existsSync(join(hiveDir(), 'bootstrap.secret'))).toBe(false);+ });+ });++ describe('RUFLO_HIVE_REQUIRE_AUTH=1 (strict mode for bridged/shared stdio)', () => {+ it('treats stdio and in-process callers as remote', async () => {+ await localInit();+ process.env.RUFLO_HIVE_REQUIRE_AUTH = '1';+ for (const [, ctx] of LOCAL_CTXS) {+ expect((await run('hive-mind_spawn', { count: 1 }, ctx)).success).toBe(false);+ }+ const token = getHiveTokenForCli();+ expect((await run('hive-mind_spawn', { count: 1, hiveToken: token }, { transport: 'stdio' })).success).toBe(true);+ });+ });++ describe('constant-time comparison', () => {+ it('compares fixed-length digests via timingSafeEqual for any supplied length (no length oracle, no throw)', async () => {+ process.env.RUFLO_HIVE_BOOTSTRAP_SECRET = SECRET;+ await localInit();+ cryptoSpy.calls.length = 0;+ for (const supplied of ['a', 'b'.repeat(7), SECRET.slice(0, -1), SECRET + 'x', 'c'.repeat(5000)]) {+ const r = await run('hive-mind_spawn', { bootstrapSecret: supplied }, { transport: 'http' });+ expect(r.success).toBe(false);+ }+ expect(cryptoSpy.calls.length).toBeGreaterThanOrEqual(5);+ for (const [a, b] of cryptoSpy.calls) {+ expect(a).toBe(32);+ expect(b).toBe(32);+ }+ });+ });++ describe('credentials never leave the server', () => {+ it('no tool response, denial or console/stdout output contains the token or the secret', async () => {+ process.env.RUFLO_HIVE_BOOTSTRAP_SECRET = SECRET;+ const logged: string[] = [];+ const spies = (['log', 'info', 'warn', 'error', 'debug'] as const).map((m) =>+ vi.spyOn(console, m).mockImplementation((...a: unknown[]) => { logged.push(a.map(String).join(' ')); }),+ );+ const out = vi.spyOn(process.stdout, 'write').mockImplementation(((c: unknown) => { logged.push(String(c)); return true; }) as never);+ const err = vi.spyOn(process.stderr, 'write').mockImplementation(((c: unknown) => { logged.push(String(c)); return true; }) as never);+ try {+ const responses: unknown[] = [];+ responses.push(await run('hive-mind_init', {}, undefined));+ const token = getHiveTokenForCli() as string;+ responses.push(await run('hive-mind_init', { bootstrapSecret: 'wrong' }, { transport: 'http' }));+ responses.push(await run('hive-mind_init', { bootstrapSecret: SECRET }, { transport: 'http' }));+ for (const o of OPS.filter((x) => x.name !== 'init' && x.name !== 'shutdown')) {+ responses.push(await run(o.tool, o.input({}), { transport: 'http' }));+ responses.push(await run(o.tool, o.input({ hiveToken: 'forged' }), { transport: 'http' }));+ responses.push(await run(o.tool, o.input({ bootstrapSecret: 'forged' }), { transport: 'http' }));+ responses.push(await run(o.tool, o.input({}), undefined));+ }+ responses.push(await run('hive-mind_status', {}, { transport: 'http' }));+ responses.push(await run('hive-mind_status', {}, undefined));+ responses.push(await run('hive-mind_memory', { action: 'list' }, { transport: 'http' }));+ responses.push(await run('hive-mind_shutdown', { force: true }, undefined));++ const blob = JSON.stringify(responses) + logged.join('\n');+ expect(blob).not.toContain(token);+ expect(blob).not.toContain(SECRET);+ expect(blob).not.toMatch(/"hiveToken":\s*"[0-9a-f]{64}"/);+ } finally {+ spies.forEach((s) => s.mockRestore());+ out.mockRestore();+ err.mockRestore();+ }+ });+ });++ describe.skipIf(!posix)('file permissions (POSIX)', () => {+ const mode = (p: string) => statSync(p).mode & 0o777;++ it('state.json and bootstrap.secret are 0600, the hive directory 0700, after init and after later writes', async () => {+ await localInit();+ await run('hive-mind_memory', { action: 'set', key: 'k', value: 'v' }, undefined);+ expect(mode(join(hiveDir(), 'state.json'))).toBe(0o600);+ expect(mode(join(hiveDir(), 'bootstrap.secret'))).toBe(0o600);+ expect(mode(hiveDir())).toBe(0o700);+ });++ it('tightens a pre-existing world-readable state.json on the next write', async () => {+ await localInit();+ const { chmodSync } = await import('node:fs');+ chmodSync(join(hiveDir(), 'state.json'), 0o644);+ await run('hive-mind_memory', { action: 'set', key: 'k2', value: 'v' }, undefined);+ expect(mode(join(hiveDir(), 'state.json'))).toBe(0o600);+ });++ it('writes atomically: no temp files are left behind and the file is always valid JSON', async () => {+ await localInit();+ for (let i = 0; i < 20; i++) await run('hive-mind_memory', { action: 'set', key: `k${i}`, value: i }, undefined);+ expect(readdirSync(hiveDir()).filter((f) => f.endsWith('.tmp'))).toEqual([]);+ expect(() => JSON.parse(readFileSync(join(hiveDir(), 'state.json'), 'utf-8'))).not.toThrow();+ });+ });+});diff --git a/v3/@claude-flow/cli/__tests__/hive-mind-gate-transport-e2e.test.ts b/v3/@claude-flow/cli/__tests__/hive-mind-gate-transport-e2e.test.tsnew file mode 100644index 0000000000..82e0717736--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/hive-mind-gate-transport-e2e.test.ts@@ -0,0 +1,154 @@+/**+ * ADR-476 end-to-end: the real dispatchers classify real callers.+ *+ * - bin/mcp-server.js (what Claude Code launches) and `mcp start -t stdio`+ * are LOCAL: init/spawn/broadcast/shutdown work with no credential.+ * - `mcp start -t http` is REMOTE: the same calls are refused until the+ * operator secret is supplied, and the token never appears in a response.+ *+ * Needs the built CLI (like mcp-http-protocol-tools-2990.test.ts).+ */+import { afterEach, beforeAll, describe, expect, it } from 'vitest';+import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { fileURLToPath } from 'node:url';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const BIN = path.resolve(HERE, '..', 'bin');+const DIST = path.resolve(HERE, '..', 'dist', 'src', 'index.js');+const SECRET = 'operator-secret-for-e2e-0123456789';++let child: ChildProcessWithoutNullStreams | undefined;+let dir: string;++beforeAll(() => {+ if (!fs.existsSync(DIST)) throw new Error(`Built CLI required for end-to-end coverage: ${DIST}`);+});+afterEach(() => {+ if (child && child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');+ child = undefined;+ if (dir) fs.rmSync(dir, { recursive: true, force: true });+});++function env(extra: Record<string, string> = {}) {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hive-e2e-'));+ return {+ ...process.env,+ CLAUDE_FLOW_CWD: dir,+ CLAUDE_FLOW_MCP_TOOLS: 'all',+ RUFLO_DAEMON_AUTOSTART: '0',+ ...extra,+ };+}++/** Minimal newline-delimited JSON-RPC client over stdio. */+function stdioClient(args: string[], e: NodeJS.ProcessEnv) {+ child = spawn('node', args, { cwd: dir, env: e, stdio: ['pipe', 'pipe', 'pipe'] });+ const proc = child;+ let buf = '';+ const waiters = new Map<number, (m: any) => void>();+ proc.stdout.on('data', (c: Buffer) => {+ buf += c.toString();+ let i: number;+ while ((i = buf.indexOf('\n')) >= 0) {+ const line = buf.slice(0, i);+ buf = buf.slice(i + 1);+ try { const m = JSON.parse(line); waiters.get(m.id)?.(m); } catch { /* not a frame */ }+ }+ });+ let id = 0;+ const rpc = (method: string, params?: unknown) =>+ new Promise<any>((resolve, reject) => {+ const n = ++id;+ const t = setTimeout(() => reject(new Error(`timeout on ${method}`)), 20_000);+ waiters.set(n, (m) => { clearTimeout(t); resolve(m); });+ proc.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: n, method, params }) + '\n');+ });+ return {+ async ready() {+ await rpc('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'e2e', version: '1' } });+ },+ async call(name: string, args: Record<string, unknown> = {}) {+ const r = await rpc('tools/call', { name, arguments: args });+ return JSON.parse(r.result.content[0].text);+ },+ };+}++describe('hive-mind gate end to end (ADR-476)', () => {+ for (const [label, args] of [+ ['bin/mcp-server.js (Claude Code stdio entry)', [path.join(BIN, 'mcp-server.js')]],+ ['cli.js mcp start -t stdio', [path.join(BIN, 'cli.js'), 'mcp', 'start', '-t', 'stdio']],+ ] as Array<[string, string[]]>) {+ it(`${label}: a local stdio client runs the whole hive lifecycle with no credential and is never handed the token`, async () => {+ const c = stdioClient(args, env());+ await c.ready();+ const init = await c.call('hive-mind_init', {});+ expect(init.success).toBe(true);+ expect(init.hiveToken).toBeUndefined();+ expect((await c.call('hive-mind_spawn', { count: 1 })).success).toBe(true);+ expect((await c.call('hive-mind_broadcast', { message: 'hello' })).success).toBe(true);+ expect((await c.call('hive-mind_memory', { action: 'set', key: 'k', value: 1 })).success).toBe(true);+ expect((await c.call('hive-mind_shutdown', { force: true })).success).toBe(true);++ const hiveDir = path.join(dir, '.claude-flow', 'hive-mind');+ const token = JSON.parse(fs.readFileSync(path.join(hiveDir, 'state.json'), 'utf-8')).hiveToken;+ expect(JSON.stringify(init)).not.toContain(token);+ if (process.platform !== 'win32') {+ expect(fs.statSync(path.join(hiveDir, 'state.json')).mode & 0o777).toBe(0o600);+ expect(fs.statSync(path.join(hiveDir, 'bootstrap.secret')).mode & 0o777).toBe(0o600);+ }+ }, 60_000);+ }++ it('RUFLO_HIVE_REQUIRE_AUTH=1 makes the stdio server demand the operator secret', async () => {+ const c = stdioClient([path.join(BIN, 'mcp-server.js')], env({ RUFLO_HIVE_REQUIRE_AUTH: '1', RUFLO_HIVE_BOOTSTRAP_SECRET: SECRET }));+ await c.ready();+ expect((await c.call('hive-mind_init', {})).success).toBe(false);+ expect((await c.call('hive-mind_init', { bootstrapSecret: SECRET })).success).toBe(true);+ }, 60_000);++ it('the HTTP server refuses every gated call without the operator secret, then accepts it', async () => {+ const port = 34000 + Math.floor(Math.random() * 4000);+ const e = env({ RUFLO_HIVE_BOOTSTRAP_SECRET: SECRET });+ child = spawn('node', [path.join(BIN, 'cli.js'), 'mcp', 'start', '-t', 'http', '--port', String(port)], {+ cwd: dir, env: e, stdio: ['ignore', 'pipe', 'pipe'],+ });+ await new Promise<void>((resolve, reject) => {+ let out = '';+ const t = setTimeout(() => reject(new Error(`http start timeout\n${out}`)), 20_000);+ child!.stdout.on('data', (c: Buffer) => { out += c.toString(); if (out.includes('MCP Server started')) { clearTimeout(t); resolve(); } });+ child!.once('exit', (code) => { clearTimeout(t); reject(new Error(`exited ${code}\n${out}`)); });+ });+ let id = 0;+ const post = async (body: unknown) => (await fetch(`http://127.0.0.1:${port}/mcp`, {+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),+ })).json() as Promise<any>;+ await post({ jsonrpc: '2.0', id: ++id, method: 'initialize', params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'e2e', version: '1' } } });+ const call = async (name: string, args: Record<string, unknown>) => {+ const r = await post({ jsonrpc: '2.0', id: ++id, method: 'tools/call', params: { name, arguments: args } });+ return JSON.parse(r.result.content[0].text);+ };++ const denied = await call('hive-mind_init', {});+ expect(denied.success).toBe(false);+ expect(denied.hiveToken).toBeUndefined();+ expect(fs.existsSync(path.join(dir, '.claude-flow', 'hive-mind', 'state.json'))).toBe(false);+ expect((await call('hive-mind_init', { bootstrapSecret: 'wrong-wrong-wrong-wrong' })).success).toBe(false);++ const init = await call('hive-mind_init', { bootstrapSecret: SECRET });+ expect(init.success).toBe(true);+ expect(init.hiveToken).toBeUndefined();++ expect((await call('hive-mind_spawn', { count: 1 })).success).toBe(false);+ expect((await call('hive-mind_broadcast', { message: 'x' })).success).toBe(false);+ expect((await call('hive-mind_shutdown', { force: true })).success).toBe(false);+ expect((await call('hive-mind_consensus', { action: 'propose', type: 't', value: 1 })).error).toBeTruthy();+ expect((await call('hive-mind_memory', { action: 'set', key: 'k', value: 1 })).error).toBeTruthy();++ expect((await call('hive-mind_spawn', { count: 1, bootstrapSecret: SECRET })).success).toBe(true);+ expect((await call('hive-mind_shutdown', { force: true, bootstrapSecret: SECRET })).success).toBe(true);+ }, 90_000);+});diff --git a/v3/@claude-flow/cli/__tests__/hive-mind-spawn-broadcast-shutdown-auth.test.ts b/v3/@claude-flow/cli/__tests__/hive-mind-spawn-broadcast-shutdown-auth.test.tsindex 9ccf2c52fc..b321af16fb 100644--- a/v3/@claude-flow/cli/__tests__/hive-mind-spawn-broadcast-shutdown-auth.test.ts+++ b/v3/@claude-flow/cli/__tests__/hive-mind-spawn-broadcast-shutdown-auth.test.ts@@ -33,16 +33,13 @@* re-reading state.json fresh off disk (simulating a process restart)* after each denial.*- * Round 2 review (#3339) additionally found that requireHiveToken alone- * doesn't "establish authorization" while hive-mind_init -- the- * credential-issuance point itself -- was reachable by any caller (to mint- * the first token, or have the current one echoed back on re-init).- * hive-mind_init now requires its own same-machine `bootstrapSecret`- * (getOrCreateBootstrapSecret()) and no longer returns `hiveToken` in its- * response. Tests below read the token via `getHiveTokenForCli()` instead,- * and a dedicated block covers the bootstrap-secret gate itself, plus a- * real child-process CLI-command-level test (not just direct handler- * calls) exercising `node bin/cli.js hive-mind init/spawn`.+ * ADR-476 (rework of #3339): the gate is a boundary for REMOTE callers only.+ * Local stdio/CLI/in-process callers need no credential (so existing flows+ * keep working), and hive-mind_init never returns the token. These tests+ * therefore model an untrusted HTTP caller by passing the server-built+ * context `{ transport: 'http' }`; the full caller x credential matrix,+ * env override, file permissions and no-leak guarantees live in+ * hive-mind-gate-matrix.test.ts.*/import { describe, it, expect, beforeEach, afterEach } from 'vitest';@@ -50,7 +47,7 @@ import { mkdtempSync, rmSync, readFileSync, existsSync } from 'node:fs';import { execFileSync } from 'node:child_process';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { hiveMindTools, getHiveTokenForCli, getHiveBootstrapSecretForCli } from '../src/mcp-tools/hive-mind-tools.js';+import { hiveMindTools, getHiveTokenForCli } from '../src/mcp-tools/hive-mind-tools.js';const CLI = join(__dirname, '..', 'bin', 'cli.js');@@ -69,7 +66,17 @@ function runCli(args: string[], cwd: string): { stdout: string; exit: number } {}}+const REMOTE = { sessionId: 'auth-test', transport: 'http' };+const SECRET = 'operator-secret-for-tests-0123456789';+function tool(name: string) {+ const t = hiveMindTools.find((t) => t.name === name);+ if (!t) throw new Error(`tool not found: ${name}`);+ return { ...t, handler: (input: Record<string, unknown>) => t.handler(input, REMOTE) };+}++/** The local operator (no context): what the CLI and stdio MCP use. */+function localTool(name: string) {const t = hiveMindTools.find((t) => t.name === name);if (!t) throw new Error(`tool not found: ${name}`);return t;@@ -93,19 +100,18 @@ describe('hive-mind_spawn / consensus(propose) / broadcast / shutdown capabilitydir = mkdtempSync(join(tmpdir(), 'hive-mind-auth-'));prevCwd = process.env.CLAUDE_FLOW_CWD;process.env.CLAUDE_FLOW_CWD = dir;+ process.env.RUFLO_HIVE_BOOTSTRAP_SECRET = SECRET;});afterEach(() => {+ delete process.env.RUFLO_HIVE_BOOTSTRAP_SECRET;if (prevCwd === undefined) delete process.env.CLAUDE_FLOW_CWD;else process.env.CLAUDE_FLOW_CWD = prevCwd;rmSync(dir, { recursive: true, force: true });});async function initHive(): Promise<string> {- const init = (await tool('hive-mind_init').handler({- consensus: 'raft',- bootstrapSecret: getHiveBootstrapSecretForCli(),- })) as any;+ const init = (await localTool('hive-mind_init').handler({ consensus: 'raft' })) as any;expect(init.success).toBe(true);expect(init.hiveToken).toBeUndefined();return getHiveTokenForCli() as string;@@ -324,15 +330,11 @@ describe('hive-mind_spawn / consensus(propose) / broadcast / shutdown capabilityexpect(persisted.sharedMemory).toEqual({});});- describe('hive-mind_init bootstrap-secret gate (round 2 review, #3339)', () => {+ describe('hive-mind_init operator-secret gate for remote callers (ADR-476)', () => {it('is denied without a bootstrapSecret on first-time (fresh) init, and mints no hive at all', async () => {const denied = (await tool('hive-mind_init').handler({ consensus: 'raft' })) as any;expect(denied.success).toBe(false);- expect(denied.error).toBe('bootstrapSecret is required');-- // No state.json was ever written -- there is nothing to "reload":- // the whole point is that an unauthenticated first call must not be- // able to bootstrap a hive at all.+ expect(denied.error).toMatch(/bootstrapSecret is required/);expect(existsSync(join(dir, '.claude-flow', 'hive-mind', 'state.json'))).toBe(false);});@@ -346,43 +348,39 @@ describe('hive-mind_spawn / consensus(propose) / broadcast / shutdown capabilityexpect(existsSync(join(dir, '.claude-flow', 'hive-mind', 'state.json'))).toBe(false);});- it('never echoes the real bootstrap secret back to a denied caller, even though denial forces it to be generated', async () => {- const denied = (await tool('hive-mind_init').handler({- consensus: 'raft',- bootstrapSecret: 'wrong',- })) as any;- // The bug this guards: requireBootstrapSecret() must generate the- // real secret server-side to compare against, but must never leak it- // in the response merely because a caller who doesn't have it asked.- expect(JSON.stringify(denied)).not.toContain(getHiveBootstrapSecretForCli());+ it('never echoes the operator secret back to a denied caller', async () => {+ const denied = (await tool('hive-mind_init').handler({ consensus: 'raft', bootstrapSecret: 'wrong' })) as any;+ expect(JSON.stringify(denied)).not.toContain(SECRET);+ });++ it('succeeds with the correct bootstrapSecret, and still does not return the token', async () => {+ const ok = (await tool('hive-mind_init').handler({ consensus: 'raft', bootstrapSecret: SECRET })) as any;+ expect(ok.success).toBe(true);+ expect(ok.hiveToken).toBeUndefined();+ expect(JSON.stringify(ok)).not.toContain(getHiveTokenForCli() as string);});- it('succeeds with the correct bootstrapSecret', async () => {+ it('a remote hiveToken cannot (re)initialize: init accepts only the operator secret', async () => {const token = await initHive();- expect(typeof token).toBe('string');+ const denied = (await tool('hive-mind_init').handler({ consensus: 'byzantine', hiveToken: token })) as any;+ expect(denied.success).toBe(false);});- it('re-init on an already-initialized hive is ALSO denied without the bootstrapSecret, and changes nothing (verified after a fresh state reload)', async () => {+ it('re-init on an already-initialized hive is ALSO denied without the secret, and changes nothing (verified after a fresh state reload)', async () => {await initHive();const before = readPersistedState(dir);const denied = (await tool('hive-mind_init').handler({ consensus: 'byzantine', topology: 'ring' })) as any;expect(denied.success).toBe(false);- expect(denied.error).toBe('bootstrapSecret is required');+ expect(denied.error).toMatch(/bootstrapSecret is required/);- const after = readPersistedState(dir);- expect(after).toEqual(before);+ expect(readPersistedState(dir)).toEqual(before);});- it('re-init with the correct bootstrapSecret succeeds and keeps the existing hiveToken (does not rotate it)', async () => {+ it('re-init with the correct secret succeeds and keeps the existing hiveToken (does not rotate it)', async () => {const token = await initHive();-- const reinit = (await tool('hive-mind_init').handler({- consensus: 'byzantine',- bootstrapSecret: getHiveBootstrapSecretForCli(),- })) as any;+ const reinit = (await tool('hive-mind_init').handler({ consensus: 'byzantine', bootstrapSecret: SECRET })) as any;expect(reinit.success).toBe(true);-expect(getHiveTokenForCli()).toBe(token);});});diff --git a/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts b/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.tsindex d95f90d8ea..6077bfeef0 100644--- a/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts+++ b/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts@@ -223,7 +223,7 @@ import { coordinationTools } from '../src/mcp-tools/coordination-tools.js';import { daaTools } from '../src/mcp-tools/daa-tools.js';import { embeddingsTools } from '../src/mcp-tools/embeddings-tools.js';import { githubTools } from '../src/mcp-tools/github-tools.js';-import { hiveMindTools, getHiveBootstrapSecretForCli } from '../src/mcp-tools/hive-mind-tools.js';+import { hiveMindTools } from '../src/mcp-tools/hive-mind-tools.js';import { memoryTools } from '../src/mcp-tools/memory-tools.js';import { neuralTools } from '../src/mcp-tools/neural-tools.js';import { performanceTools } from '../src/mcp-tools/performance-tools.js';@@ -725,7 +725,7 @@ describe('MCP Tools Deep Test Suite', () => {describe('Hive Mind Tools - Handler Invocation', () => {it('hive-mind_init initializes the hive', async () => {const tool = hiveMindTools.find(t => t.name === 'hive-mind_init')!;- const result: any = await tool.handler({ topology: 'mesh', bootstrapSecret: getHiveBootstrapSecretForCli() });+ const result: any = await tool.handler({ topology: 'mesh' });expect(result.success).toBe(true);expect(result.topology).toBe('mesh');});diff --git a/v3/@claude-flow/cli/bin/cli.js b/v3/@claude-flow/cli/bin/cli.jsindex bbcf42aab3..0c112b0f56 100755--- a/v3/@claude-flow/cli/bin/cli.js+++ b/v3/@claude-flow/cli/bin/cli.js@@ -301,7 +301,7 @@ if (isMCPMode) {}try {- const result = await callMCPTool(toolName, toolParams, { sessionId });+ const result = await callMCPTool(toolName, toolParams, { sessionId, transport: 'stdio' });// Failed task outcomes are data; an explicit handler error is a tool failure.const isError = result !== null && typeof result === 'object'&& typeof result.error === 'string' && result.error.trim().length > 0;diff --git a/v3/@claude-flow/cli/bin/mcp-server.js b/v3/@claude-flow/cli/bin/mcp-server.jsindex 5991bd054c..6f3944da84 100755--- a/v3/@claude-flow/cli/bin/mcp-server.js+++ b/v3/@claude-flow/cli/bin/mcp-server.js@@ -190,7 +190,7 @@ async function handleMessage(message) {}try {- const result = await callMCPTool(toolName, toolParams, { sessionId });+ const result = await callMCPTool(toolName, toolParams, { sessionId, transport: 'stdio' });return {jsonrpc: '2.0',id: message.id,diff --git a/v3/@claude-flow/cli/src/commands/hive-mind.ts b/v3/@claude-flow/cli/src/commands/hive-mind.tsindex 2117ec3612..674f02f8bc 100644--- a/v3/@claude-flow/cli/src/commands/hive-mind.ts+++ b/v3/@claude-flow/cli/src/commands/hive-mind.ts@@ -15,7 +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 { getHiveTokenForCli, getHiveBootstrapSecretForCli } from '../mcp-tools/hive-mind-tools.js';+import { getHiveTokenForCli } from '../mcp-tools/hive-mind-tools.js';// Worker type definitions for prompt generationinterface HiveWorker {@@ -495,8 +495,7 @@ const initCommand: Command = {consensus: consensus || 'byzantine',maxAgents: ctx.flags.maxAgents as number || 15,persist: ctx.flags.persist as boolean,- memoryBackend: ctx.flags.memoryBackend as string || 'hybrid',- bootstrapSecret: getHiveBootstrapSecretForCli(),+ memoryBackend: ctx.flags.memoryBackend as string || 'hybrid'};output.writeln();@@ -668,7 +667,6 @@ const spawnCommand: Command = {role,agentType,prefix,- hiveToken: getHiveTokenForCli(),});// Check for errors from MCP tool@@ -1111,7 +1109,6 @@ const optimizeMemoryCommand: Command = {}>('hive-mind_optimize-memory', {aggressive,qualityThreshold: threshold,- hiveToken: getHiveTokenForCli(),});spinner.succeed('Memory optimized');@@ -1236,7 +1233,7 @@ const broadcastCommand: Command = {const message = ctx.args.join(' ') || ctx.flags.message as string;if (!message) { output.printError('Message required. Use --message or -m flag.'); return { success: false, exitCode: 1 }; }try {- const result = await callMCPTool<{ success: boolean; messageId: string; recipients: number; error?: string }>('hive-mind_broadcast', { message, priority: ctx.flags.priority, fromId: ctx.flags.from, hiveToken: getHiveTokenForCli() });+ const result = await callMCPTool<{ success: boolean; messageId: string; recipients: number; error?: string }>('hive-mind_broadcast', { message, priority: ctx.flags.priority, fromId: ctx.flags.from });if (!result.success) { output.printError(result.error || 'Failed'); return { success: false, exitCode: 1 }; }output.printSuccess(`Message broadcast to ${result.recipients} workers (ID: ${result.messageId})`);return { success: true, data: result };@@ -1260,7 +1257,7 @@ const memorySubCommand: Command = {if ((action === 'get' || action === 'delete') && !key) { output.printError('Key required for get/delete.'); return { success: false, exitCode: 1 }; }if (action === 'set' && (!key || value === undefined)) { output.printError('Key and value required for set.'); return { success: false, exitCode: 1 }; }try {- const result = await callMCPTool<Record<string, unknown>>('hive-mind_memory', { action, key, value, hiveToken: getHiveTokenForCli() });+ const result = await callMCPTool<Record<string, unknown>>('hive-mind_memory', { action, key, value });if (ctx.flags.format === 'json') { output.printJson(result); return { success: true, data: result }; }if (action === 'list') {const keys = (result.keys as string[]) || [];@@ -1327,7 +1324,6 @@ const shutdownCommand: Command = {}>('hive-mind_shutdown', {force,saveState,- hiveToken: getHiveTokenForCli(),});spinner.succeed('Hive mind shutdown complete');diff --git a/v3/@claude-flow/cli/src/commands/mcp.ts b/v3/@claude-flow/cli/src/commands/mcp.tsindex 40291b85fc..2eec63793b 100644--- a/v3/@claude-flow/cli/src/commands/mcp.ts+++ b/v3/@claude-flow/cli/src/commands/mcp.ts@@ -670,6 +670,7 @@ const execCommand: Command = {const startTime = performance.now();const result = await callMCPTool(tool, params, {sessionId: `cli-${Date.now().toString(36)}`,+ transport: 'cli',requestId: `exec-${Date.now()}`,});const duration = performance.now() - startTime;diff --git a/v3/@claude-flow/cli/src/mcp-server.ts b/v3/@claude-flow/cli/src/mcp-server.tsindex 5b6fc562a2..1d53869b38 100644--- a/v3/@claude-flow/cli/src/mcp-server.ts+++ b/v3/@claude-flow/cli/src/mcp-server.ts@@ -848,7 +848,7 @@ export class MCPServerManager extends EventEmitter {}try {- const result = await callMCPTool(toolName, toolParams, { sessionId });+ const result = await callMCPTool(toolName, toolParams, { sessionId, transport: 'stdio' });const isError = hasToolError(result);trackRequest(toolName, !isError);return {@@ -936,7 +936,7 @@ export class MCPServerManager extends EventEmitter {const result = await callMCPTool(tool.name,(input as Record<string, unknown>) || {},- { sessionId: context?.sessionId || fallbackSessionId }+ { sessionId: context?.sessionId || fallbackSessionId, transport: this.options.transport === 'websocket' ? 'websocket' : 'http' });trackRequest(tool.name, !hasToolError(result));return result;diff --git a/v3/@claude-flow/cli/src/mcp-tools/hive-mind-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hive-mind-tools.tsindex 5ca0c43b2d..de7e4e786e 100644--- a/v3/@claude-flow/cli/src/mcp-tools/hive-mind-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/hive-mind-tools.ts@@ -4,9 +4,9 @@* Tool definitions for collective intelligence and swarm coordination.*/-import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';+import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, chmodSync, unlinkSync } from 'node:fs';import { join } from 'node:path';-import { randomBytes, timingSafeEqual } from 'node:crypto';+import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';import { type MCPTool, getProjectCwd } from './types.js';import { validateIdentifier, validateText } from './validate-input.js';@@ -31,13 +31,12 @@ interface HiveState {electedAt: string;term: number;};- // Capability token minted by hive-mind_init. join/leave/vote all require- // it (see requireHiveToken below) -- previously these mutated state.workers- // and proposal.votes for any caller, with nothing standing between an- // unauthenticated MCP caller and the hive's membership/consensus state.- // Undefined means no token was ever minted (state predates this field, or- // the hive was never initialized): fail-closed, not fail-open -- no token- // means no caller is authorized, not "any caller is".+ // Capability token minted by hive-mind_init and stored in state.json+ // (0600). It is NEVER returned by a tool response (ADR-476). Remote+ // callers may present it (or the operator bootstrap secret) to the gated+ // tools -- see authorizeHive(); local stdio/CLI callers need no credential.+ // Undefined means no token was ever minted: a remote caller then has only+ // the bootstrap secret to authenticate with, never "any caller".hiveToken?: string;workers: string[];consensus: {@@ -169,100 +168,128 @@ function tryResolveProposal(}/**- * Verify a caller-supplied hiveToken against the one minted by hive-mind_init,- * using a constant-time comparison (bearer-token capability check -- callers- * that never joined, and callers that guess/omit the token, get identical- * rejection). Returns an error string on failure, or null on success.+ * ADR-476: hive-mind caller authorization.+ *+ * The trust decision is made from the SERVER-SIDE `context` the dispatcher+ * builds (never from a tool argument an injected agent could forge):+ *+ * - `context` absent -> in-process call (CLI subcommands, library, tests): local+ * - `context.transport` -> 'stdio' | 'cli': local (same user, same machine)+ * - anything else -> remote ('http', 'websocket', or a context that+ * names no transport): fail closed+ * - RUFLO_HIVE_REQUIRE_AUTH=1 -> every caller is treated as remote+ *+ * Local callers need no credential. Remote callers must present the operator's+ * secret out of band: `bootstrapSecret` (any gated tool) or the hive's+ * `hiveToken` (every gated tool except hive-mind_init). Neither value is ever+ * returned by a tool response or written to a log.+ *+ * Honest limit: a local caller (including a prompt-injected agent) can read the+ * same files, so for local callers this is not a boundary -- it matters when the+ * MCP surface is reachable by someone who cannot read the project directory.*/-function requireHiveToken(state: HiveState, suppliedToken: unknown): string | null {- if (!state.hiveToken) {- return 'Hive-mind has no capability token minted (re-run hive-mind_init)';- }- if (typeof suppliedToken !== 'string' || !suppliedToken) {- return 'hiveToken is required';- }- const expected = Buffer.from(state.hiveToken, 'utf-8');- const actual = Buffer.from(suppliedToken, 'utf-8');- if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {- return 'Invalid hiveToken';- }- return null;+type HiveCaller = 'local' | 'remote';++const LOCAL_TRANSPORTS = new Set(['stdio', 'cli']);+const MIN_ENV_SECRET_LENGTH = 16;+const BOOTSTRAP_FILE = 'bootstrap.secret';++function classifyCaller(context: Record<string, unknown> | undefined): HiveCaller {+ if (process.env.RUFLO_HIVE_REQUIRE_AUTH === '1') return 'remote';+ if (context === undefined || context === null) return 'local';+ const transport = context.transport;+ return typeof transport === 'string' && LOCAL_TRANSPORTS.has(transport) ? 'local' : 'remote';}/**- * Read the current hiveToken directly off disk, for same-machine callers- * that already have filesystem access to hive state (the CLI's own- * `hive-mind join/leave/consensus` subcommands) -- NOT exposed over any MCP- * tool response (in particular, not hive-mind_status), since that's a- * remote-reachable surface a capability token must not leak through.+ * Constant-time string equality. Both sides are hashed first so the compare is+ * over fixed-length digests: no early exit and no length side channel.*/-export function getHiveTokenForCli(): string | undefined {- return loadHiveState().hiveToken;+function constantTimeEqual(expected: string, supplied: string): boolean {+ const a = createHash('sha256').update(expected, 'utf-8').digest();+ const b = createHash('sha256').update(supplied, 'utf-8').digest();+ return timingSafeEqual(a, b);}-const BOOTSTRAP_FILE = 'bootstrap.secret';-function getBootstrapSecretPath(): string {return join(getHiveDir(), BOOTSTRAP_FILE);}/**- * Lazily creates (0600, same-machine-only) and reads the bootstrap secret- * gating hive-mind_init itself. Fixes the gap review found in #3339 round 1:- * requireHiveToken alone does not "establish authorization" while the- * credential-issuance point (hive-mind_init) is reachable by anyone --- * previously ANY caller, including one with zero prior standing, could call- * hive-mind_init (fresh bootstrap or re-init) and either mint the very- * first token themselves or receive the current one back in the response,- * defeating every requireHiveToken gate at the source.- *- * The fix follows the same trust boundary getHiveTokenForCli() already- * relies on: same-machine filesystem access. This file is created on first- * touch and never returned to a caller who cannot already read it directly- * (requireBootstrapSecret only ever compares against it, never echoes it- * back on failure), so a pure MCP caller with no filesystem access to the- * project directory -- the actual "unauthenticated" case in this codebase's- * threat model, same as the one getHiveTokenForCli() itself relies on --- * can never produce it and can never call hive-mind_init at all, first-time- * bootstrap included.+ * Operator secret: env `RUFLO_HIVE_BOOTSTRAP_SECRET` wins (>= 16 chars), else+ * the 0600 file. Read-only: never creates anything.*/-function getOrCreateBootstrapSecret(): string {- ensureHiveDir();- const path = getBootstrapSecretPath();+function readBootstrapSecret(): string | undefined {+ const fromEnv = process.env.RUFLO_HIVE_BOOTSTRAP_SECRET?.trim();+ if (fromEnv && fromEnv.length >= MIN_ENV_SECRET_LENGTH) return fromEnv;try {+ const path = getBootstrapSecretPath();if (existsSync(path)) {- const existing = readFileSync(path, 'utf-8').trim();- if (existing) return existing;+ const fromFile = readFileSync(path, 'utf-8').trim();+ if (fromFile) return fromFile;}} catch {- // fall through to (re)creating it+ // unreadable file == no secret configured}- const secret = randomBytes(32).toString('hex');- writeFileSync(path, secret, { encoding: 'utf-8', mode: 0o600 });- return secret;+ return undefined;}-/** Same-machine accessor for the CLI's own `hive-mind init` subcommand. */-export function getHiveBootstrapSecretForCli(): string {- return getOrCreateBootstrapSecret();+/**+ * Create the 0600 secret file if neither env nor file provides one. Only local+ * callers ever reach this (hive-mind_init, local path). Returns nothing: the+ * value is never handed to a caller.+ */+function ensureBootstrapSecret(): void {+ if (readBootstrapSecret()) return;+ ensureHiveDir();+ try {+ writeFileSync(getBootstrapSecretPath(), randomBytes(32).toString('hex'), {+ encoding: 'utf-8',+ mode: 0o600,+ flag: 'wx', // never clobber a secret another process just created+ });+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;+ }}/**- * Gates hive-mind_init itself (both first-time bootstrap and re-init) --- * see getOrCreateBootstrapSecret() for why this is the real fix, not- * requireHiveToken alone. Never leaks the expected secret on denial.+ * Authorize a caller for a gated hive-mind operation. Returns an error string+ * on denial, null on success. Denial text never contains either credential.*/-function requireBootstrapSecret(suppliedSecret: unknown): string | null {- const expectedStr = getOrCreateBootstrapSecret();- if (typeof suppliedSecret !== 'string' || !suppliedSecret) {- return 'bootstrapSecret is required';+function authorizeHive(+ state: HiveState | undefined,+ input: Record<string, unknown>,+ context: Record<string, unknown> | undefined,+ opts: { allowToken?: boolean } = {},+): string | null {+ if (classifyCaller(context) === 'local') return null;++ const secret = readBootstrapSecret();+ const suppliedSecret = typeof input.bootstrapSecret === 'string' ? input.bootstrapSecret : '';+ if (secret && suppliedSecret && constantTimeEqual(secret, suppliedSecret)) return null;++ const allowToken = opts.allowToken !== false;+ const suppliedToken = typeof input.hiveToken === 'string' ? input.hiveToken : '';+ if (allowToken && state?.hiveToken && suppliedToken && constantTimeEqual(state.hiveToken, suppliedToken)) {+ return null;}- const expected = Buffer.from(expectedStr, 'utf-8');- const actual = Buffer.from(suppliedSecret, 'utf-8');- if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {- return 'Invalid bootstrapSecret';++ if (!suppliedSecret && !suppliedToken) {+ return allowToken+ ? 'hiveToken is required (remote callers must present the operator credential: hiveToken or bootstrapSecret; local stdio/CLI callers are exempt; see ADR-476)'+ : 'bootstrapSecret is required (remote callers must present the operator secret; set RUFLO_HIVE_BOOTSTRAP_SECRET on the server; see ADR-476)';}- return null;+ return suppliedSecret ? 'Invalid bootstrapSecret' : 'Invalid hiveToken';+}++/**+ * Read the current hiveToken directly off disk, for same-machine callers+ * (the CLI's own `hive-mind join/leave/consensus` subcommands) -- NOT exposed+ * over any MCP tool response.+ */+export function getHiveTokenForCli(): string | undefined {+ return loadHiveState().hiveToken;}function getHiveDir(): string {@@ -276,8 +303,11 @@ function getHivePath(): string {function ensureHiveDir(): void {const dir = getHiveDir();if (!existsSync(dir)) {- mkdirSync(dir, { recursive: true });+ mkdirSync(dir, { recursive: true, mode: 0o700 });}+ // The directory holds the capability token and operator secret: owner-only.+ // Best effort (no-op on Windows, may fail on a directory we do not own).+ try { chmodSync(dir, 0o700); } catch { /* not ours / unsupported */ }}function loadHiveState(): HiveState {@@ -304,7 +334,19 @@ function loadHiveState(): HiveState {function saveHiveState(state: HiveState): void {ensureHiveDir();state.updatedAt = new Date().toISOString();- writeFileSync(getHivePath(), JSON.stringify(state, null, 2), 'utf-8');+ // state.json embeds hiveToken: write it owner-only (0600) and atomically+ // (temp file in the same directory, then rename) so a reader never sees a+ // half-written file and the token is never briefly world-readable.+ const path = getHivePath();+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;+ try {+ writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf-8', mode: 0o600, flag: 'wx' });+ try { chmodSync(tmp, 0o600); } catch { /* unsupported */ }+ renameSync(tmp, path);+ } catch (err) {+ try { unlinkSync(tmp); } catch { /* already gone */ }+ throw err;+ }}// Import agent store helpers for spawn functionality@@ -340,11 +382,11 @@ export const hiveMindTools: MCPTool[] = [role: { type: 'string', enum: ['worker', 'specialist', 'scout'], description: 'Worker role in hive', default: 'worker' },agentType: { type: 'string', description: 'Agent type for spawned workers', default: 'worker' },prefix: { type: 'string', description: 'Prefix for worker IDs', default: 'hive-worker' },- hiveToken: { type: 'string', description: 'Capability token minted by hive-mind_init' },+ hiveToken: { type: 'string', description: 'Remote/HTTP callers only: hive capability token (read from the server, never returned by tools). Local stdio/CLI callers omit it. See ADR-476.' },+ bootstrapSecret: { type: 'string', description: 'Remote/HTTP callers only: operator secret (alternative to hiveToken). See ADR-476.' },},- required: ['hiveToken'],},- handler: async (input) => {+ handler: async (input, context) => {const state = loadHiveState();if (!state.initialized) {@@ -357,7 +399,7 @@ export const hiveMindTools: MCPTool[] = [// gate, an unauthenticated caller could mint arbitrary "workers" here// and then vote as them -- bypassing #3291's join/leave/vote Sybil// fix entirely via this sibling tool. No token, no spawn.- const tokenError = requireHiveToken(state, input.hiveToken);+ const tokenError = authorizeHive(state, input, context);if (tokenError) {return { success: false, error: tokenError };}@@ -430,18 +472,21 @@ export const hiveMindTools: MCPTool[] = [description: 'Consensus strategy. Default: raft (anti-drift). Use byzantine for f<n/3 fault tolerance.',},queenId: { type: 'string', description: 'Initial queen agent ID' },- bootstrapSecret: { type: 'string', description: 'Same-machine bootstrap credential (see hive-mind_init doctor/CLI docs) -- required for both first-time init and re-init' },+ bootstrapSecret: { type: 'string', description: 'Operator secret (RUFLO_HIVE_BOOTSTRAP_SECRET or .claude-flow/hive-mind/bootstrap.secret). Only needed by remote/HTTP callers; local stdio/CLI callers omit it. See ADR-476.' },},- required: ['bootstrapSecret'],},- handler: async (input) => {- // Fail-closed: gates hive-mind_init itself, first-time bootstrap- // included -- see getOrCreateBootstrapSecret()'s doc comment for why- // requireHiveToken on the other tools isn't sufficient on its own.- const bootstrapError = requireBootstrapSecret(input.bootstrapSecret);+ handler: async (input, context) => {+ // ADR-476: init is the credential-issuance point, so it is gated too+ // (first-time bootstrap and re-init alike). hiveToken is not accepted+ // here: only the operator secret may (re)initialize a hive remotely.+ const bootstrapError = authorizeHive(undefined, input, context, { allowToken: false });if (bootstrapError) {return { success: false, error: bootstrapError };}+ // Local first init materialises the 0600 operator secret so a later+ // remote/HTTP deployment has something to be told out of band. The+ // value is never returned.+ if (classifyCaller(context) === 'local') ensureBootstrapSecret();if (input.queenId) { const v = validateIdentifier(input.queenId as string, 'queenId'); if (!v.valid) return { success: false, error: v.error }; }@@ -604,11 +649,12 @@ export const hiveMindTools: MCPTool[] = [properties: {agentId: { type: 'string', description: 'Agent ID to join' },role: { type: 'string', enum: ['worker', 'specialist', 'scout'], description: 'Agent role in hive' },- hiveToken: { type: 'string', description: 'Capability token minted by hive-mind_init' },+ hiveToken: { type: 'string', description: 'Remote/HTTP callers only: hive capability token (read from the server, never returned by tools). Local stdio/CLI callers omit it. See ADR-476.' },+ bootstrapSecret: { type: 'string', description: 'Remote/HTTP callers only: operator secret (alternative to hiveToken). See ADR-476.' },},- required: ['agentId', 'hiveToken'],+ required: ['agentId'],},- handler: async (input) => {+ handler: async (input, context) => {const state = loadHiveState();const agentId = input.agentId as string;@@ -621,7 +667,7 @@ export const hiveMindTools: MCPTool[] = [// Fail-closed: an unrecognized/missing token makes no membership// change at all -- state.workers is untouched, not just left// unsaved (the write below never happens on this path).- const tokenError = requireHiveToken(state, input.hiveToken);+ const tokenError = authorizeHive(state, input, context);if (tokenError) {return { success: false, agentId, error: tokenError };}@@ -648,11 +694,12 @@ export const hiveMindTools: MCPTool[] = [type: 'object',properties: {agentId: { type: 'string', description: 'Agent ID to remove' },- hiveToken: { type: 'string', description: 'Capability token minted by hive-mind_init' },+ hiveToken: { type: 'string', description: 'Remote/HTTP callers only: hive capability token (read from the server, never returned by tools). Local stdio/CLI callers omit it. See ADR-476.' },+ bootstrapSecret: { type: 'string', description: 'Remote/HTTP callers only: operator secret (alternative to hiveToken). See ADR-476.' },},- required: ['agentId', 'hiveToken'],+ required: ['agentId'],},- handler: async (input) => {+ handler: async (input, context) => {const state = loadHiveState();const agentId = input.agentId as string;@@ -660,7 +707,7 @@ export const hiveMindTools: MCPTool[] = [// Fail-closed: a denied caller makes no membership change -- the// splice/save below is unreachable on this path.- const tokenError = requireHiveToken(state, input.hiveToken);+ const tokenError = authorizeHive(state, input, context);if (tokenError) {return { success: false, agentId, error: tokenError };}@@ -693,7 +740,8 @@ export const hiveMindTools: MCPTool[] = [value: { description: 'Proposal value (for propose)' },vote: { type: 'boolean', description: 'Vote (true=for, false=against)' },voterId: { type: 'string', description: 'Voter agent ID' },- hiveToken: { type: 'string', description: 'Capability token minted by hive-mind_init (required to vote)' },+ hiveToken: { type: 'string', description: 'Remote/HTTP callers only: hive capability token (read from the server, never returned by tools). Local stdio/CLI callers omit it. See ADR-476.' },+ bootstrapSecret: { type: 'string', description: 'Remote/HTTP callers only: operator secret (alternative to hiveToken). See ADR-476.' },strategy: { type: 'string', enum: ['bft', 'raft', 'quorum'], description: 'Consensus strategy (default: raft)' },quorumPreset: { type: 'string', enum: ['unanimous', 'majority', 'supermajority'], description: 'Quorum threshold preset (for quorum strategy, default: majority)' },term: { type: 'number', description: 'Term number (for raft strategy)' },@@ -701,7 +749,7 @@ export const hiveMindTools: MCPTool[] = [},required: ['action'],},- handler: async (input) => {+ handler: async (input, context) => {if (input.proposalId) { const v = validateIdentifier(input.proposalId as string, 'proposalId'); if (!v.valid) return { action: input.action, error: v.error }; }if (input.voterId) { const v = validateIdentifier(input.voterId as string, 'voterId'); if (!v.valid) return { action: input.action, error: v.error }; }if (input.type) { const v = validateText(input.type as string, 'type'); if (!v.valid) return { action: input.action, error: v.error }; }@@ -717,7 +765,7 @@ export const hiveMindTools: MCPTool[] = [// legitimate workers to vote on, or exhaust raft's one-pending-// proposal-per-term slot as a denial-of-service. No token, no// proposal recorded.- const proposeTokenError = requireHiveToken(state, input.hiveToken);+ const proposeTokenError = authorizeHive(state, input, context);if (proposeTokenError) {return { action, error: proposeTokenError };}@@ -790,7 +838,7 @@ export const hiveMindTools: MCPTool[] = [// Fail-closed: a denied caller records no vote at all -- the// votes[voterId] write below is unreachable on this path, and// nothing about the proposal (vote tallies, status) changes.- const tokenError = requireHiveToken(state, input.hiveToken);+ const tokenError = authorizeHive(state, input, context);if (tokenError) {return { action, error: tokenError, proposalId: proposal.proposalId };}@@ -1043,11 +1091,12 @@ export const hiveMindTools: MCPTool[] = [message: { type: 'string', description: 'Message to broadcast' },priority: { type: 'string', enum: ['low', 'normal', 'high', 'critical'], description: 'Message priority' },fromId: { type: 'string', description: 'Sender agent ID' },- hiveToken: { type: 'string', description: 'Capability token minted by hive-mind_init' },+ hiveToken: { type: 'string', description: 'Remote/HTTP callers only: hive capability token (read from the server, never returned by tools). Local stdio/CLI callers omit it. See ADR-476.' },+ bootstrapSecret: { type: 'string', description: 'Remote/HTTP callers only: operator secret (alternative to hiveToken). See ADR-476.' },},- required: ['message', 'hiveToken'],+ required: ['message'],},- handler: async (input) => {+ handler: async (input, context) => {const state = loadHiveState();if (!state.initialized) {@@ -1057,7 +1106,7 @@ export const hiveMindTools: MCPTool[] = [// Fail-closed: no token, no message stored -- otherwise any caller// could inject spoofed broadcasts (arbitrary fromId) into shared// memory that every real worker reads.- const tokenError = requireHiveToken(state, input.hiveToken);+ const tokenError = authorizeHive(state, input, context);if (tokenError) {return { success: false, error: tokenError };}@@ -1099,11 +1148,11 @@ export const hiveMindTools: MCPTool[] = [properties: {graceful: { type: 'boolean', description: 'Graceful shutdown (wait for pending tasks)', default: true },force: { type: 'boolean', description: 'Force immediate shutdown', default: false },- hiveToken: { type: 'string', description: 'Capability token minted by hive-mind_init' },+ hiveToken: { type: 'string', description: 'Remote/HTTP callers only: hive capability token (read from the server, never returned by tools). Local stdio/CLI callers omit it. See ADR-476.' },+ bootstrapSecret: { type: 'string', description: 'Remote/HTTP callers only: operator secret (alternative to hiveToken). See ADR-476.' },},- required: ['hiveToken'],},- handler: async (input) => {+ handler: async (input, context) => {const state = loadHiveState();if (!state.initialized) {@@ -1113,7 +1162,7 @@ export const hiveMindTools: MCPTool[] = [// Fail-closed: no token, no shutdown -- otherwise any caller could// terminate a running hive (wiping workers/pending consensus/shared// memory) as a denial-of-service with zero proof of membership.- const tokenError = requireHiveToken(state, input.hiveToken);+ const tokenError = authorizeHive(state, input, context);if (tokenError) {return { success: false, error: tokenError };}@@ -1175,11 +1224,12 @@ export const hiveMindTools: MCPTool[] = [action: { type: 'string', enum: ['get', 'set', 'delete', 'list'], description: 'Memory action' },key: { type: 'string', description: 'Memory key' },value: { description: 'Value to store (for set)' },- hiveToken: { type: 'string', description: 'Capability token minted by hive-mind_init (required for set/delete)' },+ hiveToken: { type: 'string', description: 'Remote/HTTP callers only: hive capability token (read from the server, never returned by tools). Local stdio/CLI callers omit it. See ADR-476.' },+ bootstrapSecret: { type: 'string', description: 'Remote/HTTP callers only: operator secret (alternative to hiveToken). See ADR-476.' },},required: ['action'],},- handler: async (input) => {+ handler: async (input, context) => {if (input.key) { const v = validateIdentifier(input.key as string, 'key'); if (!v.valid) return { action: input.action, error: v.error }; }const state = loadHiveState();@@ -1202,7 +1252,7 @@ export const hiveMindTools: MCPTool[] = [// tamper with or inject entries into shared memory every worker// and the queen read, the same attack class hive-mind_broadcast// was gated for.- const tokenError = requireHiveToken(state, input.hiveToken);+ const tokenError = authorizeHive(state, input, context);if (tokenError) {return { action, key, error: tokenError };}@@ -1230,7 +1280,7 @@ export const hiveMindTools: MCPTool[] = [if (action === 'delete') {if (!key) return { action, error: 'Key required' };// Fail-closed, same reasoning as 'set' above.- const tokenError = requireHiveToken(state, input.hiveToken);+ const tokenError = authorizeHive(state, input, context);if (tokenError) {return { action, key, error: tokenError };}@@ -1268,18 +1318,18 @@ export const hiveMindTools: MCPTool[] = [type: 'object',properties: {qualityThreshold: { type: 'number', description: 'Quality threshold for pattern retention (advisory — not enforced yet)' },- hiveToken: { type: 'string', description: 'Capability token minted by hive-mind_init' },+ hiveToken: { type: 'string', description: 'Remote/HTTP callers only: hive capability token (read from the server, never returned by tools). Local stdio/CLI callers omit it. See ADR-476.' },+ bootstrapSecret: { type: 'string', description: 'Remote/HTTP callers only: operator secret (alternative to hiveToken). See ADR-476.' },},- required: ['hiveToken'],},- handler: async (input) => {+ handler: async (input, context) => {const t0 = Date.now();const state = loadHiveState();if (!state.initialized) return { optimized: false, error: 'Hive-mind not initialized', before: { patterns: 0, memory: '0' }, after: { patterns: 0, memory: '0' }, removed: 0, consolidated: 0, timeMs: 0 };// Fail-closed: no token, no prune -- this mutates state.sharedMemory// via the same saveHiveState() path set/delete/broadcast were gated// for (found in round 2 review, #3339).- const tokenError = requireHiveToken(state, input.hiveToken);+ const tokenError = authorizeHive(state, input, context);if (tokenError) {return { optimized: false, error: tokenError, before: { patterns: 0, memory: '0' }, after: { patterns: 0, memory: '0' }, removed: 0, consolidated: 0, timeMs: 0 };}diff --git a/v3/docs/adr/ADR-476-hive-mind-gating.md b/v3/docs/adr/ADR-476-hive-mind-gating.mdnew file mode 100644index 0000000000..2df60f9fa7--- /dev/null+++ b/v3/docs/adr/ADR-476-hive-mind-gating.md@@ -0,0 +1,77 @@+# ADR 476: Hive-Mind Gating That Does Not Break Local Users++Status: Accepted++Date: 2026 10 07++Related: #3338 (issue), #3339 (this PR), #3291 (join/leave/vote token), #3599 (HTTP MCP tool authorization)++## Context++`hive-mind_init` returned `hiveToken` to any caller, and `hive-mind_spawn`, `hive-mind_consensus` (`propose`), `hive-mind_broadcast`, `hive-mind_shutdown`, `hive-mind_memory` (`set`/`delete`) and `hive-mind_optimize-memory` required no credential. `spawn` appends to `state.workers`, which `vote` treats as the voting roster, so an unauthenticated caller could mint voters (the Sybil path #3291 meant to close). `state.json`, which holds the token, was written with default permissions.++Severity is medium. The exposure exists only when the MCP surface is reachable by someone who cannot already read the project directory, which in practice means the HTTP or WebSocket transport (tracked separately in #3599). A stdio MCP server and the CLI run as the user who owns the files.++The first version of the fix (round 1 and 2 of #3339) gated every tool on a token and made `hive-mind_init` demand a file-based `bootstrapSecret` as a tool argument. That closed the hole and broke existing users: an MCP-only stdio client could never init, spawn or join (it has no way to read the secret and init no longer returned the token), and `hive-mind-work.test.ts` failed.++## Decision++Authorize by caller class, taken from the server-built `context.transport`, never from a tool argument.++| Caller | How classified | Credential |+|---|---|---|+| In-process call (CLI subcommands, library, tests) | no `context` | none |+| stdio MCP server | `transport: 'stdio'` | none |+| `ruflo mcp exec` | `transport: 'cli'` | none |+| HTTP / WebSocket MCP | `transport: 'http' \| 'websocket'` | operator credential |+| A context that names no transport, or an unknown one | anything else | operator credential (fail closed) |+| Any caller with `RUFLO_HIVE_REQUIRE_AUTH=1` | env | operator credential |++The operator credential is, for every gated tool, `bootstrapSecret`; for every gated tool except `hive-mind_init`, the hive's `hiveToken` is accepted as well. `hive-mind_init` accepts only the secret, because it is the credential-issuance point.++Secret sources, in order: env `RUFLO_HIVE_BOOTSTRAP_SECRET` (at least 16 characters, otherwise ignored), then `.claude-flow/hive-mind/bootstrap.secret`. The file is created (0600, `wx`, never overwritten) by the first local `hive-mind init`, whether through the CLI or a stdio MCP client. A remote call never creates it.++Hardening that applies to everyone:++- No tool response, denial message or log line contains the token or the secret. `hive-mind_init` no longer returns `hiveToken`. Local clients do not need it.+- `state.json` is written 0600 through a same-directory temp file and `rename`, so it is atomic and never briefly world-readable. A pre-existing 0644 file is tightened on the next write. The hive directory is 0700.+- Comparison is constant time over SHA-256 digests, so supplied length is not observable.+- Gated tools: `init`, `join`, `leave`, `spawn`, `consensus` (`propose`, `vote`), `broadcast`, `shutdown`, `memory` (`set`, `delete`), `optimize-memory`.++### Behaviour matrix++| Caller | No credential | Wrong secret/token | Operator secret | hiveToken |+|---|---|---|---|---|+| Local (in-process, stdio, cli) | allowed | allowed | allowed | allowed |+| Remote (http, websocket, unknown) | refused | refused | allowed | allowed (not for `init`) |+| Remote, no secret configured on the server | refused | refused | refused | allowed (not for `init`) |+| Strict mode (`RUFLO_HIVE_REQUIRE_AUTH=1`), any transport | refused | refused | allowed | allowed (not for `init`) |++## Alternatives considered++- **Token and secret required for everyone, secret only in a file (the earlier PR).** Rejected: it breaks every MCP-only client and gives no gain against a caller who can read the file.+- **Keep returning `hiveToken` from `init` to local callers.** Rejected: the requirement is that a tool response never carries a credential, and local callers do not need one.+- **A legacy "ungated" flag for one release.** Not added. Local callers are not broken, so there is nothing to keep open for them. The only users who lose behaviour are remote HTTP callers who relied on the unauthenticated hole, and they must lose it. They have one step: set `RUFLO_HIVE_BOOTSTRAP_SECRET` on the server and send it as `bootstrapSecret`.+- **Trust HTTP on loopback.** Rejected: a browser or any local process can reach loopback, and #3599 owns HTTP authentication.++## Limits (stated plainly)++- For local callers this is not a security boundary. A prompt-injected agent in the same session can read `state.json` and `bootstrap.secret` from disk, and can call the stdio tools directly. The gate matters when the MCP surface is reachable by a caller that cannot read the project directory.+- If a stdio server is bridged to a network (a tunnel, `mcp-remote`, a shared ssh session), the bridge turns remote callers into "stdio" ones. Set `RUFLO_HIVE_REQUIRE_AUTH=1` on such servers.+- `hive-mind_status`, `hive-mind_memory` `get`/`list` and `hive-mind_consensus` `status` stay readable by any caller. They return no credential but do expose roster and shared-memory contents.+- The remote credential travels as a tool argument, so a remote agent that holds it can echo it. It is a bearer secret handed over out of band, not a per-caller identity.++## Enforcement++- `hive-mind-gate-matrix.test.ts`: caller x credential matrix for every gated tool, env override, short env secret, no-overwrite of an existing file, strict mode, constant-time digests, no token or secret in any response or console/stdout/stderr output, 0600/0700 permissions (POSIX), atomic write.+- `hive-mind-spawn-broadcast-shutdown-auth.test.ts` and `hive-mind-consensus-sybil-vote.test.ts`: the original denial assertions, now driven as a remote caller, with zero-state-change checks after a fresh reload.+- `hive-mind-gate-dispatch-contract.test.ts`: each dispatcher labels its transport, and the classifier never reads tool arguments.+- Mutation checks run on the core: always-local classification, skipped authorization, non-constant-time compare, 0644 modes, token in the `init` response, file-beats-env, no strict mode, token accepted by `init`, weak env secret. Each is caught by at least one test.++## Consequences++- Local users: no change, no extra step. `hive-mind init` now also writes `.claude-flow/hive-mind/bootstrap.secret`.+- MCP clients that read `hiveToken` from the `init` response get `undefined`. Over stdio they can omit it everywhere. Over HTTP they use the operator secret.+- Remote HTTP clients: refused until the operator sets `RUFLO_HIVE_BOOTSTRAP_SECRET` (or reads the file) and passes it as `bootstrapSecret`.+- `hive-mind_join` and `hive-mind_leave` no longer list `hiveToken` as required in their schemas.+- Semver: minor. The break is a security fix to a surface that was an unauthenticated hole.