Same model, four machines around it. The bare chat stalls at 36 of 100 steps. The full harness finishes all 100 in 25 minutes, with none of your time.
Pick a machine, then press Run. Watch the steps, the context window and the files. Then we build each part, piece by piece: the loop, the files, the sub-agents and the tool belt.
You need to have used a chatbot or a coding agent and a little Python for the code. We build the rest from zero.
Based on Lilian Weng, Harness Engineering for Self-Improvement (Lil'Log, 4 July 2026). We use its introduction, its three design patterns, its coding-agent case study and “Harness Layer vs Core Intelligence”. This is the first lesson of a trilogy; Harness Optimization and Self-Improving Harnesses follow.
Illustrative toy, not a benchmark. The task needs 100 tool steps plus a 20-step side quest. Each step returns 3,000 tokens into a 200,000-token window. A human turn takes 100 s and a tool turn 15 s; the human gives up after 60 minutes.
Chapter 0
See why the code around a model decides what the model can get done
Two engineers get the same model on the same day. The first pastes a bug report into a chat window. She copies the suggested fix into her editor, runs the tests, and pastes the failure back. Forty minutes later she has a fix.
The second points a coding agent at the repository and types "the date parser fails in CI, fix it". He gets coffee. The agent finds the failing test, edits two files, reruns the tests until they pass, and commits. Same weights. Different machine.
That machine is the harness: the system around a base model that runs it and decides five things (Weng, 2026).
| The harness decides how the model | In a bare chat | Inside a harness |
|---|---|---|
| thinks and plans | the plan lives in your head | the model writes a plan first; the harness keeps it in view |
| calls tools and acts | you copy text into your editor | bash and edit run for real |
| perceives and manages context | you choose what to paste back | a rule trims every tool result |
| stores artifacts | scrollback, gone with the tab | files that outlast the session |
| evaluates results | you run the tests and judge | tests rerun after each edit |
In the bare column, every job falls to you. Your attention is the bottleneck. How much does that cost?
Call the number of turns a task needs N. Call the seconds one turn takes t. In a chat, a turn is a human round trip: read, decide, paste. In a harness, a turn is one tool call.
T equals N times t.
Count the turns N. Multiply by the time t of one turn. That is the time T you wait.
With made-up numbers: N = 30 turns. Bare chat, t = 100 s: T = 3,000 s, or 50 minutes, about 45 of them yours. Harness, t = 15 s: T = 450 s, or 7.5 minutes, none of them yours.
Yellow is your time in the bare chat. Blue is tool time in the harness. Drag the turns and watch the bare bar cross your patience line.
Illustrative: 100 s per human turn (90 s of it yours), 15 s per tool turn, and a 60-minute patience line. We made up the exact values; the shape is the point.
Human attention caps the bare lane, and attention tires and goes home. Compute caps the harness lane, and compute scales. Weng states the claim: the layer between the raw model and the real world "seems to be as important as the model's raw intelligence".
The failure. The symptom: users say "the model is dumb today", but the weights did not change. To measure it, rerun the same task with the same model in a second harness. If the result changes, the harness is at fault. The fix lives in this lesson: a bad truncation rule, a blocked test runner or a verifier that passes everything.
Chapter 1
Add the four parts the old agent recipe missed, and see the harness as an operating system
For years the recipe was: agent = model + memory + tools + planning + action. It worked for tasks that took seconds. Then agents ran for hours, and three questions had no answer. Who checks the work? What may the agent touch? What survives when the session ends?
Weng lists what harness engineering adds to the recipe:
The job stops being a prompt template, which is text with blanks. It becomes a runtime: a running program with state, a schedule, retries and a budget. You cannot store a budget in a string.
pythonTEMPLATE = "You are a coding agent. Task: {task}. Think step by step." # text with blanks class AgentRuntime: # the same intent, as a machine def __init__(self, task, budget=20): self.task, self.budget = task, budget # workflow: a lap counter self.allowed = {"read": "anywhere", "edit": "repo-only", "bash": "ask-if-destructive"} # permissions: a table self.log = open("state/trajectory.log", "a") # persistent state def should_stop(self): self.budget -= 1 return self.budget <= 0 or tests_pass() # evaluation: a verifier, not a feeling
The post asks for a design that is "deliberately simple and generic", so it works on tasks nobody planned for. It also asks the harness to follow existing software practice, "to benefit from pretraining knowledge". A model has read millions of bash sessions and git logs. It knows grep -rn without a lesson. A private command language costs context to teach and gets no help from the next model.
Weng draws the analogy: a harness is to a model what an operating system is to hardware. It hides complex logic behind a small interface. Your editor calls open() and never sees disk sectors. The model calls read or bash and never sees the retry policy. The device sends one tool call down this stack.
The model at the bottom proposes a call. The harness kernel checks it, runs it and trims the result. Pick a call and press Send.
Illustrative sizes. The layer names follow the post's analogy; the 2,000-character cut is a common trimming rule, not a fixed standard.
The analogy breaks in one place. A CPU does what it is told; a model can call the wrong tool or invent arguments. So a harness treats each call as a proposal to check, never an order. The Loop Engineering lesson splits the same machine into a harness layer and a loop layer. Weng's "harness" covers both.
The failure. Symptom: an agent deletes files outside the repo. Measure: grep the trajectory for writes and see which ones no rule checked. Fix: an explicit permission table that the harness enforces before execution, not a sentence in the prompt.
Chapter 2
Place the harness inside the loop where models help build their successors, and see it set the rate
In 1965, I. J. Good described a machine that could surpass humans in all intellectual work. Designing machines is intellectual work, so it could design a better machine. In 2008, Eliezer Yudkowsky named the loop recursive self-improvement (RSI): a system uses its intelligence to improve the machinery that produces its intelligence.
Weng expects the near-term path "is unlikely to start as a model directly rewriting its weights". Instead, the model improves the training pipeline and the deployment system. That machinery then produces a better successor model. The post cites reports from Anthropic and OpenAI that AI already speeds up research in their labs.
Every action a model takes on that pipeline goes through its harness: running experiments, reading logs, editing configs. The harness is the model's hands. Clumsy hands slow the loop, even with a smart model.
Here is arithmetic for intuition, not a forecast. Call today's capability C0. Say each trip around the loop multiplies capability by a loop gain g. After n trips, capability is Cn.
C-n equals C-zero times g to the n.
Start at C-zero. Multiply by g once for each trip. After n trips you have C-n.
With made-up numbers and n = 5: g = 0.95 gives 0.955 = 0.77, a drain. g = 1.15 gives 1.155 = 2.01, a doubling. A gap of 0.2 in g separates decay from doubling.
The gain is not one dial. Each stage of the loop keeps some share of the value it receives. Call the three stage factors eexp for experiments, edata for training data and eeval for evaluation.
g equals e-exp times e-data times e-eval.
Multiply the three stage factors. One weak stage pulls down the whole gain g.
With made-up numbers: e-exp = 1.2, e-data = 1.1, e-eval = 0.9 gives g = 1.188. Repair only the eval to 1.0 and g = 1.32, which is 11% higher. Over 5 trips that is 2.37 against 4.01.
The warm curve is your loop. The dashed curves are g = 0.95 and g = 1.15. Drag the weakest stage up and watch the whole curve lift.
Toy arithmetic, not a forecast. Real capability is not one number, and gains saturate. The model only shows that a product of stages rewards fixing the weakest one.
The failure. Symptom: a loop that runs and runs while each new model is no better. Measure: score each stage on fixed tasks and find the factor below 1. Fix: repair that stage first, often the evaluation, because a product is only as strong as its weakest factor.
Chapter 3
Turn one guess into a loop that plans, acts, observes and improves until a check says done
A one-shot answer is fixed by the prompt. Whatever the model did not know at the start, it never learns. The first pattern fixes that: give the model a workflow in which it can "operate, test, and iterate". The shape is a goal-directed loop:
Weng's figure of the Codex loop says it in one line: "the agent calls tools and tool responses affect the model's next generation". You wrote the prompt before the test failed. Only the loop can carry that failure into the next step.
The ring lights the current stage; the log shows each event. Press Step. Then switch on a flaky test, a weak verifier or asking first, and run it again.
A scripted episode, made for this page. The weak verifier checks only that the code compiles.
Count the laps in the clean run. The first test run fails, the agent edits line 41, the second run passes, and the loop exits: two laps. A flaky test costs one extra lap. The loop reruns the suspect test, sees it pass, and moves on.
The loop may also stop to ask the user, about the task or about a preference. "Should the parser accept two-digit years?" costs the user ten seconds. A wrong guess costs a whole run in the wrong direction.
pythondef agent_loop(goal, model, run_tool, max_turns=20): history = [goal] for _ in range(max_turns): # budget: the loop cannot spin forever tool, args = model(history) # PLAN: one tool call out = run_tool(tool, args) # ACT history.append(out[-2000:]) # OBSERVE: keep the tail, where errors live verdict = run_tool("bash", "pytest -q | tail -3") if "failed" not in verdict and "error" not in verdict: return "goal met" # an objective check, not confidence history.append(verdict) # IMPROVE: the failure feeds the next plan return "budget spent: stop and report"
| How a loop dies | Symptom | Fix in the code |
|---|---|---|
| Stall | the same tool call again and again | failures stay in history so the plan must change |
| Thrash | a new plan every turn, nothing finishes | keep the plan as a file; revise it, do not restart |
| Token furnace | turn 400 of a 12-turn task | max_turns: stop and report |
| False victory | "Done!" with the bug still there | exit only on a strong check |
The failure. Turn on the weak verifier. The agent exits after one lap with the bug alive, because it passed the check you gave it. Measure: run the strong test suite on the "finished" work. Fix: choose what "done" measures with care, and stack checks: compile, then tests, then a person for decisions that matter.
Chapter 4
Keep the working set in the window and everything else on disk, one grep away
A loop that runs for hours piles up logs, diffs, error traces and old trajectories. Weng notes these "often grow much longer than the context window that the model has trained for". The second pattern is "simple control over rich states and artifacts": keep durable state in files, not in context.
Think of the context window as RAM: fast, small, and wiped when the session ends. Files are disk: one tool call away, large, and durable. The window holds the current goal, the plan and the last few results. Disk holds the rest. The agent gets it back with grep and a thin read.
How far over the window does "keep everything" go? Call the number of tool calls N, the average tokens per result s and the window size W. The raw total is Traw.
T-raw equals N times s, compared with W.
Multiply the number of calls N by the size s of each result. Compare T-raw with the window W. If T-raw is larger, something falls out.
With made-up numbers: N = 400, s = 3,000, W = 200,000. T-raw = 1,200,000, which is 6 windows. With files: keep the last 10 results (30,000 tokens) plus a 500-token grep slice. That is 30,500 tokens, 15% of one window.
The bar is the window. The yellow block is the constraint from step 1: "the public API is frozen". Drag the run longer, then switch file memory off.
Illustrative: 3,000 tokens per result, a 200,000-token window, and truncation from the oldest end. With file memory, the last 10 results stay and the rest go to named files.
Without files, the window fills at call 67 (200,000 / 3,000 = 66.7). Truncation drops the oldest tokens first, and the oldest tokens hold the constraints. Nothing errors. The agent "improves" the frozen public API and undoes its own earlier work.
Why files and not a custom memory service? Reading and writing files with bash is a skill the model learned in pretraining. Weng: memory "in the simple form of files naturally benefits from improvements in core model capability". Each new model greps better, with no change to the harness.
pythonimport subprocess, pathlib NOTES = pathlib.Path("notes"); NOTES.mkdir(exist_ok=True) def write_note(name, text): # durable: survives resets and crashes (NOTES / f"{name}.md").write_text(text) def recall(query, max_lines=12): # retrieval is grep: a thin slice back r = subprocess.run(["grep", "-rin", query, str(NOTES)], capture_output=True, text=True) return "\n".join(r.stdout.splitlines()[:max_lines]) write_note("constraints", "public API frozen: do NOT rename parse()") recall("public API") # one line re-enters context, not 40k tokens
The failure. Symptom: the agent breaks a rule you gave it hours ago. Measure: plot peak context fill and check whether the rule is still inside the window. Fix: write constraints to a named file, and write notes with the words a later grep will search for.
Chapter 5
Run work in parallel, and keep every job's state in files so the parent can recover and audit it
Mid-refactor, the agent needs to know why one test fails only on CI. Bisecting it means 20 test runs and about 10,000 lines of logs. Inline, those logs push the refactor plan out of the window. Hand the job to a sub-agent instead: a child agent with its own fresh context. It returns one sentence: "test_tz depends on the machine's timezone; set TZ=UTC in the fixture."
Weng names three uses: search several hypotheses at once, run experiments in parallel, and isolate subtasks from the main context. The parent needs "a small process manager" to launch jobs, inspect logs, cancel failed runs and merge results: Unix's spawn, tail, kill and wait. Backend jobs, such as a nightly cron, get the same treatment.
The key design choice, in the post's words: "make parallelism explicit and inspectable". If sub-agent outputs "only live in a transient chat context, they quickly become obselete [sic] and hidden". Stored as files, logs and status records, they let the parent recover after an interruption.
Four jobs run under one parent. Press Run, then Interrupt partway. Compare what the parent knows when it restarts in each mode.
Illustrative: four jobs of 20 minutes of work each, at slightly different speeds.
More agents are not always faster. The parent must check each child's finding before it merges. Call the jobs m, the minutes per job t, the merge time tm, and the chance one unchecked finding is right p. A wrong finding forces a full serial redo of m × t minutes.
E equals t, plus t-m, plus one minus p to the m, times m times t.
Wait t for the jobs and t-m to merge. Then add the redo cost m times t, weighted by the chance that at least one finding was wrong: one minus p to the m.
With made-up numbers: m = 4, t = 20, t-m = 15, p = 0.9. p4 = 0.656, so E = 20 + 15 + 0.344 × 80 = 62.5 minutes. Serial takes 80. At p = 0.75, p4 = 0.316 and E = 89.7: slower than serial.
The blue bar is the serial cost. The warm bar is the parallel plan; its pink part is the expected redo. Lower the reliability until parallel loses.
Illustrative: 20 minutes per job, 15 minutes to merge, and a full serial redo when any finding is wrong.
The failure. Symptom: after a crash, the parent spawns the same four investigations again. Measure: look for a jobs/ folder with status records. Fix: each job writes jobs/N.status and jobs/N.log; on restart the parent reads them and reruns only the unfinished job.
Chapter 6
Open the eight tool groups that coding agents share, and trace what each call puts into context
Weng observes that "the core interface of mainstream coding agents has become stabilized" across Claude Code, Codex, OpenCode and Cursor-style agents. Different teams reached nearly the same tool set. With it, the agent works in a repository "similar to how human developers are equipped with IDEs".
| Group | Tools named in the post | Without it |
|---|---|---|
| File system | glob, grep, ls; read, read_many; write, edit, multi_edit, apply_patch | it can neither find nor change code |
| Shell | bash, PowerShell | it edits but never runs the tests |
| IO | lsp, git_status, git_diff, git_commit | no checkpoint, no self-review |
| External context | MCP tools, Skills | blind to the ticket and the team's procedures |
| Web | web_search, web_fetch, browser tools | frozen at its training date |
| Artifacts | read docs and images; make HTML and images | cannot read the screenshot in the bug report |
| Backend processes | CronCreate, CronDelete, CronList | nothing runs after the session |
| Agent delegation | spawn_agent, resume_agent, wait_agent, list_agents, close_agent, interrupt_agent | side quests pollute the main context |
One design detail repays study. edit replaces an exact string, not a line number. If the file changed since the model read it, the old string no longer matches, and the edit fails loudly. A line number would still "work", on the wrong line.
Every call passes one dispatch gate: look up the tool, check the permission table, run it, trim the output. A refusal goes back into context as a message, so the loop can react to "no" like a failing test. Results from the web are data, never instructions: a fetched page cannot widen the permission table.
pythonPERMISSIONS = {"read": lambda a: True, "edit": lambda a: inside_repo(a["path"]), "bash": lambda a: not destructive(a["cmd"])} def dispatch(call): fn = TOOLS.get(call.name) if fn is None: return f"unknown tool {call.name}" # fail loudly, in-band if not PERMISSIONS.get(call.name, lambda a: True)(call.args): return "PERMISSION DENIED: ask the user first" # the harness says no return fn(**call.args)[:2000] # trim at the boundary
How much enters context in a whole bug fix? Call the tokens that call number i adds ci, and the total C.
C equals the sum over i of c-i.
For each call, count only what it puts into context: paths, a slice, a tail. Add them up to get C.
With made-up numbers: glob 40, read 900, pytest 350, edit 60, pytest 220, git_diff 180, git_commit 30. C = 1,780 tokens, for a repo of about 400,000.
Each call lights its tool group and adds its tokens to the meter. Press Run. Then turn trimming off and run it again.
Illustrative token counts. Without trimming, each pytest run returns its full 4,000-line log (about 40,000 tokens) and edit returns the whole file.
The failure. Symptom: a routine fix costs 80,000 tokens and the plan drifts. Measure: log the tokens each call adds, as the meter does. Fix: trim at the dispatch gate, keep the tails of logs, and return paths before contents.
edit replace an exact string instead of a line number?Chapter 7
Drive one full episode with all three patterns live, then break each pattern on purpose
The goal is "make the tests pass". The ring is Pattern 1. The meter and the files are Pattern 2. The child box is Pattern 3, a sub-agent that bisects a noisy test. The log streams every event.
Press Auto or Step. Then reset, switch on a fault, and run again. Kill the sub-agent while it is alive.
A scripted toy episode with a tiny 3,000-token window so the effects show. Token counts are illustrative. A real harness would also gate every bash call and time-box the child.
| Switch | What you see | Which pattern it tests |
|---|---|---|
| Clean run | two failures answered, a child's one-line verdict, a commit | all three working |
| Flaky test | one spurious failure, absorbed in one extra lap | 1: failures are fuel |
| No file memory | the meter overflows; the agent repeats its first edit, which now finds no match | 2 in reverse |
| Kill sub-agent | the parent reads the status file and bisects inline: 540 tokens instead of the child's 180 | 3: a death becomes a detour |
Read the clean run's numbers. It ends after 24 events and 2,970 tokens of total traffic, for a two-bug fix with a child. The two writes lower the meter, because a filed note lets the harness drop what the note now holds.
With file memory off, the note "month fixed" never lands on disk. The window overflows and truncation drops the first edit. The agent tries the same edit again. The exact-match rule from Chapter 6 saves it: the edit fails loudly, the agent rereads the file, and moves on one lap later.
The failure. Symptom: duplicated actions in the log. Measure: grep the trajectory for identical tool calls. Fix: file every decision worth keeping, and keep edits exact-match so repeats fail loudly instead of doing damage.
Chapter 8
Sort harness behaviours that will move into the weights from interfaces that must stay outside
If models keep getting smarter, does the harness vanish? Weng's answer has three parts.
Meta-methodology. Harness engineering "will evolve in the direction of meta-methodology": improving the machinery that finds better answers, not each answer. The harness becomes a thing with a score that a search can improve. That is the next lesson, Harness Optimization.
A two-way pact. "Mature harnesses enable auto-research for model self-improvement loop", and "smarter models prevents harnesses from overengineering". A good harness sheds scaffolding as models improve.
Internalization. "Many harness improvements will be internalized into core model behavior, but the interface with external context and tools should remain." The precedent is prompt engineering. Manual prompt tricks faded as instruction tuning and reasoning improved. The need to state goals, constraints, context and evaluation did not.
The top band is the harness; the bottom band is the weights. Warm pills are behaviours. Blue pills are interfaces to the world. Drag the generations.
Illustrative order, not dates. The post gives the prompt-trick precedent and the rule that interfaces stay; the order of the other behaviours is our guess.
Two interfaces stay outside by design, not by model weakness. A permission table that the agent can edit is no boundary. The loop can game an evaluator that sits inside it. Weng makes the same point about self-editing harnesses: "if a program is allowed to edit the OS system, abstraction boundaries are broken".
Here is a worked check, with made-up numbers. An old model needs 20 laps on a task, or 12 with a forced-planning scaffold, so the scaffold pays. A new model needs 8 laps alone, but 11 with the scaffold. The scaffold now costs 3 laps. Rerun this check for each new model and delete what no longer pays.
Intelligence is still the core. The STOP system (Zelikman et al., 2023) let an improver improve itself. The post reports that it "improved mean downstream performance across iterations with GPT-4 but degraded with weaker models". The harness multiplies what the model brings, weakness included.
The failure. Symptom: a new, smarter model scores worse in your harness. Measure: switch scaffolds off one at a time and rerun the benchmark. Fix: build each behaviour as a removable module with an off switch.
Chapter 9
Keep the terms, the numbers, a checklist, the code and the next steps in one place
A harness is the system around a model that decides how it plans, acts, perceives, stores and checks. Its three patterns are a verified loop, durable state in files, and parallel work you can inspect. It sets how fast a model's intelligence turns into work, and how fast the improvement loop turns.
| Term | Meaning | Number from this lesson |
|---|---|---|
| Harness | the system around a base model that runs it | 5 jobs: plan, act, perceive, store, check |
| Loop gain g | toy multiplier per trip of the improvement loop | 0.955 = 0.77; 1.155 = 2.01 |
| Workflow automation | plan, act, observe, improve until a check passes | 2 laps clean, 3 with a flaky test |
| Files as memory | durable state on disk, a slice in context | 1.2M raw vs 30,500 kept |
| Inspectable parallelism | sub-agent state in files, logs and status records | 62.5 min at p = 0.9; 89.7 at 0.75 |
| Dispatch gate | lookup, permission check, run, trim | 1,780 tokens for one bug fix |
| Internalization | behaviours move into weights; interfaces stay out | 4 pinned: tools, permissions, artifacts, evaluation |
| Symptom | Suspect | First check |
|---|---|---|
| Forgets a rule mid-task | truncation reached the constraints | peak context fill; is the rule in a file? |
| Confident but wrong "done" | weak verifier | what does "done" measure? |
| Restarts from zero after a stop | no persistent state | is there a jobs/*.status to reread? |
| Smarter model, worse results | scaffolding taxes the new model | switch scaffolds off one at a time |
| Token bill explodes | stall or no budget | grep for repeated identical calls |
Build in this order, and test each piece before the next: the loop and a verifier, the budget, files, the permission gate, sub-agents.
pythonfrom loop import agent_loop # Ch 3: plan, act, observe, improve, with a budget from memory import write_note, recall # Ch 4: files as durable state from jobs import launch, inspect, recover # Ch 5: the small process manager from belt import dispatch # Ch 6: registry, permission gate, trimming def harness(goal, model): write_note("goal", goal) # stores artifacts result = agent_loop(goal, model, run_tool=dispatch) # acts, perceives, checks write_note("trajectory", result) # raw material for self-improvement return result
Now press Present or Teach and explain from memory: the five jobs, the three patterns and the dispatch gate. Then go back to the hero and run each machine again. Say which pattern each extra machine adds.
Built on Lilian Weng, Harness Engineering for Self-Improvement, Lil'Log, 4 July 2026. Lineage cited there and here: I. J. Good, "Speculations Concerning the First Ultraintelligent Machine" (1965); E. Yudkowsky on recursive self-improvement (2008); E. Zelikman et al., Self-Taught Optimizer (STOP) (2023). Pattern 1 in a few readable files: Karpathy's autoresearch. The toy numbers and devices are ours.