# How the Progression of Sessions in learn-claude-code Works: A 12-Step Guide to Building a Coding Agent

> Master building a Claude-Code agent with our 12-step guide. Explore the progression of sessions in learn-claude-code and add new mechanisms to a core loop.

- Repository: [shareAI-Lab/learn-claude-code](https://github.com/shareAI-lab/learn-claude-code)
- Tags: how-to-guide
- Published: 2026-03-08

---

**The learn-claude-code repository teaches you to build a Claude-Code-style agent through 12 incremental sessions, each adding one isolated mechanism to a fixed core loop while maintaining backward compatibility.**

The progression of sessions in learn-claude-code follows a pedagogical ladder approach, starting from a minimal agent loop and culminating in a fully-featured coding assistant. Developed by shareAI-lab, this repository structures each session (`s01` through `s12`) as a standalone Python module in the `agents/` directory that introduces exactly one new capability without modifying the underlying agent architecture established in the first session.

## The Fixed Core Agent Loop

At the heart of every session lies an unchanged **agent loop** that handles the fundamental interaction pattern with the Large Language Model (LLM). This loop, first established in [`agents/s01_agent_loop.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s01_agent_loop.py), persists through all twelve sessions without modification.

The core implementation follows this pattern:

```python
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   # Exit when the model stops calling tools

        # Dispatch every tool call to its handler

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

```

This loop handles message creation, tool dispatch via the `TOOL_HANDLERS` dictionary, and result collection. Every subsequent session adds new entries to `TOOLS` and `TOOL_HANDLERS`, or wraps this loop with additional logic, but never modifies the loop itself.

## The 12-Session Progression Explained

The progression of sessions in learn-claude-code follows a strict additive architecture. Each session introduces exactly one isolated mechanism, represented by a motto that captures its pedagogical purpose.

### Session 1 (s01): Basic Agent Loop with Bash

**Mechanism added:** The fundamental agent loop plus a single `bash` tool.

**Motto:** *"One loop & Bash is all you need"*

**Key file:** [`agents/s01_agent_loop.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s01_agent_loop.py)

This session establishes the foundation. The agent can execute shell commands through the `bash` tool but has no specialized file manipulation capabilities.

### Session 2 (s02): Tool Dispatch and File Operations

**Mechanism added:** A tool dispatch map with additional safe tools for file operations.

**Motto:** *"Adding a tool means adding one handler"*

**Key file:** [`agents/s02_tool_use.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s02_tool_use.py)

This session introduces `read_file`, `write_file`, and `edit_file` tools with path validation through a `safe_path()` function. The `TOOL_HANDLERS` dictionary maps tool names to their implementations, establishing the pattern for extensibility without core loop modification.

### Session 3 (s03): Todo-List Planning Layer

**Mechanism added:** A planning layer that maintains a todo list of steps to execute.

**Motto:** *"An agent without a plan drifts"*

**Key file:** [`agents/s03_todo_write.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s03_todo_write.py)

The `TodoManager` class creates structured plans. The agent first produces a todo list, then executes each step sequentially, verifying completion before proceeding. This prevents drift in complex multi-step tasks.

### Session 4 (s04): Sub-Agents with Independent Contexts

**Mechanism added:** Sub-agents that maintain independent message histories.

**Motto:** *"Break big tasks down; each subtask gets a clean context"*

**Key file:** [`agents/s04_subagent.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s04_subagent.py)

The `SubAgent` class encapsulates separate `messages` lists. When the parent agent delegates a task, the sub-agent operates with a clean context, preventing context pollution and allowing parallel exploration of different approaches.

### Session 5 (s05): Lazy-Loaded Skills

**Mechanism added:** Knowledge files loaded on demand via `tool_result` injection.

**Motto:** *"Load knowledge when you need it, not upfront"*

**Key file:** [`agents/s05_skill_loading.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s05_skill_loading.py)

The `run_skill(name)` function reads markdown files from the `skills/` directory and injects them as tool results. This prevents token bloat by loading domain-specific knowledge only when explicitly requested.

### Session 6 (s06): Multi-Layer Context Compression

**Mechanism added:** Three-layer compression to manage context window limits.

**Motto:** *"Context will fill up; you need a way to make room"*

**Key file:** [`agents/s06_context_compact.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s06_context_compact.py)

The `compress_context()` function implements in-memory caching, on-disk JSON storage, and LLM-based summarization. When the message history grows too large, older messages are compressed and archived rather than discarded.

### Session 7 (s07): Persistent Task Graph

**Mechanism added:** File-based task graph with dependency tracking.

**Motto:** *"Break big goals into small tasks, order them, persist to disk"*

**Key file:** [`agents/s07_task_system.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s07_task_system.py)

The `TASKS.create()` method generates JSON files under `.tasks/` describing status and dependencies. This enables complex workflow management with explicit dependency chains that survive process restarts.

### Session 8 (s08): Background Task Execution

**Mechanism added:** Daemon threads for long-running operations.

**Motto:** *"Run slow operations in the background; the agent keeps thinking"*

**Key file:** [`agents/s08_background_tasks.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s08_background_tasks.py)

The `BackgroundRunner` class manages a thread pool for executing long commands. Results are posted to a `notifications_queue`, allowing the agent to continue processing other tasks while waiting for slow operations to complete.

### Session 9 (s09): Agent Teams with Mailboxes

**Mechanism added:** Persistent JSONL mailboxes for inter-agent communication.

**Motto:** *"When the task is too big for one, delegate to teammates"*

**Key file:** [`agents/s09_agent_teams.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s09_agent_teams.py)

The `Mailbox` class provides shared JSONL files for message passing. Multiple agents can read from and write to these mailboxes, enabling coordination without direct memory sharing.

### Session 10 (s10): Team Negotiation Protocols

**Mechanism added:** Request-response finite state machine for task delegation.

**Motto:** *"Teammates need shared communication rules"*

**Key file:** [`agents/s10_team_protocols.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s10_team_protocols.py)

The `TeamProtocol.handle_request()` method implements a structured negotiation protocol. This finite state machine coordinates who accepts which tasks, preventing conflicts in multi-agent workflows.

### Session 11 (s11): Autonomous Task Claiming

**Mechanism added:** Idle-cycle scanning for autonomous task acquisition.

**Motto:** *"Teammates scan the board and claim tasks themselves"*

**Key file:** [`agents/s11_autonomous_agents.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s11_autonomous_agents.py)

The `AutonomousAgent.idle_loop()` method enables agents to periodically scan the task board during idle cycles. When unassigned tasks are detected, agents claim them automatically without explicit delegation.

### Session 12 (s12): Git Worktree Isolation

**Mechanism added:** Per-task git worktrees for filesystem isolation.

**Motto:** *"Each works in its own directory, no interference"*

**Key file:** [`agents/s12_worktree_task_isolation.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s12_worktree_task_isolation.py)

The `WORKTREES.create(name, task_id=...)` method generates isolated git worktrees under `.worktrees/`. Each task operates in its own directory, preventing file conflicts when multiple agents or tasks run concurrently.

## Running the Complete Capstone

After understanding the individual components of the progression of sessions in learn-claude-code, you can run the capstone script that combines all twelve mechanisms:

```bash
python agents/s_full.py   # all mechanisms combined

```

This script demonstrates how each layer composes cleanly without altering the original `while True:` core loop established in session 1. Because every session only **adds** data structures or background processes while re-using the same core, you can experiment by swapping, disabling, or extending any layer without breaking the fundamental agent architecture.

## Summary

The progression of sessions in learn-claude-code provides a pedagogical ladder for constructing a Claude-Code-style coding agent through incremental complexity:

- **Fixed Foundation**: The core agent loop in [`agents/s01_agent_loop.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s01_agent_loop.py) remains unchanged across all twelve sessions
- **Additive Architecture**: Each session `s01` through `s12` introduces exactly one isolated mechanism without modifying existing code
- **Capability Evolution**: Features progress from basic bash execution through tool dispatch, planning layers, sub-agents, context compression, persistent task graphs, background processing, multi-agent teams, autonomous claiming, and git worktree isolation
- **Modular Composition**: All layers combine cleanly in [`agents/s_full.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s_full.py), demonstrating that complex agent behavior emerges from simple, composable additions to an unchanging core

## Frequently Asked Questions

### How does the progression of sessions in learn-claude-code maintain backward compatibility?

The repository uses an **additive architecture** where the core agent loop established in session 1 never changes. Subsequent sessions only extend the `TOOL_HANDLERS` dictionary, add wrapper classes, or introduce background processes. Because the fundamental `while True:` loop in [`agents/s01_agent_loop.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s01_agent_loop.py) remains untouched, code from earlier sessions continues to function correctly when imported into later implementations.

### What is the difference between sub-agents (s04) and agent teams (s09)?

**Sub-agents** (session 4) provide **context isolation** for individual tasks within a single agent process. The `SubAgent` class maintains its own `messages` list, preventing the parent context from being polluted when exploring specific implementation details.

**Agent teams** (session 9) enable **inter-process communication** between multiple independent agents. The `Mailbox` class uses persistent JSONL files for message passing, allowing separate agent processes to coordinate on large tasks through shared mailboxes rather than shared memory.

### Can I skip intermediate sessions and jump directly to the final implementation?

While the capstone script [`agents/s_full.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s_full.py) contains all mechanisms combined, **skipping sessions is not recommended for learning**. Each session builds conceptual understanding necessary for the next layer. For example, understanding context compression (s06) requires grasping why sub-agents (s04) create context isolation needs that lead to message accumulation. The documentation in `docs/en/` provides essential architectural context for each incremental step.

### How does session 12 (worktree isolation) differ from session 4 (sub-agents)?

**Session 4 (sub-agents)** provides **logical isolation** through separate message histories within the same filesystem context. All sub-agents operate on the same working directory and can potentially interfere with each other's files.

**Session 12 (worktree isolation)** provides **physical isolation** through git worktrees. The `WORKTREES.create()` method in [`agents/s12_worktree_task_isolation.py`](https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s12_worktree_task_isolation.py) generates separate directories under `.worktrees/`, ensuring that concurrent tasks cannot interfere with each other's filesystem operations even when running simultaneously in autonomous mode (s11).