π 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 gate hive-mind_spawn/propose/broadcast/shutdown/memory behind requireHiveToken
Claude07be91704a81
diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.mdindex 548bb16327..c986b4c6d4 100644--- a/docs/dream-cycle/LEDGER.md+++ b/docs/dream-cycle/LEDGER.md@@ -192,3 +192,7 @@ as a first-class, high-priority candidate, not a background note.| 2026-09-10 | performance | `mmrRerank()` eagerly re-tokenized every remaining candidate's content on every MMR outer-loop pass (O(NΓlimit) `tokenize()` calls) β a pattern that predates and survived PR #3169's embedding-cosine wiring unchanged, even though the cosine branch made that tokenization mostly discarded work in the now-common all-embedded case; made lazy and cached per-candidate | #3265 | #3266 | yes | ACCEPT | `tokenize()` calls 400β0 (N=30/limit=20 corpus, stash-isolated: fails against real baseline, passes against candidate); wall-clock 5.88x faster (0.6745msβ0.1148ms mean), independently reproduced at 5.96x by an adversarial critic; selection output byte-identical to baseline across all-embedded/none/mixed/lambda-extreme scenarios; 473/474 full-suite both ways (1 pre-existing unrelated failure), `tsc` clean | 78c074ef... | rebased onto main (post #3086/#3094/#3103/#3110/#3119/#3123/#3130/#3139/#3152/#3160/#3232 merges), awaiting fresh CI as of 2026-09-14 || 2026-09-11 | security | `hive-mind_consensus` accepted votes from any caller-supplied `voterId` with no check against `state.workers` (a single caller could cross any strategy's quorum by voting under fabricated identities β a Sybil attack on consensus); fail-closed roster-membership check added. **Update (ruvnet review):** REJECTed the initial scoped fix on the caveat the adversarial critic had already disclosed (`hive-mind_join`/`leave` fully unauthenticated β the roster itself could be Sybil'd) plus a required-CI cold-install failure (`@claude-flow/security` missing a `prepare` script, so root `npm ci` never built its dist/). Both addressed same-session: `join`/`leave`/`vote` now capability-bound to a `hiveToken` minted by `hive-mind_init` (32-byte random, constant-time comparison, fail-closed β zero state change for denied calls, verified via a fresh state.json reload simulating restart; a same-machine-only token reader lets the CLI's own subcommands keep working without exposing the token over any MCP response); `@claude-flow/security`'s `package.json` gained a `prepare: npm run build` so root `npm ci` builds it automatically for every consumer, not just this CI job | #3290 | #3291 | yes | ACCEPT-scoped (post-review) | stash-isolated 2/3 fail baseline (forged votes silently accepted) β 3/3 pass candidate; full `@claude-flow/cli` suite failures 46β28 after the CI fix (remainder pre-existing/unrelated); adversarial critic CONFIRMED-WITH-CAVEATS pre-review, both caveats closed post-review | 55d67b4a... | rebased onto main (post #3086/#3094/#3103/#3110/#3119/#3123/#3130/#3139/#3152/#3160/#3232/#3266 merges), awaiting fresh CI as of 2026-09-14 || 2026-09-12 | intelligence | `LocalReasoningBank.findSimilar()` overwrote every returned pattern's `confidence` (learned reliability) with the per-query cosine similarity score instead of the already-declared `PatternMatch.similarity` field, inverting `distillLearning()`'s "only distill from high-confidence matches" gate (it tested query-similarity, not reliability) and forcing `findSimilarPatterns()`'s public API into an unsafe cast that made `confidence`/`similarity` always identical; `findSimilar()` now preserves real `confidence` and returns `similarity` separately, with the one affected consumer (`memory-bridge.ts`'s search-ranking score) migrated accordingly | #3301 | #3302 | yes | ACCEPT | 4 new discriminating tests, baseline-fails/candidate-passes via stash isolation; full suite 90-vs-91-failed-files identical except the new test file; `tsc --noEmit` byte-identical (463 errors both ways); independent adversarial critique CONFIRMED, no blocking caveats | cb60b43b... | rebased onto main (post #3086/#3094/#3103/#3110/#3119/#3123/#3130/#3139/#3152/#3160/#3232/#3266/#3291 merges), awaiting fresh CI as of 2026-09-14 |++**Update (2026-09-16):** Verified via GitHub MCP tools (`pull_request_read`, not `gh` β unavailable in this environment) that the entire backlog flagged above as "unmerged draft"/"awaiting fresh CI" is now **MERGED**: #3086, #3094, #3103, #3110, #3119, #3123, #3130, #3139, #3152, #3160 (the 2026-08-24..09-02 batch) all merged 2026-09-14, and #3184, #3221, #3232, #3243, #3266, #3291, #3302 (2026-09-05..09-12) all merged 2026-09-14/15 β 20/20 checked, 0 open. Trailing-night merge rate has gone from "0 of last 14" (as of 08-31) to 20/20 of everything checked tonight. STEP 1.1's "bias toward small, reviewable candidates" guidance is credited but no longer forced by a stuck backlog β reviewability remains a goal on its own merits, not a workaround for non-merging.++| 2026-09-16 | security | Six `hive-mind_*` MCP tools (`spawn`, `consensus` `propose`, `broadcast`, `shutdown`, `memory` `set`/`delete`) mutated hive state with no `hiveToken` check, though sibling `join`/`leave`/`vote` were capability-bound the night before (#3291, merged 09-15) β most severely, `spawn` let an unauthenticated caller mint its own voting "workers" and vote as them, bypassing #3291 entirely via a sibling tool; all six now reuse the existing `requireHiveToken` gate | #3338 | TBD | yes | ACCEPT | stash-isolated: 7/12 new tests fail on baseline exactly for the 6 gated call sites, 18/18 pass on candidate; full `@claude-flow/cli` suite (251 files/3165 tests) failing-test-name sets identical both ways (34 pre-existing, unrelated); `tsc --noEmit` byte-identical (22 errors); independent adversarial critique CONFIRMED-WITH-CAVEATS pre-fix (found the `hive-mind_memory` gap the first patch missed), re-verified after closing it | f2dca5c7... | 20/20 previously-checked backlog PRs now confirmed merged (see note above) β first night since 08-31 with zero open dream-cycle backlog |diff --git a/docs/dream-cycle/dream-gist-2026-09-16.md b/docs/dream-cycle/dream-gist-2026-09-16.mdnew file mode 100644index 0000000000..f55a8ad4dc--- /dev/null+++ b/docs/dream-cycle/dream-gist-2026-09-16.md@@ -0,0 +1,165 @@+# Security SOTA Report β 2026-09-16++TL;DR: Tonight's `security` deep-dive found that PR #3291 (merged 2026-09-15, last+night'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+with no such gate**: `hive-mind_spawn` (which pushes attacker-chosen agent ids straight+into `state.workers`, the same roster `vote` treats as legitimate β letting an+unauthenticated caller mint its own "workers" and then vote as them, bypassing #3291+entirely 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.++## What's New in 2026++| Finding | Source | Confidence |+|---|---|---|+| MCP spec's 2026-07-28 revision is the largest authorization hardening pass to date: Dynamic Client Registration deprecated for Client ID Metadata Documents, `iss` validation per RFC 9207, token-passthrough prohibited | [blog.modelcontextprotocol.io](https://blog.modelcontextprotocol.io/posts/2026-07-28-release-candidate/) | A |+| Tool poisoning (malicious instructions embedded in tool metadata/descriptions) is identified as the most prevalent, highest-impact client-side MCP vulnerability class | arXiv:2603.22489 / MDPI 2624-800X/6/3/84 | A |+| "Authorization Propagation in Multi-Agent AI Systems" names exactly the failure mode Ruflo's own `mcp-caller-identity.ts` was built to close: authorization state persisting across calls without re-verifying *who* is presenting it | arXiv:2605.05440 | A |+| OWASP Top 10 for Agentic Applications 2026 (published 2025-12-09) categorizes unauthenticated inter-agent messages/shared-state mutation as **ASI07 β Insecure Inter-Agent Communication**, distinct from ASI03 (credential misuse) | OWASP GenAI Security Project | A |+| A2A protocol's own open design process (GitHub discussion #199, SEP #1404, RFC #1716) is actively proposing Ed25519 capability tokens scoped to skill invocations β directionally identical to Ruflo's `hiveToken` approach, but pre-production | github.com/a2aproject/A2A | B/C |+| LangGraph had 3 CVEs disclosed 2026-03-27 (CVE-2026-34070, CVE-2025-68664, CVE-2025-67644); no framework-native least-privilege tool gate exists | CSA research note, cross-checked | B |++## Ruflo Current Capability++`requireHiveToken()` (`hive-mind-tools.ts:177-190`) is a constant-time, fail-closed+bearer-capability check against a 32-byte token minted once by `hive-mind_init` and+never 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).++## Competitor Comparison++| Framework | Tool-authority enforcement | Agent identity/auth | MCP security posture | Grade |+|---|---|---|---|---|+| LangGraph | No built-in least-privilege gate; 3 CVEs disclosed 2026-03-27 | No signed per-agent identity | Inherits upstream MCP risk | B |+| Microsoft Agent Framework (AutoGen successor) | Delegated to Entra Agent ID (OAuth2/FIC) β real, but platform-layer not framework-native | Real signed tokens exist, not framework-enforced for shared state | Case-study only | B/C |+| CrewAI | Explicitly permissive-by-default (open issue #5888, unresolved) | No capability-token concept | None found | A (no built-in enforcement, primary) |+| OpenAI Agents SDK | Per-tool-call guardrails exist; handoffs bypass them (single-source) | No portable signed identity between agents | N/A | C |+| MCP protocol itself | N/A framework-wide; real CVEs (MCPoison, CurXecute, mcp-remote CVSS 9.6) | 2026-07-28 spec requires OAuth 2.1 + audience-bound tokens | Improving, reactive | A |++Synthesis: none of the four mainstream frameworks ship Ruflo's specific combination β+signed capability tokens bound into shared multi-agent coordination state β as a native+feature. The closest analog is the A2A protocol's own in-discussion Ed25519+capability-token proposal, confirming this is a recognized industry gap, not one Ruflo+invented alone, and that Ruflo's `hiveToken` mechanism from #3291 is ahead of what any+shipped competitor does β the gap tonight closes is that the mechanism wasn't applied+consistently to every tool that needed it.++## Hypothesis++> 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.++## Benchmarks++No benchmark corpus applies β this is a deterministic authentication-gate fix, not a+retrieval/ranking/routing candidate. Evidence is a discriminating Vitest regression+suite plus stash-isolated baseline/candidate comparison, the same evidence shape every+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.++## Darwin Results++Skipped β confirmed via `npx ruvector harness darwin --help`: the real interface+evolves continuous/categorical genome parameters (routing/topology/prompt/memory/+tool/tier/context/coordination) against an LLM-scored bench corpus. A binary+authentication gate (token present-and-valid, or not) has no fitness gradient for+Darwin to search over β same skip class as nearly every accepted night since 2026-08-18.++## SOTA Proof & Witness++No signed `@metaharness/flywheel` bundle β the schema targets LLM-task-corpus-evaluated+retrieval-policy candidates; this is a deterministic code-correctness/authentication+fix, 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).++Witness table:++| Field | Value |+|---|---|+| Session commit | `a65bdf683a73dcc1f20d455658daab1cca07306b` |+| Gist SHA-256 (pre-witness content) | `bd92faac26c595c64bafd51ba26062ad14151483861793d98afb1f98773100cc` |+| Witness stamp | `f2dca5c7404705dd5fde38b7bbc98eb4dc49161c21e2cd73d3b61d894decc043` |++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.++## Recommended Next Steps++1. **`terminal_execute` shells out via raw `execSync` with zero policy enforcement**+ (`terminal-tools.ts:192`), contradicting `.harness/mcp-policy.json`'s own claim that+ shell/network/file-write are "not in this server's tool surface." Independently+ found by two research roles tonight (deep researcher + architecture reviewer) as+ the second-highest-scored candidate β RCE-relevant, small patch, deferred only+ because tonight's finding was a more direct, more severe continuation of last+ night's own accepted work. Recommend as tomorrow's security-surface candidate if+ the rotation returns here, or sooner.+2. **Consensus "strategy-discard" bug**: `raft.ts:232-234` and `byzantine.ts:248-250`+ silently drop a vote arriving after a proposal leaves `'pending'` (return before+ recording, no error) β `gossip.ts` behaves differently (records then ignores).+ Timing-inducible one-sided vote suppression; not implemented tonight (swarm scan,+ secondary surface).+3. **Unvalidated embedding/verdict feeding EWC Fisher consolidation**+ (`intelligence.ts:1041`, `ewc-consolidation.ts:211-233`): any MCP caller can+ self-report `success: true` with crafted trajectory content to skew which patterns+ EWC protects from forgetting β no independent verification of the caller-supplied+ verdict. Intelligence scan finding, security-adjacent, out of scope for the+ hive-mind-specific fix tonight; a real memory/benchmark-poisoning-shaped gap for a+ future `intelligence` or `security` night.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 40789bbeb7..373330bd3f 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@@ -129,6 +129,7 @@ describe('hive-mind_consensus / join / leave capability-token authentication', (type: 'test',value: 'x',strategy: 'raft',+ hiveToken: token,}) as any;expect(propose.status).toBe('pending');@@ -180,6 +181,7 @@ describe('hive-mind_consensus / join / leave capability-token authentication', (type: 'test',value: 'x',strategy: 'raft',+ hiveToken: token,}) as any;const vote = await tool('hive-mind_consensus').handler({@@ -207,6 +209,7 @@ describe('hive-mind_consensus / join / leave capability-token authentication', (type: 'test',value: 'x',strategy: 'bft',+ hiveToken: token,}) as any;for (const voterId of ['sybil-a', 'sybil-b', 'sybil-c']) {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.tsnew file mode 100644index 0000000000..3bb253d94a--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/hive-mind-spawn-broadcast-shutdown-auth.test.ts@@ -0,0 +1,268 @@+/**+ * Regression test β hive-mind_spawn / consensus(propose) / broadcast / shutdown+ * authentication gap (dream-cycle 2026-09-16, follow-up to #3291).+ *+ * PR #3291 (merged 2026-09-15) bound hive-mind_join/leave/vote to a+ * capability token minted by hive-mind_init, closing a Sybil-vote attack.+ * Six sibling MCP tools mutate the same hive state with no such gate:+ *+ * - hive-mind_spawn pushes attacker-chosen agent ids straight into+ * `state.workers` β the exact roster `vote` treats as legitimate voters+ * (`state.workers.includes(voterId)`). An unauthenticated caller could+ * spawn its own "workers" and then vote as them, bypassing #3291+ * entirely via this sibling tool rather than defeating it directly.+ * - hive-mind_consensus's 'propose' action let anyone inject an arbitrary+ * proposal (type/value of their choosing) for real workers to vote on,+ * or exhaust raft's one-pending-proposal-per-term slot as a DoS.+ * - hive-mind_broadcast let anyone inject spoofed messages (arbitrary+ * fromId) into shared memory every worker reads.+ * - hive-mind_shutdown let anyone terminate a running hive (wiping+ * workers/pending consensus/shared memory) with zero proof of+ * membership.+ * - hive-mind_memory's 'set'/'delete' actions let anyone tamper with or+ * erase shared-memory entries every worker/queen reads β the same+ * attack class broadcast was gated for, on a sibling action in the+ * 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).+ *+ * All six 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.+ */++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';++function tool(name: string) {+ const t = hiveMindTools.find((t) => t.name === name);+ if (!t) throw new Error(`tool not found: ${name}`);+ return t;+}++function readPersistedState(dir: string): {+ workers: string[];+ initialized: boolean;+ consensus: { pending: Array<{ proposalId: string }> };+ sharedMemory: Record<string, unknown>;+} {+ const raw = readFileSync(join(dir, '.claude-flow', 'hive-mind', 'state.json'), 'utf-8');+ return JSON.parse(raw);+}++describe('hive-mind_spawn / consensus(propose) / broadcast / shutdown capability-token authentication', () => {+ let dir: string;+ let prevCwd: string | undefined;++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'hive-mind-auth-'));+ prevCwd = process.env.CLAUDE_FLOW_CWD;+ process.env.CLAUDE_FLOW_CWD = dir;+ });++ afterEach(() => {+ 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' })) as any;+ expect(init.success).toBe(true);+ return init.hiveToken as string;+ }++ it('hive-mind_spawn is denied without the token, and mints zero workers (verified after a fresh state reload)', async () => {+ await initHive();++ const denied = (await tool('hive-mind_spawn').handler({ count: 3 })) as any;+ expect(denied.success).toBe(false);+ expect(denied.error).toMatch(/hiveToken is required/);++ const deniedWrongToken = (await tool('hive-mind_spawn').handler({+ count: 3,+ hiveToken: 'forged',+ })) as any;+ expect(deniedWrongToken.success).toBe(false);+ expect(deniedWrongToken.error).toMatch(/Invalid hiveToken/);++ const persisted = readPersistedState(dir);+ expect(persisted.workers).toEqual([]);+ });++ it('hive-mind_spawn succeeds with the correct token and the spawned worker can then legitimately vote', async () => {+ const token = await initHive();++ const spawn = (await tool('hive-mind_spawn').handler({ count: 1, prefix: 'w', hiveToken: token })) as any;+ expect(spawn.success).toBe(true);+ expect(spawn.workers).toHaveLength(1);+ const agentId = spawn.workers[0].agentId as string;++ const propose = (await tool('hive-mind_consensus').handler({+ action: 'propose',+ type: 'test',+ value: 'x',+ strategy: 'raft',+ hiveToken: token,+ })) as any;+ expect(propose.status).toBe('pending');++ const vote = (await tool('hive-mind_consensus').handler({+ action: 'vote',+ proposalId: propose.proposalId,+ vote: true,+ voterId: agentId,+ hiveToken: token,+ })) as any;+ expect(vote.error).toBeUndefined();+ });++ it('without the spawn gate, an attacker could have minted a Sybil voter and crossed quorum -- with the gate, the attempt to vote as a never-joined id is rejected', async () => {+ // Regression guard for the actual attack chain #3291 left open via+ // hive-mind_spawn: attacker calls spawn (now denied) to try to mint a+ // voter, then tries to vote as a fabricated id anyway. Both steps must+ // fail and the vote must never be recorded.+ const token = await initHive();++ const spawnDenied = (await tool('hive-mind_spawn').handler({ count: 1 })) as any;+ expect(spawnDenied.success).toBe(false);++ const propose = (await tool('hive-mind_consensus').handler({+ action: 'propose',+ type: 'test',+ value: 'x',+ strategy: 'raft',+ hiveToken: token,+ })) as any;++ const forgedVote = (await tool('hive-mind_consensus').handler({+ action: 'vote',+ proposalId: propose.proposalId,+ vote: true,+ voterId: 'sybil-worker-0',+ hiveToken: token,+ })) as any;+ expect(forgedVote.error).toMatch(/not a registered hive-mind worker/);++ const persisted = readPersistedState(dir);+ const persistedProposal = persisted.consensus.pending.find((p) => p.proposalId === propose.proposalId) as any;+ expect(persistedProposal?.votes ?? {}).toEqual({});+ });++ it("hive-mind_consensus 'propose' is denied without the token, and records zero proposals (verified after a fresh state reload)", async () => {+ await initHive();++ const denied = (await tool('hive-mind_consensus').handler({+ action: 'propose',+ type: 'malicious',+ value: 'attacker-controlled',+ strategy: 'raft',+ })) as any;+ expect(denied.error).toMatch(/hiveToken is required/);++ const persisted = readPersistedState(dir);+ expect(persisted.consensus.pending).toEqual([]);+ });++ it('hive-mind_broadcast is denied without the token, and stores zero messages (verified after a fresh state reload)', async () => {+ await initHive();++ const denied = (await tool('hive-mind_broadcast').handler({+ message: 'attacker-controlled announcement',+ fromId: 'queen',+ })) as any;+ expect(denied.success).toBe(false);+ expect(denied.error).toMatch(/hiveToken is required/);++ const persisted = readPersistedState(dir);+ expect((persisted.sharedMemory.broadcasts as unknown[] | undefined) ?? []).toEqual([]);+ });++ it('hive-mind_broadcast succeeds with the correct token', async () => {+ const token = await initHive();+ const ok = (await tool('hive-mind_broadcast').handler({ message: 'hello', hiveToken: token })) as any;+ expect(ok.success).toBe(true);++ const persisted = readPersistedState(dir);+ expect(persisted.sharedMemory.broadcasts as unknown[]).toHaveLength(1);+ });++ it('hive-mind_shutdown is denied without the token, and leaves the hive fully initialized (verified after a fresh state reload)', async () => {+ const token = await initHive();+ await tool('hive-mind_join').handler({ agentId: 'worker-0', hiveToken: token });++ const denied = (await tool('hive-mind_shutdown').handler({ force: true })) as any;+ expect(denied.success).toBe(false);+ expect(denied.error).toMatch(/hiveToken is required/);++ const persisted = readPersistedState(dir);+ expect(persisted.initialized).toBe(true);+ expect(persisted.workers).toEqual(['worker-0']);+ });++ it('hive-mind_shutdown succeeds with the correct token', async () => {+ const token = await initHive();+ await tool('hive-mind_join').handler({ agentId: 'worker-0', hiveToken: token });++ const ok = (await tool('hive-mind_shutdown').handler({ force: true, hiveToken: token })) as any;+ expect(ok.success).toBe(true);++ const persisted = readPersistedState(dir);+ expect(persisted.initialized).toBe(false);+ expect(persisted.workers).toEqual([]);+ });++ it("hive-mind_memory 'set' is denied without the token, and writes zero entries (verified after a fresh state reload)", async () => {+ await initHive();++ const denied = (await tool('hive-mind_memory').handler({+ action: 'set',+ key: 'attacker-key',+ value: 'attacker-controlled',+ })) as any;+ expect(denied.error).toMatch(/hiveToken is required/);++ const persisted = readPersistedState(dir);+ expect(persisted.sharedMemory).toEqual({});+ });++ it("hive-mind_memory 'set' succeeds with the correct token", async () => {+ const token = await initHive();+ const ok = (await tool('hive-mind_memory').handler({+ action: 'set',+ key: 'k',+ value: 'v',+ hiveToken: token,+ })) as any;+ expect(ok.success).toBe(true);++ const persisted = readPersistedState(dir);+ expect(persisted.sharedMemory).toEqual({ k: 'v' });+ });++ it("hive-mind_memory 'delete' is denied without the token, and leaves an existing entry untouched (verified after a fresh state reload)", async () => {+ const token = await initHive();+ await tool('hive-mind_memory').handler({ action: 'set', key: 'k', value: 'v', hiveToken: token });++ const denied = (await tool('hive-mind_memory').handler({ action: 'delete', key: 'k' })) as any;+ expect(denied.error).toMatch(/hiveToken is required/);++ const persisted = readPersistedState(dir);+ expect(persisted.sharedMemory).toEqual({ k: 'v' });+ });++ it("hive-mind_memory 'delete' succeeds with the correct token", async () => {+ const token = await initHive();+ await tool('hive-mind_memory').handler({ action: 'set', key: 'k', value: 'v', hiveToken: token });++ const ok = (await tool('hive-mind_memory').handler({ action: 'delete', key: 'k', hiveToken: token })) as any;+ expect(ok.deleted).toBe(true);++ const persisted = readPersistedState(dir);+ expect(persisted.sharedMemory).toEqual({});+ });+});diff --git a/v3/@claude-flow/cli/src/commands/hive-mind.ts b/v3/@claude-flow/cli/src/commands/hive-mind.tsindex 66ca259ff7..9e44adbac2 100644--- a/v3/@claude-flow/cli/src/commands/hive-mind.ts+++ b/v3/@claude-flow/cli/src/commands/hive-mind.ts@@ -681,6 +681,7 @@ const spawnCommand: Command = {role,agentType,prefix,+ hiveToken: getHiveTokenForCli(),});// Check for errors from MCP tool@@ -1246,7 +1247,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 });+ 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() });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 };@@ -1270,7 +1271,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 });+ const result = await callMCPTool<Record<string, unknown>>('hive-mind_memory', { action, key, value, hiveToken: getHiveTokenForCli() });if (ctx.flags.format === 'json') { output.printJson(result); return { success: true, data: result }; }if (action === 'list') {const keys = (result.keys as string[]) || [];@@ -1337,6 +1338,7 @@ const shutdownCommand: Command = {}>('hive-mind_shutdown', {force,saveState,+ hiveToken: getHiveTokenForCli(),});spinner.succeed('Hive mind shutdown complete');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 972825299e..c0cf364928 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@@ -275,7 +275,9 @@ 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' },},+ required: ['hiveToken'],},handler: async (input) => {const state = loadHiveState();@@ -284,6 +286,17 @@ export const hiveMindTools: MCPTool[] = [return { success: false, error: 'Hive-mind not initialized. Run hive-mind/init first.' };}+ // Fail-closed: spawned agents are pushed straight into state.workers,+ // which hive-mind_consensus's vote tally treats as legitimate voting+ // roster members (`state.workers.includes(voterId)`). Without this+ // 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);+ if (tokenError) {+ return { success: false, error: tokenError };+ }+if (input.agentType) { const v = validateIdentifier(input.agentType as string, 'agentType'); if (!v.valid) return { success: false, error: v.error }; }if (input.prefix) { const v = validateIdentifier(input.prefix as string, 'prefix'); if (!v.valid) return { success: false, error: v.error }; }@@ -620,6 +633,16 @@ export const hiveMindTools: MCPTool[] = [const totalNodes = state.workers.length || 1;if (action === 'propose') {+ // Fail-closed: an unauthenticated caller could otherwise inject+ // arbitrary consensus proposals (type/value of their choosing) for+ // 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);+ if (proposeTokenError) {+ return { action, error: proposeTokenError };+ }+const proposalId = `proposal-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;const quorumPreset = (input.quorumPreset as QuorumPreset) || 'majority';const term = (input.term as number) || (state.queen?.term ?? 1);@@ -941,8 +964,9 @@ 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' },},- required: ['message'],+ required: ['message', 'hiveToken'],},handler: async (input) => {const state = loadHiveState();@@ -951,6 +975,14 @@ export const hiveMindTools: MCPTool[] = [return { success: false, error: 'Hive-mind not initialized' };}+ // 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);+ if (tokenError) {+ return { success: false, error: tokenError };+ }+{ const v = validateText(input.message as string, 'message'); if (!v.valid) return { success: false, error: v.error }; }if (input.fromId) { const v = validateIdentifier(input.fromId as string, 'fromId'); if (!v.valid) return { success: false, error: v.error }; }@@ -988,7 +1020,9 @@ 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' },},+ required: ['hiveToken'],},handler: async (input) => {const state = loadHiveState();@@ -997,6 +1031,14 @@ export const hiveMindTools: MCPTool[] = [return { success: false, error: 'Hive-mind not initialized or already shut down' };}+ // 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);+ if (tokenError) {+ return { success: false, error: tokenError };+ }+const graceful = input.graceful !== false;const force = input.force === true;const workerCount = state.workers.length;@@ -1054,6 +1096,7 @@ 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)' },},required: ['action'],},@@ -1076,6 +1119,14 @@ export const hiveMindTools: MCPTool[] = [if (action === 'set') {if (!key) return { action, error: 'Key required' };+ // Fail-closed: no token, no write -- otherwise any caller could+ // 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);+ if (tokenError) {+ return { action, key, error: tokenError };+ }state.sharedMemory[key] = input.value;saveHiveState(state);@@ -1099,6 +1150,11 @@ 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);+ if (tokenError) {+ return { action, key, error: tokenError };+ }const existed = key in state.sharedMemory;delete state.sharedMemory[key];saveHiveState(state);