ZeroGrok
by TinkCarlos
README.md
<div align="center">
<img src="./assets/logo.svg" alt="ZeroGrok Logo" width="84" height="84" />
# ZeroGrok
**Cross-CLI Multi-Agent Orchestration, Sandboxed Execution & Visual Control Plane for Antigravity**
English | [简体中文](./README.zh-CN.md)
[](./LICENSE)
[](https://nodejs.org/)
[](./engine/Cargo.toml)
[](#mcp-tools-reference)
</div>
---
## What Is ZeroGrok?
**ZeroGrok** is an open-source Antigravity plugin (MCP Server + MCP App UI + PreInvocation Hook + optional native Rust daemon `zerogrokd`) that turns a single IDE session into a multi-agent engineering control plane.
Instead of locking you into one model or forcing you to babysit separate terminal tabs, ZeroGrok lets Antigravity route tasks to external coding agent CLIs—**Codex (`codex`)**, **Pi (`pi`)**, **Cursor (`cursor`)**, **OpenCode (`opencode`)**, and **Antigravity (`agy`)**—using each CLI's own subscription/quota, model settings, and enforced permission mode (`chat`, `plan`, `ask`, `agent`, `full`).
Agents can fan out in parallel (up to 5 concurrent instances per bot), collaborate peer-to-peer over a scoped local MCP bridge, run inside Copy-on-Write (`clonefile`) isolated sandboxes, pass deterministic 0-token contract gates, and recover mid-flight via bypass slot hot-swap—all visualized in an interactive live signal-graph cockpit.
---
## Core Innovations
1. **Hybrid TypeScript MCP App + Native Rust `zerogrokd` Engine**
- Works out of the box in pure Node.js (`>= 24`) with zero native compilation required.
- When the Rust `zerogrokd` binary (`engine/`) is built, ZeroGrok automatically upgrades its execution plane to a Unix Domain Socket RPC daemon (`[u32_be][UTF-8 JSON]`, `0700` dir / `0600` socket, SQLite WAL with zero foreign-key lock contention).
2. **APFS Copy-on-Write (`clonefile(2)`) Sandboxes + Serial 3-Way Merge Queue**
- Parallel writable (`agent` / `full`) tasks no longer fight over the same `cwd` or corrupt files mid-edit.
- `zerogrokd` clones workspaces via APFS `clonefile(2)` into isolated temp sandboxes and commits changes back through `SerialMergeQueue` with symlink-escape checks, conflict patch output, and atomic rollback on error.
3. **0-Token Deterministic `TaskContract` Gates & Zero-Orphan Process Reaping**
- Validate worker outputs before merging without spending extra LLM tokens: `writeScopeGlobs`, `forbiddenPatterns`, `objectiveGates` (command exit codes / file assertions), plus a `blake3` thrash-loop circuit breaker (trips after 3 identical tool failures).
- Native macOS `kqueue` + `proc_listchildpids` + `proc_bsdinfo` start-time tracking guarantees `0` orphan grandchild processes on cancellation or timeout.
4. **Bypass `TaskSlot` Hot-Swap & Automatic `fallbackBotIds` Failover**
- When a worker stalls, hits a limit, or fails, `hot_swap_slot` (or automatic `fallbackBotIds` recovery) swaps only that slot (`epoch N → epoch N+1`) using `expected_epoch` CAS fencing tokens, `one_for_one` / `rest_for_one` supervision, and Saga compensation—without restarting upstream parent agents.
5. **Summary-First Peer-to-Peer Bridge (`<= 8 KB` Handoffs) + 16 MiB Line Scanner**
- Permitted bots receive an ephemeral, bearer-authenticated local HTTP MCP bridge (`submit_handoff`, `peer_list`, `peer_call`, `peer_batch`, `peer_dispatch`, `peer_wait`, `peer_read`) or `$ZEROGROK_PEER_CLI` fallback.
- `peer_wait` trims structured responses to `<= 8 KB` so child chatter never blows up the parent's context window (full logs remain on disk via `peer_read`). Meanwhile, `zerogrokd`'s `ByteLineScanner` handles JSONL lines up to 16 MiB without dropping token/tool telemetry.
6. **Interactive Precision Signal-Graph Cockpit & In-Place Hot Reload**
- Built-in MCP App UI (`ui://agent-bots/manager.html`) with wheel-zoom, canvas pan, draggable DAG nodes, obstacle-avoiding Bezier edges, per-agent spotlight telemetry cards, conversation-scoped multi-project grouping (`conv:<conversationId>`), host Overview panel injection (`OverviewCdpBridge`), and zero-restart runtime + UI hot reload (`bots_reload` + `bots_read_ui_chunk`).
---
## Architecture
```mermaid
flowchart LR
Host["Antigravity Host<br/>(PreInvocation Hook + Overview Panel + Chat)"] -->|stdio MCP + UI Resource| Mcp["ZeroGrok MCP Server<br/>(src/mcp/server.ts & runtime.ts)"]
Mcp --> Router["BotRouter & Store<br/>(Admission, Locking, Peer Bridge)"]
Router -->|Optional UDS RPC| Daemon["Native Rust zerogrokd (engine/)<br/>SQLite WAL · APFS CoW · 0-Token Gates<br/>SerialMergeQueue · kqueue Reaping"]
Router -->|Local HTTP MCP / $ZEROGROK_PEER_CLI| CLIs["External Agent CLIs<br/>codex · pi · cursor · opencode · antigravity"]
Daemon -->|Spawn & Isolate| CLIs
```
---
## How ZeroGrok Compares to Existing Tools
| Capability | Single-Vendor Subagents (e.g., Claude Code / Built-in Swarms) | Terminal Multiplexers (e.g., Claude Squad / tmux scripts) | Python Agent Frameworks (e.g., CrewAI / LangGraph) | **ZeroGrok** |
| :--- | :--- | :--- | :--- | :--- |
| **Cross-CLI / Cross-Vendor Routing** | Locked to one vendor/CLI | Manual CLI switching in panes | API-centric; not IDE CLI-native | Native adapters for **5 CLIs** (`codex`, `pi`, `cursor`, `opencode`, `antigravity`) |
| **Parallel Same-Repo Isolation** | Shared `cwd` or manual git worktrees | Git worktrees only | No workspace filesystem sandbox | **APFS `clonefile` CoW sandboxes** + `SerialMergeQueue` 3-way merge & rollback |
| **Verification & Guardrails** | Prompt-based / LLM self-review | None built-in | Custom Python callbacks | **0-Token `TaskContract` gates**, `blake3` thrash breaker, enforced per-bot permission modes |
| **Mid-Flight Failure Recovery** | Retry whole prompt or manual fix | Manual pane restart | Graph-level retry | **Bypass `TaskSlot` Hot-Swap** (`epoch N -> N+1`) + `fallbackBotIds` + `RestForOne` supervision |
| **Context Window Protection** | Often dumps full child output | Manual copy-paste | Manual state pruning | **Summary-first `<= 8 KB` `HandoffEnvelope`** + disk-backed `peer_read` |
| **IDE Control Plane & Telemetry** | Text logs in chat | Terminal text | Separate web server / none | **Embedded MCP App Cockpit** (zoom/pan/drag DAG, token/step telemetry, Overview widget, hot reload) |
---
## Measured Benchmark Results
The numbers below are **directly measured** on macOS arm64 (APFS) by running the built-in self-verification suite (`./engine/target/release/zerogrokd benchmark --workspace .`, `status: "ACCEPTED"`):
| Metric / Invariant | Measured Result | Baseline / What It Means |
| :--- | :--- | :--- |
| **UDS `daemon.ping` median RTT** | **`0.026 ms`** | vs. `30,000 ms` legacy polling interval (`1,153,846x` control-plane RTT ratio) |
| **Event-push guardrail wakeup** | **`246.83 ms`** | **`121.5x` faster** than 30s polling (`events.wait_for_events` + 25ms incremental hash sentinel) |
| **Rust binary spawn median** | **`4.028 ms`** | Sub-5ms daemon/helper startup |
| **Native Mach-O `codex` vs npm `.js` shim** | **`19.753 ms` vs `73.762 ms`** | ~`3.7x` faster CLI startup by unwrapping Node wrapper shims |
| **APFS `clonefile` vs `cp -R` (300 files)** | **`71.903 ms` vs `116.503 ms`** | **`1.6x` faster** on small 300-file trees (`ApfsClonefile` backend; scales further on larger repos) |
| **Bypass Hot-Swap + `RestForOne` verify** | **`93.34 ms`** | Atomic Saga compensation + epoch rollover + downstream reset |
| **Orphan grandchild processes** | **`0` (`orphanGrandchildAlive: false`)** | Verified via `kqueue` + `proc_listchildpids` reaping |
| **Large JSONL line telemetry (>64 KiB)** | **`110 KiB` line preserved** | `totalSteps: 1`, `totalTokens: 2300`, `totalToolCalls: 1` (no truncation drop) |
| **SQLite foreign-key pragma** | **`0` (`sqliteForeignKeysPragma: 0`)** | WAL mode with zero foreign-key lock contention |
> **Honest Boundary:** Cloud LLM reasoning time (typically seconds to minutes per turn) is governed by your model provider and network. ZeroGrok accelerates the **orchestration and control plane**—eliminating polling dead-time, workspace write collisions, context bloat, orphan processes, and full-tree restarts.
---
## Installation
### Prerequisites
- **Node.js** `>= 24.0.0`
- **Antigravity (`agy` CLI)** installed and available on `PATH`
- **At least one external agent CLI** you want to orchestrate: `codex`, `pi`, `cursor-agent` (Cursor CLI), `opencode`, or `agy`
- **Optional (Recommended on macOS/Linux):** **Rust toolchain (`cargo`)** to compile the native `zerogrokd` engine (`engine/`). Without Rust, ZeroGrok runs cleanly in pure-Node fallback mode.
### Option A: Quick Install (Pure Node.js Mode)
```bash
git clone https://github.com/TinkCarlos/zerogrok.git
cd zerogrok
npm install
npm run install:plugin
```
### Option B: Full Install with Native Rust `zerogrokd` Engine (Recommended)
```bash
git clone https://github.com/TinkCarlos/zerogrok.git
cd zerogrok
npm install
npm run build:all
npm run install:plugin
```
`npm run build:all` compiles `engine/target/release/zerogrokd`, bundles the MCP server, hooks, and UI into `dist/`, and automatically stages `dist/bin/zerogrokd` so `npm run install:plugin` ships both together.
### Verify Installation
```bash
npm run validate
agy plugin list --json
```
You should see `"name": "zerogrok"` with `"enabled": true` and `"findings": []`. Restart your Antigravity session (or run `RefreshMcpServers`) so the host picks up the newly installed plugin.
---
## How to Use
### 1. Open the ZeroGrok Manager & Check CLI Health
Ask Antigravity:
- `"Open the ZeroGrok manager"` (calls `open_bot_manager`)
- Check the **Health** tab to verify which local CLIs (`codex`, `pi`, `cursor`, `opencode`, `antigravity`) are installed and authenticated.
### 2. Create Your Agent Bots
In the **Bots** tab, click **+ New Bot** to configure:
- **Agent CLI**: `codex`, `pi`, `cursor`, `opencode`, or `antigravity`
- **Permission Mode**:
| Mode | Behavior |
| :--- | :--- |
| `chat` | Pure conversation; tools disabled where supported (`pi`, `opencode`, `codex`, etc.) |
| `plan` | Read-only codebase inspection and planning |
| `ask` | Read tools allowed; mutations gated/fail-closed (e.g., `pi-ask-guard`) |
| `agent` | Standard workspace read/write execution (uses CoW sandbox when `zerogrokd` is active) |
| `full` | Full autonomous execution with sandbox isolation and peer bridge |
- **Routing Prompt**: Natural-language rule telling Antigravity when to auto-delegate tasks to this bot (enforced via `rules/AGENTS.md` and `PreInvocation` hook).
- **Allowed Peer IDs (`allowedPeerIds`)**: Optional list of peer bot IDs this bot can invoke autonomously.
- **Fallback Bot IDs (`fallbackBotIds`)**: Ordered backup bots used for automatic slot hot-swap recovery on recoverable failures.
### 3. Dispatch, Collaborate & Monitor
Once bots are enabled, simply chat in Antigravity:
- **Single Delegation**: *"Ask the Codex backend bot to add rate-limiting middleware and run unit tests."*
- **Parallel Fan-Out**: *"Dispatch up to 3 instances of the reviewer bot in parallel to audit `src/mcp/`, `src/adapters/`, and `src/ui/`."*
- **Autonomous Peer Pipeline**: *"Have the lead architect bot implement the endpoint and automatically call the QA bot to verify it before reporting back."*
In the **Live** cockpit tab:
- **Zoom / Pan / Drag**: Scroll wheel zooms around cursor (`0.35x`–`2.5x`), drag empty canvas to pan, double-click to reset, or drag any node to rearrange the signal graph.
- **Hot-Swap (`Replace & Re-run`)**: Swap a stalled or failed slot (`hot_swap_slot`) to a new bot or revised task mid-flight without killing parent runs.
- **Stop (`Cancel`)**: Cancel a single run tree (`cancel_bot_run`) or stop all active runs in a project (`{ all: true, projectId }`).
- **Diagnostics & GC**: Use the **Health / Diagnostics** panel (`bots_diagnose`) to inspect `zerogrokd` daemon status, lock state, manifest drift, and garbage-collect stale auxiliary files.
### Environment Variables (Optional)
| Variable | Description | Default |
| :--- | :--- | :--- |
| `ZEROGROKD_BIN` | Explicit path to `zerogrokd` binary | Auto-detected (`dist/bin/zerogrokd`, `engine/target/release/zerogrokd`, `PATH`) |
| `ZEROGROKD_DISABLE` | Set to `1` to force pure-Node.js fallback mode | Unset |
| `ZEROGROKD_SANDBOX_ROOT` | Custom directory for APFS CoW sandboxes | `os.tmpdir()/zerogrokd-sandboxes/<hash>` |
| `ZEROGROK_MAX_CONCURRENT_RUNS` | Global concurrent run cap per data dir | `6` |
| `ZEROGROK_MAX_CONCURRENT_RUNS_PER_ENGINE` | Per-engine concurrent run cap (up to 5 per bot) | `4` |
---
## MCP Tools Reference
| Scope | Tools |
| :--- | :--- |
| **Model-Visible Tools** | `list_bots`, `dispatch_bot`, `get_bot_runs`, `hot_swap_slot`, `cancel_bot_run`, `open_bot_manager` |
| **App UI Management & Ops Tools** | `bots_list`, `bots_create`, `bots_update`, `bots_delete`, `bots_check_health`, `bots_run_history`, `bots_run_events`, `bots_test_dispatch`, `bots_set_locale`, `bots_agent_options`, `bots_set_all_enabled`, `bots_set_plugin_enabled`, `bots_read_ui_chunk`, `bots_cancel_run`, `bots_retry_run`, `bots_diagnose`, `bots_reload` |
| **Local Peer Bridge Tools** *(injected into child bots)* | `submit_handoff`, `peer_list`, `peer_call`, `peer_batch`, `peer_dispatch`, `peer_wait`, `peer_read` |
---
## Development & Testing
```bash
# Typecheck TypeScript
npm run typecheck
# Build Rust engine + TypeScript bundle + UI
npm run build:all
# Run Rust engine unit tests
cargo test --manifest-path engine/Cargo.toml --lib
# Run TypeScript unit tests
npm test
# Strict Antigravity plugin manifest check
npm run validate
```
More technical specs live in [`docs/`](./docs/api.md):
- [API & RPC Contracts](./docs/api.md)
- [Storage & Schema](./docs/database.md)
- [Features & Regressions](./docs/features-and-regressions.md)
- [Runtime & Delivery Notes](./docs/project-notes.md)
---
## License
[MIT](./LICENSE) © 2026 TinkCarlos