The intelligence dashboard showed the model router shipping 77% Opus on
0.30 avg complexity — over-routing to the most expensive tier on tasks
where Haiku would have been correct. Root cause: the deterministic
selectModel() ignored hooks_model-outcome history; outcomes were recorded
but never closed the loop.
This PR converts the router into a cost-adjusted Thompson sampling bandit
so that every model-outcome call updates posterior beliefs over Tier 1 /
Tier 2 / Tier 3, and the router auto-balances cost/quality from real data.
What changed in v3/@claude-flow/cli/src/ruvector/model-router.ts:
- New BetaPrior interface + BANDIT_REWARDS table (cost-adjusted Bernoulli):
Haiku-success -> α += 1.0 (cheap + worked = best outcome)
Sonnet-success -> α += 0.7 (worked, somewhat expensive)
Opus-success -> α += 0.4 (worked but cost-suboptimal)
Sonnet-escalated -> α += 0.1 (partial credit)
*-failure / haiku-escalated / opus-escalated -> α += 0.0
- Pure-JS Beta sampler (Marsaglia-Tsang gamma + ratio + Box-Muller normal)
- selectModel() now multiplies the deterministic complexity score by a
Thompson draw θ_m ~ Beta(α_m, β_m) before argmax. Beta(1,1) cold-start
so behavior matches the prior router until outcomes accumulate.
- recordOutcome() updates priors with the cost-adjusted reward
- RouterState extended with priors; loadState backfills defaults for
pre-bandit state files; reset() and getBanditPriors() updated
Tests (__tests__/router-bandit.test.ts, 6 cases):
- Beta(1,1) uniform prior on cold start
- Cost-adjusted updates produce the right α/β deltas (success/failure/escalated)
- Persistence: priors round-trip across router instances
- Convergence: 100-trial workload at avg complexity 0.3 — Haiku posterior
mean dominates Opus by N=100, and Haiku is picked more than Opus over
the run
- Recovery: even with adversarial cold-start outcomes, exploration pulls
the bandit back to the optimal arm within 100 trials
Validation:
- npm run build clean
- 6 new bandit tests pass
- 769 baseline tests still pass (parser, output, validate-input x 2,
mcp-tools-deep, commands, cli, commands-deep, config-adapter x 2,
p1-commands)
- Benchmarked route() overhead: 45.5 µs/call (under the file headers
documented "<100 µs" target). Adds ~3 sampleBeta() draws per route.
Bumps all three packages to 3.7.0-alpha.5:
@claude-flow/cli 3.7.0-alpha.4 -> 3.7.0-alpha.5
claude-flow 3.7.0-alpha.4 -> 3.7.0-alpha.5
ruflo 3.7.0-alpha.4 -> 3.7.0-alpha.5
Visible result: the 77% Opus / 0.30 complexity mismatch corrects itself
within ~50 routing decisions, automatically. No manual threshold tuning.
Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
CLI Module Tests
This directory contains comprehensive tests for the V3 CLI module using Vitest.
Test Files
1. cli.test.ts (~15+ tests)
Tests for the main CLI class covering:
- Version command (
--version,-V) - Help output (
--help,-h) - Command parsing (long flags, short flags, equals syntax)
- Positional arguments
- Boolean flags and negation
- Global flags (
--quiet,--format,--config,--no-color) - Error handling (unknown commands, missing options)
- Subcommand execution and aliases
- Exit codes
2. mcp-client.test.ts (~10+ tests)
Tests for MCP tool invocation:
callMCPTool()- Tool execution with various inputsgetToolMetadata()- Metadata retrievallistMCPTools()- Tool listing and filtering by categoryhasTool()- Tool existence checksgetToolCategories()- Category enumerationvalidateToolInput()- Input validation against schemasMCPClientError- Custom error handling
3. commands.test.ts (~48+ tests)
Tests for all CLI commands:
Agent Commands (spawn, list, status, stop, metrics):
- Spawning agents with various configurations
- Listing agents with filters
- Getting agent status and metrics
- Stopping agents (graceful/force)
- Agent performance metrics
Swarm Commands (init, start, status, stop, scale, coordinate):
- Initializing swarms with different topologies
- Starting swarm execution with objectives
- Checking swarm status
- Stopping and scaling swarms
- V3 15-agent coordination structure
Memory Commands (store, retrieve, search, list, delete, stats, configure):
- Storing data in memory (with/without vectors)
- Retrieving data by key
- Semantic/vector search
- Listing memory entries
- Deleting entries
- Viewing statistics
- Backend configuration
Config Commands (init, get, set, providers, reset, export, import):
- Initializing configuration
- Getting/setting config values
- Managing AI providers
- Resetting to defaults
- Exporting/importing configuration
Mocking Strategy
MCP Tools
All MCP tools are mocked at the module level to prevent actual tool execution:
agent-tools.js- Mocked agent operationsswarm-tools.js- Mocked swarm coordinationmemory-tools.js- Mocked memory operationsconfig-tools.js- Mocked configuration
Output
The output module is fully mocked to capture formatted output without console pollution.
Prompts
Interactive prompts (select, confirm, input, multiSelect) are mocked to return default values for non-interactive testing.
Process
process.exit() is mocked to throw errors instead of terminating the test process.
Running Tests
# Run all CLI tests
npm test -- v3/@claude-flow/cli/__tests__/
# Run specific test file
npm test -- v3/@claude-flow/cli/__tests__/cli.test.ts
# Run with coverage
npm test -- v3/@claude-flow/cli/__tests__/ --coverage
# Run in watch mode
npm test -- v3/@claude-flow/cli/__tests__/ --watch
Test Coverage Goals
- Statements: >80%
- Branches: >75%
- Functions: >80%
- Lines: >80%
Key Testing Patterns
1. Command Execution
const result = await command.action!(ctx);
expect(result.success).toBe(true);
expect(result.data).toHaveProperty('expectedField');
2. Flag Parsing
ctx.flags = { myFlag: 'value', _: [] };
await command.action!(ctx);
// Assertions in action callback
3. Error Handling
try {
await cli.run(['invalid-command']);
} catch (e) {
expect((e as Error).message).toContain('process.exit');
}
4. Output Validation
const output = consoleOutput.join('');
expect(output).toContain('Expected text');
Notes
- All tests are non-interactive (
interactive: false) - Console output is captured for verification
- Process exits are converted to exceptions
- MCP client is fully isolated from actual MCP server
- Tests use unique command names to avoid conflicts