PolyTuring
vadde/PolyTuring monorepo
v0.2.2 Living Docs
Quick search documentation... ⌘K
Token Simulator API Playground GitHub
Visual Architecture Theater
125%
Reading Mode:
Press ⌘K or / to search anytime
Architectural Platform Manifesto · Antigravity Native · Multi-Assistant Roadmap

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.

3,480+ nodes
Polyglot AST Symbols Indexed
< 1,500 tokens
Graph-RAG Slice vs. 50k Raw Tokens
500+ galaxies
Louvain/Leiden Subsystem Clusters
100% Antigravity
Native CLI & IDE Integration
Chapter 00 · Platform Manifesto

The Autonomous Agentic Platform Manifesto

Why AI coding assistants fail on real codebases — and how deterministic AST substrates solve it
▼

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

Native Antigravity Integration & The Extensibility Invariant
PolyTuring is currently built and calibrated natively for Google Antigravity:
  • 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.
Chapter 01 · Primary Tool

Omni-Graph: 100% Local Semantic Knowledge Hub

Apple Silicon M-Series AST & Vector Graph RAG · Rust Axum + SurrealDB v2 + HF TEI
▼

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.

❌ The "Old Way" (Blind Agent)
  • Runs blind grep or find across 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.
✅ The Omni-Graph Way (Instant X-Ray)
  • 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:

Architecture Blueprint · 4-Tier Container Stack
100%
flowchart TB
    subgraph UI["Tier 4: WebGL Visualizer (:3000)"]
        Cosmo["Cosmograph 3D Force Graph"]
        Analytics["Dual-Source Agent Analytics"]
    end

    subgraph Rust["Tier 3: Rust Axum Orchestrator (:8080)"]
        Parser["Tree-Sitter Polyglot Parser"]
        Condenser["Context Condenser (≤ 1500 Tokens)"]
        RagEngine["GraphRagEngine (Hybrid Synthesizer)"]
        Watcher["Notify Background Watcher Daemon"]
    end

    subgraph DB["Tier 1: SurrealDB v2 (:8000)"]
        NodeTbl["node (SCHEMAFULL, HNSW 384-dim)"]
        EdgeTbl["linked_to (TYPE RELATION, idx_edge_*)"]
        GalaxyTbl["galaxy (Pre-Computed LPA Clusters)"]
    end

    subgraph TEI["Tier 2: HuggingFace TEI (:8081)"]
        Model["BAAI/bge-small-en-v1.5 (ARM64 SIMD)"]
    end

    UI --> Rust
    Rust --> DB
    Rust --> TEI
                
Figure 1.1: Omni-Graph 4-Tier Container Topology & Dataflow
Service Registry Table · Ports & Responsibilities
100%
Service Port Image / Technology Operational Responsibility
omni-rust-app 8080 Rust 1.80+ (Axum, Tree-Sitter) AST extraction, file watching, Graph-RAG synthesis, token budgeting.
omni-graph-db 8000 SurrealDB v2.x Multi-model database: schemeful nodes, graph edges, and HNSW vector index.
omni-embedding-engine 8081 HuggingFace TEI (ARM64) Sub-millisecond token embedding using BAAI/bge-small-en-v1.5.
omni-graph-ui 3000 React, Vite, Cosmograph GPU-accelerated WebGL force-directed graph and real-time telemetry HUD.
Table 1.1: Container Port Topology & Operational Invariants
Live Interface · 3D Galaxy Subsystems Studio
100%
Omni-Graph 3D Galaxy Studio
Figure 1.2: 3D Force-Directed Galaxy Subsystems — Macro Topology & LPA Community Clusters
Live Interface · Agent Analytics & LSP Telemetry
100%
Omni-DB Agent Analytics & LSP Telemetry
Figure 1.3: Real-Time Agent Analytics — AST Call Efficiency, Context Window Preservation (90.7%), & Multi-Language LSP Telemetry

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.

Mathematical Formulation: Modularity Optimization ($Q$)
Omni-Graph discovers cohesive subsystems by maximizing Newman-Girvan network Modularity ($Q$) across directed, edge-weighted AST relations:

$$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.
Dynamic Blast Radius Endpoint: GET /api/galaxy/boundary?symbol=X
Before an agent refactors any symbol, the pre-tool hook queries the symbol's boundary contract. Omni-Graph returns:

• 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):

💡 Layman's Mental Model: What is a Git Worktree?
Think of Git Worktrees like having multiple browser tabs open for the exact same website at the same time:

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.

Architecture Blueprint · Ephemeral Branch Fabric (EBF)
100%
flowchart TB
    Trunk["Trunk Workspace (Parent)
e.g. ecommerce-platform"] subgraph GitWorktrees["Git Worktree Directory (.git/worktrees/*)"] WT1[".git/worktrees/feat-stripe-v2"] WT2[".git/worktrees/refactor-auth-jwt"] WT3[".git/worktrees/hotfix-cart-lock"] WT4[".git/worktrees/exp-graphql-mesh"] end subgraph EBFEngine["Omni-Graph EBF Core (Rust Axum Engine)"] Peeker["O(1) Worktree Peeker
Resolves gitdir and lineage"] Cascade["Top-Down Auto-Cascade
Asynchronous Background Ingestion"] LPAInherit["Seed-Preserving LPA
Inherits parent community IDs"] WatcherPool["Notify Watcher Pool
Multi-Path Concurrent Daemon"] end subgraph Storage["SurrealDB v2 Isolation"] DB_Trunk["workspace: ecommerce-platform"] DB_WT1["workspace: feat-stripe-v2"] DB_WT2["workspace: refactor-auth-jwt"] DB_WT3["workspace: hotfix-cart-lock"] DB_WT4["workspace: exp-graphql-mesh"] end Trunk --> Peeker Peeker --> GitWorktrees GitWorktrees --> Cascade Cascade --> LPAInherit Cascade --> WatcherPool LPAInherit --> Storage WatcherPool -.->|Live Invalidation| Storage
Figure 1.2: Ephemeral Branch Fabric (EBF) Multi-Worktree Auto-Cascade & Live-Watch Dataflow
Multi-Worktree Concurrency & Branch Isolation
When parallel AI agents develop multiple strategies simultaneously (such as 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 impl blocks (with DECLARES edges from structs), struct declarations with child field_declaration nodes (with CONTAINS and REFERENCES edges), enum_item, trait_item, macro_definition, and macro_invocation.
  • Go: Package declarations, function declarations, method declarations with pointer receiver binding, type_spec structs with member field_declaration nodes, and discrete import_spec symbols.
  • TypeScript / JavaScript: Lexical arrow functions, classes, interface_declaration with child property_signature nodes, type aliases, and multi-symbol named imports (import { A, B }).
  • Python: Synchronous and async coroutine definitions, class definitions with multi-inheritance tracking, call sites, and multi-symbol imports (from m import A, B).
Relational Edge Graph Schema
Every edge in the 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:

Mathematical Budget SLA: $\le 1,500$ Tokens
Given that 1 LLM token $\approx 4$ characters of source code, the total character budget is capped at $C_{\text{max}} = 6,000$ characters:

$$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:

SurrealQL · src/db/schema.surql
-- 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.

Chapter 01 · Interactive Module 1.1

Interactive Context Condenser Token Simulator

Real-time token estimation, character bounding, and SLA validation
▼

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.

Root Symbol Snippet
300 chars
Neighbor Signatures Cap
2400 chars
Structural Relations Count
15 relations
Galaxy Macro Summary
350 chars
4,025
Total Characters
~1,007
Estimated Tokens (Chars / 4)
SLA PASSED (≤ 1,500 Tokens)
SLA Compliance Gate
Chapter 01 · Interactive Module 1.2

Omni-Graph Live API Playground & Curl Generator

Terminal-ready curl generator for all graph, vector, and AST endpoints
▼

Select any Omni-Graph REST endpoint to generate ready-to-run curl commands formatted for terminal or agent tool invocations.

Generated Command
curl -s -X POST http://localhost:8080/api/query \
  -H "Content-Type: application/json" \
  -d '{"prompt": "How does token budgeting work?", "workspace": "PolyTuring"}'
Chapter 02 · Secondary Tool

Session Explorer: Agent Observability & Telemetry

Go 1.22+ Single Binary · Bun Embedded Frontend · JSONL Trajectory 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:

Architecture Blueprint · Embedded Binary Pipeline
100%
flowchart LR
    CLI["~/.gemini/antigravity-cli/brain/ (CLI)"] --> Scanner["Go Concurrent Scanner (Worker Pool + Delta Cache)"]
    IDE["~/.gemini/antigravity-ide/brain/ (IDE)"] --> Scanner
    Scanner --> MemIndex["In-Memory Index & Search Engine"]
    MemIndex --> Api["Go HTTP REST API & SSE Live Tail (/tail)"]
    Assets["Bun Web Frontend (Liquid Glass UI)"] --> Embed["go:embed Static Assets"]
    Embed --> Binary["Standalone 'session-explorer' Binary (0 Deps)"]
    Binary --> Browser["Local Browser (:9876)"]
    Api -.->|SSE Stream| Browser
                
Figure 2.1: Session Explorer Embedded Binary Architecture & Log Processing Pipeline

⚡ 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 (📋 → ✓).

Live Interface · Session Explorer Cockpit
100%
Session Explorer Cockpit
Figure 2.2: Session Explorer Cockpit — Multi-Runtime Workspace Discovery, Date Clustering & Live Filter HUD
Live Interface · 1-Click Dialogue Mode
100%
Session Trail Dialogue Mode
Figure 2.3: Session Trail in Dialogue Mode — High-Signal Reading, Markdown Tables & Inline KaTeX Rendering
Live Interface · Native File & Artifact Viewer
100%
Native In-Browser File Viewer
Figure 2.4: Native In-Browser File Viewer — Syntax Highlighting, Synchronized Gutter, Anchored Highlights & Pinned Find Widget

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.

🛑 The Multi-Session Disambiguation Invariant
What happens when a codebase has multiple parallel sessions?

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.
Agent Protocol Blueprint · WIP Recovery & Halting Lifecycle
100%
flowchart TD
    Trigger["Coding Assistant Runs /most-recent-wip (or wip.sh)"] --> QueryAPI["Query Session Explorer Engine (GET /api/wip)"]
    QueryAPI --> ScanIndex["Scan Brain Transcripts & Correlate Workspace"]
    ScanIndex --> Decision{"Multiple Active Sessions Found?"}
    Decision -- "Yes (>1 Candidates)" --> HaltAgent["🛑 MANDATORY AGENT HALT: Present Candidates & Ask User"]
    Decision -- "No (1 Match or Forced)" --> LoadDigest["🚀 Auto-Resume: Extract Recent Prompts, Diffed Files & Commands"]
    HaltAgent --> UserPicks["User Selects Target Session UUID"]
    UserPicks --> LoadDigest
    LoadDigest --> ContinueWork["Assistant Resumes Task Seamlessly Without Context Loss"]
                
Figure 2.5: Autonomous Agent WIP Recovery & Multi-Session Disambiguation Protocol

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

Terminal · Makefile Targets
# 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
Chapter 03 · Assistant Ecosystem

Universal Coding Assistant Matrix & Extensibility Blueprint

Built Antigravity-First · Plug-and-Play Adapters for Copilot, Claude Code, and Cursor
▼

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.

Ecosystem Matrix · Multi-Assistant Support
100%
Capability Dimension Google Antigravity (Native) GitHub Copilot (Roadmap) Claude Code (Roadmap) Cursor (Roadmap)
AST Knowledge Graph ✅ Native HTTP (:8080) 🔄 MCP Tool Server 🔄 MCP Tool Server 🔄 LSP / MCP Server
Galaxy Subsystems & Blast Radius ✅ Pre-Tool Recon Hook 🔄 Copilot Extension 🔄 Hook / CLI Tool 🔄 Context Provider
Graph-RAG Token Condenser ✅ Strict ≤1,500 Token Slice 🔄 MCP Prompt Inject 🔄 Tool Call (/condense) 🔄 MCP Prompt Inject
WIP Memory & State Recovery ✅ Native Brain Scanner 🔄 Workspace State API 🔄 Session Log Scanner 🔄 Storage JSON Scanner
Trajectory Replay & Telemetry ✅ JSONL Auto-Replay & Tail 🔄 Telemetry Importer 🔄 CLI Session Reader 🔄 Trace Importer
Table 3.1: Cross-Assistant Capability Matrix — Antigravity Native Implementation vs. Multi-Assistant Roadmap

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:

Architecture Blueprint · Universal MCP Bridge
100%
flowchart TB
    subgraph Assistants["Supported Coding Assistants"]
        AG["Google Antigravity
(Native CLI / IDE / Brain)"] CC["Claude Code
(Anthropic CLI)"] GH["GitHub Copilot
(VS Code / IntelliJ)"] CR["Cursor
(IDE / Composer)"] end subgraph AdapterLayer["PolyTuring Universal Adapter Layer"] Hooks["Native Hooks
hook_pre_tool.sh"] MCPServer["PolyTuring MCP Server
(JSON-RPC over stdio / HTTP)"] LSPBridge["LSP Proxy Sidecar
(Diagnostics & Hover)"] end subgraph CoreEngines["PolyTuring Deterministic Engines"] OG["Omni-Graph Core (:8080)
AST Knowledge & Galaxies"] SE["Session Explorer (:9876)
Trajectory Intelligence & WIP"] DB["SurrealDB v2 Graph Store"] end AG --> Hooks CC --> MCPServer CR --> MCPServer GH --> LSPBridge Hooks --> OG Hooks --> SE MCPServer --> OG MCPServer --> SE LSPBridge --> OG OG <--> DB
Figure 3.1: Universal MCP & Hook Adapter Architecture Connecting AI Assistants to PolyTuring Engines
Chapter 04 · Engineering Rigor & Governance

Engineering Rigor, SDD Constitution & Verification Gates

Spec-Driven Development · Agentic Reconnaissance Gate · Continuous Documentation Sync
▼

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.

Theoretical Principle: The Reflexion Pattern
When tests fail or architectural invariants are breached, agents are forbidden from applying blind heuristic patches. Instead, agents must apply the Reflexion loop: extract the root cause from the compiler/runtime, correlate with the spec requirement, document the failure hypothesis, and execute a mathematically minimal, targeted correction.

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:

Agentic State Machine · Recon Ladder
100%
graph TD
    User["Agent Trigger / PreInvocation Hook"] --> ReconCheck{"Recon Marker Present? /tmp/omni_recon"}
    ReconCheck -- No --> GateEnforce["150-Line Source Gate ACTIVE"]
    GateEnforce --> Tier1["Tier 1: Global Graph-RAG (make query Q=...)"]
    Tier1 --> Tier2["Tier 2: Galaxy Cluster Boundaries (make galaxies)"]
    Tier2 --> Tier3["Tier 3: AST Call Graph Condenser (make condense SYM=...)"]
    Tier3 --> TouchMarker["Touch Recon Marker"]
    TouchMarker --> GatePass["150-Line Gate UNLOCKED for Precision Reads"]
    ReconCheck -- Yes --> GatePass
                
Figure 4.1: Deterministic Agent Reconnaissance Ladder & Guardrail State Machine
The 150-Line Gate Invariant
Directly viewing or catting more than 150 lines of source code without querying Omni-Graph's AST or condenser first is an immediate anti-pattern. The PreToolUse hook halts unauthorized large reads and directs the agent to retrieve exact AST symbol definitions or condensed slices.

Continuous Integration Matrix

The repository enforces continuous integration across all supported languages (Rust, Go, TypeScript, Python, Shell) using matrix workflows:

Workflow Matrix · CI & CD Pipelines
100%
Workflow Trigger Responsibilities & Quality Gates
ci.yml Push / PR to main Detects changed tools, executes spec validation (validate-specs.sh), runs repository markdown link checks.
tool-ci.yml Reusable (Called by CI) Auto-detects language stack. Executes Rust Clippy with strict -D warnings, runs cargo test, Go vet/test, and Bun web builds.
docs-publish.yml Push to main Builds the master liquid-glass static documentation portal via scripts/build-docs.sh and deploys to GitHub Pages.
Table 4.1: Automated CI/CD Workflow Responsibilities

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:

The 4-Point Documentation Gate
1. Spec Alignment: 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.