π 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
fix: #2267 #2257 #2256 #2253 β CI/router/ONNX bug cluster
ruv4c01443712a3
diff --git a/.github/workflows/v3-ci.yml b/.github/workflows/v3-ci.ymlindex 99c43ed5fb..fa1ee40fdc 100644--- a/.github/workflows/v3-ci.yml+++ b/.github/workflows/v3-ci.yml@@ -2429,7 +2429,7 @@ jobs:test -f @claude-flow/cli/dist/src/init/statusline-generator.js \|| { echo "::error::statusline-generator.js not built"; exit 1; }- - name: Guard 2 β smoke: generate .cjs and validate output ranges+ - name: "Guard 2 β smoke: generate .cjs and validate output ranges"shell: bashrun: node scripts/smoke-statusline-generator-delegation.mjsdiff --git a/v3/@claude-flow/cli/.claude/helpers/router.js b/v3/@claude-flow/cli/.claude/helpers/router.jsindex 8a7f14344a..df8f9bc00c 100644--- a/v3/@claude-flow/cli/.claude/helpers/router.js+++ b/v3/@claude-flow/cli/.claude/helpers/router.js@@ -1,7 +1,16 @@#!/usr/bin/env node/*** Claude Flow Agent Router- * Routes tasks to optimal agents based on learned patterns+ *+ * Static keyword router that suggests an agent for a task description.+ * NOTE: This is *not* a learned model. It is a heuristic table; "confidence"+ * is reported as a heuristic prior, not a calibrated probability.+ *+ * #2257 fix: patterns are now word-boundary-anchored so short tokens like+ * `cd`, `ci`, `ui`, `add`, `structure` no longer match inside unrelated+ * words (`decision`, `infrastructure`, `address`, `addendum`). Default+ * confidence dropped from 0.8 to 0.6 to better reflect that this is a+ * static heuristic, not a learned classifier.*/const AGENT_CAPABILITIES = {@@ -15,52 +24,82 @@ const AGENT_CAPABILITIES = {devops: ['ci-cd', 'docker', 'deployment', 'infrastructure'],};-const TASK_PATTERNS = {+// Each entry is an array of tokens. Tokens are alternation-friendly:+// - multi-word phrases ("unit test") match as phrases+// - single tokens are wrapped with \b β¦ \b word boundaries at match time+const TASK_PATTERNS = [// Code patterns- 'implement|create|build|add|write code': 'coder',- 'test|spec|coverage|unit test|integration': 'tester',- 'review|audit|check|validate|security': 'reviewer',- 'research|find|search|documentation|explore': 'researcher',- 'design|architect|structure|plan': 'architect',+ { tokens: ['implement', 'create', 'build', 'add', 'write code', 'refactor', 'debug'], agent: 'coder' },+ { tokens: ['test', 'tests', 'spec', 'coverage', 'unit test', 'integration test'], agent: 'tester' },+ { tokens: ['review', 'audit', 'check', 'validate', 'security'], agent: 'reviewer' },+ { tokens: ['research', 'find', 'search', 'documentation', 'explore'], agent: 'researcher' },+ { tokens: ['design', 'architect', 'architecture', 'structure', 'plan'], agent: 'architect' },// Domain patterns- 'api|endpoint|server|backend|database': 'backend-dev',- 'ui|frontend|component|react|css|style': 'frontend-dev',- 'deploy|docker|ci|cd|pipeline|infrastructure': 'devops',-};+ { tokens: ['api', 'endpoint', 'server', 'backend', 'database'], agent: 'backend-dev' },+ { tokens: ['ui', 'frontend', 'component', 'react', 'css', 'style'], agent: 'frontend-dev' },+ // 'cd' / 'ci' are kept but require word boundaries via \b β they will not+ // match inside "decision" or "specific". 'cd' as a literal command in a+ // task description ("set up cd pipeline") still matches.+ { tokens: ['deploy', 'docker', 'ci', 'cd', 'ci/cd', 'pipeline', 'infrastructure', 'devops'], agent: 'devops' },+];++function escapeRegex(s) {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++// Build an anchored alternation regex from a token list.+// - multi-word phrases (containing whitespace or '/') match literally+// - single tokens are wrapped with \b boundaries so 'cd' won't match "decide"+function buildPattern(tokens) {+ const alternatives = tokens.map((tok) => {+ const escaped = escapeRegex(tok.toLowerCase());+ if (/\s|\//.test(tok)) {+ // Phrase: whitespace/'/' on each side acts as a natural boundary+ return escaped;+ }+ return `\\b${escaped}\\b`;+ });+ return new RegExp(`(?:${alternatives.join('|')})`, 'i');+}++const COMPILED_PATTERNS = TASK_PATTERNS.map((entry) => ({+ agent: entry.agent,+ tokens: entry.tokens,+ regex: buildPattern(entry.tokens),+}));function routeTask(task) {- const taskLower = task.toLowerCase();+ const taskLower = String(task ?? '').toLowerCase();- // Check patterns- for (const [pattern, agent] of Object.entries(TASK_PATTERNS)) {- const regex = new RegExp(pattern, 'i');- if (regex.test(taskLower)) {+ for (const entry of COMPILED_PATTERNS) {+ if (entry.regex.test(taskLower)) {return {- agent,- confidence: 0.8,- reason: `Matched pattern: ${pattern}`,+ agent: entry.agent,+ // Heuristic prior, not a learned probability β see file header.+ confidence: 0.6,+ reason: `Matched keyword(s) from: ${entry.tokens.join('|')}`,};}}- // Default to coder for unknown tasksreturn {agent: 'coder',- confidence: 0.5,- reason: 'Default routing - no specific pattern matched',+ confidence: 0.3,+ reason: 'Default routing - no specific keyword matched',};}// CLI-const task = process.argv.slice(2).join(' ');--if (task) {- const result = routeTask(task);- console.log(JSON.stringify(result, null, 2));-} else {- console.log('Usage: router.js <task description>');- console.log('\nAvailable agents:', Object.keys(AGENT_CAPABILITIES).join(', '));+if (require.main === module) {+ const task = process.argv.slice(2).join(' ');+ if (task) {+ const result = routeTask(task);+ console.log(JSON.stringify(result, null, 2));+ } else {+ console.log('Usage: router.js <task description>');+ console.log('\nAvailable agents:', Object.keys(AGENT_CAPABILITIES).join(', '));+ }}-module.exports = { routeTask, AGENT_CAPABILITIES, TASK_PATTERNS };+module.exports = { routeTask, AGENT_CAPABILITIES, TASK_PATTERNS, buildPattern };diff --git a/v3/@claude-flow/cli/bin/cli.js b/v3/@claude-flow/cli/bin/cli.jsindex 9aab4d22e9..5896e492ca 100755--- a/v3/@claude-flow/cli/bin/cli.js+++ b/v3/@claude-flow/cli/bin/cli.js@@ -9,32 +9,85 @@*/import { randomUUID } from 'crypto';+import { readFileSync } from 'fs';+import { fileURLToPath } from 'url';+import { dirname, join } from 'path';-// Suppress the SPECIFIC cosmetic "[AgentDB Patch] Controller index not found"-// warning from agentic-flow's runtime patch β these are emitted because the-// patch was written for agentdb v1.x and we use v3, where the controllers-// dist directory is laid out differently. The warning surfaces on every-// command and the audit (audit_1776483149979) flagged a too-broad suppression-// as a security risk because it could hide legitimate [AgentDB Patch] warnings.+// #2253 / #2256: Console filter installed BEFORE any other import. Two jobs://-// Tight match: must include both the prefix AND the specific "Controller-// index not found" text. Anything else (including future [AgentDB Patch]-// warnings about real issues) flows through unchanged. Also patch-// console.log because the underlying code uses it (the previous filter-// only caught console.warn and was therefore a no-op).+// 1. Suppress the cosmetic "[AgentDB Patch] Controller index not found"+// warning from agentic-flow (it expects agentdb v1.x but we use v3).+// Tight match β must include BOTH the prefix AND the specific text;+// other [AgentDB Patch] messages flow through. Audit log+// audit_1776483149979 flagged a broader filter as too aggressive.+//+// 2. Redirect noisy stdout writes from upstream embedder libraries+// (ruvector ONNX loader, ruvector-onnx-embeddings-wasm parallel+// embedder) to stderr. Those libraries use console.log for progress+// messages β "Loading model:", " Downloading: β¦", "π Initializing N+// workers" β which corrupts MCP JSON-RPC stdio (#2253) and is noise+// on stdout. stderr is the right channel for progress to a TTY user,+// and the MCP stdio framer reads stdout only.+//+// This MUST be installed before `import('../dist/src/index.js')` so the+// patch is in place before agentic-flow / ruvector load transitively.const _origWarn = console.warn;const _origLog = console.log;+const _origError = console.error;const _isCosmeticAgentdbPatchNoise = (msg) =>msg.includes('[AgentDB Patch]') && msg.includes('Controller index not found');+const _STDERR_REDIRECT_PREFIXES = [+ 'Loading model: ',+ ' Downloading: ',+ ' Cache hit: ',+ ' Disk cache hit: ',+ 'Model cache cleared',+ 'π Initializing ',+ 'β ',+];+const _shouldRedirectToStderr = (msg) => {+ for (const prefix of _STDERR_REDIRECT_PREFIXES) {+ if (msg.startsWith(prefix)) return true;+ }+ return false;+};console.warn = (...args) => {if (_isCosmeticAgentdbPatchNoise(String(args[0] ?? ''))) return;_origWarn.apply(console, args);};console.log = (...args) => {- if (_isCosmeticAgentdbPatchNoise(String(args[0] ?? ''))) return;+ const head = String(args[0] ?? '');+ if (_isCosmeticAgentdbPatchNoise(head)) return;+ if (_shouldRedirectToStderr(head)) {+ _origError.apply(console, args);+ return;+ }_origLog.apply(console, args);};+// #2256 fast path: --version / -V / --help / -h must NOT trigger heavy+// imports (agentic-flow, ruvector ONNX, etc.) β those eagerly download a+// 23 MB ONNX model on cold cache, blocking 60+ s and causing SIGTERM+// under common timeout windows (npx default, MCP stdio 30 s). Resolve+// version directly from package.json and exit before any heavy import.+{+ const _argv = process.argv.slice(2);+ if (_argv.length === 1 && (_argv[0] === '--version' || _argv[0] === '-V')) {+ try {+ const __dirname = dirname(fileURLToPath(import.meta.url));+ const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'));+ process.stdout.write(`ruflo v${pkg.version || '0.0.0'}\n`);+ } catch {+ process.stdout.write('ruflo v0.0.0\n');+ }+ process.exit(0);+ }+ // --help / -h with no other args also stays lightweight β fall through+ // to the existing fast help path inside index.ts; we don't short-circuit+ // here because some users pass `<command> --help` which needs lazy command+ // loading. The version short-circuit is the only one safe to inline.+}+// Check if we should run in MCP server mode// Conditions:// 1. stdin is being piped AND no CLI arguments provided (auto-detect)diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.tsindex 51bd618eb3..cd84d10074 100644--- a/v3/@claude-flow/cli/src/init/helpers-generator.ts+++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts@@ -211,7 +211,16 @@ export function generateAgentRouter(): string {return `#!/usr/bin/env node/*** Ruflo Agent Router- * Routes tasks to optimal agents based on learned patterns+ *+ * Static keyword router that suggests an agent for a task description.+ * NOTE: This is *not* a learned model. It is a heuristic table; "confidence"+ * is reported as a heuristic prior, not a calibrated probability.+ *+ * #2257 fix: patterns are now word-boundary-anchored so short tokens like+ * \`cd\`, \`ci\`, \`ui\`, \`add\`, \`structure\` no longer match inside unrelated+ * words (\`decision\`, \`infrastructure\`, \`address\`, \`addendum\`). Default+ * matched-confidence dropped from 0.8 to 0.6, and fall-through from 0.5 to+ * 0.3, to reflect that this is a static heuristic, not a learned classifier.*/const AGENT_CAPABILITIES = {@@ -225,40 +234,54 @@ const AGENT_CAPABILITIES = {devops: ['ci-cd', 'docker', 'deployment', 'infrastructure'],};-const TASK_PATTERNS = {- // Code patterns- 'implement|create|build|add|write code': 'coder',- 'test|spec|coverage|unit test|integration': 'tester',- 'review|audit|check|validate|security': 'reviewer',- 'research|find|search|documentation|explore': 'researcher',- 'design|architect|structure|plan': 'architect',-- // Domain patterns- 'api|endpoint|server|backend|database': 'backend-dev',- 'ui|frontend|component|react|css|style': 'frontend-dev',- 'deploy|docker|ci|cd|pipeline|infrastructure': 'devops',-};+// Each entry has a token list. Single tokens get \\bβ¦\\b boundaries so 'cd'+// won't match inside 'decide'. Phrases (whitespace or '/') match literally β+// the whitespace acts as a natural boundary.+const TASK_PATTERNS = [+ { tokens: ['implement', 'create', 'build', 'add', 'write code', 'refactor', 'debug'], agent: 'coder' },+ { tokens: ['test', 'tests', 'spec', 'coverage', 'unit test', 'integration test'], agent: 'tester' },+ { tokens: ['review', 'audit', 'check', 'validate', 'security'], agent: 'reviewer' },+ { tokens: ['research', 'find', 'search', 'documentation', 'explore'], agent: 'researcher' },+ { tokens: ['design', 'architect', 'architecture', 'structure', 'plan'], agent: 'architect' },+ { tokens: ['api', 'endpoint', 'server', 'backend', 'database'], agent: 'backend-dev' },+ { tokens: ['ui', 'frontend', 'component', 'react', 'css', 'style'], agent: 'frontend-dev' },+ { tokens: ['deploy', 'docker', 'ci', 'cd', 'ci/cd', 'pipeline', 'infrastructure', 'devops'], agent: 'devops' },+];++function escapeRegex(s) {+ return s.replace(/[.*+?^\${}()|[\\]\\\\]/g, '\\\\$&');+}-function routeTask(task) {- const taskLower = task.toLowerCase();+function buildPattern(tokens) {+ const alternatives = tokens.map((tok) => {+ const escaped = escapeRegex(tok.toLowerCase());+ if (/\\s|\\//.test(tok)) return escaped;+ return \`\\\\b\${escaped}\\\\b\`;+ });+ return new RegExp(\`(?:\${alternatives.join('|')})\`, 'i');+}++const COMPILED_PATTERNS = TASK_PATTERNS.map((entry) => ({+ agent: entry.agent,+ tokens: entry.tokens,+ regex: buildPattern(entry.tokens),+}));- // Check patterns- for (const [pattern, agent] of Object.entries(TASK_PATTERNS)) {- const regex = new RegExp(pattern, 'i');- if (regex.test(taskLower)) {+function routeTask(task) {+ const taskLower = String(task == null ? '' : task).toLowerCase();+ for (const entry of COMPILED_PATTERNS) {+ if (entry.regex.test(taskLower)) {return {- agent,- confidence: 0.8,- reason: \`Matched pattern: \${pattern}\`,+ agent: entry.agent,+ confidence: 0.6,+ reason: \`Matched keyword(s) from: \${entry.tokens.join('|')}\`,};}}-- // Default to coder for unknown tasksreturn {agent: 'coder',- confidence: 0.5,- reason: 'Default routing - no specific pattern matched',+ confidence: 0.3,+ reason: 'Default routing - no specific keyword matched',};}@@ -273,7 +296,7 @@ if (task) {console.log('\\nAvailable agents:', Object.keys(AGENT_CAPABILITIES).join(', '));}-module.exports = { routeTask, AGENT_CAPABILITIES, TASK_PATTERNS };+module.exports = { routeTask, AGENT_CAPABILITIES, TASK_PATTERNS, buildPattern };`;}diff --git a/v3/@claude-flow/cli/src/log-filters.ts b/v3/@claude-flow/cli/src/log-filters.tsindex 83426167e3..4807f64699 100644--- a/v3/@claude-flow/cli/src/log-filters.ts+++ b/v3/@claude-flow/cli/src/log-filters.ts@@ -1,20 +1,28 @@/**- * Console filter for the cosmetic "[AgentDB Patch] Controller index not found"- * warning emitted by agentic-flow's runtime patch (it expects agentdb v1.x- * layout but we use v3). This file MUST be imported as the first side-effect- * import in any entry point so the patch is in place before agentic-flow- * (and anything that transitively imports it) loads.+ * Console filter installed at the top of every entry point. Two jobs:*- * The previous attempt put the suppression as a top-level code block inside- * src/index.ts, but ES module imports are evaluated before the file's own- * top-level code, so transitive imports of agentic-flow were still- * triggering the warning before the suppression took effect. A dedicated- * side-effect module imported FIRST avoids that.+ * 1. Suppress the cosmetic "[AgentDB Patch] Controller index not found"+ * warning emitted by agentic-flow's runtime patch (it expects agentdb+ * v1.x layout but we use v3). Tight match: requires BOTH the prefix+ * AND the specific message. Other [AgentDB Patch] messages flow through.+ * Audit log audit_1776483149979 flagged the previous broad filter as+ * too aggressive β this one is tight enough to be safe.*- * Tight match: requires BOTH "[AgentDB Patch]" AND "Controller index not- * found". Other [AgentDB Patch] messages (real issues) flow through.- * Audit log audit_1776483149979 flagged the previous broad filter as too- * aggressive β this one is tight enough to be safe.+ * 2. (#2253, #2256) Redirect noisy stdout writes from upstream embedder+ * libraries (ruvector ONNX loader, ruvector-onnx-embeddings-wasm+ * parallel embedder) to stderr. The libraries use `console.log` for+ * progress messages like "Loading model:" and " Downloading: ...",+ * which corrupts MCP JSON-RPC stdio (#2253) and is generally noise on+ * stdout. We never want these on stdout β stderr is the right channel+ * for progress to a TTY user, and the MCP stdio framer reads stdout+ * only, so this keeps the protocol clean without dropping useful+ * diagnostics.+ *+ * This file MUST be imported as the first side-effect import in any entry+ * point so the patch is in place before agentic-flow / ruvector (and+ * anything that transitively imports them) loads. ES module imports are+ * evaluated before the file's own top-level code, so putting this in+ * src/index.ts directly would race with transitive eager imports.*/const isCosmeticAgentdbPatchNoise = (msg: unknown): boolean => {@@ -22,8 +30,31 @@ const isCosmeticAgentdbPatchNoise = (msg: unknown): boolean => {return s.includes('[AgentDB Patch]') && s.includes('Controller index not found');};+// #2253 / #2256: prefixes from third-party embedder libs that come out on+// stdout via console.log and corrupt MCP JSON-RPC. We redirect to stderr.+// Match is anchored to known prefixes only β anything else (e.g. legitimate+// user-facing CLI output) is unaffected.+const STDERR_REDIRECT_PREFIXES = [+ 'Loading model: ', // ruvector + ruvector-onnx-embeddings-wasm loader.js+ ' Downloading: ', // ruvector + ruvector-onnx-embeddings-wasm loader.js+ ' Cache hit: ', // ruvector + ruvector-onnx-embeddings-wasm loader.js+ 'Model cache cleared', // ruvector + ruvector-onnx-embeddings-wasm loader.js+ 'π Initializing ', // ruvector-onnx-embeddings-wasm parallel-embedder.mjs+ 'β ', // ruvector-onnx-embeddings-wasm parallel-embedder.mjs (workers ready)+ ' Disk cache hit: ', // ruvector-onnx-embeddings-wasm parallel-embedder.mjs+];++const shouldRedirectToStderr = (msg: unknown): boolean => {+ const s = String(msg ?? '');+ for (const prefix of STDERR_REDIRECT_PREFIXES) {+ if (s.startsWith(prefix)) return true;+ }+ return false;+};+const origWarn = console.warn.bind(console);const origLog = console.log.bind(console);+const origError = console.error.bind(console);console.warn = (...args: unknown[]) => {if (isCosmeticAgentdbPatchNoise(args[0])) return;@@ -31,5 +62,9 @@ console.warn = (...args: unknown[]) => {};console.log = (...args: unknown[]) => {if (isCosmeticAgentdbPatchNoise(args[0])) return;+ if (shouldRedirectToStderr(args[0])) {+ origError(...args);+ return;+ }origLog(...args);};diff --git a/v3/@claude-flow/mcp/.claude/helpers/router.js b/v3/@claude-flow/mcp/.claude/helpers/router.jsindex 8a7f14344a..df8f9bc00c 100644--- a/v3/@claude-flow/mcp/.claude/helpers/router.js+++ b/v3/@claude-flow/mcp/.claude/helpers/router.js@@ -1,7 +1,16 @@#!/usr/bin/env node/*** Claude Flow Agent Router- * Routes tasks to optimal agents based on learned patterns+ *+ * Static keyword router that suggests an agent for a task description.+ * NOTE: This is *not* a learned model. It is a heuristic table; "confidence"+ * is reported as a heuristic prior, not a calibrated probability.+ *+ * #2257 fix: patterns are now word-boundary-anchored so short tokens like+ * `cd`, `ci`, `ui`, `add`, `structure` no longer match inside unrelated+ * words (`decision`, `infrastructure`, `address`, `addendum`). Default+ * confidence dropped from 0.8 to 0.6 to better reflect that this is a+ * static heuristic, not a learned classifier.*/const AGENT_CAPABILITIES = {@@ -15,52 +24,82 @@ const AGENT_CAPABILITIES = {devops: ['ci-cd', 'docker', 'deployment', 'infrastructure'],};-const TASK_PATTERNS = {+// Each entry is an array of tokens. Tokens are alternation-friendly:+// - multi-word phrases ("unit test") match as phrases+// - single tokens are wrapped with \b β¦ \b word boundaries at match time+const TASK_PATTERNS = [// Code patterns- 'implement|create|build|add|write code': 'coder',- 'test|spec|coverage|unit test|integration': 'tester',- 'review|audit|check|validate|security': 'reviewer',- 'research|find|search|documentation|explore': 'researcher',- 'design|architect|structure|plan': 'architect',+ { tokens: ['implement', 'create', 'build', 'add', 'write code', 'refactor', 'debug'], agent: 'coder' },+ { tokens: ['test', 'tests', 'spec', 'coverage', 'unit test', 'integration test'], agent: 'tester' },+ { tokens: ['review', 'audit', 'check', 'validate', 'security'], agent: 'reviewer' },+ { tokens: ['research', 'find', 'search', 'documentation', 'explore'], agent: 'researcher' },+ { tokens: ['design', 'architect', 'architecture', 'structure', 'plan'], agent: 'architect' },// Domain patterns- 'api|endpoint|server|backend|database': 'backend-dev',- 'ui|frontend|component|react|css|style': 'frontend-dev',- 'deploy|docker|ci|cd|pipeline|infrastructure': 'devops',-};+ { tokens: ['api', 'endpoint', 'server', 'backend', 'database'], agent: 'backend-dev' },+ { tokens: ['ui', 'frontend', 'component', 'react', 'css', 'style'], agent: 'frontend-dev' },+ // 'cd' / 'ci' are kept but require word boundaries via \b β they will not+ // match inside "decision" or "specific". 'cd' as a literal command in a+ // task description ("set up cd pipeline") still matches.+ { tokens: ['deploy', 'docker', 'ci', 'cd', 'ci/cd', 'pipeline', 'infrastructure', 'devops'], agent: 'devops' },+];++function escapeRegex(s) {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++// Build an anchored alternation regex from a token list.+// - multi-word phrases (containing whitespace or '/') match literally+// - single tokens are wrapped with \b boundaries so 'cd' won't match "decide"+function buildPattern(tokens) {+ const alternatives = tokens.map((tok) => {+ const escaped = escapeRegex(tok.toLowerCase());+ if (/\s|\//.test(tok)) {+ // Phrase: whitespace/'/' on each side acts as a natural boundary+ return escaped;+ }+ return `\\b${escaped}\\b`;+ });+ return new RegExp(`(?:${alternatives.join('|')})`, 'i');+}++const COMPILED_PATTERNS = TASK_PATTERNS.map((entry) => ({+ agent: entry.agent,+ tokens: entry.tokens,+ regex: buildPattern(entry.tokens),+}));function routeTask(task) {- const taskLower = task.toLowerCase();+ const taskLower = String(task ?? '').toLowerCase();- // Check patterns- for (const [pattern, agent] of Object.entries(TASK_PATTERNS)) {- const regex = new RegExp(pattern, 'i');- if (regex.test(taskLower)) {+ for (const entry of COMPILED_PATTERNS) {+ if (entry.regex.test(taskLower)) {return {- agent,- confidence: 0.8,- reason: `Matched pattern: ${pattern}`,+ agent: entry.agent,+ // Heuristic prior, not a learned probability β see file header.+ confidence: 0.6,+ reason: `Matched keyword(s) from: ${entry.tokens.join('|')}`,};}}- // Default to coder for unknown tasksreturn {agent: 'coder',- confidence: 0.5,- reason: 'Default routing - no specific pattern matched',+ confidence: 0.3,+ reason: 'Default routing - no specific keyword matched',};}// CLI-const task = process.argv.slice(2).join(' ');--if (task) {- const result = routeTask(task);- console.log(JSON.stringify(result, null, 2));-} else {- console.log('Usage: router.js <task description>');- console.log('\nAvailable agents:', Object.keys(AGENT_CAPABILITIES).join(', '));+if (require.main === module) {+ const task = process.argv.slice(2).join(' ');+ if (task) {+ const result = routeTask(task);+ console.log(JSON.stringify(result, null, 2));+ } else {+ console.log('Usage: router.js <task description>');+ console.log('\nAvailable agents:', Object.keys(AGENT_CAPABILITIES).join(', '));+ }}-module.exports = { routeTask, AGENT_CAPABILITIES, TASK_PATTERNS };+module.exports = { routeTask, AGENT_CAPABILITIES, TASK_PATTERNS, buildPattern };