Neuroweave: The Basal Ganglia Engine (v1.0-stable)
Shift+Alt+F) and CLI aliases (cargo fmt) that run in 1 millisecond without an intermediary MCP proxy. The True Architectural Target: Neuroweave is an in-code, headless MCP middleware engineered specifically for autonomous agent loops and bot swarms (such as CI/CD build agents, batch-generation runners, and unattended worker subagents) that programmatically execute rigid, identical mechanical operations thousands of times per hour.🧠 The Biological Metaphor: Why "Basal Ganglia"?
In neuroscience, the human brain delegates high-level strategic reasoning, creative synthesis, and abstract problem-solving to the prefrontal cortex. However, if your prefrontal cortex had to consciously deliberate every heartbeat, muscle twitch, or mechanical step while walking, cognitive capacity would instantly collapse.
The brain offloads repetitive, habitual motor patterns to the basal ganglia—an ancient, ultra-fast reflex loop that executes deterministic physical subroutines with zero conscious overhead.
Modern autonomous AI coding agents suffer from a fatal lack of a basal ganglia:
Traditional Agentic Architecture (No Reflex Loop):
Autonomous Agent Loop ──[Repeated Task: "format workspace"]──► Cloud LLM (2,000 Tokens, 3,500ms, $0.005)
Autonomous Agent Loop ──[Repeated Task: "clean imports"]────► Cloud LLM (1,800 Tokens, 2,800ms, $0.004)
Autonomous Agent Loop ──[Repeated Task: "scaffold module"]───► Cloud LLM (2,500 Tokens, 4,100ms, $0.008)
Neuroweave Basal Ganglia Architecture (Hardware Reflex Loop):
Autonomous Agent Loop ──[Repeated Task: "format workspace"]──► Neuroweave Regex Gate ──► Local Rust Subroutine (0 Tokens, 2ms, $0.00)
Autonomous Agent Loop ──[Subjective: "re-architect pipeline"]► Neuroweave Drift Gate ──► Cloud LLM Reasoning (Full Context Window)
Neuroweave acts as the dedicated hardware basal ganglia for synthetic intelligence. It sits directly on the Model Context Protocol (MCP) transport pipe, intercepting deterministic operational commands before they can burn remote cognitive tokens.
🎯 Target Audience Comparison: Who This Is (and Isn't) For
| Architectural Dimension | Interactive Human Developer (Anti-Pattern) | Autonomous Agent Loop (Target Persona) |
|---|---|---|
| Prompt Style | Conversational, ambiguous, subjective ("tweak this") | Rigid, programmatic, standardized ("format", "init") |
| Execution Volume | 10 to 50 prompts per working day | Thousands of automated passes per hour |
| Existing Alternatives | Native IDE shortcuts (Ctrl+K, Ctrl+F, CLI commands) | Scripted tool calls over standard input/output (stdio) |
| Semantic Drift Risk | Human catches bad code visually in real time | Agent silently hallucinates or corrupts codebase |
| Token Impact | Negligible savings ($0.02 / day) | Massive savings ($50 – $300 / day in automated swarms) |
| User Experience | Annoying friction; constantly triggers drift alerts | Seamless, sub-millisecond local execution |
⚡ The Problem It Solves in Autonomous Pipelines
When autonomous agents (such as headless Cursor instances, Claude Code swarms, or custom build-repair loops) operate unattended in Docker containers or cloud runners, they encounter three severe bottlenecks:
- 💸 Token Budget Hemorrhaging: Asking an LLM to repeatedly parse an entire workspace just to run a linter or scaffold an identical boilerplate controller burns millions of unnecessary prompt tokens.
- ⏳ Cumulative Pipeline Latency: Outbound HTTPS requests to upstream cognitive APIs incur 2 to 5 seconds of network and generation latency. In an agent loop executing 500 iterative test cycles, latency alone consumes over 30 minutes of idle wait time.
- 🌪️ Semantic Drift & Hallucinatory Overreach: Stochastic models cannot guarantee zero-mutation invariance. An LLM tasked simply with "tidying imports" will occasionally rename variables, alter function signatures, or introduce subtle logic bugs.
Neuroweave provides a mathematically deterministic firewall: if an agent's intent is 100% mechanical and verified, it executes natively in Rust in under 2 milliseconds with guaranteed transactional rollbacks. If the prompt contains even a single ambiguous word, it escalates untouched to the cloud LLM.
🛠️ Architecture & Core Components
Neuroweave is engineered around the Single-Binary Appliance Pattern, boasting an idle memory footprint of < 30MB and cold-boot times under 50ms.
graph TD
User([Autonomous Agent Loop]) --> Intercept[Agent Client Hook]
Intercept --> Router[router::evaluate_intent]
subgraph Intent Intersection Gate
Router --> Drift{Layer 4: Semantic Drift?}
Drift -->|Subjective Language| ZeroConf[Confidence: 0.0 / Escalate]
Drift -->|Safe Directives| Lexical[Layer 1: Lexical Match / TaskID]
end
ZeroConf --> Dispatcher[dispatcher::dispatch]
Lexical --> Dispatcher
subgraph Actuation Pipeline
Dispatcher --> Security{Trust Boundary >= 0.90?}
Security -->|No| LLMEscalation[Escalate to Cloud LLM]
Security -->|Yes| Subroutine[subroutines::BasalTask]
Subroutine --> Transaction[executor::FileTransaction]
Rollback -->|No| Revert[Abort & Rollback file delta]
Rollback -->|Yes| Success[resolved_locally: true]
end
1. The Intent Intersection Gate (src/router.rs)
The triage center. It executes compiled OnceLock regex filters. It strictly processes Layer 4 Semantic Drift (checking for subjective danger words like "modernize", "simplify", "improve") first. If drift is detected, it zeroes the confidence score and escalates immediately. Otherwise, it proceeds to Layer 1 Lexical matching (mapping "format" and "lint" to deterministic local task IDs).
2. The Confidence Engine & Trust Radius (src/confidence.rs & src/core.rs)
Defines the ConfidenceProfile and TrustRadius of tasks. Every local task declares its blast radius parameters—defining hard constraints on maximum mutable files, permitted AST mutations, cross-module writes, and mandatory rollbacks.
3. The Transactional Actuator (src/executor.rs & src/subroutines.rs)
Guarantees absolute workspace safety. File edits are managed in a transactional context via FileTransaction. In the event of an OS-level friction error (such as file locks or permission denials), it immediately executes a rollback() to the pre-transaction state and escalates the execution back to the cloud LLM with the error trace attached.
4. The Dispatcher (src/dispatcher.rs)
Enforces strict security trust boundaries. Any interaction falling below 0.90 confidence or yielding active ambiguity flags is blocked from physical file I/O and routed safely to standard cloud LLM execution.
🎯 Trigger Keywords & Triage Rules
For programmatic agent pipelines utilizing Neuroweave, prompt templates should be configured to deliberately target these exact trigger keywords:
🟢 Local Bypass Triggers (Automated Reflexes)
These keywords immediately map to ultra-fast, zero-token local subroutines:
- Code Formatting / Linting (
FormatLintSubroutine): - Trigger words:
format,lint(e.g., "format codebase") - Boilerplate Scaffolding (
ScaffoldModuleSubroutine): - Trigger words:
scaffold,init(e.g., "scaffold module controller") - Import Optimization (
CleanImportsSubroutine): - Trigger words: Both
cleanandimportspresent (e.g., "clean unused imports")
⚠️ Cloud Escalation Words (Semantic Drift Shield)
If an automated workflow injects any of these subjective "danger words," Neuroweave immediately halts local execution and escalates to the cloud LLM to protect code integrity:
improve • refactor • simplify • modernize • clean this up • optimize • architect • design • rework • bulletproof • harden • audit • review • evaluate • fix • debug • resolve • advise • integrate
(For example: format codebase executes locally in 2ms. Asking improve and format codebase safely bypasses local execution and escalates to the cloud LLM for full contextual evaluation.)
🚀 Headless Deployment & Daemon Configuration
Neuroweave compiles to a standalone, zero-dependency static executable designed to run alongside agent processes or inside CI containers.
Compile Standalone Release Binary
cargo build --release
Run E2E Verification Test Suite
target/release/neuroweave.exe
Activate stdio JSON-RPC MCP Agent Mode
target/release/neuroweave.exe --mcp
MCP Client Registration (mcp_config.json)
{
"mcpServers": {
"neuroweave": {
"command": "/usr/local/bin/neuroweave",
"args": ["--mcp"],
"env": {
"RUST_LOG": "info"
}
}
}
}
📊 Telemetry & Cumulative Savings Ledger
To track and audit the cost, latency, and energy reductions achieved across automated agent pools, Neuroweave operates a file-based telemetry logging pipeline.
Transactional Payload Mechanism
To avoid shell-escaping limitations under complex CLI environments (such as PowerShell or Docker sh), logging processes utilize a transactional file-based protocol:
- The caller (MCP server, CI pipeline, or test runner) writes output to
last_action_payload.json:
{
"raw_prompt": "format codebase",
"task_output": {
"resolved_locally": true,
"execution_ms": 2,
"message": "Deterministic formatting applied.",
"tokens_saved": 1500,
"cost_saved_usd": 0.0001125,
"energy_saved_wh": 0.01
}
}
- The telemetry consumer runs
python telemetry_tracker.pyto ingest the record into persistent audit storage (savings_log.json). last_action_payload.jsonis atomically cleaned up.
Persistent Ledger Metrics (savings_log.json)
total_runs: Total intercepted prompts triaged by Neuroweave.total_bypasses: Total prompts resolved locally without invoking upstream cognitive APIs.total_tokens_saved: Cumulative tokens saved by bypassing standard cloud reasoning models.total_cost_saved_usd: Total USD saved based on active token pricing structures.total_energy_saved_wh: Total estimated compute energy footprint saved.
🏁 Summary Verdict
Neuroweave is a high-speed, zero-cost reflex arc. Used as a human interactive assistant, it feels rigid and restrictive. But deployed as headless infrastructure inside automated agent loops, it acts as a tireless, zero-token basal ganglia—handling thousands of routine mechanical operations at machine speed while preserving cognitive tokens for real engineering challenges.
Support our open-source research: Support AIYoda on Ko-fi