π 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(hooks): match router keywords on word boundaries, not substrings (#3401) (#3402)
rUv8080d872ac2a
diff --git a/.claude/helpers/router.cjs b/.claude/helpers/router.cjsindex 816bba20e2..6f19e3756f 100644--- a/.claude/helpers/router.cjs+++ b/.claude/helpers/router.cjs@@ -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,41 +24,73 @@ const AGENT_CAPABILITIES = {devops: ['ci-cd', 'docker', 'deployment', 'infrastructure'],};-const TASK_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',- 'api|endpoint|server|backend|database': 'backend-dev',- 'ui|frontend|component|react|css|style': 'frontend-dev',- 'deploy|docker|ci|cd|pipeline|infrastructure': 'devops',-};+// 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+ { tokens: ['implement', 'create', 'build', 'add', 'write code', 'refactor', 'debug'], agent: 'coder' },+ { tokens: ['test', 'tests', 'testing', 'spec', 'specs', '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+ { 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();- 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('|')}`,};}}return {agent: 'coder',- confidence: 0.5,- reason: 'Default routing - no specific pattern matched',+ confidence: 0.3,+ reason: 'Default routing - no specific keyword matched',};}-module.exports = { routeTask, AGENT_CAPABILITIES, TASK_PATTERNS };--// CLI - only run when executed directly+// CLIif (require.main === module) {const task = process.argv.slice(2).join(' ');if (task) {@@ -60,3 +101,5 @@ if (require.main === module) {console.log('\nAvailable agents:', Object.keys(AGENT_CAPABILITIES).join(', '));}}++module.exports = { routeTask, AGENT_CAPABILITIES, TASK_PATTERNS, buildPattern };diff --git a/v3/@claude-flow/cli/.claude/helpers/router.js b/v3/@claude-flow/cli/.claude/helpers/router.jsindex df8f9bc00c..6f19e3756f 100644--- a/v3/@claude-flow/cli/.claude/helpers/router.js+++ b/v3/@claude-flow/cli/.claude/helpers/router.js@@ -30,7 +30,7 @@ const AGENT_CAPABILITIES = {const TASK_PATTERNS = [// Code patterns{ tokens: ['implement', 'create', 'build', 'add', 'write code', 'refactor', 'debug'], agent: 'coder' },- { tokens: ['test', 'tests', 'spec', 'coverage', 'unit test', 'integration test'], agent: 'tester' },+ { tokens: ['test', 'tests', 'testing', 'spec', 'specs', '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' },diff --git a/v3/@claude-flow/cli/__tests__/router-wordboundary.test.ts b/v3/@claude-flow/cli/__tests__/router-wordboundary.test.tsnew file mode 100644index 0000000000..9b62488017--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/router-wordboundary.test.ts@@ -0,0 +1,132 @@+/**+ * Keyword routers must match whole words, not substrings.+ *+ * Observed live: "sync and review latest issues" routed to `tester` at 0.8+ * because the pattern `test|spec|coverage|unit test|integration` was compiled+ * with `new RegExp(pattern, 'i')` and no word boundaries β "la-TEST" matched.+ * The same class of bug made `ui` match "build"/"guide"/"quick", `ci`/`cd`+ * match "decide"/"special", `add` match "address".+ *+ * #2257 already anchored the generated router (helpers-generator.ts), but:+ * - the repo-root `.claude/helpers/router.cjs` still carried the substring+ * version, and+ * - `suggestAgentsForTask()` in mcp-tools/hooks-tools.ts (used by+ * hooks_pre-task, and as the keyword fallback of hooks_route and+ * hooks_explain) used `taskLower.includes(keyword)` β `'test'` matched+ * "latest" at 0.95 confidence, `'auth'` matched "author", `'fix'`+ * matched "prefix", `'api'` matched "capital".+ *+ * Every copy is driven through the same table here.+ */+import { describe, it, expect, vi } from 'vitest';+import { createRequire } from 'module';+import { mkdtempSync, writeFileSync, rmSync, readFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { fileURLToPath } from 'url';++// hooks-tools pulls optional native / memory modules at call time only; the+// keyword matcher is pure, so no mocks are needed beyond silencing init logs.+vi.spyOn(console, 'log').mockImplementation(() => {});++import { generateAgentRouter } from '../src/init/helpers-generator.js';+import { suggestAgentsForTask } from '../src/mcp-tools/hooks-tools.js';++const require = createRequire(import.meta.url);+const here = fileURLToPath(new URL('.', import.meta.url));++type RouteResult = { agent: string; confidence: number; reason: string };+type Router = { routeTask: (task: string) => RouteResult };++// Load router source as CommonJS from a temp dir. The in-repo .js snapshots+// live under a "type": "module" package, so they cannot be require()d in place;+// user projects load them as CJS via hook-handler.cjs.+function loadRouterSource(source: string): Router {+ const dir = mkdtempSync(join(tmpdir(), 'router-wb-'));+ const file = join(dir, 'router.cjs');+ writeFileSync(file, source);+ try {+ return require(file) as Router;+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++const ROUTERS: Array<[string, () => Router]> = [+ ['generated (helpers-generator.ts)', () => loadRouterSource(generateAgentRouter())],+ ['repo-root .claude/helpers/router.cjs', () => loadRouterSource(readFileSync(join(here, '../../../../.claude/helpers/router.cjs'), 'utf8'))],+ ['cli .claude/helpers/router.js', () => loadRouterSource(readFileSync(join(here, '../.claude/helpers/router.js'), 'utf8'))],+ ['mcp .claude/helpers/router.js', () => loadRouterSource(readFileSync(join(here, '../../mcp/.claude/helpers/router.js'), 'utf8'))],+];++// [task, expected] β expected is an agent, `{ not: agent }`, or `{ oneOf: [...] }`.+type Expect = string | 'default' | { not: string } | { oneOf: string[] };+const HELPER_CASES: Array<[string, Expect]> = [+ // Negatives β the live bugs+ ['sync and review latest issues', { not: 'tester' }],+ ['sync and review latest issues', 'reviewer'],+ ['can we integrate into ruflo', { not: 'tester' }],+ ['guide me through the quick setup', { not: 'frontend-dev' }],+ ['decide on the approach', { not: 'devops' }],+ ['a special case in the parser', { not: 'devops' }],+ ['address the bug', 'default'], // 'add' must not match "address"+ ['write specifications for the parser', { not: 'tester' }],+ // Positives β real intent still matches+ ['write unit tests for auth', 'tester'],+ ['add integration tests for the api', { oneOf: ['coder', 'tester'] }],+ ['improve test coverage', 'tester'],+ ['testing the login flow', 'tester'],+ ['build the UI component', { oneOf: ['coder', 'frontend-dev'] }],+ ['style the react component', 'frontend-dev'],+ ['set up ci pipeline', 'devops'],+ ['add JWT support', 'coder'],+];++function check(r: RouteResult, want: Expect): boolean {+ const actual = r.agent;+ if (want === 'default') return r.confidence < 0.5;+ if (typeof want === 'string') return actual === want;+ if ('not' in want) return actual !== want.not;+ return want.oneOf.includes(actual);+}++describe.each(ROUTERS)('helper router word boundaries: %s', (_name, load) => {+ const router = load();++ it.each(HELPER_CASES)('%s β %j', (task, want) => {+ const r = router.routeTask(task);+ expect(check(r, want), `${task} routed to ${r.agent} (${r.reason})`).toBe(true);+ });++ it('never reports the old 0.8 "learned" confidence for a keyword hit', () => {+ expect(router.routeTask('write unit tests for auth').confidence).toBeLessThan(0.8);+ });+});++describe('hooks-tools suggestAgentsForTask word boundaries', () => {+ const DEFAULT = ['coder', 'researcher', 'tester'];++ it.each([+ 'sync and review latest issues', // 'test' in "latest"+ 'update the author field', // 'auth' in "author"+ 'strip the prefix', // 'fix' in "prefix"+ 'capitalize the heading', // 'api' in "capitalize"+ ])('"%s" falls through to the default instead of a substring hit', (task) => {+ const r = suggestAgentsForTask(task);+ expect(r.agents).toEqual(DEFAULT);+ expect(r.confidence).toBe(0.7);+ });++ it.each([+ ['write unit tests for the parser', 'tester'],+ ['testing the login flow', 'tester'],+ ['fix the crash on startup', 'coder'],+ ['fixes for the parser', 'coder'],+ ['add auth to the gateway', 'security-architect'],+ ['document the api', 'architect'],+ ['set up ci/cd', 'devops'],+ ['deploying to staging', 'devops'],+ ])('"%s" still routes to %s', (task, first) => {+ expect(suggestAgentsForTask(task).agents[0]).toBe(first);+ });+});diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.tsindex 6145698c3c..f9f57fb340 100644--- a/v3/@claude-flow/cli/src/init/helpers-generator.ts+++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts@@ -289,7 +289,7 @@ const AGENT_CAPABILITIES = {// 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: ['test', 'tests', 'testing', 'spec', 'specs', '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' },@@ -335,15 +335,16 @@ function routeTask(task) {};}-// 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(', '));+// CLI β only when executed directly, not when require()d by hook-handler.cjs+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, buildPattern };diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.tsindex 66da00301e..b6b5e3c467 100644--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts@@ -779,12 +779,22 @@ function suggestAgentsForFile(filePath: string): string[] {return AGENT_PATTERNS[ext] || ['coder', 'architect'];}-function suggestAgentsForTask(task: string): { agents: string[]; confidence: number } {- const taskLower = task.toLowerCase();-+// Whole-word matchers for KEYWORD_PATTERNS. A bare `includes()` matched+// substrings: 'test' hit "latest" (tester @ 0.95), 'auth' hit "author",+// 'fix' hit "prefix", 'api' hit "capitalize". Single words get \b anchors plus+// simple inflections (tests, testing, fixes, deployed); phrases containing+// whitespace or '/' (e.g. 'ci/cd') match literally between word boundaries.+const KEYWORD_MATCHERS = Object.entries(KEYWORD_PATTERNS).map(([keyword, result]) => {+ const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const body = /[\s/]/.test(keyword) ? escaped : `${escaped}(?:s|es|ing|ed)?`;+ return { regex: new RegExp(`\\b${body}\\b`, 'i'), result };+});++/** Exported for tests. */+export function suggestAgentsForTask(task: string): { agents: string[]; confidence: number } {// Check static keyword patterns first- for (const [pattern, result] of Object.entries(KEYWORD_PATTERNS)) {- if (taskLower.includes(pattern)) {+ for (const { regex, result } of KEYWORD_MATCHERS) {+ if (regex.test(task)) {return result;}}diff --git a/v3/@claude-flow/mcp/.claude/helpers/router.js b/v3/@claude-flow/mcp/.claude/helpers/router.jsindex df8f9bc00c..6f19e3756f 100644--- a/v3/@claude-flow/mcp/.claude/helpers/router.js+++ b/v3/@claude-flow/mcp/.claude/helpers/router.js@@ -30,7 +30,7 @@ const AGENT_CAPABILITIES = {const TASK_PATTERNS = [// Code patterns{ tokens: ['implement', 'create', 'build', 'add', 'write code', 'refactor', 'debug'], agent: 'coder' },- { tokens: ['test', 'tests', 'spec', 'coverage', 'unit test', 'integration test'], agent: 'tester' },+ { tokens: ['test', 'tests', 'testing', 'spec', 'specs', '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' },