diff --git a/v3/@claude-flow/cli/__tests__/hive-capacity-4727.test.ts b/v3/@claude-flow/cli/__tests__/hive-capacity-4727.test.ts new file mode 100644 index 0000000000..5b8ee9ff98 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/hive-capacity-4727.test.ts @@ -0,0 +1,250 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { hiveMindTools, getHiveTokenForCli } from '../src/mcp-tools/hive-mind-tools.js'; +import { agentTools } from '../src/mcp-tools/agent-tools.js'; + +// Registration is real; its optional graph mirror is outside this file-store test. +vi.mock('../src/ruvector/graph-backend.js', () => ({ addNode: vi.fn() })); + +const run = (name: string, input: Record = {}, context?: Record) => + hiveMindTools.find(tool => tool.name === name)!.handler(input, context) as Promise>; + +describe('#4727 hive capacity and registered membership', () => { + let dir: string; + let previousCwd: string | undefined; + let previousAuth: string | undefined; + const path = (...parts: string[]) => join(dir, '.claude-flow', ...parts); + const read = (...parts: string[]) => JSON.parse(readFileSync(path(...parts), 'utf8')); + const write = (parts: string[], value: unknown) => { + const target = path(...parts); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, JSON.stringify(value, null, 2)); + }; + const snapshot = () => ['hive-mind/state.json', 'agents.json', 'agents/store.json'].map(file => + existsSync(path(file)) ? readFileSync(path(file), 'utf8') : null); + const register = async (agentId: string) => { + const result = await agentTools.find(tool => tool.name === 'agent_spawn')!.handler({ + agentId, agentType: 'coder', model: 'sonnet', config: { keep: 'config' }, + }) as Record; + expect(result.success).toBe(true); + }; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'ruflo-4727-')); + previousCwd = process.env.CLAUDE_FLOW_CWD; + previousAuth = process.env.RUFLO_HIVE_REQUIRE_AUTH; + process.env.CLAUDE_FLOW_CWD = dir; + delete process.env.RUFLO_HIVE_REQUIRE_AUTH; + }); + + afterEach(() => { + if (previousCwd === undefined) delete process.env.CLAUDE_FLOW_CWD; + else process.env.CLAUDE_FLOW_CWD = previousCwd; + if (previousAuth === undefined) delete process.env.RUFLO_HIVE_REQUIRE_AUTH; + else process.env.RUFLO_HIVE_REQUIRE_AUTH = previousAuth; + rmSync(dir, { recursive: true, force: true }); + }); + + it('rejects an oversized batch before creating any agents or changing hive data', async () => { + expect(await run('hive-mind_init', { maxAgents: 2 })).toHaveProperty('success', true); + await run('hive-mind_memory', { action: 'set', key: 'keep', value: { data: 42 } }); + const before = snapshot(); + const result = await run('hive-mind_spawn', { count: 3 }); + expect(result).toMatchObject({ success: false, maxAgents: 2 }); + expect(result.error).toMatch(/capacity|full|maxAgents/i); + expect(snapshot()).toEqual(before); + }); + + it('fills exactly to capacity, rejects the next batch in full, and reuses a slot after leave', async () => { + await run('hive-mind_init', { maxAgents: 2 }); + const first = await run('hive-mind_spawn', { count: 1, role: 'scout' }); + const before = snapshot(); + expect(await run('hive-mind_spawn', { count: 2 })).toHaveProperty('success', false); + expect(snapshot()).toEqual(before); + const second = await run('hive-mind_spawn'); + expect(second).toMatchObject({ success: true, spawned: 1, totalWorkers: 2 }); + expect(await run('hive-mind_spawn')).toHaveProperty('success', false); + expect(read('hive-mind', 'state.json').workers).toEqual([ + first.workers[0].agentId, second.workers[0].agentId, + ]); + expect(read('agents.json').agents[first.workers[0].agentId].config).toEqual({ role: 'scout', hiveRole: 'scout' }); + expect(await run('hive-mind_leave', { agentId: first.workers[0].agentId })).toHaveProperty('success', true); + expect(await run('hive-mind_spawn')).toMatchObject({ success: true, totalWorkers: 2 }); + }); + + it('enforces the default capacity for legacy state without maxAgents', async () => { + await run('hive-mind_init'); + const state = read('hive-mind', 'state.json'); + delete state.maxAgents; + write(['hive-mind', 'state.json'], state); + expect(await run('hive-mind_spawn', { count: 15 })).toMatchObject({ success: true, totalWorkers: 15 }); + await register('extra'); + const before = snapshot(); + expect(await run('hive-mind_spawn')).toHaveProperty('success', false); + expect(await run('hive-mind_join', { agentId: 'extra' })).toHaveProperty('success', false); + expect(snapshot()).toEqual(before); + }); + + it('joins normally registered agents, persists role, and permits a duplicate at capacity', async () => { + await run('hive-mind_init', { maxAgents: 1 }); + await register('coder'); + await register('extra'); + const original = read('agents', 'store.json'); + expect(await run('hive-mind_join', { agentId: 'coder', role: 'specialist' })).toMatchObject({ + success: true, role: 'specialist', totalWorkers: 1, + }); + const stored = read('agents', 'store.json'); + expect(stored).toEqual({ ...original, agents: { ...original.agents, coder: { + ...original.agents.coder, config: { ...original.agents.coder.config, role: 'specialist', hiveRole: 'specialist' }, + } } }); + expect(existsSync(path('agents.json'))).toBe(false); + const before = snapshot(); + expect(await run('hive-mind_join', { agentId: 'extra' })).toMatchObject({ success: false, maxAgents: 1 }); + expect(snapshot()).toEqual(before); + expect(await run('hive-mind_join', { agentId: 'coder', role: 'scout' })).toMatchObject({ success: true, totalWorkers: 1 }); + expect(read('hive-mind', 'state.json').workers).toEqual(['coder']); + expect(read('agents', 'store.json').agents.coder.config).toMatchObject({ keep: 'config', role: 'scout', hiveRole: 'scout' }); + }); + + it('persists the default role on an existing hive-spawned agent without duplicating membership', async () => { + await run('hive-mind_init', { maxAgents: 1 }); + const spawned = await run('hive-mind_spawn', { role: 'scout' }); + const agentId = spawned.workers[0].agentId; + expect(await run('hive-mind_join', { agentId })).toMatchObject({ success: true, role: 'worker', totalWorkers: 1 }); + expect(read('agents.json').agents[agentId].config).toEqual({ role: 'worker', hiveRole: 'worker' }); + }); + + it('rejects unknown agents, including with a valid remote token, without writing', async () => { + await run('hive-mind_init', { maxAgents: 2 }); + const before = snapshot(); + for (const context of [undefined, { sessionId: 'capacity-test', transport: 'http' }]) { + const result = await run('hive-mind_join', { agentId: 'missing', hiveToken: getHiveTokenForCli() }, context); + expect(result.success).toBe(false); + expect(result.error).toMatch(/not found|unknown|not registered/i); + expect(snapshot()).toEqual(before); + } + }); + + it('keeps remote authorization ahead of membership and capacity writes', async () => { + await run('hive-mind_init', { maxAgents: 1 }); + await register('coder'); + const before = snapshot(); + const context = { sessionId: 'capacity-test', transport: 'http' }; + expect(await run('hive-mind_join', { agentId: 'coder' }, context)).toMatchObject({ success: false, error: expect.stringMatching(/hiveToken is required/) }); + expect(await run('hive-mind_spawn', {}, context)).toMatchObject({ success: false, error: expect.stringMatching(/hiveToken is required/) }); + expect(snapshot()).toEqual(before); + expect(await run('hive-mind_join', { agentId: 'coder', hiveToken: getHiveTokenForCli() }, context)).toHaveProperty('success', true); + }); + + it.each([1.5, -1, 0, NaN, Infinity, '2'])('rejects invalid spawn count %s without writes', async count => { + await run('hive-mind_init', { maxAgents: 2 }); + const before = snapshot(); + expect(await run('hive-mind_spawn', { count })).toHaveProperty('success', false); + expect(snapshot()).toEqual(before); + }); + + it.each([ + ['agents.json', false], ['agents/store.json', false], + ['agents.json', true], ['agents/store.json', true], + ] as const)('preserves records and metadata when joining from %s (array: %s)', async (file, array) => { + await run('hive-mind_init', { maxAgents: 2 }); + const original = { version: 'old-version', metadata: { keep: true }, agents: { + existing: { agentId: 'existing', status: 'idle', config: { custom: [1, 2] }, extra: 'preserved' }, + unrelated: { agentId: 'unrelated', config: { keep: true } }, + } }; + const store = { ...original, agents: array ? Object.values(original.agents) : original.agents }; + write([file], store); + expect(await run('hive-mind_join', { agentId: 'existing', role: 'scout' })).toHaveProperty('success', true); + const existing = { ...original.agents.existing, config: { custom: [1, 2], role: 'scout', hiveRole: 'scout' } }; + expect(read(file)).toEqual({ ...store, agents: array + ? [existing, original.agents.unrelated] + : { ...original.agents, existing } }); + }); + + it('updates both copies of a registered agent while preserving each store', async () => { + await run('hive-mind_init'); + await register('coder'); + write(['agents.json'], { metadata: 'keep', agents: { coder: { agentId: 'coder', config: { hiveOnly: true } } } }); + expect(await run('hive-mind_join', { agentId: 'coder', role: 'scout' })).toHaveProperty('success', true); + expect(read('agents', 'store.json').agents.coder.config).toMatchObject({ keep: 'config', role: 'scout', hiveRole: 'scout' }); + expect(read('agents.json')).toEqual({ metadata: 'keep', agents: { coder: { + agentId: 'coder', config: { hiveOnly: true, role: 'scout', hiveRole: 'scout' }, + } } }); + }); + + it('preserves an existing map store and metadata during spawn', async () => { + await run('hive-mind_init'); + const existing = { agentId: 'existing', config: { keep: 42 }, history: ['keep'] }; + write(['agents.json'], { version: 'legacy', agents: { existing } }); + const result = await run('hive-mind_spawn'); + const stored = read('agents.json'); + expect(result.success).toBe(true); + expect(stored.version).toBe('legacy'); + expect(Object.keys(stored.agents)).toHaveLength(2); + expect(stored.agents.existing).toEqual(existing); + expect(stored.agents[result.workers[0].agentId]).toMatchObject({ agentId: result.workers[0].agentId }); + }); + + it('appends to an existing array store without losing records or changing its representation', async () => { + await run('hive-mind_init', { maxAgents: 2 }); + const original = { version: 'legacy', agents: [{ agentId: 'existing', config: { keep: 42 } }] }; + write(['agents.json'], original); + const result = await run('hive-mind_spawn'); + expect(result.success).toBe(true); + expect(read('agents.json')).toMatchObject({ version: 'legacy', agents: [original.agents[0], { agentId: result.workers[0].agentId }] }); + expect(await run('hive-mind_join', { agentId: 'existing', role: 'specialist' })).toHaveProperty('success', true); + expect(read('agents.json').agents[0].config).toEqual({ keep: 42, role: 'specialist', hiveRole: 'specialist' }); + expect((await run('hive-mind_status')).workers).toEqual(expect.arrayContaining([ + expect.objectContaining({ id: result.workers[0].agentId, status: 'idle' }), + ])); + await run('hive-mind_leave', { agentId: 'existing' }); + expect(await run('hive-mind_shutdown', { force: true })).toHaveProperty('success', true); + expect(read('agents.json')).toEqual({ version: 'legacy', agents: [{ + ...original.agents[0], config: { keep: 42, role: 'specialist', hiveRole: 'specialist' }, + }] }); + }); + + it('checks both stores before persisting a role or membership', async () => { + await run('hive-mind_init'); + await register('coder'); + writeFileSync(path('agents.json'), '{ preserve'); + const before = snapshot(); + await expect(run('hive-mind_join', { agentId: 'coder', role: 'scout' })).rejects.toThrow(); + expect(snapshot()).toEqual(before); + }); + + it.each(['raft', 'bft', 'quorum'])('retains authenticated membership and voting boundaries for %s with real registrations', async strategy => { + await run('hive-mind_init', { maxAgents: 3 }); + const hiveToken = getHiveTokenForCli(); + const context = { sessionId: 'capacity-test', transport: 'http' }; + for (const agentId of ['first', 'second', 'third']) { + await register(agentId); + expect(await run('hive-mind_join', { agentId, hiveToken }, context)).toHaveProperty('success', true); + } + const proposal = await run('hive-mind_consensus', { action: 'propose', type: 'test', value: 'keep', strategy, hiveToken }, context); + const before = snapshot(); + for (const voterId of ['unknown-a', 'unknown-b', 'unknown-c']) { + expect(await run('hive-mind_consensus', { + action: 'vote', proposalId: proposal.proposalId, voterId, vote: true, hiveToken, + }, context)).toHaveProperty('error', expect.stringMatching(/not a registered/)); + } + expect(await run('hive-mind_leave', { agentId: 'first' }, context)).toHaveProperty('success', false); + expect(await run('hive-mind_shutdown', { force: true }, context)).toHaveProperty('success', false); + expect(snapshot()).toEqual(before); + expect(await run('hive-mind_consensus', { + action: 'vote', proposalId: proposal.proposalId, voterId: 'first', vote: true, hiveToken, + }, context)).not.toHaveProperty('error'); + expect(read('hive-mind', 'state.json').consensus.pending[0].votes).toEqual({ first: true }); + }); + + it.each(['{ "keep":', 'null', '[]', '{"agents":null}', '{"agents":"invalid"}'])('does not overwrite an unreadable or invalid hive agent store: %s', async original => { + await run('hive-mind_init'); + writeFileSync(path('agents.json'), original); + const before = snapshot(); + await expect(run('hive-mind_spawn')).rejects.toThrow(); + await expect(run('hive-mind_join', { agentId: 'missing' })).rejects.toThrow(); + expect(snapshot()).toEqual(before); + }); +}); diff --git a/v3/@claude-flow/cli/__tests__/hive-mind-cli-consensus-errors.test.ts b/v3/@claude-flow/cli/__tests__/hive-mind-cli-consensus-errors.test.ts index 0caf3404fc..bea8deb894 100644 --- a/v3/@claude-flow/cli/__tests__/hive-mind-cli-consensus-errors.test.ts +++ b/v3/@claude-flow/cli/__tests__/hive-mind-cli-consensus-errors.test.ts @@ -19,8 +19,11 @@ vi.mock('../src/mcp-client.js', async () => { }); import { hiveMindCommand } from '../src/commands/hive-mind.js'; import { hiveMindTools } from '../src/mcp-tools/hive-mind-tools.js'; +import { agentTools } from '../src/mcp-tools/agent-tools.js'; import type { CommandContext } from '../src/types.js'; +vi.mock('../src/ruvector/graph-backend.js', () => ({ addNode: vi.fn() })); + // Only the MCP dispatch seam and output presentation are replaced. The real // command action calls the real hive handler, which reads/writes disposable files. function tool(name: string) { return hiveMindTools.find(tool => tool.name === name)!; } @@ -42,7 +45,13 @@ describe('CLI consensus outcomes reflect actual persisted hive state', () => { const init = await tool('hive-mind_init').handler({ consensus: 'quorum' }) as Record; token = init.hiveToken as string; for (const agentId of ['worker-1', 'worker-2', 'worker-3']) { - await tool('hive-mind_join').handler({ agentId, hiveToken: token }); + // #4727: registration is required before hive membership. + const agent = await agentTools.find(t => t.name === 'agent_spawn')!.handler({ + agentId, agentType: 'worker', model: 'sonnet', + }) as Record; + expect(agent.success).toBe(true); + const joined = await tool('hive-mind_join').handler({ agentId, hiveToken: token }) as Record; + expect(joined.success).toBe(true); } const proposal = await tool('hive-mind_consensus').handler({ action: 'propose', type: 'design', value: 'use-jwt' }) as Record; proposalId = proposal.proposalId as string; 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.ts index f798e56fdb..ff0dca5c6c 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 @@ -23,11 +23,14 @@ * process restart/reopen) after each denial. */ -import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { mkdtempSync, rmSync, readFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { hiveMindTools, getHiveTokenForCli } from '../src/mcp-tools/hive-mind-tools.js'; +import { agentTools } from '../src/mcp-tools/agent-tools.js'; + +vi.mock('../src/ruvector/graph-backend.js', () => ({ addNode: vi.fn() })); // ADR-476: these tests model an UNTRUSTED remote (HTTP) caller -- the only // caller class the capability token is a boundary for. Local stdio/CLI @@ -57,10 +60,17 @@ describe('hive-mind_consensus / join / leave capability-token authentication', ( let dir: string; let prevCwd: string | undefined; - beforeEach(() => { + beforeEach(async () => { dir = mkdtempSync(join(tmpdir(), 'hive-mind-sybil-')); prevCwd = process.env.CLAUDE_FLOW_CWD; process.env.CLAUDE_FLOW_CWD = dir; + // #4727: only registered agents may join; registration does not join them. + for (let i = 0; i < 5; i++) { + const agent = await agentTools.find(t => t.name === 'agent_spawn')!.handler({ + agentId: `worker-${i}`, agentType: 'worker', model: 'sonnet', + }) as any; + expect(agent.success).toBe(true); + } }); afterEach(() => { diff --git a/v3/@claude-flow/cli/__tests__/hive-mind-gate-matrix.test.ts b/v3/@claude-flow/cli/__tests__/hive-mind-gate-matrix.test.ts index 332d0cd40c..a112f70844 100644 --- a/v3/@claude-flow/cli/__tests__/hive-mind-gate-matrix.test.ts +++ b/v3/@claude-flow/cli/__tests__/hive-mind-gate-matrix.test.ts @@ -30,6 +30,9 @@ vi.mock('node:crypto', async () => { }); import { hiveMindTools, getHiveTokenForCli } from '../src/mcp-tools/hive-mind-tools.js'; +import { agentTools } from '../src/mcp-tools/agent-tools.js'; + +vi.mock('../src/ruvector/graph-backend.js', () => ({ addNode: vi.fn() })); const SECRET = 'operator-secret-0123456789abcdef'; const posix = process.platform !== 'win32'; @@ -78,13 +81,20 @@ describe('hive-mind gate matrix (ADR-476)', () => { let prevCwd: string | undefined; const hiveDir = () => join(dir, '.claude-flow', 'hive-mind'); - beforeEach(() => { + beforeEach(async () => { dir = mkdtempSync(join(tmpdir(), 'hive-gate-')); prevCwd = process.env.CLAUDE_FLOW_CWD; process.env.CLAUDE_FLOW_CWD = dir; delete process.env.RUFLO_HIVE_BOOTSTRAP_SECRET; delete process.env.RUFLO_HIVE_REQUIRE_AUTH; cryptoSpy.calls.length = 0; + // #4727: keep the matrix about authorization, with real registered IDs. + for (const agentId of ['w-join', 'w1']) { + const agent = await agentTools.find(t => t.name === 'agent_spawn')!.handler({ + agentId, agentType: 'worker', model: 'sonnet', + }) as any; + expect(agent.success).toBe(true); + } }); afterEach(() => { delete process.env.RUFLO_HIVE_BOOTSTRAP_SECRET; 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.ts index db36c95c35..f079f6e67e 100644 --- a/v3/@claude-flow/cli/__tests__/hive-mind-spawn-broadcast-shutdown-auth.test.ts +++ b/v3/@claude-flow/cli/__tests__/hive-mind-spawn-broadcast-shutdown-auth.test.ts @@ -42,11 +42,14 @@ * hive-mind-gate-matrix.test.ts. */ -import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { mkdtempSync, rmSync, readFileSync, existsSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { hiveMindTools, getHiveTokenForCli } from '../src/mcp-tools/hive-mind-tools.js'; +import { agentTools } from '../src/mcp-tools/agent-tools.js'; + +vi.mock('../src/ruvector/graph-backend.js', () => ({ addNode: vi.fn() })); const REMOTE = { sessionId: 'auth-test', transport: 'http' }; const SECRET = 'operator-secret-for-tests-0123456789'; @@ -78,11 +81,16 @@ describe('hive-mind_spawn / consensus(propose) / broadcast / shutdown capability let dir: string; let prevCwd: string | undefined; - beforeEach(() => { + beforeEach(async () => { dir = mkdtempSync(join(tmpdir(), 'hive-mind-auth-')); prevCwd = process.env.CLAUDE_FLOW_CWD; process.env.CLAUDE_FLOW_CWD = dir; process.env.RUFLO_HIVE_BOOTSTRAP_SECRET = SECRET; + // #4727: the shutdown fixtures join a previously registered worker. + const agent = await agentTools.find(t => t.name === 'agent_spawn')!.handler({ + agentId: 'worker-0', agentType: 'worker', model: 'sonnet', + }) as any; + expect(agent.success).toBe(true); }); afterEach(() => { 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.ts index f920f62406..5c64bbc581 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 @@ -354,25 +354,54 @@ function saveHiveState(state: HiveState): void { } } -// Import agent store helpers for spawn functionality -import { existsSync as agentStoreExists, readFileSync as readAgentStore, writeFileSync as writeAgentStore, mkdirSync as mkdirAgentStore } from 'node:fs'; - -function loadAgentStore(): { agents: Record } { - const storePath = join(getProjectCwd(), '.claude-flow', 'agents.json'); - try { - if (agentStoreExists(storePath)) { - return JSON.parse(readAgentStore(storePath, 'utf-8')); - } - } catch { /* ignore */ } - return { agents: {} }; +type HiveAgentRecord = Record; +interface HiveAgentStore { + agents: Record | HiveAgentRecord[]; } -function saveAgentStore(store: { agents: Record }): void { - const storeDir = join(getProjectCwd(), '.claude-flow'); - if (!agentStoreExists(storeDir)) { - mkdirAgentStore(storeDir, { recursive: true }); +function getHiveAgentPath(): string { + return join(getProjectCwd(), STORAGE_DIR, 'agents.json'); +} + +function loadAgentStore(storePath = getHiveAgentPath()): HiveAgentStore { + let text: string; + try { + text = readFileSync(storePath, 'utf-8'); + } catch (error) { + // Only an absent file is empty: never replace corrupt/unreadable data. + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { agents: {} }; + throw error; } - writeAgentStore(join(storeDir, 'agents.json'), JSON.stringify(store, null, 2), 'utf-8'); + const store = JSON.parse(text); + if (!store || typeof store !== 'object' || Array.isArray(store) + || !store.agents || typeof store.agents !== 'object' + || Object.values(store.agents).some(agent => !agent || typeof agent !== 'object' || Array.isArray(agent))) { + throw new Error(`Invalid agent store at ${storePath}; existing data was preserved`); + } + return store; +} + +function saveAgentStore(store: HiveAgentStore, storePath = getHiveAgentPath()): void { + // A new hive store lives directly in STORAGE_DIR; join only writes stores + // that already contain its agent, so their parent directories already exist. + mkdirSync(join(getProjectCwd(), STORAGE_DIR), { recursive: true }); + writeFileSync(storePath, JSON.stringify(store, null, 2), 'utf-8'); +} + +function findAgent(store: HiveAgentStore, agentId: string): HiveAgentRecord | undefined { + if (Array.isArray(store.agents)) return store.agents.find(agent => agent.agentId === agentId); + return Object.prototype.hasOwnProperty.call(store.agents, agentId) ? store.agents[agentId] : undefined; +} + +function capacityError(state: HiveState, additionalWorkers: number): Record | null { + const maxAgents = state.maxAgents ?? 15; + if (state.workers.length + additionalWorkers <= maxAgents) return null; + return { + success: false, + error: `Hive-mind capacity exceeded: ${state.workers.length}/${maxAgents} workers; cannot add ${additionalWorkers}. Leave the hive or initialize with a larger maxAgents.`, + totalWorkers: state.workers.length, + maxAgents, + }; } export const hiveMindTools: MCPTool[] = [ @@ -412,7 +441,14 @@ export const hiveMindTools: MCPTool[] = [ 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 }; } - const count = Math.min(Math.max(1, (input.count as number) || 1), 20); // Cap at 20 + const requestedCount = input.count === undefined ? 1 : input.count; + if (typeof requestedCount !== 'number' || !Number.isInteger(requestedCount) || requestedCount < 1) { + return { success: false, error: 'count must be a positive integer' }; + } + const count = Math.min(requestedCount, 20); // Preserve the per-call cap. + // Reject the entire batch before creating agents or mutating the roster. + const full = capacityError(state, count); + if (full) return full; const role = (input.role as string) || 'worker'; const agentType = (input.agentType as string) || 'worker'; const prefix = (input.prefix as string) || 'hive-worker'; @@ -424,7 +460,7 @@ export const hiveMindTools: MCPTool[] = [ const agentId = `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`; // Create agent record (like agent/spawn) - agentStore.agents[agentId] = { + const agent: HiveAgentRecord = { agentId, agentType, status: 'idle', @@ -434,6 +470,8 @@ export const hiveMindTools: MCPTool[] = [ createdAt: new Date().toISOString(), domain: 'hive-mind', }; + if (Array.isArray(agentStore.agents)) agentStore.agents.push(agent); + else agentStore.agents[agentId] = agent; // Join to hive-mind (like hive-mind/join) if (!state.workers.includes(agentId)) { @@ -638,7 +676,7 @@ export const hiveMindTools: MCPTool[] = [ term: state.queen.term, } : { id: 'N/A', status: 'offline', load: 0, tasksQueued: 0 }, workers: state.workers.map(w => { - const agent = agentStore.agents[w] as Record | undefined; + const agent = findAgent(agentStore, w); return { id: w, type: (agent?.agentType as string) || 'worker', @@ -720,7 +758,34 @@ export const hiveMindTools: MCPTool[] = [ return { success: false, agentId, error: tokenError }; } - if (!state.workers.includes(agentId)) { + const alreadyJoined = state.workers.includes(agentId); + // Retrying a registered member does not consume another slot. + if (!alreadyJoined) { + const full = capacityError(state, 1); + if (full) return { ...full, agentId }; + } + + // Both registration paths are legitimate (#1916). Update each existing + // record in place, preserving metadata and map/array representation. + const paths = [ + join(getProjectCwd(), STORAGE_DIR, 'agents', 'store.json'), + getHiveAgentPath(), + ]; + const records = paths.flatMap(path => { + const store = loadAgentStore(path); + const agent = findAgent(store, agentId); + return agent ? [{ path, store, agent }] : []; + }); + if (records.length === 0) { + return { success: false, agentId, error: 'Agent not found. Register it with agent_spawn or hive-mind_spawn first.' }; + } + const role = (input.role as string) || 'worker'; + for (const { path, store, agent } of records) { + agent.config = { ...(agent.config as Record), role, hiveRole: role }; + saveAgentStore(store, path); + } + + if (!alreadyJoined) { state.workers.push(agentId); saveHiveState(state); } @@ -728,7 +793,7 @@ export const hiveMindTools: MCPTool[] = [ return { success: true, agentId, - role: input.role || 'worker', + role, totalWorkers: state.workers.length, joinedAt: new Date().toISOString(), }; @@ -1232,9 +1297,13 @@ export const hiveMindTools: MCPTool[] = [ // Clear workers from agent store const agentStore = loadAgentStore(); - for (const workerId of state.workers) { - if (agentStore.agents[workerId]) { - delete agentStore.agents[workerId]; + if (Array.isArray(agentStore.agents)) { + agentStore.agents = agentStore.agents.filter(agent => !state.workers.includes(agent.agentId as string)); + } else { + for (const workerId of state.workers) { + if (Object.prototype.hasOwnProperty.call(agentStore.agents, workerId)) { + delete agentStore.agents[workerId]; + } } } saveAgentStore(agentStore);