The Deterministic Intelligence Substrate for AI Coding Assistants
Modern Large Language Models fail on enterprise codebases not because of reasoning limits, but because of context starvation, token exhaustion, and architectural blindness. PolyTuring provides the deterministic infrastructure layer: Omni-Graph (Polyglot AST & Louvain/Leiden Galaxy Subsystems), Session Explorer (Autonomous Trajectory Observability & Memory Recovery), and the Living Documentation Engine.
The Autonomous Agentic Platform Manifesto
The software industry has entered the era of autonomous pair-programming. However, modern frontier models (Claude 3.7 Sonnet, GPT-4o, Gemini 2.0 Flash) face fundamental physical limits when dropped into enterprise repositories. PolyTuring was engineered to bridge the chasm between raw LLM reasoning and real-world software architecture.
The Context Window Crisis & The Myth of Raw Grep
When autonomous coding agents are equipped only with primitive filesystem tools (cat, grep, find), three catastrophic failure modes inevitably emerge:
🔥 Context Window Saturation
Dumping 1,500-line source files into LLM prompts burns 80%+ of model attention on boilerplate, triggering early context window truncation, memory loss, and steep API latency.
🌫️ The "Blind Grep" Hallucination Trap
Simple keyword searches lack structural semantic awareness. They cannot distinguish a symbol definition from a comment, an import statement, or an unrelated variable, causing agents to patch the wrong symbols.
💥 Silent Cross-Boundary Blast Radii
When an agent refactors an interface or method signature without knowing all foreign callers across other packages, it causes cascading compilation failures and invisible downstream regressions.
The PolyTuring Triad
To transform stochastic coding assistants into deterministic software engineers, PolyTuring provides three foundational pillars:
1. Omni-Graph (Rust)
The AST Nervous System. 100% local, high-throughput multi-language parser and vector graph engine. Clusters codebases into Louvain/Leiden Galaxy Subsystems, enforces blast-radius contracts, and delivers <1,500 token condensed call graphs.
2. Session Explorer (Go + Bun)
The Trajectory Observability Cockpit. Zero-dependency standalone binary providing instant agent memory recovery (/most-recent-wip), conversational step replay, and an in-browser code viewer with 1:1 gutter alignment and in-page find.
3. Living Documentation Engine
The Architectural Contract. Interactive liquid-glass documentation portal with automated diagram rendering, KaTeX mathematical notation, real-time token simulators, and zero-drift verification gates.
Built Antigravity-First — Architected for the Entire Ecosystem
- Deep integration with the Antigravity CLI (
agy) and Antigravity IDE workflow. - Direct telemetry parsing for
.gemini/antigravity-cli/brain/trajectory logs. - Lifecycle pre-tool interception hooks (
hook_pre_tool.sh) enforcing AST recon before source code reads.
Extensibility by Design: While Antigravity is the primary native substrate today, both Omni-Graph and Session Explorer expose standardized REST, SSE, and Model Context Protocol (MCP) tool interfaces. The adapter architecture is specifically designed to plug directly into GitHub Copilot, Claude Code, and Cursor without modifying core engine binaries.
Omni-Graph: 100% Local Semantic Knowledge Hub
Omni-Graph is a zero-telemetry, multi-container semantic graph engine that models software repositories as rich Abstract Syntax Tree (AST) graphs augmented with dense 384-dimensional vector embeddings. It solves code navigation, blast-radius analysis, and agent context starvation entirely on local hardware.
The 60-Second Mental Model: Why Does Omni-Graph Exist?
Imagine hiring a brilliant senior software engineer, but forcing them to read your entire 100,000-line codebase from top to bottom every single time you ask: "Where is payment processing handled?". They would waste 30 minutes reading, blow thousands of dollars in billing fees, and lose their train of thought due to cognitive exhaustion.
- Runs blind
greporfindacross the repository. - Dumps 10,000 lines of noise, minified assets, and test logs.
- Burns 40,000+ LLM tokens per simple question.
- Blows past model context limits, triggering code hallucinations.
- Pre-indexes exact syntax trees and caller relationships locally.
- Pinpoints symbol declarations, signatures, and callers in 5ms.
- Guarantees strict token budget: ≤ 1,500 tokens.
- Agent gets precise context instantly and writes working code.
4-Tier Container Architecture
Omni-Graph runs on an isolated Docker network (omni-net) coordinating four decoupled microservices:
Galaxy Subsystems & Louvain / Leiden Modularity Clustering
Software codebases are not flat hierarchies of directories. In reality, modern applications are scale-free, directed multi-graphs of functions, types, interfaces, and traits linked by call invocations, type references, and implementations. When an autonomous coding agent attempts to modify a codebase without architectural clustering, it suffers from context blindness: it cannot distinguish tightly-coupled internal modules from loose external boundaries.
Omni-Graph solves this by partitioning the entire AST graph into self-contained, cohesive architectural clusters called Galaxy Subsystems using a dual-phase Louvain and Leiden community detection engine.
$$Q = \frac{1}{2m} \sum_{i,j} \left[ A_{ij} - \gamma \frac{k_i k_j}{2m} \right] \delta(c_i, c_j)$$
Parameters & Invariants:
- $A_{ij}$: Weighted adjacency matrix representing architectural affinity between symbols $i$ and $j$.
- $k_i = \sum_j A_{ij}$: Total degree (structural connectivity) of symbol node $i$.
- $m = \frac{1}{2} \sum_{ij} A_{ij}$: Total edge weight across the entire repository graph.
- $\gamma$: Resolution parameter governing community scale ($\gamma = 1.0$ standard, calibrated to prevent micro-cluster fragmentation).
- $\delta(c_i, c_j)$: Kronecker delta ($\delta = 1$ if symbols $i$ and $j$ belong to the same Galaxy $c$, else $0$).
⚖️ Edge-Weighted Semantic Affinity
Not all code links carry equal architectural weight. Omni-Graph applies strict domain weights: IMPLEMENTS ($w = 3.0$), CALLS ($w = 2.0$), TYPE_REF ($w = 1.5$), and IMPORTS ($w = 1.0$).
🛡️ Louvain vs. Leiden Resolution
While standard Louvain greedily aggregates nodes, it can trap symbols in disconnected sub-communities. Omni-Graph adopts the Leiden refinement step, guaranteeing that every discovered galaxy is internally well-connected.
⚡ Two-Phase Dynamic Re-Clustering
Phase 1 (Instant Inheritance): File edits preserve existing galaxy assignments in SurrealDB via MERGE.
Phase 2 (Quiescent LPA): After 3.5s of edit silence, seed-preserving Label Propagation updates macro boundaries with zero ID thrashing.
Robert C. Martin Coupling Metrics & Dynamic Blast Radius Contracts
Once Galaxy Subsystems are clustered, Omni-Graph analyzes cross-boundary dependency vectors using Robert C. Martin's package metric formulations. This allows agents to quantify risk before writing a single line of refactored code:
📥 Afferent Coupling ($C_a$)
The number of external symbols outside this galaxy that depend upon symbols inside this galaxy. Measures incoming responsibility.
📤 Efferent Coupling ($C_e$)
The number of external symbols that symbols inside this galaxy depend upon. Measures outgoing structural dependency.
📐 Instability Metric ($I$)
Calculates resistance to change: $$I = \frac{C_e}{C_a + C_e} \quad (0 \le I \le 1)$$ $I=0$ indicates maximum stability (hard to change); $I=1$ indicates maximum volatility (easy to change).
| Architectural Role | Instability Threshold | Subsystem Characteristics | Agent Modification Strategy |
|---|---|---|---|
Core Foundation |
$I \le 0.25$ | Heavy incoming dependencies ($C_a \gg C_e$), shared domain types, zero external knowledge. | CRITICAL RISK: Wide blast radius. Agent must preserve backward-compatible signatures. |
Domain Service |
$0.25 < I \le 0.65$ | Balanced business logic, moderate internal abstractions with external service calls. | MODERATE RISK: Agent must verify intra-galaxy and direct caller contracts. |
Orchestrator / Leaf |
$I > 0.65$ | High outgoing dependencies ($C_e \gg C_a$), API controllers, CLI command routers, leaves. | LOW RISK: Contained blast radius. Agent can safely refactor implementation details. |
GET /api/galaxy/boundary?symbol=X• Containment Status:
🛡️ Contained Internal (all callers reside in same galaxy), ⚠️ Boundary Crossing (foreign callers detected), or 🔌 Isolated (leaf / entrypoint).• Caller Provenance: Exact line numbers, files, and galaxy IDs of every external caller.
• Agentic Advice: Concrete heuristics (e.g., "Symbol is called by 14 external callers in galaxy 'api_gateway'. Do NOT alter parameters without default fallbacks.").
Ephemeral Branch Fabric (EBF) & Git Worktrees
Coding agents frequently branch or create Git worktrees to isolate experimental code and execute parallel strategies. Traditional code indexing tools either re-index the entire multi-gigabyte repository from scratch or fail completely. Omni-Graph solves this with the Ephemeral Branch Fabric (EBF):
In normal Git, if you want to switch from a payment feature to fix an urgent checkout bug, you must run
git stash, run git checkout bugfix, and restart your compiler or local dev server.
With Git Worktrees, you have multiple physical folders on disk sharing the same underlying Git history. You (or 4 parallel AI agents) can work on
feat-stripe-v2 and refactor-auth-jwt simultaneously in separate folders without branch switching conflicts.
The Problem with other indexers: They get confused, treat each folder as an unrelated duplicate repository, or force you to re-index the whole project from scratch on every branch switch.
The Omni-Graph Solution: Point Omni-Graph at the main project folder once. It automatically discovers all active worktree folders, links their lineage, indexes them in parallel, and live-updates whichever folder you edit in real time!
⚡ O(1) Worktree Pointer Peeking
Instead of spawning slow subshells (git rev-parse), Omni-Graph reads the .git worktree pointer file directly in Rust in under 5 microseconds, resolving parent repository root, branch name, and lineage.
🚀 Top-Down Fleet Auto-Cascade
Ingesting a trunk parent repo automatically inspects .git/worktrees/*, locates all active sibling checkouts, asynchronously indexes each branch, and attaches concurrent live file watchers.
🌱 Prior LPA Seed Inheritance
When clustering a new worktree, Omni-Graph inherits community IDs from the parent workspace. Only modified files shift, preserving 99% cluster visual stability across branches.
🔄 Dynamic Fleet Synchronizer
POST /api/worktrees/sync sweeps registered workspaces, discovers newly checked-out worktrees, cascades indexing, and aligns watcher daemons without restarts.
🧹 Automatic Dead Worktree GC
When an agent deletes a temporary worktree, /api/workspaces immediately sweeps SurrealDB and purges dead nodes, edges, and watchers, eliminating zombie workspace pollution.
🌲 Worktree Hierarchy & Delta UI
Worktrees are cleanly nested under their parent repository (worktrees: [...]), with branch selectors and glowing delta halos for modified AST nodes in Cosmograph.
feat-stripe-v2, refactor-auth-jwt, and hotfix-cart-lock), EBF enforces strict SurrealDB record-level partition isolation (workspace = "<worktree_id>") while sharing the parent LPA community cluster seeds. Each worktree enjoys independent sub-100ms incremental file watching without cross-talk or lock contention.
Polyglot AST Grammar & Struct Field Extraction
Omni-Graph utilizes Tree-Sitter grammars compiled natively in Rust. Unlike shallow regex matchers, Omni-Graph models true language semantics across four enterprise languages:
- Rust: Functions, methods in
implblocks (withDECLARESedges from structs),structdeclarations with childfield_declarationnodes (withCONTAINSandREFERENCESedges),enum_item,trait_item,macro_definition, andmacro_invocation. - Go: Package declarations, function declarations, method declarations with pointer receiver binding,
type_specstructs with memberfield_declarationnodes, and discreteimport_specsymbols. - TypeScript / JavaScript: Lexical arrow functions, classes,
interface_declarationwith childproperty_signaturenodes, type aliases, and multi-symbol named imports (import { A, B }). - Python: Synchronous and
asynccoroutine definitions, class definitions with multi-inheritance tracking, call sites, and multi-symbol imports (from m import A, B).
linked_to table models directed relationships:
$$\text{Node}_{\text{source}} \xrightarrow[\text{category}]{\text{edge\_type}} \text{Node}_{\text{target}}$$ Where $\text{edge\_type} \in \{\text{CALLS}, \text{IMPORTS}, \text{CONTAINS}, \text{IMPLEMENTS}, \text{REFERENCES}\}$ and $\text{category} \in \{\text{EXTRACTED}, \text{INFERRED}\}$.
Two-Tier Context Condenser & Graph-RAG Token Budget Math
A common failure mode in code assistants is context starvation: a retrieval tool dumps 8,000 tokens of raw source code, blowing past agent context windows and truncating essential architectural call graphs. Omni-Graph enforces a mathematical token budget guarantee:
$$C_{\text{total}} = C_{\text{root}} + \min(C_{\text{neighbors}}, 3800) + C_{\text{edges}} + C_{\text{macro}} \le 6,000 \text{ chars}$$
1. Seed / Root Symbols ($C_{\text{root}}$): Receive full code snippets (bounded to 300 chars max).
2. 1-Hop Neighbors ($C_{\text{neighbors}}$): Compressed to concise 1-line signatures (e.g.
fn authenticate(user: &User) -> Result), strictly bounded at 3,800 characters.3. Structural Graph Traces ($C_{\text{edges}}$): Reserved $\ge 1,800$ characters for structural relations:
source ──[CALLS]──▶ target.4. Result: Guaranteed $\le 1,500$ tokens regardless of graph density or codebase scale!
SurrealDB Relational Indexing & Zero-Blackout Re-indexing
SurrealDB v2 handles both relational graph traversals and HNSW vector searches. In Round 4, four dedicated relational indexes were added to linked_to:
-- Sub-millisecond graph edge traversals & caller lookups
DEFINE INDEX idx_edge_workspace ON TABLE linked_to FIELDS workspace;
DEFINE INDEX idx_edge_in ON TABLE linked_to FIELDS in;
DEFINE INDEX idx_edge_out ON TABLE linked_to FIELDS out;
DEFINE INDEX idx_edge_out_ws ON TABLE linked_to FIELDS workspace, out;
DEFINE INDEX idx_edge_in_ws ON TABLE linked_to FIELDS workspace, in;
During live file modifications, the live watcher daemon performs an atomic zero-blackout swap: the HuggingFace TEI vector embedding is computed prior to pruning previous AST nodes. This eliminates the 404 deletion gap from ~250ms down to $\approx 1$ms.
Interactive Context Condenser Token Simulator
Test and simulate Omni-Graph's mathematical token budget. Tweak the sliders to see how two-tier symbol truncation and edge reservation guarantee compliance with the < 1,500 token SLA.
Omni-Graph Live API Playground & Curl Generator
Select any Omni-Graph REST endpoint to generate ready-to-run curl commands formatted for terminal or agent tool invocations.
curl -s -X POST http://localhost:8080/api/query \
-H "Content-Type: application/json" \
-d '{"prompt": "How does token budgeting work?", "workspace": "PolyTuring"}'
Session Explorer: Agent Observability & Telemetry
Session Explorer is a single-binary conversation intelligence browser and real-time observability cockpit for agent transcripts across Antigravity CLI, Antigravity IDE, and extensible runtime providers. It parses raw JSONL logs on local disk, extracts tool parameters, indexes user prompts, and serves an embedded liquid-glass web interface with zero runtime dependencies.
Go + Bun Standalone Binary Architecture
Built for zero runtime friction, Session Explorer embeds its entire web application, Highlight.js syntax engine, KaTeX mathematical typesetter, client-side Mermaid compiler, and Swagger UI directly inside the compiled Go binary using //go:embed:
⚡ 200ms Concurrent Ingestion
Concurrently parses tens of thousands of JSONL transcript lines in under 200ms with sub-50µs incremental delta rescans via mtime and file-size tracking.
🌐 Universal Multi-Runtime Discovery
Simultaneously discovers active sessions across Antigravity CLI and IDE runtimes, attributing transcripts with provider and runtime badges (⚡ CLI, 💻 IDE).
⚡ Real-Time Live Tailing (SSE)
Streams newly appended conversation steps with sub-second latency via Server-Sent Events (/api/sessions/:id/tail), Auto-Follow mode, and zero-layout-shift buffering (Δy = 0).
💬 1-Click Dialogue Mode
Isolates pure conversational human-to-AI exchange from hundreds of autonomous tool execution cards for rapid high-signal reading.
📊 Bounded Diagrams & Theater Mode
Constrains inline diagrams to 440px to eliminate scroll trapping; double-click opens full-screen distraction-free theater with 20%–500% zoom and SVG/Source export.
📁 Native In-Browser File & Artifact Viewer
Instant file inspection with syntax highlighting, line numbers gutter, line anchor highlighting (#L10-L20), pinned floating Find widget (Cmd+F), and 1-click quick-copy chips (📋 → ✓).
Agent Work-in-Progress (WIP) Recovery & Disambiguation
Autonomous coding companions occasionally suffer from context window resets, token ceiling truncations, IDE crashes, or system reboots. Without telemetry, an assistant entering a codebase has no recollection of recent file modifications, pending tasks, or error blockers.
Session Explorer introduces the Agent WIP Recovery System (/most-recent-wip and make session-wip). It extracts recent user prompts, modified files, executed commands, and error logs directly from local JSONL transcripts.
If a developer has three parallel sessions open (e.g. one for backend refactoring, another for CSS polishing, and another for CI debugging), a recovering assistant must NEVER guess or blindly assume the latest session is the target. Doing so leads to catastrophic context corruption!
The Invariant: When multiple sessions match a workspace, the engine automatically halts, returns a structured candidate table with timestamps and prompt previews, and requires the coding assistant to STOP and ask the human user which session to resume.
Liquid Glass UI, 22px Gutter Invariant & Persistent In-Page Find
Reviewing source code touched by coding assistants inside traditional tools often suffers from jarring layout shifts, duplicate scrollbars, and line-number drift. Session Explorer enforces three critical frontend engineering invariants:
📏 The 22px Gutter Invariant
Both the line numbers gutter and the code text container are locked to identical font-size (0.84rem) and line-height (22px). Highlights use inline marks rather than block elements, guaranteeing 0px drift from line 1 to line 10,000.
🪟 Natural Box-Sizing & Zero Dual-Scroll
The code body expands naturally to full content height within an outer scroll container, completely eliminating nested viewport clipping and confusing double scrollbars.
🔍 Sticky Floating In-Page Find
Pressing Ctrl+F or Cmd+F inside the viewer summons a floating acrylic search HUD that remains docked regardless of scroll depth, with real-time match counters and keyboard arrow traversal.
Embedded OpenAPI 3.0 & Swagger UI
Session Explorer embeds an interactive, 100% offline OpenAPI 3.0 specification and Swagger-compatible documentation explorer directly inside the compiled binary:
📖 Interactive Explorer
Navigate to http://localhost:9876/docs to view all endpoints, schema definitions, and execute live API requests with real-time response latency indicators.
📄 Raw OpenAPI 3.0 JSON
Fetch GET /api/openapi.json to import the machine-readable contract into Postman, Insomnia, or automated SDK generators.
⚡ One-Click Skill Installer
Deploy the session-wip agent skill to your workspace (.agents/) or globally (~/.gemini/config/) with one click from the UI or via make setup-session-wip.
CLI Commands & Quickstart
# Launch Session Explorer (auto-opens browser at http://localhost:9876)
make session-explorer
# Launch interactive OpenAPI/Swagger Documentation in browser
open http://localhost:9876/docs
# Recover Agent WIP status for current repository
make session-wip
# Force selection of newest session
make session-wip LATEST=1
# Install session-wip skill into local workspace or global system
make setup-session-wip TARGET=workspace
make setup-session-wip TARGET=global
# Headless mode (no auto-opening browser)
cd tools/session-explorer && make run-headless
# Run unit tests and automated mock dataset demo
make test-tool T=session-explorer
make demo-tool T=session-explorer
Universal Coding Assistant Matrix & Extensibility Blueprint
While PolyTuring was engineered natively and verified first against Google Antigravity, its architectural nervous system is deliberately decoupled from any single proprietary AI ecosystem. Through clean protocol boundaries (REST, SSE, and the Model Context Protocol), PolyTuring serves as a universal intelligence substrate across the leading AI coding companions.
Extensibility Roadmap: Multi-Assistant Phasing
Phase 1: Native Antigravity Substrate (Active)
Full integration with Google Antigravity IDE and agy CLI. Intercepts file reads via hook_pre_tool.sh, parses JSONL brain trajectories in ~/.gemini/, and enforces zero-context-loss WIP recovery.
Phase 2: Universal Model Context Protocol (Active)
Exposes Omni-Graph's AST queries (/symbol, /condense, /galaxies) as an official MCP Tool Server. Any MCP-compliant client (Claude Code, Claude Desktop, Cursor) instantly gains deterministic AST superpowers.
Phase 3: Copilot Extensions & LSP Sidecars (Roadmap)
Packages Omni-Graph as a GitHub Copilot Extension and a standalone Language Server Protocol (LSP) proxy. Copilot users receive boundary-aware completions without leaving VS Code.
Universal MCP Extensibility Blueprint
The diagram below illustrates how PolyTuring's Model Context Protocol (MCP) server bridges any AI coding assistant into the deterministic local substrate:
Engineering Rigor, SDD Constitution & Verification Gates
Autonomous development requires extreme discipline. Without formal contracts and automated verification gates, agent-generated code rapidly decays into technical debt. PolyTuring enforces a constitutional engineering framework across every tool in the monorepo:
Spec-Driven Development (SDD) & SDLC Constitution
In traditional codebases, autonomous coding agents rapidly diverge from human architectural intent because documentation and code live in disconnected universes. In vadde/PolyTuring, every single line of production code is governed by Spec-Driven Development (SDD):
📋 Contract Before Code
Every tool, script, and workflow begins with an airtight specification in specs/catalog/<tool>.md defining verifiable functional requirements, testable acceptance criteria, and non-functional guarantees.
🔄 SDLC Lifecycle Finite State Machine
Tools traverse deterministic phases: draft → spec-review → in-progress → testing → review → released. Advancement is cryptographically blocked unless all checklist gates pass.
🧭 Continuous Session Memory
Every tool folder contains a mandatory CONTEXT.md (agent state snapshot) and append-only DEVLOG.md. Agents never start from zero or lose historical context between compacting sessions.
The Agentic Defense Shield & Reconnaissance Gates
Large Language Models possess context windows, but context windows are finite and vulnerable to noise contamination. Blindly reading a 3,000-line source file wastes tokens and destroys reasoning capabilities. The monorepo enforces the 3-Tier Omniverse Reconnaissance Ladder:
Continuous Integration Matrix
The repository enforces continuous integration across all supported languages (Rust, Go, TypeScript, Python, Shell) using matrix workflows:
The Documentation Synchronization Gate
Under Rule 06 (06-documentation.md), no tool may transition to review or released if documentation has drifted from the active implementation:
specs/catalog/<tool>.md requirements matrix updated with 100% test traceability.2. Tool Catalog:
tools/README.md regenerated via make catalog.3. Living Docs Portal:
docs/site/index.html chapters and architecture diagrams updated with newly added endpoints or features.4. SDLC Quad:
STATUS.md, CONTEXT.md, CHANGELOG.md, and DEVLOG.md updated according to Rule 07.