Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Distributed Agentic CLI
Coding Platform (Claude Code).

Design an end-to-end agentic CLI coding platform supporting millions of developers, local OS sandboxing, 85%+ prompt-cache hit rates, parallel MCP subagents, and enterprise auditability.
Start the journey7 stages· Last modified Nov 24, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If model quality drifts from offline training baselines, keep execution local inside Seatbelt/seccomp + shadow Git worktrees while routing inference through an ephemeral prefix-cache-aware cloud gateway.

TL;DR30-second simplified summary
▾

The local Rust/Go binary manages TUI streaming, shadow Git snapshots for instant rollback, and signed enterprise policies enforced via Seatbelt/Landlock. Only compacted prompts cross TLS to the cloud gateway.

In the cloud, consistent hashing routes turns to GPU clusters with HBM + NVMe L2 KV-prefix caches, surviving multi-minute developer review pauses while keeping TTFT under 400ms.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Agentic CLI Coding Harness Architecture
An agentic CLI coding harness pairs a local ReAct tool-execution loop (Bash, file edit, grep, git) with OS-level sandboxing, AST-backed repo mapping, prompt-prefix caching, and auto-compaction to solve multi-file engineering tasks from the terminal.
Full walkthrough · 7 stages
01
foundation

Split Local-Cloud Control Plane & Latency Budget.

Why this matters: Decide which components run on the developer's machine versus the cloud inference cluster.

File reads, ripgrep, AST parsing, and test execution MUST run locally to avoid uploading gigabytes of proprietary source code and adding network latency per tool call.

Only compacted prompts, tool schemas, and tool outputs cross TLS to the cloud LLM gateway.

Stage 1 - Hybrid Architecture

Local Runtime vs Cloud Inference Split

Local CLI BinarysourceCloud LLM GatewayrouterPrefix-Cached GPUsprocessorAsync OTelCollectorsinkRoute to warm prefix

1.Zero Repo Upload: Only targeted file slices read by the agent ever leave the developer's workstation.

2.Offline Resilience: Persist session transcripts locally in SQLite so network drops resume cleanly.

Keeping file and test execution local minimizes bandwidth while preserving developer speed.

02
foundation

Shadow Git Worktrees & Parallel Safe Execution.

Why this matters: Isolate agent edits from dirty working trees and enable atomic multi-file rollback.

Developers often invoke the CLI in a repo with uncommitted changes.

Before the agent mutates any file, the CLI captures a baseline shadow Git tree (GIT_INDEX_FILE=.git/agent-shadow-index git write-tree).

Stage 2 - Workspace Isolation

Shadow Git Index & Worktree Manager

User Working TreesourceShadow Git IndexcacheIsolated GitWorktreeprocessorVerified PatchApplysinkRun speculative fix

1.No Git Pollution: Shadow indices never create commits or alter HEAD/stash.

2.Instant Rollback: Restoring a shadow tree SHA reverts 50+ file edits in milliseconds.

Shadow Git indices and worktrees protect uncommitted developer work during autonomous runs.

Engineering Decision Framework
Problem
How to implement Design a Distributed Agentic CLI Coding Platform (Claude Code) without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
If model quality drifts from offline training baselines, keep execution local inside Seatbelt/seccomp + shadow Git worktrees while routing inference through an ephemeral prefix-cache-aware cloud gateway.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design a Distributed Agentic CLI Coding Platform (Claude Code) experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
intermediate

Enterprise Permission Policy & Kernel Sandboxing.

Why this matters: Enforce organization-wide security rules and kernel-level filesystem/network jails.

Think of Enterprise Permission Policy & Kernel Sandboxing as the intuition layer for Design a Distributed Agentic CLI Coding Platform (Claude Code): Enforce organization-wide security rules and kernel-level filesystem/network jails.

Enterprises push signed policy JSON (managed-settings.json) specifying forbidden paths (**/.env, **/secrets/**), blocked binaries (rm -rf, curl), and allowed MCP servers. The CLI evaluates policies deterministically before spawning any subprocess inside macOS Seatbelt or Linux seccomp/landlock, ensuring even a compromised MCP tool output cannot exfiltrate credentials.

Stage 3 - Enterprise Security

Policy Engine & Kernel Sandbox

Signed Org PolicycachePolicy EvaluatorrouterLandlock / SeatbeltprocessorLocal Security LogsinkEnforce syscalls

1.Bash AST Check: Parse shell commands before execution to catch chained `&& curl` or subshell bypasses.

2.Fail-Closed: Any policy parse error defaults to interactive user confirmation.

Signed org policies and kernel sandboxes block credential exfiltration under prompt injection.

04
intermediate

Ephemeral Prefix-Cache Routing in the Cloud Gateway.

Why this matters: Route 100-turn CLI sessions to warm KV-cache GPUs for 85%+ cache hits.

Think of Ephemeral Prefix-Cache Routing in the Cloud Gateway as the intuition layer for Design a Distributed Agentic CLI Coding Platform (Claude Code): Route 100-turn CLI sessions to warm KV-cache GPUs for 85%+ cache hits.

CLI coding sessions have a 5-minute TTL between turns as developers review diffs. The Cloud Gateway hashes the first 4KB of the system+tools+repo-map prefix plus session_id to route requests via consistent hashing to GPU clusters holding those KV blocks in HBM or fast NVMe L2 cache, cutting per-turn prefill cost by up to 90%.

Stage 4 - Cloud Prefix Routing

Session-Sticky Ephemeral Prefix Cache

Turn N RequestsourceConsistent Hash RingrouterGPU HBM L1 CachecacheNVMe L2 OffloadstorageHit L1 (<150ms TTFT)

1.NVMe L2 Bridge: Offloading KV blocks to NVMe survives 5-minute human code-review pauses.

2.ZDR Compliance: Ephemeral KV caches are encrypted per-tenant and wiped on TTL expiry.

Two-tier HBM + NVMe KV caching survives human review pauses between coding turns.

05
intermediate

90% Context Budget Manager & Auto-Compaction.

Why this matters: Keep multi-hour debugging sessions within token limits without losing active bug context.

Think of 90% Context Budget Manager & Auto-Compaction as the intuition layer for Design a Distributed Agentic CLI Coding Platform (Claude Code): Keep multi-hour debugging sessions within token limits without losing active bug context.

The CLI tracks exact token counts from API usage headers (input_tokens + cache_read_tokens). At 90% of the model's window, the Context Budget Manager runs a two-phase compaction: first replacing older tool_result blobs (>1,000 tokens) with [pruned: path/lines], then invoking a structured compaction prompt to distill older turns into a dense engineering handoff summary.

Stage 5 - Context Budgeting

Two-Phase Auto-Compaction Pipeline

Token BudgetMonitorrouterTool Blob PrunerprocessorCompaction SummarycacheResumed SessionsinkSummarize old turns

1.Preserve Invariants: Never compact the system prompt, active task checklist, or latest error trace.

2.Deterministic Trigger: Compact proactively at 90% so the next tool output never hits a hard 400 error.

Proactive two-phase compaction prevents mid-task context overflow.

06
advanced

Parallel MCP Subagent Spawner & Shared Repo Cache.

Why this matters: Accelerate large-monorepo investigations with concurrent read-only subagents.

Think of Parallel MCP Subagent Spawner & Shared Repo Cache as the intuition layer for Design a Distributed Agentic CLI Coding Platform (Claude Code): Accelerate large-monorepo investigations with concurrent read-only subagents.

When asked to trace an end-to-end bug across frontend, API, and database layers, the CLI spawns 3 concurrent read-only subagents. Each subagent shares the local read-only AST/ripgrep index and connects to scoped MCP servers (e.g., Sentry, Datadog, GitHub), returning structured summaries that the main agent synthesizes into a single coordinated patch.

Stage 6 - Parallel Subagents

Concurrent MCP Subagent Fan-Out

Main Agent LoopsourceFrontend ExplorerprocessorBackend ExplorerprocessorCoordinated PatchsinkCheck API + Sentry

1.Bounded Concurrency: Cap parallel subagents (e.g., 4) to respect org TPM/RPM rate limits.

2.Shared Prefix: Subagents share the same base tool prefix, hitting the cloud KV cache.

Concurrent read-only subagents cut monorepo investigation wall-clock time by 3x.

07
advanced

Headless CI/CD Mode, Webhook Triggers & Fleet Telemetry.

Why this matters: Run the same agentic harness unattended in GitHub Actions for PR review and test fixing.

Think of Headless CI/CD Mode, Webhook Triggers & Fleet Telemetry as the intuition layer for Design a Distributed Agentic CLI Coding Platform (Claude Code): Run the same agentic harness unattended in GitHub Actions for PR review and test fixing.

With --headless --output-format json, the CLI runs non-interactively in CI runners: no TUI, strict read/test allowlists, and a hard dollar/turn budget cap (--max-turns 15 --max-budget-usd 1.50). Structured JSON outcomes (patch diff, test pass status, token cost) post directly back to the PR via GitHub Apps.

Stage 7 - Headless CI Mode

Unattended CI/CD Agent Runner

GitHub PR WebhooksourceHeadless CLIContainerprocessorHard Cost & TurnCaprouterPR Review / FixCommitsinkEnforce spend cap

1.Budget Safety: Hard USD and turn caps prevent runaway CI loops on flaky tests.

2.Ephemeral Containers: CI containers destroy all state after posting the PR diff.

Headless mode extends the exact same local harness to automated CI/CD PR workflows.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why must file reading, ripgrep search, and test execution run locally on the developer's machine rather than in the cloud?

Recommended Learning Flow