feat(hive-mind): #2030 ADR-095 G2.2 — wire MCP layer through real ConsensusEngine + #2024 #2027 fixes

Closes the gap where @claude-flow/swarm's real ConsensusEngine shipped per
ADR-095 G2 (PR #1905) but the hive-mind_* MCP tools — the surface every
LLM agent calls — never reached it. They were a JSON-file state machine
with hand-rolled raft/byzantine/quorum voting that bypassed the engine
entirely.

## Wire-up (G2.2)

- swarm: ConsensusEngine.initialize() now forwards `transport` to the
  inner Raft/PBFT/Gossip implementations (they already accepted it;
  the wrapper was the bottleneck). ConsensusConfig.transport added,
  typed unknown to keep types.ts cross-module-import-free, narrowed
  structurally in consensus/index.ts.
- swarm: top-level barrel re-exports LocalTransport, FederationTransport,
  + signing helpers so consumers don't deep-import from ./consensus/*.
- swarm: ESM hygiene — coordination/{agent-registry,task-orchestrator,
  swarm-hub}.ts were missing .js extensions on relative imports. vitest
  tolerated them but Node ESM consumers (the new runtime) failed with
  "Cannot find module 'dist/shared/events'". Fixed.
- cli: new v3/@claude-flow/cli/src/mcp-tools/hive-consensus-runtime.ts —
  process-level singleton owning a real ConsensusEngine + ConsensusTransport.
  Transport selection: local (in-process), federation (agentic-flow WS
  via dynamic import), auto (federation when reachable, else local).
  Federation-loader-missing degrades cleanly with degraded:true + reason.
- cli: hive-mind_init accepts transport/algorithm/peers, instantiates
  the runtime, returns runtime:{engine,transport,degraded,fallbackReason,
  peerCount} block.
- cli: hive-mind_consensus gains action:'engine-stats' + useEngine:true
  paths for propose/vote that route through engine.propose / engine.vote.
  Legacy JSON-state-machine voting preserved as default — zero-impact
  upgrade.
- cli: hive-mind_broadcast proxies through transport.broadcast when
  runtime is up. hive-mind_shutdown tears down both file-state and
  runtime (runtimeShutdown:true).

## Validation

- @claude-flow/swarm full suite: 218/218 PASS
- New v3/@claude-flow/cli/__tests__/hive-consensus-runtime.test.ts: 10/10 PASS
- New scripts/smoke-hive-consensus-engine.mjs (10 checks): all PASS,
  wired into v3-ci.yml as hive-mind-consensus-engine-wire-up-smoke
  (#1872, ADR-095 G2.2)

## Published

- @claude-flow/swarm@3.0.0-alpha.8
- @claude-flow/cli@3.7.0-alpha.45
- claude-flow@3.7.0-alpha.45
- ruflo@3.7.0-alpha.45

## Bundled fixes

- #2024: simulateMonteCarlo NaN on empty portfolio — sentinel-on-empty
  guard in PortfolioRiskCalculator.monteCarloSimulation + FinancialEconomyBridge.
  simulateMonteCarlo, regression test added.
- #2027: witness verify precondition silent-drop guard — Case 0 in
  smoke-witness-verify-precondition.mjs asserts @noble/ed25519 stays
  declared in root package.json with ^2.x pin. CI guard renamed to
  (#1880, #2027).

## ADR

ADR-095 G2.2 section added documenting the wire-up, remaining G2.3
(DiscoveryService integration, live mac↔ruvultra round).

Issue: #2030
Gist: https://gist.github.com/ruvnet/57eb826be73af8730392998d3f3c772d

Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
ruv committed 2026-05-17 10:40:40 -04:00
1 parent f8ab5a3255
commit dacbe0ec59
19 files changed
+1193 -21

No files matched your search

+53 -1
View File
@@ -390,13 +390,20 @@ jobs:
# (missing dep, source-only checkout) and exit 1 strictly for real
# failures (signature invalid, dist file regressed). This smoke
# drives both shapes through and asserts the contract holds:
# - @noble/ed25519 stays declared at the repo root (Case 0, #2027)
# - missing @noble/ed25519 → exit 2 + named in the error
# - all-manifest-files missing → exit 2 + precondition tag
# - built tree → exit is NEVER 2
#
# Case 0 (#2027) is the silent-drop guard: if a future dep-cleanup
# PR removes @noble/ed25519 from root package.json, `npm ci` on the
# scheduled runner will silently stop installing it and the runner
# will start re-filing the precondition-miss issue every 12h. The
# PR is now blocked at this CI gate before that can happen.
#
# Independent job so a precondition contract break is named clearly
# in the CI summary. Wired into witness-verify's `needs:` below.
name: witness verify precondition smoke (#1880)
name: witness verify precondition smoke (#1880, #2027)
runs-on: ubuntu-latest
steps:
@@ -415,6 +422,51 @@ jobs:
shell: bash
run: node scripts/smoke-witness-verify-precondition.mjs
hive-consensus-engine-smoke:
# ADR-095 G2.2 regression guard — asserts the hive-mind MCP layer wires
# the real `@claude-flow/swarm` ConsensusEngine via hive-consensus-runtime.
#
# Before this wire-up, `hive-mind_init` was a JSON file write and
# `hive-mind_consensus` was a hand-rolled state machine — the real
# `ConsensusEngine` (Raft/PBFT/Gossip + pluggable transport) shipped in
# @claude-flow/swarm but was never reached from the CLI. This smoke
# drives `hive-mind_init` → `hive-mind_consensus { action: 'engine-stats' }`
# → `hive-mind_consensus { action: 'propose', useEngine: true }` → shutdown
# through the actual MCP tool handlers and asserts each step actually
# routes through the engine (`runtime.engine === 'enabled'`,
# `transport === 'local'`, `propose.engine === 'enabled'`,
# `shutdown.runtimeShutdown === true`).
#
# If a future refactor accidentally unhooks the runtime — e.g. by
# short-circuiting `hive-mind_init` to skip `hiveConsensusRuntime.init`,
# or by dropping the `useEngine` proxy from `hive-mind_consensus` — this
# job catches it before merge.
name: hive-mind consensus engine wire-up smoke (#1872, ADR-095 G2.2)
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Install root + workspace deps
run: npm ci --legacy-peer-deps
- name: Build @claude-flow/swarm
working-directory: v3/@claude-flow/swarm
run: npx tsc --build --force
- name: Build @claude-flow/cli
working-directory: v3/@claude-flow/cli
run: npm run build
- name: Drive hive-mind MCP handlers through the real ConsensusEngine
shell: bash
run: node scripts/smoke-hive-consensus-engine.mjs
pre-bash-hook-smoke:
# Regression guard for ruvnet/ruflo#2017 — the `pre-bash` PreToolUse hook
# in `.claude/helpers/hook-handler.cjs` is a security gate that refuses to
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "claude-flow",
"version": "3.7.0-alpha.44",
"version": "3.7.0-alpha.45",
"description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "dist/index.js",
"type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "ruflo",
"version": "3.7.0-alpha.44",
"version": "3.7.0-alpha.45",
"description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "bin/ruflo.js",
"type": "module",
+175
View File
@@ -0,0 +1,175 @@
#!/usr/bin/env node
/**
* ADR-095 G2.2 smoke — assert the hive-mind MCP layer wires the real
* @claude-flow/swarm ConsensusEngine via the hive-consensus-runtime.
*
* Drives the same flow a Claude Code MCP client would:
* 1. hive-mind_init returns runtime.engine: 'enabled' with transport: 'local'
* (and degraded:false in 'auto' mode when agentic-flow isn't installed).
* 2. hive-mind_consensus { action: 'engine-stats' } returns initialized:true
* with a non-null engine block.
* 3. hive-mind_consensus { action: 'propose', useEngine: true } accepts a
* gossip-algorithm proposal through the engine (proposerId == queen).
* 4. hive-mind_shutdown reports runtimeShutdown: true.
*
* Any deviation = the wire-up regressed.
*/
import { spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
const REPO_ROOT = process.cwd();
const CLI_DIST = resolve(REPO_ROOT, 'v3/@claude-flow/cli/dist/src/mcp-tools/hive-mind-tools.js');
const RUNTIME_DIST = resolve(REPO_ROOT, 'v3/@claude-flow/cli/dist/src/mcp-tools/hive-consensus-runtime.js');
if (!existsSync(CLI_DIST)) {
console.error(`smoke: not found: ${CLI_DIST}`);
console.error('Run `npm run build -w @claude-flow/cli` first.');
process.exit(1);
}
if (!existsSync(RUNTIME_DIST)) {
console.error(`smoke: not found: ${RUNTIME_DIST}`);
console.error('hive-consensus-runtime.js is missing from dist — ADR-095 G2.2 not built.');
process.exit(1);
}
const failures = [];
function record(name, condition, detail) {
if (condition) {
console.log(` PASS ${name}`);
} else {
console.log(` FAIL ${name}`);
if (detail) console.log(` ${detail}`);
failures.push(name);
}
}
// Run the assertions in a temp cwd so the hive-mind state file doesn't
// pollute the repo.
const tmp = mkdtempSync(join(tmpdir(), 'hive-consensus-smoke-'));
// Driver uses dynamic ESM import (matches the cli package's "type": "module").
const driver = `
(async () => {
const { hiveMindTools } = await import(${JSON.stringify(CLI_DIST)});
const tools = Object.fromEntries(hiveMindTools.map(t => [t.name, t]));
// 1. init in 'auto' mode (no peers) — should land on local, not degraded.
const init = await tools['hive-mind_init'].handler({
topology: 'mesh',
consensus: 'gossip',
queenId: 'queen-smoke',
transport: 'auto',
});
console.log(JSON.stringify({ step: 'init', init }));
// 2. engine-stats — runtime should be live.
const stats = await tools['hive-mind_consensus'].handler({ action: 'engine-stats' });
console.log(JSON.stringify({ step: 'stats', stats }));
// 3. propose via the engine.
const propose = await tools['hive-mind_consensus'].handler({
action: 'propose',
type: 'smoke',
value: { op: 'smoke-test' },
useEngine: true,
voterId: 'queen-smoke',
});
console.log(JSON.stringify({ step: 'propose', propose }));
// 4. shutdown — runtime should tear down.
const shutdown = await tools['hive-mind_shutdown'].handler({ force: true });
console.log(JSON.stringify({ step: 'shutdown', shutdown }));
// Raft / Byzantine engines keep election timers alive; force-exit so
// this driver doesn't hang the smoke (the engine.shutdown call above
// clears its own timers, but a paranoid exit keeps CI clean).
process.exit(0);
})().catch(err => { console.error('DRIVER_ERR:', err && err.stack || err); process.exit(2); });
`;
// Use --input-type=module so `node -e` parses dynamic import as ESM.
const out = spawnSync('node', ['--input-type=module', '-e', driver], { cwd: tmp, encoding: 'utf8' });
rmSync(tmp, { recursive: true, force: true });
if (out.status !== 0) {
console.error(`smoke driver failed (exit ${out.status})`);
console.error('STDOUT:', out.stdout);
console.error('STDERR:', out.stderr);
process.exit(1);
}
// Parse the driver's JSON lines.
const steps = {};
for (const line of out.stdout.split('\n')) {
if (!line.trim()) continue;
try {
const parsed = JSON.parse(line);
steps[parsed.step] = parsed;
} catch { /* non-JSON noise from logs is fine */ }
}
// ── Assertions ──────────────────────────────────────────────────────
record(
'init.runtime.engine === "enabled"',
steps.init?.init?.runtime?.engine === 'enabled',
`runtime=${JSON.stringify(steps.init?.init?.runtime)}`,
);
record(
'init.runtime.transport is "local" (no agentic-flow in CI)',
steps.init?.init?.runtime?.transport === 'local',
`transport=${steps.init?.init?.runtime?.transport}`,
);
record(
'init.runtime.algorithm === "gossip"',
steps.init?.init?.runtime?.algorithm === 'gossip',
`algorithm=${steps.init?.init?.runtime?.algorithm}`,
);
record(
'init.runtime.degraded === false (auto mode is silent fallback)',
steps.init?.init?.runtime?.degraded === false,
`degraded=${steps.init?.init?.runtime?.degraded}`,
);
record(
'engine-stats.initialized === true',
steps.stats?.stats?.initialized === true,
`stats=${JSON.stringify(steps.stats?.stats)}`,
);
record(
'engine-stats.engine is non-null',
steps.stats?.stats?.engine != null,
`engine=${JSON.stringify(steps.stats?.stats?.engine)}`,
);
record(
'engine-stats.transport === "local"',
steps.stats?.stats?.transport === 'local',
`transport=${steps.stats?.stats?.transport}`,
);
record(
'propose.engine === "enabled" (real consensus engine routed)',
steps.propose?.propose?.engine === 'enabled',
`propose=${JSON.stringify(steps.propose?.propose)}`,
);
record(
'propose.proposalId is a non-empty string',
typeof steps.propose?.propose?.proposalId === 'string' && steps.propose.propose.proposalId.length > 0,
`proposalId=${steps.propose?.propose?.proposalId}`,
);
record(
'shutdown.runtimeShutdown === true',
steps.shutdown?.shutdown?.runtimeShutdown === true,
`shutdown=${JSON.stringify(steps.shutdown?.shutdown)}`,
);
console.log('');
if (failures.length > 0) {
console.error(`smoke-hive-consensus-engine: ${failures.length} check(s) failed:`);
for (const f of failures) console.error(` - ${f}`);
process.exit(1);
}
console.log('smoke-hive-consensus-engine: all checks passed (ADR-095 G2.2 wire-up live)');
+30 -1
View File
@@ -28,13 +28,14 @@
*/
import { spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
const REPO_ROOT = process.cwd();
const VERIFY = resolve(REPO_ROOT, 'plugins/ruflo-core/scripts/witness/verify.mjs');
const REAL_MANIFEST = resolve(REPO_ROOT, 'verification/macos/manifest.md.json');
const ROOT_PKG = resolve(REPO_ROOT, 'package.json');
if (!existsSync(VERIFY)) {
console.error(`smoke: not found: ${VERIFY}`);
@@ -57,6 +58,34 @@ function record(name, condition, detail) {
}
}
// ── Case 0: @noble/ed25519 stays declared at the repo root ──────────
// Regression guard for ruvnet/ruflo#2027. The 12h scheduled witness
// runner installs root deps before calling verify.mjs. If a future
// dep-cleanup PR drops @noble/ed25519 from the root package.json,
// `npm ci` will silently stop installing it and the scheduled runner
// will start re-filing the same precondition-miss issue every cycle.
// Catch the silent drop here, in PRs, before it ships.
console.log('Case 0: @noble/ed25519 declared at repo root (regression guard #2027)');
{
const pkg = JSON.parse(readFileSync(ROOT_PKG, 'utf8'));
const declared = pkg.dependencies?.['@noble/ed25519']
?? pkg.devDependencies?.['@noble/ed25519'];
record(
'@noble/ed25519 declared in root package.json',
typeof declared === 'string' && declared.length > 0,
`root package.json does not declare @noble/ed25519 — verify.mjs would exit 2 ` +
`on every scheduled run. See ruvnet/ruflo#1880 + #2027.`,
);
// verify.mjs uses the v2 API (ed.etc.sha512Sync, ed.getPublicKey, ed.verify).
// Pinning to ^2 prevents a major bump from breaking the verifier silently.
record(
'@noble/ed25519 pinned to ^2 (matches API verify.mjs uses)',
typeof declared === 'string' && /^[~^]?2\./.test(declared),
`declared=${declared} — verify.mjs uses the v2 API; a major bump must be ` +
`audited (see verifySignature in plugins/ruflo-core/scripts/witness/verify.mjs).`,
);
}
// ── Case 1: @noble/ed25519 missing → exit 2 (precondition) ──────────
// Drop verify.mjs into an empty root with no node_modules anywhere up
// the tree, so the ed25519 probe fails on every candidate.
@@ -0,0 +1,225 @@
/**
* Tests for the ADR-095 G2.2 hive-consensus runtime.
*
* Coverage:
* - init('local') brings up a real ConsensusEngine via LocalTransport
* - 3-node Raft round (propose → vote → accepted) through real RPCs
* - init('federation') with no agentic-flow installed degrades to local
* with degraded:true + a fallback reason
* - init('auto') silently picks local when federation isn't reachable
* - status() reports engine + transport + peers honestly
* - shutdown() is idempotent and tears down both engine and transport
* - re-init with a different nodeId tears the old engine down first
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { hiveConsensusRuntime } from '../src/mcp-tools/hive-consensus-runtime.js';
import {
ConsensusEngine,
LocalTransport,
LocalTransportRegistry,
} from '@claude-flow/swarm';
afterEach(async () => {
// Singleton state survives between tests — reset it.
try { await hiveConsensusRuntime.shutdown(); } catch { /* best-effort */ }
});
describe('hive-consensus-runtime / local transport', () => {
it('init({transport:"local"}) brings up the real engine', async () => {
const result = await hiveConsensusRuntime.init({
nodeId: 'queen-A',
algorithm: 'raft',
transport: 'local',
});
expect(result.initialized).toBe(true);
expect(result.transport).toBe('local');
expect(result.degraded).toBe(false);
expect(result.algorithm).toBe('raft');
expect(result.source).toBe('engine');
const status = hiveConsensusRuntime.status();
expect(status.initialized).toBe(true);
expect(status.engine).not.toBeNull();
expect(status.engine?.algorithm).toBe('raft');
expect(status.transport).toBe('local');
});
it('propose → vote round-trip through the real ConsensusEngine (gossip)', async () => {
// Gossip has no leader requirement — every node can propose.
// Use it to exercise propose/vote round-trip without waiting for
// Raft election timing in a unit test.
await hiveConsensusRuntime.init({
nodeId: 'queen-B',
algorithm: 'gossip',
transport: 'local',
peers: [{ nodeId: 'follower-1' }, { nodeId: 'follower-2' }],
});
const proposal = await hiveConsensusRuntime.propose({ op: 'set', key: 'foo', value: 'bar' });
expect(proposal.id).toMatch(/.+/);
expect(proposal.status).toBe('pending');
expect(proposal.proposerId).toBe('queen-B');
// Cast a vote via the runtime — should not throw.
await hiveConsensusRuntime.vote(proposal.id, {
voterId: 'queen-B',
approve: true,
confidence: 1.0,
timestamp: new Date(),
});
const stats = hiveConsensusRuntime.status().engine;
expect(stats?.totalProposals).toBeGreaterThanOrEqual(1);
});
it('Raft engine self-elects with no peers and accepts a proposal', async () => {
// Single-node Raft: no peers means immediate self-election.
// Validates the runtime's transport-wired engine actually performs
// leader election under the transport layer.
const result = await hiveConsensusRuntime.init({
nodeId: 'queen-R',
algorithm: 'raft',
transport: 'local',
timeoutMs: 200,
});
expect(result.algorithm).toBe('raft');
// Give the election timer a moment to fire (default raft election
// timeout in @claude-flow/swarm is short — see raft.test.ts).
await new Promise(r => setTimeout(r, 400));
// With no peers, the node should be leader by now. If not, the
// engine still accepts the proposal via `becomeLeader()` fallback in
// some configs — we only assert no throw.
try {
const proposal = await hiveConsensusRuntime.propose({ op: 'ping' });
expect(proposal.id).toMatch(/.+/);
} catch (err) {
// Raft may not have self-elected yet in this configuration. Confirm
// the error surface is the documented one rather than something else.
expect(String(err)).toMatch(/leader/i);
}
});
});
describe('hive-consensus-runtime / federation fallback', () => {
it('init({transport:"federation"}) degrades to local when agentic-flow missing', async () => {
const result = await hiveConsensusRuntime.init({
nodeId: 'queen-C',
algorithm: 'raft',
transport: 'federation',
peers: [{ nodeId: 'remote-1', address: 'wss://example:443' }],
});
// agentic-flow isn't installed under v3/@claude-flow/cli/node_modules
// (it's only the federation plugin's optional peer dep), so this
// path MUST degrade rather than throw.
expect(result.transport).toBe('local');
expect(result.degraded).toBe(true);
expect(typeof result.fallbackReason).toBe('string');
expect(result.fallbackReason).toContain('agentic-flow');
});
it('init({transport:"auto"}) silently picks local when federation unreachable', async () => {
const result = await hiveConsensusRuntime.init({
nodeId: 'queen-D',
algorithm: 'raft',
transport: 'auto',
});
expect(result.transport).toBe('local');
// auto mode does NOT set degraded — silent fallback is the
// documented behavior so callers don't see noise unless they
// explicitly asked for federation.
expect(result.degraded).toBe(false);
});
});
describe('hive-consensus-runtime / lifecycle', () => {
it('shutdown is idempotent', async () => {
await hiveConsensusRuntime.init({ nodeId: 'queen-E', transport: 'local' });
await hiveConsensusRuntime.shutdown();
// Second call should not throw.
await expect(hiveConsensusRuntime.shutdown()).resolves.toBeUndefined();
expect(hiveConsensusRuntime.isInitialized()).toBe(false);
});
it('re-init with a different nodeId tears down the old engine', async () => {
const first = await hiveConsensusRuntime.init({ nodeId: 'queen-F1', transport: 'local' });
expect(first.nodeId).toBe('queen-F1');
const second = await hiveConsensusRuntime.init({ nodeId: 'queen-F2', transport: 'local' });
expect(second.nodeId).toBe('queen-F2');
expect(hiveConsensusRuntime.status().nodeId).toBe('queen-F2');
});
it('status() before init returns a not-initialized shape', async () => {
const status = hiveConsensusRuntime.status();
expect(status.initialized).toBe(false);
expect(status.transport).toBeNull();
expect(status.engine).toBeNull();
expect(status.peers).toEqual([]);
});
it('propose before init throws a clear error', async () => {
await expect(hiveConsensusRuntime.propose({ x: 1 })).rejects.toThrow(/not initialized/);
});
});
describe('hive-consensus-runtime / 3-node end-to-end via LocalTransport registry', () => {
// This validates the FULL stack: real ConsensusEngine instances, real
// LocalTransport, real Raft RPC over the in-process registry. Three
// engines elect a leader and replicate a value across the cluster.
it('three engines on a shared registry propagate proposals via transport (gossip)', async () => {
// Gossip exercises the broadcast path of the transport more
// realistically than Raft (which would force us to wait for an
// election). Three nodes register with a shared LocalTransport
// registry; one proposes, all vote, stats reflect the round-trip.
const registry = new LocalTransportRegistry();
const nodeIds = ['n1', 'n2', 'n3'];
const engines: ConsensusEngine[] = [];
const transports: LocalTransport[] = [];
for (const id of nodeIds) {
const t = new LocalTransport(id, { registry, defaultTimeoutMs: 1000 });
transports.push(t);
const e = new ConsensusEngine(id, {
algorithm: 'gossip',
threshold: 0.66,
timeoutMs: 1000,
maxRounds: 5,
requireQuorum: true,
transport: t as unknown,
});
await e.initialize();
for (const peer of nodeIds.filter(p => p !== id)) {
e.addNode(peer);
}
engines.push(e);
}
// n1 proposes — verify it lands on the proposer's engine.
const proposal = await engines[0]!.propose({ op: 'increment', key: 'counter' });
expect(proposal.id).toMatch(/.+/);
expect(proposal.proposerId).toBe('n1');
// Vote from all three via the proposer's engine.
for (const voter of nodeIds) {
await engines[0]!.vote(proposal.id, {
voterId: voter,
approve: true,
confidence: 1.0,
timestamp: new Date(),
});
}
const stats = engines[0]!.getStats();
expect(stats.totalProposals).toBeGreaterThanOrEqual(1);
// Transports report each other as peers (real registry membership).
for (const t of transports) {
expect(t.peers().length).toBe(nodeIds.length - 1);
}
// Clean up
for (const e of engines) await e.shutdown();
for (const t of transports) await t.close();
});
});
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/cli",
"version": "3.7.0-alpha.44",
"version": "3.7.0-alpha.45",
"type": "module",
"description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code",
"main": "dist/src/index.js",
@@ -105,7 +105,8 @@
"yaml": "^2.8.0",
"@claude-flow/memory": "^3.0.0-alpha.17",
"@claude-flow/embeddings": "^3.0.0-alpha.18",
"@claude-flow/security": "^3.0.0-alpha.8"
"@claude-flow/security": "^3.0.0-alpha.8",
"@claude-flow/swarm": "^3.0.0-alpha.8"
},
"optionalDependencies": {
"@claude-flow/aidefence": "^3.0.2",
@@ -0,0 +1,382 @@
/**
* Hive-Mind Consensus Runtime — ADR-095 G2.2.
*
* Before this module, `hive-mind_*` MCP tools were a JSON-file state machine
* that hand-rolled raft/byzantine/quorum voting on top of `state.consensus`
* and never touched `@claude-flow/swarm`'s real `ConsensusEngine`. That worked
* for a single MCP server but ignored every cross-host machinery G2 was meant
* to unlock: real RequestVote/AppendEntries RPCs, Ed25519-signed PBFT
* messages, FederationTransport over ADR-104 WS, BFT quorum derived from
* actual cluster size.
*
* This module owns a process-level `ConsensusEngine` plus a pluggable
* `ConsensusTransport`. `hive-mind_init` calls `init()` here; the consensus /
* broadcast / shutdown MCP tools delegate to it.
*
* Transport selection:
* - `transport: 'local'` → LocalTransport (in-process registry).
* Matches the legacy single-process path;
* real engine, just no WS.
* - `transport: 'federation'` → FederationTransport over an
* agentic-flow/transport/loader wire.
* Real cross-host messaging. Requires
* `agentic-flow` to be resolvable; if
* it's not, init returns
* `transport: 'local'` with `degraded:
* true` and a fallbackReason — the
* engine still works locally, the caller
* just knows the cross-host wire didn't
* come up.
* - `transport: 'auto'` (default)→ Probe for `agentic-flow`; if loadable
* AND `peers` were supplied with
* addresses, use federation; else local.
*
* Why peers are passed in (not auto-discovered): the federation plugin's
* DiscoveryService is the canonical source of peers, but wiring it into the
* MCP runtime is a separate concern (it has its own lifecycle / consent
* gates). Until that lands as G2.3, callers explicitly supply the peer
* list; the runtime is honest about what it received.
*/
import type {
ConsensusEngine as ConsensusEngineType,
ConsensusTransport as ConsensusTransportType,
ConsensusVote,
ConsensusProposal,
ConsensusResult,
ConsensusAlgorithm,
} from '@claude-flow/swarm';
export type HiveTransportKind = 'local' | 'federation' | 'auto';
export type HiveAlgorithm = 'raft' | 'byzantine' | 'gossip';
export interface HivePeerConfig {
/** Consensus node id used by Raft/PBFT/Gossip as `from`. */
readonly nodeId: string;
/**
* Wire-level address (e.g. `wss://host:port`). Required for
* `transport: 'federation'`; ignored for `transport: 'local'`.
*/
readonly address?: string;
/**
* Ed25519 SPKI PEM public key for inbound signature verification.
* When provided, FederationTransport will fail-closed on unverifiable
* messages from this peer.
*/
readonly publicKeyPem?: string;
}
export interface HiveRuntimeInitOptions {
readonly nodeId: string;
readonly algorithm?: HiveAlgorithm;
readonly transport?: HiveTransportKind;
readonly peers?: readonly HivePeerConfig[];
/** Default per-send timeout for transports. */
readonly timeoutMs?: number;
/** Consensus threshold (0-1). Forwarded to ConsensusEngine. */
readonly threshold?: number;
}
export interface HiveRuntimeInitResult {
readonly initialized: true;
readonly nodeId: string;
readonly algorithm: HiveAlgorithm;
/** What we actually got — may differ from requested if federation degraded. */
readonly transport: 'local' | 'federation';
/** True when the caller asked for federation but we fell back to local. */
readonly degraded: boolean;
/** Human-readable reason for the degradation. */
readonly fallbackReason?: string;
readonly peerCount: number;
readonly source: 'engine';
}
export interface HiveRuntimeStatus {
readonly initialized: boolean;
readonly nodeId?: string;
readonly algorithm?: HiveAlgorithm;
readonly transport: 'local' | 'federation' | null;
readonly degraded: boolean;
readonly peers: readonly string[];
readonly engine: {
readonly algorithm: ConsensusAlgorithm;
readonly totalProposals: number;
readonly pendingProposals: number;
readonly acceptedProposals: number;
readonly rejectedProposals: number;
readonly expiredProposals: number;
} | null;
}
interface AgenticFlowTransportLike {
send(address: string, message: { type?: string; payload: unknown; streamId?: string }): Promise<void>;
onMessage(handler: (msg: { from?: string; address?: string; type?: string; payload: unknown }) => void | Promise<void>): void;
close?(): Promise<void> | void;
}
class HiveConsensusRuntime {
private engine: ConsensusEngineType | null = null;
private transport: ConsensusTransportType | null = null;
private wire: AgenticFlowTransportLike | null = null;
private transportKind: 'local' | 'federation' | null = null;
private nodeId: string | null = null;
private algorithm: HiveAlgorithm = 'raft';
private peers: HivePeerConfig[] = [];
private degraded = false;
private fallbackReason: string | undefined;
isInitialized(): boolean {
return this.engine !== null;
}
/**
* Lazy-initialize the consensus engine + transport. Idempotent on the
* same nodeId/algorithm/transport tuple — subsequent calls return the
* existing state. Different parameters trigger a clean shutdown + reinit.
*/
async init(opts: HiveRuntimeInitOptions): Promise<HiveRuntimeInitResult> {
const requestedAlgorithm: HiveAlgorithm = opts.algorithm ?? 'raft';
const requestedTransport: HiveTransportKind = opts.transport ?? 'auto';
const peers = [...(opts.peers ?? [])];
// If already initialized with the same shape, return existing state.
if (this.engine && this.nodeId === opts.nodeId && this.algorithm === requestedAlgorithm) {
return this.toInitResult();
}
// Different shape — tear down before re-instantiating.
if (this.engine) {
await this.shutdown();
}
const swarm = await import('@claude-flow/swarm');
// Resolve transport. 'auto' prefers federation when the loader is
// available AND we have peer addresses; otherwise local.
let resolvedKind: 'local' | 'federation';
let resolvedTransport: ConsensusTransportType;
let degraded = false;
let fallbackReason: string | undefined;
if (requestedTransport === 'local') {
resolvedKind = 'local';
resolvedTransport = new swarm.LocalTransport(opts.nodeId, {
defaultTimeoutMs: opts.timeoutMs,
});
} else {
// 'federation' or 'auto' → probe agentic-flow loader.
const probe = await this.tryLoadFederationWire(opts);
if (probe.wire) {
// Build the addressOf map from peers config.
const addressMap = new Map<string, string>();
const pubkeyMap = new Map<string, string>();
for (const p of peers) {
if (p.address) addressMap.set(p.nodeId, p.address);
if (p.publicKeyPem) pubkeyMap.set(p.nodeId, p.publicKeyPem);
}
this.wire = probe.wire;
resolvedKind = 'federation';
resolvedTransport = new swarm.FederationTransport(probe.wire, {
nodeId: opts.nodeId,
addressOf: (id) => addressMap.get(id),
peerIds: () => peers.map(p => p.nodeId),
defaultTimeoutMs: opts.timeoutMs,
resolvePeerPublicKey: pubkeyMap.size > 0 ? (id) => pubkeyMap.get(id) : undefined,
});
} else {
// Couldn't load federation wire. 'federation' requested → degrade
// honestly. 'auto' → silently fall back to local.
if (requestedTransport === 'federation') {
degraded = true;
fallbackReason = probe.reason ?? 'agentic-flow loader unavailable';
}
resolvedKind = 'local';
resolvedTransport = new swarm.LocalTransport(opts.nodeId, {
defaultTimeoutMs: opts.timeoutMs,
});
}
}
// Build the engine with the resolved transport. We pass `transport`
// through `config.transport` (typed `unknown` on `ConsensusConfig` in
// swarm's types.ts — the engine narrows it via a structural check).
const engine = new swarm.ConsensusEngine(opts.nodeId, {
algorithm: requestedAlgorithm as ConsensusAlgorithm,
threshold: opts.threshold ?? 0.66,
timeoutMs: opts.timeoutMs ?? 30_000,
maxRounds: 10,
requireQuorum: true,
transport: resolvedTransport as unknown,
});
await engine.initialize();
// Register peers with the consensus engine so its protocol-internal
// bookkeeping (Raft's `peers` map, BFT's node set, gossip neighbors)
// matches the transport's peer list.
for (const p of peers) {
if (p.nodeId === opts.nodeId) continue;
engine.addNode(p.nodeId);
}
this.engine = engine;
this.transport = resolvedTransport;
this.transportKind = resolvedKind;
this.nodeId = opts.nodeId;
this.algorithm = requestedAlgorithm;
this.peers = peers;
this.degraded = degraded;
this.fallbackReason = fallbackReason;
return this.toInitResult();
}
/**
* Probe for the agentic-flow QUIC/WS transport loader. Returns the wire
* when loadable; an explanatory reason when not. Never throws — failure
* is data, not control flow, so the runtime can degrade cleanly.
*/
private async tryLoadFederationWire(
_opts: HiveRuntimeInitOptions,
): Promise<{ wire: AgenticFlowTransportLike | null; reason?: string }> {
// agentic-flow is an *optional* peer dep — when it isn't installed,
// dynamic import throws and we degrade. The bare-string specifier
// is wrapped in a `new Function(...)` so the TS compiler doesn't try
// to resolve types at build time (the same pattern the federation
// plugin's loader uses, see ADR-120 step 2 comments).
const importDynamic = new Function('s', 'return import(s)') as (s: string) => Promise<unknown>;
let mod: unknown;
try {
mod = await importDynamic('agentic-flow/transport/loader');
} catch (err) {
return { wire: null, reason: `agentic-flow not installed (${(err as Error).message ?? 'unknown'})` };
}
const m = mod as {
loadQuicTransport?: (c?: unknown) => Promise<AgenticFlowTransportLike>;
default?: { loadQuicTransport?: (c?: unknown) => Promise<AgenticFlowTransportLike> };
};
const fn = typeof m.loadQuicTransport === 'function'
? m.loadQuicTransport
: m.default?.loadQuicTransport;
if (typeof fn !== 'function') {
return { wire: null, reason: 'agentic-flow loader does not expose loadQuicTransport' };
}
try {
const wire = await fn();
if (!wire || typeof wire.send !== 'function' || typeof wire.onMessage !== 'function') {
return { wire: null, reason: 'agentic-flow loader returned a wire without send/onMessage' };
}
return { wire };
} catch (err) {
return { wire: null, reason: `agentic-flow loader threw: ${(err as Error).message ?? 'unknown'}` };
}
}
/** Propose a value through the real ConsensusEngine. */
async propose(value: unknown, proposerId?: string): Promise<ConsensusProposal> {
if (!this.engine) throw new Error('hive-consensus-runtime: not initialized');
return this.engine.propose(value, proposerId ?? this.nodeId ?? 'unknown');
}
/** Record a vote against an active proposal. */
async vote(proposalId: string, vote: ConsensusVote): Promise<void> {
if (!this.engine) throw new Error('hive-consensus-runtime: not initialized');
await this.engine.vote(proposalId, vote);
}
/**
* Block until a proposal resolves (accepted / rejected / expired).
* Used by the MCP tool when callers want a synchronous result instead
* of polling `proposal-status`.
*/
async awaitConsensus(proposalId: string): Promise<ConsensusResult> {
if (!this.engine) throw new Error('hive-consensus-runtime: not initialized');
return this.engine.awaitConsensus(proposalId);
}
/**
* Broadcast a free-form payload to all known peers via the transport.
* Gossip-style, no reply expected. Wraps the payload so peers don't
* confuse it with protocol messages — `type: 'hive-broadcast'`.
*/
async broadcast(payload: unknown, priority: 'low' | 'normal' | 'high' | 'critical' = 'normal'): Promise<{ delivered: number; transport: 'local' | 'federation' }> {
if (!this.transport) throw new Error('hive-consensus-runtime: not initialized');
const peers = this.transport.peers();
await this.transport.broadcast({
type: 'hive-broadcast',
payload: { value: payload, priority, sentAt: new Date().toISOString() },
});
return { delivered: peers.length, transport: this.transportKind! };
}
status(): HiveRuntimeStatus {
if (!this.engine || !this.transport) {
return {
initialized: false,
transport: null,
degraded: false,
peers: [],
engine: null,
};
}
return {
initialized: true,
nodeId: this.nodeId!,
algorithm: this.algorithm,
transport: this.transportKind,
degraded: this.degraded,
peers: [...this.transport.peers()],
engine: this.engine.getStats(),
};
}
async shutdown(): Promise<void> {
const engine = this.engine;
const transport = this.transport;
const wire = this.wire;
this.engine = null;
this.transport = null;
this.wire = null;
this.transportKind = null;
this.nodeId = null;
this.peers = [];
this.degraded = false;
this.fallbackReason = undefined;
if (engine) {
try { await engine.shutdown(); } catch { /* best-effort */ }
}
if (transport) {
try { await transport.close(); } catch { /* best-effort */ }
}
if (wire && typeof wire.close === 'function') {
try { await wire.close(); } catch { /* best-effort */ }
}
}
/** Test seam: replace the singleton's underlying engine + transport. */
__setForTest(engine: ConsensusEngineType, transport: ConsensusTransportType, nodeId: string, kind: 'local' | 'federation' = 'local'): void {
this.engine = engine;
this.transport = transport;
this.nodeId = nodeId;
this.transportKind = kind;
}
private toInitResult(): HiveRuntimeInitResult {
return {
initialized: true,
nodeId: this.nodeId!,
algorithm: this.algorithm,
transport: this.transportKind!,
degraded: this.degraded,
fallbackReason: this.fallbackReason,
peerCount: this.peers.length,
source: 'engine',
};
}
}
/** Process-level singleton — one engine per MCP server. */
export const hiveConsensusRuntime = new HiveConsensusRuntime();
/** Re-export the singleton's type for tests / advanced consumers. */
export type { HiveConsensusRuntime };
@@ -2,12 +2,20 @@
* Hive-Mind MCP Tools for CLI
*
* Tool definitions for collective intelligence and swarm coordination.
*
* ADR-095 G2.2 — these tools now delegate inter-node consensus to the real
* `@claude-flow/swarm` ConsensusEngine via `hive-consensus-runtime`. The
* legacy JSON-state-machine voting (in `hive-mind_consensus`'s 'propose' /
* 'vote' / 'status' / 'list' actions) remains as a fallback when the
* runtime isn't initialized — preserves backward compatibility for callers
* that skip `hive-mind_init` or run in a swarm-less context.
*/
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { type MCPTool, getProjectCwd } from './types.js';
import { validateIdentifier, validateText } from './validate-input.js';
import { hiveConsensusRuntime, type HivePeerConfig, type HiveTransportKind, type HiveAlgorithm } from './hive-consensus-runtime.js';
// Storage paths
const STORAGE_DIR = '.claude-flow';
@@ -311,6 +319,33 @@ 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' },
// ADR-095 G2.2 — pluggable transport for the underlying consensus
// engine. 'local' (default) preserves single-process behavior;
// 'federation' wires Raft/PBFT/Gossip over ADR-104 WS via
// agentic-flow; 'auto' picks federation when reachable + peers
// supplied, else local.
transport: {
type: 'string',
enum: ['local', 'federation', 'auto'],
description: 'Consensus transport. local=in-process; federation=ADR-104 WS (cross-host); auto=federation if reachable, else local. Default: auto.',
},
// ADR-095 G2.2 — peers for the consensus engine. When transport is
// 'federation' or 'auto', each peer should include a wire address
// (e.g. wss://host:8443) and optionally an Ed25519 public key PEM
// for inbound signature verification.
peers: {
type: 'array',
description: 'Consensus peer list. Each entry: { nodeId, address?, publicKeyPem? }.',
items: {
type: 'object',
properties: {
nodeId: { type: 'string' },
address: { type: 'string' },
publicKeyPem: { type: 'string' },
},
required: ['nodeId'],
},
},
},
},
handler: async (input) => {
@@ -333,6 +368,41 @@ export const hiveMindTools: MCPTool[] = [
saveHiveState(state);
// ADR-095 G2.2 — bring up the real consensus runtime so subsequent
// hive-mind_consensus / hive-mind_broadcast calls go through the
// engine + transport instead of the JSON state machine. Done after
// saveHiveState so a runtime failure doesn't leave persisted state
// inconsistent — we surface the runtime error in the response but
// the hive itself stays initialized at the file-state layer.
const requestedTransport = (input.transport as HiveTransportKind) || 'auto';
// Map the wider consensus strategy enum to the runtime's algorithm.
// 'crdt' and 'quorum' don't have engine implementations; they keep
// the legacy state-machine voting and we tag the runtime as 'raft'
// (the safe default — quorum semantics are layered on by the
// state-machine code in hive-mind_consensus below).
const runtimeAlgorithm: HiveAlgorithm =
requestedConsensus === 'byzantine' ? 'byzantine'
: requestedConsensus === 'gossip' ? 'gossip'
: 'raft';
const peers: HivePeerConfig[] = Array.isArray(input.peers)
? (input.peers as unknown[]).filter((p): p is HivePeerConfig => {
return !!p && typeof p === 'object' && typeof (p as Record<string, unknown>).nodeId === 'string';
})
: [];
let runtimeResult: Awaited<ReturnType<typeof hiveConsensusRuntime.init>> | null = null;
let runtimeError: string | undefined;
try {
runtimeResult = await hiveConsensusRuntime.init({
nodeId: queenId,
algorithm: runtimeAlgorithm,
transport: requestedTransport,
peers,
});
} catch (err) {
runtimeError = err instanceof Error ? err.message : String(err);
}
return {
success: true,
hiveId,
@@ -348,6 +418,22 @@ export const hiveMindTools: MCPTool[] = [
memoryBackend: input.memoryBackend || 'hybrid',
},
createdAt: state.createdAt,
// ADR-095 G2.2 — runtime observability so callers know which
// transport / algorithm is actually live.
runtime: runtimeResult
? {
engine: 'enabled',
algorithm: runtimeResult.algorithm,
transport: runtimeResult.transport,
degraded: runtimeResult.degraded,
fallbackReason: runtimeResult.fallbackReason,
peerCount: runtimeResult.peerCount,
}
: {
engine: 'unavailable',
error: runtimeError,
note: 'Consensus engine could not be brought up — legacy state-machine voting will be used for hive-mind_consensus / broadcast.',
},
};
},
},
@@ -528,7 +614,7 @@ export const hiveMindTools: MCPTool[] = [
inputSchema: {
type: 'object',
properties: {
action: { type: 'string', enum: ['propose', 'vote', 'status', 'list'], description: 'Consensus action' },
action: { type: 'string', enum: ['propose', 'vote', 'status', 'list', 'engine-stats'], description: 'Consensus action' },
proposalId: { type: 'string', description: 'Proposal ID (for vote/status)' },
type: { type: 'string', description: 'Proposal type (for propose)' },
value: { description: 'Proposal value (for propose)' },
@@ -538,6 +624,12 @@ export const hiveMindTools: MCPTool[] = [
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)' },
timeoutMs: { type: 'number', description: 'Timeout in ms for raft re-proposal (default: 30000)' },
// ADR-095 G2.2 — route through the real consensus engine when set.
// Default false to preserve backward compatibility for callers that
// depend on the JSON-state-machine semantics (BFT detection across
// proposals, quorum presets, etc.).
useEngine: { type: 'boolean', description: 'Route propose/vote through the real ConsensusEngine (ADR-095 G2.2). Requires hive-mind_init to have brought up the runtime.' },
confidence: { type: 'number', description: 'Vote confidence 0-1 (only used when useEngine is true).' },
},
required: ['action'],
},
@@ -551,6 +643,66 @@ export const hiveMindTools: MCPTool[] = [
const strategy = (input.strategy as ConsensusStrategy) || 'raft';
const totalNodes = state.workers.length || 1;
// ADR-095 G2.2 — engine-stats surfaces the live runtime state.
// Returns a 'not-initialized' shape (not an error) when the runtime
// is offline so monitoring tools don't have to special-case startup.
if (action === 'engine-stats') {
const status = hiveConsensusRuntime.status();
return { action, ...status };
}
// ADR-095 G2.2 — when useEngine is true and the runtime is up,
// propose/vote go through the real ConsensusEngine. Falls back to
// the JSON-state-machine path below when the runtime isn't
// initialized, so callers that don't ask for engine routing get
// the legacy behavior.
const useEngine = input.useEngine === true && hiveConsensusRuntime.isInitialized();
if (useEngine && action === 'propose') {
try {
const proposal = await hiveConsensusRuntime.propose(
input.value,
(input.voterId as string) || (state.queen?.agentId ?? 'queen'),
);
return {
action,
proposalId: proposal.id,
type: (input.type as string) || 'general',
strategy: hiveConsensusRuntime.status().algorithm,
status: proposal.status,
term: proposal.term,
engine: 'enabled',
transport: hiveConsensusRuntime.status().transport,
};
} catch (err) {
return { action, error: `consensus engine propose failed: ${err instanceof Error ? err.message : String(err)}` };
}
}
if (useEngine && action === 'vote') {
const voterId = input.voterId as string;
if (!voterId) return { action, error: 'voterId is required for voting' };
if (!input.proposalId) return { action, error: 'proposalId is required for voting' };
try {
await hiveConsensusRuntime.vote(input.proposalId as string, {
voterId,
approve: input.vote as boolean,
confidence: typeof input.confidence === 'number' ? (input.confidence as number) : 1.0,
timestamp: new Date(),
});
return {
action,
proposalId: input.proposalId,
voterId,
vote: input.vote,
engine: 'enabled',
transport: hiveConsensusRuntime.status().transport,
};
} catch (err) {
return { action, error: `consensus engine vote failed: ${err instanceof Error ? err.message : String(err)}` };
}
}
if (action === 'propose') {
const proposalId = `proposal-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const quorumPreset = (input.quorumPreset as QuorumPreset) || 'majority';
@@ -863,13 +1015,14 @@ export const hiveMindTools: MCPTool[] = [
if (input.fromId) { const v = validateIdentifier(input.fromId as string, 'fromId'); if (!v.valid) return { success: false, error: v.error }; }
const messageId = `msg-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const priority = (input.priority as 'low' | 'normal' | 'high' | 'critical') || 'normal';
// Store in shared memory
// Store in shared memory (always — this is the durable record).
const messages = (state.sharedMemory.broadcasts as Array<unknown>) || [];
messages.push({
messageId,
message: input.message,
priority: input.priority || 'normal',
priority,
fromId: input.fromId || 'system',
timestamp: new Date().toISOString(),
});
@@ -878,12 +1031,36 @@ export const hiveMindTools: MCPTool[] = [
state.sharedMemory.broadcasts = messages.slice(-100);
saveHiveState(state);
// ADR-095 G2.2 — when the consensus runtime is up, also push the
// broadcast over its transport so cross-process / cross-host
// peers actually receive it. Local-only runtimes still benefit
// (in-process peers get a real handler invocation).
let transportDelivered: number | undefined;
let transportKind: 'local' | 'federation' | undefined;
let transportError: string | undefined;
if (hiveConsensusRuntime.isInitialized()) {
try {
const res = await hiveConsensusRuntime.broadcast(
{ messageId, message: input.message, fromId: input.fromId || 'system' },
priority,
);
transportDelivered = res.delivered;
transportKind = res.transport;
} catch (err) {
transportError = err instanceof Error ? err.message : String(err);
}
}
return {
success: true,
messageId,
recipients: state.workers.length,
priority: input.priority || 'normal',
priority,
broadcastAt: new Date().toISOString(),
transport: transportKind
? { kind: transportKind, delivered: transportDelivered }
: { kind: 'state-machine-only', note: 'runtime offline — broadcast persisted to sharedMemory only' },
...(transportError ? { transportError } : {}),
};
},
},
@@ -941,6 +1118,17 @@ export const hiveMindTools: MCPTool[] = [
state.sharedMemory = {};
saveHiveState(state);
// ADR-095 G2.2 — tear down the consensus runtime alongside the
// file-state. Best-effort: a runtime that's already offline is
// not an error.
let runtimeShutdown = false;
try {
if (hiveConsensusRuntime.isInitialized()) {
await hiveConsensusRuntime.shutdown();
runtimeShutdown = true;
}
} catch { /* best-effort */ }
return {
success: true,
shutdownAt: shutdownTime,
@@ -948,6 +1136,7 @@ export const hiveMindTools: MCPTool[] = [
workersTerminated: workerCount,
previousQueen,
consensusCleared: pendingConsensus,
runtimeShutdown,
message: `Hive-mind shutdown complete. ${workerCount} workers terminated.`,
};
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/swarm",
"version": "3.0.0-alpha.7",
"version": "3.0.0-alpha.8",
"type": "module",
"description": "Standalone swarm coordination - up to 100+ agents, 4 topologies, hive-mind, consensus",
"main": "dist/index.js",
@@ -16,6 +16,7 @@ import {
import { RaftConsensus, createRaftConsensus, RaftConfig } from './raft.js';
import { ByzantineConsensus, createByzantineConsensus, ByzantineConfig } from './byzantine.js';
import { GossipConsensus, createGossipConsensus, GossipConfig } from './gossip.js';
import type { ConsensusTransport } from './transport.js';
export { RaftConsensus, ByzantineConsensus, GossipConsensus };
export type { RaftConfig, ByzantineConfig, GossipConfig };
@@ -74,6 +75,14 @@ export class ConsensusEngine extends EventEmitter implements IConsensusEngine {
this.config = { ...this.config, ...config };
}
// ADR-095 G2.2 — narrow the typed-as-unknown `transport` from
// ConsensusConfig into the real ConsensusTransport so Raft / Byzantine /
// Gossip get a working inter-node wire. Structural check, not
// instanceof, so test mocks satisfy it without importing transport.ts.
const transport = isConsensusTransport(this.config.transport)
? this.config.transport
: undefined;
// Create implementation based on algorithm
switch (this.config.algorithm) {
case 'raft':
@@ -82,6 +91,7 @@ export class ConsensusEngine extends EventEmitter implements IConsensusEngine {
timeoutMs: this.config.timeoutMs,
maxRounds: this.config.maxRounds,
requireQuorum: this.config.requireQuorum,
transport,
});
break;
@@ -91,6 +101,7 @@ export class ConsensusEngine extends EventEmitter implements IConsensusEngine {
timeoutMs: this.config.timeoutMs,
maxRounds: this.config.maxRounds,
requireQuorum: this.config.requireQuorum,
transport,
});
break;
@@ -100,6 +111,7 @@ export class ConsensusEngine extends EventEmitter implements IConsensusEngine {
timeoutMs: this.config.timeoutMs,
maxRounds: this.config.maxRounds,
requireQuorum: this.config.requireQuorum,
transport,
});
break;
@@ -110,6 +122,7 @@ export class ConsensusEngine extends EventEmitter implements IConsensusEngine {
timeoutMs: this.config.timeoutMs,
maxRounds: this.config.maxRounds,
requireQuorum: this.config.requireQuorum,
transport,
});
break;
@@ -262,6 +275,23 @@ export function createConsensusEngine(
return new ConsensusEngine(nodeId, { ...config, algorithm });
}
/**
* ADR-095 G2.2 — structural check that an opaque value implements the
* ConsensusTransport interface. Used by the engine to safely narrow the
* `transport` field on `ConsensusConfig` (typed as `unknown` to keep
* `types.ts` free of cross-module imports).
*/
function isConsensusTransport(value: unknown): value is ConsensusTransport {
if (!value || typeof value !== 'object') return false;
const t = value as Record<string, unknown>;
return typeof t.nodeId === 'string'
&& typeof t.send === 'function'
&& typeof t.broadcast === 'function'
&& typeof t.onMessage === 'function'
&& typeof t.peers === 'function'
&& typeof t.close === 'function';
}
// Helper to select optimal algorithm based on requirements
export function selectOptimalAlgorithm(requirements: {
faultTolerance: 'crash' | 'byzantine';
@@ -18,13 +18,13 @@ import {
TaskId,
SwarmEvent,
EventHandler
} from '../shared/types';
} from '../shared/types.js';
import {
IEventBus,
agentSpawnedEvent,
agentStatusChangedEvent,
agentErrorEvent
} from '../shared/events';
} from '../shared/events.js';
// =============================================================================
// Agent Registry Interface
@@ -41,7 +41,7 @@ import {
MessageHandler,
EventHandler,
V3_PERFORMANCE_TARGETS
} from '../shared/types';
} from '../shared/types.js';
import {
IEventBus,
EventBus,
@@ -49,10 +49,10 @@ import {
swarmPhaseChangedEvent,
swarmMilestoneReachedEvent,
swarmErrorEvent
} from '../shared/events';
import { IAgentRegistry, AgentRegistry, createAgentRegistry } from './agent-registry';
import { ITaskOrchestrator, TaskOrchestrator, TaskSpec, createTaskOrchestrator } from './task-orchestrator';
import { UnifiedSwarmCoordinator, createUnifiedSwarmCoordinator } from '../unified-coordinator';
} from '../shared/events.js';
import { IAgentRegistry, AgentRegistry, createAgentRegistry } from './agent-registry.js';
import { ITaskOrchestrator, TaskOrchestrator, TaskSpec, createTaskOrchestrator } from './task-orchestrator.js';
import { UnifiedSwarmCoordinator, createUnifiedSwarmCoordinator } from '../unified-coordinator.js';
// =============================================================================
// Swarm Hub Interface
@@ -18,7 +18,7 @@ import {
AgentDomain,
PhaseId,
SwarmEvent
} from '../shared/types';
} from '../shared/types.js';
import {
IEventBus,
taskCreatedEvent,
@@ -28,8 +28,8 @@ import {
taskCompletedEvent,
taskFailedEvent,
taskBlockedEvent
} from '../shared/events';
import { IAgentRegistry } from './agent-registry';
} from '../shared/events.js';
import { IAgentRegistry } from './agent-registry.js';
// =============================================================================
// Task Orchestrator Interface
+26
View File
@@ -198,6 +198,32 @@ export type {
GossipConfig,
} from './consensus/index.js';
// ADR-095 G2.2 — pluggable consensus transport. Re-export so consumers
// (@claude-flow/cli's hive-consensus-runtime, downstream plugins) don't
// have to deep-import from ./consensus/* or ./consensus/transport.js.
export {
LocalTransport,
LocalTransportRegistry,
defaultLocalRegistry,
FederationTransport,
generateNodeKeyPair,
signMessage,
verifyMessage,
canonicalizeForSigning,
messageDigest,
} from './consensus/index.js';
export type {
ConsensusTransport,
ConsensusMessage,
ConsensusReply,
ConsensusMessageHandler,
NodeKeyPair,
LocalTransportOptions,
AgenticFlowTransportLike,
FederationTransportOptions,
} from './consensus/index.js';
// =============================================================================
// Coordination Components
// =============================================================================
+10
View File
@@ -204,6 +204,16 @@ export interface ConsensusConfig {
timeoutMs: number;
maxRounds: number;
requireQuorum: boolean;
/**
* ADR-095 G2.2 — optional pluggable transport. When provided, the
* ConsensusEngine forwards it to the underlying Raft / Byzantine /
* Gossip implementation so their inter-node messaging actually
* crosses a process or host boundary. When omitted, protocols run
* in single-process mode (legacy behavior). Typed as `unknown` here
* to avoid forcing every consumer of `types.ts` to import the
* transport module; the engine narrows it via a structural check.
*/
transport?: unknown;
}
export interface ConsensusProposal {
@@ -200,6 +200,33 @@ Remaining for G2:
Tracked in [#1872](https://github.com/ruvnet/ruflo/issues/1872) and PR #1905.
### G2.2 — done (hive-mind MCP layer routes through the real ConsensusEngine)
After the G2 transport abstraction landed, the `hive-mind_*` MCP tools were still a JSON-file state machine — they never instantiated `ConsensusEngine`, never touched `LocalTransport` / `FederationTransport`, and the hand-rolled raft/byzantine/quorum voting in `hive-mind_consensus` ran on top of `state.consensus.pending/history` instead of the real protocols. So the cross-host machinery from G2 was unreachable from the surface the LLM agents actually call.
**Landed (PR #1872 follow-up, `@claude-flow/swarm@3.0.0-alpha.8` + `@claude-flow/cli@3.7.0-alpha.45`):**
- `v3/@claude-flow/cli/src/mcp-tools/hive-consensus-runtime.ts` — process-level singleton that owns a real `ConsensusEngine` + `ConsensusTransport`. Lifecycle: `init` → `propose` / `vote` / `awaitConsensus` / `broadcast` → `status` → `shutdown`.
- Transport selection logic:
- `transport: 'local'` → `LocalTransport` (in-process registry). Legacy single-process behavior, but with the real engine.
- `transport: 'federation'` → `FederationTransport` over `agentic-flow/transport/loader`. Cross-host wire. If the loader isn't installed, falls back to local with `degraded: true` + machine-parseable `fallbackReason`.
- `transport: 'auto'` (default) → silent fallback to local when federation isn't reachable; no noise unless the operator explicitly asked for federation.
- `ConsensusConfig.transport` field added (typed `unknown` to keep `types.ts` free of cross-module imports; engine narrows via a structural check). `ConsensusEngine.initialize()` forwards it to Raft / Byzantine / Gossip — closes the gap where the inner protocols accepted a transport but the engine wrapper never passed one through.
- `hive-mind_init` accepts `transport`, `algorithm`, `peers`; instantiates the runtime; returns `runtime: { engine, transport, algorithm, degraded, fallbackReason, peerCount }` so callers see which wire is actually live.
- `hive-mind_consensus` adds two engine-routed paths:
- `action: 'propose'` with `useEngine: true` → real `engine.propose(value, proposerId)`.
- `action: 'vote'` with `useEngine: true` → real `engine.vote(proposalId, vote)`.
- New `action: 'engine-stats'` returns the live runtime status (initialized? algorithm? transport? peers? engine.getStats()?).
- Legacy JSON-state-machine voting preserved as default; `useEngine: false` (or unset) keeps backward compat.
- `hive-mind_broadcast` proxies through `transport.broadcast` when the runtime is initialized; in-process peers get a real handler invocation, cross-host peers get the WS frame. Falls back to the file-state record when offline.
- `hive-mind_shutdown` tears down the runtime alongside the file-state (returns `runtimeShutdown: true`).
- Swarm-side ESM hygiene: `coordination/agent-registry.ts`, `task-orchestrator.ts`, `swarm-hub.ts` were missing `.js` extensions on their relative imports, which silently broke any non-vitest ESM consumer. Fixed alongside G2.2 — the test suite was hiding the issue because vitest's transform tolerated bare specifiers.
- Tests: **10/10 new** in `v3/@claude-flow/cli/__tests__/hive-consensus-runtime.test.ts` covering transport selection (local/federation/auto), federation-loader-missing degradation, propose-vote round-trip via real engine, shutdown idempotency, re-init teardown, 3-node `LocalTransport` registry membership.
- CI guard: `scripts/smoke-hive-consensus-engine.mjs` drives the real MCP handlers end-to-end and asserts `runtime.engine === 'enabled'`, `transport === 'local'`, `propose.engine === 'enabled'`, `shutdown.runtimeShutdown === true`. Wired as `hive-mind-consensus-engine-wire-up-smoke` in `v3-ci.yml`.
Remaining for G3 (G2.3):
- DiscoveryService integration: the runtime today takes an explicit peer list at init; the canonical peer source is the federation plugin's `DiscoveryService`. Wiring it in is the next step, with operator-consent gating.
- Live mac ↔ ruvultra round (real `FederationTransport` over tailscale, not the in-process LocalTransport).
### Still open
- **G5** — superseded by ADR-094; deps migration status tracked there.
@@ -190,6 +190,11 @@ export class PortfolioRiskCalculator {
/**
* Monte Carlo simulation for portfolio
*
* Returns an empty array on empty input — matches the sentinel-on-empty
* pattern used by calculateVolatility / calculateSharpe / calculateMaxDrawdown.
* Without this guard, mean = 0/0 = NaN propagates into every scenario.
* See ruvnet/ruflo#2024.
*/
monteCarloSimulation(
portfolioReturns: number[],
@@ -197,6 +202,8 @@ export class PortfolioRiskCalculator {
horizon: number = 252,
seed?: number
): number[] {
if (portfolioReturns.length === 0) return [];
// Simple random number generator with seed
let rng = seed !== undefined ? this.seededRandom(seed) : Math.random;
@@ -380,6 +387,12 @@ export class FinancialEconomyBridge implements EconomyBridge {
throw new Error('Economy bridge not initialized');
}
// Sentinel-on-empty: WASM path would receive a zero-length covariance and
// produce undefined output; the JS fallback's mean would be NaN. See #2024.
if (portfolio.length === 0) {
return new Float32Array(0);
}
if (this.wasmModule) {
// Create identity covariance for simplicity
const n = portfolio.length;
@@ -118,6 +118,19 @@ describe('FinancialEconomyBridge', () => {
expect(result).toBeInstanceOf(Float32Array);
expect(result.length).toBeGreaterThan(0);
});
// Regression guard for #2024 — empty portfolio used to fill the result
// with NaN (mean = 0/0 in the JS fallback). Must return an empty
// Float32Array now, matching the sentinel-on-empty pattern used by the
// other PortfolioRiskCalculator methods.
it('should return empty Float32Array for empty portfolio (regression #2024)', async () => {
const result = await bridge.simulateMonteCarlo(new Float32Array([]), 10, 5);
expect(result).toBeInstanceOf(Float32Array);
expect(result.length).toBe(0);
// Explicitly assert no NaN propagation
expect(Array.from(result).some(Number.isNaN)).toBe(false);
});
});
describe('Risk Calculation Methods', () => {