开源项目 GitHub Topic ai-agent 2026-07-06T12:02 正文 ok 3220 words

📦 shareAI-lab/learn-claude-code:学习 Claude Code,从 0 到 1 构建真正 Agent 的 Harness 工程

英文标题:📦 shareAI-lab/learn-claude-code

该项目认为智能体(Agent)的核心能力来自模型训练,而非外部代码编排;一个可工作的 Agent 产品由模型与 Harness(运维环境)共同组成。项目通过 20 个递进章节,从最简单的“一个循环 + Bash”开始,逐步实现工具调用、子代理、上下文压缩、任务系统、团队协作、权限控制、MCP 等完整机制。教程强调 Harness 工程师的职责是为模型提供工具、知识、上下文、动作接口与权限边界,从而让模型在编码等具体领域中高效行动。对想理解 Claude Code 内部模式、或自建 Agent 环境的开发者具有实用参考价值。
打开原文相关 4.9 · 机会 3
media5.1 KB media65.8 KB

中文

学习 Claude Code —— 真实 Agent 的 Harness 工程

能动性来自模型。一个 Agent 产品 = 模型 + Harness。

在写任何代码之前,需要先明确一件事。

能动性——感知、推理与行动的能力——来自模型训练,而非外部代码编排。 但一个可工作的 Agent 产品同时需要模型和 Harness。模型是驾驶员,Harness 是车辆。本仓库教你如何建造这辆车。

每一个 Agent 的核心都是一个神经网络——Transformer、RNN 或训练好的函数——它由数十亿次基于感知、推理与行动序列的梯度更新所塑造。能动性从来就不是由外围代码赐予的,它是在训练中学会的。

人类就是最原始的证明。一个生物神经网络,经过数百万年进化压力的打磨,通过感官感知世界,通过大脑进行推理,通过身体采取行动。当 DeepMind、OpenAI 或 Anthropic 说“Agent”时,她们指向同一核心事实:一个通过训练学会行动的模型,加上让它能在特定环境中运作的基础设施。

历史记录毫不含糊:

  • 2013 年 —— DeepMind DQN 玩 Atari。 单个神经网络仅接收原始像素和游戏分数,就学会了 7 款 Atari 2600 游戏——超越了此前的算法,并在其中 3 款上击败人类专家。到 2015 年,扩展到 49 款游戏,达到专业测试员水平,并发表在《自然》杂志上。没有针对具体游戏的规则。一个模型,从经验中学习。
  • 2019 年 —— OpenAI Five 征服 Dota 2。 五个神经网络在 10 个月内 相互对抗了相当于 45,000 年的 Dota 2 对局,随后在直播比赛中以 2-0 击败了 TI8 世界冠军 OG。在公开竞技场中,该 AI 在 42,729 场对战中赢了 99.4%。没有脚本化策略。模型通过自我博弈学会了团队协作。
  • 2019 年 —— DeepMind AlphaStar 精通星际争霸 II。 AlphaStar 在封闭比赛中 以 10-1 击败职业选手,随后在欧洲服务器达到 宗师段位——位列 90000 名玩家中的前 0.15%。这是一款不完全信息、实时战略游戏,其组合动作空间远超国际象棋或围棋。
  • 2019 年 —— 腾讯绝悟统治王者荣耀。 腾讯 AI Lab 的“绝悟”系统在王者荣耀世界冠军杯半决赛中 以完整 5v5 击败 KPL 职业选手。在 1v1 模式下,职业选手 在 15 局中仅赢 1 局,最久坚持不足 8 分钟。训练强度:一天等于 440 个人类年。一个通过自我博弈从零学会整个游戏的模型。
  • 2024-2025 —— 大语言模型 Agent 重塑软件工程。 Claude、GPT、Gemini——在海量人类代码和推理上训练的大型语言模型,正被部署为编程 Agent。他们阅读理解代码库,编写实现,调试错误,并以团队形式协调协作。其架构与此前的每一个 Agent 完全相同:一个训练好的模型,被置于一个环境中,并被赋予感知与行动的工具。

每个里程碑都指向同一个事实:能动性——感知、推理与行动的能力——是训练出来的,不是代码堆砌出来的。 但每个 Agent 也需要一个操作环境:一台 Atari 模拟器、Dota 2 客户端、星际争霸 II 引擎、一个 IDE 和一个终端。模型提供智能,环境提供行动空间。两者共同构成完整的 Agent。

“Agent”一词已被整个提示词管道产业劫持。

拖拽式工作流构建器、零代码“AI Agent”平台、提示词链编排库……它们共享一个错觉:把 LLM API 调用用 if-else 分支、节点图和硬编码路由逻辑串联起来,就等于“构建一个 Agent”。

事实并非如此。它们制造的是戈德堡机械——一种过度工程化、脆弱、过程式的规则管道,里头夹着一个 LLM,其作用不过是美化的文本补全节点。那不是 Agent,那只是一个带着浮夸妄想的 shell 脚本。

你不可能通过堆砌过程逻辑——庞杂的规则树、节点图、链式提示瀑布——并祈祷足够的胶水代码能奇迹般地催生自主行为,来暴力制造智能。这行不通。你无法用工程手段创造能动性。能动性是学来的,不是编码编出来的。

思维转变:从「构建 Agent」到构建 Harness

当有人说“我在构建一个 Agent”时,他只能意味着以下两件事之一:

1. 训练一个模型。 通过强化学习、微调、RLHF 或其他基于梯度的方法调整权重。收集轨迹数据——目标领域中感知、推理、行动的真实世界序列——并用这些数据塑造模型的行为。这是 DeepMind、OpenAI、腾讯 AI Lab 和 Anthropic 在做的事情。

2. 构建一个 Harness。 编写代码,为模型提供运行环境。这是我们大多数人在做的事,也是本仓库的核心。

Harness 是一个 Agent 在特定领域中工作所需的一切:

Harness = 工具 + 知识 + 观察 + 动作接口 + 权限

工具:          文件 I/O、shell、网络、数据库、浏览器
知识:          产品文档、领域参考资料、API 规范、风格指南
观察:          git diff、错误日志、浏览器状态、传感器数据
动作:          CLI 命令、API 调用、UI 交互
权限:          沙箱隔离、审批流程、信任边界

模型做决策,Harness 负责执行。模型进行推理,Harness 提供上下文。模型是驾驶员,Harness 是车辆。

本仓库教你建造这辆车:一辆用于编程的车辆。但其设计模式可推广到任何领域。

Harness 工程师究竟做什么

如果你正在阅读这个仓库,你极大概率是一名 Harness 工程师。以下是这项工作实际包含的内容:

  • 实现工具。 给 Agent 双手。文件读写、shell 执行、API 调用、浏览器控制、数据库查询。每个工具是 Agent 在其环境中可执行的一个动作。设计原则:原子化、可组合、描述清晰。
  • 整理知识。 给 Agent 领域专长。产品文档、架构决策记录、风格指南、合规要求。按需加载,而非一次性全部塞入。
  • 管理上下文。 给 Agent 干净的记忆。子 Agent 隔离可防止噪声泄漏;上下文压缩可防止历史淹没事当下;任务系统让目标能超越单次对话持续存在。
  • 控制权限。 给 Agent 边界。沙箱文件访问。对破坏性操作要求审批。在 Agent 与外部系统之间强制执行信任边界。
  • 收集轨迹数据。 Agent 在你的 Harness 中执行的每一个动作序列都是训练信号。真实部署轨迹是微调下一代 Agent 模型的原始材料。

你不是在编写智能,你是在建造智能栖居的世界。这个世界的质量直接决定了智能能多有效地表达自己。

把 Harness 建好,模型会完成剩下的事。

之所以选择 Claude Code,是因为它是我们所见过的最优雅、最完整的 Agent Harness 实现。并非因为什么聪明的技巧,而是因为它 没做什么:它没有试图充当 Agent,没有强加僵化的工作流,没有用人工设计的决策树替代模型自身的判断。它只是给模型提供了工具、知识、上下文管理和权限边界——然后让路。

将 Claude Code 剥离到本质:

Claude Code = 一个 Agent 循环 + 工具(bash、read、write、edit、glob、grep、browser...) + 按需技能加载 + 上下文压缩 + 生成子 Agent + 带依赖图的任务系统 + 异步信箱团队协作 + 工作树隔离的并行执行 + 权限治理 + 钩子扩展系统 + 记忆持久化 + MCP 外部能力路由

就是这样。Agent 本身呢?Claude。一个模型,由 Anthropic 在人类推理与代码的全部广度上训练而成。Harness 没有让 Claude 变聪明,Claude 本来就很聪明。Harness 只是给了 Claude 双手、眼睛和一个工作空间。

启示不是“照抄 Claude Code”,而是:最优秀的 Agent 产品出自那些明白自己职责是建造 Harness、而非建造智能的工程师之手。


             THE AGENT PATTERN
             =================

 User --> messages[] --> LLM --> response
                                   |
                         stop_reason == "tool_use"?
                        /                          \
                      yes                           no
                       |                             |
                 execute tools                    return text
                 append results
                 loop back -----------------> messages[]


 模型决定何时调用工具、何时停止。
 代码只执行模型要求的操作。
 本仓库教你构建围绕这一循环的所有内容——
 让 Agent 在特定领域发挥效力的 Harness。

def agent_loop(messages): while True: response = client.messages.create( model=MODEL, system=SYSTEM, messages=messages, tools=TOOLS, ) messages.append({"role": "assistant", "content": response.content})

     if response.stop_reason != "tool_use":
         return

     results = []
     for block in response.content:
         if block.type == "tool_use":
             output = TOOL_HANDLERS[block.name](**block.input)
             results.append({
                 "type": "tool_result",
                 "tool_use_id": block.id,
                 "content": output,
             })
     messages.append({"role": "user", "content": results})

每一课在这个循环之上叠加一层 Harness 机制——循环本身从不改变。循环属于 Agent,机制属于 Harness。

循环是常量,工具、知识和权限会发生变化。Agent = 模型(LLM)+ 通用运行环境(Harness)。


本仓库目前包含两条教程轨迹:

  • 当前轨迹:根级 s01-s20 根级 s01_* … s20_* 文件夹是新规范版本。每章包含完整的叙事 README、翻译、可运行的 code.py 以及必要的图表。
  • 旧版过渡轨迹:docs/、agents/ 以及当前的 web/ 应用 这些仍然保留着较早的 12 课版本。在新 20 课版本稳定前,暂时为既有读者、旧链接以及 web 平台保留。

如果你现在才开始,请阅读根级 s01_agent_loop/ 至 s20_comprehensive/ 章节。如果你正在按旧链接或使用当前 web 应用,你很可能在读旧的 12 课轨迹。旧版与当前版的课程序号并不总是一一对应,请避免混用不同轨迹的课程序号。

旧版到当前版映射表

旧版 12 课轨迹 当前 20 课轨迹 主题
old s01 new s01 Agent 循环
old s02 new s02 工具使用
old s03 new s05 TodoWrite
old s04 new s06 子 Agent
old s05 new s07 技能加载
old s06 new s08 上下文压缩
old s07 new s12 任务系统
old s08 new s13 后台任务
old s09 new s15 Agent 团队
old s10 new s16 团队协议
old s11 new s17 自主 Agent
old s12 new s18 工作树隔离
仅新版本 s03, s04, s09, s10, s11, s14, s19, s20 权限、钩子、记忆、系统提示、错误恢复、定时任务、MCP、综合 Agent

本仓库是一个从 0 到 1 的 Harness 工程学习项目:它教你如何在 Agent 模型周围构建工作环境。为了保持学习路径清晰,有意简化或省略了一些生产机制:

  • 完整的事件/钩子总线行为,如 PreToolUse、SessionStart/End 和 ConfigChange。教学代码仅在需要时使用最小的生命周期事件。
  • 基于规则的权限治理与完整信任工作流。
  • 会话生命周期控制,如恢复/分叉,以及更完整的工作树生命周期处理。
  • 完整的 MCP 运行时细节,如传输、OAuth、资源订阅与轮询。

本仓库中的 JSONL 信箱协议是一个教学实现,并非声称是任何特定生产内部实现。


每一课添加一项 Harness 机制,每个机制都有一句格言。

s01 “一个循环 + Bash 便是你所需的一切” —— 一个工具加一个

English / 原文

English | 中文 | 日本語

shareAI-lab%2Flearn-claude-code | Trendshift

Learn Claude Code -- Harness Engineering for Real Agents

Agency Comes from the Model. An Agent Product = Model + Harness.

Before we write any code, one thing needs to be clear.

Agency -- the capacity to perceive, reason, and act -- comes from model training, not from external code orchestration. But a working agent product needs both the model and the harness. The model is the driver. The harness is the vehicle. This repository teaches you how to build the vehicle.

At the core of every agent is a neural network -- a Transformer, an RNN, a trained function -- shaped by billions of gradient updates on sequences of perception, reasoning, and action. Agency was never bestowed by the surrounding code. It was learned during training.

Humans are the original proof. A biological neural network, refined by millions of years of evolutionary pressure, perceives the world through senses, reasons through a brain, and acts through a body. When DeepMind, OpenAI, or Anthropic say "agent," they all mean the same core thing: a model that learned to act through training, plus the infrastructure that lets it operate in a specific environment.

The historical record is unambiguous:

  • 2013 -- DeepMind DQN plays Atari. A single neural network, receiving only raw pixels and game scores, learned 7 Atari 2600 games -- surpassing prior algorithms and beating human experts in 3 of them. By 2015, scaled to 49 games at professional tester level, published in Nature. No game-specific rules. One model, learning from experience.

  • 2019 -- OpenAI Five conquers Dota 2. Five neural networks played 45,000 years of Dota 2 against themselves over 10 months, then defeated OG -- the TI8 world champions -- 2-0 in a live match. In the public arena, the AI won 99.4% of 42,729 games. No scripted strategies. Models learned teamwork through self-play.

  • 2019 -- DeepMind AlphaStar masters StarCraft II. AlphaStar beat a professional player 10-1 in closed matches, then reached Grandmaster rank on the European server -- top 0.15% of 90,000 players. An incomplete-information, real-time game with a combinatorial action space far exceeding chess or Go.

  • 2019 -- Tencent Jueyu dominates Honor of Kings. Tencent AI Lab's "Jueyu" system defeated KPL professional players in full 5v5 at the World Champion Cup semifinal. In 1v1 mode, pros won just 1 out of 15 matches, lasting under 8 minutes at best. Training intensity: one day equaled 440 human years. A model that learned the entire game from scratch through self-play.

  • 2024-2025 -- LLM agents reshape software engineering. Claude, GPT, Gemini -- large language models trained on the full breadth of human code and reasoning -- are deployed as coding agents. They read codebases, write implementations, debug failures, and coordinate as teams. The architecture is identical to every previous agent: a trained model, placed in an environment, given tools for perception and action.

Every milestone points to the same fact: Agency -- the ability to perceive, reason, and act -- is trained, not coded. But every agent also needs an environment to operate in: an Atari emulator, the Dota 2 client, the StarCraft II engine, an IDE and a terminal. The model supplies the intelligence. The environment supplies the action space. Together they form a complete agent.

The word "agent" has been hijacked by an entire prompt-plumbing industry.

Drag-and-drop workflow builders. No-code "AI Agent" platforms. Prompt-chain orchestration libraries. They share a single delusion: that stringing LLM API calls together with if-else branches, node graphs, and hardcoded routing logic constitutes "building an agent."

It does not. What they produce are Rube Goldberg machines -- over-engineered, brittle, procedural rule pipelines with an LLM wedged in as a glorified text-completion node. That is not an agent. That is a shell script with grandiose pretensions.

You cannot brute-force intelligence by stacking procedural logic -- sprawling rule trees, node graphs, chained prompt waterfalls -- and praying that enough glue code will spontaneously produce autonomous behavior. It will not. You cannot engineer agency into existence. Agency is learned, not coded.

The Mindshift: From "Building Agents" to Building Harnesses

When someone says "I am building an agent," they can only mean one of two things:

1. Training a model. Adjusting weights through reinforcement learning, fine-tuning, RLHF, or another gradient-based method. Collecting trajectory data -- real-world sequences of perception, reasoning, and action in a target domain -- and using it to shape the model's behavior. This is what DeepMind, OpenAI, Tencent AI Lab, and Anthropic do.

2. Building a harness. Writing the code that gives a model an operational environment. This is what most of us do, and it is the core of this repository.

A harness is everything an agent needs to work in a specific domain:

Harness = Tools + Knowledge + Observation + Action Interfaces + Permissions

    Tools:          file I/O, shell, network, database, browser
    Knowledge:      product docs, domain references, API specs, style guides
    Observation:    git diff, error logs, browser state, sensor data
    Action:         CLI commands, API calls, UI interactions
    Permissions:    sandbox isolation, approval workflows, trust boundaries

The model decides. The harness executes. The model reasons. The harness provides context. The model is the driver. The harness is the vehicle.

This repository teaches you to build the vehicle. A vehicle for coding. But the design patterns generalize to any domain.

What Harness Engineers Actually Do

If you are reading this repository, you are most likely a harness engineer. Here is what the job actually entails:

  • Implement tools. Give the agent hands. File read/write, shell execution, API calls, browser control, database queries. Each tool is one action the agent can take in its environment. Design them atomic, composable, and clearly described.

  • Curate knowledge. Give the agent domain expertise. Product documentation, architecture decision records, style guides, compliance requirements. Load on demand, not upfront.

  • Manage context. Give the agent clean memory. Subagent isolation prevents noise leakage. Context compaction prevents history from drowning the present. Task systems let goals persist beyond a single conversation.

  • Control permissions. Give the agent boundaries. Sandbox file access. Require approval for destructive operations. Enforce trust boundaries between the agent and external systems.

  • Collect trajectory data. Every action sequence the agent executes in your harness is training signal. Real deployment trajectories are the raw material for fine-tuning the next generation of agent models.

You are not writing intelligence. You are building the world that intelligence inhabits. The quality of that world directly determines how effectively the intelligence can express itself.

Build the harness well. The model will do the rest.

Because Claude Code is the most elegant, most complete agent harness implementation we have seen. Not because of any clever trick, but because of what it does not do: it does not try to be the agent. It does not impose rigid workflows. It does not substitute hand-crafted decision trees for the model's own judgment. It gives the model tools, knowledge, context management, and permission boundaries -- then gets out of the way.

Strip Claude Code down to its essence:

Claude Code = one agent loop
            + tools (bash, read, write, edit, glob, grep, browser...)
            + on-demand skill loading
            + context compaction
            + subagent spawning
            + task system with dependency graphs
            + async mailbox team coordination
            + worktree-isolated parallel execution
            + permission governance
            + hooks extension system
            + memory persistence
            + MCP external capability routing

That is it. The agent itself? Claude. A model. Trained by Anthropic on the full breadth of human reasoning and code. The harness did not make Claude smart. Claude was already smart. The harness gave Claude hands, eyes, and a workspace.

The takeaway is not "copy Claude Code." The takeaway is: the best agent products come from engineers who understand that their job is the harness, not the intelligence.


                    THE AGENT PATTERN
                    =================

    User --> messages[] --> LLM --> response
                                      |
                            stop_reason == "tool_use"?
                           /                          \
                         yes                           no
                          |                             |
                    execute tools                    return text
                    append results
                    loop back -----------------> messages[]


    The model decides when to call tools and when to stop.
    The code just executes what the model asks for.
    This repo teaches you to build everything around this loop --
    the harness that makes the agent effective in a specific domain.



def agent_loop(messages):
    while True:
        response = client.messages.create(
            model=MODEL, system=SYSTEM,
            messages=messages, tools=TOOLS,
        )
        messages.append({"role": "assistant",
                         "content": response.content})

        if response.stop_reason != "tool_use":
            return

        results = []
        for block in response.content:
            if block.type == "tool_use":
                output = TOOL_HANDLERS[block.name](**block.input)
                results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": output,
                })
        messages.append({"role": "user", "content": results})

Every lesson layers one harness mechanism on top of this loop -- the loop itself never changes. The loop belongs to the agent. The mechanisms belong to the harness.

The loop is constant. Tools, knowledge, and permissions change. Agent = Model (LLM) + a generalized operational environment (Harness).


This repository currently contains two tutorial tracks:

  • Current track: root-levels01-s20 The root-level s01_* ... s20_* folders are the new canonical version. Each chapter contains a full narrative README, translations, runnable code.py, and diagrams where needed.
  • Legacy transition track:docs/, agents/, and the current web/ app These still preserve the older 12-lesson version. They are kept temporarily for existing readers, old links, and the web platform while the new 20-lesson track settles.

If you are starting now, read the root-level s01_agent_loop/ through s20_comprehensive/ chapters. If you are following an older link or using the current web app, you are likely reading the legacy 12-lesson track. The legacy and current chapter numbers do not always match, so avoid mixing chapter numbers across tracks.

Legacy-to-Current Mapping

Legacy 12-lesson track Current 20-lesson track Topic
old s01 new s01 Agent Loop
old s02 new s02 Tool Use
old s03 new s05 TodoWrite
old s04 new s06 Subagent
old s05 new s07 Skill Loading
old s06 new s08 Context Compact
old s07 new s12 Task System
old s08 new s13 Background Tasks
old s09 new s15 Agent Teams
old s10 new s16 Team Protocols
old s11 new s17 Autonomous Agents
old s12 new s18 Worktree Isolation
new only s03, s04, s09, s10, s11, s14, s19, s20 Permission, Hooks, Memory, System Prompt, Error Recovery, Cron, MCP, Comprehensive Agent

This repository is a 0-to-1 harness engineering learning project: it teaches how to build the working environment around an agent model. To keep the learning path clear, some production mechanisms are intentionally simplified or omitted:

  • Full event / hook bus behavior, such as PreToolUse, SessionStart/End, and ConfigChange. The teaching code uses minimal lifecycle events where needed.
  • Rule-based permission governance and full trust workflows.
  • Session lifecycle controls such as resume/fork, plus more complete worktree lifecycle handling.
  • Full MCP runtime details such as transport, OAuth, resource subscription, and polling.

The JSONL mailbox protocol in this repository is a teaching implementation, not a claim about any specific production internal implementation.


Each lesson adds one harness mechanism. Each mechanism has a motto.

s01 "One loop & Bash is all you need" — one tool + one loop = one agent

s02 "Adding a tool means adding one handler" — the loop stays untouched; new tools register into the dispatch map

s03 "Set boundaries first, then grant freedom" — check what can run, what must stop, and what needs approval

s04 "Hook around the loop, never rewrite the loop" — add extension points without changing the main loop

s05 "An agent without a plan drifts" — list the steps before starting; completion rate doubles

s06 "Big tasks split small, each subtask gets clean context" — subagents do the side work and bring back only the result

s07 "Load knowledge on demand, not upfront" — list skills first, expand them only when needed

s08 "Context always fills up -- have a way to make room" — multi-layer compaction strategies buy you infinite sessions

s09 "Remember what matters, forget what doesn't" — three subsystems: selection, extraction, consolidation

s10 "Prompts are assembled at runtime, not hardcoded" — section-based concatenation, loaded on demand

s11 "Errors aren't the end, they're the start of a retry" — retry, make room, or take another path when things fail

s12 "Big goals break into small tasks, ordered, persisted to disk" — a file-backed task graph that lays the groundwork for multi-agent coordination

s13 "Slow ops go background, agent keeps thinking" — background threads run commands; notifications inject on completion

s14 "Fire on schedule, no human kick needed" — trigger tasks automatically by time

s15 "Too big for one agent -- delegate to teammates" — persistent teammates + async mailboxes

s16 "Teammates need shared communication rules" — use a fixed request-reply format for coordination

s17 "Teammates check the board, claim work themselves" — no leader assigning one by one; self-organizing

s18 "Each works in its own directory, no interference" — tasks own goals, worktrees own directories, bound by ID

s19 "Not enough capability? Plug in more via MCP" — connect external tools into the same tool pool

s20 "Many mechanisms, one loop" — all previous mechanisms return to one complete harness


Main line: act → handle complex work → remember and recover → run long tasks → collaborate → extend and assemble.

flowchart TD
    %% Card styles
    classDef stage1 fill:#E3F2FD,stroke:#1976D2,stroke-width:2px,color:#0D47A1,rx:12,ry:12,text-align:left
    classDef stage2 fill:#E8F5E9,stroke:#388E3C,stroke-width:2px,color:#1B5E20,rx:12,ry:12,text-align:left
    classDef stage3 fill:#FFF3E0,stroke:#F57C00,stroke-width:2px,color:#E65100,rx:12,ry:12,text-align:left
    classDef stage4 fill:#FCE4EC,stroke:#C2185b,stroke-width:2px,color:#880E4F,rx:12,ry:12,text-align:left
    classDef stage5 fill:#F3E5F5,stroke:#7B1FA2,stroke-width:2px,color:#4A148C,rx:12,ry:12,text-align:left
    classDef stage6 fill:#E0F7FA,stroke:#0097A7,stroke-width:2px,color:#006064,rx:12,ry:12,text-align:left

    %% Group style
    classDef groupBox fill:#F8F9FA,stroke:#CED4DA,stroke-width:2px,stroke-dasharray: 5 5,rx:15,ry:15,color:#495057

    %% Layer 1: stages 1-3
    subgraph Phase1 ["🌱 Stages 1-3: Core capabilities (simple to complex)"]
        direction LR
        S1["<b>1. Let the Agent act</b><br/>━━━━━━━━━━━━━<br/><b>s01 Agent Loop</b><br/>└─ one loop + bash<br/><br/><b>s02 Tool Use</b><br/>└─ one tool to many tools<br/><br/><b>s03 Permission</b><br/>└─ decide what can run<br/><br/><b>s04 Hooks</b><br/>└─ extension points around tools"]:::stage1

        S2["<b>2. Handle complex work</b><br/>━━━━━━━━━━━━━<br/><b>s05 TodoWrite</b><br/>└─ plan first, then execute<br/><br/><b>s06 Subagent</b><br/>└─ side work, result back<br/><br/><b>s08 Context Compact</b><br/>└─ make room in long context"]:::stage2

        S3["<b>3. Remember and recover</b><br/>━━━━━━━━━━━━━<br/><b>s09 Memory</b><br/>└─ remember what matters<br/><br/><b>s10 System Prompt</b><br/>└─ assemble at runtime<br/><br/><b>s11 Error Recovery</b><br/>└─ retry or change path"]:::stage3

        S1 ==> S2 ==> S3
    end

    %% Layer 2: stages 4-6
    subgraph Phase2 ["🚀 Stages 4-6: Advanced capabilities (long-running, collaboration, integration)"]
        direction LR
        S4["<b>4. Run long tasks</b><br/>━━━━━━━━━━━━━<br/><b>s12 Task System</b><br/>└─ persist tasks and deps<br/><br/><b>s13 Background Tasks</b><br/>└─ send slow work background<br/><br/><b>s14 Cron Scheduler</b><br/>└─ trigger by time"]:::stage4

        S5["<b>5. Coordinate many Agents</b><br/>━━━━━━━━━━━━━<br/><b>s15 Agent Teams</b><br/>└─ teammates + mailboxes<br/><br/><b>s16 Team Protocols</b><br/>└─ fixed request-reply format<br/><br/><b>s17 Autonomous Agents</b><br/>└─ claim work from the board<br/><br/><b>s18 Worktree Isolation</b><br/>└─ separate directories"]:::stage5

        S6["<b>6. Extend and assemble</b><br/>━━━━━━━━━━━━━<br/><b>s07 Skill Loading</b><br/>└─ expand skills on demand<br/><br/><b>s19 MCP Plugin</b><br/>└─ external tools, one pool<br/><br/><b>s20 Comprehensive Agent</b><br/>└─ all mechanisms, one loop"]:::stage6

        S4 ==> S5 ==> S6
    end

    %% Connect the two layers
    Phase1 ===> Phase2

    class Phase1,Phase2 groupBox

Loading


Chapter Topic Key Concepts
s01 Agent Loop messages / while True / stop_reason
s02 Tool Use TOOL_HANDLERS / dispatch map / concurrency
s03 Permission System PermissionRule / approval pipeline
s04 Hook System PreToolUse / PostToolUse / extension points
s05 TodoWrite TodoItem / plan-then-execute
s06 Subagent fresh messages[] / context isolation
s07 Skill Loading SkillManifest / on-demand injection
s08 Context Compact snipCompact / microCompact / toolResultBudget / autoCompact
s09 Memory System selection / extraction / consolidation
s10 System Prompt runtime assembly / section concatenation
s11 Error Recovery token escalation / fallback model / retry strategies
s12 Task System TaskRecord / blockedBy / disk persistence
s13 Background Tasks threaded execution / notification queue
s14 Cron Scheduler durable scheduling / session-scoped triggers
s15 Agent Teams MessageBus / inbox / permission bubbling
s16 Team Protocols shutdown handshake / plan approval
s17 Autonomous Agents idle cycle / auto-claim / self-organization
s18 Worktree Isolation WorktreeRecord / task-directory binding
s19 MCP Plugin multi-transport / channel routing / tool pool assembly
s20 Comprehensive Agent all mechanisms around one loop

Each chapter is a folder. Open one and you will find:

s08_context_compact/
  README.md              # full narrative with inline code
  README.en.md           # English translation
  README.ja.md           # Japanese translation
  code.py                # standalone runnable implementation
  images/                # SVG diagrams (where needed)

Read the README.md for the core idea and work through the code. Complex chapters have <details> folds for deep dives -- open them when you want to go deeper. Simple chapters have 0-1 diagrams, complex chapters have more.

Read from s01 through s20 in order. Each chapter assumes you've read the previous ones and ends with a hook into the next.


git clone https://github.com/shareAI-lab/learn-claude-code
cd learn-claude-code
pip install -r requirements.txt
cp .env.example .env   # configure ANTHROPIC_API_KEY

python s01_agent_loop/code.py        # Start here -- one loop + bash
python s08_context_compact/code.py   # Context compaction (complex)
python s20_comprehensive/code.py     # Endpoint: all mechanisms in one loop


python agents/s01_agent_loop.py
python agents/s12_worktree_task_isolation.py
python agents/s_full.py

The current web app still renders the legacy docs/ s01-s12 track. Use the root-level folders for the new s01-s20 track.

cd web && npm install && npm run dev   # http://localhost:3000

learn-claude-code/
  s01_agent_loop/          # one folder per chapter
    README.md              #   Chinese source (complete narrative)
    README.en.md           #   English translation
    README.ja.md           #   Japanese translation
    code.py                #   standalone runnable code
    images/                #   SVG diagrams
  s02_tool_use/
  ...
  s19_mcp_plugin/
  s20_comprehensive/       # endpoint chapter
  agents/                  # legacy 12 runnable copies + s_full.py
  skills/                  # skill files used by s07
  docs/                    # legacy 12-lesson docs, kept during transition
  web/                     # currently renders the legacy docs/ track
  tests/

After 20 lessons, you understand harness engineering from the inside out. Two paths to turn that knowledge into product:

Kode Agent CLI -- Open-Source Coding Agent CLI

npm i -g @shareai-lab/kode

Skill and LSP support, Windows compatible, works with GLM / MiniMax / DeepSeek and other open models. Install and go.

GitHub: shareAI-lab/Kode-CLI

Kode Agent SDK -- Embed Agent Capabilities in Your Application

A standalone library with no per-user process overhead. Embed it in backends, browser extensions, embedded devices, or any runtime.

GitHub: shareAI-lab/kode-agent-sdk


Sister Tutorial: From Passive Sessions to Always-On Assistants

The harness taught in this repository is the use-and-discard kind -- open a terminal, give the agent a task, close when done, next session starts fresh. Claude Code works this way.

But OpenClaw proves another possibility: on the same agent core, two additional harness mechanisms turn an agent from "poke it and it moves" into "wakes itself every 30 seconds to look for work":

  • Heartbeat -- every 30 seconds the harness sends the agent a message, letting it check for pending work. Nothing to do? Keep sleeping. Something appeared? Act immediately.
  • Cron -- the agent can schedule its own future tasks, which fire automatically when the time arrives.

Add IM multi-channel routing (WhatsApp / Telegram / Slack / Discord and 13+ other platforms), persistent context memory, and a Soul personality system, and the agent transforms from a disposable tool into an always-on personal AI assistant.

claw0 is our sister teaching repository, breaking down these harness mechanisms from scratch:

claw agent = agent core + heartbeat + cron + IM chat + memory + soul



learn-claude-code                   claw0
(agent harness internals:            (always-on harness:
 loop, tools, planning,               heartbeat, cron, IM channels,
 teams, worktree isolation)            memory, Soul personality)

MIT


Agency comes from the model. The harness gives agency a place to land. Build the harness well, and the model will do the rest.

Bash is all you need. Real agents are all the universe needs.

This is not "copy the source code." This is "grasp the key designs and build it yourself."