Inside Claude Code’s Harness: How Loops, Planning, Sandboxes, and Memory Power AI Programming
The article dissects Claude Code’s harness control framework, showing how a simple execution loop, planning layer, sandboxed tools, hierarchical delegation, and persistent memory—implemented with CrewAI—enable reliable AI‑driven code fixing, while highlighting trade‑offs, overhead, and future limitations.
Building an AI programming assistant depends more on a reliable control framework (the Harness) than on using a larger language model. The Harness wraps ordinary code around the model to handle planning, tool execution, memory management, and safety, allowing the model to focus solely on deciding the next step.
Four Core Components of the Harness
Memory system supplies context and cross‑session knowledge to the model.
Skill layer encodes how the agent should act, including workflows and constraints.
Protocol layer connects users, tools, and other agents.
Core layer orchestrates sub‑agents, sandbox environments, evaluators, approval loops, observability, and context compression.
Anthropic describes this split as a "brain" (the model) and "hands" (the Harness). Claude Code is a production‑grade example where the Harness is the decisive factor for stability.
Recreating Claude Code with CrewAI
The author rebuilt the Harness using the open‑source CrewAI framework and validated it on a buggy bank‑account class. The reconstruction revealed many features that map directly to CrewAI’s built‑in capabilities, while other parts required custom engineering.
Core Execution Loop
python
while True:
reply = model(messages, tools)
calls = [b for b in reply if b.type == "tool_use"]
if not calls: # pure text, no tool call: task complete
return reply.text
messages += [reply, run_all(calls)]CrewAI embeds this infinite loop automatically; defining an agent and a task is enough to start the process.
Tool Integration
Tools give the model "hands"—the ability to read/write files, list directories, execute shell commands, or run custom Python functions. Example tool definitions:
python
from crewai_tools import DirectoryReadTool, FileReadTool, FileWriterTool
read_file = FileReadTool()
write_file = FileWriterTool()
list_dir = DirectoryReadTool()Custom tools are created with the @tool decorator, where the docstring serves as the model’s instruction.
python
from crewai.tools import tool
import subprocess
@tool("run_tests")
def run_tests(path: str = "tests/") -> str:
"""Run the pytest suite at the given path and return the result."""
result = subprocess.run(["pytest", path, "-q"], capture_output=True, text=True, timeout=120)
output = result.stdout + result.stderr
return output[-4000:] if len(output) > 4000 else outputPlanning Layer
Long‑running tasks suffer from "context decay" as intermediate results fill the window. The planning layer generates a step‑by‑step plan that stays in context throughout execution, acting as a map for the model. In CrewAI this is enabled with planning=True and an optional planning LLM:
python
crew = Crew(
agents=self.agents,
tasks=self.tasks,
planning=True,
planning_llm=LLM(model="gpt-4o-mini"),
)Agents can also enable reasoning mode, allowing them to self‑reflect before acting.
Hierarchical Delegation
To avoid the main agent’s context from being overwhelmed, sub‑agents handle subtasks. A manager agent delegates work to specialist agents, each operating in its own context and returning concise summaries.
python
explorer = Agent(
role="Codebase Explorer",
goal="Map the repository and surface relevant files.",
tools=[FileReadTool(), list_dir],
llm=llm,
)
coder = Agent(
role="Software Engineer",
goal="Implement the requested change.",
tools=filesystem_tools,
reasoning=True,
llm=llm,
)
tester = Agent(
role="Test Runner",
goal="Run tests in a sandbox and report results.",
tools=sandbox_tools + [FileReadTool(), run_tests],
llm=llm,
)
manager = Agent(
role="Engineering Lead",
goal="Delegate steps and finish once tests pass.",
allow_delegation=True,
llm=llm,
)Sandbox Safety
Agents with terminal access could execute destructive commands. Safety is enforced by two layers: permission checks and sandbox isolation. CrewAI’s E2B tools run code inside a temporary VM that is destroyed after execution.
python
from crewai_tools import E2BExecTool, E2BPythonTool
sandbox_tools = [E2BExecTool(), E2BPythonTool()]Human Approval
Critical tasks can require human review by setting human_input=True on a Task. The crew pauses after the agent’s answer, awaiting manual approval before proceeding.
Memory and Checkpoints
By default agents forget after a run. Persistent memory and checkpoints preserve state across sessions. Memory extracts important facts via the LLM and stores them for later retrieval; checkpoints snapshot configuration, task status, and intermediate results.
python
crew = Crew(
agents=[explorer, coder, tester],
tasks=[task],
memory=True,
checkpoint=True,
)Full Configuration Example
python
from crewai import Agent, Crew, LLM, Process, Task
from crewai.tools import tool
from crewai_tools import (
DirectoryReadTool, FileReadTool, FileWriterTool,
E2BExecTool, E2BPythonTool,
)
llm = LLM(model="anthropic/claude-sonnet-4.6")
list_dir = DirectoryReadTool(directory="./workspace")
filesystem_tools = [FileReadTool(), FileWriterTool(), list_dir]
sandbox_tools = [E2BExecTool(), E2BPythonTool()]
@tool("run_tests")
def run_tests(path: str = "tests/") -> str:
"""Sync ./workspace into the sandbox, then run pytest there."""
return E2BExecTool().run(command=sync_and_test_command(path))
explorer = Agent(role="Codebase Explorer", goal="Map repo, surface relevant files.", tools=[FileReadTool(), list_dir], llm=llm)
coder = Agent(role="Software Engineer", goal="Implement requested change.", tools=filesystem_tools, reasoning=True, llm=llm)
tester = Agent(role="Test Runner", goal="Run tests in sandbox, report pass/fail.", tools=sandbox_tools + [FileReadTool(), run_tests], llm=llm)
manager = Agent(role="Engineering Lead", goal="Delegate steps, finish once tests pass.", allow_delegation=True, llm=llm)
task = Task(
description="In ./workspace, {objective}. Explore, edit, test, and report.",
expected_output="Summary of changes and test output.",
human_input=True,
)
crew = Crew(
agents=[explorer, coder, tester],
tasks=[task],
manager_agent=manager,
process=Process.hierarchical,
planning=True,
memory=True,
checkpoint=True,
)
result = crew.kickoff(inputs={"objective": "fix failing tests in account.py"})The configuration was run against a small bank‑account module containing two real bugs and five tests (three initially failing). With the rule that only implementation code may be changed, the harness turned three failures into five passing tests, demonstrating the framework’s effectiveness.
Limitations and Overhead
The harness adds API‑call overhead; complex agent setups can become more expensive than a single model call.
Prompt engineering, sandbox provisioning, and tool selection remain manual responsibilities.
Some harness components are temporary patches for current model limitations and may become unnecessary as models improve.
In summary, the majority of an AI programming agent’s capability resides in the Harness control system, and a well‑designed orchestration framework like CrewAI provides far more of this infrastructure out‑of‑the‑box than many expect. The real engineering work begins where the framework ends.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
