Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Claude Code Architecture Deep Dive: 98.4% Deterministic Engineering Behind a Production AI Agent

This article analyzes a Hong Kong University paper dissecting Claude Code's architecture, revealing that its production-grade AI agent relies on a simple while-loop surrounded by deterministic engineering—context governance, permission systems, extensibility layers, and persistence—rather than complex AI decision logic.

What the Paper Studies

The paper "Dive into Claude Code: The Design Space of Today's and Future AI Agent Systems" from Hong Kong University's VLA lab (arXiv, April 14) analyzes the leaked Claude Code v2.1.88 source code. It performs a design-space analysis rather than a product review, doing three things: (1) dissecting Claude Code's architecture layers, key mechanisms, and design trade-offs; (2) contrasting with open systems like OpenClaw to show how deployment environments push agents toward different architectural answers; (3) raising open problems for future agent systems such as long-term memory, cross-session continuity, observability, governance, and human capability retention.

The paper identifies four unavoidable architectural questions for any production AI agent system:

Where does reasoning live—in the model or in a workflow framework?

Should the execution engine be unified or split by scenario?

What is the default safety posture—allow-first or deny-first?

What is the scarcest resource—compute, permissions, or context window?

Claude Code's answers are distinct: reasoning stays with the model while the system handles constraints and execution; all entry points share a single core agent loop; safety uses deny-first; and the context window is treated as the primary scarce resource with multi-layer compression and recovery mechanisms.

Core Insight: The Agent Loop Is a Simple While-Loop

The paper's most striking finding: Claude Code's core agent loop is just a simple while-loop. Only about 1.6% of the codebase implements AI decision logic; the remaining 98.4% is deterministic system engineering. The loop performs these steps each turn:

Read current context.

Let the model decide the next action.

If a tool call is needed, route it through the permission system.

Execute the tool and feed results back into context.

Repeat until the task ends.

The external harness handles context assembly, model invocation, tool-call parsing, permission adjudication, tool execution, result collection, and continuation decisions. This design avoids complex planners, explicit state graphs, or heavy orchestration frameworks, instead giving the model autonomy within a constrained, well-governed runtime.

Overall Architecture: 7 Components, 5 Subsystem Layers

The paper decomposes Claude Code into seven high-level components that form a production-grade agent loop:

User

Interaction Interface

Agent Loop

Permission System

Tool System

State & Persistence

Execution Environment

These map to five subsystem layers—Surface, Core, Safety/Action, State, Backend—which align with real agent problem boundaries: who assembles context, who approves actions, who executes, who guarantees recovery.

Key Layer Details

Interface Layer: Interactive terminal, headless CLI, SDK, IDE/desktop integrations all converge on a single queryLoop, eliminating behavioral drift across entry points.

Agent Loop Layer: Acts as a runtime coordination hub (like an OS scheduler), not a complex policy center.

Permission & Safety Layer: Multi-layered defense including tool pre-filtering, deny-first rule evaluation, permission-mode gating, an ML classifier in auto mode, shell sandbox, session-recovery trust reset, and hook interception—seven layers embodying defense-in-depth.

Tool Layer: Unifies built-in tools, MCP tools, Skills, Plugins, and Hooks; focus is on low-side-effect, auditable, trimmable exposure to the model.

State & Persistence Layer: Uses JSONL transcripts, history, subagent sidechains, and file-based memory—preferring simple, transparent filesystem representations over opaque databases.

Turn Pipeline: 9 Steps with Critical Pre/Post Model Governance

Each turn executes a 9-step pipeline:

Parse setup

Initialize state

Assemble context

Execute 5-layer pre-processing compression

Invoke model

Dispatch tool calls

Enter permission gate

Execute tools

Check stop conditions

Pre-Model: Context Governance via Progressive Degradation

Before every model call, five compression layers run sequentially, embodying an engineering principle: use cheap, local, reversible compression first; escalate to heavier, lossy compression only when necessary.

Budget Reduction

Snip

Microcompact

Context Collapse

Auto-Compact

This progressive degradation strategy preserves information integrity as long as possible, avoiding the common agent failure mode where aggressive summarization destroys evidence chains needed for multi-file debugging or iterative repair.

Post-Model: Action Governance with Dual Execution Paths

After model output, tool calls pass through scheduling, permission checks, and execution-path selection. Two paths exist: a streaming tool executor for latency reduction, and a fallback path that classifies calls by concurrency safety. The system prioritizes continuous closed-loop operation over single-shot reasoning.

Permission System: A Tiered Trust Spectrum, Not a Binary Switch

Claude Code implements seven permission modes forming an evolvable trust spectrum :

plan
default
acceptEdits
auto
dontAsk
bypassPermissions

Internal bubble mode

Default posture is deny-first : deny always overrides allow; strict rules take precedence. This contrasts with many systems that allow by default and only block on explicit matches. The paper notes that safety layers can share failure modes—e.g., when safety analysis becomes too expensive or slow, the system may skip checks to avoid REPL stalls, revealing that safety is not about layer count but about whether layers function under real load. The paper also highlights CVE-exposed "pre-trust window" issues where extensions or MCP components execute initialization logic before user consent dialogs appear.

Context as the Primary Resource Constraint

Claude Code treats the context window as a first-class resource requiring continuous governance. Context is assembled from nine ordered sources:

System prompt

Environment info

CLAUDE.md hierarchical instructions

Path rules

Auto memory

Tool metadata

Conversation history

Tool results

Compression summaries

This makes Claude Code a context assembly system , not merely a chatbot plus tool caller.

CLAUDE.md: Soft Constraints as User Context

CLAUDE.md operates at four levels (system, user, project, local) as editable, version-controlled files. Crucially, they are injected as user context , not as hard system-prompt constraints. This separates soft preferences (habits, project conventions) from hard boundaries enforced by the permission and rule systems—a mature layering that avoids the unreliability and unauditability of stuffing all constraints into prompts.

Memory: Transparent File-Based, Not Vector Black Box

Memory relies on file-header scanning and LLM selection of relevant memory files. Advantages: transparent, editable, version-controllable, no embedding infrastructure. Trade-off: weaker complex knowledge retrieval vs. dedicated memory stores, but a deliberate engineering choice favoring understandability, controllability, and auditability.

Extensibility: Layered Injection by Context Cost

Four extension mechanisms form a cost-graded spectrum:

Hooks – lowest context cost; lifecycle interception.

Skills – inject capability descriptions into current context.

Plugins – system-level product capability extensions.

MCP Servers – formally integrate external tools/services into model-callable space.

The paper abstracts three injection points that clarify all agent extension decisions: assemble() – decides what the model sees model() – decides what the model can reach execute() – decides how actions run

This separation prevents the chaos of conflating context supplementation, capability exposure, and execution governance.

Subagents: Context Isolation, Not Parallel Cleverness

Subagents address single-context-window overload. Two distinct mechanisms: SkillTool – injects capabilities into current context (cheap, but pollutes context). AgentTool – spawns an isolated new context (expensive, but strong isolation).

Subagents are not the default path; they are a costly but reliable isolation mechanism when the main context is too crowded. Each subagent maintains an independent transcript; only summaries return to the parent, avoiding the common multi-agent failure of context explosion.

Persistence: Append-Oriented Design for Auditability

Three persistence channels:

Main session transcript

Global prompt history

Subagent sidechain transcript

All are append-only / mostly append-only JSONL—human-readable, tool-friendly, incrementally writable, no complex storage dependency. A critical security design: session recovery does not restore prior permission state. Trust is session-scoped, not persistent; users must re-establish authorization each session, sacrificing seamlessness for the invariant that historical trust cannot cross new context boundaries.

Values and Design Principles as Architectural Interpreter

The paper articulates five human values that explain nearly every architectural choice:

Human Decision Authority → deny-first, permission escalation, audit visibility

Safety, Security, and Privacy → multi-layer defense, sandbox, trust reset

Reliable Execution → heavy investment in recovery, verification, compression, persistence

Capability Amplification → model autonomy over rigid rule graphs

Contextual Adaptability → CLAUDE.md, Skills, Hooks, MCP as gradually injectable layers

These values make the architecture a coherent value-driven system, not an ad-hoc bag of tricks.

What Is Truly Hard to Replicate: The Harness, Not the Loop

The paper's pivotal judgment: the hard part to copy is not the while-loop but the cross-subsystem harness. Prototypes are easy—wire a model, add tools, loop. Production systems hit:

Context explosion

Noisy tool returns

User authorization fatigue

Session recovery state decisions

Multi-agent context pollution

Plugin/MCP initialization control

Security checks skipped under performance pressure

These collectively form the real production barrier.

Open Problems the Paper Identifies

Observability–evaluation gap: Traces exist, but turning them into signals that detect silent agent errors remains open.

Cross-session memory: Between project instruction files and single-session transcripts, a robust long-term state layer is missing.

Horizon scaling: Mechanisms optimized for single-session, medium-length tasks may not suffice for multi-day complex programs.

Governance & external compliance: Future enterprise/regulated deployments will need external audit logs, disclosure, and human oversight interfaces.

Human capability retention: Short-term productivity gains are clear, but long-term effects on developer understanding, codebase consistency, and skill growth lack explicit mechanisms.

Practical Takeaways for Agent Builders

Build the harness first. Solidify permissions, context, recovery, tool governance before chasing complex agent cognition.

Treat context as a resource management problem. Context overflow is the norm; implement layered compression, progressive degradation, and reversible strategies.

Design safety for real load. Watch for shared failure modes, initialization windows, and performance-induced safety degradation.

Layer extensibility by cost. Not every external capability should be a model-callable tool; some belong in context injection, some in lifecycle hooks.

Multi-agent value lies in isolation. Subagents shine at isolating complex tasks to protect the main thread, not at running many agents simultaneously.

The article concludes that Claude Code's greatest lesson is not how much the model does, but how a restrained, pragmatic, precise operating system built around the model enables reliable production deployment. The so-called "engineering details" are the true boundaries of system capability.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

PersistenceExtensibilitySystem EngineeringPermission SystemContext ManagementClaude CodeSubagentsAI Agent ArchitectureHarness EngineeringProduction AI Agents

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion