π 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
dream(security): #3338 round 2 -- gate hive-mind_init's own credential issuance, close optimize-memory gap
Claude046c4b8ed0dc
diff --git a/docs/dream-cycle/dream-gist-2026-09-16.md b/docs/dream-cycle/dream-gist-2026-09-16.mdindex f55a8ad4dc..0dce388f8f 100644--- a/docs/dream-cycle/dream-gist-2026-09-16.md+++ b/docs/dream-cycle/dream-gist-2026-09-16.md@@ -3,18 +3,26 @@TL;DR: Tonight's `security` deep-dive found that PR #3291 (merged 2026-09-15, lastnight's own dream-cycle candidate) closed a Sybil-vote attack on `hive-mind_consensus`by binding `join`/`leave`/`vote` to a capability token minted by `hive-mind_init` β-but left **six sibling MCP tools in the same file mutating the exact same hive state+but left **seven sibling MCP tools in the same file mutating the exact same hive statewith no such gate**: `hive-mind_spawn` (which pushes attacker-chosen agent ids straightinto `state.workers`, the same roster `vote` treats as legitimate β letting anunauthenticated caller mint its own "workers" and then vote as them, bypassing #3291entirely via a sibling tool rather than defeating it), `hive-mind_consensus`'s `propose`-action, `hive-mind_broadcast`, `hive-mind_shutdown`, and `hive-mind_memory`'s `set`/-`delete` actions (the last pair found only by an independent adversarial critique of-the first version of tonight's fix, which covered the first four). All six now call the-same `requireHiveToken()` gate, fail-closed, with zero state change on denial (verified-by reloading `state.json` fresh off disk after each denial, simulating a process-restart). Five research roles ran in parallel tonight; three converged independently on-this finding before implementation began.+action, `hive-mind_broadcast`, `hive-mind_shutdown`, `hive-mind_memory`'s `set`/`delete`+actions, and `hive-mind_optimize-memory`. All seven now call the existing+`requireHiveToken()` gate, fail-closed, with zero state change on denial. **Round-1+review (ruvnet) correctly REJECTed the first version of this fix**: gating sibling+tools behind `requireHiveToken` doesn't "establish authorization" while the+credential-issuance point, `hive-mind_init` itself, remained 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 also requires its own same-machine `bootstrapSecret`+(a lazily-created 0600 file, the same same-machine trust boundary+`getHiveTokenForCli()` already relied on) for both first-time bootstrap and re-init,+and no longer echoes `hiveToken` in its response at all. Five research roles ran in+parallel tonight; three converged independently on the sibling-tool gap before+implementation began; the credential-issuance gap was caught by human review, not by+this session's own research or adversarial-critique passes β a real miss disclosed+here, not papered over.## What's New in 2026@@ -32,16 +40,20 @@ this finding before implementation began.`requireHiveToken()` (`hive-mind-tools.ts:177-190`) is a constant-time, fail-closedbearer-capability check against a 32-byte token minted once by `hive-mind_init` andnever exposed via `hive-mind_status`. Before tonight it gated only `join`/`leave`/-`vote` (#3291). `hive-mind_init` itself is correctly left unauthenticated by design-(#3291's own scope decision, re-verified tonight: it doesn't leak the token beyond its-own response, doesn't reset an existing token on re-init, and doesn't allow queen-hijack via re-init without prior review β that lead from tonight's swarm scan turned-out to be a duplicate of an already-considered, already-decided boundary). `.harness/-mcp-policy.json`'s `allowShell`/`allowNetwork`/`allowFileWrite: false` fields are, by-the policy's own rationale comment, scoped to the native-Claude-Code-tool layer, not-this MCP server's tool surface β independently confirmed real by two research roles-tonight (`terminal_execute` calls raw `execSync` with no policy enforcement, a second-strong candidate, see Recommended Next Steps).+`vote` (#3291). **Correction from round-1 review**: this session's initial assessment+that `hive-mind_init`'s lack of a gate was "an already-considered, already-decided+boundary" was wrong β #3291's disclosed scope note only covered *whether* to solve+bootstrap trust at all, not a considered decision that leaving it fully open was safe+once a whole gate matrix was being built around the token it issues. `hive-mind_init`+now requires its own `bootstrapSecret` (`getOrCreateBootstrapSecret()`), a lazily+created, 0600, same-machine-only file β the identical trust boundary+`getHiveTokenForCli()` already relied on β for both first-time bootstrap and re-init,+and no longer returns `hiveToken` in its response at all. `.harness/mcp-policy.json`'s+`allowShell`/`allowNetwork`/`allowFileWrite: false` fields are, by the policy's own+rationale comment, scoped to the native-Claude-Code-tool layer, not this MCP server's+tool surface β independently confirmed real by two research roles tonight+(`terminal_execute` calls raw `execSync` with no policy enforcement, a second strong+candidate, see Recommended Next Steps).## Competitor Comparison@@ -66,22 +78,29 @@ consistently to every tool that needed it.> Given the hive-mind MCP tools, where `hive-mind_join`/`leave`/`vote` already require> a `hiveToken` minted by `hive-mind_init` (#3291) to prevent Sybil-vote manipulation,> when `hive-mind_spawn`, `hive-mind_consensus`'s `propose` action, `hive-mind_broadcast`,-> `hive-mind_shutdown`, and `hive-mind_memory`'s `set`/`delete` actions are given the-> same `requireHiveToken` gate, then an unauthenticated caller should no longer be able-> to mint voting workers via spawn (bypassing the Sybil-vote fix at a sibling tool),-> inject unauthenticated consensus proposals, inject spoofed broadcast messages,-> terminate a running hive, or tamper with/erase shared-memory entries β relative to-> today's baseline where all six accept any caller with no proof of hive membership β-> subject to: (1) the CLI's own hive-mind spawn/broadcast/shutdown/memory subcommands-> pass the token via the existing `getHiveTokenForCli()` same-machine helper so-> legitimate local usage is unaffected; (2) `hive-mind_init`'s already-decided-> unauthenticated-bootstrap scope is unchanged; (3) existing hive-mind test suites-> remain green; (4) zero added LLM/API cost, fully deterministic coverage.--Frozen before evaluation began. Not modified after seeing results β one clause was-*added* mid-session (the `hive-mind_memory` set/delete gate) after an independent-adversarial critique found it as a real missed-scope gap in the first version; this is-disclosed as a scope extension, not a post-hoc weakening.+> `hive-mind_shutdown`, `hive-mind_memory`'s `set`/`delete` actions, and+> `hive-mind_optimize-memory` are given the same `requireHiveToken` gate, AND+> `hive-mind_init` itself is gated behind a same-machine `bootstrapSecret` for both+> first-time bootstrap and re-init, then an unauthenticated caller (one with no+> filesystem access to the project directory, the same "unauthenticated" boundary+> `getHiveTokenForCli()` already relies on) should no longer be able to mint voting+> workers via spawn, inject unauthenticated consensus proposals, inject spoofed+> broadcast messages, terminate a running hive, tamper with/erase shared-memory+> entries, or bootstrap/hijack a hive's credential-issuance point at all β relative to+> today's baseline where all eight accept any caller with no proof of standing β+> subject to: (1) the CLI's own hive-mind init/spawn/broadcast/shutdown/memory/+> optimize-memory subcommands pass the token/secret via the existing+> `getHiveTokenForCli()`/new `getHiveBootstrapSecretForCli()` same-machine helpers so+> legitimate local usage is unaffected; (2) existing hive-mind test suites remain+> green, extended with fresh-child-process CLI-command-level tests (not only direct+> handler calls); (3) zero added LLM/API cost, fully deterministic coverage.++Frozen before round-1 evaluation began; extended after round-1 human review (not+after this session's own evaluation) to add the `bootstrapSecret` clause and the+`hive-mind_optimize-memory` gate β both real, disclosed scope corrections in response+to a REJECT, not a post-hoc relaxation to fit a result. The `hive-mind_memory`+set/delete clause was likewise added mid-round-1 after an independent adversarial+critique found it as a missed-scope gap.## Benchmarks@@ -92,24 +111,34 @@ accepted security-surface candidate has used since 2026-08-18.## Evaluation-**evaluated: accepted.** Real evaluator: Vitest 4.1.8, deterministic, zero LLM calls,-$0 cost. New file `hive-mind-spawn-broadcast-shutdown-auth.test.ts` (12 tests) plus 3-existing `propose` calls in `hive-mind-consensus-sybil-vote.test.ts` updated to pass-the token (a legitimate adjustment given the new gate, not a loosening β diffed-byte-for-byte, no assertion changed).--Stash-isolated baseline (source reverted, tests kept): **7 of 12 new tests fail**-exactly for the six gated call sites (`spawn`, `propose`, `broadcast`, `shutdown`,-`memory.set`, `memory.delete` all previously succeeded with no token; the "succeeds-with correct token" tests pass on both sides, as expected β old behavior always let-the call through). Candidate: all 18 hive-mind tests (12 new + 6 existing) pass.--Full `@claude-flow/cli` suite (251 files, 3165 tests) run both ways via controlled-stash comparison (not raw counts alone β this suite has real run-to-run timing/flake-noise in subprocess-spawning tests, documented since 2026-08-30): failing-test-name-sets are **identical** between baseline and candidate (34 pre-existing failures, all-traced to an unbuilt `dist/src/index.js` / docker-build class, zero referencing-hive-mind). `tsc --noEmit`: 22 pre-existing errors, unrelated, byte-identical count.+**evaluated: accepted (round 2, post-REJECT).** Real evaluator: Vitest 4.1.8,+deterministic, zero LLM calls, $0 cost. Test file `hive-mind-spawn-broadcast-shutdown-+auth.test.ts` grew from 12 to 28 tests across round 1β2 (spawn/propose/broadcast/+shutdown/memory-set/memory-delete gates, `hive-mind_optimize-memory`'s gate, a+dedicated `bootstrapSecret` block covering fresh-bootstrap denial, forged-secret+denial, non-leakage of the real secret on denial, and re-init denial/acceptance, plus+two real child-process tests that spawn `node bin/cli.js hive-mind init`/`spawn` end+to end β not direct handler calls). 3 pre-existing `propose` calls in+`hive-mind-consensus-sybil-vote.test.ts`, plus one pre-existing `hive-mind_init` call+in `mcp-tools-deep.test.ts`, updated to pass the new required fields (diffed β no+assertion changed, purely additive).++Stash-isolated baseline (source reverted, tests kept): the discriminating subset of+tests fails exactly for each of the seven newly-gated tools plus every+`bootstrapSecret` scenario; "succeeds with correct token/secret" tests pass on both+sides, as expected β old behavior always let the call through. Candidate: all 28 new++ 6 existing hive-mind-consensus + 3 mcp-tools-deep hive-mind tests pass (37 total).++Two sibling packages (`@claude-flow/swarm`, `@claude-flow/neural`) were unbuilt in+this session's checkout β building them (a one-time environment fix, not a candidate+change, same class documented by multiple prior nights) let `tsc --noEmit` run fully+clean (0 errors, down from 22 pre-existing/unrelated in round 1) and let real+`bin/cli.js` child-process tests run at all. Full `@claude-flow/cli` suite (251 files,+~3432 tests once unbuilt-sibling-gated tests could run): 18 failures remain, all in+`@claude-flow/mcp`-package-resolution/http-server-startup-timing/unrelated areas,+zero referencing hive-mind β confirmed via the same controlled-comparison discipline+(failing-test-name sets, not raw counts, given this suite's documented run-to-run+timing flake).## Darwin Results@@ -124,22 +153,35 @@ Darwin to search over β same skip class as nearly every accepted night since 2No signed `@metaharness/flywheel` bundle β the schema targets LLM-task-corpus-evaluatedretrieval-policy candidates; this is a deterministic code-correctness/authenticationfix, consistent with every accepted candidate since 2026-08-18. Evidence retained as:-12 new tests + 3 adjusted tests + issue + this gist + two independent adversarial-critiques (research-phase: 3 of 5 roles converged on this finding before code was-written; evaluation-phase: a fresh subagent with no authoring context found and this-session closed the `hive-mind_memory` gap the first patch missed).+28 new tests + 4 adjusted tests + issue + this gist + PR #3339's round-1 human review+(REJECT, correctly identifying the credential-issuance gap and the missed+`hive-mind_optimize-memory` sibling) + a round-1 independent adversarial critique+(found and this session closed the `hive-mind_memory` gap the first patch missed).++**Round-1 witness was not independently reproducible** β round-1 review correctly+flagged that the receipt witness must reproduce from a preserved canonical preimage,+not an ephemeral scratch file. Verified directly: recomputing round 1's documented+procedure against the committed round-1 file did *not* reproduce the recorded round-1+witness (the SHA-256 had been computed against a `/tmp` scratch copy that no longer+exists byte-for-byte anywhere in the repository). The table below is regenerated from+this exact final file, with reproducibility verified before commit β see the script+below the table, run against this file itself, not a copy.Witness table:| Field | Value ||---|---|| Session commit | `a65bdf683a73dcc1f20d455658daab1cca07306b` |-| Gist SHA-256 (pre-witness content) | `bd92faac26c595c64bafd51ba26062ad14151483861793d98afb1f98773100cc` |-| Witness stamp | `f2dca5c7404705dd5fde38b7bbc98eb4dc49161c21e2cd73d3b61d894decc043` |+| Gist SHA-256 (pre-witness content) | `9c69e5fab39d81b71e652e80c47dccfe72c709d8a1c030df1744332505418439` |+| Witness stamp | `4c373db1631c56626dd77caedaeb1e0ed5ca9903fb31ad0c1c1eced59d9fb872` |-Verifier procedure: fetch `docs/dream-cycle/dream-gist-2026-09-16.md` from this branch,-strip the witness table's filled values back to `PENDING`, SHA-256 it, concatenate with-the session commit above, SHA-256 again β result must equal the witness stamp.+Verifier procedure (self-contained, no external state): take this exact file as+committed, replace the three `` `...` `` values in the table above with the literal+text `PENDING` (keeping every other byte, including this paragraph and everything+below it, unchanged), SHA-256 the result β must equal the Gist SHA-256 above;+concatenate that hash with the Session commit value and SHA-256 again β must equal+the Witness stamp above. This was verified by actually running that substitution+against this committed file (not a draft) before the values below were filled in.## Recommended Next Steps@@ -163,3 +205,11 @@ the session commit above, SHA-256 again β result must equal the witness stamp.verdict. Intelligence scan finding, security-adjacent, out of scope for thehive-mind-specific fix tonight; a real memory/benchmark-poisoning-shaped gap for afuture `intelligence` or `security` night.+4. **`bootstrapSecret`'s file-based mechanism is a same-machine trust boundary, not a+ cross-transport-safe credential** β adequate for the stdio/local-CLI threat model+ this fix targets (matching `getHiveTokenForCli()`'s existing precedent), but a+ future night wiring hive-mind auth through the separate HTTP/SSE MCP transport+ (`startHttpServer()`, `@claude-flow/mcp`) or through ADR-377's Ed25519+ caller-identity tokens should reconsider whether a filesystem-cookie bootstrap is+ still the right primitive once the caller isn't guaranteed to share a filesystem+ with the operator.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 373330bd3f..80101fcb11 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,13 +21,22 @@* 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 } from '../src/mcp-tools/hive-mind-tools.js';+import { hiveMindTools, getHiveTokenForCli, getHiveBootstrapSecretForCli } from '../src/mcp-tools/hive-mind-tools.js';function tool(name: string) {const t = hiveMindTools.find(t => t.name === name);@@ -60,11 +69,16 @@ 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 }) as any;+ const init = await tool('hive-mind_init').handler({+ consensus: strategy,+ bootstrapSecret: getHiveBootstrapSecretForCli(),+ }) as any;expect(init.success).toBe(true);- expect(typeof init.hiveToken).toBe('string');- expect(init.hiveToken.length).toBeGreaterThanOrEqual(32);- return init.hiveToken as string;+ expect(init.hiveToken).toBeUndefined();+ const token = getHiveTokenForCli();+ expect(typeof token).toBe('string');+ expect((token as string).length).toBeGreaterThanOrEqual(32);+ return token as string;}async function joinWorkers(token: string, count: number) {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 3bb253d94a..9ccf2c52fc 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@@ -25,18 +25,49 @@* same tool (found by an independent adversarial critique of the* first version of this fix, which covered spawn/propose/broadcast/* shutdown but missed this one).+ * - hive-mind_optimize-memory prunes shared-memory entries with no gate+ * either (found in round 2 review, #3339).*- * All six now call the same `requireHiveToken` gate join/leave/vote+ * All seven now call the same `requireHiveToken` gate join/leave/vote* already use. A denied call makes zero state change, verified below by* 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`.*/import { describe, it, expect, beforeEach, afterEach } from 'vitest';-import { mkdtempSync, rmSync, readFileSync } from 'node:fs';+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 } from '../src/mcp-tools/hive-mind-tools.js';+import { hiveMindTools, getHiveTokenForCli, getHiveBootstrapSecretForCli } from '../src/mcp-tools/hive-mind-tools.js';++const CLI = join(__dirname, '..', 'bin', 'cli.js');++function runCli(args: string[], cwd: string): { stdout: string; exit: number } {+ try {+ const stdout = execFileSync('node', [CLI, ...args], {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, CLAUDE_FLOW_CWD: cwd },+ });+ return { stdout, exit: 0 };+ } catch (err) {+ const e = err as { status?: number; stdout?: Buffer; stderr?: Buffer };+ return { stdout: (e.stdout?.toString() ?? '') + (e.stderr?.toString() ?? ''), exit: e.status ?? -1 };+ }+}function tool(name: string) {const t = hiveMindTools.find((t) => t.name === name);@@ -71,9 +102,13 @@ describe('hive-mind_spawn / consensus(propose) / broadcast / shutdown capability});async function initHive(): Promise<string> {- const init = (await tool('hive-mind_init').handler({ consensus: 'raft' })) as any;+ const init = (await tool('hive-mind_init').handler({+ consensus: 'raft',+ bootstrapSecret: getHiveBootstrapSecretForCli(),+ })) as any;expect(init.success).toBe(true);- return init.hiveToken as string;+ expect(init.hiveToken).toBeUndefined();+ return getHiveTokenForCli() as string;}it('hive-mind_spawn is denied without the token, and mints zero workers (verified after a fresh state reload)', async () => {@@ -265,4 +300,114 @@ describe('hive-mind_spawn / consensus(propose) / broadcast / shutdown capabilityconst persisted = readPersistedState(dir);expect(persisted.sharedMemory).toEqual({});});++ it('hive-mind_optimize-memory is denied without the token, and prunes nothing (verified after a fresh state reload)', async () => {+ const token = await initHive();+ await tool('hive-mind_memory').handler({ action: 'set', key: 'empty', value: null, hiveToken: token });++ const denied = (await tool('hive-mind_optimize-memory').handler({})) as any;+ expect(denied.optimized).toBe(false);+ expect(denied.error).toMatch(/hiveToken is required/);++ const persisted = readPersistedState(dir);+ expect(persisted.sharedMemory).toEqual({ empty: null });+ });++ it('hive-mind_optimize-memory succeeds with the correct token', async () => {+ const token = await initHive();+ await tool('hive-mind_memory').handler({ action: 'set', key: 'empty', value: null, hiveToken: token });++ const ok = (await tool('hive-mind_optimize-memory').handler({ hiveToken: token })) as any;+ expect(ok.removed).toBe(1);++ const persisted = readPersistedState(dir);+ expect(persisted.sharedMemory).toEqual({});+ });++ describe('hive-mind_init bootstrap-secret gate (round 2 review, #3339)', () => {+ 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(existsSync(join(dir, '.claude-flow', 'hive-mind', 'state.json'))).toBe(false);+ });++ it('is denied with a forged bootstrapSecret, and mints no hive', async () => {+ const denied = (await tool('hive-mind_init').handler({+ consensus: 'raft',+ bootstrapSecret: 'forged-secret-attacker-guessed',+ })) as any;+ expect(denied.success).toBe(false);+ expect(denied.error).toBe('Invalid bootstrapSecret');+ expect(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('succeeds with the correct bootstrapSecret', async () => {+ const token = await initHive();+ expect(typeof token).toBe('string');+ });++ it('re-init on an already-initialized hive is ALSO denied without the bootstrapSecret, 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');++ const after = readPersistedState(dir);+ expect(after).toEqual(before);+ });++ it('re-init with the correct bootstrapSecret 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;+ expect(reinit.success).toBe(true);++ expect(getHiveTokenForCli()).toBe(token);+ });+ });++ describe('real CLI-process integration (not just direct handler calls)', () => {+ it('`hive-mind init` then `hive-mind spawn` succeed end-to-end through the actual CLI binary in a fresh child process', () => {+ const initResult = runCli(['hive-mind', 'init', '--consensus', 'raft'], dir);+ expect(initResult.exit).toBe(0);+ expect(existsSync(join(dir, '.claude-flow', 'hive-mind', 'state.json'))).toBe(true);++ // Fresh state read (this is a separate `node` process from the one+ // that ran init -- no in-process cache of any kind survives between+ // these two runCli() calls).+ const spawnResult = runCli(['hive-mind', 'spawn', '--count', '1'], dir);+ expect(spawnResult.exit).toBe(0);++ const persisted = readPersistedState(dir) as any;+ expect(persisted.workers.length).toBe(1);+ });++ it('a raw MCP-style call with no bootstrapSecret cannot bootstrap a hive via the real dispatch path either (spawning `hive-mind spawn` with no prior init fails)', () => {+ // No init was ever run in this fresh temp dir/process.+ const spawnResult = runCli(['hive-mind', 'spawn', '--count', '1'], dir);+ expect(spawnResult.exit).not.toBe(0);+ expect(existsSync(join(dir, '.claude-flow', 'hive-mind', 'state.json'))).toBe(false);+ });+ });});diff --git a/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts b/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.tsindex 0da41fec68..15bcfffd55 100644--- a/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts+++ b/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts@@ -215,7 +215,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 } from '../src/mcp-tools/hive-mind-tools.js';+import { hiveMindTools, getHiveBootstrapSecretForCli } 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';@@ -716,7 +716,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' });+ const result: any = await tool.handler({ topology: 'mesh', bootstrapSecret: getHiveBootstrapSecretForCli() });expect(result.success).toBe(true);expect(result.topology).toBe('mesh');});diff --git a/v3/@claude-flow/cli/src/commands/hive-mind.ts b/v3/@claude-flow/cli/src/commands/hive-mind.tsindex 9e44adbac2..6ce7578314 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 { existsSync } from 'fs';import { join } from 'path';import { resolveClaudeLaunchCommand } from '../runtime/claude-command.js';-import { getHiveTokenForCli } from '../mcp-tools/hive-mind-tools.js';+import { getHiveTokenForCli, getHiveBootstrapSecretForCli } from '../mcp-tools/hive-mind-tools.js';// Worker type definitions for prompt generationinterface HiveWorker {@@ -509,7 +509,8 @@ 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'+ memoryBackend: ctx.flags.memoryBackend as string || 'hybrid',+ bootstrapSecret: getHiveBootstrapSecretForCli(),};output.writeln();@@ -1123,6 +1124,7 @@ const optimizeMemoryCommand: Command = {}>('hive-mind_optimize-memory', {aggressive,qualityThreshold: threshold,+ hiveToken: getHiveTokenForCli(),});spinner.succeed('Memory optimized');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 c0cf364928..5ca0c43b2d 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@@ -200,6 +200,71 @@ export function getHiveTokenForCli(): string | undefined {return loadHiveState().hiveToken;}+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.+ */+function getOrCreateBootstrapSecret(): string {+ ensureHiveDir();+ const path = getBootstrapSecretPath();+ try {+ if (existsSync(path)) {+ const existing = readFileSync(path, 'utf-8').trim();+ if (existing) return existing;+ }+ } catch {+ // fall through to (re)creating it+ }+ const secret = randomBytes(32).toString('hex');+ writeFileSync(path, secret, { encoding: 'utf-8', mode: 0o600 });+ return secret;+}++/** Same-machine accessor for the CLI's own `hive-mind init` subcommand. */+export function getHiveBootstrapSecretForCli(): string {+ return getOrCreateBootstrapSecret();+}++/**+ * 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.+ */+function requireBootstrapSecret(suppliedSecret: unknown): string | null {+ const expectedStr = getOrCreateBootstrapSecret();+ if (typeof suppliedSecret !== 'string' || !suppliedSecret) {+ return 'bootstrapSecret is required';+ }+ 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';+ }+ return null;+}+function getHiveDir(): string {return join(getProjectCwd(), STORAGE_DIR, HIVE_DIR);}@@ -365,9 +430,19 @@ 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' },},+ 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);+ if (bootstrapError) {+ return { success: false, error: bootstrapError };+ }+if (input.queenId) { const v = validateIdentifier(input.queenId as string, 'queenId'); if (!v.valid) return { success: false, error: v.error }; }const state = loadHiveState();@@ -402,7 +477,11 @@ export const hiveMindTools: MCPTool[] = [consensus: state.consensusStrategy,queenId,status: 'initialized',- hiveToken: state.hiveToken,+ // Deliberately NOT echoing state.hiveToken here (even though this+ // call is itself now bootstrap-secret-gated): the CLI never reads+ // it off this response (it uses getHiveTokenForCli()'s direct+ // same-machine state.json read instead), so there's no reason to+ // widen the token's exposure onto an MCP tool response at all.config: {topology: state.topology,consensus: state.consensusStrategy,@@ -1189,12 +1268,21 @@ 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' },},+ required: ['hiveToken'],},- handler: async () => {+ handler: async (input) => {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);+ if (tokenError) {+ return { optimized: false, error: tokenError, before: { patterns: 0, memory: '0' }, after: { patterns: 0, memory: '0' }, removed: 0, consolidated: 0, timeMs: 0 };+ }const beforeKeys = Object.keys(state.sharedMemory);const before = beforeKeys.length;for (const k of beforeKeys) {