mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-04 06:21:59 +09:00
Merge PR #4817
This commit is contained in:
commit
ebc84e0c81
5 files changed
+166
-8
No files matched your search
@@ -0,0 +1,52 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const route = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../src/ruvector/model-router.js', () => ({
|
||||
getModelRouter: () => ({ route }),
|
||||
}));
|
||||
vi.mock('../src/mcp-client.js', () => ({
|
||||
callMCPTool: vi.fn(),
|
||||
MCPClientError: class extends Error {},
|
||||
}));
|
||||
|
||||
import { hooksModelRoute } from '../src/mcp-tools/hooks-tools.js';
|
||||
import { hooksCommand } from '../src/commands/hooks.js';
|
||||
import { callMCPTool } from '../src/mcp-client.js';
|
||||
import { CommandParser } from '../src/parser.js';
|
||||
import { output } from '../src/output.js';
|
||||
|
||||
beforeEach(() => {
|
||||
route.mockReset().mockResolvedValue({ model: 'sonnet', complexity: 0.3, confidence: 0.8 });
|
||||
vi.mocked(callMCPTool).mockReset().mockResolvedValue({ model: 'sonnet' });
|
||||
vi.spyOn(output, 'printInfo').mockImplementation(() => {});
|
||||
vi.spyOn(output, 'printJson').mockImplementation(() => {});
|
||||
});
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
describe('hooks model-route preferences through MCP and CLI (#4722)', () => {
|
||||
it('forwards boolean MCP preferences per request without changing singleton defaults', async () => {
|
||||
await hooksModelRoute.handler({ task: 'add extra feature', preferCost: true, preferSpeed: false });
|
||||
await hooksModelRoute.handler({ task: 'refactor module', preferCost: false, preferSpeed: true });
|
||||
await hooksModelRoute.handler({ task: 'fix a typo' });
|
||||
expect(route.mock.calls).toEqual([
|
||||
['add extra feature', undefined, { preferCost: true, preferSpeed: false }],
|
||||
['refactor module', undefined, { preferCost: false, preferSpeed: true }],
|
||||
['fix a typo', undefined, { preferCost: undefined, preferSpeed: undefined }],
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[['--prefer-cost', '--prefer-speed'], true, true],
|
||||
[['--no-prefer-cost', '--no-prefer-speed'], false, false],
|
||||
])('forwards normalized CLI flags %j using MCP preference names', async (flags, preferCost, preferSpeed) => {
|
||||
const parser = new CommandParser();
|
||||
parser.registerCommand(hooksCommand);
|
||||
const parsed = parser.parse(['hooks', 'model-route', '--task', 'add extra feature', '--format', 'json', ...flags]);
|
||||
const command = hooksCommand.subcommands!.find(command => command.name === 'model-route')!;
|
||||
const result = await command.action!({ args: [], flags: parsed.flags, cwd: process.cwd(), interactive: false });
|
||||
expect(result?.success).toBe(true);
|
||||
expect(callMCPTool).toHaveBeenCalledWith('hooks_model-route', {
|
||||
task: 'add extra feature', context: undefined, preferCost, preferSpeed,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { ModelRouter, type ModelRoutingResult } from '../src/ruvector/model-router.js';
|
||||
|
||||
let dir: string;
|
||||
let router: ModelRouter;
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'ruflo-model-preferences-'));
|
||||
vi.stubEnv('CLAUDE_FLOW_ROUTER_NEURAL', undefined);
|
||||
vi.stubEnv('CLAUDE_FLOW_ROUTER_TRAJECTORY', undefined);
|
||||
// Equal Thompson samples isolate preference effects from exploration.
|
||||
vi.spyOn(Math, 'random').mockReturnValue(0.5);
|
||||
router = new ModelRouter({ statePath: join(dir, 'router.json'), maxUncertainty: 1 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function alternativeScore(result: ModelRoutingResult, model: string): number {
|
||||
return result.alternatives.find(alternative => alternative.model === model)!.score;
|
||||
}
|
||||
|
||||
describe('request-local model routing preferences (#4722)', () => {
|
||||
it('preferCost selects a cheaper capable tier for a borderline task', async () => {
|
||||
const task = 'add extra feature';
|
||||
const baseline = await router.route(task);
|
||||
const preferred = await router.route(task, undefined, { preferCost: true });
|
||||
expect(baseline.model).toBe('sonnet');
|
||||
expect(preferred.model).toBe('haiku');
|
||||
expect(preferred.costMultiplier).toBeLessThan(baseline.costMultiplier);
|
||||
});
|
||||
|
||||
it('preferSpeed selects a faster capable tier', async () => {
|
||||
const task = 'refactor module';
|
||||
expect((await router.route(task)).model).toBe('sonnet');
|
||||
expect((await router.route(task, undefined, { preferSpeed: true })).model).toBe('haiku');
|
||||
});
|
||||
|
||||
it('omitted and false preferences retain baseline behavior after a preferred request', async () => {
|
||||
const task = 'add extra feature';
|
||||
const baseline = await router.route(task);
|
||||
await router.route(task, undefined, { preferCost: true, preferSpeed: true });
|
||||
for (const result of [
|
||||
await router.route(task),
|
||||
await router.route(task, undefined, { preferCost: false, preferSpeed: false }),
|
||||
]) {
|
||||
expect(result).toMatchObject({
|
||||
model: baseline.model,
|
||||
confidence: baseline.confidence,
|
||||
uncertainty: baseline.uncertainty,
|
||||
alternatives: baseline.alternatives,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
['haiku', 'architect a distributed concurrent system with security audit'],
|
||||
['sonnet', 'investigate and implement a distributed security architecture across multiple files; maybe debug an unknown error and unclear concurrency problem'],
|
||||
])('does not boost %s beyond its complexity capability', async (model, task) => {
|
||||
const baseline = await router.route(task);
|
||||
const preferred = await router.route(task, undefined, { preferCost: true, preferSpeed: true });
|
||||
expect(alternativeScore(baseline, model)).toBeGreaterThan(0);
|
||||
expect(alternativeScore(preferred, model)).toBe(alternativeScore(baseline, model));
|
||||
});
|
||||
|
||||
it('retains uncertainty escalation when speed is preferred', async () => {
|
||||
router = new ModelRouter({ statePath: join(dir, 'router.json'), maxUncertainty: 0.15 });
|
||||
const result = await router.route('refactor module', undefined, { preferSpeed: true });
|
||||
expect(result.uncertainty).toBeGreaterThan(0.15);
|
||||
expect(result.model).toBe('sonnet');
|
||||
});
|
||||
|
||||
it('applies circuit-breaker penalties after cost weighting', async () => {
|
||||
const task = 'add extra feature';
|
||||
const baseline = await router.route(task);
|
||||
expect((await router.route(task, undefined, { preferCost: true })).model).toBe('haiku');
|
||||
for (let i = 0; i < 5; i++) router.recordOutcome(task, 'haiku', 'failure');
|
||||
const result = await router.route(task, undefined, { preferCost: true });
|
||||
expect(result.model).not.toBe('haiku');
|
||||
expect(alternativeScore(result, 'haiku')).toBeCloseTo(alternativeScore(baseline, 'haiku') * 1.96 * 0.1);
|
||||
});
|
||||
});
|
||||
@@ -4927,7 +4927,7 @@ const modelRouteCommand: Command = {
|
||||
{ name: 'task', short: 't', type: 'string', description: 'Task description to route', required: true },
|
||||
{ name: 'context', short: 'c', type: 'string', description: 'Additional context' },
|
||||
{ name: 'prefer-cost', type: 'boolean', description: 'Prefer lower cost models' },
|
||||
{ name: 'prefer-quality', type: 'boolean', description: 'Prefer higher quality models' },
|
||||
{ name: 'prefer-speed', type: 'boolean', description: 'Prefer faster models when possible' },
|
||||
],
|
||||
examples: [
|
||||
{ command: 'claude-flow hooks model-route -t "fix typo"', description: 'Route simple task (likely haiku)' },
|
||||
@@ -4953,8 +4953,8 @@ const modelRouteCommand: Command = {
|
||||
}>('hooks_model-route', {
|
||||
task,
|
||||
context: ctx.flags.context,
|
||||
preferCost: ctx.flags['prefer-cost'],
|
||||
preferQuality: ctx.flags['prefer-quality'],
|
||||
preferCost: ctx.flags.preferCost,
|
||||
preferSpeed: ctx.flags.preferSpeed,
|
||||
});
|
||||
|
||||
if (ctx.flags.format === 'json') {
|
||||
|
||||
@@ -5264,7 +5264,10 @@ export const hooksModelRoute: MCPTool = {
|
||||
};
|
||||
}
|
||||
|
||||
const result = await router.route(task);
|
||||
const result = await router.route(task, undefined, {
|
||||
preferCost: typeof params.preferCost === 'boolean' ? params.preferCost : undefined,
|
||||
preferSpeed: typeof params.preferSpeed === 'boolean' ? params.preferSpeed : undefined,
|
||||
});
|
||||
return {
|
||||
model: result.model,
|
||||
confidence: result.confidence,
|
||||
|
||||
@@ -219,6 +219,12 @@ export interface ModelRouterConfig {
|
||||
priorDecay: number;
|
||||
}
|
||||
|
||||
/** Request-local preferences; omitted or false keeps the existing scoring. */
|
||||
export interface ModelRoutingPreferences {
|
||||
preferCost?: boolean;
|
||||
preferSpeed?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Routing decision result
|
||||
*/
|
||||
@@ -616,7 +622,7 @@ export class ModelRouter {
|
||||
* 'bandit-fallback'` (neural was enabled but declined) or
|
||||
* `'heuristic'` (neural was disabled).
|
||||
*/
|
||||
async route(task: string, embedding?: number[]): Promise<ModelRoutingResult> {
|
||||
async route(task: string, embedding?: number[], preferences: ModelRoutingPreferences = {}): Promise<ModelRoutingResult> {
|
||||
const startTime = performance.now();
|
||||
|
||||
// Analyze task complexity
|
||||
@@ -694,7 +700,7 @@ export class ModelRouter {
|
||||
}
|
||||
}
|
||||
|
||||
const scores = this.computeModelScores(complexity);
|
||||
const scores = this.computeModelScores(complexity, preferences);
|
||||
const adjustedScores = this.applyCircuitBreaker(scores);
|
||||
|
||||
// A/B mode: compute the pure-bandit pick alongside the hybrid pick so
|
||||
@@ -968,18 +974,27 @@ export class ModelRouter {
|
||||
/**
|
||||
* Compute scores for each model
|
||||
*/
|
||||
private computeModelScores(complexity: ComplexityAnalysis): Record<ClaudeModel, number> {
|
||||
private computeModelScores(complexity: ComplexityAnalysis, preferences: ModelRoutingPreferences): Record<ClaudeModel, number> {
|
||||
const { score } = complexity;
|
||||
|
||||
// Base scoring: inverse relationship with complexity
|
||||
// Low complexity → haiku scores high
|
||||
// High complexity → opus scores high
|
||||
return {
|
||||
const scores: Record<ClaudeModel, number> = {
|
||||
haiku: Math.max(0, 1 - score * 2), // Drops off quickly as complexity rises
|
||||
sonnet: 1 - Math.abs(score - 0.5) * 2, // Peaks at medium complexity
|
||||
opus: Math.min(1, score * 1.5), // Rises with complexity
|
||||
inherit: 0.1, // Low baseline unless explicitly needed
|
||||
};
|
||||
for (const model of ['haiku', 'sonnet', 'opus'] as const) {
|
||||
const capabilities = MODEL_CAPABILITIES[model];
|
||||
// Preferences must not boost a tier beyond its task capability.
|
||||
// Circuit-breaker penalties and uncertainty escalation still apply.
|
||||
if (score > capabilities.maxComplexity) continue;
|
||||
if (preferences.preferCost) scores[model] *= 2 - capabilities.costMultiplier;
|
||||
if (preferences.preferSpeed) scores[model] *= capabilities.speedMultiplier;
|
||||
}
|
||||
return scores;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user