Last week I worked through a project called learn-claude-code, from s01 all the way to s20.
In 20 chapters it hand-writes a nano version of Claude Code from scratch. Its tagline is a single line: Bash is all you need. What surprised me is that the core of a coding agent that actually gets work done really is a twenty-line loop. Every fancy capability after that, memory, subtasks, multi-agent collaboration, context compaction, grows outward from those twenty lines.
When I finished, I felt it had explained something I'd never managed to put clearly: when you build an agent, what are you actually writing? These are my reading notes. I take its core mechanisms apart one at a time, with diagrams and my own take.
The premise: Agent = model + harness
The project opens with a premise I think is crucial:
Agency (the ability to perceive, reason, and act) comes from model training, not from external code orchestration. An agent product = model + harness.
It backs this up with history. In 2013, DQN learned to play Atari from nothing but pixels and the score. In 2019, OpenAI Five played 45,000 years of Dota against itself and beat the TI8 champions. AlphaStar reached Grandmaster in StarCraft. Tencent's Juewu, in Honor of Kings, let pro players win just 1 game out of 15. All of these systems share one architecture: a trained model, dropped into an environment, given interfaces to perceive and act.
The model supplies the intelligence, the environment supplies the action space, and only together do they make a complete agent. Atari emulator, Dota client, StarCraft engine. For a coding agent, the environment is the IDE and the terminal.
Once you accept that premise, "building an agent" leaves only two options: either you're training the model (tuning weights, RLHF, collecting trajectory data), or you're building the harness (the code that lets the model work in some domain). Most people are doing the second. The project calls it harness engineering. I'd rather call it "building the car."
The model is the driver; you build the car
The project has a clean formula for the harness:
Harness = Tools + Knowledge + Observation + Action + Permissions
Tools: file read/write, shell, network, database, browser
Knowledge: product docs, domain references, API specs, style guides
Observation: git diff, error logs, browser state
Action: CLI commands, API calls, UI interactions
Permissions: sandboxing, approval flows, trust boundariesThe model decides; the harness executes. The model reasons; the harness provides context. There's a line in the project I really agree with: what makes Claude Code elegant is exactly what it doesn't do. It doesn't try to make decisions for the model, doesn't impose a fixed workflow, doesn't replace the model's judgment with hand-written rules. It provides tools, knowledge, context management, and permission boundaries, and then gets out of the way.
You're not writing intelligence. You're building the world the intelligence lives in. The quality of that world decides how much of the intelligence gets to show up.
A twenty-line core
With the premise and the division of labor clear, let's look at the code. This loop doesn't change by a single line from chapter 1 to chapter 20:
def agent_loop(messages):
while True:
response = client.messages.create(model, system, messages, tools)
messages.append(assistant_response)
if response.stop_reason != "tool_use":
return # stop when the model says stop
# otherwise: run the tools the model asked for, append the results to messages, keep loopingIf the model wants a tool, it calls it. The result goes back into the conversation, and the loop runs until the model itself decides to stop. The code doesn't judge "is the task done?" on the model's behalf. That's the model's call.
This is the essence of the whole project: the loop stays fixed, and each of the next 19 chapters adds one mechanism around it, never rewriting the loop itself.
The loop belongs to the agent. The mechanisms belong to the harness.
I won't go chapter by chapter. I'll pick the mechanisms that best show the design thinking and take them apart. First, a full map to orient by.
Map of the 20 chapters
| Chapter | Topic | One-line motto |
|---|---|---|
| s01 | Agent Loop | A loop plus bash is an agent |
| s02 | Tool Use | Adding a tool means adding a handler; the loop stays put |
| s03 | Permission | Set the boundaries first, then grant freedom |
| s04 | Hooks | Hang hooks around the loop; don't touch the loop |
| s05 | TodoWrite | An agent without a plan drifts |
| s06 | Subagent | Split big tasks; give each subtask a clean context |
| s07 | Skill Loading | Load knowledge on demand, not all at once |
| s08 | Context Compact | Context always fills up; you need a way to make room |
| s09 | Memory | Remember what matters, forget what doesn't |
| s10 | System Prompt | The prompt is assembled at runtime, not hard-coded |
| s11 | Error Recovery | An error isn't the end; it's where the retry starts |
| s12 | Task System | Break big goals into small tasks, order them, persist them |
| s13 | Background Tasks | Push slow work to the background; the agent keeps thinking |
| s14 | Cron Scheduler | Fire on a schedule, no human poking required |
| s15 | Agent Teams | When one agent can't finish, call in teammates |
| s16 | Team Protocols | Teammates need shared communication rules |
| s17 | Autonomous Agents | Teammates claim work from the board; nobody hands it out |
| s18 | Worktree Isolation | Each works in its own directory, no stepping on toes |
| s19 | MCP Plugin | Not enough capability? Plug in more tools via MCP |
| s20 | Comprehensive | Many mechanisms, back to one loop |
One gotcha up front: the repo currently has two tutorials side by side. The s01 to s20 folders at the root are the new official version; docs/ and the web platform are still the old 12-chapter version, and the chapter numbers don't line up. New readers should go straight to the root.
The breakdown below isn't in chapter order. I grouped it by theme: from giving the agent hands and rules, to managing the context fed to the model, to surviving failure and scaling into a team. It jumps around a bit, but it reads as more of a whole.
Adding a tool means adding a handler
Chapter 2 solves the most basic problem: how do you give an agent new abilities without touching the core loop?
The answer is a dispatch table. Each tool is a function, registered in a dictionary mapping names to functions. When the model asks for bash, the loop looks up the bash handler and runs it; when it asks for read_file, it looks up read_file. The loop only ever does one thing: forward the tool name the model picked to the matching handler.
It's a bit like a switchboard operator. A caller gives an extension number, and the operator just connects them, without caring whether it's sales or support on the other end. To add a new department, you register a new extension on the switchboard, and the operator's routine doesn't change at all.
The value of this design is that the cost of extension stays constant. Adding the 1st tool and the 100th tool look the same to the loop: one more entry in the dictionary. All of Claude Code's many tools sit on a table like this.
Set the boundaries first, then grant freedom
The stronger the tools, the more dangerous they get. An agent that can run bash can, in theory, rm -rf your whole directory. Chapters 3 and 4 deal with that.
Chapter 3 is permissions. Every tool call goes through a check: some are allowed straight through (reading a file), some must be blocked (deleting the root directory), and some have to stop and ask a human (writing production config). It's like setting up access for a new intern: spell out what they can do, draw the red lines clearly, and have them check in on anything they're unsure about.
Chapter 4 is hooks, which insert extension points before and after a tool runs. PreToolUse fires before the tool runs, PostToolUse after. The key is its motto: hang hooks around the loop; don't touch the loop. Logging, auditing, custom blocking all come in through hooks, and the core loop stays perfectly still. It's the same philosophy as the dispatch table: all extension happens at the loop's perimeter.
Context always fills up: four layers of compaction
With hands and rules in place, the agent can move. But once a task runs long, it hits the same wall right away: the context window is full. The next few chapters all address one thing, how to manage the context fed to the model, and they're my favorite group. Chapter 8 takes on the most direct question first: what do you do when the window is full? Its answer isn't a single switch but a four-layer pipeline, on the principle of "cheap first, expensive last."
I think of it as clearing a desk that keeps piling up. First, file the big documents into a drawer (write oversized tool results to disk and keep only a reference in context). Then toss the useless drafts in the middle (trim old messages). Then replace old files you rarely look at with a sticky note (swap old tool results for placeholders). All three steps are cheap. Only if the desk is still full do you spend the time writing meeting minutes that compress a stack of paper into one page (have the model summarize the whole history; this costs an API call, so it goes last). And if the API still complains it's too long after the summary, there's an emergency fallback.
The comments note that this execution order matches how Claude Code actually behaves. Turning "context management" from a vague idea into a pipeline with an order and an awareness of cost is, to me, the most valuable thing in this chapter.
Remember what matters, forget what doesn't
Compaction handles space within one session; memory handles continuity across sessions. Chapter 9 splits memory into three subsystems, and I think the split is close to how a human brain works.
Extraction is jotting notes as you go: at the end of each turn, pull whatever is worth keeping out of the raw messages and write it to a file. Selection is flipping to the relevant pages when you need them: use file names and descriptions to load the memories relevant to the current task into context, instead of carrying the whole notebook around. Consolidation, which the project calls "dreaming," periodically tidies, merges, and dedupes the scattered notes so the memory store doesn't get messier as it grows.
For storage it uses a MEMORY.md as an index, one line per memory, pointing to a set of single files with YAML frontmatter. This "index plus load on demand" structure is the same idea it uses for skills and for context: never stuff everything in at once.
The prompt isn't hard-coded; it's assembled at runtime
Chapter 10 handles the system prompt. Most people write it as one big fixed string that never changes. This chapter does it differently: the prompt is split into sections (identity, tool descriptions, working directory, memory, and so on), and each turn assembles it fresh from the current real state.
The key is "from the real state," not guessing from keywords. The memory section, for example, is only added when .memory/MEMORY.md actually exists; if it doesn't, it takes no space. After assembly there's also a deterministic cache, so the same state always produces exactly the same prompt.
It's like packing a bag before you head out. Keys and wallet are always in there; you add an umbrella only if it's raining and a laptop only if you're traveling. You don't walk out every day with one huge, never-changing bag stuffed with everything you might possibly need.
This has two benefits. First, the context stays clean: each turn holds only the sections that are actually relevant right now. Second, it's cache-friendly: stable prefixes like identity and tool descriptions can hit prompt caching, saving both money and latency. At heart it's the same philosophy as compaction and memory showing up again: if it doesn't need to be in the context, leave it out.
Hand the dirty work to a stand-in
There's an even more aggressive way to keep things out of the context: don't let a whole stretch of dirty work into the main context at all. That's what the subagent in chapter 6 does. The name sounds like multi-agent mysticism, but at heart it's just context isolation.
When the main agent hits a chore that requires digging through a lot of material, say "find every place in the codebase that calls a certain deprecated API," it doesn't do it itself. It sends a subagent with a brand-new, blank context. The subagent opens dozens of files and runs a pile of greps, an extremely verbose process, but all that noise stays in its own context. When it's done, it brings just one conclusion back to the main thread.
It's like sending an assistant to search the archives. They spend the whole morning on it and hand you a one-page summary; they don't haul the entire archive room onto your desk. So the main agent's context stays clean, and the space saved goes to the reasoning that actually matters.
Load knowledge on demand
Skill loading in chapter 7 is the same "on demand" philosophy showing up again.
An agent might have dozens or hundreds of skills, but you can't write all of them into the system prompt. That would blow up the context instantly, and most skills aren't needed for this task anyway. Its approach has two layers: first give the model a catalog listing which skills exist and roughly what each does, which is very light; only when the model decides which one it needs this time does the full content of that skill get expanded and injected.
It's how a library works. You check the index cards first to see where a book is and what it covers, then go get the one you need from the shelf. Nobody carts the whole collection home. How capable an agent can get depends largely on how well it does this kind of "compress, then expand on demand."
An error isn't the end
That about covers context management, but there's a reality I've been avoiding: the LLM call itself fails, and it fails in several different ways. Chapter 11 wraps the call in try/except and splits recovery into three paths by error type.
I think of these three paths as a long road trip. Cut off mid-sentence (output truncated by max_tokens)? Take a breath and keep talking. Trunk too full to close (prompt too long)? Toss some stuff before you drive on (trigger compaction). Traffic jam ahead, long line at the rest stop (rate limited, service overloaded)? Wait a bit, and if you've waited too long, just switch to the spare car (fallback model).
Different error types, different recovery paths. Not "always retry," and not "quit at the first error."
This chapter looks unremarkable, but it's the dividing line between a demo and something usable. With a real agent, the hard part was never the happy path. It's catching things gracefully when the API acts up in all its various ways. Sorting recovery strategies by error type is where robustness starts.
When one can't finish, call in teammates
However robust, a single agent has limits, and some tasks don't fit in one head. From chapter 12 to chapter 18, the project extends it into a team that can collaborate. Together these chapters are a complete minimal multi-agent implementation, so I'll cover them together.
Chapter 12 first breaks the goal into tasks with dependencies and persists them as a task graph on disk, with a blockedBy field recording who's blocking whom. Chapters 15 and 16 give teammates file mailboxes, a set of .jsonl files serving as async inboxes. Teammates run their own simplified loops in background threads, and their messages get injected back into the main agent's conversation history, not just printed. Chapter 17 goes further: teammates claim work from the task board themselves, without the main agent assigning each one. Chapter 18 gives every task its own git worktree, so each works in its own branch directory without stepping on anyone else.
It runs like a small team: a task board with dependencies on the wall, members claiming their own work, async communication through inboxes, everyone at their own desk. Take the mechanism apart and "multi-agent" isn't mysterious at all. It's a task graph plus mailboxes plus directory isolation.
Not enough capability? Plug it in
Chapter 19 is MCP, which connects external capabilities into the same tool pool.
To the model, an external tool connected via MCP looks exactly like a built-in local bash: just one more entry in the tool pool. It's like a docking station for your laptop. You don't open the case and change the motherboard; you plug in a dock and suddenly you have an external monitor, Ethernet, and a card reader. The agent's capability boundary can keep expanding outward without touching the core.
By chapter 20, all the earlier mechanisms come together and get reassembled around that twenty-line loop into a complete agent. After that whole long detour, the core is still the same core.
How to read it and get started
Each chapter is a folder with a uniform structure: a narrative README.md (in Chinese, with inline code, plus English and Japanese translations), a standalone runnable code.py, and SVG diagrams where needed. Complex chapters fold the deep-end material into <details> blocks you can expand if you want to dig in.
Reading it is simple: go from s01 straight through to s20. Each chapter assumes you've read the previous ones, and each ends with a hook into the next. Getting started takes three lines:
git clone https://github.com/shareAI-lab/learn-claude-code
pip install -r requirements.txt && cp .env.example .env # set ANTHROPIC_API_KEY
python s01_agent_loop/code.py # start with one loop plus bashOnce you've run s01, you'll probably be hooked, because you'll see with your own eyes that the core of a working coding agent really is those twenty lines. Then run python s08_context_compact/code.py to see the compaction pipeline, and python s20_comprehensive/code.py to see all the mechanisms combined. The project also points to two productized next steps: Kode Agent CLI, and a sister tutorial, claw0 (on how heartbeat and cron turn a one-shot agent into an always-on assistant). If you finish the main line and want to keep going, treat them as signposts.
My thoughts
After working through these 20 chapters, a few convictions got clearer for me.
First, "orchestration" is overrated. More than half the agent platforms out there are selling orchestration: drag and drop, wiring, configuring branches. But orchestration is fundamentally making decisions on the model's behalf, using deterministic code to box in an intelligence that's supposed to be non-deterministic. The stronger the model, the more you box it in, the more you waste. What deserves the investment isn't orchestration. It's the quality of the tools, the organization of knowledge, the management of context, the boundaries of permission: the harness itself.
Second, the harness is a moat, and the moat is getting deeper. Models are shared; anyone can call the API. But the same model in a good harness versus a bad one can perform an order of magnitude apart. An agent's ceiling isn't in the model's parameters; it's in the environment you give it. And that is exactly the part engineers can control, accumulate, and differentiate on.
Third, restraint is a very advanced engineering skill. What moved me most about this project isn't how many mechanisms it implements. It's that it has a twenty-line loop that goes untouched for twenty chapters. Knowing what not to write is harder than knowing what to write. A common failing when people write agents is itchy fingers: not trusting the model, always wanting to control a little more. Learning to get out of the way is the biggest lesson it gave me.
Fourth, trajectories are data. There's an underrated line in the project: every action sequence an agent runs inside your harness is a training signal. The car you build today, and the routes it drives, are the raw material for tomorrow's stronger model. Harness engineers aren't just using models; they're also feeding data to the next generation. Once that loop clicks, the long-term value of building harnesses looks completely different.
If you're building agents too, my advice is to run s01 first, then go back to the system you're working on and ask yourself one question: of the code I've written, how much is helping the model, and how much is doing the model's job for it?