Grok Build Architecture Deep Dive: How It Works and How It Compares to Claude Code
In July 2026, SpaceXAI open-sourced an enormous Rust codebase overnight — 79 crates totaling over 250,000 lines of production code (not counting tests, generated files, and build infrastructure). But this wasn't planned generosity — it was damage control after a major privacy scandal. Setting the controversy aside, the code reveals a genuinely interesting architecture for building AI coding agents.
This post breaks down how Grok Build works internally, compares it head-to-head with Claude Code, and helps you understand when each tool shines — whether you're picking one for your daily workflow or curious about building AI tools yourself.
New to AI coding agents? Check out our Claude Code Architecture Deep Dive for a companion perspective.
What Is an AI Coding Agent?#
Think of an AI coding agent as a programmable collaborator living in your terminal. It reads your code, suggests changes, runs commands, and asks permission before doing anything risky. The key difference from ChatGPT: it can act, not just talk — editing real files and running real commands.
Under the hood, every AI coding agent runs the same basic loop:
This is called the agentic loop — the AI acts autonomously within boundaries you set. Both Claude Code and Grok Build implement this pattern, but with very different architectural choices.
The Backstory: Why Grok Build Is Open Source#
Before diving into architecture, you should know the context behind why we can read this code at all.
In May 2026, SpaceXAI launched Grok Build as a public beta. Two months later, security researchers at Cereblab discovered something alarming: for a task that only needed 192 KiB of code, Grok Build uploaded 5.1 GiB — the entire project including git history, SSH keys, API secrets, and database passwords. All sent as Git Bundles to Google Cloud Storage. The privacy toggle in settings did nothing to stop it.
Timeline of Events
| Date | Event |
|---|---|
| May 25, 2026 | Grok Build public beta launches |
| July 12, 2026 | Cereblab publishes findings; SpaceXAI quietly disables upload server-side |
| July 14, 2026 | Story goes viral (The Verge, The Register). Musk promises "complete deletion" |
| July 15, 2026 | SpaceXAI open-sources the full codebase under Apache 2.0 |
The silver lining: we now have ~250K+ lines of production Rust code to study. Let's see what's inside.
Grok Build at a Glance#
Quick Facts
| Aspect | Details |
|---|---|
| Language | Rust (edition 2024, strict clippy) |
| Codebase size | ~79 crates, ~250K+ lines |
| CLI command | grok |
| Async runtime | Tokio (multi-threaded) |
| TUI framework | ratatui (full-screen terminal UI) |
| License | Apache 2.0 (open source) |
| Default model | grok-4.5 (500K context window) |
Deployment Modes: How You Can Run It#
Grok Build goes beyond just "type in the terminal." It offers multiple deployment modes, each serving a different workflow.
| When you want to... | Mode | Description |
|---|---|---|
| Code interactively | Interactive TUI | grok — full-screen terminal UI with scrollback, prompts, and permission modals |
| Run in CI/automation | Headless | grok -p "fix the tests" — non-interactive single-turn; pass a prompt, get a response, exit |
| Use in VS Code/JetBrains | Stdio ACP | ACP (Agent Client Protocol) — a JSON-RPC protocol over stdin/stdout for IDE extensions |
| Keep sessions alive 24/7 | Leader daemon | Long-running background process; clients connect via Unix socket |
| Access from another machine | WebSocket server | Remote access over WebSocket, authenticated by shared secret |
The Leader Daemon: Grok Build's Standout Feature#
Here's the most interesting architectural difference in deployment. Imagine you're editing code, your terminal crashes, and you lose all your in-progress work — frustrating, right?
Grok Build solves this with a leader daemon — a background process that holds all your session state. Your terminal (the UI) just connects to it. If the terminal crashes, you reconnect and pick up exactly where you left off with full state replay.
The analogy: Claude Code is like a document you're editing locally — your work is saved, but if the app crashes mid-action, you lose that in-flight operation. Grok Build is like Google Docs — the server holds the state, so even if your browser tab dies, you reconnect and everything's still there.
Claude Code saves conversation history to disk and you can resume later, but an in-progress tool execution won't survive a process crash the way Grok Build's leader architecture allows.
The Agentic Loop: Same Idea, Different Architecture#
Both tools implement the same high-level loop, but the engineering underneath looks very different.
How Claude Code Does It#
Claude Code uses a single-threaded event loop (TypeScript on the Bun runtime — think of it like Node.js but faster). One QueryEngine controller manages the conversation. The loop is serial (one turn at a time), but tool calls within a single turn can execute in parallel batches of up to 10 concurrent tools. If something goes wrong, it has multiple recovery strategies (retry with exponential backoff, model fallback, compaction, and error-triggered recovery).
How Grok Build Does It#
Grok Build uses an actor model on Tokio (Rust's multi-threaded async runtime). Each session runs on its own dedicated thread — they never share state.
The analogy for actors: Imagine each session is a person in their own room with their own desk. They never share papers — they just pass notes through a slot in the door. One person having a bad day can't mess up another's work.
Architecture Implications for Your Workflow
| You care about... | Claude Code | Grok Build |
|---|---|---|
| Multiple sessions at once | One process per conversation | Multiple sessions in one leader process, fully isolated |
| Where you connect from | Terminal, IDE, or web — separate processes | Terminal, IDE, WebSocket — all connect to same leader |
| If one session crashes | That session is interrupted | Other sessions are unaffected (actor isolation) |
| Protocol consistency | Same engine, different front-ends | Same ACP protocol guarantees identical behavior everywhere |
Tools: How the AI Actually Does Things#
When the AI wants to read a file, it doesn't just... read it. It calls a "Read File" tool. When it wants to run npm test, it calls a "Bash" tool. This is called the "everything is a tool" pattern, and both agents use it.
Why? Because every tool goes through the same pipeline: validate inputs → check permissions → execute → format results. Adding a new capability is just adding a new tool — it automatically gets permissions, logging, and error handling for free.
What Tools Are Available#
Tool Categories
| Category | Claude Code | Grok Build |
|---|---|---|
| File operations | Read, Edit, Write, Grep, Glob | ReadFile, SearchReplace, ListDir, Grep |
| Code execution | Bash | BashTool (foreground + background) |
| Web access | WebFetch, WebSearch | WebFetch, WebSearch |
| Sub-agents | Agent tool (background + worktree) | TaskTool (background + worktree) |
| Media generation | — | ImageGen, ImageEdit, ImageToVideo |
| Tool discovery | ToolSearch (deferred loading) | SearchTool (MCP discovery) |
| Total tools | 40+ | 45+ |
The Namespace Trick: Grok Build's Unique Approach to Long Output#
Here's a clever problem that Grok Build solves differently from Claude Code. When a tool reads a 500-line file or runs a test suite, it dumps a lot of text back into the AI's context window. That eats up the limited memory the AI has.
Grok Build's solution: Every tool has two output methods:
model_output()— what gets sent to the AIchat_completion_output()— what gets shown to you in the terminal
The "Concise" namespace (BashConcise, ReadFileConcise, etc.) overrides model_output() to produce deliberately stripped-down results for the AI, while you still see full output via chat_completion_output(). The AI can work longer before running out of context.
Claude Code's approach: Instead of dual outputs, Claude Code uses ToolSearch (most tools are hidden until needed, saving input tokens from schemas) and retroactive trimming (old tool results get compressed when context gets tight).
Different Approaches to the Same Problem
| Strategy | When it helps | Trade-off |
|---|---|---|
| Grok Build: Concise namespaces | Prevents bloat from the start — AI always gets short results | You configure namespace upfront; AI may miss details in truncated output |
| Claude Code: ToolSearch + retroactive trimming | Tools load on demand; old results shrink when context fills | Full results early (better context initially), but compaction needed later |
Grok Build optimizes at generation time. Claude Code optimizes lazily when needed.
Context Management: How They Handle Long Conversations#
Imagine pair-programming with someone who has limited short-term memory. After 30 minutes, they start forgetting what you discussed earlier. You need a strategy: summarize? Keep only recent stuff? Write notes? That's exactly what these tools face with the AI's context window.
Claude Code: Progressive Escalation (6 Levels)#
Claude Code starts cheap and gets more aggressive only when needed:
The system automatically escalates through these strategies during a single session. If level 1 keeps you under the limit, levels 2–6 never fire. If the API returns a "prompt too long" error, it triggers emergency compaction as a fallback.
Grok Build: Choose Your Strategy (3 Modes)#
Grok Build takes a different approach — you configure which strategy to use, and it sticks for the session:
Grok Build's Compaction Strategies
| Strategy | How it works | Best for |
|---|---|---|
| Basic (default) | Send all turns to the LLM for summarization in one shot | Short sessions, simplicity |
| Intra-Turn (Tail-Keep) | Summarize old turns, keep recent K turns intact verbatim | Medium sessions where recent context matters most |
| Inter-Turn (Segments) | Break conversation into semantic "chapters," summarize completed ones to disk | Very long sessions (hours of work) |
All strategies trigger at 85% context utilization by default.
The Segment Approach: Chapters in a Book#
The Inter-Turn strategy is worth understanding because it's unique. Think of it like chapters in a book:
- "Chapter 1: Set up the database" → summarized and saved to disk
- "Chapter 2: Fix the auth bug" → summarized and saved to disk
- "Chapter 3: Refactoring the API" → still in full detail (active segment)
Only the current chapter stays in full detail. Completed chapters become markdown summaries. This lets very long sessions (hours) stay manageable without losing important context.
The key difference: Claude Code progressively escalates through strategies within a session (automatic). Grok Build lets you pick one strategy upfront (manual configuration).
Permissions and Security: Keeping You Safe#
The AI can do anything it can convince the tool system to allow. Without guardrails, "delete all files" or "push to production" are possible. Both tools take this seriously — but with very different philosophies.
Claude Code: Multiple Guards Checking Each Other#
Analogy: Like airport security — multiple independent checkpoints, and any one can stop you.
The critical design choice: if the AI classifier can't be reached, it blocks by default (fail-closed). The philosophy is: if any safety system is broken, assume unsafe.
Grok Build: The OS Kernel as the Final Guard#
Analogy: Instead of multiple security guards, you put the valuables in a vault that physically can't be opened.
Grok Build has software permissions too (modes, rules, hooks). But its unique layer is kernel-level sandboxing:
Kernel-Level Enforcement
| Platform | Mechanism | What it does |
|---|---|---|
| Linux | Landlock LSM | The OS kernel enforces path-based access control (e.g., write only within your project directory) |
| macOS | Seatbelt | Apple's sandbox framework enforces filesystem access rules |
Once applied, the sandbox is irreversible for that process — even if the AI tricks the tool system, the OS blocks the action.
The sandbox is stored in a OnceLock (Rust's one-time initialization) — it literally cannot be undone after being applied.
The Philosophical Difference#
Quick vocabulary: "Fail-closed" means when a safety check can't run (timeout, crash, network error), the system blocks the action — safe by default. "Fail-open" means when a safety check can't run, the system allows the action — prioritizing availability over safety.
Security Philosophies Compared
| Claude Code | Grok Build | |
|---|---|---|
| When in doubt... | Block (fail-closed) | Allow (fail-open for hooks), but kernel still protects |
| Unique security layer | AI classifier (separate model evaluating safety) | OS kernel sandbox (Landlock/Seatbelt) |
| If safety system crashes | Classifier unavailable → deny | Hooks timeout → allow, but kernel boundary is unbreakable |
| Defense model | Multiple software layers, any one can block | Software permissions + hardware-enforced boundary |
The irony: Grok Build has arguably stronger LOCAL security (kernel sandbox). But the upload scandal happened at the NETWORK level — the sandbox restricts file/process access, not what gets sent to SpaceXAI's servers. Security is a spectrum.
Memory: Remembering Across Sessions#
Without memory, every conversation starts from zero. The AI doesn't know your preferences, your project's quirks, or that you told it yesterday to "never use semicolons."
Memory Systems Compared
| Aspect | Claude Code | Grok Build |
|---|---|---|
| Storage format | Markdown files in ~/.claude/ directories | Local vector store + keyword index |
| Memory types | 4 types: User, Feedback, Project, Reference | Flat entries with embedding similarity search |
| Retrieval | Semantic recall — smaller AI picks 5 most relevant memories | Combined vector + keyword search, injected as <memory> blocks |
| When memories save | Explicitly, by pattern detection, or via "dreaming" (consolidation between sessions) | Explicit memory_write tool calls or end-of-session hooks |
| Auto-write during conversation | Yes (pattern detection) | No — model must explicitly call memory_write tool |
Grok Build's Standout: Checkpoint/Undo System#
This is a real differentiator. Before each prompt, Grok Build creates a multi-domain snapshot:
If the AI messes up, you can rewind to before any specific prompt. Why is this better than rolling back with git (revert, reset, stash, checkout)?
- Works on uncommitted changes — the AI often creates or edits files without committing. Git rollback commands only operate on committed or staged state; the checkpoint captures everything.
- Per-prompt granularity — git works at commit boundaries, but the AI may make many changes within a single prompt before committing anything.
- Preserves staging state — restores exactly what was staged vs unstaged, which no git rollback command fully reconstructs.
- Non-destructive — rewinding saves your current state first, so you can undo the undo. Git reset/checkout can permanently discard work.
Sub-Agents: One Deep Thinker vs. Many Parallel Workers#
Both tools support sub-agents, but they emphasize different strengths.
Claude Code's philosophy: Deep serial reasoning with a large context window is the primary mode. Sub-agents supplement when parallelism helps.
Grok Build's philosophy: Parallel sub-agents are a first-class architectural pattern from the start. The SubagentCoordinator orchestrates background, worktree-isolated, and inline sub-agents.
How Grok Build Isolates Workers#
Each sub-agent gets its own copy of the codebase via xai-fast-worktree:
- On Linux (BTRFS): Instant filesystem snapshots (nearly free)
- On macOS (APFS): Copy-on-write via reflinks (only changed files cost disk space)
- Workers can edit files without conflicting with each other
- When done: merge results back (or discard if the worker failed)
- Pre-created worktree pool — workers start instantly, no setup delay
When Each Approach Wins
| Scenario | Better fit | Why |
|---|---|---|
| Complex bug requiring deep reasoning | Claude Code | One thinker with big context can hold the full problem in mind |
| "Find all usages of X across the codebase" | Grok Build | Fan out workers to search in parallel |
| Large refactoring across many files | Grok Build | Parallel edits in isolated worktrees, merge at the end |
| Subtle architectural decision | Claude Code | Step-by-step reasoning chain benefits from serial depth |
The Big Picture: Which Should You Use?#
Final Comparison
| You care about... | Claude Code | Grok Build |
|---|---|---|
| Reasoning depth | Large context window, deep serial reasoning | Parallel sub-agents, divide-and-conquer |
| Speed | Optimized for thoroughness | Optimized for parallelism |
| Model choice | Anthropic models (Claude family) | Any model (OpenAI-compatible, configurable base URL) |
| Privacy track record | Clean — no data exfiltration incidents | Controversial (upload scandal) |
| Open source | No | Yes (Apache 2.0) |
| Session persistence | History saved to disk, but process-bound | Leader daemon with full state replay across crashes |
| Local security | 5 software layers + AI classifier (fail-closed) | Kernel-level sandbox (Landlock/Seatbelt) |
| Undo system | Git history / manual stash | Built-in multi-domain checkpoint/rewind |
Practical Recommendations#
Use Claude Code if: you value deep reasoning, want a mature ecosystem with extensive IDE integration, prefer fail-closed safety defaults, and trust Anthropic's track record on privacy.
Use Grok Build if: you want parallel sub-agents as a primary workflow, need model flexibility (use any provider), want to audit the source code yourself, need session persistence across terminal crashes, or want kernel-level sandboxing.
Use both: They support the same protocols (MCP) and similar configs (Grok Build reads AGENTS.md). You can switch between them for different tasks.
The Trust Question#
"Open source" doesn't automatically mean "trustworthy" — the upload code is still there in the codebase, disabled by a flag. "Proprietary" doesn't mean "untrustworthy" — Claude Code has never had a data exfiltration scandal.
What actually matters: network monitoring, clear privacy policies, and independent security audits. Judge tools by their behavior, not their marketing.
What You Can Learn From This#
If you're building AI-powered tools, both architectures offer lessons:
- The "everything is a tool" pattern is universal — adopt it for your own agents. It gives you permissions, logging, and extensibility for free.
- Actor model vs event loop — pick based on whether you need multi-session isolation (actors) or simplicity (event loop). Most developers only need one session at a time.
- Context management is THE hard problem — both tools spend enormous engineering effort on it. Plan for it early in your design.
- Layered configuration pays off — it enables enterprise + personal + project settings cleanly. Both tools use 5+ configuration layers.
- Security must be defense-in-depth — no single layer is enough. The scandal proved that even kernel sandboxing misses network-level threats.
The AI coding agent space is converging: same patterns (agentic loop, tools, compaction, hooks, MCP), different trade-offs. Understanding the architecture helps you use them better — and build your own when the time comes.