Skip to main content
← CONCEPTS / AI-MACHINE-LEARNING
An end-to-end domain learning journey

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.
Start the journey7 sections· Last modified Nov 24, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If model quality drifts from offline training baselines, keep the harness thin and deterministic: isolate side effects in an OS sandbox, enforce explicit permission gates on writes/exec, and preserve prompt-cache prefixes across tool iterations.

TL;DR30-second simplified summary
▾

Production CLI harnesses balance autonomy with token efficiency and safety. A Tree-sitter + PageRank repo map gives global codebase context in ~2K tokens, while ripgrep and line-bounded reads fetch only needed slices.

Placing static instructions, tool schemas, and the repo map at the front of the prompt unlocks >85% provider prompt-cache hits. When context hits 85-90%, two-stage compaction prunes stale tool logs before summarizing older turns, and exact hunk patches with shadow Git snapshots ensure atomic rollback.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Autonomous Agent Execution Harness
An Autonomous Agent Execution Harness wraps non-deterministic LLM reasoning inside a durable finite state machine with step-level checkpointing, loop/budget guardrails, Firecracker MicroVM tool isolation, and deterministic replay.
AI/LLM Prefix Caching & RadixAttention (Zero-Copy KV Sharing)
RadixAttention indexes cached GPU KV-cache blocks in a compressed prefix trie (Radix Tree) with LRU eviction, enabling zero-copy prefix sharing across concurrent and sequential LLM requests.
Full walkthrough · 7 stages
01
foundation

The Terminal ReAct Loop & Structured Tool Schemas.

Why this matters: Connect LLM reasoning turns with deterministic local tool dispatch and streaming terminal rendering.

Think of The Terminal ReAct Loop & Structured Tool Schemas as the intuition layer for Agentic CLI Coding Harness Architecture: Connect LLM reasoning turns with deterministic local tool dispatch and streaming terminal rendering.

The CLI runs an event-driven loop: send messages + JSON tool schemas to the LLM, stream thinking/text deltas to an ANSI/TUI diff renderer, parse tool_use blocks, execute the local tool with a strict timeout, and append tool_result back to the message array. Bounded step limits (e.g., max 50 turns) and duplicate-call detectors prevent infinite edit-fail loops.

Stage 1 - Core Loop

Terminal ReAct Execution Cycle

Terminal REPL / TUIsourceLLM Reasoning APIprocessorLocal ToolDispatcherrouterLocal Repo ToolssinkInvoke tool_use

1.Thin Harness: Let the model plan dynamically rather than hardcoding rigid multi-step pipelines.

2.Streaming UX: Render unified color diffs inline as edits are proposed.

A thin ReAct loop lets the model iteratively read, edit, and test code until checks pass.

02
foundation

OS-Level Sandboxing & Permission Policy Gates.

Why this matters: Prevent arbitrary shell execution or prompt injection from damaging the host machine.

Think of OS-Level Sandboxing & Permission Policy Gates as the intuition layer for Agentic CLI Coding Harness Architecture: Prevent arbitrary shell execution or prompt injection from damaging the host machine.

Running an LLM-generated bash command directly on a developer laptop risks rm -rf, credential exfiltration, or network leaks. A Permission Policy Engine classifies every tool call into Read-Only (auto-allow), Workspace Write (ask once or session-allow), or Dangerous Exec (explicit user confirmation), while wrapping subprocesses in macOS sandbox-exec (Seatbelt) or Linux bubblewrap/seccomp with read-only root and blocked outbound network by default.

Stage 2 - Security Boundary

Permission Gate & OS Sandbox

Proposed Tool CallsourcePermission PolicyGaterouterSeatbelt / SeccompprocessorWorkspace DirectorysinkSpawn jailed process

1.Least Privilege: Deny reads of ~/.ssh, ~/.aws, and .env by default inside the sandbox.

2.Egress Control: Block arbitrary curl/wget unless explicitly allowlisted by the user.

Policy gates and OS sandboxes contain untrusted commands and prompt-injected tool calls.

Engineering Decision Framework
Problem
How to implement Agentic CLI Coding Harness Architecture 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 the harness thin and deterministic: isolate side effects in an OS sandbox, enforce explicit permission gates on writes/exec, and preserve prompt-cache prefixes across tool iterations.
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 Agentic CLI Coding Harness Architecture experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
intermediate

AST Repo Mapping & Targeted File Reading.

Why this matters: Give the agent global codebase awareness without stuffing 100K lines into the prompt.

Reading every file in a 5,000-file repository exhausts context immediately.

Instead, the harness builds a compact Repo Map using Tree-sitter AST parsing + PageRank over symbol references, fitting the most central classes, function signatures, and file paths into ~2,000 tokens.

Stage 3 - Codebase Indexing

Tree-Sitter AST Repo Map

Local Git ReposourceTree-Sitter ParserprocessorSymbol Graph Rankercache2K-Token Repo MapsinkScore symbol centrality

1.Fast Discovery: ripgrep + AST symbol maps cut file-search turns by 3x-5x.

2.Line-Bounded Reads: Cap single file reads (e.g., 400 lines) to avoid accidental 50K-token log dumps.

Tree-sitter AST maps give structural navigation in ~2K tokens instead of full-repo dumps.

04
intermediate

Prompt-Prefix Caching & Deterministic Cache Alignment.

Why this matters: Slash API cost and TTFT by 80% across 20-turn coding sessions.

Think of Prompt-Prefix Caching & Deterministic Cache Alignment as the intuition layer for Agentic CLI Coding Harness Architecture: Slash API cost and TTFT by 80% across 20-turn coding sessions.

A 25-turn debugging session re-sends the system prompt, tool definitions, repo map, and earlier turns on every iteration. Placing static instructions, tool schemas, and CLAUDE.md project rules at the exact byte-for-byte start of the prompt—with explicit cache_control breakpoints—lets the LLM provider serve 85%+ of input tokens from KV-prefix cache at 10x lower cost and 3x faster TTFT.

Stage 4 - Prompt Caching

Immutable Prefix Cache Layout

Static Prefix BlockcacheRepo Map BreakpointcacheDynamic Turn TailsourceProvider KV CachesinkAppend new turn

1.Never Mutate Prefix: Avoid injecting changing timestamps or random IDs into the system prompt.

2.Tool Schema Stability: Keep tool list order identical across turns to prevent cache invalidation.

Strict prefix immutability turns multi-turn agent loops into cheap KV-cache hits.

05
intermediate

Auto-Compaction & Context Budget Management.

Why this matters: Prevent context overflow during marathon refactoring sessions without losing critical state.

Think of Auto-Compaction & Context Budget Management as the intuition layer for Agentic CLI Coding Harness Architecture: Prevent context overflow during marathon refactoring sessions without losing critical state.

When cumulative tokens approach 85-90% of the context window, the harness triggers Auto-Compaction before the next LLM call. Old verbose tool_result outputs (like 500-line test logs) are pruned first; if still over budget, a fast summarizer model condenses earlier turns into a structured state brief (modified files, failing tests, architectural decisions) while keeping the last few turns verbatim.

Stage 5 - Context Compaction

90% Window Auto-Compactor

Token Usage TrackerrouterTool-Output PrunerprocessorState SummarizercacheCompacted HistorysinkSummarize old turns

1.Lossless Anchors: Always preserve exact file paths, symbol names, and current error stack traces.

2.User Visibility: Notify the terminal user cleanly when compaction runs.

Two-stage pruning and structured summarization keep long coding sessions coherent.

06
advanced

Atomic Patching & Shadow Git Rollback Snapshots.

Why this matters: Guarantee clean, conflict-free file edits and instant one-command undo.

Asking an LLM to rewrite an entire 800-line file wastes output tokens and risks silent deletions.

Instead, the edit_file tool requires exact search-and-replace hunks (old_string -> new_string) verified against a pre-edit file hash/mtime to prevent stale overwrites.

Stage 6 - Safe File Edits

Search-Replace Patch & Shadow Git Tree

Exact Hunk PatchsourceMTime/Hash GuardrouterShadow Git IndexcacheAtomic File WritesinkSave pre-edit tree

1.Atomic Undo: Shadow Git trees capture snapshots without polluting the user's real git history.

2.OCC Protection: Reject edits if the user modified the file in their IDE concurrently.

Exact hunk matching and shadow Git trees make agentic edits fast and safely reversible.

07
advanced

Parallel Subagent Fan-Out & Headless MCP Integration.

Why this matters: Delegate noisy codebase exploration to isolated subagents without polluting main context.

Think of Parallel Subagent Fan-Out & Headless MCP Integration as the intuition layer for Agentic CLI Coding Harness Architecture: Delegate noisy codebase exploration to isolated subagents without polluting main context.

When an agent needs to investigate 4 different microservices, reading 30 files in the main loop fills the context window with irrelevant code. The harness spawns isolated read-only subagents with their own fresh context windows and MCP tool servers (GitHub, Jira, Postgres schema), returning only concise 500-token findings summaries to the parent agent.

Stage 7 - Subagent Delegation

Isolated Read-Only Subagent Fan-Out

Parent Coding AgentsourceSubagent: AuthSearchprocessorSubagent: DB SchemaprocessorConcise FindingssinkQuery schema via MCP

1.Context Isolation: Subagents discard raw file dumps and return only verified file:line citations.

2.Read-Only Default: Parallel subagents run read-only tools to avoid concurrent write races.

Subagent fan-out keeps the main agent's context focused on synthesis and implementation.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does an agentic CLI coding harness place the system prompt, tool definitions, and AST repo map at the very beginning of the prompt without dynamic timestamps?

Recommended Learning Flow