claude-code-from-source / field guide
Deep-dive deck · September 2026

How a production coding agent thinks.

A practical tour of Claude Code from Source: the architecture, patterns and trade-offs behind a serious agentic CLI.

18 chapters · 7 parts Educational pseudocode Build your own mental model
01 · TL;DR

It’s a field guide to the machinery around an LLM.

The repo is not Claude Code source. It is an independent educational reconstruction of the patterns that make an agentic coding tool useful, safe and fast.

↗

Plain-English takeaway: the model is only one component. The durable advantage comes from the loop around it: tools, permissions, state, memory, concurrency, interfaces and recovery.

01 / SEE

Understand the system

Trace a request from keystroke to model stream, tool call, permission decision and final output.

mental model
02 / STEAL

Reuse the patterns

Take the transferable pieces: async generators, fail-closed tools, prompt-cache-aware forks and layered context compression.

architecture
03 / BUILD

Implement a smaller version

Use the how-to section as a sequence for building a safe, observable agent shell in your own stack.

practice
Source: README.md · purely educational
02 · Why it matters

Use it when an agent must do more than answer.

For builders

Design an agent that can inspect a codebase, call tools, recover from errors, and keep a human in the loop when risk rises.

Example → build a repo-aware coding assistant with a Bash tool, file edits and test execution.

For technical leaders

Evaluate architectures beyond model quality: where are the trust boundaries, cost controls, extension points and failure modes?

Example → compare two agent platforms by their permission model and context economics.

For product teams

Turn “AI can code” into a usable workflow with observable progress, good terminal interaction and predictable stop conditions.

Example → prototype an internal developer experience for a multi-repo organisation.

For AI researchers

Study the system-level bets that determine agent behaviour in practice: memory selection, tool scheduling, and multi-agent coordination.

Example → define evals for autonomy, latency, safety and recovery, not just task success.
!

Boundary: the repository uses original pseudocode and analysis. Treat it as a pattern library, not as a drop-in clone or an authoritative description of Anthropic’s proprietary implementation.

01
Part I · Foundations

Before the agent can think, the process must exist.

Start with the shape of the system: the abstractions that make a language model into a working tool.

03 · The architecture

Six abstractions carry most of the weight.

01
Query loopStreams, calls tools, appends results, repeats until a terminal state.
02
Tool systemTyped action contracts with validation, permissions and rendering.
03
TasksBackground work and sub-agents with explicit state transitions.
04
StateInfrastructure state separated from reactive UI state.
05
MemoryPersistent context selected for relevance across sessions.
06
HooksLifecycle interceptors that can modify, block or extend behaviour.
User / REPLinput + display
Query loopstream · act · observe
Toolsside effects
Memoryrelevant context
Tasksrecursive work
Hooksintercept + govern
Source: book/ch01-architecture.md · six core abstractions
04 · Golden path

Every request is a controlled feedback loop.

The interesting part isn’t the first model response. It’s what happens after the model asks to act.

1 · PromptUser asks for a change in natural language.
→
2 · StreamModel response and tool-use blocks arrive incrementally.
→
3 · GovernValidate, classify, check hooks and resolve permissions.
→
4 · ActRun safe tools, collect results and preserve ordering.
→
5 · RepeatAppend results; the model decides whether it needs another turn.
⌁
Modelgenerates intent and tool calls
⚙
Tool executorruns with safety and budget controls
▣
Conversationstores messages and results

Why an async generator? The consumer pulls messages at its own pace, which gives the loop natural backpressure, cancellation and typed terminal states.

05 · Tools & permissions

Tools are not functions. They are governed capabilities.

A useful tool declares its input schema, output, concurrency safety, permission behaviour and progress surface.

✓

Fail-closed defaults: new tools run serially and are treated as writes unless they explicitly prove they are safe to parallelise or read-only.

One uniform path

Built-in tools and MCP tools pass through the same validation, permission, result-budgeting and error-handling path. That consistency is the safety feature.

01
Look up + validateResolve the tool, parse input, check semantic meaning.
02
PrepareStart a classifier; backfill derived input without mutating the original.
03
GovernRun hooks, rules, tool checks and mode-based permissions.
04
Execute or denyRun the action, budget results, fire post-hooks and classify errors.

The full repo describes this as a 14-step pipeline. The four blocks above are the useful implementation boundaries.

06 · Safety boundary

Make safety a mode, not a scattering of if-statements.

A named permission mode gives you a system-level answer to “what can this agent do right now?”

ModeBehaviourGood fit
planRead-only; deny mutations.Discovery, architecture, impact analysis.
defaultPrompt for unresolved operations.Interactive developer workflow.
acceptEditsAuto-allow file edits; prompt on other mutations.Fast local iteration with a human boundary.
autoUse a transcript-aware classifier for routine decisions.Semi-autonomous, observable background work.
bubbleEscalate a child agent’s decision to its parent.Coordinator / worker systems.
bypassPermissionsAllow everything without prompting.Internal testing only.
↗

Design implication: the permission resolver should be a first-class subsystem with rules, provenance, hooks, user prompts and audit events, not a boolean tucked inside each tool.

02
Part II · Core loop & scale

Make the loop fast enough, cheap enough and composable enough.

Once the agent can act safely, performance and coordination become product features.

07 · Agent loop

Context management is a ladder, not a single compact button.

The loop protects the context window by applying the lightest intervention that solves the immediate pressure.

Tool-result budgetLimit or persist oversized outputs before they flood the transcript.always on
Snip compactTrim low-value sections from large tool results.light
MicrocompactReplace stale tool results with compact references.medium
Context collapseSummarise a finished portion of the conversation.heavy
Auto-compactRebuild a smaller working context when thresholds are reached.last resort
↘

Product lesson: context pressure is user-visible latency and cost. Make compaction observable, reversible where possible, and tested against task continuity.

08 · Concurrency

Parallelise reads. Serialise risk.

SAFE TO OVERLAP

Speculative reads

Start concurrency-safe tools while the model is still streaming. If the final call changes, discard the speculative result.

latency win
KEEP ORDER

Serial writes

Writes and context modifiers wait for the right point in the queue. This preserves causality and prevents conflicting side effects.

safety boundary

Partition by input, not just tool name

One tool can be safe or unsafe depending on its input. ls and rm shouldn’t inherit the same concurrency classification merely because both arrive through Bash.

Read batchgrep · read · search
parallel
→
Write queueedit · git · deploy
ordered
09 · Multi-agent orchestration

Sub-agents are new loop instances, not magical exceptions.

01 / ISOLATE

Context

Give the child its own message history and deliberate visibility into the parent’s context.

02 / GOVERN

Permissions

Use bubble mode so dangerous requests travel back to a parent with a real user boundary.

03 / CLEAN UP

Lifecycle

Model resolution, hooks, skills, MCP, abort controllers, query loop and cleanup are explicit steps.

Choose the lightest coordination pattern

ForegroundParent waits for a child result.
BackgroundChild reports through progress channels.
CoordinatorParent decomposes work and dispatches workers.
SwarmPeers communicate through a mailbox and task registry.
↺

The strongest reusable idea is recursive sameness: a child agent should inherit the parent loop’s guarantees, while its context, tools and permissions are intentionally scoped.

10 · Prompt-cache economics

Parallel agents only pay off when they share the prefix.

Fork agents preserve a byte-identical prompt prefix, allowing multiple children to reuse the expensive shared context.

The design move

Freeze the parent’s rendered system prompt. Add a small fork marker. Let the child diverge only after the cached prefix.

Why it matters → less input-token cost and more predictable parallelism.
conceptual costshared prefix
parent contextchild-specific tail
95%

The README describes a roughly 95% input-token saving for byte-identical fork prefixes. Treat this as the repo’s reported design claim, not a universal benchmark.

Trade-off: cache stability can constrain dynamic prompt content. A few unstable fields, headers or reordered tools can invalidate the benefit.

11 · Persistence & extension

Memory gives continuity. Hooks give control.

MEMORY

Retrieve relevance, not keywords

Project, user and team memories are stored as files, indexed with metadata, then selected for the current task. An always-loaded index can point to deeper memories.

Useful pattern → human-readable files + machine-selected recall.
EXTENSIBILITY

Load light, execute deliberately

Skills use two-phase loading: discover cheap frontmatter first, load full instructions only when invoked. Hooks intercept lifecycle events and can modify or block execution.

Useful pattern → keep startup cheap and runtime boundaries explicit.
Session startscan files + frontmatter
→
Recallselect relevant context
→
Invokeload skill / run hook
→
Snapshotfreeze config for safety
03
Part III · Implementation guide

Build the smallest system that preserves the guarantees.

You don’t need 18 chapters to start. You do need the right order of operations.

12 · Blueprint

Start with the loop. Add capability only after the boundary is observable.

01

Define messages and terminal states. Make cancellation, max turns, budget exhaustion and errors explicit.

02

Build one self-describing tool. Schema, execution, permission check, concurrency flag and result budget.

03

Put every call through one resolver. Hooks → rules → tool check → mode → prompt.

04

Add result budgeting and compaction. Protect the model from your own tool output.

05

Expose progress, costs and decisions. If the human can’t see the boundary, they can’t trust it.

06

Add memory, skills, MCP and child agents. Each should reuse the same loop and governance path.

Pattern synthesis from: ch01 · ch06 · ch18
13 · Step-by-step build

Implement the core loop as a small, testable generator.

async function *runAgent(input, deps) {
  let messages = [userMessage(input)]

  for (let turn = 0; turn < MAX_TURNS; turn++) {
    messages = compactIfNeeded(messages, deps.budget)
    const stream = yield* callModel(messages, deps.client)
    const calls = extractToolCalls(stream)

    if (calls.length === 0)
      return { kind: "completed" }

    const results = yield* executeTools(calls, deps)
    messages = messages.concat(results)
  }

  return { kind: "max_turns" }
}
1
Inject dependencies.
Model client, tool registry, permission resolver, budget and clock.
2
Yield messages, not logs.
Let the REPL, SDK or headless runner decide how to render them.
3
Keep terminal states typed.
“Stopped” is not the same as “failed”. Preserve the reason.
4
Test the loop without a model.
Feed canned streams and tool results to exercise recovery paths deterministically.
⌘

This is deliberately pseudocode. The repo’s examples are educational; your implementation should make its own contracts explicit.

Source: ch05-agent-loop.md · pseudocode adapted for teaching
14 · Step-by-step build

Give every tool a contract the orchestrator can reason about.

type Tool<Input, Output> = {
  name: string
  inputSchema: Schema<Input>
  isReadOnly(input: Input): boolean
  isConcurrencySafe(input: Input): boolean
  checkPermissions(input: Input): Decision
  call(input: Input, ctx: ToolContext):
    Promise<ToolResult<Output>>
}

// safe defaults: serial + treated as a write
const defaults = {
  isReadOnly: () => false,
  isConcurrencySafe: () => false
}

Build in this order

✓
Schema first. The model-facing contract and runtime validator should be the same object.
✓
Permission before execution. Never let the tool decide its own trust boundary after side effects begin.
✓
Budget the result. Large output is a context attack, even when the tool is benign.
✓
Classify concurrency by input. A tool name is not a safety guarantee.

First tools to implement

ReadFile → ListFiles → Search → EditFile → RunCommand.

15 · Connectivity

Make the boundary portable: local tools, MCP and remote sessions.

LOCAL

Fast path

Use direct process calls for filesystem, shell and local project workflows. Keep permission and result contracts identical.

MCP

Universal tool surface

Wrap remote tools into the same model-facing interface. Handle transports, OAuth, timeouts, expiry and tool discovery.

REMOTE

Session bridge

Separate durable reads from HTTP writes, route messages, deduplicate echoes and make token refresh explicit.

Model-facing toolstable schema
→
Adapterlocal / MCP / bridge
→
Governancesame resolver
→
Resultnormalised + budgeted
↔

Implementation rule: add connectivity by extending the adapter layer, not by teaching the core loop a new special case for every transport.

16 · Performance checklist

Make the machinery feel invisible.

Startup

→
Dispatch fast paths before expensive imports.
→
Start independent I/O in parallel.
→
Preconnect to the model when it is safe.

Tokens & cost

→
Reserve a modest default output slot; escalate only when needed.
→
Keep stable prompt prefixes byte-identical.
→
Defer low-frequency tool schemas.

Rendering

→
Stream through a rendering pipeline, not one giant re-render.
→
Use double buffers and pools where terminal churn is high.
→
Make progress and partial output visible.

Search & memory

→
Index asynchronously; expose partial queryability.
→
Use cheap filters before expensive relevance scoring.
→
Measure recall quality and staleness, not only latency.
17 · Design judgement

Transfer the patterns. Question the scale-specific machinery.

Transfers broadly

✓
Generator-based loop
Backpressure, cancellation and terminal states.
✓
Self-describing tools
Safety and concurrency travel with capability.
✓
Layered context control
Protect quality and cost as sessions grow.
✓
Permission modes
Make trust posture legible.

Needs evidence in your context

?
Fork-cache economics
Depends on provider, prefix stability and workload shape.
?
Swarm complexity
Coordination can cost more than it saves.
?
File-based memory
Excellent for inspectability; not automatically right for every scale.
?
Terminal-first UI
Powerful for developers; not a universal interaction model.
◎

The repo’s highest-value contribution is not an exact implementation. It is a set of design questions you can ask of any agent architecture.

18 · How-to guide

A focused first build for your own agent shell.

DAY 1

Read-only agent

Model stream + file listing + file reading + search. No writes. Log every message and tool decision.

DAY 2–3

Governed edits

Add a diff-based edit tool, permission prompts, plan mode and result budgeting. Test denial paths first.

DAY 4–5

Recovery & memory

Add typed terminal states, retry boundaries, compact context and a small project-memory index.

DAY 6

Concurrency

Partition reads and writes. Speculate only on tools with a proven input-level safety classification.

DAY 7

One extension

Integrate one MCP server or one child agent through the same tool and permission path.

DONE WHEN

You can explain every stop

For any action, you can answer: what happened, why it was allowed, what it cost and how it can be stopped.

Implementation sequence synthesised from: ch01 · ch06 · ch17
19 · Closing

Don’t copy the product. Copy the questions.

What is the loop? What can act? Who decides? What is remembered? What is parallel? What happens when the model is wrong?

↻

The durable mental model: agent quality is the product of model capability, tool design, governance, context economics and interaction design.

Repository

Full book, web implementation and chapter navigation.

Read online

The project’s published interactive reading experience.

Epilogue

Five architectural bets, transfer boundaries and future directions.

README

Scope, table of contents and educational disclaimer.

Use ← → to navigate · O for overview · F for fullscreen

← → navigate   O overview   F fullscreen