@nxuss/lemma
v1.0.3
Published
Intelligent AI Gateway for IDEs & Agents — Semantic cache, Privacy Firewall, and Autonomous Cost-Optimization.
Maintainers
Readme
🧠 Lemma v1.0.3
__
/ / ___ ____ ___ ____ ___ ____ _
/ / / _ \/ __ `__ \/ __ `__ \/ __ `/
/ /___/ __/ / / / / / / / / / / /_/ /
/_____/\___/_/ /_/ /_/_/ /_/ /_/\__,_/ The Intelligent local-first AI Gateway — Privacy, Performance, and Static Code Intelligence for the Agentic Era.
Lemma is a high-performance orchestration layer that sits between your development environment and LLM providers. It transforms the way you build with AI by providing Shared Semantic Memory, Autonomous Cost Optimization, Privacy Guardrails, and a suite of 51 MCP tools — including zero-token static code intelligence that runs entirely on your machine with no LLM calls required.
💎 Free vs Pro
| Feature | 🆓 Free | 💎 Pro |
| :--- | :---: | :---: |
| AI Proxy (OpenAI/Anthropic/Gemini) | ✅ | ✅ |
| Exact-match cache | ✅ | ✅ |
| Context Squeezer (auto-compression) | ✅ | ✅ |
| Privacy Firewall (proxy layer) | ✅ | ✅ |
| Complexity Router | ✅ | ✅ |
| Dashboard | Basic stats | ✅ Full time-travel |
| Proxy requests/month | 300 | ✅ Unlimited |
| MCP Server (all 51 tools) | ❌ | ✅ |
| The Brain — Semantic Memory | ❌ | ✅ |
| Zero-Token Static Analysis | ❌ | ✅ |
| Cross-Project Telepathy | ❌ | ✅ |
| AutoPilot & Auto-Heal | ❌ | ✅ |
| depgraph — Dependency Graph | ❌ | ✅ |
| refactor — Codemod Engine | ❌ | ✅ |
The MCP is Pro. All 51 tools — The Brain, PreCrime predictor, AST Hologram, Entropy Score, Coupling Radar,
depgraph,refactor, and every optimization tool — require a Pro license. Activate withlemma activate <key>→ Get Pro
⚡ What's in the Pro MCP
🧠 Shared Semantic Memory — The Brain (Zero-Dependency)
Lemma maintains a persistent semantic cache index (TheBrainV2) using Okapi BM25 + Jaccard re-ranking and Bloom Filters that runs entirely on your local machine with NO external ML dependencies (no ChromaDB, no Ollama required). Every solution, bug fix, and architecture decision you work through gets stored and semantically indexed globally across all your projects. Future sessions can retrieve this knowledge in milliseconds (<10ms) — saving you thousands of tokens.
🛡️ Privacy Firewall (Semantic Scrubber)
Enterprise-Grade Privacy. Prevents API keys, credentials, and PII from ever leaving your machine. Applied automatically to every file read and workspace search via MCP.
🔮 PreCrime Static Analyzer — Zero Tokens
Minority Report for your code. Combines cyclomatic complexity, git churn history, and module coupling into a composite risk score per file. Predicts which files are most likely to produce a bug before you touch them — using only the TypeScript Compiler API and git log. No LLM. No Ollama. No tokens.
🕸️ Coupling Radar — Zero Tokens
Builds a full import/export dependency graph of your codebase using the TypeScript Compiler. Detects circular dependencies, god modules (imported by everything), dead islands (no importers), and fan-in/fan-out per module. Essential before any large refactor.
🧮 Entropy Score — Zero Tokens
Mathematical chaos score (0-100) per file using the TS Compiler API. Measures cyclomatic complexity, nesting depth, any ratio, and average function size. Tells you exactly where refactor debt is accumulating.
🗺️ AST Hologram — Zero Tokens
Scans the entire workspace and returns a dense JSON index of all exported symbols (classes, functions, interfaces, types, consts) with file paths and line numbers. Use this instead of reading individual files — saves up to 90% tokens when navigating large codebases.
📡 depgraph — Real-Time Dependency Graph (NEW in v0.9.3)
Architecture-aware blast radius analysis. Builds a real-time, bidirectional dependency graph for any file in the workspace using the TypeScript Compiler API — zero LLM calls, zero tokens. Shows exactly what a file imports, what imports it (reverse dependencies), and what symbols it exports.
📦 src/services/pantry.ts
├── importa:
│ ├── src/lib/utils/ingredient-parser.ts → parseIngredientString, normalizeUnit
│ └── src/db/prisma.ts → PrismaClient
├── es importado por:
│ ├── src/app/actions/generate-recipe.ts
│ └── src/components/PantryWidget.tsx
└── exporta:
├── applyRecipeDeductions
└── getPantryBalanceSupports --depth (1-5), --format text|mermaid|json, --reverse, --circular (cycle detection), and --external (include node_modules).
🔧 refactor — Declarative Codemod Engine (NEW in v0.9.3)
Multi-file refactoring with surgical precision. Rename any symbol across the entire workspace or move files updating all importers — using the TypeScript Compiler API for accurate AST-based reference detection. Zero LLM calls.
rename — Finds every reference to a symbol (via AST, not text search) and renames it everywhere:
# Preview first
lemma refactor --operation rename --from "applyRecipeDeductions" --to "deductPantryIngredients" \
--file src/services/pantry.ts --dryRun
# Apply with TypeScript verification
lemma refactor --operation rename --from "applyRecipeDeductions" --to "deductPantryIngredients" \
--file src/services/pantry.ts --tscCheckmove — Moves a file physically and rewires every import path in the workspace:
lemma refactor --operation move \
--from src/lib/validation/recipe.schema.ts \
--to src/lib/schemas/recipe.ts \
--tscCheckSupports --dryRun (unified diff preview), --tscCheck (post-refactor type verification), and --backup (.bak files).
🚦 Complexity Router
Intelligently evaluates each prompt and routes it to the most cost-effective model. Reserves premium models for complex reasoning, uses smaller models for simple tasks. Slashes your AI bill without sacrificing quality.
✂️ Context Squeezer & TurboMode
Dynamically squeezes outgoing code payloads, strips comments, collapses whitespace, and compacts JSON. Saves up to 90% on token consumption. Automatically injected via the lemma-turbomode system prompt on MCP handshake.
🛸 Autonomous Workspace Control
Exposes write_workspace_file, smart apply_workspace_patch (collision-safe search-and-replace), and run_workspace_command (with allowlist security) to any IDE via MCP. Any standard chat instantly becomes a fully-featured autonomous multi-file editor.
🩺 AutoPilot & Auto-Heal
Lemma's background file watcher detects TypeScript compilation errors on every save, parses the error, and calls the auto-heal agent to apply a fix — automatically. When Autopilot succeeds, the fix is stored in The Brain for future sessions.
🕵️ Silent Patch Watcher (NEW in v1.0.1)
Magia negra, no invasiva. Like Autopilot, but never touches your code. Lemma watches your project silently, detects TypeScript errors on save, generates fixes, and stores them as patches in .lemma/patches/. You review with lemma patches and apply with lemma apply <id>.
lemma watch ← starts silently watching src/
[you save a file with a bug]
📬 macOS notification ← "Lemma: TS2322 in route.ts:42"
lemma patches ← shows 1 pending fix
lemma apply ts2322-... ← applies the fix
npm run build ← ✅ passes🧬 get_symbol_surgical_context — Surgical Symbol Context (NEW in v1.0.0)
Saves up to 90% input tokens. Instead of reading complete dependency source files, this tool parses your workspace via TS Compiler AST and extracts ONLY the targeted symbol implementation along with the precise function/class signatures of all its direct workspace imports.
⚙️ surgical_ast_insert — AST Surgical Code Injector (NEW in v1.0.0)
Saves up to 95% output tokens. Removes the need for the LLM to output massive file diffs or rewrite entire files. The LLM only outputs the exact function snippet, and Lemma compiles it surgically into the class/scope AST at the specified anchor point.
🩹 local_semantic_autofix — Offline Self-Healing (NEW in v1.0.0)
Resolves compilation/runtime crashes in <15ms with 0 tokens. When your tests or compilers crash, Lemma queries the global error index in TheBrainV2. If a matching traceback fix is found in memory (solved in this or any other repo on your machine), it applies the resolution instantly.
💰 generate_executive_roi_report — Corporate ROI Ledger (NEW in v1.0.0)
Generates a complete executive Markdown/PDF-ready report of total direct API dollars saved, developer hours reclaimed from caching, security masking events, and scalability financial projections for engineering managers.
🌀 wormhole_squeeze — Reversible Code Compression (NEW in v1.0.0)
Compresses your source code using non-colliding mathematical unicode symbols (like ⨃, ⨂, ⨁) and temporary aliases to shrink file sizes by up to 70% while keeping it 100% reversible.
📐 smart_file_slice — Context Slicing (NEW in v1.0.3)
Reads only the relevant lines of a file around a keyword or query, avoiding sending the entire file to the LLM. Saves ~85% of input tokens.
🧪 test_oracle — Smart Test Failure Filter (NEW in v1.0.3)
Executes unit tests locally and returns ONLY the failing test cases with compressed stack traces, keeping successful test logs out of the prompt. Saves ~90% tokens.
📄 schema_extract — High-Level Type Extractor (NEW in v1.0.3)
Extracts TS interfaces, types, Zod schemas, or Prisma schemas via AST, stripping out all execution and implementation code. Saves ~80% tokens.
📜 changelog_auto — Zero-Token conventional changelogs (NEW in v1.0.3)
Generates a conventional commit changelog directly from git history logs with 0 LLM queries.
🪚 spec_to_stub — Spec Mock Stub Creator (NEW in v1.0.3)
Parses interfaces and types to output a mock stub template object configuration using pure AST.
📋 env_snapshot — Env Dependency Capture (NEW in v1.0.3)
Captures node/npm versions, package.json dependencies, and present .env keys (hiding private values/credentials) for instant environment onboarding.
🧭 migration_tracer — Prisma Migration Analyst (NEW in v1.0.3)
Traces recent schema modifications (creates, alters, drops) from local Prisma migration files without reading the full SQL code.
🩹 multi_file_patch — Multi-File Search-and-Replace (NEW in v1.0.3) ⭐
Applies search-and-replace patches to multiple files in a single call. Eliminates round-trips for multi-file refactoring.
📁 file_intent_index — Codebase Categorizer (NEW in v1.0.3)
Automatically groups workspace files by domain intent (auth, routing, config, schemas) for lightning fast navigation.
🧠 cognitive_map — Auto-Cognitive Knowledge Graph (NEW in v1.0.3)
A persistent, auto-updating structural knowledge graph representing codebase domains, patterns, decisions, and known bugs at ~/.lemma-cache/cog_map.json.
🔍 semantic_grep — BM25 Concept Search (NEW in v1.0.3)
Token relevance concept searching across your codebase, allowing natural language queries instead of strict substring matches.
📦 imports_skeleton_resolver — Import Signature Mapper (NEW in v1.0.3)
Scans imports inside a file and retrieves exported TypeScript signatures from local dependencies in a unified reference sheet. Saves ~85% reading tokens.
🎨 ast_flow_visualizer — Flowchart Generator (NEW in v1.0.3)
Compiles any TS function's control flow statements (loops, ifs, try-catches) into an interactive visual Mermaid diagram rendered directly in markdown.
🚀 Quick Start (Zero Config)
# Install globally
npm install -g @nxuss/lemma
# Initialize (auto-configures local DB and MCP for your IDEs)
lemma init
# Start the gateway + dashboard
lemma start🛠️ CLI Reference
| Command | Action |
| :--- | :--- |
| lemma init | Bootstraps config and auto-configures MCP for OpenCode, Claude Desktop, Cursor, Windsurf, Kiro, VS Code. |
| lemma start | Launches proxy, cache engine, and dashboard at http://localhost:8081. |
| lemma stop | Gracefully shuts down the background proxy. |
| lemma status | Health of all modules and active connections. |
| lemma stats | Real-time token and cost savings metrics. |
| lemma mcp | Starts the stdin/stdout MCP server for IDE integration. |
| lemma heal | Auto-diagnose and repair the latest server crash from live context logs. |
| lemma autopilot | Toggle autonomous background watcher mode (auto-applies fixes). |
| lemma watch | NEW Silent background watcher — saves patches without touching code. |
| lemma patches | NEW List available patches (--all, --pending). |
| lemma apply <id> | NEW Apply a pending fix patch. |
| lemma discard <id> | NEW Discard a pending fix patch. |
Customizing via lemma.config.json
{
"system": {
"clipboardWatcher": { "disabled": false }
},
"mcp": {
"allowedCommandPrefixes": ["npm", "git", "tsc", "your-custom-tool"]
}
}🔌 MCP Integration
Add Lemma to any MCP-compatible IDE in seconds:
OpenCode (Terminal AI)
Just run lemma init. Lemma automatically registers its MCP server in your ~/.opencode.json and injects its autonomous rules so OpenCode works with zero configuration.
Cursor / Windsurf / Kiro / Antigravity
- Go to Settings → MCP
- Add new server: Command =
lemma mcp
Claude Desktop
{
"mcpServers": {
"lemma": {
"command": "npx",
"args": ["-y", "@nxuss/lemma", "mcp"]
}
}
}Once connected, your IDE gains access to all 38 MCP tools and Lemma auto-injects the TurboMode system prompt on handshake.
🛠️ MCP Tools Reference (v0.9.3 — 38 Tools)
🗂️ Workspace Tools
| Tool | Description |
| :--- | :--- |
| read_workspace_file | Read a file with automatic token compression and privacy scrubbing. |
| write_workspace_file | Write content to a file, creating parent directories as needed. |
| apply_workspace_patch | Smart search-and-replace patch — safe against duplicate matches. Returns clear errors if search block is ambiguous. |
| list_workspace_dir | Recursively list the project structure up to a configurable depth. |
| search_workspace | Fast text search (grep) across all project files with optional extension filter. Results are privacy-scrubbed. |
| run_workspace_command | Execute bash commands in the workspace root. Secured by an allowlist. 15s timeout. |
🔬 Code Intelligence Tools
| Tool | Description |
| :--- | :--- |
| get_ast_hologram | Holographic AST Map. Scans the workspace via TS Compiler API and returns a dense JSON index of all exported symbols with file paths and line numbers. Use instead of reading individual files — 90% token savings. Zero LLM calls. |
| validate_patch_sandbox | Pre-flight Validator. Validates a proposed patch in an isolated sandbox before applying it. Runs tsc --noEmit and bracket-balance checks. Returns SAFE TO APPLY or DO NOT APPLY verdict. |
| diff_only | Compute a compact line-by-line diff between the last known state of a file and its current content. Session-scoped state tracking. |
🧠 Brain & Memory Tools
| Tool | Description |
| :--- | :--- |
| search_memory | Semantic search across The Brain — retrieves past solutions and context from all your projects globally. |
| store_memory | Persist a technical solution, bug fix, or architecture decision into The Brain for future sessions. |
| query_hybrid_consensus | Hybrid Consensus Engine. Checks The Brain at configurable threshold (default 80%). HIT → instant answer, zero cloud tokens. MISS → proceed with cloud and cache afterward. |
| get_telepathic_hints | Proactive Telepathy. Given the active file path, surfaces the top N most relevant past solutions from The Brain — no query needed. |
⚙️ Optimization & Privacy Tools
| Tool | Description |
| :--- | :--- |
| scrub_privacy | Mask PII, API keys, and secrets from any text block using the Privacy Firewall. |
| squeeze_prompt | Compress code blocks and boilerplate in any prompt. Up to 80% token reduction. |
| turbosqueeze | Extreme compression. Strips comments, imports, whitespace, and compacts JSON. Returns reduction stats. |
| compress_context | Summarizes old conversation turns, keeps last N turns intact. Falls back to truncation if no Ollama. |
| prune_conversation_history | Intelligently decimate conversation history while preserving critical recent context. |
| summarize_long_text | Summarize lengthy content via Ollama to save context window space. Falls back gracefully. |
| smarter_cache | Predictive cache. Queries The Brain at 75% threshold before any reasoning. Auto-suggests store_memory on MISS. |
| token_budget | Optimization dashboard: multiplier, total tokens saved, active strategies, and recommendations. |
| get_routing_advice | Analyze a prompt and get optimal model recommendation from the Complexity Router. |
| get_project_onboarding | Download a one-shot architectural mental model of the current codebase. |
| auto_heal | Diagnose and auto-heal the latest crash from Lemma's live context logs. |
| batch_tool_calls | Execute multiple tool calls in parallel via Promise.all. High-throughput operations in a single MCP round-trip. |
🔮 Zero-Token Static Intelligence Tools
All tools in this section use zero LLM tokens, zero Ollama, zero cloud. Pure local computation via TypeScript Compiler API, git, and math.
| Tool | Description |
| :--- | :--- |
| entropy_score | Mathematical chaos score (0-100) per file. Measures cyclomatic complexity, max nesting depth, any type ratio, and average function size. Identifies which files need refactoring before you touch them. |
| coupling_radar | Dependency graph analysis. Detects circular imports, god modules (high fan-in), dead islands (no importers), and fan-in/fan-out per module. Essential before large refactors. |
| pattern_fossil | Zombie code detector. Finds patterns that were replaced in most of the codebase but survive in old files: var vs const/let, callbacks vs async/await, require() vs import, : any vs generics. Reports adoption percentage. |
| git_heatmap_risk | Git churn analysis. Calculates change frequency per file and co-edit pairs (files that always change together = hidden coupling). Returns a risk score for each file based on historical git behavior. |
| precrime_static | Minority Report predictor. Combines entropy_score (40%) + git_heatmap_risk (40%) + coupling_radar (20%) into a composite PreCrime Score per file. Ranks files by bug probability with per-factor breakdown and names the riskiest functions. |
| semantic_dedup_guard | Brain dedup firewall. Before calling store_memory, pass content through here. If similarity ≥ 92% → rejects as duplicate. If 75–91% → warns and shows the similar entry. Keeps The Brain lean and dense. |
| dead_export_necromancer | Dead code auditor. Maps every export in the workspace against every import. Symbols exported but never imported anywhere = zombie code inflating your context. Reports dead exports by file with estimated token waste. |
🏗️ Architecture & Refactoring Tools (NEW in v0.9.3)
Architecture-aware tools that combine dependency analysis with surgical code transformation. Zero LLM calls.
| Tool | Description |
| :--- | :--- |
| depgraph | Real-time dependency graph. Builds a bidirectional import/export map for any file. Shows what a file imports, what imports it (reverse deps with --reverse), and what symbols it exports. Supports --depth 1-5, --format text\|mermaid\|json, --circular (cycle detection), and --external (include node_modules). Use before any refactor to measure blast radius. |
| refactor | Declarative codemod engine. rename renames a symbol across all files using AST-based reference detection (no false positives from string search). move relocates a file and rewires every import path in the workspace. Both support --dryRun (unified diff preview), --tscCheck (post-apply type verification), and --backup (.bak files). |
🔍 PR Review Agent Tools
| Tool | Description |
| :--- | :--- |
| review_diff | Analyze a raw diff for bugs, security issues, and best practices before committing. |
| review_pr | Full PR review against a Git platform (GitHub, Azure DevOps, GitLab). Runs all 4 analyzers (Static, Security, Regression, Quality) and stores results in The Brain. |
| pr_status | Query the last review status and report for a given PR number and platform. |
| generate_pr_workflow | Generate a CI/CD workflow YAML (GitHub Actions or Azure Pipelines) that runs lemma pr-review as a step. |
⚡ TurboMode Auto-Injection
When connected via lemma mcp, Lemma auto-injects 7 rules into the agent's system prompt on handshake:
turbosqueezebefore writing large code blockssmarter_cachebefore any reasoningstore_memoryafter every resolved solutionget_ast_hologrambefore reading filesbatch_tool_callsfor parallel operationssemantic_dedup_guardbefore everystore_memory- No fluff, no chit-chat — maximum density
📡 MCP Resources
| Resource URI | Description |
| :--- | :--- |
| lemma://runtime/context | Live application errors, stack traces, and runtime state. Subscribable — IDE notified instantly on crash. |
| lemma://stats/usage | Current token savings, cost report, and cache hit metrics in JSON. |
| lemma://project/context | Active project metadata, tech stack, memory count, and token savings. |
| lemma://project/onboarding | Dynamic project architecture guide compiled on demand. |
| lemma://multiverse/timeline | Chronological AST diff timeline of recent code snapshots. |
🔒 Security
Network Binding
By default, Lemma binds only to 127.0.0.1 (localhost). Not network-accessible unless explicitly configured:
LEMMA_BIND_HOST=0.0.0.0
AUTH_ENABLED=true
AUTH_REQUIRE_API_KEY=true
AUTH_ALLOWED_ORIGINS=https://yourdomain.comMCP Command Allowlist
run_workspace_command only executes commands from an allowlist. Default safe prefixes: npm, npx, git, tsc, node, jest, eslint, ls, grep, and more.
Extend for your project in lemma.config.json:
{
"mcp": {
"allowedCommandPrefixes": ["your-tool", "another-cmd"]
}
}See .env.security.example for all security-related environment variables.
🦜 SDK Integrations
LangChain
import { LemmaLangChainProvider } from '@nxuss/lemma/langchain';
const model = new LemmaLangChainProvider({
apiKey: process.env.OPENAI_API_KEY,
});CrewAI
import { LemmaCrewAIProvider } from '@nxuss/lemma/crewai';
const crew = new LemmaCrewAIProvider({ agents: [...] });🔄 Using as a Proxy
Point any OpenAI-compatible tool to Lemma's local proxy for transparent caching and privacy:
- Cursor:
Settings > Models > OpenAI API > Override Base URL→http://localhost:8081/v1 - VS Code (Continue): Set
apiBasetohttp://localhost:8081/v1 - Custom apps: Replace
https://api.openai.com/v1withhttp://localhost:8081/v1
MIT © Nxus Studio | Upgrade to Lemma Pro
