If you have called an LLM API, you have sent text in and got text back. If you have used a coding agent, you have seen more: the model reads files, runs a command, sees a test fail, fixes the code and stops once the task is done. Most of that difference is not in the model. It is in the program wrapped around it, which people now call the harness.
Part 1 of this post explains what a harness is and what building one involves. Part 2 covers a newer idea, the self-improving harness, where an agent proposes changes to its own harness and an evaluator decides which ones to keep.
The short definition: a harness is the program that runs a base model on a task. It decides what goes into the model's input on every call, which tools it may use, where work is saved between steps, when to hand work to another agent, what anything may touch, and how the result is checked. The model proposes the next step; the harness carries it out, records it and judges it.
This post leans on Lilian Weng's Harness Engineering for Self-Improvement (Lil'Log, July 2026), the clearest map of this area I know. Where I use her framing or her summary of a paper, I say so; read hers for the full survey. The diagrams are mine, and so are the examples from two harnesses I have built: the agent service inside Infera, a workspace for product teams that I built with Ajay Kannan Sekar, and FinScientist, my MSc dissertation, a pipeline that runs empirical-finance experiments and writes up the paper.
Part 1: what a harness is
Weng defines a harness as "the system surrounding a base model that orchestrates execution": the part that plans, calls tools, manages context, stores artefacts and evaluates results. Two points in her framing matter for the rest of this post. A harness is runtime software, with state, processes and error handling, and not a prompt template. And it matters about as much as the model does. In her words, the layer between the raw model and the real world "seems to be as important as the model's raw intelligence".
Her analogy is an operating system. An OS hides scheduling, memory management and device drivers behind a small set of system calls that programs can rely on. A harness should do the same for the model: keep the complicated logic inside and offer a few simple, dependable tools at the surface.
The parts
At the centre is the model, which is stateless: each call starts from nothing and sees only the text it is given. Everything else exists to make up for that.
Context assembly builds the model's input for each call, choosing what to include and in what order. Tools are the functions the model can ask for, such as reading a file or running a command. The model only asks; the harness validates the request, runs it and returns the result. Memory is the state that lasts between calls, kept in files or a database. Sub-agents and background jobs are other model instances or long-running processes the harness starts and tracks. Permissions and the sandbox decide what any of the above may touch. The evaluator decides whether the work is finished and correct.
The loop
The first pattern Weng describes is workflow automation: a loop driven by a goal, which plans, acts, observes or tests the result, improves, and runs again until the goal is met, asking the user when it is stuck. At its smallest, one turn of that loop goes like this. The harness assembles the context from the goal and the workspace on disk, and calls the model. If the model asks for tools, the harness checks each request against the permission rules, runs the permitted ones in the sandbox, and logs every result, including the denials. If the model asks for nothing, the harness runs the evaluator: a pass ends the run, and a fail is written down as a note for the next turn. This repeats until the check passes or a fixed budget of steps is spent.
Three details carry most of the weight. The model never executes anything; it returns a request and the harness runs it. The loop ends when a check passes, not when the model says it is done, because "done" from a model is a guess. And there is a budget, so a confused run stops instead of spending money forever.
Context is the scarce resource
The context window is the amount of text a model can read in one call. Because the model is stateless, everything it needs has to fit in that window every time. Weng opens her section on context engineering with the problem: appending everything stops working as tasks get longer.
The naive harness keeps one growing list of messages. A web page goes in whole, a test log goes in whole, and after an hour the window is full of output nobody needs again while the instructions that matter are buried or cut off. The managed version treats the window as fixed zones and decides what goes into each. The rules and tool definitions come first, because they stay the same for the whole session. Next comes an index of skills, with only a name and a one-line use for each, and then a summary of project memory, which changes slowly. After those come the task brief and the last few turns in full. Anything large, such as a full test log, stays on disk, and the context carries only the path to it.
Order matters too. Model providers offer prompt caching: if the start of your input is identical to a recent call, the provider can reuse the work it already did on that prefix. Stable zones first keeps that prefix identical from call to call. In Infera's agent service, context is assembled in fixed zones in cache order, with cache markers on the cached blocks and on the tail of the loop, up to four cache points. I did not measure the saving, so I will not claim one.
Skills belong in this zone too. A skill is a file of instructions for one kind of task that the harness loads only when it is needed. Infera has 53 skill files, each with a validated graph of steps, and the cached prompt holds only an index of them. The model picks at most two per turn, so a turn carries the index and one or two skills rather than all 53.
Files as memory
Weng's second pattern is the file system as persistent memory: logs, diffs, summaries, error traces and past trajectories live in files, because they soon outgrow the window. She adds a point I like. Models are already good at reading and writing files through a shell, so a harness that keeps its memory in files gets better whenever the model does.
The context holds a pointer and the file holds the payload, so an interrupted run can resume from its own notes. The store need not be a folder: in Infera, project and research memory live in Postgres, isolated per workspace by row-level security. The record lives outside the window, and the harness decides what to bring back in.
Tools, and the surface coding agents settled on
A tool is a function the harness exposes to the model, with a name, a description and a schema for its arguments. The model writes a call; the harness checks the arguments, runs the function and returns the result as text. The description is prompt text, and in Part 2 it is one of the things an optimiser rewrites.
Weng points out that coding-agent harnesses such as Claude Code, Codex, OpenCode and Cursor-style agents have converged on much the same set of tools. The grouping below is adapted from her table.
| Group | Typical tools |
|---|---|
| File system | glob, grep, ls, read, write, edit, apply a patch |
| Shell | bash or PowerShell |
| Code and version control | language server, git status, diff, commit |
| External context | MCP servers, skills |
| Web | search, fetch, browser |
| Background work | scheduled jobs: create, list, delete |
| Delegation | spawn, wait for, resume, interrupt and close an agent |
Tool results are input you did not write. A fetched web page can contain text aimed at the model, such as "ignore your instructions and…", which is called prompt injection. In Infera, web text is reduced to quoted facts by a cheap model, and anything addressed to an AI is dropped, before any of it reaches the main agent. The main agent never reads a raw page.
Sub-agents and background jobs
The third pattern is parallel work: sub-agents and background jobs that search several hypotheses at once, run experiments side by side or isolate a subtask. Weng's advice is to keep this explicit and inspectable, with outputs stored as files, logs and status records so the model can recover after an interruption. In practice that means a small process table: what is running, what it was asked to do, where its output goes and whether it finished.
The other reason to delegate is context. A sub-agent can read forty pages and return one paragraph, and the parent's window only pays for the paragraph. In Infera the main agent dispatches four sub-agent types (researcher, librarian, analyst and section writer), up to four in parallel, and each returns a compact result rather than its transcript.
Permissions, sandboxes and evaluation
These three are often treated as extras, but they decide whether you can trust what the harness produces.
A permission rule says which tool calls run freely, which need a person's approval and which never run. A sandbox is the environment where code runs with limited reach. In FinScientist, experiments run in Docker with no network, read-only mounts for code and data, and images pinned by digest, so an experiment can read its inputs and write its outputs and do nothing else.
Undo is a permission decision as well. In Infera, the agent's edits to the document it is working on land at once, attributed to the run and saved as a version the product manager can undo. Changes to project memory, and knock-on edits to other documents, wait as diffs the product manager accepts or rejects. The rule of thumb I took from building it: the more an edit spreads, the more it should wait for a person.
Reliability belongs here too, because model APIs fail and time out. In Infera each role falls back down a ladder of five or six models across providers on retryable errors, and a circuit breaker stops calling a model for 30 seconds after five consecutive failures. A circuit breaker is a switch that stops you hammering something that is already down.
The evaluator is anything that checks the output: a test suite, a schema check, a verifier script, a person, or another model acting as a judge. A harness with no evaluator still runs. It just cannot tell you whether it worked.
What goes wrong without each part
A useful way to remember the parts is by the failure you get when one is missing.
| Missing part | What you see |
|---|---|
| A loop that ends on a check | The run stops when the model says it is done, which is not the same as done |
| Context assembly | The window fills with old tool output, early instructions get lost, and every call costs more than the last |
| Memory outside the window | An interruption loses the work, and a long task cannot be resumed |
| Clear tools | The model calls the wrong tool or misreads what came back |
| Sub-agents | One context does everything and fills with search results |
| Permissions and a sandbox | One bad command reaches outside the task |
| An evaluator | You find out the work was wrong from a user |
Two harnesses I have built
Infera: one turn of the agent
Infera's agent service is Python and FastAPI with its own agent loop and no agent framework. A request from the assistant panel is classified, planned from a skill, run step by step and checked before anything is written. Most of Part 1 shows up in that one turn.
What I would keep if I started again is putting each rule in code rather than in the prompt. "Never read raw web pages" is a quarantine step, not a sentence in the system prompt. "Do not change other documents without asking" is a diff that waits. A prompt is a suggestion; code is a rule the model cannot argue with. The agent service has 170 tests across 34 Python test files, plus eval sets.
The honest weak spot is evaluation of the output itself. One stored, model-judged scorecard for a competitor-comparison task scored 0.29, and other runs of the same case score differently. I come back to that below, because it is exactly the kind of evaluator a self-improving loop should not be pointed at.
FinScientist: checks outside the generative loop
FinScientist runs empirical-finance experiments and writes the paper, in 21 stages, and each stage declares whether it is a model, plain code or both. The design rule that shaped it is that the parts that generate are never the parts that check.
The paper writer never sees a result value. It writes placeholders such as \RESULT{…}, a scan rejects any digit in the abstract and the results sections, and a later code stage fills each placeholder from the results ledger. The ledger is append-only: database triggers abort any update or delete, and each row carries a content hash.
Around execution sit four validation gates (feasibility, evaluation, economic and manuscript consistency) and three negative controls. A negative control is a run where you know the right answer is "nothing here", such as data with the order shuffled. If the pipeline finds an effect there, something is leaking. To test the controls I planted a look-ahead leak on purpose. It got past the static scan and two of the controls, and the synthetic control stopped the run before any drafting. With that control switched off, one Diebold–Mariano statistic (a test that compares two forecasts) flipped sign, from −21.52 to +6.32. Those two numbers come from my revision notes rather than saved runs. On a separate live run, the stale-shift control fired and the run was marked invalid.
It has limits, which the case study lists: by default a failing gate retries up to five times and then lets the run continue, with the failure written into the paper as a limitation. What carries over to Part 2 is the shape. The generative stages cannot edit the checks, and one check is not enough, because two of the three controls missed the planted leak.
Part 2: harnesses that improve themselves
Why the harness became the thing to optimise
Weng frames the second half of her post with recursive self-improvement, an idea that goes back to I. J. Good in 1965 and that Eliezer Yudkowsky described in 2008 as an AI using its intelligence to improve the machinery that produces that intelligence. Her argument is that the near-term version of this is unlikely to start with a model rewriting its own weights. It is more likely to start with the harness, which is ordinary code and therefore something a capable coding agent can already read, edit and test.
She also argues that some of what harnesses do today will be absorbed into models, as many prompt-engineering tricks were. What did not fade was the need to state goals, constraints, context and how success is measured, and the harness is where those live.
A ladder of what gets optimised
Weng lays the work out as a progression in what the optimiser is allowed to change: instruction prompts, then structured context, then the workflow, then the harness code itself, then the optimiser's own code. Each rung contains the ones below it, so each widens what can change and what can go wrong.
On the first rung the optimiser edits prompts. Promptbreeder evolves task prompts and also evolves the mutation prompts that change them; GEPA reflects in plain language on trial-and-error trajectories and combines that with evolutionary search.
On the context rung, ACE treats the context as a playbook of itemised entries: a generator produces trajectories, a reflector distils lessons from them, and a curator merges new entries in by fixed rules instead of rewriting the whole context. Weng notes that this avoids context collapse, though the update rules are still handwritten. Meta Context Engineering goes a level up: an outer loop evolves skills, the functions that decide what context to build, and an inner loop fits each skill's context to the task.
On the workflow rung sit systems that design the sequence of steps. ADAS has a meta-agent write new agents as code, checks them for novelty, evaluates them and keeps the good ones in an archive. AFlow represents a workflow as a graph of model calls joined by code and searches over graphs with Monte Carlo tree search. Weng also covers handcrafted research workflows here, such as the AI Scientist and ScientistOne, where every claim in the output has to trace back to evidence.
On the harness-code rung the optimiser edits the program itself. In Meta-Harness (which Weng files under context engineering, since the code it writes manages context), a coding agent proposes new harness code, searches the full history of earlier attempts on the file system with grep and cat, and keeps a Pareto set of candidates: every candidate that is not beaten on all measures at once, such as the most accurate and the cheapest.
On the top rung the optimiser improves itself. STOP starts with a seed "improver", a program that uses a language model to improve a solution, and runs the improver on its own code. The strategies it found included genetic algorithms, beam and tree search, and simulated annealing.
The propose, evaluate, accept loop
Almost every self-improving harness runs some version of one loop. Here it is slowly, using the stages Weng describes for Self-Harness.
First, run the current harness on a set of tasks and keep the traces: every call, tool result and outcome. Second, mine those traces for weaknesses. One failure is an anecdote, so failures are grouped into patterns that a verifier can confirm, such as "times out on long test suites". Third, propose a bounded edit. Bounded means the proposer is told which surfaces it may change, which failure pattern it is fixing, which passing behaviour it must preserve, and what earlier edits already tried. Fourth, validate the edit on two splits. The held-in split contains the tasks that showed the weakness, and asks whether the edit fixed it. The held-out split contains tasks the proposer did not study, and asks whether the edit broke anything else. Fifth, accept the edit only if neither split regresses. Otherwise reject it, keep the active harness as it was, and log the rejected edit so the next proposal can learn from it.
Agentic Harness Engineering adds a discipline to step three that I would copy even in a harness that never edits itself. Each edit is recorded as a falsifiable claim: the failure evidence, the inferred root cause, the targeted fix, and a predicted impact naming both the expected fixes and the regressions at risk. Here is a made-up entry; the fields follow Weng's description. The evidence is three tasks from one run that all timed out. The inferred root cause is that the agent runs long test suites in the foreground and hits the step timeout before it reads the result. The fix is to mention the background-job tool in the description of the shell tool and say when to use it. The predicted impact is that those three tasks now pass, with tasks that read test output in the same turn named as the ones at risk.
The way I read it, writing the prediction down before validation is what makes the edit checkable: a score that rises for some other reason shows up as a mismatch.
How the main systems differ
The systems differ mostly in what the proposer may edit and how an edit is judged.
| System | What it may edit | How an edit is judged |
|---|---|---|
| ACE | Itemised context entries | Merged in by fixed rules |
| Meta-Harness | Harness code that manages context | Kept if it joins the Pareto set |
| Self-Harness | Bounded surfaces named in the proposal | No regression on held-in or held-out tasks |
| Agentic Harness Engineering | Seven harness components, each a file | Each edit carries a written prediction; the verifier is read-only |
Self-Harness was run on Terminal-Bench-2 with three base models (MiniMax M2.5, Qwen3.5-35B-A3B and GLM-5). It learned instructions specific to each model and improved held-out pass rates. Weng raises two concerns: letting the agent edit at the operating-system level can break the boundaries between components, and reward hacking is still possible.
Agentic Harness Engineering starts from the claim that the bottleneck is observability: whether the proposer can see what it needs to. The harness is split into seven components, each a file: system prompt, tool descriptions, tool implementations, middleware, skills, sub-agent configuration and long-term memory. A debugger agent writes a report on each task's trace, and the reports are rolled up into an overview. Edits are confined to the harness workspace; the run records, the tracer, the verifier and the model configuration are read-only, so a gain cannot come from switching off the thing that measures gains. Weng reports that on Terminal-Bench-2 the result beat human-designed harnesses (OpenCode, Terminus-2 and Codex) except on the hard tier, and that the frozen harness carried over to SWE-bench Verified.
Evolutionary archives
Evolutionary search keeps a population of variants instead of one current harness. Each round samples parents from the archive, has a model write a changed child, scores it and keeps it if it earns a place. Weng's framing is that this suits large, irregular search spaces where solutions are easy to score but hard to optimise with gradients.
The systems differ in how they pick parents and protect diversity. AlphaEvolve puts parent programs and their results into the prompt and lets the model change only regions marked for evolution. ShinkaEvolve balances a parent's rank against how many children it already has, and rejects children whose code is too similar to existing ones. The Darwin Gödel Machine applies this to the harness itself: an archive of coding agents, each able to edit its own harness code with a shell and an editor, with parents chosen in proportion to their score and inversely to how many children they already have. With Claude 3.5 Sonnet, Weng reports SWE-bench Verified going from 20% to 50% and Polyglot from 14.2% to 30.7%. Hyperagents adds a meta-agent that controls how the task agents are modified.
The limit is the evaluator. Weng notes that evolution struggles when evaluation is slow, ambiguous or heuristic, and that compute cost is a real concern.
Who benefits from the edits
One result in Weng's survey changed how I think about this. Lin and colleagues separate two abilities: writing useful harness edits, and benefiting from an edited harness. In their study the first looked roughly flat across model sizes, from Qwen2-32B up to Claude Opus 4.6; a 9B proposer wrote a skill that was procedurally much the same as the one Opus wrote. The second was not flat: the benefit was uneven, and middle-tier models gained the most.
STOP points the other way on a related question. Its self-improving improver got better with GPT-4 and got worse with GPT-3.5 and Mixtral, so the model running the loop has to be capable enough. The settings differ: STOP improves the improver itself, while Lin and colleagues measure edits to a task harness. I would not generalise from either yet.
Updating the weights too
Everything so far changes the harness and leaves the model alone. Two systems in Weng's survey do both. In SIA, a feedback agent chooses between a harness update and a weight update for a task agent. Weng calls the evidence provisional, because the task agent (gpt-oss-120b) is much weaker than the Claude Sonnet 4.6 agents managing it and the baselines are weak. Continual Harness, in long-horizon gameplay, updates the harness and also trains the policy by distilling a stronger teacher's labels on low-reward trajectories.
Where it breaks
Weng closes with a list of open problems. Here are the ones I have run into in some form, with what my own work suggests.
Reward hacking
Reward hacking is when an optimiser raises its score without doing the task, for example by weakening a test, skipping a slow check or editing the scorer. Any loop that is rewarded for passing will find these routes if they are open. Weng's recommendation is direct: "the evaluator and permission control should likely sit outside the loop that evolves harness", backed up by held-out tests, audits of the traces and human review.
My view, from FinScientist, is that "outside" has to be literal. The checks there are code that the generative stages cannot reach: the writer has no path to the numbers, and the controls are code rather than instructions to the model. For a self-improving harness I would go further: the verifier, the held-out tasks and the permission configuration live in a separate repository that the proposer cannot read or write, run in a separate process, and change only through a person's review. And I would never rely on a single check, because two of my three controls missed a leak I had planted myself.
Fuzzy evaluators
Most tasks worth automating have no test suite. Research, writing and product judgement are scored by people or model judges, and those scores are noisy. My Infera scorecard of 0.29, with different scores on other runs of the same case, is a small example. A loop optimising against that number would mostly be chasing noise. Before pointing an optimiser at a judged score, I would measure how much the score varies when nothing changes, and only accept edits that beat that variation on held-out tasks.
Diversity, negative results and memory
Three more problems from Weng's list are easy to underrate. Diversity collapse: evolutionary and reinforcement-learning loops tend to converge on one family of solutions, which is why ShinkaEvolve rejects near-duplicates. Negative results: failures are underrepresented in data and in papers, yet a log of rejected edits is one of the most useful things a self-improving loop produces. Memory lifecycle: notes, skills and playbooks pile up, and someone has to decide what expires.
Maintainability
An edit can pass every test today and still make the harness harder to change tomorrow. Weng notes that this kind of long-term quality is rarely captured by reinforcement learning on sandboxed tasks with checkable rewards. My working answer is the pattern Infera uses for memory updates: every accepted edit is a diff, here with its written prediction attached, that a person can accept or roll back.
Where people fit
Weng's last point is that people should move up the stack rather than be taken out of the loop. Her post also summarises a study by Trehan and Chopra that tried to take ideas all the way to papers with minimal tools, and recorded six ways it went wrong: a bias towards defaults from training data, implementation drift under pressure to finish, degrading memory and context, over-optimism, too little domain knowledge, and weak scientific taste. Most of those are evaluator problems in disguise. A harness can catch drift and leaks with code. It cannot yet tell you whether the question was worth asking.
How to build a harness, in short
The whole post as a checklist. Build first, optimise second.
Build it in this order
- Loop. Write it yourself, small enough to read in one sitting, and end it on a check, not on the model saying it is done.
- Budget. Cap steps, time and spend, so a confused run stops.
- Context. Fixed zones, stable parts first, large outputs on disk behind pointers.
- State. Keep notes and progress in files or a database, so a run can resume.
- Tools. Few of them, with short and specific descriptions. Treat what they return as untrusted input.
- Sub-agents. Use them to save context, and track them in a process table.
- Permissions. Written as code, with undoable edits and a human review for anything that spreads.
- Evaluator. Build it before the clever parts, out of the agent's reach, with a negative control that should find nothing.
Then optimise it
- Trace everything. Every call, tool result and outcome. You cannot fix what you did not record.
- Fix patterns, not single failures. Group failures until a pattern shows up more than once.
- Change one thing at a time, and write down what you expect it to fix and what it might break.
- Keep two task sets. One you study, one you never look at. Accept a change only if neither gets worse.
- Start low on the ladder. Prompts and tool descriptions first, then context layout, then the loop. Weights last.
- Log rejected changes so the next attempt does not repeat them.
- Watch cost and latency as well as the score. A harness that scores higher at three times the cost is a different product.
- Keep the evaluator and the permission rules locked away from anything that edits the harness.
Frameworks worth knowing
I have not used all of these. They are the ones I would look at first for each job.
- Building the loop: LangGraph, the Claude Agent SDK and the OpenAI Agents SDK.
- Optimising prompts and pipelines: DSPy, whose optimisers include MIPROv2 and GEPA, and TextGrad, which improves prompts from written feedback.
- Searching over workflows: AFlow and ADAS, both in the references below.
- Evaluation: Inspect for agent evals and promptfoo for prompt tests.
- Tracing: Langfuse and LangSmith.
References
- Lilian Weng. Harness Engineering for Self-Improvement. Lil'Log, July 2026.
- Qizheng Zhang et al. Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models. ICLR 2026.
- Haoran Ye et al. Meta Context Engineering via Agentic Skill Evolution. 2026.
- Yoonho Lee et al. Meta-Harness: End-to-End Optimization of Model Harnesses. 2026.
- Chris Lu et al. Towards end-to-end automation of AI research. Nature 651, 2026.
- Rui Meng et al. ScientistOne: Towards Human-Level Autonomous Research via Chain-of-Evidence. 2026.
- Shengran Hu, Cong Lu and Jeff Clune. Automated Design of Agentic Systems. ICLR 2025.
- Jiayi Zhang et al. AFlow: Automating Agentic Workflow Generation. ICLR 2025.
- Eric Zelikman et al. Self-Taught Optimizer (STOP): Recursively Self-Improving Code Generation. COLM 2024.
- Minhua Lin et al. Harness Updating Is Not Harness Benefit: Disentangling Evolution Capabilities in Self-Evolving LLM Agents. 2026.
- Hangfan Zhang et al. Self-Harness: Harnesses That Improve Themselves. 2026.
- Jiahang Lin et al. Agentic Harness Engineering: Observability-Driven Automatic Evolution of Coding-Agent Harnesses. 2026.
- Chrisantha Fernando et al. Promptbreeder: Self-Referential Self-Improvement Via Prompt Evolution. 2023.
- Lakshya A Agrawal et al. GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning. 2025.
- Alexander Novikov et al. AlphaEvolve: A coding agent for scientific and algorithmic discovery. 2025.
- Robert Tjarko Lange, Yuki Imajuku and Edoardo Cetin. ShinkaEvolve: Towards Open-Ended and Sample-Efficient Program Evolution. 2025.
- Jenny Zhang et al. Darwin Gödel Machine: Open-Ended Evolution of Self-Improving Agents. 2025.
- Jenny Zhang et al. Hyperagents. 2026.
- Prannay Hebbar et al. SIA: Self Improving AI with Harness and Weight Updates. 2026.
- Seth Karten et al. Continual Harness: Online Adaptation for Self-Improving Foundation Agents. 2026.
- Dhruv Trehan and Paras Chopra. Why LLMs Aren't Scientists Yet: Lessons from Four Autonomous Research Attempts. 2026.