A model alone is an engine. The harness is the rest of the car: memory, tools, skills and loops. Let the model rewrite more of that harness, and the same engine goes further.
Learn what a harness is, and the three ways a model can rewrite it: its notes, its whole context, and its own code.
Choose how much of the harness the model may rewrite, then press Run the loop. Watch the same flawed agent fix more of itself as its reach grows. Then we build each reach from zero: external memory, an internal state, lessons from failure, a context file, tools, skills, and a search over whole harnesses.
You need a rough picture of a chatbot that calls tools in a loop and a little Python for the code. We build the rest from zero.
Based on Lecture 4 (Harness Evolution, Paul Liang) and its guest lecture (Alex Zhang) of MIT MAS.S62 How to AI an AI for (Almost) Anything, Fall 2026, from the MIT Multisensory Intelligence group. Slides: the lecture and the guest lecture. Every idea is re-taught here in our own words and devices; none of the course’s slide images appear.
Illustrative toy, not a result from the course. The agent starts with six flaws, one per harness part, and scores 30 of 100. Each round it fixes one flaw it is allowed to touch and gains 11 points. The reaches follow the lecture’s summary slide: memory (MEM1), the whole context (CLM), the whole harness (Meta-Harness). Skills written as text live in the context file, so the context reach can fix them; tools, the loop and the checks are code, so only the whole-harness reach can.
Chapter 0
Split an agent into the model and the code around it, and name the eight things that code stores
Picture a coding agent that fixed a bug for you on Monday. It found the right file, ran the tests twice, and wrote a clean patch. On Tuesday it meets the same kind of bug and starts from nothing. It opens the wrong files. It forgets that your team runs tests with one particular command. It repeats the Monday mistakes, one by one.
The model did not get worse overnight. The model is the same set of weights. What is missing is everything around the model that could have kept Monday’s lessons. That surrounding code has a name, and today’s lecture is about how it can learn.
First, the housekeeping, in one paragraph. This is Lecture 4 of the course, taught by Paul Liang, with a guest talk by Alex Zhang. Homework 1 is due on 13 October. Reading 2 goes out this week, with submissions and presentations on 14 October. The next project checkpoint, a midterm report and presentation, is on 28 October: processed datasets, baselines run, error analysis done, a better proposed idea.
The last lecture introduced context: everything the model reads before it writes the next token. That includes the instructions a developer wrote, the examples, the user’s message, the files and search results the environment returns, and the model’s own earlier thoughts. Think of it as the desk the model works at. Whatever is on the desk can be used. Whatever is not on the desk does not exist for it.
The lecture recaps two ideas. First, an LLM can optimise a context. Write a few versions of a prompt, score each one, keep the best. This is search, and the lecture writes it as p* = argmax score(p): the best prompt p* is the one with the highest score. Second, an LLM can evolve its own context to solve open-ended problems such as hard optimisation puzzles, coding and scientific discovery. The loop has four moves: select a candidate from a population, vary it (mutate or cross it with another), evaluate the child, and retain the good ones.
Today the desk gets a whole workshop around it.
The lecture’s first new definition is the one everything else hangs on. An agent is a model plus a harness. The harness is the code around the model that manages its context and its flow of execution so that it can finish a task. Picture a race car. The model is the engine. The harness is the chassis, the steering, the fuel line and the pit crew. A great engine in a bad car loses.
The slide splits the harness into five jobs, stacked in a loop:
The last job is the new one for this lecture. A fixed harness never changes. An evolving harness rewrites some of itself after each run. The hero at the top of this page is that idea in a toy: how much of the harness may the model rewrite?
To rewrite a harness, you need names for what is in it. The lecture gives a glossary, each item with a coding-agent example:
Try the glossary below. Pick an item and see which harness job it mostly feeds. The mapping is our own reading, not a rule from the slides, but it makes one thing clear: the five jobs are not equally busy. Several different stored things feed the Action job, and only one feeds Evolution.
Five boxes are the harness jobs. Pick one of the eight stored things; a line runs to the job it mostly feeds. Try all eight and count how many land on each box.
The five jobs and the eight definitions come from the lecture. Which job each item feeds is our own simplification: real items often feed several jobs.
Naming the parts lets you ask a sharp question: which part of the harness failed? If the agent forgot your test command, the Context job lost a fact. If it picked a tool that cannot work, the Action job is wrong. If it said “done” while tests failed, the Evaluation job is too weak. A vague agent that is “sometimes bad” becomes five places to look.
Now the data flow. On every step, the harness builds a request for the model, and reads the reply. In practice that request is a list of messages, and the reply is text that may contain a tool call:
pythondef step(harness, model, task): context = harness.build_context(task) # Context: prompt + memory + retrieved facts (list of messages) reply = model(context) # the only line that touches the weights action = harness.parse(reply) # Control: which tool, which arguments result = harness.run(action) # Action: tool call, API call, code run verdict = harness.check(result) # Evaluation: tests, safety, human feedback harness.update(task, reply, result, verdict) # Evolution: write notes, change prompts or skills return result, verdict
Only one line in that function uses the model. Everything else is the harness. That is why a model-plus-harness view is useful: most of the lines you can change are not weights, and you can change them in seconds, with no training run.
The rest of the lecture walks through the parts in the order the slides take them. Memory comes first, since it decides what lands on the desk. Then tools and skills. Then the newest idea: letting the model search over the whole harness. The guest lecture then asks whether harnesses should even exist.
Chapter 1
Place any memory system on a two-axis map, then watch an agent read and write its own external memory
On 7 February you tell your assistant that your partner James baked you a birthday cake. On 8 February you ask, “Did anything fun happen on my birthday?” A model with no memory sees only today’s message. It cannot answer. A model with memory can look up February 7 and say, “James baked you a cake.”
The lecture defines memory as the persistent state of an agent harness that stores information beyond the current context. It enables long-range learning that builds up over time. Three short rules follow from the definition. Memory is part of the context and part of the harness. Memory decides what goes into the context. And memory management is the harness’s job, not the user’s.
The slide also borrows the human split. Short-term memory holds what you are using now: a flash of sensory input, and a working memory of a few items, like a phone number you are about to dial. Long-term memory lasts for years. It has an implicit side you cannot easily put into words (how to ride a bike, a procedural memory) and an explicit side you can state: semantic facts (Paris is the capital of France) and episodic events (what happened at your last birthday). Agent designers reuse these names, so it helps to know them.
Dozens of memory systems exist. The lecture gives one map to place them all, with four questions:
Place a few systems on the map. Each dot is one method this lecture covers. We use two of the four questions, what is stored and where, because they separate the methods most clearly.
Columns say where the memory lives. Rows say what it holds. Pick a method and see its cell light up.
Our simplified placement of the lecture’s summary slide: each method really spans several cells (for example MemGPT stores facts and trajectories). LSTM is the lecture’s example of memory kept in parameters.
The simplest place to keep memory is outside the model altogether. The context window has a fixed size, say 8,000 tokens. A database does not. The hard part is that the model must choose what to store and what to fetch.
MemGPT (Packer et al., 2024) treats this like an operating system. A computer has a small, fast RAM and a big, slow disk, and the operating system moves data between them. MemGPT splits the model’s world the same way. The main context is the small RAM: the system instructions, a working-context scratchpad, and a first-in-first-out queue of recent messages. Outside it sit two big stores, archival storage and recall storage. The key move: the model reads and writes them by function calls, exactly like any tool. In the lecture’s example the user mentions a boyfriend named James, and the model calls working_context.append("Boyfriend named James"). A day later the user asks about a trip, and the model calls recall_storage.search("six flags") and gets back the matching old messages.
What triggers the write? When the queue nears its limit, the harness inserts a “memory pressure” warning. The model sees it and decides what to save before old messages are evicted. That makes memory management a decision the model takes with the same loop it uses for everything else. (A full lesson on the idea sits in our MemGPT lesson.)
Mem0 (Chhikara et al., 2025) turns chat into a tidy list of facts, in two phases. In the extraction phase, an LLM reads the newest messages together with a running summary and writes candidate facts. In the update phase, each candidate is compared against the most similar facts already stored. The LLM then picks exactly one of four operations: ADD a new fact, UPDATE an existing one, DELETE one that is now wrong, or NOOP (do nothing). One variant keeps the store as a graph: each message becomes entity and relation triplets, such as (user, lives in, Denver), which suits knowledge, databases and symbolic state.
Step through a short chat below. Watch the store change, and notice that most of the work is deciding between four verbs.
The top band shows the newest message and the verb the model chose. The cards below are the memory store. Press Next message six times.
A hand-written toy chat. In Mem0 an LLM picks each verb after comparing the new fact with similar stored facts; here the choices are scripted so you can see each verb once.
What happens when the chat ends with “thanks, that is all”? The right verb is NOOP. Storing it would waste space and later crowd out useful facts. A good memory system must forget and ignore as well as remember. Deleting a stale fact matters just as much: if “lives in Boston” stays beside “lives in Denver”, the model will sometimes pick the wrong one.
The failure mode shows up as a symptom first: the assistant contradicts itself across sessions. The measurement is to count contradictory fact pairs in the store after a long chat. The fix is the UPDATE and DELETE verbs, not a bigger store.
Chapter 2
Keep the context the same size forever by rewriting one small state each turn and dropping everything else
Give an agent a big research chore: sixteen questions in a row, each needing a few web searches. After each search the agent pastes the results into its context and moves on. By question five, the context holds thousands of search snippets. Most are useless now. The agent starts to mix up facts from question two with facts from question four.
This is the problem MEM1 attacks. The lecture states it in one line: a growing reasoning context brings complexity and forgetting. More text on the desk means more cost per step, and a harder time finding what matters. The slide plots the old way as a line that only goes up.
Think of a student who must finish a long exam with one small sticky note. After each question, the student rewrites the note so it holds only what the next question needs, then throws the old scratch work away. The desk never fills up.
MEM1 (Zhou et al., 2025, from the MIT Multisensory Intelligence group; our MEM1 paper lesson goes deeper) does exactly that. It adds an internal state (IS): a short piece of text the model writes that mixes reasoning and memory in one place. At each turn the model gets three things: the previous internal state, the latest query it issued, and the information the environment returned. It writes a new internal state, plus one of two things: an action (a new search query) or a final answer. Then the harness deletes everything that came before. The next turn sees only the new state, the new query and the new results.
The slide calls this memory consolidation: compressing past knowledge into the latest internal state. Two consequences follow. Memory use stays close to constant. And, because the model itself decides what the state keeps, the memory can be trained end to end with the rest of the agent, with no separate summariser to tune by hand.
pythonstate, query, info = "", "", "" # nothing remembered yet for turn in range(MAX_TURNS): context = [SYSTEM, task, state, query, info] # ONE state, ONE query, ONE result: constant size out = model(context) # <IS>...</IS> then <query>...</query> or <answer>...</answer> state, kind, payload = parse(out) # the new state replaces the old one if kind == "answer": return payload # scored by exact match or F1 (the outcome reward) query, info = payload, env.search(payload) # old state, old query, old results are dropped
Compare this with the usual loop, which appends to history forever. The only change is one line: the context is rebuilt from three short pieces instead of a growing list. Slide the number of turns below and compare the two context sizes.
The yellow line is an agent that keeps every turn. The purple line is MEM1, which keeps one state. The dashed line marks an 8,000-token window. Drag the number of turns.
Illustrative token counts, not the paper’s: a 400-token system prompt and task, then 150 tokens of thought and 600 tokens of search results per turn; the MEM1 state starts at 300 tokens and grows by 4 per turn. Three turns make one question, so 48 turns is the 16-question task. The paper measures a 3.7 times memory gap on its 16-objective task, which is smaller than this toy’s.
A state that keeps the wrong facts is worse than none. MEM1 learns what to keep from the answer. The harness scores each finished attempt with the final answer: exact match (does the answer string equal the gold string?) and F1 (how much of the answer overlaps the gold words?). That score is the outcome reward. There are two ways to use MEM1. You can prompt a model to follow the loop, which needs no training. Or you can use the reward to train the model with reinforcement learning (training by trial, with a score for each finished attempt), so it learns to compress. The paper trains tasks by joining existing question sets into longer chains with many objectives, so the agent must carry facts across questions.
Because the earlier context is deleted, the reward can only come from what the state kept. A model that drops a needed fact fails the later question and earns no reward. That pressure is how it learns to write good notes. It is also why this is an end-to-end method.
On a 16-objective multi-hop question task (each answer needs several linked searches), MEM1-7B beats Qwen2.5-14B-Instruct by 3.5 times in performance while using 3.7 times less memory. In the paper’s own words, it needs 27.1% of the peak tokens and 29.3% of the inference time of the 14B model. The lecture’s results slide shows the shape: as the number of questions rises, baseline performance falls and MEM1’s climbs, while the baselines’ context keeps growing and MEM1’s stays flat. MEM1 even starts behind the 14B model on small tasks, and catches up and passes it as tasks grow.
Three real excerpts on the slides show what the trained model does with its state. First, it stores the key facts about each question separately, under its own heading, such as two baseball facts and then a show’s TV run. Second, it explicitly updates its summary before moving on: “Beniamino Di Giacomo was born in Porto Recanati. Now we can add this to our cumulative summary”, then it starts the next question. Third, it learns to give up: after several searches without a useful result, it writes that it cannot determine the answer, and moves on to the second question. Nobody wrote a rule for any of this. The reward taught it.
The failure mode is the mirror of the gain. The symptom: late questions fail although early ones pass. The measurement: check whether a needed fact was in the state at the turn before it was needed. The fix: train on longer chains so the model learns to keep the facts that matter later.
Chapter 3
Write down why a trial failed, store the note, and read it before the next trial
You fail a practice exam. A weak student looks at the score, sighs, and takes the next exam the same way. A strong student writes a short note for each miss: “I forgot to convert units.” “I read the question too fast.” Before the next exam, the student reads the notes. The score goes up with no new teacher and no new textbook.
That is the idea of this chapter. The last two chapters kept facts. This one keeps experience: what happened when the agent tried, and what to do differently. The lecture’s title for the idea is “turning memory into useful experience”.
Ordinary reinforcement learning improves an agent by updating its weights, which needs many trials and a training run. Reflexion (Shinn et al., 2023) changes the model’s words instead. It uses three roles, each played by a language model. The Actor tries the task. The Evaluator scores the attempt (a test result, a reward, or a judgement). The Self-reflection model reads the attempt and the score, and writes a short note in plain language about what went wrong and what to try next.
Two kinds of memory carry it. The trajectory of the current trial, every action and observation, lives in short-term memory. The reflections live in long-term memory, an episodic buffer that survives between trials. At the start of the next trial, the harness puts the reflections into the Actor’s context. The weights never change. Only the context does. The lecture calls this a combination of context evolution and memory evolution.
The paper tests it on three kinds of task: sequential decision making, programming and reasoning. Its headline result is on HumanEval, a coding benchmark: Reflexion reaches 91% pass@1, where the earlier best GPT-4 result was 80%. (Pass@1 is the share of problems solved on the first submitted answer.) Our Reflexion paper lesson covers the details.
pythonreflections = [] # long-term memory: a short list of strings for trial in range(MAX_TRIALS): context = [TASK] + reflections[-3:] # the last few lessons go in front of the model trajectory = actor.run(context) # short-term memory: this trial's steps score, feedback = evaluator.check(trajectory) # e.g. unit tests: "failed on [3, 1, 2]" if score == 1.0: return trajectory reflections.append(reflector(trajectory, feedback)) # "I forgot to sort the list first."
Notice what the note must be: specific and about the cause. “Try harder” carries no information. “I forgot to sort the list first” tells the next trial what to change. Run the toy trial loop below. It asks an agent to write a function that finds the median of a list, with three hidden bugs. Turn the reflection memory off and on, and compare.
Each row is one trial, and each square is one unit test. The first failing test is the only feedback. Press Run next trial four times, then switch the memory and try again.
A scripted toy, not the paper’s setup: three bugs (no sort, wrong even case, crash on an empty list) and an Actor that fixes only the one bug named in its newest note. Real Reflexion lets the language model decide how much to fix per trial.
With memory on, the agent passes after 4 trials: three lessons, three fixes, then a clean run. With memory off, every trial starts blank, so it hits the same first failure, forever. The model is identical in both rows. Only the harness differs.
Take the median toy by hand. The task prompt is: “Write median(xs).” Trial 1 has no notes, so the context is only the task. The Actor writes a function that returns the middle item without sorting. The Evaluator runs three unit tests and reports the first failure: median([3, 1, 2]) returned 1, expected 2. The reflector writes note 1: “I forgot to sort the list first.”
Trial 2 starts with the task plus note 1, about 30 more tokens. The Actor now sorts. Test 1 passes. Test 2 fails: median([1, 2, 3, 4]) returned 3, expected 2.5. Note 2 says: “For an even length I must average the two middle values.” Trial 3 reads both notes and passes two tests. It still crashes on the empty list, so note 3 is added. Trial 4 reads three notes, about 90 tokens in all, and passes all three tests.
The cost of the whole memory is 90 tokens. A full trajectory of one failed trial could be 2,000 tokens or more. That is the design reason for a reflection: it compresses a long failed attempt into the one sentence that changes the next attempt. The harness decides how many notes to show. The sketch above shows only the last three. Too many notes would crowd the context, and the next chapters return to that problem.
Reflexion’s notes only help the task they came from. ExpeL (Zhao et al., 2024) builds on it to learn across tasks. It also puts trajectories in short-term memory and reflections in long-term memory. Then it adds feedback to memory: a record of whether each experience turned out to be useful or not. When a new task arrives, ExpeL retrieves the stored trajectories, experiences and feedback that look most like it, and shows them to the model as few-shot examples. Good lessons rise and bad ones fade.
The failure mode matters here. The symptom: the agent’s notes pile up and contradict each other, so context grows and answers get worse. The measurement: track, for each note, how often the trials that used it succeeded. The fix is the ExpeL one: keep the feedback bit, and retire notes that do not help.
Chapter 4
Let the model edit its own context with ordinary shell commands instead of a harness rule that trims it
An agent has worked on a research question for six hours. Its context holds a hundred thousand tokens of search results, half-finished plans and dead ends. The harness has a rule written by a human: “When the context passes 100,000 tokens, summarise everything into 500 tokens.” The rule fires. The summary drops the one detail the agent needed in hour seven.
A fixed rule cannot know what matters for this task. The model can. So the lecture ends its tour of memory with a bold step: take context management out of the harness and give it to the model.
A standard language model treats its context as a log you can only add to. Say c is the context at some step and f is the model. The model reads c, writes new text, and the harness glues that text onto the end. The lecture writes this as one line:
Everything else that changes the context, such as trimming old messages or summarising, happens in the harness, outside the model. A Context Language Model (CLM; Shao et al., 2026) removes that limit. Its next context is any function of the current one, chosen by the model itself:
The append-only model is a special case: it always returns the old context plus new text. A CLM is a strictly larger class.
How do you let a model rewrite its own context without inventing a new interface? Use the one models already know. The lecture’s implementation, context-as-a-file, stores the live context as an ordinary file. The path of that file is written in the system prompt. The model edits it with Bash commands (the shell commands used on any computer), just like any other file: cat to read, sed to change lines, echo >> to append. Whenever the file changes, the harness synchronises the change with what the model actually reads. No special tool, no new training format.
The idea extends to teams. Several context files can exist at once, each tied to one agent, all kept in sync. A parent agent starts a subagent by creating a new context file, and ends it by deleting the file. Creating and deleting files become the controls for a whole swarm of agents.
Try the three ways of managing context on the same twelve-step chore. Six facts appear along the way and all six are needed at the end.
Bars show the tokens in the context after each step. The dashed line is an 8,000-token window. The six squares are the six facts: green if the context still holds the fact, red if it lost it. Choose a policy and drag the step.
Illustrative toy. A 400-token start, 1,400 tokens of tool results per step, facts first seen at steps 2, 3, 5, 6, 8 and 10. The harness rule keeps only the two newest facts when it summarises. The CLM row assumes the model writes a 60-token note for each fact and deletes the raw result, so it keeps all six; a real model can delete the wrong line, which is why the paper tests it.
Read the three results at step 12. Append-only never exceeds the window, but the window quietly cuts the oldest text, so four facts vanish. The harness rule empties the context at the cap and keeps two facts. The CLM row keeps all six, in about 1,100 tokens. The model chose what to keep because it knew what the task needed.
The lecture shows the CLM in two settings. Zero-shot, an ordinary model is simply given the context file and told it may edit it. Against strong context-management baselines, the paper reports 11.4% higher accuracy with 21.5% fewer FLOPs (floating-point operations, a count of the arithmetic done) on BrowseComp-Plus, a web research benchmark. It reports 5% higher scores with 59% fewer FLOPs on a 12-hour task, and a 65% greater improvement at equal compute on a 24-hour multi-repository coding task.
The second setting is learning to manage. The same model can be steered three ways. In-context instructions are written advice, for example “compact once you reach 4,000 tokens.” Context evolution evolves those instructions with the search loop from Chapter 0, and it raised held-out accuracy by up to 35.9 points on one context-management task. Reinforcement learning trains the weights, with a reward that mixes task success and cache efficiency. Cache efficiency matters because a server reuses its work on the front of a context, its KV cache; an edit near the front forces it to redo that work. The paper reports 47.6% better BrowseComp-Plus performance for a 9-billion-parameter Qwen model with 12% fewer FLOPs, and a serving trick called Suffix Cache Reuse that cuts server compute by 35%. On the lecture’s table, a summarising baseline goes from 34.7 to 42.1 accuracy, while the CLM goes from 28.8 to 42.5 at fewer FLOPs per question (2.19 against 1.34 PFLOPs after tuning).
The failure mode: the symptom is a model that deletes the one line it needs later. Measure it by checking, after a run, which facts the final answer needed and whether they were still in the file. The fix is the learning step above: train or evolve the editing policy against task reward, so careless deletions cost points.
Chapter 5
See why one line of code can replace many tool calls, and how models learned to call tools at all
You ask an agent: “Which of these six countries sells this phone for the least money, in US dollars?” An agent that can call only one tool per turn must ask for a price, wait, ask for an exchange rate, wait, and repeat that six times. That is twelve round trips to the model, and the context grows at every one. A different agent writes six lines of code, runs them once, and reads one answer.
Same model, same question. The only difference is what an action is. This chapter starts the second half of the harness: tools and skills.
The lecture splits the Action job into two words. A tool is a task-specific, atomic action the agent can execute. “Search a database for one paper and put the result in the context” is a tool. “Atomic” means one step that cannot be split further. A skill is a task-agnostic, reusable procedure the agent learns while completing tasks. It often combines reasoning with several tool calls: do a thorough literature search, cluster the themes, write a summary. A tool is a verb. A skill is a recipe made of verbs. Chapter 6 is about skills.
A survey the lecture cites (Wang et al., 2024, “What are Tools Anyway?”) sorts tools into five groups, with a typed signature for each, such as search_engine(query: str) -> document:
Every one of them is a function with typed inputs and a typed output. That is the full interface: a name, some arguments, a result. Anything that fits that shape can be a tool.
The survey makes a sharp claim: code is a meta-tool. A code action can compose control flow (loops and ifs), libraries, functions and many operations in a single action. A calculator tool does one sum. A line of Python can loop over six countries, call the price function six times, convert each, and take the minimum. The lecture’s examples show a model writing a small program, for example using pandas to answer a table question, instead of guessing the answer in words.
CodeAct (Wang et al., 2024) tests this directly. It compares an agent that acts by emitting text or JSON ({"action": "get_price", "country": "Japan"}) with one that emits Python, and the lecture’s result is simple: acting through code gives the best success rate with the fewest interaction turns. Our CodeAct lesson has the full paper. The reasons are plain. Code is something models have seen a great deal of. It handles loops and variables, so the model need not copy intermediate numbers by hand. And errors come back as readable messages the model can fix.
Count the turns for yourself. Pick how many countries to compare, and switch between the two styles.
The question asks for the cheapest of several countries in US dollars. The bars show model turns and tokens read. The transcript shows the first lines of what the model wrote and what came back.
Illustrative arithmetic. The JSON style needs two calls per country (price, then exchange rate) plus a final answer, so 2k + 1 turns. The code style needs one turn to write the loop and one to read the result. Each turn re-reads the context: 500 tokens to start, 150 more added per turn. The course shows only that code needs fewer turns; these numbers are ours.
At six countries the JSON agent takes 13 turns and the code agent takes 2. Because every turn re-reads the whole context, the token cost grows faster than the turn count. That is the extra price of one-call-at-a-time.
The sample the code agent writes is short:
pythonbest = None for country in COUNTRIES: # the loop lives in the action, not in the model's turns usd = get_price(PHONE, country) * get_rate(country, "USD") best = min(best, (usd, country)) if best else (usd, country) print(best) # one observation goes back to the model: (412.5, "Japan")
Writing a tool call is itself a skill a model must learn. Two papers on the slides show two ways.
Toolformer (Schick et al., 2023) learns tool use with no human labels. It takes ordinary text and asks the model to try inserting API calls at plausible spots, such as a calculator call before a number. It then runs each call and keeps only the ones that help: calls whose result makes the next words easier to predict. It fine-tunes on the kept examples. The model teaches itself, and only successful tool uses survive. (More in our Toolformer lesson.)
ToolLLM (Qin et al., 2024) scales this to the real world. It collects more than 16,000 real web APIs from RapidAPI, organised into a hierarchy of categories, and builds training data for multi-step work: the model must pick APIs, call them in order, and use earlier results. An API retriever finds the few relevant APIs from the thousands, because no context could list them all.
The failure mode: the symptom is a call with wrong arguments, or a tool that does not exist. The measurement is the share of calls that error. The fix, in the code style, is that the error text returns to the model, which edits one line and retries within the same action.
Chapter 6
Find the steps that many tasks share, store them as a skill, and call that skill next time
An agent just finished the chore “add Sony headphones to my wish list” on a shopping site. Its steps were: go to the store, find the search box, type the product, click Search, open a result, click Add to Wish List. A minute later you ask a new chore: “find the price range of wireless keyboards.” The steps are: go to the store, find the search box, type the product, click Search, read the prices. The first four steps are the same.
The lecture, crediting the CMU AI Agents course, puts it in one line: lots of structure recurs in agent tasks. A person who does the first four steps ten times stops thinking about them. They become one habit: “search the store.” An agent can form the same habit if the harness lets it write the habit down. That written habit is a skill.
Chapter 5 defined a skill as a task-agnostic, reusable procedure. Here is how one is found. Compare several successful runs. Look for a run of steps that appears in all of them. That shared stretch is the candidate skill. The parts that differ between runs (“sony headphones” versus “wireless keyboards”) become the skill’s inputs.
Select tasks below and watch the shared stretch change. The hotel booking is a trap on purpose: it begins at a different site.
Each row is one task and each block is one step. Pink blocks are the longest run of steps that all selected tasks share. Toggle tasks and see how many steps a skill would save.
Hand-written toy tasks, with one block per low-level action. The shared run is the longest contiguous run of identical steps in every selected task. Real skill induction, as in the papers below, also generalises the inputs and checks the result.
With the first three tasks selected, the shared run is four steps long. A skill search_site(query) turns those four steps into one call in every task, saving 3 steps in each, so 9 in total. Add the hotel task and the run shrinks to three steps, because that task starts on a different page. A skill is only as wide as what really repeats.
How should a skill be written down? “Inducing Programmatic Skills for Agentic Tasks” (Wang et al., 2025) compares two forms.
Neither form wins everywhere. Text bends. Code is cheap and checked. That is the tradeoff you design around.
Rigid code has a problem: a function that clicks the search box on one shop breaks on another. PolySkill (Yu et al., 2026) borrows an idea from software, polymorphism: one abstract definition, many concrete versions. The abstract class says what a shopping site can do. Each site gets an implementation that says how.
pythonclass ShoppingSite: # abstract: the schema every shop shares def search_product(self, query): ... def add_to_cart(self, item_id): ... def checkout(self): ... def purchase_item(self, query): # a composed skill: built from the abstract ones item = self.search_product(query) self.add_to_cart(item) self.checkout() class Amazon(ShoppingSite): # concrete: how THIS site does it def search_product(self, query): click("#twotabsearchtextbox"); type(query) class Target(ShoppingSite): def search_product(self, query): click("#search"); type(query) # selectors here are illustrative
The composed skill purchase_item is written once and works on every site, because it only calls the abstract steps. When the agent meets a new store, it needs to learn only the concrete parts.
Agent Workflow Memory (Wang et al., 2025) mines the agent’s own past runs. A judge decides whether each run solved its task. An induction step reads the runs and extracts workflows: common sequences of sub-routines. Its prompt asks for workflows that are reusable, with the non-fixed parts, such as the text typed into a box or a button’s label, replaced by descriptive variable names. Approved workflows are admitted to memory and shown to the agent on the next task. It learns from both successful and failed runs.
Voyager (Wang et al., 2024) is the full loop, in Minecraft. An automatic curriculum picks the next goal, such as “craft a wooden pickaxe”. The model writes code to attempt it. The environment’s feedback and the code’s errors return to the model, which fixes the code. Code that works is stored, with a description, in a skill library. Later goals retrieve and combine earlier skills, so “make a stone pickaxe” reuses “mine wood”. The lecture’s chart shows the library letting the agent collect more distinct items, faster, than agents without one.
The failure mode: the symptom is a skill that worked yesterday and breaks today because the page changed. The measurement is to replay the stored skill against the live site before you trust it. The fix is the code form’s own gift: skills are testable, so a failing test triggers a rewrite. (Our agent skills lesson covers skills in today’s coding agents.)
Chapter 7
Hand a proposer the full source, scores and traces of every past harness, and let it write the next one
Imagine coaching a football team where you may only read the final score of each game. Lost 2 to 3. Won 1 to 0. You never see the tape. You change the tactics and hope. Progress is slow, because the score does not say why.
That is how most automatic prompt and code optimisers work. They show the optimiser a short summary, a single score, and a few past attempts. This worked for single prompts. It breaks for a harness. A harness is thousands of lines of code, and one bad decision deep inside, such as truncating a document too early, hides behind a single number.
Meta-Harness (Lee et al., 2026) treats the harness as a directory of files and the search for a better harness as a coding job. It runs an outer loop with three parts:
The proposer does not get a summary. It explores the archive with grep and cat, the same way a developer reads a messy repo. The lecture puts the scale in one line: the proposer reads about 10 million tokens of feedback per iteration, against about 26 thousand for earlier text optimisers. And it can trace a failure back to the specific harness decision that caused it: in an invented example, grep the failing runs for the word “truncate”, find line 212, and see that the context compiler cut the label list at 2,000 characters.
Because a harness is a program, the search space covers everything in the lecture. The same loop can optimise prompts, retrieval systems, skills, tools, memory, and whole agent loops. The slide calls it a unifying framework represented as file systems, fully optimised through code.
Try the feedback ladder below. The same toy search runs with three levels of access to the past. Press Run 20 proposals for each.
Choose how much of the past the proposer may read. Curves show the best harness score found so far. The panel shows what it sees about candidate 7, which has a hidden bug.
The curve shapes are illustrative, drawn to show the paper’s idea, not its data: a score starting at 30 and climbing toward 38, 44 or 56 at different speeds. The 26K and 10M token counts are the lecture’s figures for earlier optimisers and for Meta-Harness. The trace line is invented.
The lecture shows three use cases.
Text classification. The proposer evolves a harness for online text classification. It beats a state-of-the-art context-management system by 7.7 points while using 4 times fewer context tokens, and its search curve climbs above other text optimisers within a few dozen candidates.
Retrieval for maths. A single discovered retrieval harness raises accuracy on 200 olympiad-level problems by 4.7 points on average across five held-out models. On the lecture’s table the average score is 34.1 with no retriever, 32.2 with random few-shot examples, 37.5 with BM25 search, and 38.8 with Meta-Harness. Notice that random examples made things worse. The harness has to be right, not just present.
Agentic coding. On Terminal-Bench 2, a long task where an agent works autonomously and a verifier checks the result, the discovered harness scores 76.4% with Claude Opus 4.6, above the best hand-built entry in the lecture’s table (75.3%), and 58.0% for Claude Code. With Claude Haiku 4.5 it scores 37.6% against 35.5% for the best baseline. (Our Meta-Harness lesson has the paper in full.)
The Darwin Godel Machine (Zhang et al., 2025; our lesson) is the older cousin. A coding agent edits its own source code, then runs the edited agent on coding benchmarks to see whether the change helped. Instead of keeping only the best agent, it keeps an archive of every agent it made and samples parents from it, so odd but promising branches survive. Over many rounds it discovered better editing tools, better long-context handling and peer-review steps, lifting SWE-bench from 20.0% to 50.0% and Polyglot from 14.2% to 30.7%, with sandboxing and human oversight.
Continual Harness (2026; arXiv 2605.09998) asks for evolution in a place where you cannot reset: an agent playing Pokemon for hours. Most prompt optimisers need to restart an episode to test a change. Continual Harness instead alternates between acting and refining its own prompt, sub-agents, skills and memory, drawing on past trajectories, all inside one unbroken run, starting from only a minimal interface. On Pokemon Red and Emerald it cuts the button presses needed relative to a minimal baseline and recovers a majority of the gap to a hand-engineered expert harness.
The failure mode shared by all three: a change that scores better on the search tasks and worse in the world. The symptom is a gain that vanishes on new tasks. The measurement is a held-out test set the proposer never sees. The fix is the one these papers use: evaluate on held-out models or tasks, and keep the sandbox.
Chapter 8
Stop pasting a huge prompt into the window and let the model explore it with code and calls to itself
You hand an assistant a 5,000-page company archive and ask one question whose answer sits in a single footnote. A person would not read all 5,000 pages from the top. They would search, jump, read a few pages, make a note, and search again. Most agent harnesses do the opposite. They paste as much of the archive as fits into the model’s window and hope.
The second half of the session is a guest lecture by Alex Zhang, a PhD student at MIT CSAIL advised by Omar Khattab and Tim Kraska. He starts with where his questions came from. His earlier projects were benchmarks, such as writing fast GPU kernels, where tasks have clear goals but little training data. Those tasks pushed him toward one question: how do we help a model do long, iterative work?
The simplest use of a model is one call. A prompt goes in, and “reasoning” plus an answer come out. The next picture adds a loop around the model: the answer is transformed and sent back in. A “standard” agent such as Claude Code, Codex or OpenClaw is that loop. At its core is a few lines of code, the ReAct pattern (reason, then act, then read the result):
pythondef agent(prompt): history = [prompt] while True: reply = llm_call(render(history, tools)) # the whole history is the input, every time history.append(reply) if not reply.tool_calls: return reply.text history.extend(run_tool(t) for t in reply.tool_calls) # results are appended to the same list
Notice what grows: history. By early 2026 this was the pressure point. The talk’s slides note that Prime Intellect said on 1 January that it was working on RLMs, and that Cursor released dynamic context on 6 January. Everyone was trying to manage context, and people had begun to use coding agents for tasks that were not coding.
The talk’s own paper is Recursive Language Models (RLMs; Zhang, Kraska and Khattab, arXiv 2512.24601). It asks three bold questions: Should a language model be entirely neural? Do harnesses matter, and which abstractions in them matter? And, provocatively, is long context a silly problem?
Here is the answer in one picture. Do not put the long prompt in the model’s context at all. Store it as a variable in a Python session (a REPL, a read-eval-print loop where code runs and shows results). The model sees only a short description and a handle to the variable. It then writes code to look at pieces: print the first lines, search for a word, slice a range. And it may call a language model on a snippet, which is the “recursive” part: the model calls itself, a fresh instance with a small context, on one chunk, and gets a short answer back. The prompt has become an environment the model explores.
python# the model writes this inside the REPL; `context` is the 1,000,000-token prompt, held as a variable CHUNK = 50_000 chunks = [context[i:i+CHUNK] for i in range(0, len(context), CHUNK)] answers = [llm_query(f"Does this text give the fiscal-year revenue? Quote it.\n{c}") for c in chunks] print([a for a in answers if "revenue" in a]) # only these few lines ever return to the root model
Slide the length below. See how the root model’s own context stays small, while a pasted prompt overflows.
The long bar is the prompt. The bright part is what the model’s own context holds. Choose a method and drag the prompt length.
Illustrative toy. We assume a 128,000-token window, the cut-off of a pasted prompt dropping everything past it, a brute-force scan in 50,000-token chunks, and a root context of 1,500 tokens plus 40 per sub-call result. A real RLM can also search first and visit far fewer chunks. The paper reports inputs up to two orders of magnitude beyond the window.
At one million tokens the pasted prompt reaches only 12.8% of the text, so the chance that the footnote is inside is 12.8%. The RLM visits all 20 chunks, and its root context stays near 2,300 tokens. The lecture’s graph shows the real effect: GPT-5 falls off as input length grows, while the same model wrapped as an RLM holds up.
The paper’s abstract gives the comparison. On four long-context tasks, an RLM built on GPT-5 beat the base model, and beat a compaction harness by a median of 26%, a CodeAct agent with sub-calls by 130%, and Claude Code by 13%, at similar cost. The authors also post-trained a small model, RLM-Qwen3-8B, which beat plain Qwen3-8B by 28.3% on average. A guest slide quotes a later post that makes the point sharply: RLMs fold reasoning and tool use into one inference abstraction, where the model treats its own prompt as an environment.
Zhang offers a view that sounds simple. Language models are limited by their architecture. A harness is a set of opinionated choices, made on top of a black box, to get around those limits. On that view, even a complete coding agent such as mini-swe-agent is only about 100 lines of code.
Two papers from his group state what a harness does. The Mismanaged Geniuses Hypothesis (Zhang, Li and Khattab, 2026) says models are already capable enough to compose themselves into solutions to harder tasks, and that this is a property of the tasks. Harnesses help by implicitly shaping what the model sees. Language Model Harnesses are Compositional Generalizers (Zhang and Khattab, 2026) makes it testable. The idea is local in-distribution-ness: even if a whole long task is far from anything the model trained on, each individual model call inside a good harness can look like a short, familiar task. So train only on short tasks, test on longer ones, and let the harness cut the long task into short calls. Their check is whether performance on a long task is explained by re-running the closest training trajectories on the new inputs.
The failure mode of an RLM: the symptom is a root model that writes a bad slicing loop, or asks sub-calls too many times. The measurement is the number of sub-calls and the total tokens they read. The fix is training the model around the loop, which is why the paper post-trains RLM-Qwen3-8B.
Chapter 9
Measure the cost of a harness, and separate writing a good update from benefiting from one
You have now seen eight ways to rewrite a harness. A sharp reader should ask: does any of this beat just using a better model? If the harness only patches a weak model, it may shrink as models improve. If a harness gives a strong model new power, it will stay. Two readings and the end of the guest lecture try to measure which.
Zhang ends with the questions he finds most interesting now, at two levels. The micro level asks about individual design choices. Along a line from a base model, to compaction (summarising the history), to compaction plus an RLM, to an RLM, what does each step buy? And what happens if the model gets its own say in what it sees, which he calls model shape?
The macro level asks about scaling. We know how model quality grows with data and compute. How does it grow with a harness? He suggests two things to study: how a harness changes scaling with data and environments, and a scaling law for harnesses, with token spend as the axis.
Three harder questions follow on the slides. Are harnesses characterisable? To get predictable laws, you must first describe the class of harnesses you search over. As models get better, what is the harness for? And with a verifier, does a harness reduce to “LLM monkeys”, meaning many random tries plus a checker? The last slides blur the line between model and harness. A model need not always be a plain function from string to string. A harness might constrain its output to a small set of labels, and a harness change can become an architectural change.
The slide cites one measurement of the question, HarnessTax (Pan et al., 2026; the Arena study). The authors ran 21 model and harness pairs: seven models in three harnesses, Claude Code, Codex CLI and Pi (a minimal open-source harness). Each pair got the same 30 randomly picked tasks from two benchmarks, SWE-bench Lite and Terminal-Bench 2.0, three tries each, and a cap of 100 agent turns. Cost was priced from one fixed price list so harnesses compare fairly. Three findings:
| One model, three harnesses | Success on SWE-bench Lite | Cost per attempt |
|---|---|---|
| Claude Code | 97.8% | $1.33 |
| Codex CLI | 96.7% | not reported for this model |
| Pi | 96.7% | $0.67 |
Read the table in plain words. The best-scoring harness solved one more attempt in a hundred and cost about twice as much. Across the shared models on SWE-bench Lite, Claude Code cost roughly 2.0 times what Pi did and 1.6 times what Codex did. Whether that extra cost is worth it depends on how much one more solved attempt is worth to you. That is a design choice, and now it is a measured one.
The last reading asks about the models inside a self-evolving harness. Two jobs hide in the word “evolve”. Harness updating is writing a useful, lasting change to the harness after seeing what happened. Harness benefit is solving later tasks better with the changed harness. The paper, Harness Updating Is Not Harness Benefit (arXiv 2605.30621), tests whether the same model is good at both.
It is not. Updating is flat in base capability: models of very different strength write updates that give surprisingly similar gains, and a 9-billion-parameter Qwen model’s updates gave gains comparable to Claude Opus 4.6’s. Benefit is non-monotonic: weak models benefit little, mid-tier models benefit the most, and strong models benefit less than mid-tier ones. The paper traces the weak tier’s low gain to two failure modes. The weak model may fail to activate a relevant stored artifact, or it may activate it but fail to follow it faithfully. Its advice: spend capability on the agent that solves the task, not on the one that writes the updates, and train models to invoke harness artifacts and follow long instructions.
Try the grid. Pick who writes the update and who uses it.
Rows are the tier of the model that writes the update. Columns are the tier of the model that solves tasks with the updated harness. Each cell is the gain. Pick a writer and a solver.
Shape only, with made-up numbers: every writer gives an update worth about 8 points (flat), and a solver turns that into 2, 8 or 6 points (weak, mid, strong). The paper reports the pattern, flat updating and mid-tier peak benefit, in its own measurements; these values are ours, to make the pattern visible.
Look down the columns: the rows barely differ. Look across the rows: the middle column wins. In this toy the strongest writer gives no better update than the weakest, but the strongest model is not the best user of it.
Chapter 10
Review the numbers and terms, run the checklist, read the core loop as code, and find where to go next
You can now follow the whole session. An agent is a model plus a harness. The harness stores eight kinds of things. Memory decides what goes in the context. Tools and skills decide what the agent can do. And a model, given enough access, can rewrite any of it. This page gathers what you need to use that from memory.
A harness is the code around a model that manages its context and its flow of execution: context, control, action, evaluation and evolution. It stores episodes, feedback, facts, tools, skills, artifacts, plans and experience. Memory can sit in parameters, in the context, or outside. External memory (MemGPT, Mem0) is read and written by function calls. MEM1 keeps one internal state in the context and deletes the rest. Reflexion and ExpeL store notes about failures. A Context Language Model edits its whole context as a file. Tools are atomic actions, and code is the tool that composes them. Skills are reusable procedures, as text or as code. Meta-Harness lets a proposer rewrite the whole harness from full traces. An RLM keeps the prompt outside the window. And the measured effect of a harness is often on cost, not success.
The last slides repeat the memory map from Chapter 1 and the glossary from Chapter 0, then give a favourite three: MEM1 treats memory as an internal state in the context, updated by the model. CLM treats the entire context as a persistent file that the model maintains. Meta-Harness treats the entire harness as a file system that the model modifies. What do they share? They are simple, with no hand engineering and trained or run end to end. They form a new paradigm that widens what can be optimised automatically: memory, then context, then harness. And they give scalable results for zero-shot use, in-context prompting and fine-tuning. That is the ladder the hero at the top of this page climbs.
| What | Number | Why it matters |
|---|---|---|
| MEM1-7B vs Qwen2.5-14B, 16-objective task | 3.5× performance, 3.7× less memory; 27.1% of peak tokens, 29.3% of time | One small state keeps memory near constant |
| Reflexion on HumanEval | 91% pass@1 vs 80% for GPT-4 | Words in memory can replace weight updates |
| CLM on BrowseComp-Plus | +11.4% accuracy with 21.5% fewer FLOPs | The model manages its own context better than a rule |
| CLM context instructions evolved | up to +35.9 points held-out | Context management can itself be searched |
| Proposer feedback, Meta-Harness vs earlier optimisers | about 10M vs 26K tokens per iteration | Full traces let a failure be traced to a decision |
| Meta-Harness, text classification | +7.7 points, 4× fewer context tokens | A better harness can also be a cheaper one |
| Meta-Harness, maths retrieval | avg 38.8 vs 34.1 with no retriever (+4.7) | Random examples scored 32.2, worse than none |
| Darwin Godel Machine | SWE-bench 20.0% to 50.0%; Polyglot 14.2% to 30.7% | An archive of self-edited agents compounds |
| RLM-Qwen3-8B vs Qwen3-8B | +28.3% on average | Training around the loop pays |
| HarnessTax, same model, three harnesses | 97.8%, 96.7%, 96.7% success; $1.33 vs $0.67 | Harness choice moves cost more than success |
| Harness updating vs benefit | updating flat in capability; benefit peaks at mid tier | Spend capability on the solver, not the writer |
One loop holds every reach from the lecture. The only thing that changes is which part the model may write to:
pythonclass Harness: state = "" # reach 1, MEM1: one internal state, rewritten every turn context = "context.md" # reach 2, CLM: the whole live context, a file the model edits with bash files = {"tools.py": ..., "skills/": ..., "loop.py": ..., "checks.py": ...} # reach 3, Meta-Harness def episode(h, model, task): trace = [] while not done: ctx = build_context(h, task) # the harness decides what is on the desk reply = model(ctx) # the only call that touches the weights result = run(h.files["tools.py"], reply) # action: a tool call or a code action verdict = check(h.files["checks.py"], result) # evaluation trace.append((ctx, reply, result, verdict)) h.state = parse_state(reply) # MEM1: keep the new state, drop the rest return trace, score(trace) def evolve(h, archive, proposer): # Meta-Harness: the outer loop # the proposer sees every past harness: source, score, and traces, as files (grep, cat) new_files = proposer.propose(archive) h2 = Harness(files=new_files) trace, s = episode(h2, model, TASKS) # held-out tasks, in a sandbox archive.add(h2, s, trace) # keep every candidate, not only the best (DGM) return max(archive, key=score_of)
This session follows the context lecture, where the model searched over prompts, and leads to Harness evolution 2 in Week 6: a harness-engineering tutorial, tool and skill evolution, and multi-agent evolution. The same ideas appear in harness engineering, in the Stanford course follow-along on agent memory, and in today’s coding agents.
This lesson follows the course MIT MAS.S62, How to AI an AI for (Almost) Anything (Fall 2026), from the MIT Multisensory Intelligence group. Lecture 4 was taught by Paul Liang; the guest lecture was given by Alex Zhang. All explanations, devices and numbers marked illustrative here are our own. Course site: the schedule.
Now press Present or Teach and explain from memory how an agent rewrites its notes, its context and its code, and what each rewrite costs. Then go back to the harness at the top, run the loop at each reach, and say which parts stay locked and why.