Skip to main content
Sterlites Logo
AI Architecture
Dec 1, 202616 min read
1,013
Rohit Dwivedi
Rohit Dwivedi·Founder & CEO

Demystifying the Invisible Engine Behind AI Coding Agents

TL;DR

Frontier LLMs are completely stateless and memoryless between turns. The software harness wrapping the model (managing context boundaries, KV prompt caching, and deterministic execution cages) dictates up to 90% of your coding agent's cost, latency, and production reliability.

Scroll to dive deep

1. The Amnesiac Genius in Your Terminal

Imagine hiring a world-class architect capable of designing breathtaking, structurally flawless skyscrapers in their head, who suffers from complete, 10-second memory loss between thoughts. The moment they finish drawing a single doorframe, their mind wipes entirely blank.

To get any building designed, this genius relies on an assistant standing at their side. Before every single pencil stroke, the assistant must re-read an ever-growing stack of sticky notes from top to bottom, reminding the architect who they are, what building they are drawing, what tools are on the desk, and what lines were drawn ten seconds ago.

System Architecture Flowchart

This is the non-negotiable reality of modern artificial intelligence. Underlying frontier models are entirely memoryless. Every time you ask a question, the software wrapped around the core model must package your entire conversation history, project rules, target files, and tool definitions, sending that entire payload back across the wire from scratch.

A common novice pattern is treating the system like a magic, interactive chatbox. A developer leaves a single session open for days, watching simple requests turn into endless, circular loops that silently turn a $0.50 task into a $15 to $20 compounding line-item on the corporate API bill. Meanwhile, master engineering teams leverage the invisible software shell surrounding the core model: the agentic harness. By letting this harness manage context boundaries, prune discarded thoughts, and enforce strict execution guardrails, they ship clean code at one-tenth the cost.

Upgrading to a newer, “smarter” foundational model will not fix a broken workflow. If the software harness feeds the model cluttered context, traps it in blind retry loops, and leaves memory unmanaged, even the most powerful intelligence on earth will stumble and fail.

2. Five Doors of Understanding

Door 1: The Amnesiac Chef & The Recipe Binder (Beginner Level)

To understand how an automated coding assistant actually executes work turn-by-turn, step inside a high-end restaurant kitchen run by an amnesiac head chef.

The chef possesses master-level culinary skills, but every time they finish chopping one onion, their memory resets completely. To keep dinner service moving, a kitchen assistant stands by holding a heavy recipe binder. Before the chef can chop a second onion, the assistant must open the binder to Page 1 and re-read every single past instruction, ingredient list, and completed step all the way through Page 50.

System Architecture Flowchart

When you issue a simple command in your terminal like “fix this bug,” you might assume the assistant makes one quick decision. In reality, that single command silently triggers twenty hidden trips back and forth across the kitchen. For every single action (looking at a file, tweaking a line, running a check), the assistant must open the binder, reading every single past page from the very first word to the last.

Door 2: The Cluttered Countertop & The Interns (Junior Developer Level)

As dinner service progresses, a physical crisis emerges on the prep table: Countertop Bloat.

Imagine the amnesiac chef dropping discarded onion peels, raw vegetable scraps, stained rags, and heavy culinary encyclopedias directly onto the main workspace after every step. Eventually, the table is so piled with physical trash and heavy books that the chef has no physical surface left to slice a single tomato.

System Architecture Flowchart

To prevent this collapse, smart kitchens introduce The Interns. Instead of piling trash on the main countertop, the head chef hands a fresh, blank clipboard to a specialized runner. The chef sends the runner to the back pantry to fetch one specific measurement, write down only that single number, and deliver the clean note back. The moment the runner hands over the answer, they leave the room. The main countertop stays completely spotless, allowing the chef to work without drowning in clutter.

Door 3: Three Philosophies of the Machine (Software Engineer Level)

Moving from physical intuition to production software architecture, modern coding agent harnesses split into three distinct engineering archetypes:

System Architecture Flowchart

Archetype 1: The Minimalist Bloodhound (Claude Code & OpenAI Codex CLI)

This architecture prioritizes terminal-native speed, local instruction files, and aggressive context compaction over heavy visual overlays.

  • Claude Code: Built around a monolithic ReAct loop operating over a 5-stage pre-request compaction pipeline (Tool Result Budget -> Snip Compact -> Microcompact -> Context Collapse -> Auto-Compact). It reads persistent project memory from ~/.claude/projects/<path>/memory/MEMORY.md, uses ephemeral prompt caching, and slashes upfront token overhead by 85% by deferring tool schema injection via MCPSearch.
  • OpenAI Codex CLI: Powered by a lightweight Rust harness (codex-rs), it enforces hierarchical scope precedence by reading instruction chains from global ~/.codex down to subdirectory levels (AGENTS.override.md taking precedence over AGENTS.md). It routes tool calls through a dedicated dual-model Guardian safety architecture (gpt-5.4) to audit command execution safety, applying code edits deterministically via an apply_patch diff primitive.

Archetype 2: The Compiler-Wired Engine (OpenCode & Aider)

This architecture wires the LLM directly into background compilation and parsing diagnostics.

  • OpenCode: A Go-based TUI supporting multi-provider routing (75+ backends via Vercel AI SDK) with distinct Build (write) and Plan (read-only) agents. The moment a file is modified, it fires an automated LSP.touchFile() event, extracts compiler diagnostics via LSP.diagnostics(), and feeds type errors back into the context for autonomous self-correction. Architectural Trade-off: OpenCode loads all connected Model Context Protocol (MCP) tool schemas upfront into the system prompt, which can inject up to 171KB (~8,000+ tokens) of bloat before a user types a single word.
  • Aider: Uses Tree-Sitter parsing to construct concrete Abstract Syntax Trees (AST). It computes codebase symbol graphs and applies Personalized PageRank algorithms, using a 50x multiplier for chat-file references, to rank symbol importance and project dynamic repository maps into the context window.

Archetype 3: The Mission Control Tower (Google Antigravity & Cursor)

This archetype moves past terminal threads into visual multi-agent command centers.

  • Google Antigravity (AGY): Driven by a Go binary (agy) using workspace isolation flags (--gemini_dir <workspace>/.antigravity) to prevent mutating global ~/.gemini/ configurations. It provisions clean-slate background subagents inside isolated Git worktrees, tails session logs in real time, and manages visual artifacts (task plans, diff reviews, and browser recordings). See our full Google Antigravity evaluation for a deeper architectural breakdown.
  • Cursor: Combines visual IDE integration with hybrid vector and graph retrieval, multi-root workspace navigation, and background subagents running across cloud worker pools.
Busting the #1 Developer Myth

The Myth: “Keeping one continuous chat thread open all week helps the AI get to know my project better.” The Reality: Continuous long-running chat threads cause catastrophic context rot. As raw tool outputs, stale file dumps, and conversational fluff accumulate, prompt context bloats. This degrades reasoning quality, increases hallucination rates, and drains API budgets by re-transmitting thousands of irrelevant tokens on every turn.

Thinking about AI Architecture? Our team has helped 100+ companies turn AI insight into production reality.

Door 4: The Photocopy Tax & The 5-Minute Clocks (Senior Systems Engineer Level)

Understanding why long agent runs suddenly become expensive requires breaking down token economics and Key-Value (KV) prompt cache mechanics.

Token Economics: The Triangular Token Burn

Foundation model APIs are stateless. You pay for every token sent in plus every token generated out. Because the software harness must re-transmit the entire conversation binder on every turn NN, the total token volume scales quadratically as an arithmetic sum:

Total Tokens Processed≈N×(N+1)2×Average Turn Length\text{Total Tokens Processed} \approx \frac{N \times (N + 1)}{2} \times \text{Average Turn Length}

If each turn adds file context and tool results, Turn 20 does not cost 1x. It re-reads Turns 1 through 19, turning a linear interaction into compounding credit-card billing.

The Warm Photocopy Plate (Prefix KV Caching)

To prevent API billing from exploding under triangular growth, providers use Prefix KV Caching.

Think of KV caching like a pre-heated photocopy machine plate. If the top of your request payload (system instructions, tool schemas, and repository maps) remains 100% identical byte-for-byte, the API server reuses the warm plate instantly. This skips re-processing those initial tokens, yielding up to a ~90% cost discount and lower response latency.

System Architecture Flowchart

The 20-Block Boundary & Token Thresholds

Prompt caching is governed by rigid API mechanics:

  1. Minimum Token Thresholds: Cache activation requires a minimum prefix length: 1,024 tokens for Claude Sonnet, 2,048 tokens for Claude Haiku, and 512 tokens for Claude Opus 5.5.
  2. The 20-Block Lookback Boundary: In extended tool-use sessions generating more than 20 content blocks (tool_use / tool_result), Anthropic’s prompt cache evaluation breaks unless explicit breakpoints are inserted every 15 blocks.

The 5-Minute Cold Expiry

Cached prefix plates carry a strict 5-minute Time-To-Live (TTL) clock. Every time an agent turn executes and hits the cache, the 5-minute timer resets. However, if you pause to review code or step away for coffee for 5 minutes and 1 second, the cache plate goes cold. Your next turn incurs a 100% full-cost recompute penalty.

The 3 Silent Cache-Busters

Even within the 5-minute window, subtle harness state changes instantly break exact-byte prefix matching, invalidating downstream cache plates:

  1. Mid-Chat Model Switching: Toggling from a fast model to a reasoning model mid-session changes the system prefix, busting the cache plate.
  2. Dynamic Tool Plugin Toggling: Enabling or disabling an MCP server mid-session alters the structured tool definition block near the top of the prompt.
  3. Modifying System Rules Mid-Stream: Editing early instruction files (like CLAUDE.md or AGENTS.md) alters text near the beginning of the payload, forcing a total re-computation of the entire thread.

Door 5: The Unsolved Frontier of Agentic Runtimes (AI Architect Level)

The Million-Line Wall: Graph Traversal vs. Context Dumping

As context windows expand to 1M+ tokens, a common assumption is that repository indexing is obsolete. In practice, massive context windows suffer from attention decay and lossy compaction. When forced to digest raw multi-megabyte codebase dumps, transformer attention mechanisms experience “needle-in-a-haystack” degradation, missing subtle logic dependencies across distant files.

External memory layers like mem0 and topological AST graph traversal (PageRank) remain strictly superior to raw context dumping. They enforce deterministic relevance before the LLM is invoked.

Deterministic Cages vs. Probabilistic Reasoning

Enterprise security requires enclosing probabilistic reasoning inside deterministic execution cages. Models generate probabilistic text predictions; they cannot be trusted to execute system changes without oversight. Modern runtimes enforce multi-layer containment:

System Architecture Flowchart
  • OS-Level Isolation Primitives: Runtimes utilize unprivileged Linux sandboxes (bubblewrap, Landlock + seccomp) or macOS Seatbelt to block unapproved network egress and file access. Next-generation systems leverage sub-100ms microVM sandboxes (libkrun / microsandbox).
  • Guardian Safety Models: Routing proposed tool actions through dedicated safety review passes (such as Codex CLI using gpt-5.4 as a Guardian model) to audit command safety before execution.
  • Deterministic Validation Loops: Automatically executing syntax checks (LSP.touchFile()) and test suites to confirm state changes before finalizing a turn.

Context Retention Dynamics

The mathematical relationship governing effective context retention versus prompt length is expressed as:

Effective Context Retention=∑i=1Kwi⋅Silog⁡2(Total Context Length+e)\text{Effective Context Retention} = \frac{\sum_{i=1}^{K} w_i \cdot S_i}{\log_2(\text{Total Context Length} + e)}

Where SiS_i represents key code symbols, wiw_i represents their topological PageRank graph weight, and total context length acts as a logarithmic dampener. In plain English: as raw prompt length expands, true information retention drops logarithmically unless input context is strictly pruned down to high-density, topologically relevant code symbols.

3. The Grand Harness Translation Matrix

Harness & ArchetypeReal-World MetaphorArchitectural SuperpowerWhere It Wins vs. Bleeds Tokens
Claude Code (Monolithic ReAct)A disciplined master craftsman with an efficient filing assistant.5-Stage Pre-Request Compaction, ephemeral prompt caching, persistent memory at ~/.claude/projects/.../MEMORY.md, and deferred Tool Search (MCPSearch).Wins: Sustained single-repo sessions yielding 85%+ prompt cache savings. Bleeds: Rapid requests spaced greater than 5 minutes apart, triggering cold TTL cache expirations.
OpenCode (Compiler-Wired)An expert developer working alongside a real-time syntax checker.Live LSP Diagnostic Feedback via LSP.touchFile() and LSP.diagnostics(), dual Build/Plan agents, multi-provider routing across 75+ backends.Wins: Catching type mismatches and broken imports instantly before returning control. Bleeds: Unmanaged MCP setups, where upfront tool schema loading injects up to 171KB (~8,000+ tokens) on turn 1.
Google Antigravity (AGY) (Mission Control)A general contractor delegating sub-tasks to isolated work crews.Workspace Subagent Isolation using the agy Go binary and --gemini_dir flag, executing subagents inside isolated Git worktrees with visual status artifacts.Wins: Complex multi-repo refactoring without polluting the main working tree or chat history. Bleeds: High aggregate token burn across multiple concurrent subagents on minor single-file edits.
OpenAI Codex CLI (Minimalist Bloodhound)A security-conscious engineer operating under strict policy enforcement.Hierarchical AGENTS.md Scope Chains, dual-model gpt-5.4 Guardian safety architecture, and exact apply_patch diff primitives in Rust (codex-rs).Wins: Enforcing enterprise compliance, scoped project rules, and high-safety sandboxed execution. Bleeds: Extended multi-turn exploration loops without explicit step limits.
Cursor / Aider / Cline (Hybrid Repomap & IDE)A structural surveyor mapping out blueprints before construction starts.Personalized PageRank + AST Parsing with a 50x chat-file multiplier (Aider); hybrid Graph + Vector retrieval (Cursor); LLM-initiated /condense compaction (Cline).Wins: Surfacing exact cross-file symbol references across complex codebases prior to editing. Bleeds: Manually dumping full source files into active chat scope instead of using targeted retrieval.

Architectural Trade-Offs Across Agent Runtimes

Harness selection dictates token economics and safety boundaries far more than the underlying foundation model.

4. The Sterlites Perspective: Harness Governs Intelligence

At Sterlites, we formalize this architectural shift under a single governing principle: Harness Governs Intelligence. Rather than chasing marginal benchmark gains between frontier models, engineering leaders must invest in the recursive harness layer that controls context, caching, and execution.

The future of enterprise software engineering does not belong to the organization with the largest foundation model. It belongs to those who construct deterministic execution cages where autonomous intelligence compounds reliably, enforcing strict token budget control, security blast-radius containment, and zero context rot.

Rohit DwivediFounder & CEO, Sterlites

Frequently Asked Questions

5. The Frontier Ahead

Looking forward, agentic coding harnesses are poised for three major architectural shifts over the next 24 months:

  1. Zero-Overhead Ephemeral Tool Discovery: Monolithic system-prompt tool loading will give way to dynamic, regex/BM25-indexed tool discovery (MCPSearch). Runtimes will fetch tool schemas on demand only when an agent requests them, reducing upfront context overhead to near zero.
  2. Local MicroVM Sandboxing by Default: OS isolation will transition from user permission prompts to local microVM runtimes (such as libkrun / microsandbox). Agents will spin up sub-100ms isolated microVM sandboxes on demand, executing untrusted code and testing network calls without exposing the host OS.
  3. Self-Healing Deterministic Feedback Loops: Harnesses will increasingly enclose probabilistic models inside automated validation loops, addressing the enterprise code review bottleneck. Code edits will trigger real-time compiler diagnostic hooks (LSP.touchFile()), linters, and unit tests, feeding diagnostic errors back to the agent for autonomous self-correction before human review.

Sources & Citations

Verified SourceAnthropic Prompt Caching Documentation
Verified SourceAider Repository Map & Tree-Sitter PageRank
Verified SourceOpenAI Codex CLI Repository

Give your network a competitive edge in AI Architecture.

Establish your authority. Amplify these insights with your professional network.

One-Tap Distribution