feat(hive-mind): add --model to hive-mind spawn --claude (#4672)

Part of #1870. With --claude, -m/--model goes to the Claude Code worker as --model. No flag, no change. Values starting with '-' are refused before anything spawns.

Co-authored-by: Michael Valderrama <17348490+ibucketbranch@users.noreply.github.com>
This commit is contained in:
Michael ValderramaandMichael Valderrama authored and GitHub committed 2026-11-04 17:48:51 -06:00
1 parent 8d4475d963
commit 1a5ceb62cc
3 files changed
+211 -4

No files matched your search

@@ -0,0 +1,160 @@
/**
* #1870: `hive-mind spawn --claude --model <m>` passes --model to the Claude
* Code worker; without it the argv is unchanged. Bad values are refused before
* anything is spawned. Harness taken from mods/mods-hive-mind-spawn-plugins.test.ts.
*
* Contributed by Michael Valderrama (https://bucketbranch.ai)
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { EventEmitter } from 'node:events';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const fake = vi.hoisted(() => ({ calls: [] as Array<{ cmd: string; argv: string[]; opts: any }> }));
vi.mock('child_process', async (orig) => {
const actual = await orig<typeof import('child_process')>();
return {
...actual,
spawn: vi.fn((cmd: string, argv: string[], opts: any) => {
fake.calls.push({ cmd, argv, opts });
const child: any = new EventEmitter();
child.killed = false;
child.kill = vi.fn();
setTimeout(() => child.emit('exit', 0), 0);
return child;
}),
};
});
vi.mock('fs/promises', async (orig) => ({ ...(await orig<typeof import('fs/promises')>()), mkdir: vi.fn(async () => undefined), writeFile: vi.fn(async () => undefined) }));
vi.mock('../src/runtime/claude-command.js', () => ({ resolveClaudeLaunchCommand: () => ({ command: 'claude', argsPrefix: [] }) }));
vi.mock('../src/mcp-client.js', () => ({
MCPClientError: class extends Error {},
callMCPTool: vi.fn(async (name: string) =>
name === 'hive-mind_spawn'
? { success: true, spawned: 1, workers: [{ agentId: 'w1', role: 'worker', joinedAt: new Date(0).toISOString() }], totalWorkers: 1, hiveStatus: 'active', hiveId: 'h1', message: 'ok' }
: { hiveId: 'h1' }),
}));
import { hiveMindCommand } from '../src/commands/hive-mind.js';
import { resolveWorkerModel } from '../src/commands/hive-mind-worker.js';
import { callMCPTool } from '../src/mcp-client.js';
let cfg: string;
let savedConfigDir: string | undefined;
let written: string;
const spawnCmd = hiveMindCommand.subcommands!.find((c) => c.name === 'spawn')!;
const run = (flags: Record<string, unknown>) =>
spawnCmd.action!({ args: [], flags: { claude: true, objective: 'do x', mcpConfig: '/tmp/m.json', ...flags }, interactive: false, cwd: cfg } as any);
const claudeCall = () => fake.calls.find((c) => c.cmd === 'claude');
beforeEach(() => {
fake.calls = [];
written = '';
vi.mocked(callMCPTool).mockClear();
cfg = mkdtempSync(join(tmpdir(), 'hive-model-'));
savedConfigDir = process.env.CLAUDE_CONFIG_DIR;
process.env.CLAUDE_CONFIG_DIR = cfg;
const capture = (chunk: unknown) => {
written += String(chunk);
return true;
};
vi.spyOn(process.stderr, 'write').mockImplementation(capture as any);
vi.spyOn(process.stdout, 'write').mockImplementation(capture as any);
vi.spyOn(console, 'log').mockImplementation((...a: unknown[]) => { written += a.join(' ') + '\n'; });
vi.spyOn(console, 'error').mockImplementation((...a: unknown[]) => { written += a.join(' ') + '\n'; });
});
afterEach(() => {
if (savedConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;
else process.env.CLAUDE_CONFIG_DIR = savedConfigDir;
vi.restoreAllMocks();
rmSync(cfg, { recursive: true, force: true });
});
describe('#1870 resolveWorkerModel', () => {
it('accepts model names and ids', () => {
for (const m of ['sonnet', 'opus', 'haiku', 'claude-sonnet-5', 'us.anthropic.claude-sonnet-5-v1:0', 'claude-sonnet-4-5@20250929']) {
expect(resolveWorkerModel({ model: m })).toEqual({ model: m });
}
expect(resolveWorkerModel({ model: ' sonnet ' })).toEqual({ model: 'sonnet' });
});
it('refuses flags, blanks and values with spaces', () => {
for (const m of ['-x', '--dangerously-skip-permissions', 'sonnet opus', '', ' ', true]) {
expect(resolveWorkerModel({ model: m }).error).toBeDefined();
}
});
it('returns nothing when --model is absent', () => {
expect(resolveWorkerModel({})).toEqual({});
});
});
describe('#1870 hive-mind spawn --model', () => {
it('declares -m, --model on spawn, and no other spawn option takes -m', () => {
const model = spawnCmd.options!.find((o) => o.name === 'model');
expect(model).toBeDefined();
expect(model!.short).toBe('m');
expect(model!.type).toBe('string');
expect(spawnCmd.options!.filter((o) => o.short === 'm')).toHaveLength(1);
});
it('non-interactive: passes --model <m> to Claude Code, and the prompt stays last', async () => {
const r = await run({ nonInteractive: true, model: 'sonnet' });
expect(r.success).toBe(true);
const argv = claudeCall()!.argv;
const i = argv.indexOf('--model');
expect(i).toBeGreaterThanOrEqual(0);
expect(argv[i + 1]).toBe('sonnet');
expect(i + 1).toBeLessThan(argv.length - 1);
expect(argv.filter((a) => a === '--model')).toHaveLength(1);
});
it('interactive: passes --model <m>, and the environment is still inherited', async () => {
await run({ model: 'claude-sonnet-5' });
const call = claudeCall()!;
const i = call.argv.indexOf('--model');
expect(call.argv[i + 1]).toBe('claude-sonnet-5');
expect(call.opts.env).toBeUndefined();
});
it('accepts a provider-qualified model id', async () => {
await run({ nonInteractive: true, model: 'us.anthropic.claude-sonnet-5-v1:0' });
const argv = claudeCall()!.argv;
expect(argv[argv.indexOf('--model') + 1]).toBe('us.anthropic.claude-sonnet-5-v1:0');
});
it('negative control: without --model the argument list carries no --model', async () => {
await run({ nonInteractive: true });
expect(claudeCall()!.argv).not.toContain('--model');
await run({});
expect(fake.calls.filter((c) => c.cmd === 'claude').every((c) => !c.argv.includes('--model'))).toBe(true);
});
it('refuses a value that starts with "-" before spawning workers or Claude Code', async () => {
const r = await run({ nonInteractive: true, model: '--dangerously-skip-permissions' });
expect(r.success).toBe(false);
expect(r.exitCode).toBe(1);
expect(claudeCall()).toBeUndefined();
expect(vi.mocked(callMCPTool)).not.toHaveBeenCalled();
expect(written).toContain('--model');
});
it('refuses an empty or blank value, and a bare --model with no value', async () => {
for (const model of ['', ' ', true]) {
fake.calls = [];
vi.mocked(callMCPTool).mockClear();
const r = await run({ nonInteractive: true, model });
expect(r.success).toBe(false);
expect(claudeCall()).toBeUndefined();
expect(vi.mocked(callMCPTool)).not.toHaveBeenCalled();
}
});
it('without --claude, --model is reported as ignored instead of silently dropped', async () => {
const r = await run({ claude: false, model: 'sonnet' });
expect(r.success).toBe(true);
expect(claudeCall()).toBeUndefined();
expect(written).toMatch(/--model only applies with --claude/);
});
});
@@ -104,6 +104,27 @@ export function currentRufloServer(): { command: string; args: string[] } {
: { command: 'npx', args: ['-y', '@claude-flow/cli@latest', 'mcp', 'start'] };
}
const WORKER_MODEL = /^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,199}$/;
/**
* The model for a spawned Claude, from `--model` (#1870). With no `--model`
* nothing is passed and Claude Code picks its own default. The value becomes
* its own argv token, so one starting with "-" would be read by Claude as a
* flag and is refused.
*/
export function resolveWorkerModel(flags: Record<string, unknown>): { model?: string; error?: string } {
const raw = flags.model;
if (raw === undefined || raw === null) return {};
if (typeof raw !== 'string' || raw.trim() === '') {
return { error: '--model needs a value, e.g. --model sonnet' };
}
const model = raw.trim();
if (!WORKER_MODEL.test(model)) {
return { error: `--model "${model}" is not a valid model name or id` };
}
return { model };
}
export interface RunOutcome {
ok: boolean;
output: string;
+30 -4
View File
@@ -12,7 +12,7 @@ import { select, confirm, input } from '../prompt.js';
import { callMCPTool, MCPClientError } from '../mcp-client.js';
import { spawn as childSpawn } from 'child_process';
import { mkdir, writeFile } from 'fs/promises';
import { resolveWorkerMcpConfig, currentRufloServer, workCommand } from './hive-mind-worker.js';
import { resolveWorkerMcpConfig, resolveWorkerModel, currentRufloServer, workCommand } from './hive-mind-worker.js';
import { join } from 'path';
import { resolveClaudeLaunchCommand } from '../runtime/claude-command.js';
import { withHeadlessPlugins } from '../mods/headless-plugins.js';
@@ -212,6 +212,8 @@ async function spawnClaudeCodeInstance(
spinner.succeed('Hive Mind coordination prompt ready!');
const { model: workerModel } = resolveWorkerModel(flags);
// Display coordination summary
output.writeln();
output.writeln(output.bold('🧠 Hive Mind Configuration'));
@@ -223,6 +225,7 @@ async function spawnClaudeCodeInstance(
`Worker Count: ${output.highlight(String(workers.length))}`,
`Worker Types: ${output.highlight(Object.keys(workerGroups).join(', '))}`,
`Consensus: ${output.highlight((flags.consensus as string) || 'byzantine')}`,
`Model: ${output.highlight(workerModel ?? 'Claude Code default')}`,
`MCP Tools: ${output.success('Full Claude-Flow integration enabled')}`
]);
@@ -303,6 +306,11 @@ async function spawnClaudeCodeInstance(
}
}
// #1870: without --model the argv is unchanged and Claude Code picks its default.
if (workerModel) {
claudeArgs.push('--model', workerModel);
}
// ADR-510 §2.2: a non-interactive (-p) run is a headless worker and loads
// no marketplace plugins on a fresh config, so stage the worker profile
// (default ruflo-mods) as --plugin-dir before the prompt. The interactive
@@ -409,11 +417,12 @@ async function spawnClaudeCodeInstance(
output.writeln();
output.writeln(output.bold('📋 Manual Execution Instructions:'));
output.writeln(output.dim('─'.repeat(50)));
const modelArg = workerModel ? ` --model ${workerModel}` : '';
output.printList([
'Install Claude Code: npm install -g @anthropic-ai/claude-code',
`Run with saved prompt: claude < ${promptFile}`,
`Or copy manually: cat ${promptFile} | claude`,
`With auto-permissions: claude --dangerously-skip-permissions < ${promptFile}`
`Run with saved prompt: claude${modelArg} < ${promptFile}`,
`Or copy manually: cat ${promptFile} | claude${modelArg}`,
`With auto-permissions: claude${modelArg} --dangerously-skip-permissions < ${promptFile}`
]);
return { success: true, promptFile };
@@ -615,6 +624,12 @@ const spawnCommand: Command = {
description: 'Objective for the hive mind (used with --claude)',
type: 'string'
},
{
name: 'model',
short: 'm',
description: 'Model for the Claude Code worker started by --claude, passed as claude --model (e.g. sonnet, opus, or a full model id; default: the Claude Code default)',
type: 'string'
},
{
name: 'dangerously-skip-permissions',
description: 'Skip permission prompts in Claude Code (use with caution)',
@@ -650,6 +665,7 @@ const spawnCommand: Command = {
{ command: 'claude-flow hive-mind spawn -n 3 -r specialist', description: 'Spawn 3 specialists' },
{ command: 'claude-flow hive-mind spawn -t coder -p my-coder', description: 'Spawn coder with custom prefix' },
{ command: 'claude-flow hive-mind spawn --claude -o "Build a REST API"', description: 'Launch Claude Code with objective' },
{ command: 'claude-flow hive-mind spawn --claude -m sonnet -o "Build a REST API"', description: 'Launch Claude Code on a pinned model' },
{ command: 'claude-flow hive-mind spawn -n 5 --claude -o "Research AI patterns"', description: 'Spawn workers and launch Claude Code' }
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
@@ -661,6 +677,16 @@ const spawnCommand: Command = {
const launchClaude = ctx.flags.claude as boolean;
let objective = (ctx.flags.objective as string) || ctx.args.join(' ');
// #1870: refuse a bad --model before any worker is spawned.
const workerModel = resolveWorkerModel(ctx.flags as Record<string, unknown>);
if (workerModel.error) {
output.printError(workerModel.error);
return { success: false, exitCode: 1 };
}
if (workerModel.model && !launchClaude) {
output.printWarning('--model only applies with --claude; ignoring it');
}
output.printInfo(`Spawning ${count} ${role} agent(s)...`);
try {