🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(hive-mind): honor the init persistence contract (#4336)
ordinary being76f2440487d1
diff --git a/v3/@claude-flow/cli/__tests__/hive-mind-init-persist-contract.test.ts b/v3/@claude-flow/cli/__tests__/hive-mind-init-persist-contract.test.tsnew file mode 100644index 0000000000..ca2403a7ef--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/hive-mind-init-persist-contract.test.ts@@ -0,0 +1,96 @@+/**+ * #655 follow-up: hive-mind_init's persistence contract.+ *+ * The handler read `persist`, `maxAgents` and `memoryBackend` out of the+ * input and echoed them in `config`, but the MCP schema declared none of+ * them, and `saveHiveState()` ran unconditionally. A caller that passed+ * `persist:false` was told persistence was off while state.json (and the+ * bootstrap secret) were still written. The status fallback also drifted to+ * "byzantine" for legacy state even though init's documented default is raft.+ *+ * #3241 covers the separate hiveId round-trip defect.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { hiveMindTools } from '../src/mcp-tools/hive-mind-tools.js';++const initTool = hiveMindTools.find(t => t.name === 'hive-mind_init')!;+const statusTool = hiveMindTools.find(t => t.name === 'hive-mind_status')!;+const statePath = (dir: string) => join(dir, '.claude-flow', 'hive-mind', 'state.json');+const hiveDir = (dir: string) => join(dir, '.claude-flow', 'hive-mind');++describe('hive-mind_init persistence contract (#655)', () => {+ let dir: string;+ let prevCwd: string | undefined;++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'hive-mind-persist-'));+ 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 });+ });++ it('declares the options the handler already consumes', () => {+ const props = initTool.inputSchema.properties as Record<string, Record<string, unknown>>;++ expect(props.maxAgents).toMatchObject({ type: 'number', minimum: 1, maximum: 1000, default: 15 });+ expect(props.memoryBackend).toMatchObject({ type: 'string', enum: ['agentdb', 'sqlite', 'hybrid'], default: 'hybrid' });+ expect(props.persist).toMatchObject({ type: 'boolean', default: true });+ });++ it('persist:false writes neither state.json nor the bootstrap secret', async () => {+ const result = await initTool.handler({ persist: false, maxAgents: 7, memoryBackend: 'sqlite' }) as Record<string, any>;++ expect(result.success).toBe(true);+ expect(result.persisted).toBe(false);+ expect(result.config).toMatchObject({ maxAgents: 7, memoryBackend: 'sqlite', persist: false });+ expect(existsSync(hiveDir(dir))).toBe(false);+ expect(existsSync(statePath(dir))).toBe(false);+ });++ it('persist:false leaves an existing state.json byte-for-byte unchanged', async () => {+ await initTool.handler({ maxAgents: 5, memoryBackend: 'hybrid' });+ const before = readFileSync(statePath(dir));++ await initTool.handler({ persist: false, maxAgents: 99, memoryBackend: 'agentdb' });++ expect(readFileSync(statePath(dir))).toEqual(before);+ });++ it('default init persists the requested config and status reports it', async () => {+ const init = await initTool.handler({ maxAgents: 12, memoryBackend: 'agentdb' }) as Record<string, any>;+ const status = await statusTool.handler({}) as Record<string, any>;+ const persisted = JSON.parse(readFileSync(statePath(dir), 'utf8'));++ expect(init.persisted).toBe(true);+ expect(persisted).toMatchObject({ maxAgents: 12, memoryBackend: 'agentdb', persist: true });+ expect(status.maxAgents).toBe(12);+ expect(status.memoryBackend).toBe('agentdb');+ });++ it('rejects invalid values before creating any durable state', async () => {+ for (const input of [{ maxAgents: 0 }, { maxAgents: 1001 }, { maxAgents: 2.5 }, { memoryBackend: 'redis' }, { persist: 'false' }]) {+ const result = await initTool.handler(input) as Record<string, any>;+ expect(result.success, JSON.stringify(input)).toBe(false);+ }+ expect(existsSync(hiveDir(dir))).toBe(false);+ });++ it('legacy state without a strategy reports raft, not byzantine', async () => {+ await initTool.handler({});+ const persisted = JSON.parse(readFileSync(statePath(dir), 'utf8'));+ delete persisted.consensusStrategy;+ const { writeFileSync } = await import('node:fs');+ writeFileSync(statePath(dir), JSON.stringify(persisted, null, 2));++ const status = await statusTool.handler({}) as Record<string, any>;+ expect(status.consensus).toBe('raft');+ });+});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 de7e4e786e..f920f62406 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@@ -26,6 +26,11 @@ interface HiveState {initialized: boolean;topology: 'mesh' | 'hierarchical' | 'ring' | 'star';consensusStrategy?: ConsensusStrategyName;+ // #655 follow-up: the init contract advertises these options. Persist the+ // requested values so a later status/read does not have to invent defaults.+ maxAgents?: number;+ memoryBackend?: 'agentdb' | 'sqlite' | 'hybrid';+ persist?: boolean;queen?: {agentId: string;electedAt: string;@@ -472,6 +477,24 @@ 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' },+ maxAgents: {+ type: 'number',+ minimum: 1,+ maximum: 1000,+ default: 15,+ description: 'Maximum number of agents the hive may contain (default: 15)',+ },+ memoryBackend: {+ type: 'string',+ enum: ['agentdb', 'sqlite', 'hybrid'],+ default: 'hybrid',+ description: 'Memory backend requested for this hive (default: hybrid)',+ },+ persist: {+ type: 'boolean',+ default: true,+ description: 'Persist hive state to .claude-flow/hive-mind/state.json. Set false for an ephemeral init that writes no durable state.',+ },bootstrapSecret: { type: 'string', description: 'Operator secret (RUFLO_HIVE_BOOTSTRAP_SECRET or .claude-flow/hive-mind/bootstrap.secret). Only needed by remote/HTTP callers; local stdio/CLI callers omit it. See ADR-476.' },},},@@ -483,13 +506,30 @@ export const hiveMindTools: MCPTool[] = [if (bootstrapError) {return { success: false, error: bootstrapError };}- // Local first init materialises the 0600 operator secret so a later- // remote/HTTP deployment has something to be told out of band. The- // value is never returned.- if (classifyCaller(context) === 'local') ensureBootstrapSecret();+ // Validate the advertised init contract before creating any durable+ // state (the operator secret is a filesystem write, so it must come+ // after every input check).+ if (input.persist !== undefined && typeof input.persist !== 'boolean') {+ return { success: false, error: 'persist must be a boolean' };+ }+ const persist = input.persist !== false;+ const maxAgents = input.maxAgents === undefined ? 15 : Number(input.maxAgents);+ if (!Number.isInteger(maxAgents) || maxAgents < 1 || maxAgents > 1000) {+ return { success: false, error: 'maxAgents must be an integer between 1 and 1000' };+ }+ const memoryBackend = input.memoryBackend === undefined ? 'hybrid' : String(input.memoryBackend);+ if (memoryBackend !== 'agentdb' && memoryBackend !== 'sqlite' && memoryBackend !== 'hybrid') {+ return { success: false, error: 'memoryBackend must be one of: agentdb, sqlite, hybrid' };+ }if (input.queenId) { const v = validateIdentifier(input.queenId as string, 'queenId'); if (!v.valid) return { success: false, error: v.error }; }+ // Local first init materialises the 0600 operator secret so a later+ // remote/HTTP deployment has something to be told out of band. The+ // value is never returned. An ephemeral init (persist:false) must not+ // write it either.+ if (persist && classifyCaller(context) === 'local') ensureBootstrapSecret();+const state = loadHiveState();const hiveId = `hive-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;const queenId = (input.queenId as string) || `queen-${Date.now()}`;@@ -498,6 +538,9 @@ export const hiveMindTools: MCPTool[] = [state.initialized = true;state.topology = (input.topology as HiveState['topology']) || 'mesh';state.consensusStrategy = requestedConsensus;+ state.maxAgents = maxAgents;+ state.memoryBackend = memoryBackend as HiveState['memoryBackend'];+ state.persist = persist;state.createdAt = new Date().toISOString();state.queen = {agentId: queenId,@@ -513,7 +556,7 @@ export const hiveMindTools: MCPTool[] = [state.hiveToken = randomBytes(32).toString('hex');}- saveHiveState(state);+ if (persist) saveHiveState(state);return {success: true,@@ -522,6 +565,7 @@ export const hiveMindTools: MCPTool[] = [consensus: state.consensusStrategy,queenId,status: 'initialized',+ persisted: persist,// Deliberately NOT echoing state.hiveToken here (even though this// call is itself now bootstrap-secret-gated): the CLI never reads// it off this response (it uses getHiveTokenForCli()'s direct@@ -530,9 +574,9 @@ export const hiveMindTools: MCPTool[] = [config: {topology: state.topology,consensus: state.consensusStrategy,- maxAgents: input.maxAgents || 15,- persist: input.persist !== false,- memoryBackend: input.memoryBackend || 'hybrid',+ maxAgents,+ persist,+ memoryBackend,},createdAt: state.createdAt,};@@ -580,8 +624,10 @@ export const hiveMindTools: MCPTool[] = [hiveId: `hive-${state.createdAt ? new Date(state.createdAt).getTime() : Date.now()}`,status: state.initialized ? 'active' : 'offline',topology: state.topology,- // ADR-093 F3: surface the persisted strategy instead of a hardcoded "byzantine".- consensus: state.consensusStrategy ?? 'byzantine',+ // ADR-093 F3: surface the persisted strategy instead of a hardcoded+ // "byzantine". Init's documented default is raft, so legacy state+ // without the field must not drift to a different protocol.+ consensus: state.consensusStrategy ?? 'raft',queen: state.queen ? {id: state.queen.agentId,agentId: state.queen.agentId,@@ -620,6 +666,8 @@ export const hiveMindTools: MCPTool[] = [// Additional fieldsid: `hive-${state.createdAt ? new Date(state.createdAt).getTime() : Date.now()}`,initialized: state.initialized,+ maxAgents: state.maxAgents ?? 15,+ memoryBackend: state.memoryBackend ?? 'hybrid',workerCount: state.workers.length,pendingConsensus: state.consensus.pending.length,sharedMemoryKeys: Object.keys(state.sharedMemory).length,