π 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
feat(hooks): opt-in @ruvector/typesafe task router (CLAUDE_FLOW_ROUTER_TYPESAFE=1) (#3406)
rUv7d801171d534
diff --git a/docs/USERGUIDE.md b/docs/USERGUIDE.mdindex 88abaeab12..9765ae088a 100644--- a/docs/USERGUIDE.md+++ b/docs/USERGUIDE.md@@ -4446,6 +4446,48 @@ npx ruflo@latest hooks route "implement caching layer" --include-explanationnpx ruflo@latest hooks post-task --task-id "task-123" --success true --agent coder```+### Opt-in: `@ruvector/typesafe` Task Router++`hooks_route` can ask [`@ruvector/typesafe`](https://github.com/ruvnet/RuVector/blob/main/npm/packages/typesafe/README.md)+β local typed decisions over sentence embeddings β to pick the agent, instead of+relying only on keyword matching (which, for example, routes "sync and review+latest issues" to `tester` because "la**test**" contains "test"). It is off by+default, an optional peer dependency, and removable: with the flag unset the+package is never imported and `hooks_route` output is unchanged.++```bash+npm install @ruvector/typesafe # optional peer of @claude-flow/cli+export CLAUDE_FLOW_ROUTER_TYPESAFE=1+npx ruflo@latest doctor --component typesafe+```++The choice options are built from the router's own pattern table (each primary+agent plus its keywords), with `not_for` hints separating `tester` / `reviewer` /+`researcher`. typesafe's answer replaces the built-in pick only if every gate holds;+otherwise the built-in route is kept and `typesafe.reason` names the failed gate:++| Gate | Env var | Default |+|------|---------|---------|+| abstain mass at most | `CLAUDE_FLOW_ROUTER_TYPESAFE_MAX_ABSTAIN` | `0.30` |+| lift (top-1 probability Γ option count; 1.0 = chance) at least | `CLAUDE_FLOW_ROUTER_TYPESAFE_MIN_LIFT` | `1.2` |+| top-1 minus runner-up probability at least | `CLAUDE_FLOW_ROUTER_TYPESAFE_MIN_MARGIN` | `0.005` |++When typesafe wins, the result carries `routedBy: "typesafe"`, the answer's+`confidence`, `abstain` and `calibrated` flag, `primaryAgent.confidenceCalibrated`,+and the built-in pick under `fallbackRoute`. When it does not, `routedBy` is the+built-in method and `typesafe.used` is `false`.++Limitations:+- The default `hash` embedder is a bag-of-words test double. Its answers are+ always `calibrated: false`, confidences are near chance (~0.1 with ten agents),+ and that confidence is never copied into `estimatedMetrics.successProbability`.+- For calibrated answers use the ONNX embedder: fetch models with the package's+ `scripts/fetch-models.mjs`, then set `CLAUDE_FLOW_ROUTER_TYPESAFE_MODEL_DIR`+ and `CLAUDE_FLOW_ROUTER_TYPESAFE_MANIFEST`.+- `@ruvector/[email protected]` ships a native binary for linux-x64-gnu only; other+ platforms use its WASM fallback. Any load or decide error falls back to the+ built-in router silently (set `CLAUDE_FLOW_LOG_LEVEL=debug` to see why).+### How Q-Learning Improves Over Time| Iteration | Action | Result |diff --git a/v3/@claude-flow/cli/__tests__/typesafe-router.test.ts b/v3/@claude-flow/cli/__tests__/typesafe-router.test.tsnew file mode 100644index 0000000000..a4a26f570e--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/typesafe-router.test.ts@@ -0,0 +1,209 @@+/**+ * typesafe-router.test.ts β opt-in `@ruvector/typesafe` augmentation for hooks_route.+ *+ * Contract (mirrors ADR-150's optional-integration rules):+ * (a) env unset β the package is never imported; legacy result returned as-is+ * (b) env set, no module β falls back to the legacy route, never throws+ * (c) env set, a choice β routedBy 'typesafe', uncalibrated confidence flagged+ * (d) high abstain β legacy route kept, reason names the abstain gate+ * (e) real package β runs only when @ruvector/typesafe resolves (hash embedder)+ */+import { describe, it, expect, vi } from 'vitest';+import { createRequire } from 'node:module';++import {+ TypesafeRouter,+ applyTypesafeRouting,+ buildAgentCriteria,+ readTypesafeConfig,+ type RoutingPatternLike,+} from '../src/ruvector/typesafe-router.js';++const PATTERNS: Record<string, RoutingPatternLike> = {+ 'testing-task': { keywords: ['test', 'testing', 'coverage'], agents: ['tester', 'reviewer'] },+ 'security-task': { keywords: ['auth', 'security', 'cve'], agents: ['security-architect', 'reviewer'] },+ 'feature-task': { keywords: ['feature', 'implement', 'build'], agents: ['architect', 'coder'] },+};++const LEGACY = Object.freeze({+ task: 'sync and review latest issues',+ routing: { method: 'keyword', backend: 'keyword matching', latencyMs: 0, throughput: 'N/A' },+ matchedPattern: 'keyword-fallback',+ primaryAgent: { type: 'tester', confidence: 0.95, reason: 'Task contains keywords matching tester specialization' },+ alternativeAgents: [{ type: 'reviewer', confidence: 0.85, reason: 'Alternative' }],+ estimatedMetrics: { successProbability: 0.95, estimatedDuration: '10-30 min', complexity: 'low' },+ swarmRecommendation: null,+});++function mockModule(answer: Record<string, unknown>) {+ const decide = vi.fn(async () => ({ agent: answer, answers: { agent: answer }, usage: {} }));+ const createTypesafe = vi.fn(() => ({ backend: 'native', decide }));+ const choice = vi.fn((criteria: unknown) => ({ type: 'choice', criteria }));+ return { mod: { createTypesafe, choice }, decide, createTypesafe, choice };+}++const ON = { CLAUDE_FLOW_ROUTER_TYPESAFE: '1' } as NodeJS.ProcessEnv;++describe('typesafe-router: opt-in gate', () => {+ it('(a) env unset β typesafe is never imported and the legacy object is returned untouched', async () => {+ const loadModule = vi.fn(async () => { throw new Error('must not load'); });+ const router = new TypesafeRouter({ env: {}, loadModule });+ const out = await applyTypesafeRouting({ task: LEGACY.task }, LEGACY, PATTERNS, router);+ expect(out).toBe(LEGACY);+ expect(loadModule).not.toHaveBeenCalled();+ expect(readTypesafeConfig({}).enabled).toBe(false);+ });++ it('(a) only the exact value "1" enables it', () => {+ expect(readTypesafeConfig({ CLAUDE_FLOW_ROUTER_TYPESAFE: 'true' }).enabled).toBe(false);+ expect(readTypesafeConfig(ON).enabled).toBe(true);+ });++ it('(a) hooks_route with the env unset carries no typesafe fields', async () => {+ delete process.env.CLAUDE_FLOW_ROUTER_TYPESAFE;+ const { hooksRoute } = await import('../src/mcp-tools/hooks-tools.js');+ const res = await hooksRoute.handler({ task: 'write unit tests for the parser', useSemanticRouter: false }) as Record<string, unknown>;+ expect(res.primaryAgent).toBeDefined();+ expect(res).not.toHaveProperty('typesafe');+ expect(res).not.toHaveProperty('routedBy');+ });++ it('validation failures from the legacy handler pass through even when enabled', async () => {+ const loadModule = vi.fn();+ const router = new TypesafeRouter({ env: ON, loadModule });+ const failed = { success: false, error: 'bad task' };+ expect(await applyTypesafeRouting({ task: '' }, failed, PATTERNS, router)).toBe(failed);+ expect(loadModule).not.toHaveBeenCalled();+ });+});++describe('typesafe-router: removable', () => {+ it('(b) env set + module missing β legacy route, reason says not installed, no throw', async () => {+ const err = Object.assign(new Error("Cannot find package '@ruvector/typesafe'"), { code: 'ERR_MODULE_NOT_FOUND' });+ const loadModule = vi.fn(async () => { throw err; });+ const router = new TypesafeRouter({ env: ON, loadModule, debug: () => {} });+ const out = await applyTypesafeRouting({ task: LEGACY.task }, LEGACY, PATTERNS, router);+ expect(out.primaryAgent).toEqual(LEGACY.primaryAgent);+ expect(out.routedBy).toBe('keyword');+ expect((out.typesafe as Record<string, unknown>).used).toBe(false);+ expect((out.typesafe as Record<string, unknown>).reason).toBe('@ruvector/typesafe not installed');+ // The failed load is cached: a second route does not retry the import.+ await applyTypesafeRouting({ task: LEGACY.task }, LEGACY, PATTERNS, router);+ expect(loadModule).toHaveBeenCalledTimes(1);+ });++ it('(b) a decide() error falls back instead of throwing', async () => {+ const decide = vi.fn(async () => { throw new Error('state too long'); });+ const router = new TypesafeRouter({ env: ON, debug: () => {}, loadModule: async () => ({ createTypesafe: () => ({ backend: 'wasm', decide }) }) });+ const out = await applyTypesafeRouting({ task: 'x' }, LEGACY, PATTERNS, router);+ expect(out.primaryAgent).toEqual(LEGACY.primaryAgent);+ expect((out.typesafe as Record<string, unknown>).reason).toMatch(/decide failed: state too long/);+ });+});++describe('typesafe-router: decisions', () => {+ it('(c) a clear choice β routedBy typesafe, uncalibrated confidence flagged, legacy kept as fallbackRoute', async () => {+ const { mod, decide, createTypesafe } = mockModule({+ choice: 'researcher', confidence: 0.41, abstain: 0.11, calibrated: false, head: 'nearest-prototype', model: 'hash-bow-256@test-double',+ probabilities: { researcher: 0.46, reviewer: 0.2, tester: 0.14, coder: 0.2 },+ });+ const router = new TypesafeRouter({ env: ON, loadModule: async () => ({ default: mod }) });+ const out = await applyTypesafeRouting({ task: LEGACY.task, context: 'github' }, LEGACY, PATTERNS, router);++ expect(createTypesafe).toHaveBeenCalledWith({ embedder: 'hash' });+ expect(decide).toHaveBeenCalledWith('sync and review latest issues github', expect.objectContaining({ agent: expect.anything() }));+ expect(out.routedBy).toBe('typesafe');+ expect((out.routing as Record<string, unknown>).method).toBe('typesafe');+ expect(out.primaryAgent).toMatchObject({ type: 'researcher', confidence: 0.41, confidenceCalibrated: false });+ expect(String((out.primaryAgent as Record<string, unknown>).reason)).toContain('UNCALIBRATED');+ expect(out.fallbackRoute).toEqual({ agent: 'tester', confidence: 0.95, method: 'keyword' });+ // Uncalibrated confidence is never promoted into successProbability.+ expect(out.estimatedMetrics).toEqual(LEGACY.estimatedMetrics);+ expect((out.alternativeAgents as Array<{ type: string }>).map(a => a.type)).toHaveLength(2);+ expect(out.typesafe).toMatchObject({ used: true, choice: 'researcher', abstain: 0.11, calibrated: false, embedder: 'hash', backend: 'native' });+ });++ it('(d) high abstain β legacy route kept and the reason names the abstain gate', async () => {+ const { mod } = mockModule({ choice: 'coder', confidence: 0.3, abstain: 0.62, calibrated: true, probabilities: { coder: 0.7, tester: 0.3 } });+ const router = new TypesafeRouter({ env: ON, loadModule: async () => mod });+ const out = await applyTypesafeRouting({ task: 'xyzzy' }, LEGACY, PATTERNS, router);+ expect(out.primaryAgent).toEqual(LEGACY.primaryAgent);+ expect(out.routedBy).toBe('keyword');+ expect(out.typesafe).toMatchObject({ used: false, choice: 'coder', abstain: 0.62 });+ expect(String((out.typesafe as Record<string, unknown>).reason)).toMatch(/abstain 0\.62 > max 0\.30/);+ });++ it('(d) a uniform distribution (chance-level) falls back on the lift gate', async () => {+ const { mod } = mockModule({ choice: 'coder', confidence: 0.2, abstain: 0.1, calibrated: false, probabilities: { coder: 0.25, tester: 0.25, reviewer: 0.25, researcher: 0.25 } });+ const router = new TypesafeRouter({ env: ON, loadModule: async () => mod });+ const out = await applyTypesafeRouting({ task: 'xyzzy plugh' }, LEGACY, PATTERNS, router);+ expect(String((out.typesafe as Record<string, unknown>).reason)).toMatch(/lift 1\.00 \(top-1 Γ 4 options\) < min 1\.20/);+ expect(out.primaryAgent).toEqual(LEGACY.primaryAgent);+ });++ it('(d) a tie at the top falls back on the margin gate', async () => {+ const { mod } = mockModule({ choice: 'coder', confidence: 0.36, abstain: 0.1, calibrated: false, probabilities: { coder: 0.4, tester: 0.4, reviewer: 0.1, researcher: 0.1 } });+ const router = new TypesafeRouter({ env: ON, loadModule: async () => mod });+ const out = await applyTypesafeRouting({ task: 'test or code?' }, LEGACY, PATTERNS, router);+ expect(String((out.typesafe as Record<string, unknown>).reason)).toMatch(/margin 0\.000 < min 0\.005/);+ expect(out.primaryAgent).toEqual(LEGACY.primaryAgent);+ });++ it('thresholds are env-tunable and invalid values fall back to defaults', () => {+ const cfg = readTypesafeConfig({ ...ON, CLAUDE_FLOW_ROUTER_TYPESAFE_MAX_ABSTAIN: '0.7', CLAUDE_FLOW_ROUTER_TYPESAFE_MIN_LIFT: 'nope' });+ expect(cfg.maxAbstain).toBe(0.7);+ expect(cfg.minLift).toBe(1.2);+ expect(readTypesafeConfig({ ...ON, CLAUDE_FLOW_ROUTER_TYPESAFE_MIN_LIFT: '2' }).minLift).toBe(2);+ expect(readTypesafeConfig({ ...ON, CLAUDE_FLOW_ROUTER_TYPESAFE_MAX_ABSTAIN: '1.5' }).maxAbstain).toBe(0.3);+ expect(readTypesafeConfig({ ...ON, CLAUDE_FLOW_ROUTER_TYPESAFE_MODEL_DIR: '/m', CLAUDE_FLOW_ROUTER_TYPESAFE_MANIFEST: '/m/manifest.json' }).embedder)+ .toEqual({ kind: 'onnx', modelDir: '/m', manifest: '/m/manifest.json' });+ });++ it('builds options from the pattern table with not_for hints separating tester/reviewer/researcher', () => {+ const c = buildAgentCriteria(PATTERNS);+ expect(Object.keys(c)).toEqual(expect.arrayContaining(['tester', 'security-architect', 'architect', 'researcher', 'reviewer', 'coder']));+ expect(c.tester.what).toContain('coverage');+ expect(c.tester.not_for).toMatch(/review/);+ expect(c.reviewer.not_for).toMatch(/writing tests/);+ expect(c.researcher.not_for).toMatch(/tests/);+ });+});++// (e) Real package β skipped unless @ruvector/typesafe resolves from this package.+const realModule = (() => {+ try { return createRequire(import.meta.url).resolve('@ruvector/typesafe'); } catch { return null; }+})();+describe.skipIf(!realModule)('typesafe-router: real @ruvector/typesafe (hash embedder)', () => {+ it('(e) routes through the real engine and reports calibrated:false honestly', async () => {+ const router = new TypesafeRouter({ env: ON });+ const out = await router.route('write unit tests for the parser and check coverage', PATTERNS);+ expect(out.embedder).toBe('hash');+ expect(out.answer).toBeDefined();+ expect(out.answer!.calibrated).toBe(false);+ expect(Object.keys(out.answer!.probabilities)).toEqual(expect.arrayContaining(['tester', 'reviewer', 'researcher']));+ expect(out.answer!.abstain).toBeGreaterThanOrEqual(0);+ });++ it('(e) nonsense text does not produce a confident typesafe route', async () => {+ const router = new TypesafeRouter({ env: ON });+ const out = await applyTypesafeRouting({ task: 'xyzzy plugh' }, LEGACY, PATTERNS, router);+ // The engine really ran (not a load failure) and the gate rejected it.+ expect((out.typesafe as Record<string, unknown>).choice).toEqual(expect.any(String));+ expect(out.routedBy).not.toBe('typesafe');+ expect(out.primaryAgent).toEqual(LEGACY.primaryAgent);+ });++ it('(e) hooks_route end to end: the "latest"βtester keyword misroute is overridden to researcher', async () => {+ process.env.CLAUDE_FLOW_ROUTER_TYPESAFE = '1';+ try {+ const { hooksRoute } = await import('../src/mcp-tools/hooks-tools.js');+ const res = await hooksRoute.handler({ task: 'sync and review latest issues', useSemanticRouter: false }) as Record<string, unknown>;+ expect(res.routedBy).toBe('typesafe');+ expect((res.primaryAgent as Record<string, unknown>).type).toBe('researcher');+ expect((res.primaryAgent as Record<string, unknown>).confidenceCalibrated).toBe(false);+ expect((res.fallbackRoute as Record<string, unknown>).agent).toBe('tester');+ } finally {+ delete process.env.CLAUDE_FLOW_ROUTER_TYPESAFE;+ }+ });+});diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex e8d5502ba6..7faad2ba5a 100644--- a/v3/@claude-flow/cli/package.json+++ b/v3/@claude-flow/cli/package.json@@ -143,12 +143,16 @@},"peerDependencies": {"@metaharness/router": "^0.4.0",+ "@ruvector/typesafe": "^0.1.0","metaharness": "^0.4.1"},"peerDependenciesMeta": {"@metaharness/router": {"optional": true},+ "@ruvector/typesafe": {+ "optional": true+ },"metaharness": {"optional": true}diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.tsindex c35e815928..bffc410c9f 100644--- a/v3/@claude-flow/cli/src/commands/doctor.ts+++ b/v3/@claude-flow/cli/src/commands/doctor.ts@@ -2101,6 +2101,26 @@ async function checkMetaharness(): Promise<HealthCheck> {}}+// Opt-in @ruvector/typesafe task router (optional peer). `--component typesafe` only.+async function checkTypesafeRouter(): Promise<HealthCheck> {+ const name = '@ruvector/typesafe router';+ const { readTypesafeConfig } = await import('../ruvector/typesafe-router.js');+ const cfg = readTypesafeConfig();+ const gate = cfg.enabled ? `enabled (${cfg.embedder === 'hash' ? 'hash embedder, uncalibrated' : 'onnx embedder'})` : 'disabled (set CLAUDE_FLOW_ROUTER_TYPESAFE=1)';+ try {+ const { createRequire } = await import('module');+ const pj = createRequire(import.meta.url)('@ruvector/typesafe/package.json') as { version?: string };+ return { name, status: 'pass', message: `v${pj.version ?? '?'} installed; ${gate}` };+ } catch {+ return {+ name,+ status: cfg.enabled ? 'warn' : 'pass',+ message: `Not installed; ${gate} β hooks_route uses the built-in router`,+ ...(cfg.enabled ? { fix: 'npm install @ruvector/typesafe # optional peer' } : {}),+ };+ }+}+async function checkClaudeCode(): Promise<HealthCheck> {try {const version = await runCommand('claude --version');@@ -2290,7 +2310,7 @@ export const doctorCommand: Command = {{name: 'component',short: 'c',- description: 'Check specific component (version, node, npm, config, daemon, memory, api, git, mcp, mcp-overhead, claude, disk, typescript, agentic-flow, encryption, federation, funnel, proxy, auth, metaharness)',+ description: 'Check specific component (version, node, npm, config, daemon, memory, api, git, mcp, mcp-overhead, claude, disk, typescript, agentic-flow, encryption, federation, funnel, proxy, auth, typesafe, metaharness)',type: 'string'},{@@ -2482,6 +2502,7 @@ export const doctorCommand: Command = {// a user would actually debug them (is it installed? running? exposed?).'proxy': [checkProxySponsoredConsent, checkProxyBinary, checkProxyProcess, checkProxyBindAddress],'auth': checkAuth, // ADR-306+ 'typesafe': checkTypesafeRouter, // opt-in @ruvector/typesafe task router};let checksToRun = allChecks;diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.tsindex fae9d55e2e..955b91f215 100644--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts@@ -14,6 +14,7 @@ import {type LearnedRoutingOutcome,type LearnedRoutingPattern,} from '../services/learned-routing.js';+import { applyTypesafeRouting, getTypesafeRouter } from '../ruvector/typesafe-router.js';// Real vector search functions - lazy loaded to avoid circular importslet searchEntriesFn: ((options: {@@ -325,6 +326,12 @@ const TASK_PATTERNS: Record<string, RoutingPattern> = {},};+/** Wrap hooks_route so the opt-in typesafe router (src/ruvector/typesafe-router.ts) can override the legacy pick. */+function withTypesafeRouting(legacy: (params: Record<string, unknown>) => Promise<object>) {+ return async (params: Record<string, unknown>) =>+ applyTypesafeRouting(params, (await legacy(params)) as Record<string, unknown>, TASK_PATTERNS, getTypesafeRouter());+}+/*** Get the semantic router with environment detection.* Tries native VectorDb first (HNSW, 16k routes/s), falls back to pure JS (47k routes/s cosine).@@ -1126,7 +1133,8 @@ export const hooksRoute: MCPTool = {},required: ['task'],},- handler: async (params: Record<string, unknown>) => {+ // Opt-in @ruvector/typesafe augmentation (CLAUDE_FLOW_ROUTER_TYPESAFE=1); returns the legacy result unchanged when unset.+ handler: withTypesafeRouting(async (params: Record<string, unknown>) => {const task = params.task as string;const context = params.context as string | undefined;const useSemanticRouter = params.useSemanticRouter !== false;@@ -1306,7 +1314,7 @@ export const hooksRoute: MCPTool = {coordination: 'queen-led',} : null,};- },+ }),};export const hooksMetrics: MCPTool = {diff --git a/v3/@claude-flow/cli/src/ruvector/typesafe-router.ts b/v3/@claude-flow/cli/src/ruvector/typesafe-router.tsnew file mode 100644index 0000000000..069d42d2ae--- /dev/null+++ b/v3/@claude-flow/cli/src/ruvector/typesafe-router.ts@@ -0,0 +1,297 @@+/**+ * typesafe-router.ts β opt-in `@ruvector/typesafe` augmentation for `hooks_route`.+ *+ * Mirrors ADR-150's MetaHarness rules for optional integrations:+ * 1. Removable β the package is loaded with a dynamic import only; any load,+ * construction or decide error falls back to the existing router.+ * 2. Opt-in β does nothing unless `CLAUDE_FLOW_ROUTER_TYPESAFE=1`. With the+ * flag unset the package is never imported and the legacy result is+ * returned unchanged (same object, no added fields).+ * 3. Optional β declared as an optional peer of `@claude-flow/cli`.+ * 4. Honest β the result carries `routedBy`, typesafe's confidence, abstain+ * mass and `calibrated` flag verbatim. The default `hash` embedder is+ * uncalibrated, so its confidence is reported as `confidenceCalibrated:+ * false` and is never copied into `estimatedMetrics.successProbability`.+ *+ * Gate: typesafe's answer is used only when all hold β+ * - `abstain <= maxAbstain` (default 0.30)+ * - lift = top-1 probability Γ option count >= `minLift` (default 1.2, i.e.+ * 20% above chance). Lift, not raw confidence, because confidence scales+ * with the option count (~0.1 for ten agents) and differs per embedder.+ * - top-1 beats the runner-up by >= `minMargin` (default 0.005); a uniform+ * distribution β text that matches nothing β has margin 0.+ * Otherwise the legacy route is kept and `typesafe.reason` says which gate failed.+ *+ * @module typesafe-router+ */++/** Keyword/agent table shape shared with hooks-tools' TASK_PATTERNS. */+export interface RoutingPatternLike { keywords: string[]; agents: string[] }++/** One `choice` option in typesafe's `{ what, not_for, examples }` form. */+export interface TypesafeCriterion { what: string; not_for?: string; examples?: string[] }++/** The subset of a typesafe choice answer this adapter reads. */+export interface TypesafeChoiceAnswer {+ choice: string; probabilities: Record<string, number>;+ confidence: number; abstain: number; calibrated: boolean; head?: string; model?: string;+}++/** The subset of `@ruvector/typesafe`'s module surface this adapter uses. */+export interface TypesafeModuleLike {+ createTypesafe(opts?: Record<string, unknown>): {+ readonly backend?: string;+ decide(state: string, questions: Record<string, unknown>): Promise<Record<string, unknown>>;+ };+ choice?(criteria: Record<string, TypesafeCriterion>): unknown;+}++export interface TypesafeRouterConfig {+ enabled: boolean;+ minLift: number;+ maxAbstain: number;+ minMargin: number;+ /** `'hash'` (default, uncalibrated) or an ONNX model dir + manifest. */+ embedder: 'hash' | { kind: 'onnx'; modelDir: string; manifest: string };+}++export interface TypesafeRouteOutcome {+ used: boolean;+ reason: string;+ answer?: TypesafeChoiceAnswer;+ backend?: string;+ embedder?: string;+ /** top-1 probability Γ option count (1.0 = chance). */+ lift?: number;+ thresholds: Pick<TypesafeRouterConfig, 'minLift' | 'maxAbstain' | 'minMargin'>;+}++/** Injectable deps (tests). `loadModule` defaults to a dynamic import of the package. */+export interface TypesafeRouterDeps { env?: NodeJS.ProcessEnv; loadModule?: () => Promise<unknown>; debug?: (msg: string) => void }++const MODULE_ID = '@ruvector/typesafe';++/**+ * Default loader. The variable specifier keeps tsc/bundlers off the optional peer;+ * `require` (the package is CJS) covers hosts that rewrite dynamic import (vite-node).+ * An absent package still surfaces as MODULE_NOT_FOUND β "not installed".+ */+async function loadTypesafeModule(): Promise<unknown> {+ try {+ return await import(/* @vite-ignore */ MODULE_ID as string);+ } catch (importErr) {+ try {+ const { createRequire } = await import('node:module');+ return createRequire(import.meta.url)(MODULE_ID);+ } catch (requireErr) {+ throw (requireErr as { code?: string })?.code === 'MODULE_NOT_FOUND' ? requireErr : importErr;+ }+ }+}++/** Agent descriptions + `not_for` hints that separate neighbouring roles. */+const AGENT_PROFILES: Record<string, TypesafeCriterion> = {+ tester: { what: 'write and run unit tests, integration tests, e2e tests, test coverage and specs', not_for: 'reviewing code, researching issues or reading the latest news' },+ reviewer: { what: 'review code quality, pull requests, diffs and best practices', not_for: 'writing tests, implementing features or researching background information' },+ researcher: { what: 'research, investigate, explore, read and summarize issues, docs, discussions and prior art', not_for: 'writing code, writing tests or reviewing a diff' },+ coder: { what: 'implement features, write code, fix bugs and build functionality', not_for: 'research, review or test-only work' },+ architect: { what: 'design system architecture, module boundaries, APIs, schemas and refactoring plans', not_for: 'running tests or small bug fixes' },+ 'security-architect': { what: 'security, authentication, authorization, encryption, vulnerabilities, CVEs and audits', not_for: 'general feature work or performance tuning' },+ 'performance-engineer': { what: 'performance optimization, profiling, benchmarks, latency and bottlenecks', not_for: 'security review or writing documentation' },+ devops: { what: 'deployment, CI/CD pipelines, docker, kubernetes and infrastructure', not_for: 'application feature code or unit tests' },+ 'memory-specialist': { what: 'memory systems, caches, vector stores, embeddings and persistence', not_for: 'UI work or deployment pipelines' },+ 'swarm-specialist': { what: 'multi-agent swarms, coordinators, hive-mind, mesh topology and agent orchestration', not_for: 'single-file code edits' },+};++/**+ * Build choice options from the router's pattern table: every primary agent of+ * a pattern, plus the profiled roles (researcher/reviewer) the table only lists+ * as alternates. Each pattern's keywords are appended to its primary agent's+ * `what`, so the options track TASK_PATTERNS rather than a parallel list.+ */+export function buildAgentCriteria(patterns: Record<string, RoutingPatternLike>): Record<string, TypesafeCriterion> {+ const keywordsByAgent = new Map<string, Set<string>>();+ for (const { agents, keywords } of Object.values(patterns)) {+ const primary = agents[0];+ if (!primary) continue;+ const set = keywordsByAgent.get(primary) ?? new Set<string>();+ keywords.forEach(k => set.add(k));+ keywordsByAgent.set(primary, set);+ }+ for (const agent of ['researcher', 'reviewer', 'tester', 'coder']) {+ if (!keywordsByAgent.has(agent)) keywordsByAgent.set(agent, new Set());+ }+ const criteria: Record<string, TypesafeCriterion> = {};+ for (const [agent, kws] of keywordsByAgent) {+ const profile = AGENT_PROFILES[agent] ?? { what: `${agent.replace(/-/g, ' ')} tasks` };+ const kw = [...kws].join(', ');+ criteria[agent] = {+ what: kw ? `${profile.what}; keywords: ${kw}` : profile.what,+ ...(profile.not_for ? { not_for: profile.not_for } : {}),+ };+ }+ return criteria;+}++function num(raw: string | undefined, dflt: number, max = 1): number {+ const n = raw === undefined || raw === '' ? NaN : Number(raw);+ return Number.isFinite(n) && n >= 0 && n <= max ? n : dflt;+}++/** Read config from env. Invalid numeric values fall back to the defaults. */+export function readTypesafeConfig(env: NodeJS.ProcessEnv = process.env): TypesafeRouterConfig {+ const modelDir = env.CLAUDE_FLOW_ROUTER_TYPESAFE_MODEL_DIR;+ const manifest = env.CLAUDE_FLOW_ROUTER_TYPESAFE_MANIFEST;+ return {+ enabled: env.CLAUDE_FLOW_ROUTER_TYPESAFE === '1',+ minLift: num(env.CLAUDE_FLOW_ROUTER_TYPESAFE_MIN_LIFT, 1.2, 255),+ maxAbstain: num(env.CLAUDE_FLOW_ROUTER_TYPESAFE_MAX_ABSTAIN, 0.3),+ minMargin: num(env.CLAUDE_FLOW_ROUTER_TYPESAFE_MIN_MARGIN, 0.005),+ embedder: modelDir && manifest ? { kind: 'onnx', modelDir, manifest } : 'hash',+ };+}++type Engine = ReturnType<TypesafeModuleLike['createTypesafe']>;++/**+ * Stateful router: loads the module and builds one engine on first use, caches+ * a load failure so a missing package costs one import attempt per process.+ */+export class TypesafeRouter {+ private engine: Engine | null = null;+ private mod: TypesafeModuleLike | null = null;+ private loadError: string | null = null;+ private readonly env: NodeJS.ProcessEnv;+ private readonly loadModule: () => Promise<unknown>;+ private readonly debug: (msg: string) => void;++ constructor(deps: TypesafeRouterDeps = {}) {+ this.env = deps.env ?? process.env;+ this.loadModule = deps.loadModule ?? loadTypesafeModule;+ this.debug = deps.debug ?? ((m) => { if (this.env.CLAUDE_FLOW_LOG_LEVEL === 'debug') console.error(`[typesafe-router] ${m}`); });+ }++ isEnabled(): boolean { return readTypesafeConfig(this.env).enabled; }++ private async ensureEngine(cfg: TypesafeRouterConfig): Promise<Engine | null> {+ if (this.engine || this.loadError) return this.engine;+ try {+ const raw = (await this.loadModule()) as Record<string, unknown>;+ const mod = (typeof raw.createTypesafe === 'function' ? raw : raw.default) as TypesafeModuleLike | undefined;+ if (!mod || typeof mod.createTypesafe !== 'function') throw new Error('module has no createTypesafe export');+ this.mod = mod;+ this.engine = mod.createTypesafe({ embedder: cfg.embedder });+ } catch (err) {+ const e = err as { code?: string; message?: string };+ this.loadError = e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND'+ ? `${MODULE_ID} not installed`+ : `${MODULE_ID} failed to load: ${e?.message ?? String(err)}`;+ this.debug(this.loadError);+ }+ return this.engine;+ }++ /** Ask typesafe for an agent. Never throws; `used: false` means keep the legacy route. */+ async route(task: string, patterns: Record<string, RoutingPatternLike>): Promise<TypesafeRouteOutcome> {+ const cfg = readTypesafeConfig(this.env);+ const thresholds = { minLift: cfg.minLift, maxAbstain: cfg.maxAbstain, minMargin: cfg.minMargin };+ const embedder = cfg.embedder === 'hash' ? 'hash' : 'onnx';+ if (!cfg.enabled) return { used: false, reason: 'CLAUDE_FLOW_ROUTER_TYPESAFE is not 1', thresholds };+ const engine = await this.ensureEngine(cfg);+ if (!engine) return { used: false, reason: this.loadError ?? 'typesafe unavailable', thresholds, embedder };+ let answer: TypesafeChoiceAnswer;+ try {+ const criteria = buildAgentCriteria(patterns);+ const question = this.mod?.choice ? this.mod.choice(criteria) : { type: 'choice', criteria };+ const res = await engine.decide(task, { agent: question });+ answer = res.agent as TypesafeChoiceAnswer;+ if (!answer || typeof answer.choice !== 'string') throw new Error('no choice in answer');+ } catch (err) {+ const reason = `typesafe decide failed: ${(err as Error)?.message ?? String(err)}`;+ this.debug(reason);+ return { used: false, reason, thresholds, embedder, backend: engine.backend };+ }+ const probs = Object.values(answer.probabilities ?? {}).sort((a, b) => b - a);+ const margin = (probs[0] ?? 0) - (probs[1] ?? 0);+ const lift = (probs[0] ?? 0) * probs.length;+ const base = { answer, lift, thresholds, embedder, backend: engine.backend };+ const f = (n: number) => n.toFixed(2);+ if (answer.abstain > cfg.maxAbstain) {+ return { ...base, used: false, reason: `typesafe abstain ${f(answer.abstain)} > max ${f(cfg.maxAbstain)}; kept existing router` };+ }+ if (lift < cfg.minLift) {+ return { ...base, used: false, reason: `typesafe lift ${f(lift)} (top-1 Γ ${probs.length} options) < min ${f(cfg.minLift)}; kept existing router` };+ }+ if (margin < cfg.minMargin) {+ return { ...base, used: false, reason: `typesafe top-1 margin ${margin.toFixed(3)} < min ${cfg.minMargin.toFixed(3)} (no clear winner); kept existing router` };+ }+ return { ...base, used: true, reason: `typesafe choice "${answer.choice}" (confidence ${f(answer.confidence)}, lift ${f(lift)}, abstain ${f(answer.abstain)}, ${answer.calibrated ? 'calibrated' : 'UNCALIBRATED'} ${embedder} embedder)` };+ }+}++type RouteResult = Record<string, unknown>;+const round2 = (n: number) => Math.round(n * 100) / 100;++/**+ * Merge a typesafe outcome into a legacy `hooks_route` result. Disabled or+ * error results (`success: false`) pass through untouched.+ */+export async function applyTypesafeRouting(+ params: Record<string, unknown>,+ legacy: RouteResult,+ patterns: Record<string, RoutingPatternLike>,+ router: TypesafeRouter,+): Promise<RouteResult> {+ if (!router.isEnabled() || !legacy || legacy.success === false || typeof params.task !== 'string') return legacy;+ const text = typeof params.context === 'string' && params.context ? `${params.task} ${params.context}` : params.task;+ const outcome = await router.route(text, patterns);+ const legacyRouting = (legacy.routing ?? {}) as Record<string, unknown>;+ const legacyPrimary = (legacy.primaryAgent ?? {}) as Record<string, unknown>;+ const a = outcome.answer;+ const typesafe = {+ used: outcome.used,+ reason: outcome.reason,+ ...(a ? {+ choice: a.choice,+ confidence: round2(a.confidence),+ abstain: round2(a.abstain),+ lift: outcome.lift === undefined ? undefined : round2(outcome.lift),+ calibrated: a.calibrated,+ head: a.head,+ model: a.model,+ probabilities: Object.fromEntries(Object.entries(a.probabilities).map(([k, v]) => [k, round2(v)])),+ } : {}),+ backend: outcome.backend,+ embedder: outcome.embedder,+ thresholds: outcome.thresholds,+ };+ if (!outcome.used || !a) {+ return { ...legacy, routedBy: String(legacyRouting.method ?? 'legacy'), typesafe };+ }+ const alternatives = Object.entries(a.probabilities)+ .filter(([k]) => k !== a.choice)+ .sort((x, y) => y[1] - x[1])+ .slice(0, 2)+ .map(([type, p]) => ({ type, confidence: round2(p), reason: 'typesafe runner-up (probability share)' }));+ return {+ ...legacy,+ routing: { ...legacyRouting, method: 'typesafe', backend: `@ruvector/typesafe (${outcome.backend ?? 'unknown'}, ${outcome.embedder} embedder)` },+ routedBy: 'typesafe',+ matchedPattern: `typesafe:${a.choice}`,+ primaryAgent: {+ type: a.choice,+ confidence: round2(a.confidence),+ confidenceCalibrated: a.calibrated,+ reason: outcome.reason,+ },+ alternativeAgents: alternatives,+ fallbackRoute: { agent: legacyPrimary.type, confidence: legacyPrimary.confidence, method: legacyRouting.method },+ typesafe,+ };+}++let sharedRouter: TypesafeRouter | null = null;+/** Process-wide router used by hooks_route. */+export function getTypesafeRouter(): TypesafeRouter {+ return (sharedRouter ??= new TypesafeRouter());+}diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yamlindex 5f495edaba..95fb976b9d 100644--- a/v3/pnpm-lock.yaml+++ b/v3/pnpm-lock.yaml@@ -147,6 +147,9 @@ importers:'@ruvector/rabitq-wasm':specifier: 0.1.0version: 0.1.0+ '@ruvector/typesafe':+ specifier: ^0.1.0+ version: 0.1.0ajv:specifier: ^8.20.0version: 8.20.0@@ -6149,6 +6152,12 @@ packages:'@ruvector/tiny-dancer-win32-arm64-msvc': 0.1.22'@ruvector/tiny-dancer-win32-x64-msvc': 0.1.22+ /@ruvector/[email protected]:+ resolution: {integrity: sha512-PEEabuznFjxABV9P7qC140N9zZYYi1THWPpyFi/7DB8P21VCZqBU1fKZ690jqWcgEe9tEfW9pIiI1nIrCSzVCA==}+ engines: {node: '>=18.0.0'}+ hasBin: true+ dev: false+/@ruvector/[email protected]:resolution: {integrity: sha512-BvtXLvBDxDxsnFVIi7rsRE8AvPxYOWqHvj8PUOEb3TfsCWBEA2gT5VodMJEv+DWx/mVqdongxRkuHGlVcK9pug==}dev: false