@monoes/routing

Semantic task-to-agent routing for Monomind (@monoes/routing v1.0.3 / Monomind CLI v2.9.0).
Part of the Monomind ecosystem. Handles deterministic keyword filtering, hash-embedding cosine similarity matching, and LLM fallback classification to route user tasks to specialized agent roles.
🏗 Task-to-Agent Cascade Architecture
When a task description is processed, @monoes/routing executes a multi-tier cascade flow (fast deterministic $\rightarrow$ embedding similarity $\rightarrow$ LLM fallback):
Task Description
│
▼
┌───────────────────────────┐
│ Tier 1: Keyword Pre-Filter │ ── Match ──▶ confidence: 1.0 (method: 'keyword')
│ (30+ rules, < 1ms) │
└───────────────────────────┘
│ No Match
▼
┌───────────────────────────┐
│ Tier 2: Cosine Centroid │ ── Sim >= 0.5 ──▶ confidence: cosine (method: 'semantic')
│ (256-D MD5/HNSW Vector) │
└───────────────────────────┘
│ Below Threshold
▼
┌───────────────────────────┐
│ Tier 3: LLM Fallback │ ── Classify ──▶ confidence: 0.85 (method: 'llm_fallback')
│ (Claude Haiku / Degraded) │
└───────────────────────────┘
1. Tier 1: Deterministic Keyword Pre-Filter
- Source:
keyword-pre-filter.ts:18-93
- Evaluates tasks using fast regular expression matching against 30+ default rule definitions (e.g., CVE security checks, unit test files, Docker/DevOps configs, Solidity/ZK contracts, MCP tools).
- Returns immediate match with
confidence: 1.0 and method: 'keyword'.
2. Tier 2: Cosine Centroid Embedding Match
- Source:
route-layer.ts:73-106, cosine.ts:5-20
- Computes cosine similarity between task vector embeddings and agent route centroid vectors.
- Supports lightweight 256-D MD5/SHA-256 hash embeddings (
LocalEncoder) or transformer embeddings (HNSWEncoder).
- If similarity $\ge \text{threshold}$ (default: 0.5), routes task with
method: 'semantic'.
3. Tier 3: LLM Fallback Classification
- Source:
llm-fallback.ts:20-88, prompts/classify.ts:4-28
- Constructs a compact capability prompt (max 8,000 chars) detailing candidate agent descriptions and returns classification with
confidence: 0.85 and method: 'llm_fallback'.
- On API failure or missing key, degrades gracefully to the default route with
method: 'semantic_degraded'.
💻 CLI Command Reference (monomind route)
The Monomind CLI provides 9 subcommands under monomind route (defined in src/commands/route.ts:80-800):
task | monomind route task "<prompt>" | Primary CLI entry point. Routes a task prompt to the best agent slug. | --json, --verbose |
semantic | monomind route semantic "<prompt>" | Executes full @monoes/routing embedding + centroid pipeline. | --threshold N, --json |
list-agents | monomind route list-agents | Displays all registered agents, capabilities, and keyword patterns. | --format json |
stats | monomind route stats | Displays routing performance metrics, cache hits, and tier usage breakdown. | --reset |
feedback | monomind route feedback -t "<task>" -a <agent> -r <reward> | Records routing outcome to the local feedback ledger (route-outcomes.jsonl). | -t, -a, -r |
reset | monomind route reset | Resets cached route centroids, outcomes, and feedback data. | --force |
export | monomind route export --out <file> | Exports learned routing centroids and capability index to JSON. | --out |
import | monomind route import --in <file> | Imports routing centroids and rules from external JSON file. | --in, --merge |
coverage / cov | monomind route coverage | Runs benchmark coverage test across sample task prompts. | --min-score N |
⚡ Task Complexity Scoring Rules
Task complexity is dynamically calculated to estimate execution duration, budget allocation, and agent delegation hierarchy:
- High Complexity ("2–4 hours"): Prompts containing architecture refactoring, full stack migrations, multi-package dependencies, or text length $> 500$ chars.
- Medium Complexity ("30–60 min"): Standard feature implementations, multi-file bugfixes, API integration, or text length $> 150$ chars.
- Complexity Scoring:
High (Estimated 2-4 hours): Task description contains 'complex' or 'architecture' OR character length > 200 (hooks-routing.ts:395-400).
Low (Estimated 10-30 min): Task description contains 'simple' or 'fix' OR character length < 50.
Medium (Estimated 30-60 min): All other standard task prompts.
Test Suites
Vitest test suites are located in packages/@monomind/routing/__tests__/:
route-layer.test.ts: Cascade evaluation, thresholds, and fallback behavior.
keyword-pre-filter.test.ts: Regex rule precedence and pattern matching.
encoder.test.ts: 256-D MD5/SHA-256 local encoding and LRU cache eviction.
llm-fallback.test.ts: LLM prompt construction, candidate hint parsing, and error recovery.
cosine.test.ts: Validates vector dot product calculation and centroid position aggregation.
capability-index.test.ts: Ensures agent capability indexing stays under the 8,000-character context budget.
Run unit tests via:
pnpm --filter @monoes/routing test
🚀 Usage Example
import { RouteLayer } from '@monoes/routing';
const router = new RouteLayer({
routes: [
{ name: 'coder', agentSlug: 'coder', utterances: ['implement feature', 'build api'], threshold: 0.5 },
{ name: 'tester', agentSlug: 'tester', utterances: ['write unit test', 'add coverage'], threshold: 0.5 },
{ name: 'security', agentSlug: 'security-engineer', utterances: ['fix cve', 'audit vulnerability'], threshold: 0.5 },
],
enableKeywordFilter: true,
});
await router.initialize();
const res1 = await router.route('Fix CVE-2024-12345 vulnerability');
const res2 = await router.route('Create new REST endpoint for user profiles');
🔗 Links
📄 License
Apache-2.0