{"slug": "locus-deterministic-ast-safety-firewall-for-ai-agents-in-pure-rust-0-05ms", "title": "Locus: Deterministic AST safety firewall for AI agents in pure Rust (<0.05ms)", "summary": "Locus Engine, a pure Rust AST safety firewall for AI coding agents, claims deterministic invariant checks in under 0.05 ms, with benchmarks showing 9.04 µs average latency for its 6-pass AstGuard verification. The tool, which supports MCP for integration with Claude Code, Cursor, Copilot, and Devin, also extracts cross-file symbol graphs that reduce LLM context token usage by up to 80%. It detects issues like async mutex deadlocks and ReDoS patterns, positioning itself against traditional linters and cloud-based AI guardrails with zero external dependencies and 100% memory safety.", "body_md": "Deterministic AST Safety Guard, Polyglot Semantic Symbol Graph, Surgical Byte-Span Patching, and Zero-Dependency Model Context Protocol (MCP) Server in Pure Rust.\n\nModern AI code generation agents (Claude Code, Cursor, Copilot, Devin) and automated developer pipelines face two systemic engineering bottlenecks:\n\n**Probabilistic Syntax & Concurrency Regressions:** AI agents frequently hallucinate unclosed delimiters, panic-inducing`.unwrap()`\n\ntraps, async-mutex thread deadlocks, catastrophic polynomial regular expressions (ReDoS), and unbounded array indexing.**Context Window Inflation:** Repeatedly feeding entire source code files into LLM context windows wastes up to**80% of token budgets** on repetitive function bodies rather than high-level interface contracts.\n\n** locus-engine** solves both challenges as a\n\n**standalone, zero-bloat, high-performance systems engine** written in 100% safe Rust. It enforces deterministic, non-negotiable safety invariants in\n\n**microsecond time (**, extracts cross-file symbol graphs with minimal context footprints, and communicates natively with modern AI IDEs via the\n\n`9.04 µs`\n\n)**Model Context Protocol (MCP)**.\n\n``` bash\n$ locus check src/async_task.rs\n\n+-------------------------------------------------------------+\n|                  LOCUS AST GUARD VERIFICATION               |\n+-------------------------------------------------------------+\n Target File: src/async_task.rs\n Verified Latency: 0.0194 ms\n Status: [FAIL] Invariant Violation Detected\n Violation Kind: ASYNC_MUTEX_DEADLOCK\n Violation Detail: std::sync::Mutex used in async context with .await — use tokio::sync::Mutex instead.\n+-------------------------------------------------------------+\n\n$ locus graph src/\n\n+-------------------------------------------------------------+\n|                   LOCUS SYMBOL GRAPH INDEX                  |\n+-------------------------------------------------------------+\n Indexed Root: src/\n Total Indexed Files: 8\n Extracted AST Symbols: 28\n Token Savings via AST Skeleton: 74.8%\n Indexing Latency: 4.82 ms\n+-------------------------------------------------------------+\n```\n\nBenchmarked under optimized release profile (`opt-level = 3`\n\n, `lto = thin`\n\n, `codegen-units = 1`\n\n):\n\n| Subsystem / Operation | Benchmark Cycles | Total Elapsed | Average Latency | Status |\n|---|---|---|---|---|\n🛡️ AstGuard 6-Pass Verification |\n1,000 iterations | `9.036 ms` |\n(0.009 ms / check)`9.04 µs` |\n100% PASS |\n⚡ AstContextCache (FIPS 180-4 SHA-256) |\n1,000 inserts/lookups | `18.675 ms` |\n/ digest + LRU`18.68 µs` |\n100% PASS |\n🔌 MCP Stdio JSON-RPC Dispatch |\n1,000 round-trips | `42.316 ms` |\n/ dispatch`42.32 µs` |\n100% PASS |\n✂️ AstDiffEngine (Patch & Skeleton) |\n500 cycles | `28.063 ms` |\n/ operation`56.13 µs` |\n100% PASS |\n🧠 SymbolGraph Polyglot Indexer |\n600 files (1,600 symbols) | `16.294 ms` |\n/ file`27.15 µs` |\n100% PASS |\n\n| Capability | `locus-engine` |\nTraditional Linters (ESLint, Clippy) | Cloud AI Guardrails |\n|---|---|---|---|\nVerification Latency |\n`9 µs – 0.05 ms` (Nanosecond-scale) |\n250 – 1,500 ms (Process Spawns) | 500 – 2,500 ms (Network Round-Trip) |\nExecution Architecture |\nIn-Memory Pure Rust Kernel |\nNode.js / Python Runtime | Remote HTTP Cloud API |\nContext Token Savings |\n`> 50% - 80%` (AST Skeleton) |\n0% (Full Files) | 0% (Full Files) |\nMCP Protocol Support |\nBuilt-In JSON-RPC 2.0 over Stdio |\nRequires Custom Wrappers | Proprietary APIs |\nMemory Safety |\n100% Safe Rust (0 Unsafe Blocks) |\nVaries (C/C++/Node) | Undefined |\nExternal Dependencies |\nZero Crypto/Runtime Bloat |\nHeavy `node_modules` / Python env |\nCloud Connection & API Keys |\nDeterministic Guarantee |\n100% Formal Invariant Rejection |\nHeuristic Warnings | Probabilistic LLM Re-evaluation |\n\n```\nflowchart TD\n    subgraph Input [\"Incoming Code / AI Agent Patch\"]\n        RawCode[\"Raw Code Snippet / File\"]\n    end\n\n    subgraph AstGuardPipeline [\"🛡️ AstGuard: 6-Pass Deterministic Firewall (<0.05ms)\"]\n        P0[\"Pass 0: Delimiter Balance (Dijkstra)\"]\n        P1[\"Pass 1: Async Mutex Across Await\"]\n        P2[\"Pass 2: Division-by-Zero Guard\"]\n        P3[\"Pass 3: Array Bounds Overflow\"]\n        P4[\"Pass 4: Unsafe Unwrap / Expect Trap\"]\n        P5[\"Pass 5: ReDoS Catastrophic Backtracking\"]\n        P6[\"Pass 6: TS/JS Deep Null Dereference\"]\n    end\n\n    subgraph Resolution [\"Resolution & Verification Verdict\"]\n        VerdictSafe{\"All Passes Passed?\"}\n        Reject[\"❌ Immediate Rejection & Counterexample\"]\n        Approve[\"✅ Verified Safe AST\"]\n    end\n\n    subgraph ContextEngine [\"✂️ AstDiffEngine & 🧠 SymbolGraph\"]\n        Cache[\"⚡ AstContextCache (FIPS 180-4 SHA-256)\"]\n        Skeleton[\"Context Compression (>50-80% Token Savings)\"]\n        Patch[\"Surgical Byte-Span Node Replacement\"]\n    end\n\n    subgraph Interfaces [\"Exposed Runtime Interfaces\"]\n        CLI[\"💻 CLI Binary: locus check / graph / patch\"]\n        MCP[\"🔌 Model Context Protocol Server: locus mcp\"]\n        LIB[\"📦 Rust Library Crate: locus_engine\"]\n    end\n\n    RawCode --> P0 --> P1 --> P2 --> P3 --> P4 --> P5 --> P6 --> VerdictSafe\n    VerdictSafe -->|No| Reject\n    VerdictSafe -->|Yes| Approve\n    Approve --> Cache --> Skeleton --> Patch\n    Patch --> Interfaces\nphp\ngraph LR\n    A[AstGuard Invariant Passes] --> B[1. Delimiter Balance: Dijkstra stack scan]\n    A --> C[2. Concurrency: std::sync::Mutex across .await points]\n    A --> D[3. Arithmetic: Unguarded division by variable]\n    A --> E[4. Bounds: Array index without length checks]\n    A --> F[5. Panics: Unguarded .unwrap() and .expect()]\n    A --> G[6. ReDoS: Exponential nested regex quantifiers]\n```\n\n-\n**Delimiter Balance (Dijkstra Algorithm):** Performs a linear single-pass stack scan validating matching closure for`{}`\n\n`[]`\n\n`()`\n\nacross raw byte streams while safely ignoring string literals and escapes. -\n**Async Mutex Concurrency Trap:** Prevents blocking`std::sync::Mutex`\n\nlocks across asynchronous`.await`\n\nsuspension points to eliminate thread pool exhaustion and deadlocks. -\n**Division-by-Zero Protection:** Proves the denominator is non-zero ($y \\neq 0$ ) before permitting arithmetic evaluation. -\n**Array Bounds Protection:** Ensures array and slice indexing (`arr[i]`\n\n) is preceded by length assertions or safe accessors (`.get()`\n\n). -\n**Unsafe Unwrap Guard:** Eliminates panic-inducing direct`.unwrap()`\n\nor`.expect()`\n\ncalls lacking prior safety checks (`is_some()`\n\n,`is_ok()`\n\n, or`if let`\n\n). -\n**ReDoS Catastrophic Backtracking Guard:** Identifies polynomial and exponential nested quantifiers (such as`(a+)+$`\n\n) that freeze CPU execution threads.\n\n`locus-engine`\n\nships with a built-in, zero-dependency MCP server running over stdio (JSON-RPC 2.0). It connects directly to **Claude Code**, **Claude Desktop**, **Cursor**, **Windsurf**, and **VS Code**.\n\nAdd `locus`\n\nto your `claude_desktop_config.json`\n\nor Cursor MCP settings:\n\n```\n{\n  \"mcpServers\": {\n    \"locus\": {\n      \"command\": \"locus\",\n      \"args\": [\"mcp\"]\n    }\n  }\n}\n```\n\n| MCP Tool Name | Arguments | Capabilities & Output |\n|---|---|---|\n`check_safety` |\n`{\"code\": \"string\", \"path\": \"string\"}` |\nExecutes 6-pass AST verification; returns passed/failed report with exact violation byte span. |\n`skeletonize` |\n`{\"code\": \"string\", \"language\": \"rust|typescript|python\"}` |\nStrips implementation bodies while preserving all signatures, saving >50-80% LLM context tokens. |\n`patch_symbol` |\n`{\"source\": \"string\", \"symbol\": \"string\", \"new_code\": \"string\", \"language\": \"string\"}` |\nPerforms surgical byte-offset node replacement of a target function/struct without rewriting unchanged code. |\n`index_graph` |\n`{\"path\": \"string\"}` |\nRecursively indexes project directory, extracts definitions, and maps cross-file dependency edges. |\n\n```\ncurl -fsSL https://raw.githubusercontent.com/ahmadshady747-create/LOCUS/main/scripts/install.sh | bash\nirm https://raw.githubusercontent.com/ahmadshady747-create/LOCUS/main/scripts/install.ps1 | iex\ncargo install locus-engine\n# 1. Deterministic Safety Verification (<0.05ms)\nlocus check src/lib.rs\n\n# 2. Index Workspace Symbol Graph & Measure Token Savings\nlocus graph src/\n\n# 3. Surgical Symbol Patching\nlocus patch src/models.rs --symbol User --with \"pub struct User { pub id: u64 }\"\n\n# 4. Start Model Context Protocol (MCP) stdio Server\nlocus mcp\n```\n\nAdd `locus-engine`\n\nto your `Cargo.toml`\n\n:\n\n```\n[dependencies]\nlocus-engine = \"0.1.0\"\nuse locus_engine::{AstGuard, AstDiffEngine, SymbolGraph, AstContextCache, Language};\n\nfn main() {\n    let code = \"pub fn safe_calc(a: f64, b: f64) -> f64 { if b != 0.0 { a / b } else { 0.0 } }\";\n\n    // 1. Instant Invariant Safety Verification (9µs)\n    let report = AstGuard::verify(code);\n    assert!(report.passed);\n\n    // 2. Surgical Context Compression (>70% Token Savings)\n    let skeleton = AstDiffEngine::skeletonize(code, Language::Rust);\n    println!(\"Compressed Skeleton:\\n{}\", skeleton);\n\n    // 3. Fast In-Memory FIPS 180-4 SHA-256 LRU Cache\n    let cache = AstContextCache::new(1024);\n    let hash = cache.insert(code, skeleton, 1);\n    assert_eq!(hash.len(), 64);\n}\nd:\\LOCUS\\\n├── Cargo.toml                  # Single-crate package manifest (locus bin + locus_engine lib)\n├── LICENSE                     # Business Source License 1.1 with explicit As-Is disclaimer\n├── README.md                   # Comprehensive technical documentation & benchmarks\n├── SPEC.md                     # Detailed formal specification of core algorithms\n├── .gitattributes              # GitHub Linguist classification (100% Rust project)\n├── scripts/\n│   ├── install.sh              # One-line curl installer for Linux & macOS\n│   └── install.ps1             # One-line PowerShell installer for Windows\n├── tests/\n│   └── benchmarks.rs           # High-precision benchmark & stress test suite\n└── src/\n    ├── lib.rs                  # Public library exports\n    ├── main.rs                 # CLI entrypoint (check, graph, patch, mcp commands)\n    ├── types.rs                # Core models (SymbolNode, SymbolEdge, VerificationReport)\n    ├── guard.rs                # 6-pass deterministic AST safety invariants engine\n    ├── cache.rs                # Pure FIPS 180-4 SHA-256 LRU cache with monotonic indexing\n    ├── graph.rs                # Polyglot symbol graph & dependency resolver (Rust, TS, Python)\n    ├── diff.rs                 # Surgical byte-span AST patching and skeletonizer\n    └── mcp.rs                  # Zero-dependency stdio Model Context Protocol (MCP) server\n```\n\n`locus-engine`\n\nis published under the [Business Source License 1.1 (BSL 1.1)](/ahmadshady747-create/LOCUS/blob/main/LICENSE):\n\n| License Tier | Target Audience / Scope | Pricing |\n|---|---|---|\nFree Tier |\nIndividuals, students, open-source projects, and teams with < 5 developers. |\n$0 (Free) |\nInternal Commercial Seat |\nInternal usage & CI/CD within organizations with 5+ developers (Internal use only; no re-selling/SaaS). |\n$150 USD / seat / year |\nCommercial SaaS & Cloud OEM |\nEmbedding, hosting, or offering locus-engine as a commercial SaaS, cloud API, or OEM product. | $10,000 USD / year |\n\nWarranty & Support Disclaimer (As-Is / Self-Service):The software is provided \"AS IS\" on a self-service basis without warranties of any kind. Dedicated technical support, custom SLA guarantees, and enterprise integration assistance are not included unless negotiated under a separate custom agreement.\n\nFor license activation and commercial contracts: Contact the author below or email `licensing@locus.dev`\n\n.\n\nArchitected & built independently by **Ahmed Shadi** (Libya 🇱🇾).\n\n- 📘\n**Facebook:**[Ahmed Shadi Profile](https://www.facebook.com/share/1DZibmYSrx/) - 🐙\n**GitHub:**[@ahmadshady747-create](https://github.com/ahmadshady747-create) - 📧\n**Direct Inquiries:** Via GitHub Issues & Discussions", "url": "https://wpnews.pro/news/locus-deterministic-ast-safety-firewall-for-ai-agents-in-pure-rust-0-05ms", "canonical_source": "https://github.com/ahmadshady747-create/LOCUS", "published_at": "2026-08-21 12:24:23+00:00", "updated_at": "2026-08-21 12:44:22.632539+00:00", "lang": "en", "topics": ["ai-safety", "ai-tools", "developer-tools", "ai-agents", "ai-infrastructure"], "entities": ["Locus Engine", "Claude Code", "Cursor", "Copilot", "Devin", "MCP", "AstGuard", "SymbolGraph"], "alternates": {"html": "https://wpnews.pro/news/locus-deterministic-ast-safety-firewall-for-ai-agents-in-pure-rust-0-05ms", "markdown": "https://wpnews.pro/news/locus-deterministic-ast-safety-firewall-for-ai-agents-in-pure-rust-0-05ms.md", "text": "https://wpnews.pro/news/locus-deterministic-ast-safety-firewall-for-ai-agents-in-pure-rust-0-05ms.txt", "jsonld": "https://wpnews.pro/news/locus-deterministic-ast-safety-firewall-for-ai-agents-in-pure-rust-0-05ms.jsonld"}}