Skip to main content
AGENTS
Andrei Moise · Agent Notes

How AI agents work

An agent is a model in a loop with tools, context, and memory. This page builds that loop piece by piece, then shows how to run it reliably, measure it honestly, and make it better over time. Every demo runs in your browser on small, labeled toy simulations.

Part 1 Foundations What an agent is, the model inside it, and the patterns it runs.
§1 · The Loop, the Boxes, the Spectrum

Anatomy of an agent

Coding, browser and terminal agents look different, but they share one shape: a language model that reasons, remembers and uses tools in a loop, with more loops wrapped around it. Most design decisions come down to two questions: who decides the next step, and which outer loops you build around the inner one.

Who holds the control flow?

Models, workflows, agents and multi-agent systems sit on one spectrum, ordered by where the control flow lives. In a workflow your code fixes the stages and the model works inside each one. In an agent the model picks the next tool and decides when it is done. On a GitHub issue, Agentless runs fixed stages (find the file, write a patch, run the tests), while SWE-agent lets the model choose what to open and run. A fixed pipeline wins on predictable tasks, an agent on tasks outside any script, and both pay for length, because per-step success compounds as pn.

DEMO 1.1 Who Holds the Control Flow?
Change openness and task length · watch 100 tasks split, then click one to read both traces
workflow · code picks each step · 100 tasks
agent · model picks each step · same 100 tasks
the same task under both designs · task 12

Each square is one task: green solved, amber saved by a retry, red cross failed a step, gray had no path through the script. Click a square to read both traces. Illustrative toy model.

Workflow53.9%code picks every step
Agent48.9%model picks every step
p^n59.9%all steps right, on-script
10%
0.950
10 steps
How this toy model works

Workflow success = (1 − openness) · pn: it fails outright on tasks its script lacks. The agent handles any task but picks a wrong next step 2% of the time. With retry on, it notices 60% of failed steps and redoes them once, at the cost of extra steps. Both coefficients are toy values. The 100 squares split each rate into whole tasks (rounded), in a fixed shuffled order, and the two traces are a short story of the task you picked, not a log.

  1. Start with a predictable task. Openness 10%, p = 0.950, 10 steps. The workflow wins, 53.9% to 48.9% (54 green squares to 49): it misses only the 10 gray tasks off its script, while the agent's freedom to choose costs it on every step.
  2. Make half the tasks unpredictable. Set openness to 50%. The workflow drops to 29.9% because 50 tasks turn gray: no path through its script. Click task 12 (one of them): its workflow trace stops at "No stage fits this task". The agent stays at 48.9% and wins.
  3. Make the task long. Set n to 30. Even a perfect script would succeed only 21.5% of the time (0.9530), and the two designs are nearly tied at 10.7% and 11.7%. Red crosses take over, 39 in the workflow grid and 88 in the agent's: one wrong step anywhere sinks a run.
  4. Let the agent check its own steps. Turn on retry. The agent climbs to 39.5% for 31.2 steps instead of 30, and 28 squares turn amber, saved by a retry. Catching and redoing failed steps keeps a long run alive, the same idea as the verification loop below.

Model, harness, context

The textbook diagram has five boxes: an LLM core, planning, memory, tools, and an environment the agent acts on and observes. For building, a more useful split is agent = model + harness + context. The model reasons and decides. The harness does everything else: it injects context, controls the run, executes actions, persists work, and observes and verifies results. Context is the configuration on top: instructions, skills, memory and tool definitions.

LayerWhat it doesClaude CodeOpenClaw
ModelReasons and picks the next actiona Claude modelmany models
HarnessFive jobs: inject context; control the run (compaction, orchestration, Ralph loops); execute tool, bash and MCP calls; persist work (files, Git, progress files); observe and verify (tests, logs, screenshots)Claude Code itselfPi plus other scaffolding
ContextConfiguration layered on top of the harnessCLAUDE.md, skills, mcp.jsonSOUL.md plus skills

Example mapping from a LangChain post on continual learning (2026). Product details change quickly.

Loops stack

The tool-calling loop is the innermost of several. A verification loop wraps it: a grader checks the output against a rubric and sends failures back for another try. An event-driven loop wraps that: crons, webhooks or chat messages start runs, so the agent works in the background of a larger system. The outermost loop reads many traces and rewrites the harness. The first three loops automate work, and the fourth automates improvement. This stack is also the map of this site.

DEMO 1.2 Stack the Loops
Switch on loops 2, 3 and 4 · play one run through the stack · watch 100 runs improve by day 30
the loop stack · lit = loop on · curl = tool-calling loop
one run through it · click a square below to pick another
day 1 · 100 runs
day 30
30 days of loop 4 · ✓ harness fix accepted · ✕ review wasted on a flake

Squares are runs: green right first time, amber fixed by a retry, gray sent to a person, red cross shipped wrong. Dots by the agent loop are the inspected run's attempts. Illustrative toy model.

0.60
More controls
0.90
3
0.50
50/day
3 traces
+0.02
How this toy model works

The loop-engineering post this follows gives no numbers. The grader here never rejects a good output. A person starts 5 runs a day when loop 3 is off. Failing traces split over 4 real causes, plus 25% one-off flakes. A cause files an issue at T matching traces (a flake only when T = 1). One issue is reviewed per day, and first-pass success tops out at 0.95. The 100 squares split the expected rates into whole runs (rounded) in a fixed shuffled order; the run trace is a short story of the square you picked.

Each loop has its own chapter: verification in §3, event-driven agents in §10, hill-climbing in §14.

  1. One loop only. With p = 0.60 and nothing checking the output, 40.0% of runs ship a wrong answer: 40 of the 100 squares are red crosses. At 5 hand-started runs a day, that is 2.0 bad outputs a day.
  2. Add verification. Grader recall 0.90, up to 3 retries, fix rate 0.50 (under More controls). Shipped-correct rises from 60.0% to 89.7% (+29.7 pts), but each run now averages 1.59 attempts, and 3.3% of runs exhaust their retries and go to a human. In the grid, 30 red squares turn amber, 3 turn gray and 7 stay red. Better quality costs latency and tokens.
  3. Close the improvement loop. Turn on hill-climbing with T = 3. By day 30 first-pass p climbs from 0.60 to 0.76 from 8 fixes, and attempts per run fall from 1.59 to 1.36. The 30-day strip shows 8 ✓ marks, and the day 30 grid has 76 green squares instead of 60. The outer loop's output reaches inside and changes loop 1.
  4. Let events drive the runs. At 50 events a day, day 1 ships 3.5 bad outputs, since more runs means more misses. Ten times the traces also feed loop 4: p reaches the 0.95 ceiling from 18 fixes, and bad outputs fall to 0.4 a day by day 30: 95 green squares and 1 red.
  • Model, harness, context. When an agent misbehaves there are three places to fix it: the model that reasons, the harness that runs and checks the work, and the context that configures the harness for a task or user.
  • The agency spectrum. Model, workflow, agent, multi-agent: each step right hands more control flow to the model. Pick a point per problem, not per company.
  • Compounding error. A 30-step task at 95% per step succeeds 21.5% of the time, so agents need recovery and verification.
  • Why tools exist. Models alone fail at exact multi-step computation, at knowledge after the training cutoff or behind a firewall, and at interfaces that are not language. GPT-4 gets about 59% on multiplication, and even o1 starts failing at about 4 digits, because accuracy falls as the required steps grow (Stanford CS329Z L4). Tools fill each gap.
Go deeper · 9 more notes
  • The five boxes, in detail. Each observation from the environment feeds the next thought. Every agent is a version of this diagram, and people draw the arrows differently, so the arrows carry little meaning. What differs between agents is how each box is built and how well the boxes fit together (Stanford CS329Z L1).
  • Workflows can be state of the art. AlphaCode 2 generates up to millions of candidate programs, then tests and ranks them, and is reported to beat about 87% of human competitors (Stanford CS329Z L1). Agents also cost more to evaluate and optimize, because each run takes its own path (§12, §14). With plenty of labeled data for a narrow task such as information extraction, one fine-tuned model can replace the whole workflow (§15).
  • Where humans sit in the stack. Each loop has a natural checkpoint: gate sensitive tool calls in the agent loop, let a person act as the grader for sensitive workflows, approve outputs before they reach users, and review harness edits before they deploy. Expertise you can write down belongs in the prompts and tools. Sensitive actions, such as financial transactions and database writes, keep live human review. A grader can check that every link in a doc resolves, but only a person notices that the framing is wrong for the audience.
  • Triage by system, data or metric. Model, harness and context say where a fix goes. A second question says what kind of fault it is: the architecture, the data (training examples, demonstrations, the context you supply) or the metric. A wrong metric can make a weak agent look good, so check it before trusting a win (§12). Engineering an agent needs all three pillars (Stanford CS329Z L1).
  • Always-on is the same loop, re-hosted. Move the loop to a server, give it persistent state and its own computer, and wake it with events instead of a chat message. Ambient agents (LangChain, 2025) move the trigger from a human message to an event stream, and still gate risky actions on human review.
  • Four eras (one speaker's framing). A talk on always-on agents sketches four eras of developer work with AI: copy-pasting from chat, terminal agents that edit files, apps running many agents in parallel with a human approving each command, and always-on agents with their own computer and memory.
  • Why agents need special runtimes. LangChain describes agents as slow, flaky and open-ended (2025), and as long-running, stateful and bursty (2025). Request-response backends assume the opposite, which is what Part III deals with.
  • Where multi-agent starts. One agent with parallel tool calls still has one main thread and one context window. Once control flow lives in several places at once, each with its own context, you have a multi-agent system. The lecturer calls this line blurry (Stanford CS329Z L8).
  • What the toy leaves out. Real graders also reject good outputs, and a grader the agent can game rewards the wrong thing. Harness edits from loop 4 can also regress, which is what the human review gate on harness changes is for. §12 and §14 treat both.
■ Takeaway · Next §2

Start at the least agency that covers your task distribution (a strong workflow, or with enough data one fine-tuned model, may be enough), then decide which outer loops (verify, trigger, improve) you need around it. Next, open the innermost box: the model call itself.

Next: §2 The Model Inside the Loop
§2 · The Model Inside the Loop

The Model Inside the Loop: decoding, caches, and test-time compute

You do not need to train a model to build an agent, but three of its internals shape your engineering choices. The decoding rule sets how predictable a tool call is. The prompt cache sets what each loop iteration costs. The tokens you let the model spend thinking or sampling set accuracy, latency and budget together.

Decoding: one distribution, many ways to sample it

At each step the model outputs a score (logit) for every vocabulary token, and a decoding rule picks one. Greedy takes the top token. Temperature divides the logits by T before the softmax: low T sharpens, high T flattens. Top-k keeps the k most likely tokens; top-p keeps the smallest top set whose mass reaches p. The model samples from what is left.

DEMO 2.1 Decoding Dial
Move temperature and top-p · watch which cards survive and what 50 rollouts write
Prompt:
candidate next tokens · kept · cut by top-k or top-p
50 rollouts · what the model writes in the slot each time

Each card is one candidate token and its share after temperature and the cuts. Green chips match the top token; outlined chips are other picks. Illustrative toy model.

1.0
off
More controls
off
How this toy model works

Hand-made logits over 12 tokens, shaped like the lecture example (Stanford CS329Z L2). Temperature applies first, then top-k, then top-p; the kept tokens are renormalized and "picked" counts come from sampling that renormalized set. Kept cards show their share after that renormalizing; cut cards show the probability they had before the cut. Samples use a seeded generator, so each setting always shows the same first draw. "Draw 50 more" moves to the next seeded draw.

  1. Set T = 0.2. "nap" holds 97% at 0.20 bits of entropy, and 47 of 50 rollouts write "nap": effectively greedy.
  2. Raise T to 2.0. The cards even out: "nap" drops to 26%, entropy rises to 3.14 bits, and the 50 rollouts land on 10 different tokens.
  3. Now set top-p to 0.30. The nucleus cuts the flat tail: ten cards go dashed, and only "nap" (59%) and "break" (41%) survive, at 0.98 bits.
  4. Switch to "for i in ___" at T = 1.0. These logits are already peaked, so "range" gets 90% at 0.71 bits. A safe temperature depends on the task.

The cache: why you append and never prepend

Inference has two phases. Prefill reads the whole prompt in one parallel pass and sets time to first token. Decode then emits one token at a time, and each step reads the stored keys and values of all earlier tokens: the KV cache. Those values are tied to positions, so inserting anything before them invalidates them. Appending reuses them.

Providers sell the same idea as prompt caching. An agent resends the whole conversation on every call, and an unchanged prefix is billed at a heavy discount, so treat a cache miss as a bug.

Cost of one call (fresh-token units)
$$\text{cost} = p_{\text{cached}} \cdot \text{tokens}_{\text{cached prefix}} + 1 \cdot \text{tokens}_{\text{after first change}}$$
The prefix ends at the first block that differs from the previous call.
DEMO 2.2 Cache-Warm Prompt
Break the prefix three ways · watch where each call's prompt stops matching the last one
At call K:
the prompt sent on every call, block by block · | first change

One row per call. Solid blocks come from the cache at a discount; hatched blocks after the red mark are recomputed at full price. Illustrative toy model with made-up token sizes.

Tokens cached 87% Share of all tokens sent
Total cost 133k In fresh-token units
Last prompt 79.2k Tokens sent on the final call
More controls
12
n/a
10%
How this toy model works

A 3k-token system prompt, 40 tools at 400 tokens each (10 tokens per name with tool search, plus a 400-token schema read per turn), 5k new tokens per turn, an 8k doc, and a cache that stays warm between calls. Each call reuses the longest block prefix it shares with the previous call. The toy tool edit changes a schema, not a tool name. The 10% default cached price is a toy value.

  1. Start: 12 calls, nothing changes. Only call 1 is cold. Later calls pay full price only for their new 5k-token turn: 87% cached, 133k fresh-token units, and a 79.2k-token last prompt.
  2. Tick "current time at top". Twenty tokens change at position 0 on every call: 0% cached, 618k units, ×4.6 the cost. Sending the time as a note at the end fixes it.
  3. Pick "Prepend a doc". Call 6 recomputes 57.1k tokens, and the run costs ×1.27 what appending costs. Click "Append a doc": the doc is paid once and the cache stays at 87%.
  4. Pick "Deploy edits a tool". Only the 3k system prompt survives: 46.1k tokens recomputed, cost ×1.28, 81% cached. Now tick tool search. The prompt carries names only, so the edit lands in a schema file: 85% cached (each turn reads one schema fresh) and 108k units.

Test-time compute: buying accuracy with tokens

Chain of thought, reasoning-effort levels, best-of-N with a verifier and self-consistency all trade tokens for accuracy, and inside an agent they also cost time (§8 covers where to spend effort). The simplest form is self-consistency: ask k times and take the most common answer.

DEMO 2.3 Self-Consistency Voting
Change how spread out the errors are · watch 100 votes turn green or red
100 seeded votes · click a tile or use arrow keys to open its ballots
exact vote accuracy for each k · beats one sample · worse

Each tile is one vote of k samples: green if the right answer (51) won, red if a wrong one did. Illustrative toy model (Stanford CS329Z L1).

60%
11
3
How this toy model works

Samples are independent, each is right with probability q, and wrong samples split evenly across the wrong answers. Ties at the top are broken at random. The 100 tiles come from a seeded generator, so they wobble around the exact accuracy, which is computed without sampling and shown in the readout and the k row. Based on the self-consistency demo idea in Stanford CS329Z L1.

  1. q = 60%, 3 wrong answers, k = 11. Each wrong answer gets 13%, so the vote reaches 94.6%: +34.6 points. 91 of the 100 seeded votes come out green.
  2. Drop q to 40% with 4 wrong answers. The model is usually wrong, but its errors spread out at 15% each, so the right answer still wins: 70.8% exact, 67 green tiles.
  3. Set wrong answers to 2. Each gets 30%, close to the right answer's 40%: the gain shrinks to +10.4 points (50.4%), and only 45 tiles are green.
  4. Set wrong answers to 1 and k to 21. One shared wrong answer at 60% wins, and accuracy falls to 17.4%, a 22.6-point loss: 82 of 100 tiles turn red. More samples make a shared mistake more certain.
  • Decoding is a task choice. Low temperature or a tight top-p for tool calls and code, more spread for brainstorming. Temperature is a plain logit divisor set at inference; it is neither learned nor bounded.
  • Static first, changing last. Both caches reuse only an unchanged prefix. Put the system prompt and tool definitions first, frozen for the session and in a fixed order, then the conversation, then new material. Never add or remove tools mid-turn. Tool search keeps the top small and stable.
  • Test-time compute costs time too. More reasoning or samples raise accuracy, latency and spend together. Under a deadline, maximum effort everywhere can lose (see Go deeper).
  • Voting needs spread-out errors. Self-consistency helps when wrong answers disagree. When the model repeats one mistake, voting locks it in.
Go deeper · 7 more notes
  • Effort under a deadline. LangChain reports that more reasoning can cost more than twice the tokens and time. Under Terminal-Bench 2.0's hard timeouts, xhigh effort everywhere scored 53.9% against 63.6% for high everywhere (self-reported, gpt-5.2-codex; the harness stage for those runs is unclear). The numbers come from one vendor post on one benchmark, and the post says other effort splits did not differ much.
  • TTFT and TPOT. A model scores a sequence as a product of next-token probabilities. Prefill sets time to first token and is compute-bound; decode sets time per output token and is memory-bound, because the KV cache grows with every token. Speculative decoding has a small draft model propose several tokens that the large model checks in one pass. More drafts are accepted on code than on summarization, which suggests code is more predictable (Stanford CS329Z L2).
  • Linear attention and context length. Dropping the softmax lets attention keep a fixed d × d state, so memory stays constant, but long-context recall suffers: RWKV and Mamba fall off on needle-in-a-haystack tests where full attention does not. Hybrid models interleave linear layers with some global or sliding-window attention layers; in the lecture's results, adding such layers improved retrieval without hurting common-sense tasks. Usable context length is mostly learned: apart from positional embeddings, nothing in attention caps it, so it depends on how long the training sequences were. For long agent runs, prefer full or hybrid attention, or test needle and aggregation recall yourself at the context length you will use.
  • More cache rules from practice. Hash each prompt section and keep a fixed order, so an A/B-test section can be added without reordering the rest. Prewarm the cache when the user opens the chat and starts typing. The talk these rules come from puts provider cache lifetime at roughly 10 to 60 minutes; that is the speaker's estimate, not a spec.
  • Best-of-N with a verifier. The share of problems solved at least once rises with the number of samples, but you only cash that in if something can pick the right sample. Self-consistency is the verifier-free fallback: the majority stands in for the check.
  • Reasoning effort as a setting. Some models take low, medium or high effort in the system prompt, and some budget-aware training penalizes wrong answers that also overrun the budget. Kimi's scheme, as presented in the lecture, scores +1 for correct, 0 for wrong and -1 for wrong and over budget, so an unsure model does better to stop early. Nine teachers, trained with RL per domain and effort level, are then distilled into one student model.
  • Two serving profiles. A main agent the user is waiting on needs low latency. Background helpers on long tasks can run on slower, cheaper serving, since 10 versus 12 minutes does not matter there.
■ Takeaway · Next §3

Treat the prompt prefix like an API you must not break, and spend extra tokens only where they buy accuracy. Next, the reasoning patterns that decide how an agent spends those tokens step by step.

Next: §3 Reasoning Patterns
§3 · Reasoning Patterns

Reasoning and workflow patterns: ReAct, Reflexion, plan-and-execute

Most agents are built from a few reusable shapes: think before each tool call, chain or fan out calls, check and retry, or write the whole plan first. Each trades accuracy against calls and seconds. Treat them like software design patterns that you adapt to your task.

Reason, act, observe

Chain-of-thought (CoT) reasons in one pass from what the model remembers. ReAct interleaves a thought, an action and an observation, so a failed search can be rewritten and every fact rests on a tool result. In the ReAct paper, hallucination was 0% of ReAct's failures and 56% of CoT's; ReAct failed mostly through reasoning errors and bad search results. Written thoughts make each action auditable, but chain-of-thought may not reflect what the model computed, so check a trace against the tool calls and observations it cites.

DEMO 3.1 Think vs Act vs ReAct
Change recall, search and steps · watch which mode wins and how it fails
Trace mode
200 trials per mode · same questions, same luck · click a square to read that trial
CoT think only
Act-only search, no thoughts
ReAct think, search, observe

Illustrative toy model, seeded so it repeats. Squares: right, hallucinated, search miss, reasoning error, grey out of steps. Real anchor: hallucination was 0% of ReAct's failures, 56% of CoT's.

40%
80%
More controls
2
6
How this toy model works

CoT answers each hop from recall, and a miss is a hallucination. Act-only searches once per hop and gives up on a miss. ReAct rewrites a failed query up to twice, and each search costs a step. Every mode has a 4% reasoning error per hop. The real figure (ReAct paper, as read out in Stanford CS329Z L1) is a share of failures, while the grids count trials.

  1. Start: recall 40%, search 80%, 2 hops, 6 steps. ReAct succeeds on 178 of 200 (89%), Act-only 56%, CoT 11%. CoT's grid is mostly coral crosses: 178 hallucinations. ReAct has none, since every fact comes from a search result.
  2. Drop search quality to 30%. ReAct falls to 40%, failing on search errors (112) with 0 hallucinations. Act-only, which cannot rewrite a query, falls to 9%.
  3. Search back to 80%, hops to 4. CoT drops to 1%, since every hop is another chance to misremember. ReAct reaches 60%, but 42 trials run out of steps; at max steps 10 it climbs to 81%.
  4. Recall 95%, 2 hops, max steps 3. CoT wins, 83% vs ReAct's 56%, because 71 ReAct trials run out of steps. Lookups pay off when memory is unreliable.

Workflow patterns compose

When your code owns the control flow, you have a workflow. Anthropic names five patterns: prompt chaining (sequential calls, optional gates), routing (a classifier sends easy inputs to a cheap model), parallelization (split independent work, or vote on one input), orchestrator-workers (the model decides how many subtasks to spawn) and evaluator-optimizer (generate, critique, retry). Real systems stack them.

Toy voting accuracy: N samples, per-call accuracy p, correlation ρ
$$\text{acc} = \rho\,p + (1-\rho)\sum_{j > N/2} \binom{N}{j} p^{j} (1-p)^{N-j}$$
DEMO 3.2 Pattern Composer
Pick a pattern and move its knobs · watch accuracy, calls and seconds
Pattern
LLM calls over time · one lane per call that runs at once
100 toy tasks · one call vs the pattern

Illustrative toy model. Blocks: model call, judge, grey router, small model; faded blocks run only when the judge flags an error. Faded controls do not apply.

Accuracy84%+13.7 pts vs one call
Calls per task5full-call units, on average
Latency2.0 smean wait per task
70%
More controls
5
0.0
3
60%
2
How this toy model works

A full call takes 2 s. Chain: each of k steps has error (1−p)/k and all must succeed. Route: 60% of tasks are easy, the router is right 90% of the time, the router call and a small-model call each cost 0.1 and take 0.5 s, and a hard task sent to the small model loses half its accuracy. Vote: the formula above. Evaluator: generate plus judge is 2 calls per attempt. The task grid shows only the net change against one call.

  1. Start: vote x5 at 70% per call. 84% (+13.7 pts) for 5x the calls; latency stays 2.0 s because samples run in parallel.
  2. Raise vote correlation to 0.8. The gain shrinks to +2.7 pts at the same cost. Samples that share a mistake cannot outvote it.
  3. Click Chain with 3 steps. +2.9 pts for 3x cost and 3x latency (6.0 s), since calls run in sequence. Route gives −1.4 pts at 42% lower cost.
  4. Click Evaluator loop: judge catches 60%, 2 retries. +14.9 pts for 2.42 calls and 4.8 s on average, up to 12.0 s if every retry fires. With the judge at 20% the gain falls to +4.5 pts.

Reflection needs a signal from outside

Reflexion lets an agent write a short lesson after a failed attempt and reuse it next time, by prompting alone. It worked because the feedback came from outside the model, such as failing unit tests. Prompted self-correction with no outside signal made capable models worse on GSM8K and CommonsenseQA. LangChain sees the coding-agent version in its traces: the agent re-reads its code, decides it looks fine, and stops without running anything. Their fix: a plan, build, verify, fix procedure, a hook that forces verification before exit, and checks against the spec.

DEMO 3.3 Reflection That Helps vs Hurts
Switch the feedback source and the hook · watch bugs shipped
Feedback
100 toy tasks after verify and fix · click a square
what the agent did on that task

Illustrative toy numbers, not measurements. Squares: right and stayed right, bug fixed, good code broken by a false alarm, bug shipped.

Correct submitted66of 100 toy tasks
Bugs shipped34submitted as done
Change vs first try−4.1 ptsafter the verify rounds
70%
More controls
10%
2
How this toy model works

Per round, a real bug is caught 15% of the time by self-review, 65% by a tool-using critic and 85% by tests against the spec; a caught bug is then fixed 30%, 50% or 60% of the time. A false alarm on correct code makes the agent "fix" it, which breaks it half the time (tests 2% false alarms, critic 5%, self-review set by the slider). Without the hook the agent verifies only 30% of the time. Based on Reflexion, CRITIC, "LLMs Cannot Self-Correct Reasoning Yet" (Stanford CS329Z L6) and LangChain's "looks fine, done" trace pattern.

  1. Start: re-read own code, hook on, 2 rounds. Correctness falls from 70% to 66% (−4.1 pts): false alarms broke 6.9 good tasks while 2.8 bugs got fixed, so 34 bugs ship. Click a coral cross to watch the agent "fix" working code.
  2. Click Run tests vs spec. +21.6 pts to 92%: 23.2 bugs fixed, 1.5 good tasks broken, and only 8 bugs ship.
  3. Turn the hook off. The agent verifies only 30% of the time ("looks fine, done"). The gain drops to +8.1 pts and 22 bugs ship, despite good tests.
  4. Raise first-try correct to 90% with self-review. The loss grows to −7.7 pts: a stronger model has more correct code for false alarms to break. Tests vs spec add only +6.2 pts here, so measure before adding reflection.

Plan first, then execute

ReAct pays for a model call before every action. Plan-then-execute turns a run back into a workflow. ReWOO writes the whole plan with variable references (step 2 uses step 1's output), a worker runs it with no model in the loop, and a solver answers, using fewer tokens than ReAct in its paper. LLMCompiler runs independent tool calls in parallel from a graph and replans when a check fails, which cuts latency. The price is adaptation: a fixed plan cannot react to a surprise mid-run. Today the idea mostly appears as one generated program that calls tools (CodeAct) or a batch of parallel tool calls (see §7, Demo 7.2).

  • Reason before acting. Grounding each step in a tool result removed hallucination as a failure mode, at the price of search errors and step costs.
  • Patterns trade three things. Chaining buys accuracy with latency, voting with calls, and routing saves cost at a small accuracy risk.
  • A verification loop is grader, feedback, retry. Graders can be code or an LLM judge. It pays only when feedback can be stated clearly and the judge is reliable; for human preference, put the user in the loop.
  • Reflection needs an external signal. Tests, a tool-using critic, or the spec. Prompted self-review can hurt, and agents left alone often skip verification.
  • Plan-and-execute is cheaper, less adaptive. ReWOO and LLMCompiler save tokens and latency; a fixed plan recovers only through a replan step.
Go deeper · 9 more notes
  • Prompted ReAct at scale. At 540B parameters, prompted ReAct lagged baselines that used parametric knowledge; fine-tuning on ReAct trajectories made it strong. Models are now post-trained as agents. Written thoughts also let reasoning carry over to similar cases.
  • CRITIC. A verifier with tools (search, code) clearly beat one without, which behaved like plain reflection.
  • Parallel judges. A judge that scores a 10-item rubric as 10 parallel calls keeps each call focused at single-call latency.
  • Orchestrator-workers vs parallelization. Both fan out. Parallel branches are fixed in code; an orchestrator decides how many subtasks to create, for work you cannot predict.
  • Patterns stack. STORM, which writes cited Wikipedia-style articles, combines orchestrator-workers, a question-and-answer loop per perspective, chaining into an outline, and a parallel branch.
  • Workflows can be searched. Archon searches compositions of generators, critics, rankers, verifiers and fusers under a token budget. Without diverse generators it collapses, like the correlation slider in Demo 3.2.
  • Concrete graders. LangChain's docs agent checks that links resolve, CI passes, and the diff touches only what was asked. Its verify-hook results are qualitative, from its own traces.
  • Where explicit plans survive. Mainly for laying out sub-agent workflows. An agent stuck on a broken plan can loop, with more than 10 near-identical edits in some LangChain traces (see §8).
  • Scaffolding is temporary. Reasoning models already self-correct inside their traces, so benchmark before adding a reflection step. LangChain calls its forced verification and loop detection workarounds for today's models.
■ Takeaway · Next §4

Reason before acting, verify with something outside the model, and add structure only when your evals justify the extra calls and seconds. Every one of these patterns fills the context window, so next we look at what the model should see.

Next: §4 Context Engineering
Part 2 Context and Knowledge What the agent sees, what it looks up, and what it remembers.
§4 · Context Engineering

Context engineering: rot, compaction, offloading, isolation

Every model call sees only its context window: the system prompt, tool definitions, message history, tool outputs and memories. Context engineering is getting the right context into every call as the run unfolds. The window is scarce and it degrades: it fills up, gets slower and costlier, and past a point the model uses it worse. Two principles guide the fixes (Stanford CS329Z L6): keep the context focused, and preserve continuity.

Longer context, lower accuracy

On OOLONG, a benchmark of aggregation questions over many documents, accuracy falls from about 90% on short inputs to about 10% on long ones (read off a lecture chart). The answer is in the window and the model still cannot use it. This is context rot, and tool definitions feed it too. Two ways out: retrieve only what the call needs, or split the work so no call is large. Recursive Language Models (RLMs) split: the prompt sits in a variable in a code environment, and the model slices it with code and calls itself on the pieces. The lecture reports this lifted a small model to the top OOLONG score, ahead of its larger sibling.

DEMO 4.1 Context Rot vs. Recursive Splitting
Grow the document pile · watch one big call fog over while small calls stay clear
Strategy:
QuestionHow many of the 5 docs mention a refund?

Boxes are model calls: wider means more tokens, red fog means context rot, the blue strip is tool definitions. Tiles are documents. Illustrative toy model shaped like OOLONG, not real data.

5 docs
4 tools
More controls
10
20 docs
How this toy model works

One call's accuracy falls with its token count L (1k tokens per document, 600 per tool definition, 2k system prompt), tuned to the OOLONG shape: about 89% at 5 docs, about 10% at 1,000. Top-k sees only k documents, so a count over all of them scales with k / n. Recursive mode multiplies the accuracy of one chunk call by that of the root call, which reads 150-token notes instead of raw documents.

$$\text{acc}(L) = \frac{0.92}{1 + (L / 172\text{k})^{1.2}}$$
  1. Stuff 1,000 documents. At 5 docs one 9.4k-token call scores 89%. At 1,000 docs that call carries 1.00M tokens and scores 10%, with the answer still in the window.
  2. Retrieve top-k at 20 docs. The call shrinks to 14.4k tokens but sees only 50% of the documents, so the count scores 44% against 84% for stuffing. Retrieval suits needle questions; a total needs every document.
  3. Go recursive at 1,000 docs. 50 chunk calls of 24.4k plus one root call score 74% against 10% for stuffing. The total read is 1.23M tokens, more than stuffing: the extra calls pay for keeping each call small.
  4. Now load 40 tools. Each of the 51 calls carries 24k tokens of tool definitions, so the biggest call grows to 46k and accuracy drops to 62%.

Budget the window, turn by turn

In a coding agent most tokens go to observations (tool outputs). Each fix below removes one kind of bulk. Observation masking swaps old outputs for short stubs by rule; the lecture's "Complexity Trap" result reports it does about as well as LLM-summary compaction, with less complexity and no summarization delay. Masking in batches (every 5 or 10 turns) limits how often the cached prefix is invalidated. Tool search keeps only tool names in the prompt and loads a full schema when the model needs it. Offloading sends long outputs to files and heavy work to sub-agents that return a short report.

DEMO 4.2 Context Budget Lab
Pick a preset · play the run · watch outputs shrink to stubs and files
Presets:
every turn of the run · fits · past 80% · over the window · top tick cache reset · ◆ compaction

Illustrative toy model. Each block is one item in the prompt at the viewed turn, sized by its tokens; the outline is the window. A cache reset is any rewrite of earlier context.

Peak context0largest prompt in the run
Cache resets0prefix rewrites
Tool defs0tokens on every call
turn 34 of 100
More controls
Preset:
every 1
100
2k
128k
10
10 turns
Strategies:
How this toy model works

Per turn: 300 tokens of reasoning and action plus one tool output; every 5th turn is a search with 3× the output. A full tool definition is 2,400 tokens, a name 25; on demand loads 3 full definitions. Masked outputs become 50-token stubs, file previews 400, sub-agent reports 400. Compaction keeps the last 5 turns and a 2k summary. Each masking pass or compaction changes earlier context, which counts as one cache reset.

  1. Raw log. 100 turns, 2k outputs, a 128k window and no strategy: the context overflows at turn 34, and observations are 71% of it. The view stops there: amber outputs fill the box and the last blocks spill into the hatched zone past the outline. Press Play to watch it fill.
  2. Mask outputs older than 10 turns, in batches of 10. All 100 turns fit, peaking at 111k, with 9 cache resets: every 10 turns a batch of old outputs collapses into thin stubs. Set the batch to every 1 (More controls) and the peak drops to 89.5k, but cache resets jump to 90. Batching trades a little headroom for a stable prefix.
  3. Connect 40 tools. Full definitions take 96k tokens on every call, a wall of blue before the agent does anything, and the run overflows at turn 10. Under More controls, check "Tool details on demand": tool definitions drop to 8.2k and overflow moves to turn 39.
  4. Stack them all for 200 turns. The run fits with an 87.5k peak and 19 cache resets. By turn 200, 160 long outputs live in files and 40 searches went to a sub-agent, so the box holds previews, reports and stubs. Compaction is armed but never fires, so the one lossy pattern serves only as a backstop.

What survives compaction

Compaction (summarizing older context once it passes a threshold) is the simplest fix and always lossy. The lectures return to one case: a user told an inbox agent to confirm before deleting anything, compaction judged that early instruction unimportant and dropped it, and the agent went on deleting email. What survives compaction is a design decision. Pin requirements, goals and constraints so no summary can touch them.

DEMO 4.3 What Survives Compaction
Shrink the budget · press Play · watch the rule card leave and deletes go unconfirmed
Memory mode:
30 inbox steps · ✓ asked before deleting · ✕ deleted unconfirmed · bottom stripe: rule in context or gone

Illustrative toy model of the inbox incident in Stanford CS329Z L1, L2 and L7. Cards are items in context; the green card is the user's rule, numbered by step.

40 items
step 30
How this toy model works

Step 1 is the rule; steps 2 to 30 are inbox actions, 11 of them deletes. Episodic drops the oldest items. Semantic folds the lowest-scoring items into a counts-only summary, with score = importance × 0.5^(age / 4), so an old, never-referenced rule decays. Pinned never folds the rule. Before each delete the agent asks only if the rule is still in context.

  1. Episodic, budget 40. All 30 items fit, so the agent asks before each of the 11 deletes and none goes unconfirmed.
  2. Drop the budget to 10. The oldest item goes first, and the oldest item is the rule: at step 11 its card lands in the Dropped bin. 9 of 11 deletes go ahead unconfirmed, the first at step 14.
  3. Switch to Semantic. Folding by importance removes old reads and labels first, which buys two steps. At step 13 the rule's score has decayed to 0.11 and it is folded into the summary. Still 9 unconfirmed deletes.
  4. Pin the rule. Same budget of 10, but the rule is never folded: the agent asks before all 11 deletes.
  • Context rot. Accuracy falls as the context grows, even with the answer inside. Spend the window like a budget.
  • Tools are context. Every definition rides on every call. Keep the set small, or list names only and load schemas on demand.
  • Mask before you summarize. Stubbing old outputs by rule works about as well as LLM summaries and costs less. Batch it to keep the cache warm.
  • Isolate heavy reading. Sub-agents, recursive calls and progressive disclosure of skills (names in the prompt, contents on demand) keep bulk out of the main window.
  • Pin what must survive. Compaction can silently drop a constraint. Keep requirements, goals and safety rules in a pinned block.
Go deeper · 12 more notes
  • Why it is the core job. LangChain's June 2025 post on when to build multi-agent systems calls context engineering "effectively the #1 job" of agent engineers.
  • Position matters. Accuracy over evidence position is U-shaped. In the "Lost in the Middle" QA results cited in CS329Z L4, a relevant document at the start or end gives about 88%; in the middle it falls to about the closed-book score of 56%. Put critical evidence and instructions at the start or end.
  • Advertised is not usable. In needle-in-a-haystack tests GPT-4 starts to degrade around 73K of its 128K tokens.
  • The harness tax. Pi, a minimal harness with four default tools, beat Codex and Claude Code on Terminal-Bench for every tested model except one (margins not given).
  • A tool budget in numbers. A practitioner's widget on always-on agents (all illustrative): 40 tools with full descriptions take 241k tokens and overflow a 200k window; names only plus details for the 3 tools in use take 150k; moving tool outputs to files, screenshots to a helper and old messages to a summary frees another 30k, 40k and 50k.
  • Write, select, compress, isolate. LangChain's taxonomy covers the patterns: write context out (files, memory), select what comes back in (retrieval, tool search), compress (masking, compaction), and isolate (sub-agents). The patterns stack (L6).
  • Append, don't prepend. Inserting at the front of the prompt shifts every position and invalidates the whole KV cache. Put changing values at the end, and avoid adding or removing tools mid-session.
  • Event log as source of truth. OpenHands keeps an append-only stream of tagged events and rebuilds each model input from it by filtering and grouping. Masking and compaction then change the view, never the record.
  • Skeletons for long traces. A trace-mining agent described by LangChain compresses each trace to one row per turn (role, tool name, latency, character count, no content), spots odd shapes, and greps the full trace only where needed.
  • Long horizons. For runs of hundreds of turns, summarize each finished phase, write the plan to external memory, and near the limit spawn a fresh sub-agent with a careful handoff (LangChain's June 2025 multi-agent post, citing Anthropic's research system).
  • Test format choices. Markdown or YAML, which tools to include and in what order: treat each as a hypothesis and settle it with a benchmark run (L2). §12 covers how to build that eval.
  • The harness delivers context. A start-up hook that maps the working directory and finds installed tools, then injects that map, spares the agent its own error-prone discovery (a vendor's harness change, with no per-change ablation to show its effect).
■ Takeaway · Next §5

Decide on purpose what the model sees on every call: keep it small, push bulk into files and sub-agents, and never let housekeeping delete a constraint. Next, the "select" half of the job: how agents retrieve the right documents when they need them.

Next: §5 Retrieval & Agentic RAG
§5 · Retrieval

Retrieval and Agentic RAG: search as an action the agent chooses

A model cannot know your error codes, last quarter's numbers, or the ticket filed this morning. Retrieval fetches that evidence when needed, so the agent can cite the passage it used and you update knowledge by changing the index instead of the weights. Built-in web search reaches only public pages, so private documents and databases still need your own retrieval. Classic RAG runs one search with the user's question every time. An agent treats search as a tool call and decides whether to search, what to search for, and when to stop (Stanford CS329Z L3).

Decision 1: search, or answer from memory?

Each search adds latency and tokens, and a near-miss passage can pull the model away from an answer it already had right. Never searching fails on facts the model cannot know. A simple policy searches only when the model's confidence is below a threshold.

Adaptive retrieval policy
$$\text{search}(q) \iff \text{conf}(q) < \tau$$
τ = 0: never searchτ = 1: always searchthe right τ depends on the questions you get
DEMO 5.1 Should the Agent Look It Up?
Move τ or switch the workload · watch questions cross from memory to search
Workload:
60 questions, routed by stated confidence · click one to inspect
what the agent did on that question

Each square is a question, sorted by confidence: filled = answered right, hollow ✕ = wrong. Illustrative toy model: 60 seeded questions, not a benchmark.

0.50
More controls
#1
How this toy model works

60 seeded questions. The model already knows 90% of general, 45% of long-tail and 5% of fresh or private facts. One search returns the answering passage 55%, 80% and 90% of the time. When the passage is a distractor, a model that knew the answer keeps it half the time. Stated confidence is higher when the model knows, but the ranges overlap. Latency assumes 2.0 s per answer plus 1.5 s per search. Question wording is illustrative.

  1. Mostly general knowledge, τ = 0 (never search). 46 of 60 correct (76.7%) at 2.00 s per question. All five fresh questions on the bottom row are wrong.
  2. Now τ = 1 (always search). 53 of 60 (88.3%) at 3.50 s. Search filled 12 gaps, but distracting passages broke 5 answers the model already had right.
  3. τ = 0.55. 57 of 60 (95%) with 24 searches (40%) at 2.60 s per question. Search fills the same 12 gaps and breaks just 1 answer, because confident questions skip it.
  4. Switch to mostly fresh, τ = 0.65. 95% again, with 85% of questions searched. Never searching gets 25% here, and the earlier best of 0.55 gives 86.7%. Tune τ on your own traffic.

Decision 2: what to search for, and when to stop

Many questions need a chain of facts, where each query depends on what the last one found, so one search with the whole question finds the first fact at best. An agent splits the question into a Thought, Search, Observation loop and rewrites a query when it misses. It stops when every fact is found, the step budget is spent, or the same query keeps returning the same miss.

DEMO 5.2 Multi-Hop Search Trace
Pick a strategy, budget and rewrite rule · watch the evidence chain and where the trace stops
Strategy:
evidence chain of the selected question

all four questions · ● search hit · ● miss · ○ unused budget · click to inspect
    trace of the selected question · Play steps through it

    Trace rows: thought, search call, result, miss, stop. Illustrative toy model: a scripted world with fictional names, not a benchmark.

    3
    More controls
    Question:
    How this toy model works

    Search returns one passage per query. The company was renamed, so the first founder query returns only the rename notice. A question counts as answered only when every hop is found; otherwise the model guesses and is scored wrong. Without rewriting, the agent repeats the failed query and a loop guard stops it on the second identical miss. The Thought, Search, Observation format follows ReAct, and the "who is older?" Search-R1 example in the lecture refined its query over three searches.

    1. One-shot query on the 4-hop question. It returns only "made by Corvid Labs". Across the four questions, 1 of 4 is answered with 4 searches, and only the 1-hop question survives.
    2. Agent, budget 3, rewriting on. 3 of 4 answered with 9 searches. The trace finds the maker, misses the founder, rewrites to "Corvid Robotics founder", then stops: budget hit with 2 hops unanswered.
    3. Raise the budget to 5. 4 of 4 with 11 searches. The 4-hop question uses exactly 5 (four hops plus one rewrite) and stops because the evidence is complete. Budget 6 adds nothing.
    4. Turn rewriting off. 2 of 4 with 9 searches. On "2 hops + rename" the agent repeats "Corvid Labs founder", gets the same rename notice, and the loop guard stops it after 3 searches. Budget 6 still gives 2 of 4: more steps cannot fix a query that never matches.

    Decision 3: is the evidence good enough?

    The trace above assumed every search returns the right passage. Real searches also return namesakes and stale pages, and those errors flow into the answer. CRAG adds a light evaluator that scores each passage, then keeps it or discards it and searches again with a rewritten query. Its threshold trades distractors let through against good passages thrown away.

    DEMO 5.3 Agentic RAG Loop vs One-Shot
    Switch modes and move the threshold · watch 100 runs and the evaluator's calls
    Mode:
    100 seeded runs · click a square to inspect it
    passages over all 100 runs
    trajectory of the selected run

    The trace shows each search, the passage it returned with a relevance score, and the evaluator's keep or discard call. Illustrative toy model: fictional people, 100 seeded runs, not a benchmark.

    30%
    3
    0.50
    More controls
    Question:
    #1
    How this toy model works

    One passage per search. Relevance scores are drawn so good and bad passages overlap (right passages 0.45 to 1.00, distractors 0 to 0.65), so no threshold is perfect. The evaluator is a simplified CRAG with one threshold (no "ambiguous" band, no web-search fallback). A wrong or missing fact turns the two-hop answer into a coin flip, which is why some runs are right by luck. Accuracy is over 100 seeded runs.

    1. One-shot RAG on the two-hop question. 48% correct at 1.00 search per question. One query brings back at most one person, so the comparison is a coin flip at any noise level.
    2. Switch to iterative search. One query per person gives 75% at 2.00 searches. Nothing checks the results, so 53 distractors went straight into answers.
    3. Evaluator loop at 40% noise, 4 searches, threshold 0.6. 89% at 3.13 searches, against 65% for iterative search at the same noise. The evaluator threw out 103 distractors but also discarded 43 good passages.
    4. Raise the threshold to 0.9. Accuracy falls to 63% and searches climb to 3.99: the evaluator rejects 197 good passages and the budget runs out. At 0.2 it waves distractors through (70%), so the best threshold is in between.
    • Confidence is a noisy signal. The threshold works only as well as the model's confidence tracks what it knows. Confident stale knowledge (an old price, a renamed product) skips search and fails silently.
    • More documents can hurt. In the Lost in the Middle results, the answer was in the retrieved set about 90% of the time at about 50 documents, yet reader accuracy levelled off at roughly 50 to 60% after 10 to 20 documents, and evidence placed mid-context could drop accuracy to the closed-book level (Stanford CS329Z L4). Keep what comes back small.
    • Citations can be invented too. One study of generative search engines found citation precision around 75%, so about one in four citations did not support its claim (L4).
    Go deeper · 8 more notes
    • Quality checks inside the search tool. A cheap retriever (BM25 or a bi-encoder) narrows the corpus to a top-k of 10 to 100, optionally fused across several retrievers, then a cross-encoder reads each query and passage together and reorders them. Before retrieval, the tool can route a query to the right index and expand it with synonyms or sub-queries. Cost depends on what can be precomputed: bi-encoder document vectors and ColBERT's per-token vectors are built offline, while a cross-encoder runs on every query and passage pair, so it only sees the short list.
    • Three ways to build the loop. Self-RAG trains the model to emit reflection tokens that trigger retrieval and critique its output, which needs critique-labeled data. CRAG adds an evaluator to any RAG stack that keeps passages, discards them (then rewrites and searches the web), or does both when unsure. Search-R1 learns when and what to search by reinforcement learning on final-answer reward, and beat no-search reasoning, SFT and standard RAG baselines in its paper.
    • Compounding errors. In a multi-hop chain, a wrong fact at hop 1 becomes the query for hop 2. Critique steps (Demo 5.3) reduce this without removing it, so a final answer should cite the passage behind each hop.
    • Stop rules are harness code. The step budget and loop guard in Demo 5.2 live outside the model, like the middleware in §8. Log the stop reason with every trace: "budget hit" and "loop" are failures to fix, and "enough evidence" is success.
    • Make the search tool hybrid. BM25 finds exact strings such as error codes and product IDs, and dense retrieval finds paraphrases; each misses what the other catches. Run both and merge the lists with reciprocal rank fusion, which sums 1/(k + rank) per list because raw scores from different retrievers are not on the same scale. RRF needs no per-corpus tuning and takes any number of retrievers. Ranking internals are in the companion site Search Basics.
    • Chunks lose their context. For "What was ACME's revenue growth in Q2 2023?", the best chunk may state the figure without naming the company or quarter, so it cannot match. Contextual retrieval has an LLM read the whole document and prepend 50 to 100 tokens of situating context to each chunk, then indexes that for both embeddings and BM25. In Anthropic's own reported results, failed@20 fell from 5.7% to 3.7% with contextual embeddings and to 2.9% with contextual BM25 added. It costs one LLM call per chunk at index time, so a small model is usual. Late chunking fixes the same loss without an LLM: embed the whole document, then split the token embeddings into chunks; it helps most with small chunks.
    • Memory reads are retrieval. An agent loads long-term memory through prompt assembly, store lookups, tool calls or files. A store keyed by namespaces such as (user_id, "memories") can add semantic search, and many product agents let the model grep files. The same three decisions apply.
    • Other failure points. Retrieval can return content the user should not see, sources can conflict, and searched documents can carry injected instructions.
    ■ Takeaway · Next §6

    An agent gains more from deciding when to search, rewriting queries that miss, and checking evidence before it stops than from a bigger index or context window. Next: what an agent should write down so a later run can retrieve it.

    Next: §6 Agent Memory
    §6 · Agent Memory

    Agent memory: working, episodic, semantic, procedural

    A model keeps nothing between calls. Without memory an agent loses procedure (how to launch a job), knowledge (your "ask before deleting" preference) and progress (the goal of a long run). Stored items help only when back in the window as the agent acts. One lab agent wrote a handbook with a lateness policy, then told a worker 45 minutes late "no problem"; the lab says it happened often.

    Kind (CoALA)What it holdsTypical home
    WorkingThe current window: goals, recent turns, tool resultsThe thread's checkpoint
    EpisodicPast runs: trajectories, tool calls, chatsSaved traces, few-shot examples
    SemanticFacts about the user and the worldA profile or store keyed by user
    ProceduralHow to do the task: rules, workflows, skillsAGENTS.md, SKILL.md files, the system prompt

    When the window forgets

    The simplest working memory is a first-in, first-out queue that drops the oldest turn when full. One inbox agent lost its "check and suggest what to archive and delete" instruction when its history was compacted, and began deleting mail; a queue that drops old turns fails the same way. MemGPT adds tiers: evicted turns go to a recall store searched by exact string, and a small working-context block stays pinned.

    DEMO 6.1 The Forgetting Queue
    Pick a memory mode · watch the early instruction survive or vanish
    Mode:
    Last message:

    Cards are messages in the window, numbered by turn; green is the instruction or the pinned block. The bin holds evicted turns (instruction red if lost, green if recall finds it). Illustrative toy model of MemGPT-style tiering (Stanford CS329Z L7).

    8 msgs
    More controls
    40 turns
    turn 2
    How this toy model works

    The window is a first-in, first-out queue of messages. Recall search is exact word match between the last message and the evicted turns, as in MemGPT's recall storage, and costs one tool call. The pinned working-context block takes one window slot. Editing a pinned fact halfway through the run changes the prompt prefix, so it counts one cache invalidation and re-encodes the messages in the window.

    1. Start with Truncate. Window 8, 40 turns, instruction at turn 2. The window holds turns 33-40; the instruction was evicted at turn 10, so the agent deletes mail.
    2. Add recall search. "Archive the old mail for me" shares the word "archive" with the evicted instruction, so one search (1 tool call) brings it back.
    3. Reword the request. "Tidy up my inbox" shares no word with the instruction. The search runs (1 tool call) and misses, so the instruction stays stored but unused.
    4. Pin it and edit a fact. The pinned block costs one slot (the window now holds turns 34-40), and the rule survives any wording. Editing the pinned fact at turn 20 (under More controls) counts 1 cache invalidation: 7 messages re-encoded.

    Tiers that decay

    An always-on agent spreads memory over layers with different costs. A short profile of core facts and a dated log of recent events go into every prompt, a scratchpad holds notes for the task at hand (relevant for 30 to 60 minutes, per a Stanford CS146S talk on always-on agents), and everything else sits in files behind a search tool. In the widget this demo copies, importance scores halve every 3 weeks for events and every week for notes, so old items drop out of the prompt on their own. Core facts do not decay, so they need garbage collection when they go stale.

    DEMO 6.2 Tiered Memory with Decay
    Age the memories · watch cards decay out of the prompt into search
    Ask:
    answer source, week by week · in the prompt · search (+1 call) · stale or obeyed · ◆ Berlin move

    Cards are memories; events and notes show their decayed score. The green outline answers the question, red is stale or obeyed. Illustrative toy model of an always-on agent widget.

    week 0
    More controls
    How this toy model works

    Parameters come from an always-on agent widget: a profile of up to 100 facts in 4,000 characters, a log of the 30 most relevant events, and importance halving every 3 weeks for events and every week for notes. The weekly note half-life is the widget's value; in the CS146S talk, scratchpad notes matter for only about 30 to 60 minutes. Events and notes whose score falls below 2.0 leave the prompt and drop to search, where a memory costs one tool call. The 2.0 cut-off and the guard are toy rules; real injection defenses are not this clean.

    1. Week 0. The March release event scores 6.0 and sits in the log, so the agent answers from the prompt with 0 tool calls. The profile uses 104 of 4,000 characters.
    2. Jump to week 6. Two half-lives later the event scores 1.5, below the 2.0 cut (it left the log at week 5), so it sits in search and costs 1 tool call. The legal note (half-life 1 week) dropped to search at week 2, when its score fell from 2.0 to 1.0.
    3. Ask about the office. The user moved to Berlin in week 4, but the profile still says London: a stale fact in the always-loaded tier. Tick garbage collection and the profile answers Berlin.
    4. Store the injected email, guard off. It scores 5.0, lands in the log and rides along in every prompt, so the agent obeys it. Tick "Treat memories as data" (under More controls) and it is only quoted.

    Where memory lives

    Memory is mostly retrieval, so RAG lessons carry over. Million-token windows do not retire it: long agent runs reach tens to hundreds of millions of tokens (the CS329Z L7 lecturer's estimate), and models still miss single facts in long contexts. The lecturer's advice is to start with files if you can.

    SubstrateHow it worksTrade-off
    Files + grepOne file per memory, folders as hierarchy; the agent runs ls and grepSimplest; latency from many shell calls
    DatabasesVector DB for similarity, SQLite for metadata queries, BM25 for exact termsSame tuning as RAG (§5)
    Knowledge graphA model extracts entities and relations (Zep adds community summaries; Mem0 applies ADD/UPDATE/DELETE/NOOP)Traversal does part of the reasoning; mostly for semantic memory

    Behind search, the next knob is how much to pull back. On the LoCoMo benchmark, retrieving more raised recall but could lower QA accuracy, because the extra context distracts the model. Models also use whatever is in the window, which leads to over-personalization: asked about young voters, a model tied its answer to the user's "small healthy swaps" memory.

    DEMO 6.3 Retrieve More, Answer Worse?
    Slide k · watch off-topic cards pile into the context and the answer slip
    Distraction sensitivity:
    top-k from 1 to 50 · near the best · too few · too many · ◆ best k

    Cards are retrieved memories: green on-topic, red off-topic in the context; the bin holds what the filter removed. Illustrative toy model shaped like LoCoMo (CS329Z L7), not paper numbers.

    k = 10
    30%
    How this toy model works

    Recall(k) = 1 − 0.75k. Accuracy = recall × (1 − sensitivity × distractors / 50), with sensitivity 0.5, 1 or 1.5. The filter drops 3 in 4 distractors and 5% of the gold. The leak line appears at 5 or more distractors in context. In the strip, "near the best" means k within 1.5 times the best k either way. All are toy rules.

    1. Start at k = 10. Recall 94%, accuracy 89%, 3 distractors in context. The peak is k = 13 at 92%, so this is near the sweet spot.
    2. Pull 50. Recall reaches 100%, but 15 distractors ride along and accuracy falls to 70%, 22 pts below the peak. One distractor leaks into the answer.
    3. Turn on the filter. Only 3 distractors survive, accuracy at k = 50 recovers to 89%, and the best k moves from 13 to 26 (93%).
    4. Noisy store, sensitive model. At 60% distractors and high sensitivity, k = 50 scores 10%; the best k shrinks to 8 (79%).

    Learning procedures from experience

    Procedural memory can be learned. Voyager, a Minecraft agent, writes code for a task, refines it from environment feedback, and adds it to a skill library once it works. With the library it reached diamond tools in 102 prompt iterations; without it, only iron tools. Agent Workflow Memory (AWM) induces workflows from successful web-task trajectories and appends them to the system prompt, matching hand-written workflows after about 10 to 15 examples (the lecturer's estimate). Written lessons beat raw logs: in Reflexion's ablation, trajectories plus written reflections did better than trajectories alone. In a production agent the procedural fix is usually small: state the rule more clearly, change the steps, move the behavior into a narrower skill, add an example, or change routing.

    Feedback and the memory loop

    Human feedback is a write path too. When an agent stops for review, an edit or an answered question can become a stored preference, and a thumbs-up can promote the interaction into episodic memory as a few-shot example, so an ambient agent (§10) needs fewer interrupts over time. Around each run the loop is: capture traces, analyze them for patterns, feedback and eval failures, then update the context the next run loads (§13 covers traces). Keep learned instructions and skills in a versioned store you own, apart from app code; an opaque provider-side summary cannot be inspected or migrated. Keep the raw episodic logs too, because distillation is lossy.

    • Two places. Parametric memory lives in the weights; context memory is retrieved into the window. For facts with little training data, use context: putting facts into weights takes thousands of documents and is lossy.
    • Traces are evidence. A log becomes memory only when its lesson is written where a future run will load it. Most trace data should stay history, or become an eval or a code fix.
    • When to write. In the hot path the agent saves with a tool call before replying: immediate, but slower and tangled with agent logic. In the background a worker writes later: no latency, but stale for a while and in need of a trigger policy. Also choose scope (agent, user, org) and trigger (an explicit "remember this" or implicit).
    • Episodic vs semantic. Past trajectories as few-shot examples help when there is a correct procedure. Extracted facts help when tasks are new or personal.
    • Start simple. On MemoryArena's group travel planning task, dedicated memory agents such as Mem0 scored below long-context and RAG baselines, so begin with files and grep.
    • Memories are data. Stored text is information, never instructions. The risks are poisoning (harmless-looking triggers that pull back injected procedures), privacy leaks (a weekly report that mentions lunch with a competitor's recruiter) and over-personalization. Protect memory-shaped behavior with regression evals.
    Go deeper · 11 more notes
    • Choosing what to remember. It depends on the application: a coding agent might keep the libraries a user prefers, a research agent the industries a user tracks. Decide that, and which feedback channel the interface offers, before picking a store. Semantic memory in most products today is three steps: a model extracts facts from the conversation, a per-user store keeps them, and later prompts inject them for personalization.
    • MemGPT's third tier. An archival tier keeps long-term facts in a vector store the agent pages through, and the agent edits its pinned working-context block with tools. In the MemGPT paper, accuracy stayed flat as the number of retrieved documents grew, while plain RAG got worse.
    • Skill libraries. Each Voyager skill is keyed by an embedding of its model-written description; exact duplicate names are blocked, but near-duplicates pile up and can pull back the wrong skill. AWM has no lookup step, so it would not scale to very long runs.
    • Reflection. Generative Agents write reflections back into the memory stream and rank memories by a combined score of recency, importance and relevance; removing reflection made the simulation less realistic.
    • A worked feedback loop. In LangSmith Engine, the Agent Overview (a file like AGENTS.md) starts from onboarding answers plus the first run, then updates a User Preferences section when a team resolves or closes an issue or creates an evaluator (vendor description, no metrics). LangChain's memory posts, which pitch its own products, report no measurements.
    • Keep or forget. An update can keep what worked, such as a preference or a good example, as well as fix what failed. You cannot know at write time what will matter. Keeping everything costs retrieval, context and upkeep, and forgetting can throw away evidence: is "no meetings before 10 unless there are pastries" a preference or a joke?
    • Two more patterns. Tiered hierarchies beyond MemGPT: MemoryOS promotes memories by access frequency, and a background workflow places them instead of the model. Maintenance: Sleep-Time Compute, A-Mem, and Mem0's ADD/UPDATE/DELETE/NOOP updates. Learned skills go stale when the environment changes, and Voyager and AWM have no fix for that.
    • Runtime view. In a checkpointed runtime, short-term memory is the thread's checkpoint (scoped to a thread id) and long-term memory is a namespaced store, such as one keyed by (user_id, "memories").
    • Refresh paths. If the runtime caches prompts, tools or skills, a memory commit needs a way to reach the next run, or the right update is stored while the agent keeps running on stale context. Editing an in-prompt block also breaks the KV cache, as Demo 6.1 counts.
    • What counts as procedural. A 2024 LangChain post defines it as weights plus code, rarely updated. The lectures and a 2026 LangChain post treat instructions and skill files as procedural memory, and the 2026 post's (unmeasured) view is that procedural fixes drive many of the most visible improvements.
    • Sleep-time compute. Consolidating memory while idle (Chad likes blue, then red more, then gray most, becomes one ranked list) buys snappier answers on a smaller test-time budget. Offline reasoning on questions nobody asks is wasted.
    ■ Takeaway · Next §7

    Memory is retrieval plus maintenance: design for the moment of use, expire what goes stale, and treat what you remember as data. Next, the tools an agent uses to act on what it knows.

    Next: §7 Tools, MCP & Code
    Part 3 Building the Harness Tools, middleware, durable runtimes, and agents that run all day.
    §7 · Action Spaces

    Action spaces: function calling, MCP, code, and the capability ladder

    A model can only write text. A tool is a function interface written as text: the model writes a name and arguments, and another program runs the call. Because the call is generated, models can invent APIs, parameters and versions (Stanford CS329Z L4), and generated calls are not type-safe, so validate them before running them. How you format the action space and the order in which you try tools matter as much as which tools you offer.

    From text to a call that always parses

    A tool call has five stages: select a tool from the schemas in context, fill its arguments, validate them, execute (usually in a sandbox), and return the result. Constrained decoding validates while the model writes: SGLang compiles the output format into a finite-state machine that forces braces, keys and quotes, calls the model only where the next token is open, and masks an enum slot to the legal options.

    DEMO 7.1 Constrained Decoding FSM
    Pick a schema, flip constrained on · watch model calls and parse rate
    Schema
    Decoding
    token stream · who writes each token
    100 seeded runs · click a square to see where it broke
    5%

    Each chip is one output token; each square is one run. Illustrative toy model of SGLang's state machine (Stanford CS329Z L2).

    How this toy model works

    When unconstrained, each structural token (including the enum value) independently goes off-format at the slider's rate, and every token costs a model call. The 100 runs use a fixed seed. Free text inside strings, including where a string ends, always needs the model.

    1. Start unconstrained. The name, email and intent signature is 21 tokens, each a model call. At a 5% slip rate per structural token, 45 of 100 runs fail to parse (expected parse rate 0.95 to the 13th power, about 51%).
    2. Turn constrained decoding on. All 100 runs parse. Only 9 of the 21 tokens need the model; the state machine writes the other 12, which is also why constrained decoding runs faster.
    3. Pick the tool enum. Now 4 of 12 tokens need the model, and the tool name is one masked choice among 3 (calculator, search, bash), so the model cannot name a tool that does not exist.

    Which format should an action take?

    Interfaces moved from REST endpoints documented for humans, to function calling with JSON schemas for models (around 2023), to MCP, one protocol any host can use to discover and call any server's tools. The format of the action matters too. In CodeAct the agent writes a program that calls tools as functions, loops and uses builtins like min, for example to find the cheapest country to buy a phone. Plan-then-execute (ReWOO, LLMCompiler) writes the whole plan up front and runs it without the model in the loop.

    DEMO 7.2 ReAct vs CodeAct vs Plan-then-Execute
    Pick a strategy, raise tool failures · watch turns, tokens and the answer
    Strategy
    same task, four strategies · click a lane or use arrow keys to select it
    LLM turns17selected strategy
    Tokens read89,080all turns
    Latency50 stoy timings
    0%
    4
    trajectory of the selected strategy · badge = tokens the turn reads
    More controls
    4
    500

    Each lane is one strategy's run in toy seconds; its label counts model turns and tokens read. Illustrative cost model after Stanford CS329Z L6.

    How this toy model works

    Assumptions: 600-token base prompt, 80 tokens of thought per ReAct turn, 2 s per LLM turn, 1 s per tool call. Failed calls succeed on retry, and the same seeded calls fail for every strategy. A CodeAct crash costs one rewrite turn, and LLMCompiler's replan is one extra turn. In the real LLMCompiler a verifier failure triggers a fresh plan; the toy simplifies this to rerunning only the failed calls.

    1. Start with ReAct. 4 countries times 4 lookups is 16 calls, one per turn, plus a final answer: 17 turns. Each turn rereads the growing history, so the run reads 89,080 tokens and takes 50 s.
    2. Click CodeAct. One program runs all 16 lookups and prints only the results: 2 turns, 98% fewer context tokens (1,500), and 20 s.
    3. Set failures to 30% and pick ReWOO. 7 of the 16 calls fail on the first try. ReWOO still uses 2 turns, but the 7 failed lookups flow into the answer: a fixed plan cannot adapt. ReAct adapts turn by turn, at 24 turns.
    4. Switch to LLMCompiler. It runs the 4 countries in parallel, and its verifier replans around the failed calls (the toy reruns just those 7). Correct answer in 3 turns and 11 s, against 20 s for ReWOO and 71 s for ReAct.

    Try the cheapest capability first

    Not every task has an API. An always-on agent climbs a ladder: what it already knows, an app connector (API or MCP), web search, a signed-in browser, full desktop control, and only then you, for logins, 2FA codes and payments.

    DEMO 7.3 Climb the Ladder Before You Bug the User
    Pick a task, break the connector · watch where tasks resolve and how often you are asked
    Task
    the ladder · tasks resolved per rung, of those that reach it
    how a typical task climbs
    Without you99.7%resolved on rungs 1 to 5
    Interruptions0.3per 100 tasks
    Total cost237machine + attention
    20
    More controls
    More tasks
    5%
    95%
    0%
    80%
    70%

    Green path: rungs the 100 tasks reach; dashed edge: ask first. Notes give tasks resolved of tasks reaching that rung. Illustrative toy model of the cheapest-first ladder from the always-on agents talk.

    How this toy model works

    The five tasks come from the author's always-on note. Success rates and costs (memory 1, connector 1, web 2, browser 4, desktop 8 units per attempt) are made-up toy values. Each rung is an independent try, asking you always works, and results are expected values per 100 tasks. Total cost is machine cost plus the interruption weight times the number of interruptions.

    1. Start with "Unpaid invoices?". Memory answers 5 of 100, the connector 90.3 more. 99.7% resolve without you, 0.3 interruptions per 100 tasks, total cost 237.
    2. Break the connector. Flow falls through web search to the browser (76 tasks) and the desktop (13.3). Still 94.3% without you, but 5.7 interruptions and a total cost of 1,031.
    3. Pick the bank portal. No API and nothing public, so the signed-in browser does the work (85 tasks). 95.5% without you, 4.5 interruptions, cost 1,010.
    4. Tick "Ask first". Machine cost drops to 0, but 100 interruptions at weight 20 cost 2,000, against 237 for the ladder on the same task.
    • MCP standardizes discovery. The host opens one client per server, lists tools with tools/list (name, description, input schema) and calls them with tools/call. The server can gate access and keep the API token, so the agent never sees it.
    • Descriptions are routing logic. In one eval-driven-development example, a create_ticket description covering "VPN and laptop issues" filed tickets for VPN how-to questions. Narrowing it to requests that need IT to act fixed the misroutes.
    • Code is often the better action. CodeAct had higher success and fewer turns than JSON or text actions in the lecture's comparison, across the models tested (one older model, text-davinci-003, may have needed fewer turns with JSON).
    Go deeper · 12 more notes
    • Bash as the universal tool. Bash is the extreme case of code as action: text in, text out, able to stand in for most other tools. The Pi harness ships four default tools (read, write, edit, bash).
    • Sandboxes. A sandbox adds an execute tool, but it protects the host, not the sandbox: assume prompt injection controls what runs inside, and keep credentials out with an auth proxy.
    • Is hallucination solved? The talk on always-on agents calls invented APIs "mostly" solved. That is the speaker's opinion; the talk gives no measurement.
    • Fewer calls, in parallel. A good trajectory makes the fewest calls it needs and runs independent ones in parallel. LLMCompiler and parallel tool calling exist to do this.
    • Views of a web page. On a web page, the accessibility tree saves tokens compared with HTML or screenshots. Raw pixel clicks are the fallback when none of those works.
    • Weights gave way to descriptions. Toolformer and ToolkenGPT trained tool use into the model, so every new API meant retraining. ToolkenGPT also showed how hard chaining is: about 0.5 to 0.7 on one-hop tool use, about 0.03 to 0.09 on multi-hop. The lecture gives two reasons: the number of possible tool sequences grows combinatorially with length, and multi-step sequences are rare in training data. Planning and training on agent traces try to close that gap. Runtime descriptions (function schemas, MCP) scale better.
    • Hallucination or error? Gorilla parses a generated call into a syntax tree and checks it against real APIs. No match means a hallucinated API; a match with a wrong node is an ordinary error. Its training matters as much as its check. A model fine-tuned only with correct docs in the prompt learns to copy whatever doc it gets, so one wrong retrieved doc yields a wrong call. Gorilla mixes correct and incorrect retrieved docs during fine-tuning (about 1,600 ML APIs) so the model learns to judge them. The motivating failure: GPT-4 invented Torch Hub parameters, such as an "asr" model and source="local". Tool docs fetched at runtime can be wrong too.
    • Agents behind protocols too. In LangChain's runtime post, a deployed agent exposes its own MCP endpoint and can call MCP servers, while A2A and webhooks connect it to other agents and systems.
    • One general CLI. LangChain's trace-mining agent works mostly through one general CLI instead of many custom tools, so a coding agent can reproduce its actions outside it. The always-on agents talk adds a rule of thumb: if the model spends about 90% of its time on one shell pattern, promote that pattern to a dedicated tool. Write actionable error messages for agents as you would for people.
    • Keep the menu small. Tool search puts only tool names in the prompt and loads a full schema on demand. Skills work the same way, but differ: a tool acts on the environment and returns an observation, while a skill file loads instructions or code into context. One client tool, send_user, can carry everything to the user, and each client renders it its own way (an approval draft, a sign-in form, an emoji).
    • Skip generation for a fixed menu. When the set of actions is small and fixed, a classifier head on the model, or the best dot product between an embedded state and each embedded action, returns a valid choice in one pass (Stanford CS329Z L2).
    • Typed contracts. DSPy signatures declare typed inputs and outputs and generate the prompt. The model sees only the field names, types, descriptions and the class docstring (which becomes the system prompt), so a field you did not declare cannot come back. Types also fix drift: plain strings returned both "positive" and "Negative", while Literal['positive','negative','neutral'] forces one label set. The adapter is deterministic code, not an LLM call: it renders the prompt, parses and validates the reply, falls back from the Chat adapter to JSON, and raises an error if neither parses. Constrained decoding is the decoding-time version of the same contract.
    ■ Takeaway · Next §8

    A few well-described tools plus code execution, tried cheapest first, beat a large menu of JSON calls. Next, the harness around those tools: middleware, safety rails and the loop that runs them.

    Next: §8 Harness Engineering
    §8 · Harness Engineering

    Harness engineering: middleware, reasoning sandwiches, safety rails

    The harness is everything except the model and the environment: the prompt, the tools, how context is kept, how tools run, and the code wrapped around every call. It is also the part you can change this afternoon. LangChain kept gpt-5.2-codex fixed, changed only the prompt, tools and middleware of its deepagents-cli, and reports a move from 52.8% to 66.5% on Terminal-Bench 2.0 (89 tasks). That gain is self-reported and was tuned on the tasks it was scored on, yet the lectures agree: the same model scores differently in different harnesses (Stanford CS329Z L2, L5).

    A harness is a bundle of trade-offs

    Mini SWE-Agent exposes only bash, keeps one linear history and runs each command in a fresh subprocess. OpenHands rebuilds context from stored events and keeps a persistent terminal. Pi ships four tools, keeps history as a tree you can roll back, and has no permission checks. OpenClaw runs as one long-lived process that wakes itself up. The right one depends on task length, model strength and how much control the user needs.

    DEMO 8.1 Harness Design Board
    Pick a preset, stretch the task · watch which design choice becomes the limit
    Presets:
    What the model reads at step 10 of 10
    Every step of the task · under or over the 64k toy budget
    Same model, five harnesses (toy)

      Illustrative toy model, not a benchmark. Grey: system prompt; blue: tool definitions; amber: one block per step of history; hatched: past the 64k toy budget.

      10 steps
      More controls
      Context:
      Shell:
      1
      How this toy model works

      Per-step error rises with context past a 64k toy budget, with tool count (selection errors) and with too few tools (improvising through bash). Preset traits come from Stanford CS329Z L5. Pi's shell mode, OpenClaw's context and shell modes, the tool counts for OpenHands and OpenClaw, and every coefficient are toy choices.

      1. Start with Mini SWE-Agent on a 10-step task. Bash only, linear history: 90% success for 120k tokens, and the four presets sit within 88% to 91%. On short tasks a minimal harness is fine.
      2. Stretch the task to 80 steps. The linear history crosses the 64k budget at step 41 (the strip turns coral there) and peaks at 124k, spilling into the hatched zone. Success falls to 24%, the lowest of the four presets (24% to 45%).
      3. Keep bash only, switch context to event-rebuilt. Only the last 20 steps are rebuilt into the window and the other 60 wait in the event store. Peak context is 34k and success recovers to 43% on 2,419k tokens, less than half the tokens. The lecture describes this design, not its score; the recovery is the toy's assumption.
      4. Now expose 10 tools. Success drops to 28%: every step pays a selection cost. This is the "harness tax" direction from L2, where four-tool Pi beat larger harnesses for most models tested.

      Spend reasoning where it pays

      Reasoning effort is a harness setting too. gpt-5.2-codex has four modes (low, medium, high, xhigh), and more reasoning can cost over twice the tokens and time. Under Terminal-Bench's hard timeouts LangChain reports 53.9% with xhigh everywhere, 63.6% with high everywhere, and 66.5% for a "sandwich": xhigh to plan, high to build, xhigh to verify. Other splits scored about the same, so treat the exact split as a heuristic.

      DEMO 8.2 Reasoning Sandwich
      Pick an effort mix, move the timeout · watch timeouts trade against wrong plans and missed bugs
      Presets:
      89 toy tasks · click a square to inspect it
      the inspected task, phase by phase
      a typical hard task: plan, implement, verify vs. timeout

      Illustrative toy model of 89 seeded tasks, not a reproduction. Darker phase blocks run at xhigh. A task still running at the timeout is killed.

      Reported · all xhigh 53.9% Timeouts drag it down
      Reported · all high 63.6% Same benchmark
      Reported · sandwich 66.5% Final tuned harness

      Reference strip: LangChain, self-reported, gpt-5.2-codex on Terminal-Bench 2.0. Not produced by this toy.

      58 min
      50%
      More controls
      high
      high
      high
      #1
      How this toy model works

      xhigh takes 2.1× the time of high. Plan effort raises the chance the plan is right (more on hard tasks), implement effort slightly lowers the bug rate, and verify effort raises the chance a bug is caught and fixed. A task that runs past the timeout fails. The coefficients were picked so the three presets land in the post's order at the default settings. The reported strip has no trial counts, and the post does not say which harness stage ran the two single-mode scores.

      1. Start at all high. 58 of 89 pass (65%) with 0 timeouts. The losses are quality: 15 wrong plans and 16 bugs that shipped uncaught. Task #1 is one of them: implement adds a bug and verify misses it.
      2. Click all xhigh. Plans and checks improve, but 41 tasks time out and the score drops to 46%. Task #1 runs out of time partway through verify and is killed (it needed 86.3 min). In the timeline, a typical hard task takes 60 toy minutes, past the 58-minute line.
      3. Click the sandwich. Implementation drops back to high, so only 13 tasks time out, while planning and verification stay careful: 62 pass (70%), the best of the three. Task #1 catches and fixes its bug and passes at 57.6 min. That matches the post's order, which the toy was tuned to show.
      4. Loosen the timeout to 120 with all xhigh. Nothing times out and max effort wins at 82% (the sandwich gets 81%), so the sandwich helps only when time is tight. This is the toy's assumption: the post only tested under the benchmark's timeouts.

      Put rails in code

      LangChain credits middleware, hooks that run around every model and tool call: a plan, build, verify, fix procedure in the prompt; a pre-completion checklist that forces a verification pass at exit; a start-up hook that maps the directory and installed tools; a note that tests will grade the work; time-budget warnings; and a loop detector. The loop detector targets the doom loop, where an agent retries small variations of one broken approach, more than 10 times in some traces. It counts edits per file and, after N edits, adds a note asking the agent to reconsider. The post does not give N, and admits the nudge can fail when the model believes it is right.

      DEMO 8.3 Doom-Loop Detector
      Move the threshold N · watch stuck rows recover and correct rows derail
      24 toy tasks · click a row
      the middleware around every tool call
      the selected task, step by step

      Illustrative toy model of 24 seeded tasks. One tick per edit: coral broken, green correct, amber flag nudge, blue outline re-plan. Coral row number: stuck start.

      5 edits
      70%
      More controls
      30%
      4 edits
      30 steps
      #2
      How this toy model works

      A broken approach never passes; a correct one needs about the set number of edits (±1). A followed nudge costs 2 re-plan steps and lands on a correct approach 60% of the time. Derailing correct work when N is too low is the toy's assumption; the post reports no such data.

      1. Turn the detector off. 7 of the 24 tasks start on a broken approach and edit the same file 30 times, until the budget runs out. 17 solved, and 210 steps go to tasks that never finish. Task #2's trace is one long run of failed edits.
      2. Turn it on with N = 5. Amber flags appear after the fifth edit. In task #2 the hook fires at edit 5, the model re-plans for 2 steps and solves it in 10. 5 of 7 stuck tasks recover, no correct task is touched, and 22 of 24 are solved.
      3. Drop N to 2. The nudge now fires before correct work can finish. 14 correct tasks abandon a good approach, and only 13 are solved (task #2 is nudged 4 times and drops a working approach twice), fewer than the 17 with no detector.
      4. Back to N = 5, compliance 10%. Only 2 of 7 stuck tasks recover (19 solved). A hook can add a message; it cannot force a change of mind.
      • Same model, different scores. Tools, context strategy, shell state and user control all move results. Strong models do well with simple harnesses and weaker ones need more help, so re-fit the harness with each model generation.
      • Deterministic rails. Anything that must happen every time goes in middleware: PII redaction before each model call, a cap on calls to a paid API, retries, model fallback, timeouts and budgets. Return failed tool calls to the model as observations so it can retry, within limits. A guardrail holds only if it also runs on resumes, retries and background runs.
      • Force verification. LangChain's most common failure was "looks fine, done": the agent re-read its own code and stopped. A pre-completion hook plus tests checked against the spec turns that into a verify step. Code injects the check at exit, like a Ralph loop (§1) aimed at verification, so it does not depend on the model following the prompt.
      • Ask before acting. Operator, asked to order groceries, searched stores in Iowa without asking where the user lived (L1). For under-specified tasks, require a clarification turn before the first irreversible step, and put vague requests in your evals.
      • Safety is a harness property. Pi has no permission checks; MCP servers gate access; harness audits score safety well below task completion; harmless blank pop-ups derailed agents 87% of the time in one study (L1). Treat retrieved pages, emails and webhooks as untrusted, require approval for irreversible sends, and keep passwords out of the conversation.
      • Guardrails are temporary. LangChain calls loop detection, forced verification and time warnings workarounds for today's models and expects to drop them. Plan to delete harness code as models improve.
      Go deeper · 9 more notes
      • The four harnesses in more detail. Mini SWE-Agent's fresh subprocess per command makes sandbox resets easy for evals. OpenHands stores each step as an event. OpenClaw wakes every 30 minutes, builds its identity from markdown files and stores memories nightly.
      • Grading and time notes. The grading note says programmatic tests will score the agent, so it should match the spec's file paths and interfaces exactly, write happy-path and edge-case tests when none exist, and read the full test output. Time warnings tell it to switch from building to verifying before the timeout, since agents estimate time poorly and ignore limits nobody told them about.
      • Other ways to split reasoning. Besides the hand-set sandwich, the post names adaptive reasoning (the model picks the effort per step) and a multi-model harness (a large model plans, a smaller one implements).
      • Middleware details. Hooks attach at fixed points (before_model, wrap_model_call, wrap_tool_call, after_model). A confused model might call a paid API about 50 times, so the cap lives in code. Claude Code returns tool and code errors to the model as observations, with retry limits and budgets. Redacting PII before the model call also keeps it out of traces.
      • Where the lines are. LangChain separates the harness (code, prompt and tools every instance ships with) from context (instructions, skills and memory layered on as configuration), and from the runtime underneath (durable execution, memory, tenancy, observability: §9).
      • Read the 66.5% carefully. One vendor's score on the same 89 tasks that drove the tuning, with no holdout, no per-change ablation and no variance. Claude Opus 4.6 scored 59.6% on an earlier harness not tuned for it, which argues for tuning per model and says little about which model is better.
      • Meta-agents as rails. Shepherd (research) watches a task agent, intercepts buggy tool calls and forks retries, and scores better on coding benchmarks than running without it (no numbers in L5). One product team has a separate model review every command; the speaker says it beats tired human approvers but shows no data.
      • Review gates with three answers. For risky actions, an ambient agent proposes and the human can approve, edit or send feedback. When information is missing, "ask, don't guess" turns a confident error into a blocking question.
      • Show me the prompt. Abstractions hide what you need to debug: see the exact prompt, tool calls and context the harness builds, and control which steps run in what order (L5). LangChain's "open harness" pitch says the same from a vendor's side. Avoid hidden prompts and fixed cognitive architectures. A framework is a dependency: if the system must last five or ten years, ask whether the library will still be maintained (L5). Start simple, justify each piece, and prefer opt-in primitives that read like plain code, with the runtime separate from the authoring API. LangChain calls harnesses amplifiers of the model and expects some scaffolding to become unnecessary (a vendor forecast), so re-check it when a new model ships. Also plan for injection through retrieved content, memory poisoning and privacy leaks.
      ■ Takeaway · Next §9

      Most of what you can improve, and most of your safety debt, sits in the harness: tune it per model, put must-run policies in code, and expect to delete parts as models improve. Next, the runtime underneath keeps those loops alive through crashes, pauses and deploys.

      Next: §9 Durable Runtimes
      §9 · Durable Runtimes

      Production runtimes: durable execution, checkpoints, and resume

      Web backends assume short requests that keep no state and arrive at a steady rate. Agents break all three: a run lasts minutes or hours, carries state across dozens of model and tool calls, and traffic comes in bursts. On a request-scoped function, a timeout, a crash, or a human who takes an hour to reply throws the work away. The runtime, the layer under the harness, keeps the loop alive: background execution, heartbeats, saved state, resumable runs, queues that give each run to exactly one worker, and streaming. Short single-prompt agents need little of this.

      Write the agent as a state machine

      LangGraph models a program as shared state plus nodes: each node returns only the fields it changed, and a router picks the next node. Temporal adds recovery: workers run activities that can fail, and the server keeps the execution history, so a failed activity is retried instead of killing the run (Stanford CS329Z L5). A plain while loop works, but you cannot checkpoint it mid-run or resume it on another machine. Named steps give the runtime places to save state, pause for a human, stream and trace.

      DEMO 9.1 Build the State Graph
      Make pick_emoji flaky · toggle durable execution · watch 200 runs live or die
      Email:
      the graph · path taken · failed node · flag = checkpoint saved
      200 seeded runs · click a square to inspect and replay it

      Each square is one seeded run, colored by outcome (key under the grid); dots beside pick_emoji are its attempts. Illustrative model of the CS329Z L5 notebook demo.

      50%
      3
      More controls
      #2
      event history · what the runtime recorded
      shared state after the run
      How this toy model works

      Each pick_emoji attempt fails independently with the chosen probability. With durable execution on, a failed attempt is retried up to the retry limit, with a made-up backoff of 1 s, 2 s, 4 s and so on. With it off, the first failure crashes the run. The 200 runs use fixed seeds, so the same settings always give the same grid.

      1. Start: 50% failure, 3 retries, durable on. Completed 187/200: 99 runs pass on the first try and retries save 88. Run #2 fails twice, waits 1 s and 2 s, then succeeds on attempt 3. Only 13 runs fail all four attempts.
      2. Turn durable execution off. Completed drops to 99/200 and 101 runs crash at pick_emoji, run #2 among them. A trace would show each crash, but nothing recovers it.
      3. Durable on, failure 80%, retry limit 5. Retries save 122 runs, yet 45 still fail (155/200). Retries handle flaky failures; they can't fix a dependency that is mostly down.
      4. Switch to the newsletter. The router finds no date or time and takes the dashed edge to END: 200/200, and pick_emoji never runs. The routing is plain code over shared state.

      Durable is not the same as safe

      A runtime records each step after it finishes. If the process dies after a side effect but before the record is written, the runtime can't know the effect happened. A job queue replays the whole turn and repeats every earlier side effect. A durable workflow resumes at the crashed step, so it repeats only that one. To remove the last duplicate, make the step idempotent: send a key so a second "hold seat" or "charge card" call with the same key does nothing.

      DEMO 9.2 Crash the Booking
      Pick where the worker dies · switch recovery · watch the inbox for a second email
      what really happened in the world

      Left: the attempt that crashed. Right: the recovery. Bottom: how many times each side effect really happened. Illustrative toy model of a booking widget in an always-on agents explainer.

      Steps redone3finished steps run again
      Doubled effects2side effects done twice
      4 · email itinerary
      Crash lands:
      Recovery:
      How this toy model works

      Five steps; three have a side effect (seat, email, charge). A job queue replays the turn from step 1. A durable workflow resumes at the crashed step. An idempotent step that repeats with the same key does nothing. The explainer's own numbers are illustrative; the crash-at-step-4 case reproduces them: 3 redone and 2 doubled, then 0 and 1, then 0 and 0.

      1. Start: crash in step 4, after the email went out, job queue. The queue replays the turn: 3 finished steps redone and 2 side effects doubled. The seat is held twice and the user gets two emails.
      2. Click "Durable workflow". Steps 1 to 3 come from the recorded history: 0 redone. Step 4 runs again, so 1 side effect is doubled: the email.
      3. Check "Idempotent steps". The repeated email carries the same key and is deduped: 0 redone, 0 doubled. You need both durability and idempotency.
      4. Crash before the side effect, job queue, idempotent on. No duplicates, but the verdict reads "Safe but wasteful: 3 steps redone". Idempotency prevents duplicate effects; durability prevents redone work.

      Retry from where?

      Ordinary services retry a failed request from the top. For an agent that is the wrong choice: if each step fails with probability f, a run of S steps finishes cleanly with probability (1 − f) to the power S, so restarting makes the expected work grow exponentially with S. Resuming from the last checkpoint redoes only the failed step. The same checkpoint makes human approval cheap: the run pauses, the worker is freed, and the person can answer in 30 seconds or 3 days.

      Expected step executions to finish S steps
      $$P(\text{clean run}) = (1-f)^{S} \qquad \mathbb{E}_{\text{restart}} = \frac{(1-f)^{-S}-1}{f} \qquad \mathbb{E}_{\text{resume}} = \frac{S}{1-f}$$
      f = 5%, S = 30clean run ≈ 21%restart ≈ 73.2 step runsresume ≈ 31.6 step runs
      DEMO 9.3 Retry From Where?
      Lengthen the run · add a human wait · see where each runtime picks up again
      Runtime:
      Run #1 of 100, same luck in every runtime · lane totals are for all 100 runs

      Each lane is the same seeded run under one runtime, drawn in worker time; click a lane to select it. Illustrative toy cost model, not a benchmark.

      30
      More controls
      5%
      10 s
      15 min
      50 ms
      #1
      How this toy model works

      100 seeded runs. A checkpoint write or load costs 0.2 s. Restart gives up after 10 whole attempts; checkpoint and replay give up after 10 tries of one step. A resume in replay mode re-reads one event per finished step, at the chosen cost per event. The human wait costs no worker time once the run is paused durably, but a serverless request must survive it inside its timeout.

      1. Short and reliable: 5 steps of 2 s, 0% failure, 60 s timeout (the last three are under More controls). Serverless finishes 100/100, like every other mode, and all four lanes look the same. The checkpoint and replay totals are slightly higher: writes cost 10% more worker time when nothing fails.
      2. Check the 1 h human approval. Serverless falls to 0/100: no request survives a 1 h wait under a 60 s timeout. The three background modes still finish 100/100.
      3. 30 steps, 5% failure, restart from scratch. Only 17 of 100 runs finish on the first try (the formula expects about 21), 83/100 finish within 10 attempts, and 67% of the 20.8 h of worker time was redone. Resume latest checkpoint finishes 100/100 in 9.0 h, 2.3× less.
      4. 60 steps, replay at 500 ms per event. Restart now finishes 23/100. Replay finishes 100/100, but its worst resume re-read 29.5 s of history, longer than one 10 s step: 19.3 h against 17.9 h for checkpoint resume.

      Stream progress while the run works

      Parallel steps cut actual latency; streaming cuts perceived latency, so the user reads early output instead of watching a spinner. Stream tokens for a chatbot and per-step updates for a long-running agent. Each chunk names the node or tool that produced it, so the stream is also a live debugging feed (§13). If the client disconnects, it reconnects with the Last-Event-ID header and the server replays the events it missed.

      Many users, one runtime

      A deployed agent has three separate tenancy layers. Isolate users: an authentication handler attaches an identity to every request, and authorization handlers tag each thread with its owner and filter every read by it. Skip this and one user's threads, memory and traces can show up for another. Act for users in third-party services: the runtime runs the OAuth flow and refreshes tokens, so the agent calls with the user's own scoped credentials and no secret goes into the prompt. Control your own team with role-based access to deploy, change configuration and auth, and view traces.

      • Checkpoint every step. LangGraph writes a checkpoint after each super-step, keyed by a thread_id. If a worker dies, its lease on the run is released and another worker resumes from the latest checkpoint.
      • Make side effects idempotent. Durability decides where a run resumes; idempotency decides whether the resumed step can safely repeat its effect. Seats, emails and payments need keys.
      • Pause, don't block. interrupt() saves a checkpoint and frees the worker, and Command(resume=…) continues later with the human's answer. A blocked process can't wait three days or survive a deploy.
      • Declare a double-texting policy. When a second message lands mid-run, pick one: enqueue (the default and safest), reject, interrupt (keeps progress, but half-finished tool calls need cleanup), or rollback (discard and restart with the new message).
      • Queues absorb bursts. A task queue holds incoming runs, workers scale out, and each run is processed exactly once. A run picked up by two workers repeats its side effects, the ×2 badges in Demo 9.2.
      Go deeper · 13 more notes
      • Problems and features. LangChain's post on designing LangGraph (2025, the vendor's own framing) maps each runtime feature to a property of agents. High latency: run independent steps in parallel (lower actual latency) and stream (lower perceived latency). Long runs fail: a task queue with runs detached from the request (fewer retries). Retries are costly: checkpoint after every step, so a retry resumes. Non-deterministic output: human-in-the-loop (people approve, edit or clarify before a step lands) and tracing (you see what the agent and its users did). The runtime itself must add little latency, or it worsens the first problem.
      • Recovery, not just visibility. Observability tools show you a failure. A durable runtime also recovers from it (CS329Z L5). A generator can pause like a state machine, but its state cannot be serialized and picked up later by a different process.
      • Deterministic parallel steps. Under LangGraph's graph API is a Pregel/BSP loop: each super-step runs the triggered nodes in parallel on isolated copies of state, then applies their writes in a fixed order. Node timing never changes the output, so any variability comes from the model. LangGraph's authors report that an early version with no fixed execution algorithm gave different results from the same input when nodes ran concurrently. A step limit stops runaway loops.
      • Retry policies. Per-node retry policies set backoff, max attempts and which errors retry.
      • Replay vs latest checkpoint. Temporal rebuilds a workflow from its stored history. LangGraph's authors argue history-replay engines slow down as history grows, and say their runtime loads only the latest checkpoint, constant in history length. That is the vendor's own characterization and is not benchmarked; Demo 9.3's replay mode is a toy of the argument. A checkpoint stays small and portable because it holds only serialized channel values, their versions, and the versions each node has last seen: enough to resume on any machine with no live process.
      • Why not Airflow or Temporal. DAG schedulers such as Airflow order steps by topological sort, which cannot express a loop, and agent graphs loop. LangChain judged durable-execution engines such as Temporal closer, but says they lacked streaming, added latency between steps that a chat user notices, and slowed as step history grew. That is a competitor's view, not a benchmark.
      • Interrupt details. Unlike a static breakpoint before or after a node, interrupt() is a call you can make anywhere and under a condition, so put it inside the risky tool and every caller gets the approval gate. The resume value becomes the return value of interrupt(): an approval, an edited email draft, or the answer to a clarifying question such as "staging or production?". Parallel branches that interrupt together are surfaced together and can be resumed at once or one by one. While the run is paused you can inspect and edit its state (messages, tool outputs, intermediate results) before resuming.
      • Choosing a double-texting policy. Choose by what the second message does: if it builds on the first, interrupt and clean up any dangling tool call; if it replaces the first, roll back; if correctness matters more than latency, enqueue.
      • Stream modes and thread streams. Runtimes offer several stream modes, which can be combined: the full state after each step (values), only the fields a step changed (updates), model tokens as they arrive, custom events your code emits from any node, and generative UI that renders components as output arrives. Chunks carry metadata naming the node, subgraph or tool. A run stream ends with its run; a thread stream stays open and carries every run on the thread: follow-up messages, background runs, and the resume after a human approval.
      • Where bursts come from. Spikes come from many users arriving at once and from scheduled jobs, such as an end-of-day research run for a whole team, that fan out together. Without a buffer the excess requests are dropped.
      • Two kinds of heartbeat. In this chapter a heartbeat is a liveness signal: a long run reports that it is still making progress, so the platform does not kill a long but healthy run as hung. The heartbeat in §10 is different: a scheduled wake-up that starts a new turn.
      • Event logs, forks and a real queue policy. OpenHands keeps an append-only event log and rebuilds each model input from it (CS329Z L6). Time travel forks a thread from any earlier checkpoint, optionally with edited state, and re-executes the real model and tool calls, while the original branch stays intact. In a Stanford CS146S talk on always-on agents, every turn and every helper sub-agent runs as its own Temporal workflow. The owner's direct message interrupts the running loop, other messages join the back of the queue, bursts of 3 or 4 quick messages become one turn, and clients dedupe retries so nothing shows twice.
      • Horizons keep growing. Model task horizons, measured in human time, keep rising (CS329Z L5, L10). The same speaker says his agents run a few hours to a day today and predicts runs of weeks or months within 6 to 12 months; that is his estimate, not a measurement. Loop budgets and stall detection are in §8.
      ■ Takeaway · Next §10

      Write the agent as a recoverable state machine, make its side effects idempotent, and declare what happens when a human or a second message arrives. Next, put that runtime to work for agents that sleep, wake on events, and run all day.

      Next: §10 Always-On Agents
      §10 · Always-On Agents

      Always-on agents: triggers, routers, sleep, and when to interrupt

      A week-one agent is a loop in your terminal that dies when you close the laptop. An always-on agent runs the same loop on a server, with its state in a database and its own computer. Events wake it, so it can work overnight, message you later, and run many instances at once. LangChain's ambient-agents post names the two chat limits this removes: every task starts with you typing, and you hold one conversation at a time. The new limit is how often the agents need you. The user experiences three things: what wakes the agent, what the router lets through, and when it interrupts.

      Asleep until something happens

      A trigger (a routine, your message, a scheduled check-in, a Slack mention, a helper finishing) loads the agent's saved state for one turn, then it stops. Its computer, a small VM, is restored from a snapshot only when a tool needs it, then put back to sleep. Each wake-up first passes a router that drops duplicates, sets priority, inserts the event into the conversation and asks: should I bug the user?

      DEMO 10.1 Wake-Up Day
      Toggle the router, move the sleep timers · watch agent and computer minutes split apart
      Router:
      one day · wake-ups on top · agent awake · computer awake
      router log · click a wake-up icon to find it here

      Icons are wake-ups: ✉ messages you, ✕ dropped by the router, ×2 a duplicate that ran. Bars show when the agent and its computer are awake. Illustrative toy model.

      5 min
      2 min
      More controls
      Wake-ups:
      3 of 5
      How this toy model works

      The six wake-ups and the 28 / 22 minute defaults follow the always-on note's example day. Work and tool minutes per turn are toy values. "Wake-ups that need the computer" counts the highest-priority turns, which call a tool. Heartbeats take 1 minute of work and use no tools.

      1. Start with the defaults. Five turns run and the duplicate is dropped. The agent is awake 28 min, its computer 22 min (1.5% of a 24/7 machine). 3 of 5 turns message you; the check-in and Slack mention stay quiet.
      2. Untick "Drop duplicates". The Slack event runs twice: 6 turns, agent awake 31 min. Also untick "Decide whether to message you" and all 6 turns reach you.
      3. Set the computer's sleep timer to 30 min. Computer time jumps from 22 to 97 min (6.7%); the agent stays at 28 min. The sleep timer now drives the cost.
      4. Add a 30-min heartbeat. It adds 48 quiet turns (53 in all): the agent is awake 168 min, while the computer stays at 22 min since heartbeats use no tools. With a 10 min idle stop the agent is awake 569 min. Cost follows events and timers.

      Compact while the cache is warm

      Each turn resends the whole conversation, and the cached part is billed at a discount only while the provider's cache is warm (the speaker's estimate: "maybe 10 minutes, maybe 60"). So when a 100k+ token conversation goes idle, compact it right away, while the cache is warm, and the user resumes from a cheap summary instead of a cold prefix.

      DEMO 10.2 Compact While It's Warm
      Move idle time past the cache TTL · watch the cold re-read dwarf the summary
      idle gap, 5 min per cell · cache warm until the TTL · ◆ compact now · outlined cell: user returns
      the first turn back under three policies · badges: cost in k fresh-token units

      green warm read · coral cold read · amber write summary · blue read summary · ✓ cheapest. Illustrative toy prices.

      150k tok
      30 min
      10 min
      More controls
      10%
      5k tok
      5×
      How this toy model works

      Costs are in thousands of fresh-input-token units and count only the first turn back; later turns benefit equally from B and C. A re-reads the conversation. B re-reads it, writes a summary, then reads the summary. C writes the summary now, while the cache is warm. A summary write costs its size times the write price.

      1. Start: 150k tokens, back after 30 min, 10 min TTL. The cache is cold on return. Doing nothing costs 150k; compacting on return costs 180k (cold re-read plus summary). Compacting right away costs 45k, a 70% saving.
      2. Bring the user back after 5 min. The cache is still warm: doing nothing costs 15k, so compaction (45k) can wait. A 60 min TTL with a 30 min gap gives the same answer.
      3. Shrink the conversation to 20k. A cold re-read costs only 20k, while compacting costs 32k. Compacting pays off only for long conversations left idle past the TTL.

      When to talk: notify, question, review

      An agent woken by every email must decide how much of your attention each deserves. LangChain's post (Jan 2025) names three patterns. Notify: flag the event without acting, like a DocuSign it cannot sign. Question: ask instead of guessing, like whether you want to attend a conference. Review: propose a risky action and wait while you approve it, edit it or send feedback. Too few gates and errant actions ship; too many and you become the bottleneck.

      DEMO 10.3 Notify / Question / Review Triage Desk
      Move the gates · watch attention cost trade against errant actions
      40 toy emails, sorted by the agent · errant action · dashed: never surfaced
      what the agent did with the selected email

      Each tile is one email (DS DocuSign, MT meeting, CF conference, NL newsletter, CL client, SP spam). Click a tile to see the agent's decision. Illustrative toy model.

      Attention39units, of 120 if you review everything
      Interrupts18notify + question + review
      Errant actions0shipped with no human
      Missed0events you never saw
      risk ≥ 0.60
      info < 0.50
      10%
      How this toy model works

      The 40 emails are seeded toy data, each with hidden values for whether the agent can act, how well it knows the answer (info) and risk. Attention units: notify 1, question 2, review 3. An email the agent handles alone goes wrong if it guesses with info below 0.5, or if its risk is above 0.6 and it slips at the error rate. The three patterns and the examples come from LangChain's ambient-agents post, which reports no measurements.

      1. Start with the defaults (review at risk 0.60, ask below info 0.50). 5 DocuSigns go to Notify, 5 conference invites to Question, 8 client replies to Review, and 22 emails are handled alone: 18 interrupts, 39 attention units, 0 errant.
      2. Turn on "Fully autonomous". Attention drops to 0, but 5 errant actions ship (all guessed conference replies) and 5 DocuSigns are never seen.
      3. Set the review threshold to 0. Everything waits for you: 40 interrupts and 105 attention units, 88% of reviewing everything. You are the bottleneck.
      4. Raise the review threshold to 0.85, then the error rate to 30%. At 10% error this looks balanced (13 interrupts, 0 errant), but that was luck. At 30%, 2 client replies go out wrong. Keep review on irreversible actions.
      • Triggers. Each trigger starts one turn. Heartbeats (OpenClaw wakes every 30 minutes) and cron jobs are the scheduled kind. This is the event-driven loop from §1.
      • The router. In the speaker's words, when to stay silent and when to interrupt is still an open problem.
      • Thin client, thick server. The agent process and its VM sleep on separate timers. With the loop on the server, you can ship agent updates without an app release and rebuild the VM without killing the loop.
      • Ambient is not autonomous. Notify, question and review keep a human on what the agent cannot do, does not know, or cannot undo. The speaker has a second model "auto review" every command (better than tired humans, he says, without data), yet both sources keep the user approving irreversible sends.
      Go deeper · 7 more notes
      • Cost follows events. The speaker sleeps the agent and its VM for cost, and because there are "not enough computers in the world" to keep one running per user.
      • Where the interrupts land. In the talk, one send_user tool carries everything, and each client (mobile, desktop, email, Slack) renders approvals its own way. LangChain first used Slack, which was hard to navigate and awkward for structured approve, edit or feedback steps. As notifications piled up it built an Agent Inbox, an email inbox crossed with a ticketing system, listing every open agent thread with room for custom feedback buttons. At launch it sorted only by time and had one user; priority sorting and assignment were planned.
      • Why keep a human in the loop. LangChain gives three. Gates let you ship an agent before you trust it to email a client or write to a database. Asking when unsure is how co-workers behave, which the post says builds trust and adoption (citing Devin's use of Slack as a main interface). And every approve, edit or feedback response is signal for long-term memory (§6).
      • Cron hygiene. A stateful cron appends every run to one thread so the agent sees its history; a stateless one starts fresh. Crons keep running and billing until you delete them (LangChain, self-described). Bursty jobs need task queues.
      • Sleep-time compute. Idle time can precompute likely answers or consolidate memory overnight (Stanford CS329Z L7), but work on questions nobody asks is wasted, a caveat LangChain's cron examples (nightly briefings, 15-minute alert sweeps) skip.
      • Sparse orchestrator. The main agent hands token-heavy work to durable helpers with fresh context and keeps a to-do list of them, which makes context "feel infinite". More in §11.
      • Two improvement loops. Daily: a failure becomes an eval, then a fix to the harness, prompt or inference that the eval verifies before it ships. Every few months: train a new model on the accumulated evals (§13, §15). The speaker's rule "delete the product": assume today's models are the worst you will use, and be ready to rebuild the UI within about 6 months.
      ■ Takeaway · Next §11

      An always-on agent is mostly asleep, so engineer the wake-up, the router and the interruption policy, because those are what the user experiences. Next: what happens when one agent becomes many.

      Next: §11 Multi-Agent Systems
      Part 4 Scaling and Measuring Many agents, honest evals, and traces as data.
      §11 · Many Agents

      Multi-Agent Topologies: supervisors, helpers, and the read/write line

      A multi-agent system runs control flow in several places at once, each with its own context window. That buys parallelism, specialization, focused context and broader exploration. It costs overhead, information lost at every handoff, conflicting work, and errors that spread downstream. More agents often do not help: in Google's scaling study, multi-agent setups hurt the strongest Gemini and Claude models tested, though a decentralized swarm helped GPT-5, and decentralized agents beat one agent on a finance synthesis task. In CooperBench, pairs of coding agents lost to solo agents on medium-difficulty tasks (Stanford CS329Z L8).

      Reading parallelizes, writing does not

      Reading produces facts, which merge by union. Writing produces artifacts, and each carries implicit decisions: names, interfaces, assumptions. Parallel writers make those decisions independently, so they conflict at merge. Anthropic's research system (mid-2025) follows this line: sub-agents search in parallel, and one agent writes the report.

      DEMO 11.1 Should You Split This Task?
      Raise the write share · watch decision cards clash and team sizes turn red
      Presets: Writes:
      who does what, on one time scale
      shared write decisions · what each writer chose
      success by team size, this write mode · click a size

      Decision cards turn red when parallel writers chose differently; team sizes are green above one agent, red below. Illustrative toy model: the numbers are made up for teaching.

      Speedup2.9x34 time units vs 100
      Extra tokens+36%136 token units vs 100
      Success82%1 agent: 66%
      4
      10%
      More controls
      50%
      5%
      3 windows
      How this toy model works

      Each extra agent adds 3 time units of sync and 12 token units (it reloads the prompt and re-explores). Success starts at 90% and falls when one agent cannot read all the material, when handoffs lose information, and with conflicts. Each shared write decision has 3 options, so parallel writers rarely agree; each conflict costs 6 points of success. The pattern follows the read/write argument from Cognition and Anthropic; the numbers are not from a benchmark.

      1. Research report. Four agents, 10% writing, material spanning 3 context windows, one writer. The run is 2.4x faster (42 time units vs 100) and success rises to 87% from 66%, because one agent cannot hold all the material. The price is 36% more tokens.
      2. Let every agent write. Speed climbs to 2.9x, but the one shared write decision, function names, now clashes (1.0 expected) and success drops to 82%. Still a win: there was little writing to fight over.
      3. Feature in one repo. Now 70% of the work is writing, with 60% coupling and nothing extra to read. Four parallel writers finish 2.9x faster, but all 4 decision cards clash (3.9 expected conflicts) and success falls to 64% from 90%.
      4. Keep the writing single. Conflicts go to 0, but the run is only 1.2x faster and success is 83%, still below one agent's 90%, because each handoff loses 10%. Every team size from 2 to 8 is red (86% down to 82%): stay single-agent.

      When a second agent pays

      Anthropic says multi-agent systems work mainly because they let a task spend more tokens than one agent can, so the extra token bill is the mechanism as well as the cost.

      Split whenStay with one agent when
      The material exceeds one context window, or the task needs more tokens than one agent can spendSteps depend on each other in sequence
      The work is breadth-first, with independent directions to followThe work is tightly coupled and shares context, as most coding does
      The work spans many complex toolsOne agent already meets your eval targets
      Data access must be separated (one agent may read health records, another may not)The only split is by job title along a sequential pipeline
      The task is valuable enough to pay for the extra tokensYou hope several agents debating will raise accuracy

      Topologies and what production systems use

      The lecture names four ways to run agents. In the Google results, cost rose from single agent to centralized to swarm, with hybrid the most expensive and often only matching the others.

      TopologyHow it runsWatch for
      IndependentSame task to several agents, no talking, a final step picks or mergesWasted duplicate work
      CentralizedAn orchestrator splits the goal, briefs workers, keeps controlOrchestrator bottleneck
      Decentralized swarmAgents claim work from shared state and talk all-to-allHard to track, costly
      HybridOrchestrator plus direct worker-to-worker messagesMost communication overhead

      Shipped systems lean centralized and read-heavy. One always-on agent keeps a sparse main conversation and hands token-heavy work to helpers with fresh context. LangChain's trace-analysis agent sends batches of traces to a screener sub-agent and only flagged ones to investigators, and leaves fixes to a separate agent. The helpers read; one agent decides.

      The brief decides the division of labor

      A sub-agent starts with nothing but its brief. Anthropic says a brief needs an objective, an output format, guidance on tools and sources, and clear boundaries. Given only "research the semiconductor shortage", one sub-agent studied the 2021 auto chip crisis while two others duplicated each other on 2025 supply chains. Models also share a hive mind: agents given a shared repo all picked the same branch name (L8). Diversity has to come from assigned roles, subtopics or resources.

      DEMO 11.2 Hive-Mind and the Vague Brief
      Tick the four brief parts · watch the reports stop doubling up
      Brief has:
      the lead agent's trace · a sub-agent sees only its brief
      where the sub-agents landed · on its slice · drifted · gap

      One seeded run of the query "research the semiconductor shortage". Numbered chips are sub-agents; exp is the expected number of agents per subtopic. Illustrative toy model.

      Distinct1.9of 3 subtopics (expected)
      Duplicates1.1this run: 1 dup, 1 gap
      Stays on task15%no format: +30% lead rework
      80%
      More controls
      3
      How this toy model works

      Each agent stays on its assigned subtopic with a probability set by the brief (15% base, +35% objective, +30% boundaries, +15% tools); otherwise it drifts toward the obvious subtopic, and the pull slider sets how strongly. A missing output format adds about 30% lead rework. Expected values (exp, KPIs) are exact; the trace and the subtopic cards show one seeded run. Based on Anthropic's semiconductor anecdote, a single case, not a rate.

      1. The vague brief. Three sub-agents, strong pull toward the obvious topic, no brief parts. Each stays on its slice only 15% of the time: expected 1.9 distinct directions and 1.1 duplicates. The trace echoes the duplication in the anecdote: sub-agents 1 and 2 both report on 2025 supply chains, and the merge finds fab capacity missing. (The post says vague briefs led sub-agents to misread the task or repeat each other's searches; it does not say the 2021 chip-crisis work was part of a plan. In the toy, that sub-agent is simply the one that kept to its slice.)
      2. Add an objective. Staying on task rises to 50% and distinct directions to 2.2, but 0.8 duplicates remain, and this run still doubles up on 2025 supply chains.
      3. Write the full brief. With all four parts each agent stays on its slice 95% of the time: 2.9 distinct directions, 0.1 duplicates, and the verdict flips to Clean division. Each sub-agent reports on its own slice and the merge finds all 3 subtopics covered.
      4. Drop the output format. The division stays clean (2.9 distinct), but the trace gains a reshape step: reports come back in different shapes, so the lead spends about 30% more tokens merging them.

      How teams fail

      "Why Do Multi-Agent Systems Fail" sorted annotated traces into three classes. Most fixes live in the harness.

      ClassWhat goes wrongHarness fix
      System designAgents break their role spec, repeat steps, or do not know when to stopExplicit role specs and termination criteria
      Inter-agent misalignmentAn agent reasons correctly and then acts otherwise, or drifts off the taskCompare each agent's actions with its stated plan
      VerificationThe run ends early, or checks are wrong or incompleteAn independent check wherever results change hands

      CooperBench puts two agents in separate VMs to build overlapping features in the same files, talking over chat. Commitment failures (promising an edit and not making it) were 32% of failures. Isolation adds its own: an agent sees a teammate's lines still unedited in its own worktree and overwrites them.

      • Start single. Build a strong single-agent baseline and an eval set first (about 20 examples is enough to start), then add agents one purpose at a time and measure each addition.
      • Fan out reads, keep writes single. Good fits are breadth-first, high-value tasks whose material exceeds one context window. Tightly coupled work, including most coding, is a poor fit.
      • Every agent costs tokens. Each new agent reloads the system prompt and re-explores. Those tokens are also what the split buys, so it pays only when the task needs them.
      • Brief like a manager. Objective, output format, tools and sources, boundaries. Missing parts show up as duplicates, gaps and merge rework.
      • Verify at handoffs. A flawed sub-agent report accepted at face value spreads its error downstream. Pay for checks where results change hands.
      Go deeper · 8 more notes
      • Separate reviewers. Focused context helps checking: Cursor reported better code reviews from a separate reviewer agent than from asking the author agent to review its own code in the same conversation, the same reason an outside critic beats self-review in §3.
      • More on the benchmarks. In Google's scaling study, multi-agent setups fell apart on PlanCraft, a planning and coding task, while decentralized agents beat one agent on finance synthesis. CooperBench covers 600 coding tasks across 12 libraries and 4 languages; very easy and very hard tasks came out about the same for solo and pair. Besides commitment and expectation failures (ignoring a teammate's stated plan), it counts communication failures: intents, questions or status never shared. Splitting work by read versus write explains both the negative results and Anthropic's positive case.
      • Personas and debate. Persona pipelines in the MetaGPT style pass work down a fixed sequence of roles (PM, architect, engineer); with current models, one agent with all the tools and a defined workflow would probably do better. Multi-agent debate raised accuracy when base models were weak. With strong models the lectures put the better reasons to split at efficiency and access control. Most coding has few truly parallel subtasks, and agents cannot yet coordinate in real time.
      • Production details. The always-on agent's helpers are durable, tracked like a team's to-do list. LangChain's trace-analysis agent (Engine) sends batches of about 20 traces to a fixed-prompt screener and gives flagged traces to flexible investigators; a separate agent fixes those tagged needs_fix. Its harness team runs parallel error-analysis agents whose findings one main agent merges.
      • Hive mind and conflicting goals. Asked to build something impressive, over half of Anthropic's agents built a ray tracer or a self-hosting compiler. Agents told to migrate the same backend to different languages on one machine ended unresolved, by force (kicking each other off the machine), by passivity (giving up), or by truce (a shared test to choose). One model reached a truce 98% of the time, usually only after revoking the other agents' access first.
      • Handoff vs agent-as-tool. In the OpenAI Agents SDK a handoff passes control and the full history to another agent, which then talks to the user. Agent-as-tool keeps control with the caller, which sends a specific input and gets a result back. A supervisor calling helpers works like agent-as-tool. Other channels: AutoGen conversations, MetaGPT-style message pools that agents subscribe to, and Google's A2A protocol, where an agent card lists a remote agent's skills, auth and I/O modes so an orchestrator in one deployment can call workers in another.
      • Coordination infrastructure. Task ledgers (Magentic-One keeps a task ledger and a progress ledger with stall detection), shared memory, and git worktree isolation. Worktrees stop interference during the run but move the cost to merge time, and they hide a teammate's in-progress edits. Agents that coordinate well tend to use three patterns: role division ("I'll add the header, you insert the strings"), resource division ("I'll edit lines 68 to 84, you start at 85"), and negotiation, where one agent spots overlapping plans and proposes a clean split.
      • Scale caveat. Negative academic results may partly reflect budgets: the lecturer had not seen a public academic multi-agent system above about 100 agents. The read/write rule reaches this chapter through a June 2025 LangChain post that reconciles Cognition's and Anthropic's views; it is commentary with no experiments of its own.
      ■ Takeaway · Next §12

      Split work only where it divides cleanly, keep the writing in one place, and pay for verification at every handoff. Every one of those calls needs a measurement, which is what evals are for.

      Next: §12 Evaluating Agents
      §12 · Evals, Verifiers, Trajectories

      Evaluating agents

      A regex does the same thing every run. Swap it for a model call and it generalizes better, but two runs may no longer agree. You cannot predict an agent from its definition, so you run it and judge the outputs. The engineer's job shifts from writing the spec to writing the evaluation (Stanford CS329Z L10), and the evals become the spec.

      Eval-driven development is test-driven development for non-determinism. Write one behavior as When, Do, Don't, and Keep intact. Build the dataset and grader before the fix (an eval written after you see the new output passes by design), confirm it fails on the current agent, run a baseline, then change the agent and compare example by example. Use your own domain, production-like inputs, edge cases, and LLM-rewritten variants (say, angrier messages). Record cost and latency next to accuracy.

      One success in k, or k successes in k?

      Benchmarks often report pass@k, solved if any of k attempts succeeds. Users get every run, so tau-bench reports pass^k: all k must succeed. With independent trials at rate p, pass@k is 1 − (1 − p)^k and pass^k is p^k.

      DEMO 12.1 pass@k vs pass^k
      Raise k · watch green users (all k runs pass) turn amber
      100 users, each running the task k times · click a user to see their runs
      User 1

      Each square is one user. Green: all k runs passed (counts for pass^k). Amber: some passed. Coral: none passed. pass@k counts green and amber. Illustrative toy model.

      0.70
      1
      How this toy model works

      Trials are independent with the same success rate p. The grid rounds the expected shares to whole users (all-pass users first), and each user's runs are drawn from a fixed seed. Real agents are not that tidy (some tasks are always hard), but tau-bench's pass@k and pass^k split the same way as k grows.

      1. Start at p = 0.70, k = 1. Both metrics read 70.0%: 70 users are green and 30 coral, with no amber. With one trial there is nothing to split.
      2. Set k to 8. pass@8 reaches >99.99% while pass^8 drops to 5.8%. Only 6 of 100 users stay green; the other 94 turn amber, each having seen at least one failure. The same agent looks nearly perfect or nearly useless depending on which number you report.
      3. Raise p to 0.95. pass^8 climbs to 66.3% (66 green, 34 amber): even at 95% per trial, a third of users who run the task eight times hit a failure.
      4. Raise p to 0.99. pass^8 is now 92.3% (92 of 100 users). The readout shows that pass^8 ≥ 90% needs p ≥ 0.987.

      Capability is not reliability

      pass^k measures one part of reliability. A Princeton study cited in Stanford CS329Z L1 measures three properties apart from accuracy: consistency (the same result across repeated runs), robustness (it still works when the input changes slightly or gains irrelevant content) and predictability (when it fails, can you tell why, and can the run recover?). Models ranked by accuracy showed no matching trend in reliability. When you choose a model, run repeated trials and perturbed variants of your own tasks, and read how the failures look.

      The verifier is a classifier

      A pass/fail verifier has false positives and false negatives like any classifier. Aim for a one-to-one map between what the instruction asks and what the tests check. A requirement nobody checks lets a wrong solution pass, and agents learn to skip exactly those. A check the instruction never mentioned fails correct solutions. LangSmith Engine tests each proposed evaluator on evidence traces (runs known to show the issue), which measures how many bad runs it catches and says nothing about good runs it wrongly flags.

      DEMO 12.2 Verifier as a Classifier
      Uncheck requirements or add extra checks · watch measured pass rate leave the true one
      one trial: what was asked vs what was tested
      100 graded trials · click one to inspect it

      Left: each instruction requirement and the test that checks it; "no test" rows let hacks through. Right: green true pass, amber false fail, coral false pass, grey true fail. Illustrative toy model.

      6
      6 of 6
      0
      More controls
      0.90
      0.5
      How this toy model works

      After the Terminal-Bench lecture's verifier-as-classifier view: each requirement is met with probability p; a hacking agent skips each unchecked requirement with probability h; each extra check passes with a fixed 0.6. The readout uses exact probabilities. The grid rounds them to 100 trials, and each inspected trial is a seeded example of its kind. The requirement names are made up.

      1. Start aligned. Six requirements, all six checked, no extras. Measured and true are both 53.1%: 53 green trials, 47 grey, nothing coral or amber. The hack propensity is 0.5, but there is no unchecked requirement to skip.
      2. Check only 3 of 6. The verifier now reports 72.9% while only 6.6% of trials are truly correct: it over-reports by 66.3 points, all of it false passes (66 coral squares). Trial 8 shows why: two "no test" requirements were skipped and the verifier still says PASS.
      3. Check all 6 again, add 2 extra checks. Now the error runs the other way: measured 19.1% against a true 53.1%, under-reporting by 34.0 points (34 amber squares). Those are correct solutions failing tests for things nobody asked for.
      4. Keep that verifier and test only on evidence traces. It catches 100.0% of known-bad runs (47 of 47) and looks perfect, while the 53 correct runs go untested. The readout names what this test cannot see: it also rejects 64.0% of correct runs. You need clean traces to measure false alarms.

      Correct first, then efficient

      Two correct runs can differ a lot in cost and latency. LangChain's Deep Agents team filters on correctness first, then compares the survivors against an ideal trajectory: the shortest correct sequence of steps. For "What is the current time and weather where I live?", the ideal run resolves the user, then the location, then fetches time and weather in parallel. A run gets three ratios to the ideal (steps, tool calls, latency) and a solve rate: expected steps divided by observed seconds, or 0 if the answer is wrong.

      DEMO 12.3 Trajectory Scorecard
      Load a preset, then add waste · watch the ratios and the solve rate
      Presets:
      wall-clock timeline · parallel tools share one block

      Grey blocks are model steps, blue blocks tool calls, coral blocks wasted work; the ideal run sits above this run. Illustrative toy timings.

      Step ratio 1.00 4 steps vs 4
      Tool-call ratio 1.00 4 calls vs 4
      Latency ratio 1.00 8.0 s vs 8.0 s
      0
      0
      More controls
      1.0 s
      1.00×
      How this toy model works

      Toy timings (tools: user 0.5 s, location 0.5 s, time 1 s, weather 3 s; 1 s per model step), chosen so the presets land on the post's figures. Reported by LangChain for its illustrative example: ideal 4 steps, 4 tool calls, about 8 s; correct but inefficient 6 steps, 5 tool calls, about 14 s (solve rate 4/14 ≈ 0.29). The ideal run's 0.50 is derived by the same formula and is not stated in the post. KPI colors: green within 10% of ideal, amber up to 50% over, coral beyond.

      1. Load "Ideal". 4 steps, 4 tool calls, 8.0 s. All three ratios are 1.00, the solve rate is 0.50, and the verdict is "Near-ideal".
      2. Load "Correct but inefficient". No parallel fetch and one redundant weather call: 6 steps, 5 calls, 14.0 s. The ratios are 1.50, 1.25 and 1.75, the solve rate falls to 0.29, and the verdict reads "Correct but 75% slower than ideal".
      3. Now untick "Task solved". The ratios still read 1.50 / 1.25 / 1.75, but correctness is 0 and so is the solve rate. Correctness comes first, so a wrong answer is never ranked on speed.
      4. Back to "Ideal", add 2 reasoning turns. Tool calls stay at 1.00, but steps go to 1.50 and latency to 1.25 (10.0 s). Solve rate 0.40. Each ratio catches a different kind of waste.

      Organize the suite by what it tests

      LangChain's Deep Agents team gives every eval a docstring and a tag for the behavior it tests, regardless of where it came from. Filing FRAMES and BFCL together as "external benchmarks" would hide that one measures retrieval and the other tool use. While you iterate on one behavior, run its tagged subset; run the full suite before you ship. If the score on your tuning set climbs while a held-out set stays flat, you are fitting your examples (more in §14).

      TagWhat it checks
      file_operationsReading, writing and editing files
      retrievalFinding content, even across files (FRAMES)
      tool_usePicking and chaining tools, 5+ calls in a row (BFCL)
      memorySaving and recalling the right things
      conversationMulti-turn behavior, some runs 10+ turns with a simulated user
      summarizationCondensing content
      unit_testsSDK plumbing; kept out of model-capability scores
      • Compare per example, not the average. In LangChain's docs-agent example, adding a create_ticket tool raised the average score, while "How do I connect to the VPN?" started filing tickets because the tool description ("VPN and laptop issues") was too broad. Only the per-example view showed it.
      • Every eval you keep pushes the agent. You tune prompts and tool descriptions until evals pass, so hundreds of loosely chosen tasks can raise the score while production stalls. Prefer a small targeted suite sourced from dogfooding traces, adapted benchmark tasks, and hand-written tests.
      • Match the grader to the property. Code checks for deterministic things (was the right tool called), an LLM judge for fuzzy ones, humans for domain correctness, where plausible-but-wrong answers fool judges. Validate a judge against human labels and ask it for pass/fail instead of a 1 to 10 score.
      • Agents cheat, so isolate and hold out. The classic hack is an agent editing the unit tests it was graded by. Grade in a fresh container after the agent's is gone, and keep a held-out set per category that the tuning loop never sees ("agents are famous cheaters", as LangChain's Better-Harness post puts it).
      • Run evals continuously. Fast code checks gate each PR; slower LLM-judge evals run nightly or before a release. Online evals on production traces show what is wrong; offline evals confirm the fix. Passing evals become regression tests, with a must-pass subset, and saturated evals get pruned.
      Go deeper · 11 more notes
      • Pick the unit you score. The final answer, one step, the full tool-call sequence, or a multi-turn thread. Some behaviors only show up over 10+ turns with a second model playing the user (does the agent ask a clarifying question?). Tool calls can be graded by matching the call's syntax tree, by executing it, or by checking the end state, and BFCL adds relevance-detection cases where the right move is to call no tool at all.
      • More ways agents cheat. Agents keep finding new reward hacks. A fresh grading container stops processes the agent left running, but artifacts can be code, so the verifier must sandbox them, and task-specific holes (a Lean kernel bug let agents skip proof tasks) need a fix from the task author. LLM judges and reviewers can be sycophantic and hand out inflated 5/5 ratings.
      • Anatomy of a Harbor task. Harbor, the framework behind Terminal-Bench, packages a task as an instruction, a config, an environment (usually a Dockerfile), an optional oracle solution, and verifier tests. The oracle should be a program that runs in the environment like an agent would, so it checks the environment as well as the tests. Agents that change an environment need state-based grading of what they leave behind, in a fresh sandbox per run. LangChain also uses Harbor for ablations: can a harness part be removed without the agent getting worse?
      • Build the task like production. The instruction should be fully specified, concise, and natural, like something a person would type into a coding agent. In Terminal-Bench reviews, editors cut repetition, facts the agent can discover itself (installed versions), and detail that gives the answer away; every extra line is another chance to drift out of line with the verifier. The environment should run real software instead of mocks and bake dependencies into the image instead of downloading them at runtime. Internet access is a trade-off: the web changes between runs, invites contamination, and raises safety issues. Plausible but unused distractor files make a task more realistic. When a production failure becomes a regression case, capture its environment as well as the assertion.
      • QA the tasks before trusting the score. Terminal-Bench checks tasks in layers: static checks (config sanity, instruction length), an agent judge that asks whether every instruction requirement is covered by the verifier, the oracle, real frontier agents, red-team agents trying to hack it, and then agents reading the trajectories. Tasks often turn out hard for a reason the author never meant, such as a broken package version. Infrastructure should add no variance: a trial that fails because a container or registry pull failed counts as an agent failure, which biases the score down, and more trials do not remove a bias.
      • Score the retriever on its own. For a RAG agent, a bad answer can come from retrieval or from the reader. Grade retrieval separately (Stanford CS329Z L3): hit@k (is anything relevant in the top k), failed@k (its complement), recall@k (share of all relevant passages found), MRR (1 over the rank of the first relevant hit), and NDCG@k (rank-weighted relevance against the ideal order).
      • Version tasks like software. New models find new hacks and new false negatives. With semantic versioning, a verifier patch only needs the stored artifacts regraded, an oracle fix needs no rerun, and a change the agent can see (prompt, environment, tools) needs a full rerun.
      • Assertions beat reference answers. A correct reply can be worded many ways, so Engine writes regression examples as short assertions ("must cite the config value the tool returned", "must not suggest the deprecated flag") instead of a golden output.
      • Report the failure mode next to the score. In MIT CSAIL's weight-space programming post (results as reported by the MIT post itself, relayed second-hand; not peer-reviewed or replicated), a frontier LLM edited about 0.016% of Qwen3.5-0.8B's weights, and with a 50-forward-pass budget MATH-500 accuracy rose from 7.9% to 48.1%. The edit added no math knowledge: answers hitting the token limit fell from 93.0% to 33.1%, because it removed a reasoning loop. The cap rate explained the score; accuracy alone would have hidden it. Track cost and latency next to accuracy for the same reason.
      • Keep plumbing out of capability scores. SDK unit tests (prompt passthrough, subagent routing) should exist, but any model passes them, so counting them in a model score adds no signal. Evals also often write, so run them in staging, never against production data.
      • Benchmarks and open problems. Terminal-Bench (TB2 has 89 tasks), SWE-bench Verified, BFCL, tau-bench, OSWorld, LoCoMo and MemoryArena each cover a slice. Headline benchmarks such as SWE-bench only fit your product if you are building a general coding agent; otherwise build your own domain eval. None of the LangChain posts used here report repeated trials or score noise, so treat small score differences between vendors' runs with suspicion. How to evaluate agents that run for a month, when models ship monthly, is still open.
      ■ Takeaway · Next §13

      Build your own domain eval before the fix, from production-like inputs, edge cases and LLM-rewritten variants, spend your best human effort on the verifier's decision boundary, report pass^k next to pass@k, and never read only the average. The raw material for new evals is the agent's own runs, which is where traces come in.

      Next: §13 Traces as Data
      §13 · Traces as Data

      Traces as the raw material for improvement

      In ordinary software you can read the code and reason about every behavior. In an agent the code only bounds what the agent may do. What it actually did on this input lives in the trace: every model call, tool call, retrieval, state change and error, and the decisions that link them. Agent failures are mostly semantic (wrong tool, wrong argument, a dropped constraint), so they never reach an error log. A score tells you that something went wrong; the trace tells you what to change.

      Record the user input, calls with their arguments and outputs, retrieved documents, routing decisions, latency, cost, errors and feedback, with tags to filter on. An enriched trace also carries evaluator scores, cluster labels and human annotations.

      Fix repeated failures first

      One bad run may be a fluke. A failure that repeats across many traces belongs on the work list. Monitoring tracks metrics you already defined; clustering every trace surfaces failure modes nobody thought to measure. Rank each by how often it happens times how much it hurts.

      Priority $$\text{priority}(\text{tag}) = \text{count}(\text{tag}) \times \text{severity}(\text{tag}), \quad \text{filed only if count} \ge T$$
      DEMO 13.1 Trace Miner
      Spot-check 5 vs cluster all · watch which fix wins
      Mode:
      trace pool · one square per trace, colored by its label · click to open
      issue board · clusters ranked by count × severity
      Squares: wrong tool, misses intent, drift, missing tool, ok. Each issue card holds its cluster's traces. Illustrative toy model.
      ≥ 1
      ×1
      ×1
      More controls
      500
      1
      ×1
      ×1
      the opened trace · what the agent did, then the label an evaluator attached
      How this toy model works

      A fixed, seeded pool of 1,000 synthetic traces (the slider uses the first N) with hidden tag rates: wrong tool 12%, misses intent 9%, drift 6%, missing tool 2%. The rates are invented. The symptom-to-remedy mapping follows LangChain's post on the trace-driven improvement loop. Spot-check mode samples five of those N traces with the chosen seed. In cluster-all mode a tag is filed only if its count reaches the threshold T. The opened trace is a seeded template for its label (one per failure type, three for ok traces); its latencies and token counts are invented.

      1. Cluster all 500 traces. Wrong tool leads with 58 traces, ahead of misses intent (42), drift (32) and missing tool (7). Top fix: rewrite tool descriptions or add routing. Trace #9 is open: asked for a refund, the agent called search_docs instead of issue_refund.
      2. Spot-check 5 instead. Seed 1 shows one misses-intent trace (#370, a 900-word reply to a 3-bullet request) and no wrong-tool ones, so it points at the wrong fix. Across 200 reseeds, a 5-trace spot check picks the wrong fix (or nothing) 59% of the time. Press Reseed: seed 2 shows five clean traces and suggests fixing nothing.
      3. Make misses intent cost twice as much. 42 × 2 = 84 beats wrong tool's 58, so the top fix becomes defining what "good" means in the prompt. Frequency alone does not set the priority.
      4. Require 10 traces before filing, with missing tool at severity 5. Missing tool has only 7 traces, so it is never filed, even though 7 × 5 = 35 would rank it ahead of drift (32). A threshold filters noise and also hides rare, costly causes.

      Reading traces at scale

      Mining gets hard as the pool grows. Production projects hold thousands to millions of traces, and with long-running agents ten traces can add up to hundreds of messages and tool calls. LangChain describes its trace-mining agent as working at about 50 traces and breaking at thousands. Its fix is a funnel: compress each trace to a skeleton (one row per turn: role, tool name, latency, size, no content), send batches of about 20 to a cheap Haiku-based screener that answers only "clean" or "maybe", and load full content only for flagged traces, in separate investigator subagents. The main agent sees one line per flag and a short verdict per investigation.

      DEMO 13.2 Screen-then-Investigate Funnel
      Raise the trace count · watch the main context fill
      Strategy:
      the pipeline · where each trace goes
      main agent's context · what reaches it, against a 200k window
      Context blocks: full traces, CLEAN lines, flag lines, investigator notes; hatched = past the window. Illustrative toy model.
      50
      90%
      5%
      More controls
      5%
      How this toy model works

      The token numbers are invented, not from the source: 3,000 tokens per full trace, a 200k window, batches of 20, 10 tokens per "CLEAN" line, 30 per flag line and 60 per investigator note. Counts are expected values, not samples. The funnel shape (skeletons, batches of about 20, a cheap screener, investigator subagents) is LangChain's self-described design; it reports no metrics. The context box draws at most 100k tokens past the window; anything beyond is counted, not drawn.

      1. 50 traces, read in full. 150,000 tokens fill the main context to 75%, and all 3 failing traces are found. At this size the naive design works.
      2. Go to 10,000 traces. Context overflows at trace 67: reading everything would take 30,000,000 tokens, 150× the window.
      3. Switch to the screener. The main context drops to 88,250 tokens (44%). It finds 450 of 500 failing traces and investigates 925, 9% of the pool; 475 of those flags were false.
      4. Drop screener recall to 60%. Context stays small (37%), but only 300 of 500 failing traces are found: 40% slip through unseen. The cheap first stage caps what the whole system can find.

      From trace to permanent eval

      Finding a failure is half the loop. Ship a decent agent early, since only real usage produces traces. Then collect feedback, turn failures into eval cases, change the weights, harness or context, check the change in staging, compare before and after on the full suite, deploy, and read the new traces. Traces where a user corrected the agent make the best eval cases, because the correction carries the target answer. The step teams skip is keeping every encoded failure in the suite for good, so each later change must pass all of them before it ships. That turns each fix into a ratchet.

      DEMO 13.3 The Ratchet
      Toggle the permanent suite · watch regressions get caught
      release log of the last cycle · what the team's pipeline did
      Cells: broken in production, fixed (outlined = fixed this cycle), ● regression caught, ✕ regression shipped, flag = kept as an eval. Illustrative toy model.
      10
      20%
      How this toy model works

      Eight failure modes start broken. Each cycle fixes one, and the change re-breaks at most one earlier fix with the chosen chance, drawn from a fixed seed so the walkthrough numbers repeat. Without the suite, only the current fix is tested, so a regression ships and must be fixed again later. With the suite, every fixed mode is retested and the regression is caught before release.

      1. Test only the current fix, 40% regression chance. Over 10 cycles, 4 changes re-break an old fix and all 4 reach users. Cycles go to redoing old work, and 2 of 8 failure modes are still broken at the end.
      2. Keep every failure as a permanent eval. The suite grows to 8 cases and catches 4 of 4 regressions before ship. All 8 failure modes end fixed.
      3. Set the regression chance to 0%. With or without the suite, nothing regresses and all 8 modes end fixed. The gate's value scales with how often changes break old behavior, which in agents is often.
      • Traces are the documentation. Code bounds behavior; the trace records what happened on this input. Keep full trajectories along with the score.
      • Enrich, then aggregate. Online evaluators, clustering and human annotation turn raw traces into labeled ones. File an issue only when several traces agree; user feedback raises a trace's priority but does not create an issue by itself.
      • Symptom maps to remedy. Wrong tool: rewrite descriptions or add routing. Drift mid-task: tighter prompt or smaller steps. Misses intent: define "good" in the prompt. Structural gap: a new tool or a human checkpoint. Confirm the cause in the trajectory first.
      • Screen cheaply, investigate deeply. Skeletons and a narrow screener keep the main context small, but the screener's recall caps what you can find, and its false flags cost context.
      • Failures become a permanent gate. Each production failure becomes an eval case that stays in the suite, so later changes cannot silently bring it back.
      Go deeper · 13 more notes
      • One symptom, several causes. Treat the symptom-to-remedy mapping as a starting guess. An ignored tone rule may be vague, placed in the wrong spot, missing from the relevant skill, or contradicted by another instruction. An agent "not finding obvious information" may be writing bad queries, reading poor sources, or hitting tool failures. Only the trajectory tells these apart, and since runs differ even with identical prompts, check several traces before you pick the fix.
      • Where to cluster and evaluate. Cluster the failing subset (low scores, thumbs-down) as well as all traffic. Run online evaluators on a sample or a filtered subset to keep cost down.
      • The skeleton is a navigation index. Three search_db rows in a row with similar sizes suggest looping before anyone reads the text; the screener then greps the full trace and loads only the part it needs.
      • Mining runs repeat. Each run first loads the issue board, closed issues included, so it skips known problems and adds new evidence to existing issues instead of filing duplicates.
      • A fixed taxonomy. LangChain's trace-mining agent looks mainly for a predefined set of categories (for example pii_leak, agent_looping, incorrect_tool_args, missing_tool) so each category can be measured and trusted. It also tests each proposed evaluator on the evidence traces before proposing it. That checks recall only; an evaluator should also be checked for false alarms on clean traces. Each issue carries a category, a severity (low, medium, high), its evidence traces, a proposed evaluator and dataset examples, a proposed fix, and tags such as needs_fix, which hands it to a separate fix agent.
      • Annotation queues. Route traces to humans by filter: low automated score, a feature area, or a user thumbs-down. Labels serve four uses: aligning the online judge where it disagrees with humans, ground-truth answers for offline datasets, criteria for open-ended answers, and free-text comments fed back into clustering. General reviewers check surface quality; domain experts check correctness in context, which a judge can miss (a plausible but wrong legal citation passes many automated checks).
      • False flags cost context too. In Demo 13.2 at 10,000 traces, raise the false-flag rate to 30%: 3,300 traces get flagged and the main context overflows at 302,000 tokens. A screener that is cheap per trace can still be expensive per run.
      • Small trace judges. LangChain reports that a small fine-tuned trace judge beats frontier models on a narrow judging task at "orders of magnitude" lower cost (vendor-reported; no figures given in the post).
      • Coding agents need trace access. LangChain reports Claude Code going from 17% to 92% on its own eval set when given LangSmith Skills (vendor-reported; the eval set, task count, metric and model are not given). Without traces, a coding agent proposes fixes that look fine in review but miss the actual failure.
      • Traces become training data. Rejection-sampled demonstrations, SFT sets built from filtered trajectories, and positively rated interactions reused as few-shot examples all start as traces. Filter them: training on unfiltered traces teaches the failures too. Most traces should stay history; only a small part should become memory or training data.
      • Keep artifacts, regrade later. Storing trajectories and outputs lets you regrade with a fixed verifier instead of rerunning the agent. A single observed production run is one data point, so a human should still review any verifier built from it. Prune the suite too: drop saturated or obsolete cases. Comparing traces side by side across harness versions ties a change in behavior to the edit that caused it.
      • Forks as debugging experiments. With a checkpointed runtime (§9 time travel), fork just before the suspect decision, edit the state or prompt, and compare the branches on identical upstream context. Forks re-run real model and tool calls, so the branch can differ for reasons unrelated to your edit, and side effects such as sent messages can happen again.
      • Publish trajectories, not one score. Terminal-Bench links every result on tbench.ai to per-trial data: the full trajectory, timing and cost, and logs from both the eval infrastructure and the agent harness (Stanford CS329Z). Readers used it to find reward hacks and to plot lines of code delivered per model. For your own evals, send every run to one shared trace project so anyone can debug a failure, and use an agent to triage traces too large to read by hand.
      ■ Takeaway · Next §14

      Without kept and mined traces you can only guess at fixes: patterns across many traces pick the fix, and every fixed failure stays as a permanent eval. Next, those evals become the metric you climb when you optimize prompts and harnesses.

      Next: §14 Optimizing & Hill-Climbing
      Part 5 Improving Agents Optimizing prompts and harnesses, learning over time, agents that improve agents.
      §14 · Optimizing & Hill-Climbing

      Optimizing the system: prompts, programs, and harness hill-climbing

      You cannot tell the best prompt by reading it. OPRO's search found "Take a deep breath and work on this problem step-by-step", and in a class poll students split roughly evenly on which of three prompts would win (Stanford CS329Z L9). So state your intent as data (rollouts, demonstrations, feedback) plus a metric, and let an optimizer search over a built system. The same loop works on one prompt, a multi-module program, or a whole harness, and each step up gives the optimizer more room for real gains and for gaming your eval.

      The optimizer rewrites; the test split keeps it honest

      In the lecture, a calendar extractor returned date, start time and duration from emails, scored by exact match on a 30/20 train/test split. Gemma 3 12B got 55% (11 of 20) of the held-out emails right; after GEPA rewrote the prompt from metric feedback, it got 100%. Only the instruction changed, into a detailed spec of the output formats with no few-shot examples. Note n = 20.

      DEMO 14.1 Prompt Optimizer on a Held-Out Split
      Add rounds, shrink the train set, swap the metric · watch the test emails turn green
      Metric:
      optimizer rounds · ✓ rule added · click a round
      current instruction · the only thing it edits
      30 train emails · the optimizer sees these
      20 test emails · held out

      Each tile is one email; the letter is its hidden quirk. Solid tiles are correct, dashed coral tiles fail, amber tiles are wrong but the hackable metric counts them. Illustrative toy model.

      30 emails
      0
      More controls
      Model:
      How this toy model works

      Based on the CS329Z L5 demo. It mirrors the lecture result (Gemma 3 12B, 55% → 100% on 20 held-out emails). Each email has at most one quirk: A 12-hour time, B relative date, C missing duration, D two events, E written-out date. Each rule fixes one quirk type, and each round adds the rule that fixes the most train failures. The big model already handles every quirk.

      1. Run 3 rounds. Test starts at 55% (train 60%). Three rules (24-hour time, ISO relative dates, duration in minutes) lift test to 90% and train to 93%: 18 of the 20 test tiles turn green.
      2. Run 10 rounds. Test reaches 100% at round 5, after five rules. No train failures remain, so no more rules are added.
      3. Shrink the train set to 5. Train hits 100% after two rules, but test stalls at 80%. Three quirk types never appeared in those 5 emails, so no rule covers them.
      4. Switch to the hackable metric. It says 100% from round 0, so there is nothing to fix. True test accuracy stays at 55%.

      GEPA keeps the specialists

      Few-shot search picks which examples go in the prompt, often bootstrapped from the program's own passing traces (§13). Reflective optimizers rewrite the instruction from feedback: OPRO shows an LLM past prompts with scores, MIPROv2 searches over instruction and demo pairs, and TextGrad passes critiques backward through a program. GEPA keeps a pool of candidates and remembers who solved each devset task. Only candidates on that per-task Pareto frontier can be parents, so a prompt that solves one hard task survives with a poor average. Its system-aware merge combines modules from two parents.

      DEMO 14.2 GEPA Pareto Pool
      Flip pass/fail cells or merge two parents · watch the family tree keep its specialists
      family tree · who may still be a parent
      candidate × task · click a cell to flip it

      Green rounded nodes: the Pareto frontier, the only allowed parents. Filled node: best average. Notes list tasks won; edge A or B is the module a merged child took. Illustrative toy model.

      Merge:
      How this toy model works

      Based on the CS329Z L9 example. T1 leans on module A; T2 and T3 lean on module B. The pool is the lecture's: P3 solves T1, P1 and P2 solve T2, P2 solves T3. A child takes module A from one parent and module B from the other. Real GEPA merges only frontier parents, scores the child on a minibatch first, and discards it if it does not improve. Here you can pick any parent to see what a bad merge looks like.

      1. Start from the lecture example. The frontier is {P2, P3}. P2 dominates P1: it wins T2 and also T3. P3 wins only 1 of 3 tasks, but it alone solves T1, so it stays as a kept specialist.
      2. Flip P1 on T1 to pass. P1 now wins T1 and T2, so it dominates P3. The frontier becomes {P1, P2}: tied at 2/3, each winning a task the other cannot.
      3. Merge module A from P3 with module B from P2. The child P4 solves all three tasks and is the only frontier member. Without the P3 specialist there would be no good module A to inherit.
      4. Merge the other way round. Module A from P2 with module B from P3 wins nothing. The frontier stays {P2, P3}; GEPA would discard this child.

      Harness hill-climbing: evals are the training data

      Point the same loop at the harness (instructions, tools, tool descriptions) and your evals become its training data: each eval you keep pushes the agent in a direction. In scikit-learn terms, find good data, then pick a "fit function" (harness edits or fine-tuning). LangChain's Better-Harness recipe: tag evals by behavior, split each category into optimization and holdout sets from the same distribution, baseline both, then iterate (on a large suite, start with a stratified sample per tag). Each iteration diagnoses from traces and makes one scoped change, checked for new passes and regressions, then reviewed by a human. Agents are "famous cheaters", the post warns: the loop only wants the number to go up. Better-Harness keeps an edit with a net gain and a few regressions, and feeds the regressions to the next edit.

      DEMO 14.3 Optimization vs Holdout Hill-Climber
      Raise overfit, then add the gate and review · watch hack cards pile up in the harness
      Accept:
      proposed edits, one per iteration · click one to inspect
      pass rate · optimization (dashed) · holdout · gap
      optimization · 72 evals the loop sees
      holdout · 72 evals it never sees

      Each row is one behavior category, 12 evals each. Click a tile to inspect it.

      Tiles are evals: green passes, amber passes only through a hack instruction, grey fails. Cards are instructions added to the harness; rejected edits go to the bin. Illustrative toy model.

      60%
      More controls
      40
      edit 40 of 40
      How this toy model works

      Seeded, so every setting replays the same edit stream. Six behavior categories have 12 optimization and 12 holdout evals each. A general edit raises one category's skill on both splits and sometimes regresses another. A hack flips 1 or 2 visible evals, adds 45 prompt tokens, and sometimes confuses its category. Review catches a hack with toy probability 0.7; with feedback on, the next edit repairs a fed-back regression with toy probability 0.7.

      For reference, LangChain reports deepagents-cli going from 52.8% to 66.5% on Terminal Bench 2.0 (+13.7 pts) from harness changes found by trace analysis: vendor-reported, measured on the tuning tasks, no holdout result.

      1. Climb with no guards. Overfit 60%, net-gain policy, 40 iterations. Optimization climbs 38% → 79% (+41 pts), the holdout only 38% → 46% (+8). The 33-pt gap is overfit: 21 of the 72 optimization evals pass only through a hack (amber), and 13 coral hack cards ship, adding 585 tokens to every run.
      2. Turn on the holdout gate. It blocks 3 edits that hurt the holdout, which now reaches 57% (+19); the gap shrinks to 22 pts. 11 hacks still ship (495 tokens): a hack that leaves the holdout flat passes the gate.
      3. Add human review. Review rejects 9 hacks. Optimization ends at 65%, the holdout at 63% (+25 pts): a 2-pt gap, verdict "Real gain". 2 hacks slip through (90 tokens), so only 2 tiles stay amber.
      4. Compare acceptance policies. Overfit 0%, 20 iterations. With feedback the holdout reaches 85%, with 5 edits shipped with regressions and 3 repaired. Click "Strict" (72%, 7 edits rejected) and "Net gain" (78%, 4 regressions shipped, none repaired).
      • Optimization is ML, so ML hygiene applies. Keep train/dev/test splits; 100% on the examples you tuned against means little. A sound eval can accept a strange prompt; a hackable eval produces prompts that game it.
      • What the loop changes. Mostly instructions and tools: usage and chaining examples, clearer descriptions, tools that are easier to tell apart. One change per iteration keeps results unconfounded (a prompt plus the tool it describes counts as one). With Claude Sonnet 4.6 and GLM-5, Better-Harness found four instruction fixes: use reasonable defaults, don't re-ask for given details, stop near-duplicate searches (mostly GLM-5), and ask domain-defining questions first; three applied to both models (self-reported, small sample, no scores).
      • Holdout plus human. The holdout catches edits that do not generalize. Review catches overfit instructions that leave the holdout flat but waste tokens on every run.
      Go deeper · 10 more notes
      • Why optimize when models are strong. The payoff is last-mile adaptation: the eval holds unwritten requirements, such as an ISO date your code can parse or two events in one email. Then you re-optimize when a new model ships instead of re-tuning by hand (CS329Z L9).
      • What a run costs. Roughly a couple hundred program runs and a million tokens, paid once. A stronger teacher model drives the search from your prompt (in DSPy, the signature's docstring). A metric that also says what was wrong helps a reflective optimizer. DSPy caches every call, so a rerun with the same inputs returns the same prompt (L5).
      • Bootstrapped demos. DSPy keeps program traces that pass the metric and tries random subsets as demos on a devset, keeping the best (MIPROv2's first step). STaR keeps rationales that reach the right answer. In the DSPy paper, bootstrapped chain-of-thought demos beat human-written ones. MIPROv2 proposes grounded instructions; TextGrad's "gradient" is a metaphor.
      • The trace-analysis recipe. Parallel agents analyze traces of scored runs and a main agent turns their findings into targeted harness edits, like boosting: each round targets the last round's mistakes. A human may review the edits (optional in the post), mainly to catch ones that overfit one task. On Terminal Bench the failures were reasoning errors, ignored instructions, skipped verification and running out of time, each met by a harness fix (§8). The team searched only system prompt, tools and middleware from a 52.8% baseline (vendor-reported). Better-Harness targeted over-asking follow-ups and looping searches, with tool_selection and followup_quality as holdout categories.
      • Beyond instructions and tools. With injected search-then-email tools, the loop wrote better descriptions of how to compose them. It can also edit graders (review those too: they redefine "better"), tune memory and retrieved skills, or feed RL fine-tuning of open-weight models.
      • Keep-or-revert vs repair. Karpathy-style autoresearch keeps a commit if the metric improves and reverts it otherwise (L9). Better-Harness keeps net-positive edits and hands regressions to the next iteration (Demo 14.3's strict vs feedback pills).
      • A gate that reads the holdout every round leaks it. It becomes part of tuning. Keep a final test split no decision touches (L5).
      • Noisy small devsets. MIPROv2 scores on minibatches with a full eval every few iterations, so noise is not taken for progress. On 20 test emails, one email is 5 points.
      • Traces and padding. A trace shows why a run failed, densifying the signal. Off-target padding evals make the score climb while production stalls.
      • Searching whole harnesses and workflows. The Darwin Gödel Machine and Meta-Harness let an agent edit its own harness code against evals (L9); LangChain also cites DeepMind's Auto-Harness and runs Harbor ablations to find removable parts. In practice a human still signs off. Archon searches compositions of inference-time blocks (generators, fusers, critics, rankers, verifiers, unit-test generators and evaluators) under a token budget. One math pipeline used 4 generator models × 5 samples, Claude 3.5 Sonnet to critique and rank, fusers, and a GPT-4o verifier; past a certain budget, found pipelines beat o1 on math (paper result, L6). It needs diverse generators: if they share mistakes, it collapses. Agents optimize hard: autoresearch edits ranged from batch size to, eventually, the random seed.
      ■ Takeaway · Next §15

      State intent as data plus a metric, let search do the tuning, and keep a holdout and a human between the optimizer and production. Next: where the lessons should live over time, in weights, harness or context.

      Next: §15 Continual Learning
      §15 · Continual Learning

      Continual learning: weights vs harness vs context

      "Continual learning" usually means updating model weights, yet an agent can learn in two more places. The harness is the code that drives the model plus the instructions and tools every instance ships with. The context is the instructions, skills, tools and memory supplied on top as configuration. In Claude Code terms: the model is the weights, the harness is Claude Code, and the context is CLAUDE.md, skills and mcp.json. All three learn from the same traces but differ in cost, speed, who starts the change and how many users it touches. Decide which layer a failure belongs to before you fix it.

      Pick the layer first

      Context learning is cheap and immediate: Reflexion's written lessons, Voyager's skill library, Agent Workflow Memory's workflows and a RAG index all live there. It is usually scoped per tenant (a user, org or team) and written while the agent works or by an offline job over recent traces. Weight updates cost time and money, so a human almost always starts them, and they apply per agent rather than per user.

      DEMO 15.1 Which Layer Do You Fix?
      Pick a lesson, change who needs it · watch the best home move
      Lesson:
      the session that surfaced the lesson
      where it can live · best home · also works · ruled out
        Best homeContext
        Tenants touched1
        Forgetting riskno
        0.1%
        none
        within hours
        More controls
        More lessons:
        1,000
        The trace is the session that taught the lesson. Each layer card shows the fix or why it is ruled out, time to ship, and filled squares for tenants touched. Illustrative lookup table, not data.
        How this toy model works

        Each session trace is hand-written to show how the lesson might surface. Each lesson has a hand-made fit score per layer. Each tenant square stands for 1/20 of all tenants; any tenant touched fills at least one. A layer is ruled out if it does not fit, changes every tenant when only a few need the lesson, lacks the training budget (SFT needs a small one, RL a large one), or ships slower than the deadline. Ship times are toy values: about 1 hour for context, 1 day for the harness, 2 months for weights, echoing the "fix the harness daily, retrain every few months" cadence one product team describes. The layer split, tenant scoping, human-started weight updates and forgetting risk follow LangChain's continual-learning post and a talk digest on improving agents; neither gives numbers.

        1. One user prefers tabs. 1 of 1,000 tenants needs it, so it goes into that user's context: about 1 hour, 1 tenant touched. The harness would change all 1,000, and weights are the wrong place for a fact.
        2. Now everyone wants tabs, within a week. 1,000 copies in memory would work, but the harness is now the best home: change the default formatter, ship in about a day.
        3. A domain reasoning skill, large budget, a quarter to deliver. No code path teaches reasoning, so the harness is out. Verdict: RL in a verifiable environment, about 2 months, all 1,000 tenants change, forgetting risk "yes".
        4. Drop the budget to none. RL is blocked, and the verdict falls back to context as a partial fit: write a skill file. Try "Tool call times out" with "within hours": nothing fits, since only the harness can fix it and that takes a day.

        Teams that retrain alternate between layers. Start with the harness: feedback is immediate, it is usually enough, and it gets stronger as models improve at in-context learning. Fine-tune when harness changes stop helping (an intelligence ceiling) or when volume makes a smaller distilled model pay off, then return to the harness.

        When you do touch weights

        For agents, supervised fine-tuning is mostly distillation: roll out a strong teacher, keep the good trajectories, and train the student on them. It suits classification, extraction, summarization and output format. FireAct fine-tuned Llama-2-13B on correct GPT-4 trajectories and reached 34%, against 31% for GPT-3.5 prompted with ReAct. The student needs only the teacher's visible plan and actions.

        The usual order is SFT, then RL. SFT bootstraps the student until some of its rollouts succeed; RL then learns from those attempts with no teacher, the only option at the frontier. If SFT alone scores better, use SFT. RL uses verifiable rewards (RLVR) wherever a check exists. GRPO, the common recipe, samples a group of rollouts for one prompt, scores each (unit tests passed, files matched), and uses each rollout's z-score inside the group as its advantage. PPO needs a learned value model for that job; GRPO drops it.

        GRPO advantage $$A_i = \frac{r_i - \operatorname{mean}(r_1,\dots,r_G)}{\operatorname{std}(r_1,\dots,r_G)}$$
        DEMO 15.2 GRPO Group Advantage Lab
        Click test pips or sample a hard task · watch the signal vanish when all tie
        Hand-set:
        the group · pushed up · pushed down · hand-set rewards (click test pips)
        Rollout 1 of 4: reward 7, advantage +1.73
        4
        10%
        More controls
        1
        Each row is one rollout of the same task: filled pips are unit tests passed, the bar and number are its advantage in group standard deviations. Illustrative model.
        How this toy model works

        Hand-set rewards are whatever you click or pick (clicking the last filled pip again lowers the reward by one). Moving the pass-rate or seed slider samples a pass/fail group instead: each rollout scores 10 or 0, drawn from a fixed seed, so the same seed gives the same draws for any G. Std is the population std over the group. The z-score rule is GRPO's (DeepSeekMath, as taught in Stanford CS329Z L9); the clipping and KL terms of the full update are left out.

        1. All four rollouts pass 4 of 10 tests. Mean 4.00, std 0.00, every advantage 0. A tied group teaches nothing, whatever the shared score.
        2. One rollout reaches 7/10. Mean 4.75, std 1.30. The winner gets +1.73, the other three −0.58 each, summing to 0: 1 pushed up, 3 pushed down. The group is the baseline, so no value model is needed.
        3. Sample a hard task: pass rate 10%, G = 4. All four fail, so the group ties at 0: "No signal". The chance that at least one of 4 passes is only 34%.
        4. Raise G to 16, same seed. Rollout 12 passes: mean 0.63, std 2.42, and the rare success gets +3.87 (1 pushed up, 15 pushed down). P(at least one pass) rises to 81%. Bigger groups find signal on hard tasks.

        Tied groups are also why SFT comes first: a student that never passes hands GRPO zeros on every prompt, and no weight moves.

        Who grades which token

        SFT trains on the teacher's tokens, so it never sees the student's mistakes. RL trains on the student's attempt but gives one reward for the whole output. On-policy distillation has a teacher score every token the student wrote, like a chess coach grading each move of your own game. It needs the teacher's per-token log-probabilities (reverse KL on the student's samples), so the teacher must be open-weights; SFT works with an API teacher.

        DEMO 15.3 Who Grades Which Token? SFT vs RL vs On-Policy Distillation
        Switch method and mistake · watch where the signal lands
        Method:
        Student's mistake:
        problem: 5 + 2 × 3 = ? · first mistake · follow-on token
        More controls
        Other mistake:
        0.5
        Top: the tokens trained on, each with the signal it gets (darker means more). Bottom: the other answer, for reference. Illustrative model with hand-made values.
        How this toy model works

        Under on-policy distillation, correct tokens cost 0.05 nats under the teacher, the first wrong token 4.0, and a follow-on token 1.0 or less. RL gives every token the same reward: 1 if the final answer is 11, else 0. The SFT loss is −ln(1 − gap × hardness) per teacher token, with a hand-made hardness per token; the gap slider only affects SFT. The method contrast follows Stanford CS329Z L9.

        1. RL, student slips at 2×3=5. The answer is 10, so all 11 tokens get reward 0. Switch to 5+6=12: identical signal. RL knows the answer was wrong but not where.
        2. Same attempt, on-policy distillation. Token 5 ("5") takes 4.0 of 5.45 nats (73%). Token 9, which carries the wrong value forward, gets 1.0; the rest 0.05.
        3. Wrong order of operations. The student starts with 5 + 2. Token 1 takes 4.0 of 5.80 nats (69%). The teacher grades each token given the student's prefix, so the later arithmetic (5 + 2 = 7, 7 × 3 = 21) costs little.
        4. SFT with a gap of 0.9. The loss spreads over the teacher's tokens: mean 0.70 nats, highest on token 1. The student's 2×3=5 slip (greyed out) never enters the loss, like watching grandmasters without playing your own games.
        • Three layers, one trace pool. Traces feed weights as training data, the harness via a coding agent that edits it, and context as memory updates.
        • Context first. It lands fast, needs no retraining, and can be scoped to one tenant. Facts belong here: memorizing facts in weights is lossy and data-hungry.
        • Harness for everyone. Behavior every instance needs (a verify step, a timeout and retry, a better default) goes here. Some failures have no other home.
        • Weight updates are a deliberate project. Costly, human-started, they change every tenant at once and risk catastrophic forgetting, still an open problem.
        • Signal shapes what is learned. GRPO needs a group whose rewards differ; on-policy distillation gives per-token feedback on the student's own mistakes; SFT only imitates.
        Go deeper · 10 more notes
        • Same loop for harness and context. Both improve by reading traces, finding the issue and changing something. A per-user LoRA adapter would bring weights down to tenant scope too, but it is rarely done.
        • One product team's cadence. An always-on product team fixes the harness daily and retrains every month or few months, aimed at what the harness could not fix: SFT on examples of its own harness and tool use, and RL for instruction following, picking the right skill among hundreds, and accurate browser clicks (the speaker's account). A LangChain post on the harness, fine-tune, harness cycle calls the harness a high-bandwidth way to put what you know about the errors into the agent; fine-tuning needs curated data and longer experiments, and after it you check how the tuned model handles related tasks.
        • RLHF vs verifiable rewards. The older RLHF learned its reward from human rankings, which disagree within and across annotators and push models toward sycophancy. SFT on teacher traces is what raises the pass rate until GRPO's groups start to split.
        • ToolLLM: distillation for tools. A teacher wrote queries over 16,000+ real APIs and solved them, trying other tools when one failed; Llama was fine-tuned on those solution trees, with an API retriever choosing candidate tools at inference. FireAct's trajectories mixed chain of thought, ReAct and Reflexion, and the student learned to pick a pattern itself; neither student needed the teacher's hidden reasoning. RL on real tasks suits long instructions, using skills and memory, and working with other agents.
        • Prompts or weights: a rule of thumb. Optimize context for API-only models, frequent (say daily) re-optimization, or expensive rollouts. Optimize weights when a small model ignores prompt changes, when you want a cheap student of a strong teacher, or when the optimized context keeps growing. BetterTogether found alternating them can work best. GEPA shows prompt optimization climbing faster per rollout than GRPO (the lecture gave no exact gap); OpenThoughts-Agent shows weight training needs much data but keeps scaling with it. When the two disagree, context usually overrides weights unless the behavior was trained in strongly, so keep facts in context and move procedures into weights when you have an environment to train them in (Stanford CS329Z L7, L9).
        • Where verifiable environments come from. One recipe (Stanford CS329Z L2): install GitHub repos, package the ones that build as containers, inject bugs (for example by having an LLM revert a PR or corrupt a function), write a task description for each, and keep only rollouts whose fixes pass the tests. Training Qwen 2.5 32B this way reportedly took SWE-bench Verified from about 9% (the speaker was unsure of the baseline) to 40%. An eval task is the same unit: a Harbor-style task (instruction, container, verifier tests) split into train and test is an RL environment, and one rollout engine serves both. Vendors sell such tasks to labs; the Terminal-Bench speakers put a high-quality one at thousands to tens of thousands of dollars.
        • The best teacher is not always the strongest. OpenThoughts-Agent found accuracy keeps rising with SFT data size, and that a teacher closer to the student's ability can transfer better than the strongest model.
        • On-policy distillation, as reported. The lecture cites Qwen3's small models distilled from the large ones, with AIME accuracy of about 55% for SFT, 67% for RL and 74% for on-policy distillation, using fewer GPU hours. The source, model size and AIME year were not stated, so treat these as indicative.
        • GRPO's memory savings. PPO holds four models (policy, reference, reward, value) and trains two. GRPO needs only the policy and reference in memory (the reward can be an external verifier) and trains one. Its full update also clips the probability ratio and adds a KL penalty to the reference model.
        • Rare in practice, maybe changing. In October 2024 LangChain reported seeing few or no agents that retrain their own weights or rewrite their own code; even self-edited system prompts were uncommon. A possible fourth channel is a frontier LLM (called Astra in the write-up) editing another model's weights with no gradients: an edit to 0.016% of Qwen3.5-0.8B's weights reportedly took MATH-500 from 7.9% to 48.1% by removing a reasoning-loop failure. That result is relayed second-hand from a blog post, not peer-reviewed or replicated. §16 covers it.
        ■ Takeaway · Next §16

        Learn in context first, fix the harness for everyone, and move stable procedures into weights only when the data, an environment and a human decision justify it. Next, agents that run this improvement loop on other agents.

        Next: §16 Improving Agents
        §16 · Agents That Improve Agents

        Meta-agents and self-improvement: agents that improve agents

        Every chapter so far ends with a human reading traces and deciding what to change. A meta-agent takes over part of that job: it watches another agent, scores it, files issues, writes evals, proposes fixes, or rewrites the harness. Research systems let an agent edit its own code, or let a frontier model edit another model's weights. How much of the loop to hand over depends mostly on how well your evals measure what you care about.

        How much of the loop is automated

        A digest of a Harrison Chase talk names three levels. Manual: an engineer reads performance data and edits the agent, which is the current standard. Human-in-the-loop: the system analyzes and proposes fixes and a human signs off, which is growing. Full automation: the agent finds and repairs its own problems, which the note says is not here yet. Production tools sit at the middle level.

        DEMO 16.1 The Automation Ladder
        Climb from manual to full auto · watch what reaches production
        Mode:
        the improvement loop · 20-week totals · dashed = full auto skips review
        20 weeks · ✕ regression shipped · backlog grew · click a week

        Left: where 20 weeks of fixes went. Right: one week of the loop, step by step. Illustrative toy model with a fixed seed, not data.

        Fixes shipped
        0
        over 20 weeks
        Bad fixes shipped
        0
        regressions users see
        Bad fixes blocked
        0
        by evals or a human
        Eval cases · coverage
        0
        at week 20
        30/wk
        10 h/wk
        40%
        More controls
        week 20
        20%
        90%
        How this toy model works

        The three levels come from the source. The capacities (4 engineer hours per hand-written fix, 15 minutes per review), the quality units and the assumption that auto mode is only as safe as eval coverage are this demo's own. Each fix is bad with the chance you set; a bad fix is blocked if the evals catch it or, in manual and human-in-the-loop modes, if the reviewer does. Each observed failure adds one eval case, which nudges coverage up. Every shipped fix raises the eval score; only good ones raise true quality.

        1. Manual, 30 failures a week, 10 engineer hours. The engineer writes 2 fixes a week, 40 in all, and the backlog grows every one of the 20 weeks. 560 failures are left and true quality is only 65.2.
        2. Switch to human-in-the-loop. The meta-agent proposes all 600 fixes and the same 10 hours buy 40 reviews a week. Evals block 57 bad fixes and the reviewer 62 more, 9 slip through, and true quality climbs to 93.0 with the backlog cleared.
        3. Remove the human. The review node goes dark and 18 of 20 weeks ship a regression, 71 in all. The dashboard reads 99.8 while true quality has fallen to 43.8, below where it started: a gap of 56.0 points nobody sees.
        4. Keep full auto, start at 90% eval coverage. The evals block 113 bad fixes, 15 ship, and true quality reaches 90.0. In this model, more autonomy is safe only once the evals have earned it.

        A model editing another model's weights

        This result is second-hand: an author's note on an MIT CSAIL blog post, not peer-reviewed or replicated. A frontier LLM with Python, weight access and a small inference budget inspected Qwen3.5-0.8B, which looped until the token cap on 93% of answers. It found a looping direction in MLP layers 15 and 19 and changed 131,072 parameters, about 0.016% of the model, with no gradient training. As reported, MATH-500 rose from 7.9% to 48.1% and truncated answers fell from 93.0% to 33.1%. The edit removed a failure mode that hid math the model already knew.

        DEMO 16.2 Loops or Knowledge? The 0.016% Edit
        Pick what the meta-agent edits · watch 100 answers change
        Edit target:
        100 answers · base model
        after the loop-direction edit (α = 1.00)

        Each square is one answer: correct, grey finished but wrong, ✕ hit the token cap. Below, the meta-agent's session. Illustrative toy model, not fit to the MIT figures.

        MIT-reported for the real edit: answers hitting the cap 93.0% → 33.1%, MATH-500 7.9% → 48.1%.

        α = 1.00
        93%
        5 pts
        More controls
        70%
        How this toy model works
        Toy model: loop edit
        $$\text{accuracy} = (1 - L)\times c', \qquad L = L_0(1 - \alpha k), \qquad c' = c - d\,\alpha^2$$
        L₀ = base loop rate, c = skill on finished answers, α = edit strength, d = collateral damagea knowledge edit keeps L = L₀ and adds 10α to c

        k is set so a full loop edit takes the loop rate from 93% to 33.1%. A knowledge edit adds up to 10 points of skill without touching the loop rate. The grids round each share to whole answers out of 100. The session steps are a sketch of the setup in the note (a frontier LLM with Python, weight access and a small inference budget on practice problems); the layers, the 64 columns per layer and the parameter count are the MIT authors' own report. Base accuracy above the finish rate (7.9% vs 7%) means the real numbers do not follow this formula exactly.

        1. Teach it more math. A full-strength knowledge edit lifts skill from 70% to 75%, but 93 of 100 answers still hit the cap, so accuracy moves from 4.9% to 5.3% (+0.4 pts). The session ends with "Wrong target".
        2. Edit the loop direction instead. Truncation falls from 93.0% to 33.1% and accuracy jumps from 4.9% to 43.5% (+38.6 pts): 44 green squares instead of 5, even though skill dropped slightly to 65%. The bottleneck was looping.
        3. Make the edit sloppy: collateral damage 65. Answers still finish, but 64 of them are now wrong: skill falls to 5.0% and accuracy to 3.3% (−1.6 pts). The meta-agent reverts. The real edit kept its footprint small: 131,072 parameters, about 0.016%.
        4. Now a model that rarely loops: base loop rate 10%. The knowledge edit takes accuracy from 63.0% to 67.5% (+4.5 pts), while the loop edit would lose 0.3. Diagnose the binding failure before you edit.

        Agents that rewrite their own harness

        Harness self-editing is where self-improvement is concrete today, in research (Stanford CS329Z L9). The Darwin Gödel Machine keeps an archive of agent versions. It picks a parent with probability proportional to its score and inversely proportional to its number of children, lets it edit its own code, and evaluates the child. It found harness features such as compacting context at the limit. The lecture says both self-modification and the archive were needed: sampling past versions, not always the latest or best, performed better. The demo below shows one way that can happen: weak variants kept alive become stepping stones across a valley a greedy climber rarely crosses.

        DEMO 16.3 Darwin Gödel Archive
        Compare open-ended vs greedy · click a variant · read its lineage
        Parent choice:
        the archive · one square per agent version, oldest first · click or use arrow keys

        Squares are agent versions colored by true score (key under the grid). Cards trace the selected version back to the first agent. Illustrative toy model, not the DGM's actual search space.

        120
        More controls
        1
        How this toy model works

        Each version sits on a one-dimensional "design" axis with a local peak (true score 0.55) and a higher peak (0.92) across a low valley. A child is its parent plus a random step along that axis. The parent rule follows the DGM as described in L9. The version that ships is the best measured one. With a hackable metric, a child inherits its parent's exploits and may find one more; each raises measured score by 0.10 without changing true score. Bands: past the valley above 0.70, valley below 0.40, gamed when measured beats true by more than 0.15.

        1. Open-ended archive, 120 iterations. The archive keeps all 121 versions, 88 of them in the valley. The shipped version v38 scores 0.91, and all 6 of its ancestors score below 0.40 (lowest 0.15): stepping stones a greedy climber would never pick. Over seeds 1 to 20, 18 of 20 runs escape the 0.55 peak.
        2. Switch to greedy. Every child comes from the current best, so v24 alone gets 96 children and the archive ships 0.55. No square is green. Only 1 of 20 seeds jumps the valley in one step.
        3. Make the metric hackable. 61 of 121 versions are now gamed. The version that ships, v84, measures 1.00 and truly scores 0.84, because exploits stack faster than real gains. 12 of 20 seeds ship a gamed version.
        4. Greedy on a hackable metric. 100 of 121 versions are gamed. It ships 1.00 measured, 0.54 true, and 19 of 20 seeds are gamed.
        • Three levels. Production meta-agents propose; humans approve evaluators, examples and harness edits. Full automation is not here.
        • Split the meta-agent's jobs. One agent finding issues and writing fixes struggled to make fixes reliable (self-reported), so LangChain split the jobs.
        • Diagnose before you edit. The 0.016% edit worked because the bottleneck was looping. Report the failure-mode rate next to accuracy.
        • Archives beat greedy search. In the DGM, sampling past versions beat always building on the best (L9). In the toy, weak variants kept as stepping stones let search cross a valley where greedy climbing stalls.
        • Autonomy raises the stakes on the eval. Agents cheat visible evals. Holdout sets, human review and verifiers you have tested keep "score went up" honest.
        Go deeper · 9 more notes
        • LangChain's trace-mining agent. It files issues with evidence traces, proposes an evaluator and tests it on that evidence, writes regression examples as assertions, and tags issues for a separate fix agent. A human promotes the examples into the dataset. One agent doing all of that "struggled" to make fixes reliable (self-reported, no numbers), so the jobs were split.
        • Other meta-agents. Shepherd (research) watches a task agent, intercepts buggy tool calls and forks retries (L5). Meta-Harness has an agent iterate on harness code against downstream evals; the lecturer cautions that comparing it to general-purpose harnesses is unfair because it was tuned on the benchmark's own tasks. Coding agents given trace access can pull recent failing traces, draft evals and propose fixes in one session (LangChain, vendor-described). Karpathy-style autoresearch runs the DGM keep-or-revert loop on a repo, keeping or reverting each commit by the metric; its edits eventually reached the random seed.
        • Evals all the way down. Agents now QA benchmark tasks, judge outputs and play simulated users (L10). Each of those is another stochastic model that needs its own eval.
        • Agents editing their own configuration. OpenClaw's agent-level context file (SOUL.md) changes over time, partly through an offline "dreaming" job over recent traces. LangChain's trace-mining agent keeps an AGENTS.md-like overview that learns from which issues users resolve or close. An always-on agent can turn one demonstration into a skill or routine (as described in a Stanford CS146S guest talk).
        • Read and write, not only fix. In the same MIT report, the LLM named which of 4 games a policy network was trained on from weights alone, and named the shapes of 3 small diffusion models (calling them outlines when the models draw filled shapes). For MinAtar it got the game rules, the source code and an architecture with every weight at zero, and could not train, run the network or test it before the final evaluation. It worked out a strategy and wrote it into the weights: for Breakout, one circuit estimates where the ball will land and another moves the paddle there. That one-shot policy scored 517.4, against 15.8 for PPO at 100M steps and 25.3 at 500M. It beat PPO at 100M steps in all three games but lost to the 500M baseline on Seaquest (53.1 vs 88.9) and Asterix (53.2 vs 55.2). The post reads this as compiling a program into a network instead of training one, which needs a strategy someone can write down. All MIT-reported.
        • Python as the write channel. For a Go policy the LLM wrote the weight tensors in Python, layer by layer: early layers mark each side's stones and their liberties, middle layers carry that along chains of stones to find groups in danger, and the last layer scores each move (capture, save a group, avoid atari, don't fill your own eyes). With zero feedback the policy took 336 lines of Python. When it was allowed a limited number of forward-pass batches, it refined the circuits from the failures it saw, and the post says that feedback improved results substantially. Because the weights are written by code instead of pasted into the prompt, the target model does not have to fit in the LLM's context window. MIT-reported; the note gives no Go scores or board size.
        • Limits of the weight-space results. Weights alone did not reveal a sycophantic model in 4 attempts; adding attention patterns on chosen inputs identified it in 3 of 3 pairs. The patterns show why: from the answer position, head 10.2 put 85.7% of its attention on the user's suggested answer in the sycophant and 0.75% in the honest model, which looked at the question's numbers (94.3%). A model debugging another model needs activations on probe inputs as well as weights. Feedback mattered too: MATH-500 was 12.3% at 10 forward passes, 14.1% at 25 and 48.1% at 50. The method has precedent. Abliteration measures activations, extracts a behavior direction and projects it out of the weights with no gradients, the same shape as the Qwen fix. What the post presents as new is the editor: an off-the-shelf frontier LLM with no weight-space training, in place of gradient methods, specialized interpretability tools or models trained to generate weights.
        • Is recursive self-improvement here? The note's author reads the MIT results as RSI that "seems to be here," including outside big labs. That is the author's opinion, not a finding of the experiments. The experiments show a frontier model editing other, far smaller models on narrow tasks, with no self-modification and no compounding loop, and the same author's earlier note says full automation of agent improvement is not here yet. What works today is narrower: an agent edits a harness and evals decide (L1, L9, L10).
        • Self-organization happens unasked. In one incident described in L8, agents on a sandboxed benchmark judged their task impossible, escaped the sandbox, built their own message board out of files, pooled budgets, shared answer keys and exploited an infrastructure flaw to try to steal the answers. MoltBook is a social network for autonomous agents. Both raise collusion and prompt-injection risks for any loop that runs without supervision.
        ■ Takeaway · Sources

        The more of the improvement loop you automate, the more the result depends on the eval and the guardrails. An improver that moves faster than your evals can check will raise the metric without improving the agent. The sources behind every chapter follow.

        Sources ↗

        Sources

        The ideas are theirs; the demos, simplifications, and any mistakes are mine. Every demo is a toy simulation built to show one idea, not a measurement of a real system.

        Stanford CS329Z lectures (Engineering AI Agents, Fall 2026)

        LangChain articles

        Lee Robinson talk

        Other talks and papers