Complete Guide ยท 10 Sections ยท ~4 Hours

From Zero to
AI Agent Harness

The ultimate step-by-step guide. Every command. Every error. Every solution. From your first terminal command to your own AI system.

10Sections
24CLI Commands
49Tests
30+Subsystems
Your Progress0%
01

Setting Up Your Workspace

Install Python, Git, and terminal โ€” for Windows, macOS, and Linux. Every step explained, every error solved.

Beginner 20 Min

What You'll Have at the End

A fully set up development system with Python 3.8+, Git for version control, and a terminal that can run all project commands.

Step 1: Install Python

๐Ÿ’ก
Good News
Claw Code requires no external dependencies โ€” everything runs with the Python standard library.
1
Check Python Version
Open your terminal and type:
python3 --version (macOS/Linux) or python --version (Windows)
2
Install Python (if needed)
Windows: Download from python.org
macOS: brew install python3 or installer from python.org
Linux: sudo apt install python3 (Ubuntu/Debian)
3
Verify Installation
Run python3 --version again. You should see Python 3.8 or higher.

Step 2: Install Git

bash
$ git --version
git version 2.34.1

# If not installed:
# Windows: https://git-scm.com/download/win
# macOS: brew install git
# Linux: sudo apt install git

Step 3: Download the Project

bash
# Navigate to your projects folder
$ cd ~/Documents

# Clone the repository
$ git clone https://github.com/instructkr/claw-code.git
Cloning into 'claw-code'...

# Change into the project directory
$ cd claw-code

# Verify the structure
$ ls
src/ tests/ assets/ README.md ANLEITUNG.md
โœ…
Section 1 Complete!
Your system is ready. You have Python, Git, and the Claw Code repository installed.
โš ๏ธ
Common Errors
"python3: command not found" โ†’ Use python instead of python3 on Windows
"Permission denied" โ†’ Run terminal as Administrator
"git: command not found" โ†’ Git is not in PATH โ€” restart or update PATH
02

Cloning the Repository & First Commands

Understand the directory structure and run the first three essential commands.

Beginner 15 Min

Understanding Project Structure

Folder/FilePurpose
src/Main source code โ€” all Python modules
src/main.pyCLI entry point with 24 commands
src/commands.py~150 command metadata entries
src/tools.py~100 tool metadata entries
src/runtime.pyPrompt routing & sessions
tests/49 test cases
ANLEITUNG.mdComplete command reference (German)

The First Three Commands

1
Show Porting Overview
Displays a summary of the entire Python workspace.
bash
$ python3 -m src.main summary

# Claw Code โ€” Porting Overview

## Python Workspace
- **Files:** 25 Python files
- **Subsystems:** 30+ modules
- **Commands:** ~150 mirrored
- **Tools:** ~100 mirrored
2
Show File Structure
Lists all Python files grouped by modules.
$ python3 -m src.main manifest

== Python Port Manifest ==
src/main.py
src/models.py
src/commands.py
src/tools.py
... (more files)
3
List Subsystems
Shows the top-level modules of the project.
$ python3 -m src.main subsystems --limit 10

Subsystems (10 of 30+):
- assistant
- bridge
- commands
- context
- ...
โš ๏ธ
Important
All commands must be run from the project root directory (where the src/ folder is). If you get errors, check with pwd that you're in the right folder.
03

The Three-Layer Architecture

Mirror layer, orchestration, infrastructure โ€” how the layers work together and which files go where.

Beginner Core Concept 25 Min

Architecture Overview

Claw Code follows a clear Three-Layer Model. This separation allows the system to be understood and extended modularly.

LayerFilesPurpose
Mirrorcommands.py, tools.py, reference_data/JSON snapshots as immutable reference
Orchestrationruntime.py, query_engine.pyPrompt routing, sessions, turn-loops
Infrastructuresetup.py, context.py, session_store.pyEnvironment, persistence, logging

Layer 1: Mirror Layer

This layer loads the archived JSON snapshots and provides them as typed Python objects:

  • commands.py โ€” Loads ~150 commands from reference_data/commands_snapshot.json
  • tools.py โ€” Loads ~100 tools from reference_data/tools_snapshot.json
  • LRU cache for fast access
  • Immutable data structures (Frozen Dataclasses)

Layer 2: Orchestration Layer

This is where the "intelligence" of the system happens:

  • runtime.py โ€” PortRuntime.route_prompt() tokenizes prompts and finds matching commands/tools
  • query_engine.py โ€” QueryEnginePort manages session states and message streams
  • Token-based scoring for matching
  • Multi-turn loops with budget control

Layer 3: Infrastructure Layer

Everything that keeps the system running:

  • setup.py โ€” Environment detection, prefetch operations
  • context.py โ€” Workspace context (paths, file count)
  • session_store.py โ€” Persistence in .port_sessions/
  • Trust-gating for secure initialization
python
# View the bootstrap phases
$ python3 -m src.main bootstrap-graph

Bootstrap Phases:
1. Prefetch
2. Trust Gate
3. CLI Parser
4. Setup
5. Deferred Init
6. Mode Routing
7. Query Submit
04

Exploring Commands & Tools

Browse, filter, and view in detail the catalog of ~150 commands and ~100 tools.

Core 20 Min

List Commands

bash
# Show all commands
$ python3 -m src.main commands

# Show only first 10
$ python3 -m src.main commands --limit 10

# Search for "git"
$ python3 -m src.main commands --query "git"

# Hide plugin commands
$ python3 -m src.main commands --no-plugin-commands

List Tools

# Show all tools
$ python3 -m src.main tools

# Search for "file"
$ python3 -m src.main tools --query "file"

# Block specific tool
$ python3 -m src.main tools --deny-tool Bash

# Hide all MCP tools
$ python3 -m src.main tools --no-mcp

View Individual Entries

1
Show Command Details
python3 -m src.main show-command "commit" โ€” Shows name, responsibility, and source hint of a command.
2
Show Tool Details
python3 -m src.main show-tool "Read" โ€” Shows detailed information about a tool.
๐Ÿ’ก
Pro Tip
Use --simple-mode with tools for a compact view when you only need names and short descriptions.
05

Understanding Prompt Routing

How the token scoring algorithm routes a prompt to the right commands and tools.

Core 30 Min

The Routing Algorithm

The heart of the system is PortRuntime.route_prompt(). It transforms natural language into executable commands and tools.

PhaseDescription
1. TokenizationPrompt is normalized: / and - โ†’ spaces, lowercase, deduplication
2. ScoringFor each command/tool: How many tokens match in name, source hint, responsibility?
3. Fair-ShareOne best match per category guaranteed
4. Fill-upRest sorted by score up to the limit

Try Routing

bash
# Route a prompt
$ python3 -m src.main route "Create a new branch"

Routed Matches:
1. Command: git-branch (Score: 0.85)
2. Tool: Bash (Score: 0.72)
3. Command: commit (Score: 0.45)
...


# Adjust limit
$ python3 -m src.main route "Read the file" --limit 3

How the Score is Calculated

The algorithm compares prompt tokens with:

  • Command Name โ€” exact word match
  • Source Hint โ€” where the command comes from
  • Responsibility โ€” what the command does

The more tokens match, the higher the score (0.0 to 1.0).

06

Sessions & Bootstrap

Build a complete runtime session, persist it, and restore it.

Core 25 Min

Session Lifecycle

1
Create Session
QueryEnginePort.from_workspace() collects workspace context and creates a new session.
2
Process Prompt
submit_message() processes the prompt and updates the transcript.
3
Compaction
compact_messages_if_needed() reduces the transcript when necessary.
4
Persistence
persist_session() saves the session to .port_sessions/.

Run Bootstrap

bash
# Start complete session
$ python3 -m src.main bootstrap "Analyze the codebase"

Session Report:
Session ID: sess_abc123xyz
Commands matched: 5
Tools matched: 3
Status: success


# Save session
$ python3 -m src.main flush-transcript "My Analysis Session"

# Load session
$ python3 -m src.main load-session sess_abc123xyz
๐Ÿ’ก
Session ID
The Session ID is displayed with every bootstrap and flush. Save it to restore the session later.
07

Turn-Loops & Budget System

Execute multi-turn loops, understand token budgets, and control stop conditions.

Core 25 Min

What are Turn-Loops?

A Turn is one pass through the system: Prompt โ†’ Routing โ†’ (simulated) Execution โ†’ Response. Turn-loops execute multiple turns in sequence, similar to how a real agent works.

Execute Turn-Loop

bash
# Default: up to 5 turns
$ python3 -m src.main turn-loop "Refactor the code"

# Limit number of turns
$ python3 -m src.main turn-loop "Refactor" --max-turns 3

# JSON output for further processing
$ python3 -m src.main turn-loop "Analyze" --structured-output

Budget System

The system tracks token consumption across turns:

  • Input Tokens โ€” Prompt length
  • Output Tokens โ€” Generated response
  • Total Budget โ€” Maximum tokens per session

On budget overrun, automatic compaction or stopping occurs.

โš ๏ธ
Note
The budget system is currently a simulation in this port. It shows how the original system manages resources without incurring real API costs.
08

Permission System & Security

Trust-gating, tool permissions, and the 7 bootstrap phases in detail.

Advanced 20 Min

Trust-Gating

Deferred initialization is controlled via a trusted parameter:

  • trusted=True โ†’ Plugins, skills, MCP-prefetch, and session hooks enabled
  • trusted=False โ†’ All deferred initializations disabled

Tool Permissions

bash
# Block single tool
$ python3 -m src.main tools --deny-tool Bash

# Block multiple tools
$ python3 -m src.main tools --deny-tool Bash --deny-tool Write

# Block by prefix (all MCP tools)
$ python3 -m src.main tools --deny-prefix mcp__

The 7 Bootstrap Phases

  1. Prefetch โ€” Pre-load resources
  2. Trust Gate โ€” Trust verification
  3. CLI Parser โ€” Parse arguments
  4. Setup โ€” Initialize environment
  5. Deferred Init โ€” Deferred initialization
  6. Mode Routing โ€” Select operating mode
  7. Query Submit โ€” Process prompt
$ python3 -m src.main bootstrap-graph
09

Tests & Quality Assurance

Run all 49 tests, perform parity audit, interpret port manifest.

Advanced 15 Min

Run Tests

bash
# All tests with verbose output
$ python3 -m unittest discover -s tests -v

test_commands_load (test_porting_workspace.TestWorkspaceBasics) ... ok
test_tools_load (test_porting_workspace.TestRuntimeBasics) ... ok
test_runtime_bootstrap (test_porting_workspace.TestRuntimeBasics) ... ok
... (49 tests total)

Parity Audit

Compares the Python workspace with the archived TypeScript snapshot:

$ python3 -m src.main parity-audit

Parity Audit Report:
- Root file coverage: 85%
- Directory coverage: 90%
- Command entries: 100%
- Tool entries: 100%

What is Being Tested?

  • All 24 CLI commands
  • Command and tool catalog loading
  • Session management
  • Prompt routing
  • Turn-loop execution
  • JSON snapshot validity
โœ…
Success Criterion
All 49 tests should pass with "OK". If there are failures, check your Python version (must be 3.8+).
10

Building Your Own AI System

Create custom commands and tools, implement your own routing strategies, extend the system.

Advanced 40 Min

Add Custom Commands

Commands are defined in src/reference_data/commands_snapshot.json. A command has this structure:

json
{
  "name": "my-command",
  "responsibility": "Description of what the command does",
  "source_hint": "my_module",
  "args": ["arg1", "arg2"]
}

Add Custom Tools

Tools follow a similar schema in src/reference_data/tools_snapshot.json:

{
  "name": "MyTool",
  "description": "Description of tool functionality",
  "permission_level": "read-only"
}

Customize Routing Strategy

In src/runtime.py you can modify the scoring algorithm:

# Example: Adjust weighting
def _score(self, tokens, entry):
  score = 0
  score += len(tokens & entry.name_tokens) * 2.0 # Name more important
  score += len(tokens & entry.desc_tokens) * 1.0
  return score / len(tokens)

Create New Subsystem

New subsystems are created as packages under src/:

# Create new subsystem "custom"
$ mkdir src/custom
$ touch src/custom/__init__.py
$ touch src/custom/engine.py

# In src/custom/__init__.py:
from .engine import CustomEngine

__all__ = ["CustomEngine"]
๐Ÿ’ก
Architecture Tip
Maintain the three-layer architecture: Mirror (data), Orchestration (logic), Infrastructure (persistence). This keeps your code maintainable.
๐ŸŽ‰
Congratulations!
You've completed the entire guide. You now understand the architecture of an AI Agent Harness and can build your own extensions. Time to implement your ideas!