learn-claude-code README

The project's README from github.com/shareAI-lab/learn-claude-code. As one markdown file: README.md.

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.

Where Agency Comes From

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:

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.

What an Agent Is NOT

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:

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.

Why Claude Code

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
            + task-bound worktrees for parallel edits
            + 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
                                      |
                              contains tool_use block?
                           /                          \
                         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.

Core Pattern

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})

        tool_calls = [
            block for block in response.content if block.type == "tool_use"
        ]
        if not tool_calls:
            return

        results = []
        for block in tool_calls:
            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})

Each lesson isolates one harness mechanism around this loop. s15 reconnects the cumulative runtime; s16 and s17 then study workflow orchestration and goal closure as focused examples. 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).


Version Status

This repository currently contains two tutorial tracks:

If you are starting now, read the root-level s01_agent_loop/ through s17_goal_loop/ chapters. 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 17-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 s10 Task System
old s08 new s11 Background Tasks
old s09 new s13 Agent Teams
old s10 new s13 Team Protocols
old s11 new s13 Autonomous task claiming
old s12 new s13 Task-bound worktrees
new only s03, s04, s09, s12, s14, s15, s16, s17 Permission, Hooks, Memory, Cron, MCP, Integrated Harness, Workflow Runtime, Goal Loop

Course Boundary

This is a 0-to-1 harness engineering course. Each chapter isolates one mechanism, then s15 reconnects the cumulative runtime in a complete agent loop. s16 extends that loop with workflow orchestration. s17 uses a smaller tool pool to focus on goal-controlled continuation; it is a mechanism example, not another cumulative runtime.


17 Progressive Lessons

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   Give a subtask fresh messages[]; its final text returns as one tool 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" — four compaction steps reduce tool results first, then summarize history when it remains over the limit

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

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

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

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

s13   "Too big for one agent -- let teammates divide the work" — persistent teammates coordinate, claim ready tasks, and use task-bound working directories

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

s15   "Many mechanisms, one loop" — the mechanisms used by the integrated example share one harness

s16   "When the orchestration shape is fixed, put it in code" — saved workflows with resumable journals

s17   "A goal decides when the loop may stop" — an independent evaluator reviews each proposed stop; impossible, failed, or over-limit goals return control to the user


Learning Path

Main line: act → handle complex work → remember across sessions → run long tasks → collaborate → extend and assemble → orchestrate and close goals.

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/>└─ fresh messages, final text back<br/><br/><b>s08 Context Compact</b><br/>└─ make room in long context"]:::stage2

        S3["<b>3. Remember across sessions</b><br/>━━━━━━━━━━━━━<br/><b>s09 Memory</b><br/>└─ persist and recall reusable knowledge"]:::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>s10 Task System</b><br/>└─ persist tasks and deps<br/><br/><b>s11 Background Tasks</b><br/>└─ send slow work background<br/><br/><b>s12 Cron Scheduler</b><br/>└─ trigger by time"]:::stage4

        S5["<b>5. Coordinate many Agents</b><br/>━━━━━━━━━━━━━<br/><b>s13 Agent Teams</b><br/>└─ teammates + delivery + protocols<br/>└─ atomic task claims<br/>└─ task-bound worktrees"]:::stage5

        S6["<b>6. Extend and assemble</b><br/>━━━━━━━━━━━━━<br/><b>s07 Skill Loading</b><br/>└─ expand skills on demand<br/><br/><b>s14 MCP Plugin</b><br/>└─ external tools, one pool<br/><br/><b>s15 Integrated Harness</b><br/>└─ course mechanisms, one loop"]:::stage6

        S4 ==> S5 ==> S6
    end

    %% Layer 3: orchestration and goal closure
    subgraph Phase3 ["🎯 Stage 7: Orchestration and goal closure"]
        direction LR
        S7["<b>7. Orchestrate and finish</b><br/>━━━━━━━━━━━━━<br/><b>s16 Workflow Runtime</b><br/>└─ scripts own fixed orchestration<br/><br/><b>s17 Goal Loop</b><br/>└─ independent evaluation decides when to stop"]:::stage1
        S6 ==> S7
    end

    %% Connect the three layers
    Phase1 ===> Phase2 ===> Phase3

    class Phase1,Phase2,Phase3 groupBox

All Chapters

Chapter Topic Key Concepts
s01 Agent Loop messages / while True / tool_use
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 SkillLoader / catalog / on-demand injection
s08 Context Compact tool_result_budget / snip_compact / micro_compact / compact_history
s09 Memory System selection / extraction / consolidation
s10 Task System TaskRecord / blockedBy / disk persistence
s11 Background Tasks threaded execution / notification queue
[s12](./s12_cron_sc

learn-claude-code (shareAI-lab/learn-claude-code)

Searching Database…

这是什么?这是一个教学仓库,以 Claude Code 作为参考实现,通过 17 个循序渐进的 Python 课程,教你从零开始构建 “agent harness”(即大语言模型外围的运行环境)。
这是能直接用的工具,还是一门教学课程?这是一门课程,不是产品。17 章各自有 README(附中文和日文译本)、可运行的 code.py,有时还配有示意图,每一章只专注讲解一种 harness 机制。
我该怎么开始学这些课程?克隆仓库,按顺序学习根目录下的 s01 到 s17 文件夹。每个文件夹都包含一个可运行的 code.py,对应该课的机制。
除了 Python,运行这些课程还需要别的东西吗?代码基于 Python 编写。由于课程要构建一个类似 Claude Code 的 harness,你还需要能访问一个大语言模型(Claude),才能真正驱动代码所实现的智能体循环。
课程导航有什么容易让人困惑的地方吗?仓库里保留了一条较早的 12 课“旧版”路线(docs/ 和 agents/),与当前的 17 课根目录路线并存,两者的章节编号对不上,所以混着看编号会让人糊涂。
这门课程面向哪些人?面向“harness 工程师”,即那些在智能体模型外围构建工具、上下文和权限基础设施的开发者,而不是训练模型本身的人。
这门 17 课的课程结构是怎样的?每一课都在单一的核心智能体循环之上,只增加一种 harness 机制,依次是:工具、权限、钩子、技能、上下文压缩、记忆、任务系统、子智能体、后台任务、定时任务、团队、MCP。第 15 课把所有内容整合成一个完整的运行时,第 16 和 17 课则加入工作流编排,以及由目标控制的停止机制。
为什么这门课程用 Claude Code 作为模型的 harness?作者认为 Claude Code 是最优雅的 harness 实现,因为它为模型提供了工具、知识、上下文管理和权限边界,同时不强加僵硬的工作流程,也不依赖手写的决策树。
这门课程反复强调的核心思想是什么?智能体的能力(感知、推理、行动)来自模型训练,而不是来自编排代码。harness 工程师的工作是打造载体(工具、上下文、权限),让训练好的模型去驾驭它,而不是用手写代码去堆砌智能。
这是入门级教程吗?不是。课程默认你已经在概念上理解大语言模型智能体,然后逐步讲解子智能体、上下文压缩、任务图和多智能体团队等越来越高级的机制,因此更适合有一定经验的中级开发者,而非完全的新手。
Size
5.9 MB
Stars
78.7K
Updated
CommitSep 28
Age
1y
Commits · 90 Days