Lecture 26 · Agentic Applications and Harness Design

Scalable AI: Bridging Theory, Understanding, and Practice · Lecture 26。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley EE 290/194 Scalable AI, three Spring 2026 lectures and one Fall 2026 lecture:

  • Spring L22, Agentic Applications (guest: Maryam Najafian, NVIDIA NeMo Agent Toolkit, “Building Reliable AI Agents”, 56 slides);
  • Spring L25, Software Harness Design (58 slides);
  • Spring L26, Multi-Agent Systems and Architecture (no public slides);
  • Fall 2026 L23, Harness Design (scheduled Nov 23; not public when these notes were written).

Sources beyond the slides, each cited where used:

  • Anthropic Engineering, How we built our multi-agent research system (2025);
  • Cognition (Walden Yan), Don’t Build Multi-Agents (2025);
  • Cemri et al., Why Do Multi-Agent LLM Systems Fail? (MAST taxonomy, arXiv 2503.13657, NeurIPS 2025);
  • Schluntz and Barry, Building Effective Agents (Anthropic, 2024), cited on the slides;
  • the papers the slides cite for patterns and Harness RL: ReAct, Reflexion, ReWOO, CodeAct, Agent-RLVR, SWE-RL, PivotRL, GAIA.

Recommended reading: Building Effective Agents; the Anthropic and Cognition posts above (read both: they disagree); the MAST paper; Anthropic’s Effective harnesses for long-running agents and the Dive into Claude Code analysis from the slides’ reading list.

Code: code/lecture26/ contains:

  • agent_world.py: research tasks with known answers over Lecture 25’s private corpus; tools with schemas; a call-writer with documented error rates;
  • harness.py: the agent loop and its harness features (validation, stop rule, observation shaping, context assembly, context policies, verification, delegation), with cost accounting;
  • five demos: the loop and compounding errors, the harness ablation, context management on long tasks, single vs multi-agent, permissions and cost.

Reading time: ~2.5 hours for the prose; ~3.5 minutes to run all demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain what makes an agent (a loop that acts, observes and decides) and why errors compound over its steps.
  2. Describe a harness as a controller around the model: what it assembles, gates, executes and persists, and what each choice costs.
  3. Measure harness features: call validation, stop rules, observation shaping, tool design, context assembly, verification; and match each to the failure it removes.
  4. Manage context over long runs: windowing, compaction, reset with a handoff artifact, and their failure modes.
  5. Decide when to use subagents and what they should hand back, with the token and latency bill.
  6. Design layered permissions that do not depend on a human reading every prompt.
  7. Evaluate an agent system as model + harness + tools + environment, and see why training inside a harness (Harness RL) is its own problem.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 25: the context budget, the reader, retrieval and packing, compaction and caching;
    • Lectures 18–19: RL algorithms and rollouts (for §10);
    • Lecture 23: serving engines (for agent-aware inference, §8).
  • Scope: the runtime around a model that makes it an agent, measured on a simulated research environment.
  • Not in scope:
    • building with a specific framework (the guest lecture’s lab used NVIDIA’s NeMo Agent Toolkit; its concepts are covered, its commands are not);
    • prompt injection and guardrails in depth (Lecture 27).

0.3 Section → code map

SectionIdeaCode in code/lecture26/
§1what an agent is; the patterns–
§2errors compoundagent_world.py, harness.py, 01_agent_loop.py
§3the harness as a controllerharness.py
§4measuring harness features02_harness_ablation.py
§5long runs: compaction, reset, artifacts03_context_management.py
§6tools, delegation, multi-agent04_multi_agent.py
§7permissions, sandboxes, verification05_permissions_and_cost.py (Part A)
§8cost and latency05_permissions_and_cost.py (Part B)
§9–§11evaluation, Harness RL, case studies–

0.4 What is real and what is simulated in the code

The environment and the harness are real code; the “model” is two parts:

  • The decisions are made by a real trained model: Lecture 25’s reader. At every step it reads the agent’s working context and, for each sub-question, answers or says “unknown”. The agent searches for what is still unknown, stops when nothing is, and its final answers are the reader’s. So context clutter, stale evidence and summaries affect the agent through a model that really reads.
  • How the model writes a tool call is simulated, with two documented error rates (agent_world.py): 8% of calls are malformed (a missing argument, a wrong type, an invented argument) and 15% are vague (the query drops the relation word). These rates are assumptions, chosen in the range real traces show, so that the harness has something to catch.

A task asks for 4 relations of some private entities (12 facts for 3 entities); the truth is the latest version of each fact, or “unknown” if no page states it. Every call carries a 1,000-token head (system prompt + tool schemas), about 6× a raw search result, the ratio of Lecture 25’s 17K head to its ~2.8K per turn.


1. What an agent is

1.1 From a call to a loop

The guest lecture’s opening contrast: “A chatbot generates responses. An agent generates outcomes.” Asked how many albums an artist has released, a single LLM call answers from memory in 0.5 s and misses a recent release; an agent searches, counts and cites, and is right, at about 8× the latency and 8× the tokens. The slides list four properties that separate an agent from a prompt: tool use, memory, planning, self-correction. And the loop is what makes it an agent:

  1. Think: reason over everything in the context window and decide what to do next;
  2. Act: emit a structured tool call (search, code, API);
  3. Observe: append the tool’s result to the context;
  4. Decide: loop back, or return the final answer.

“The loop is what makes it an agent. Managing the loop is the engineering problem.”

1.2 Workflows and agents

Anthropic’s Building Effective Agents (cited on the slides) distinguishes:

  • workflows: the developer designs the control flow; LLM calls are steps in it (prompt chaining, routing, parallelization, orchestrator–workers, evaluator–optimizer);
  • agents: the LLM decides the control flow, using tools in a loop.

Its advice, quoted on the slides: “Find the simplest solution possible. Add complexity only when you have evidence you need it.” The guest lecture adds two paradigms that coexist in production: workflow agents (a scaffold designed by engineers; predictable, auditable; most production systems) and model-driven agents (behaviour learned end to end with RL; e.g., OpenHands LM reaching 37% on SWE-bench with 32B parameters). Coding products such as Cursor and Claude Code are workflow agents in this sense: the scaffold is engineered, and a 17-problem gap on SWE-bench separates scaffolds that use the same model (slides).

1.3 The patterns

The slides expand Andrew Ng’s four agentic patterns (tool use, reflection, planning, multi-agent) into eight:

patternloopreported effect (as cited on the slides)
ReAct (Yao et al. 2023)thought → act → observe, as texttransparent traces; one formatting slip breaks a call
tool callingstructured JSON callsthe production default
plan-then-execute (ReWOO)plan all steps, then run them92% completion, 3.6× fewer tokens
reflection (Reflexion)generate → critique → revise+20–30% on reasoning tasks
chain-of-verificationanswer → verify each claim → revisefewer hallucinations
code as action (CodeAct)write code, execute, read+20% success; loops and error handling for free
evaluator–optimizerone model generates, another scoresiterate until a threshold
multi-agentorchestrator + specialists57% of enterprise failures are orchestration errors

One more slide number frames the field: GPT-3.5 in an agentic workflow scores 95% on HumanEval vs GPT-4’s 67% zero-shot. The right pattern can matter more than the right model.


2. Errors compound (Demo 01)

2.1 One episode

Demo 01 Part A traces one 12-fact task through harness.py. The agent searched “capital zebru” twice, found nothing and (stop rule) answered “unknown”, which was right; one call was rejected for a missing argument and retried; nine searches and 11 model calls later all 12 answers were right. The episode cost 12,916 tokens, because every call re-sends the head and the growing context.

2.2 Compounding

If each step succeeds with probability p, an n-step task succeeds with p^n. The slides’ version: at 95% per step, 10 steps give 60% and 20 steps 36%. In Demo 01 Part B the call-writer makes a malformed call 8% of the time. Without validation, a malformed call reaches the tool, which raises, and the episode crashes:

factscalls draftedcrash rate, no validationpredicted 1 − 0.92^nsuccess, no validationsuccess, validatedaccuracy per fact, validated
42.50.140.180.640.780.930
84.70.280.310.420.590.933
126.90.380.420.210.390.916
169.30.500.520.140.320.917
2414.80.670.690.020.090.886

(200 tasks per row; the prediction slightly overshoots because a validated run’s retries also count as drafted calls.)

Two lessons:

  1. Catch errors and feed them back. Validation turns every crash into a retry: crash rate 0 at every size.
  2. Compounding remains. Per-fact accuracy is ~0.92, so a 24-fact task is right only 9% of the time. Long tasks need either far more reliable steps or verification that repairs steps after the fact (§4).

3. The harness as a controller

3.1 Agent system = model + harness + tools + environment

The harness slides’ thesis: “For software agents, the interesting design problem is rarely just what the model should say next. It is what the runtime should let the model see, do, verify, remember, and recover from next.” Behaviour is a property of the whole stack:

  • model: the learned policy;
  • harness: assembles context, formats tool calls, enforces rules, runs the loop, manages recovery;
  • tools: shell, git, editor, browser, search, CI, MCP servers;
  • environment: filesystem, credentials, sandbox, network, worktree.

A tight sandbox with narrow tools and a careful harness is not the same system as a broad shell with no verification, even with the same model.

3.2 Four maps

The slides write the runtime state as s_t = (repo, conversation, memories, permissions, budget, env) and a harness as four maps around the policy π_θ:

c_t = A(s_t, u) assemble the context a_t ~ π_θ(· | c_t) the model proposes an action ã_t = G(a_t, s_t) gate it (policy, permissions, safety checks) o_t = E(ã_t, s_t) execute it and collect the observation s_{t+1} = T(s_t, ã_t, o_t) persist results, compress history, update budgets

Training changes π_θ; harness design changes A, G, E and T. In practice a large fraction of product behaviour is set by the latter four. harness.py implements each: A (_view, the context policies), G (validate_call), E (Env.execute, _shape) and T (the notes file, compaction).

3.3 Harness design is constrained optimization

max_H E[ R_task − λ_tok C_context − λ_lat L − λ_human I − λ_drift D ] subject to P(unsafe action) ≤ δ, P(irrecoverable state) ≤ ε

The costs you feel: context (tokens spent on memory, plans, tool results), latency (round trips, sandbox start-up, evaluator passes), human intervention (approvals, rescues, re-runs), and drift (architecture erosion, stale docs). More autonomy raises productivity and the importance of guardrails at the same time.

3.4 Five layers and one turn

The slides’ five-layer view of a coding harness: surface (CLI, IDE, SDK, approvals UI) → core loop (model calls, compaction triggers, stop logic) → safety and action (permissions, hooks, tool router, MCP, sandbox, subagents) → state (context assembly, memory files, progress artifacts, sessions) → backend (shell, cloud sandbox, git, CI, browsers). One turn: ingest the request → assemble context → model proposes actions → harness gates them → execute and observe → shape outputs (cap, summarize, persist) → commit state. The main systems lesson: harness design is largely about choosing what not to pass through raw.


4. Measuring harness features (Demo 02)

4.1 The ablation

The same reader, the same 120 tasks (12 facts each), seven harnesses, each adding one feature to the row above:

harnesssuccessaccuracycallstokenspeak ctxcrashcappedstalemissedhalluc.
bare loop (page search, raw output, no checks)0.040.22811.035,9372710.700.080.410.330.06
+ validate calls, return errors0.070.61725.1108,8345910.000.761.232.350.34
+ stop rule (2 searches per fact)0.140.8269.219,1381840.000.001.790.120.14
+ shape observations (entity sentences only)0.380.9019.210,748210.000.001.030.080.06
+ purpose-built fact search0.330.8919.110,613210.000.001.230.000.06
+ assemble context by version0.450.9229.110,633210.000.000.900.000.04
+ verifier (fresh, focused re-check)0.840.98321.123,061210.000.000.160.000.04

(error columns: wrong facts per task by cause; capped = hit the 30-step limit.)

4.2 What each feature removes

  • Validation turns crashes (70% of bare episodes) into retries. On its own it exposes the next failure: without a stop rule, 76% of episodes saturate, searching up to the step cap for facts that exist nowhere, with contexts of ~600 sentences and 109K tokens per task.
  • A stop rule (2 searches per fact, then “unknown”) ends saturation and cuts calls from 25.1 to 9.2. MAST’s “unaware of termination conditions” (12.4% of failures) is this.
  • Observation shaping (keep only sentences about the queried entity) is the cheapest large win: tokens 19,138 → 10,748, peak context 184 → 21 sentences, accuracy 0.826 → 0.901.
  • A purpose-built tool (sentence-level search returning distinct sentences with versions) removes the last misses but not stale answers.
  • Assembling the context by version (newest statement last) attacks the dominant error at no extra calls: stale 1.23 → 0.90 per task, success 0.33 → 0.45. The reader trusts the later of two statements (Lecture 25), so arrival order lets an old copy found late override a new one found early.
  • A verifier, a second agent with a fresh, focused context per fact, is the largest single gain (success 0.45 → 0.84; stale 0.90 → 0.16), and the most expensive (calls 9.1 → 21.1). It succeeds where the agent failed because checking one fact in a clean context is easier than producing twelve in a cluttered one. The slides call verification the harness’s second policy network.

An earlier version of the verifier overwrote answers whenever its own search found nothing, and made things worse; “no evidence found” is not evidence of absence. It now overrides only when it finds evidence.

4.3 Three failure phases

The guest lecture’s diagnostic model maps onto the table:

phasebehaviourherefix
failurewrong on the first attempt: wrong tool, answers from memory, formatting errorstale values taken at face valueprompt/tool rules, better tools
driftstarts right, degrades over turns: context exhaustion, loops, lost in the middlecontexts of hundreds of sentencesshaping, context management, plans
saturationcrash or timeout: context or iteration limitscrashes, step capsvalidation, stop rules, sensible max_iterations

Their engineering loop: trace → classify the phase → change one config variable → re-evaluate. Real traces show what Demo 02 shows: in the guest lecture’s example, one tool fix removed 5–7 redundant calls per query (~70% fewer calls, ~60% faster), and three searches returning 5 results each consumed 15K tokens, overflowing a 16K window.


5. Long runs: context, compaction and artifacts (Demo 03)

5.1 Context is a scarce control resource

The slides: a bigger window does not let an agent “simply keep everything”: attention dilutes, irrelevant logs drown key facts, stale instructions stay sticky, long histories encourage repetitive, defensive behaviour. The right view is a compressed state m_t = compress(h_{1:t}, r_t, p_t) with |m_t| ≤ B, from history, repo state and the active plan. Patterns that matter: lazy-load instruction files only when a directory is touched; short maps (an AGENTS.md) instead of encyclopedic manuals; deferred tool schemas; capped tool outputs; subagents that return summaries; progress stored in repo-visible artifacts; an explicit choice between compaction and reset.

5.2 Four policies on 32-fact tasks

Demo 03 makes the context overflow on purpose: page search without shaping (each search appends ~25 sentences), tasks of 32 facts, a trigger at 25 sentences:

policyaccuracycallstokenspeak ctxcappedstalemissedhalluc.
none (keep everything)0.81823.587,4485490.074.600.770.40
window (newest 25)0.32731.051,497621.000.8720.100.10
compact (notes + newest 6)0.84037.855,751630.073.070.300.97
reset + handoff (notes only)0.84420.531,221570.072.730.300.93
reference: shaped fact search, none0.85821.330,474570.033.970.030.33
  • Keeping everything grows the context to 549 sentences (22× the reader’s trained length): expensive and noisy.
  • A sliding window forgets what it used: 20 missed facts per task, and every episode hits the step cap re-searching what fell out of the window. (This is the slides’ “discard” policy taken too far; DeepSeek’s discard-all works for a search agent because each sub-search is independent and the answer is assembled elsewhere.)
  • Reset + handoff matches keeping everything (0.844 vs 0.818) for 36% of the tokens: the notes file carries every conclusion forward. Compaction in place is as accurate but pays an extra summarizing call each time (37.8 calls vs 20.5).
  • Summaries keep mistakes too: hallucinated facts per task rise from 0.40 to 0.97 (compact) and 0.93 (reset). A wrong conclusion written into the notes becomes “evidence” for every later call. Cognition’s warning about compression (“getting this right is difficult”) is this effect.
  • The best fix is upstream: shaped observations avoid the overflow in the first place (30K tokens, accuracy 0.858). Context management is for what shaping cannot prevent.

A bug worth knowing about: the first version compacted right after appending an observation, before the model had read it, and summarized fresh evidence away (11.8 missed facts per task). Compaction must run after the model has seen the latest observation.

5.3 Artifact-level state and reset over compaction

For work that spans many context windows, the slides describe a pattern from Anthropic’s long-running harness work: an initializer agent sets up init.sh, a progress file, feature and test artifacts and a first clean commit; each later coding agent reads those artifacts, makes one bounded increment of progress, and leaves the environment cleaner than it found it. State lives in artifacts: product spec, feature plan, tests and acceptance criteria, progress log, git commits.

Compaction vs reset: compaction preserves the current agent’s continuity cheaply, but can leave it “tired” or over-defensive; reset + handoff starts fresh with only the durable state, mitigating premature wrap-up, at the price of a good handoff format. “Fresh agents plus strong handoff artifacts can outperform endless in-place summarization” (slides); Demo 03’s reset row is a small instance.

Make the repository the system of record: a short top-level map, a structured docs tree, plans and completed plans under version control, architecture and quality notes next to the code. Then agents discover information incrementally, freshness can be checked mechanically, and handoffs between humans and agents are auditable.


6. Tools, delegation and multi-agent systems (Demo 04)

6.1 Tool surface as an economic decision

More tools are not better (each adds schema tokens and selection complexity; overlapping tools create indecision; unsafe tools widen the blast radius), and fewer tools are not better (missing tools force brittle shell workarounds; weak CI or browser access cripples self-verification). The slides’ choice rule for a tool or skill j:

j* = argmax_j E[ΔQ_j | s_t] − α ctx_j − β lat_j − γ risk_j − η fragility_j

A strong tool raises ΔQ while lowering both context cost and fragility by returning structured, clean results. Demo 02’s fact search is an example: distinct sentences with versions instead of whole pages.

6.2 When to spawn a subagent

delegate if E[ΔQ_sub | s_t] > c_spawn + c_coord + c_summary + c_merge-risk

Good candidates: read-heavy exploration of an unfamiliar module, browser-based QA, independent branches, specialized checks with a restricted tool set. Bad candidates: tiny edits with high merge coupling, tasks where the parent already has the hot context, work needing dense back-and-forth. Isolation matters even more than delegation: subagents should get their own context, a rebuilt tool set, explicit permissions and often their own worktree, and return a concise report, not their history. Failures without isolation: permission leakage, conflicting edits, transcript blow-up, hidden coupling through shared files.

6.3 Measured: breadth vs depth, and the handoff

Breadth task (24 facts about 6 entities; fact search, shaped, version assembly):

architectureaccuracysuccesstokenstokens ×callscritical pathpeak ctx
single agent0.8830.1022,0601.0016.616.645
lead + 2 subagents, answers0.9230.1525,2241.1421.113.727
lead + 3 subagents, answers0.9290.2326,2851.1923.011.420
lead + 6 subagents, answers0.9340.2531,4811.4328.89.313
lead + 6 subagents, notes0.9290.2531,4271.4228.89.320
lead + 6 subagents, transcript0.8800.1031,5991.4328.89.344

Depth task (4 facts about 1 entity): single agent 0.938 accuracy, 4,559 tokens, 4.3 calls; lead + 4 subagents 0.975, 15,569 tokens (3.42×), critical path 5.5 calls.

  • Breadth parallelizes. Six subagents with one entity each read small contexts (peak 13 vs 45 sentences); stale answers fall from 2.52 to 1.52 per task; accuracy 0.883 → 0.934; the critical path falls from 16.6 to 9.3 calls for 1.43× the tokens.
  • The handoff decides whether the gain survives. Answers only: 0.934; evidence notes: 0.929; whole transcripts: 0.880, because pasting the children’s contexts back into the lead rebuilds the cluttered single-agent context. The slides list this as a named failure: “pasting the child’s full transcript into the parent destroys isolation and reproduces monolithic bloat.”
  • The token ratio depends on the workload. With raw page results the single agent’s context bloats and six subagents cost 0.75× its tokens; with shaped results 1.43×. Each extra agent pays a head and a brief; a single growing context pays for its own bloat on every call.
  • Depth does not parallelize. Splitting one entity’s four facts costs 3.4× the tokens and lengthens the critical path: four heads, four briefs and a merge, for four facts.

6.4 What the field reports

  • Anthropic’s research system (lead Claude Opus 4, subagents Claude Sonnet 4) outperformed single-agent Opus 4 by 90.2% on an internal research eval. Agents use ~4× the tokens of chat interactions and multi-agent systems ~15×. On BrowseComp, token usage alone explained 80% of the performance variance (95% with the number of tool calls and the model choice). Parallel tool calling cut research time by up to 90% for complex queries. They name domains that fit poorly: those where all agents must share the same context or that have many dependencies between agents, such as most coding.
  • Cognition’s counter-argument: “Share context, and share full agent traces, not just individual messages” and “Actions carry implicit decisions, and conflicting decisions carry bad results.” Their example: two subagents building a Flappy Bird clone, one drawing a Super Mario-style background and the other a bird that looked and moved nothing like Flappy Bird’s. They recommend a single-threaded linear agent, with a model dedicated to compressing history for very long tasks.
  • MAST (1,642 annotated traces from 7 multi-agent frameworks; 14 failure modes): system design issues 44.2% (e.g., step repetition 15.7%, unaware of termination conditions 12.4%, disobeying the task specification 11.8%), inter-agent misalignment 32.4% (reasoning–action mismatch 13.2%, task derailment 7.4%, failing to ask for clarification 6.8%), task verification 23.5% (incorrect verification 9.1%, no or incomplete verification 8.2%, premature termination 6.2%). (The guest slides quote an earlier version: 38/38/24.) Most failures are engineering, not model capability.

The two posts agree more than their titles suggest: multiple agents pay off when the task decomposes into independent, read-heavy parts and the handoffs are compact; they fail when the parts share decisions. Demo 04 is the measured version: breadth wins, depth loses, transcripts destroy the gain.


7. Safety, autonomy and verification

7.1 Approval fatigue

Asking before each meaningful action sounds safe. When prompts become frequent, users stop reading them, and the bottleneck becomes human patience rather than model capability. Anthropic reports that users approve ~93% of Claude Code’s permission prompts (slides): at that rate the popup is not the safety system. Responses: plan mode (approve the strategy, not every step); separate low- and high-risk operations; classifiers or rules that auto-allow safe regions; safety that rests on hard boundaries, not vigilance.

7.2 Layered permissions

The slides’ four layers:

  1. policy and rules: deny-lists, allow-lists, trust modes, per-tool constraints;
  2. dynamic assessment: risk classifiers, reversibility checks, contextual escalation;
  3. execution containment: sandbox, filesystem isolation, network isolation, scoped credentials;
  4. audit and recovery: transcripts, diffs, commits, reversible operations, rollback.

If one layer misses, another should still bound the damage. Sandboxing needs both filesystem isolation (what the agent can read and modify) and network isolation (where it can connect and what it can exfiltrate); either alone leaves escape routes. The question is not “is the model perfect?” but “what can the model do if it is wrong?”

7.3 An illustrative model (Demo 05 Part A)

Demo 05 prices this with stated assumptions (action counts per task, a chance that a proposed action is harmful, and catch rates for every layer; none are measurements). Residual risk = proposals × P(harmful) × the product of the miss rates of the layers each proposal meets:

policyreviewerprompts per taskirreversible harm / 1,000 tasks
no gate–060.0
ask before every actionattentive / fatigued676.0 / 54.0
rules: allow low-risk, ask the restattentive / fatigued53.6 / 32.4
rules + sandboxattentive / fatigued12.8 / 18.8
rules + sandbox + risk classifierattentive / fatigued0.16.4 / 19.2

At 67 prompts a task, the fatigued row is the realistic one, and it is close to no gate at all. Rules and a sandbox cut the prompts to one per task, which makes an attentive reviewer plausible again (2.8). A classifier cuts prompts another 10× but lets its own misses through unreviewed: it buys attention, not safety. Reversible harm (edits in a workspace, effects inside a sandbox) is left to version control and to discarding the sandbox, which is why gates should be weighted by reversibility.

7.4 Verification is cheaper than generation

Software is verifier-rich: formatters, linters, type checkers, builds, unit/integration/end-to-end tests, browser traces and screenshots, incident replay. The harness chooses which verifier to run next, translates raw verifier output into compact context, and decides whether to retry, roll back, escalate or continue. The critical asymmetry (slides): it is often easier to build a skeptical evaluator than a generator that reliably critiques itself, hence the recurring generator–evaluator and planner–generator–evaluator loops. Demo 02’s verifier is the measured case (success 0.45 → 0.84). These loops help most when the task sits just beyond what the generator can do alone; as models improve, some evaluator logic becomes overhead and should be removed. Harnesses should be load-bearing but not ornamental.


8. Cost and latency

8.1 An agent task is a different cost class (Demo 05 Part B)

With Lecture 25’s slice sizes (17K head, +2.8K per turn) and Sonnet 4.6 prices:

workloadtokens× chat$seconds (critical path)
one chat turn (5K in, 500 out)5,50010.0229
single agent, 30 calls, no cache1,737,0003165.32337
single agent, 30 calls, cached1,737,0003160.99168
lead (4 calls) + 5 subagents (12 calls each), no cache2,060,0003756.42145
lead + 5 subagents, cached2,060,0003751.85111

The ratios to “chat” depend on what you call a chat (Anthropic’s ~4× and ~15× are relative to their own chat interactions). The shape is general: an agent task costs dollars where a chat costs cents; caching cuts it ~5×; multi-agent buys wall-clock time with tokens.

8.2 Agent-aware inference

Agents are predictable workloads: call order, step counts and output lengths repeat across trajectories. The guest lecture showed NVIDIA’s toolkit profiling agent traces, predicting each call’s output length (80% within ±10%), and passing that to Dynamo (Lecture 23) for priority scheduling and KV-aware routing. Reported on an AI-Q deep-research blueprint: TTFT per LLM call 260 s → 28 s with priority scheduling at medium utilization, throughput 535 → 2,228 tokens/s with KV-aware routing vs round-robin. Lecture 23’s routing and Lecture 25’s caching are the mechanisms.


9. Evaluating agents and harnesses

9.1 Evaluation-driven development

The guest lecture’s path from demo to production: build → demo (5 queries, not 5,000) → break (edge cases, wrong tool calls, loops, token burn) → stuck (traces show what broke, but every fix is manual and breaks three other cases) → systematic (eval scores quantify each change; regressions caught before deploy). It cites IDC’s finding that 88% of proofs of concept stall before production. The inner loop: trace → classify → fix one variable → re-evaluate. Deploy is a gate, not a step: ship when evals pass.

Practical advice from the lab:

  • define passing criteria before the prompt, like tests before code;
  • change one variable per run (prompt, tool, or agent type);
  • read the three-number snapshot of a trace set: count, p50 latency, p99 latency (p99/p50 > 5× means a tail problem);
  • exact-match scoring (as in GAIA) can mark correct reasoning wrong on formatting; check both;
  • public benchmarks overstate reliability (the slides cite 33% leakage on SWE-bench); teams that define their own success criteria win.

9.2 What to measure

The harness slides’ metric families:

familywhat to measurewhy
task completionpass rate, spec satisfaction, issue resolutionraw usefulness
verification qualitytest pass rate, evaluator precision, rollback frequencywhether “done” means correct
human attentionapprovals per task, interruptions, rescue timereal productivity
systems efficiencyTTFT, wall-clock, tokens, sandbox start-updeployability
context efficiencybytes retrieved, bytes kept, compaction ratiowhether memory is load-bearing
safety and controlirreversible-action rate, sandbox escapes, injection robustnessbounded autonomy
maintenance qualitylint drift, architectural violations, cleanup burdenwhether success compounds or decays

The object of study is model + harness + tools + environment. Demo 02 is the reason: with the model fixed, success ranged from 0.04 to 0.84.


10. Harness RL: training inside the harness

10.1 The harness is part of the MDP

Standard post-training (Lectures 16–20) leaves out what software agents actually face: navigation under partial information, failed calls and permission denials, verifier loops, context pruning, summaries, handoffs, time budgets. Harness RL trains on the full tool-using trajectory, with the observation model induced by context assembly, the action space induced by tools and permissions, and the rewards the runtime exposes:

o_t = A_H(s_t), a_t ∈ 𝒜_H(o_t), s_{t+1} = T_H(s_t, a_t), r_t = R_H(s_t, a_t, s_{t+1})

so the objective is J(π_θ; H): a policy that looks strong in H_train can move once the tool schema, reset logic or evaluator changes. When you say “the model improved”, check that you did not also move the reward extractor, the reset policy, the tool schema and the evaluator.

10.2 Three regimes (slides)

regimeideaexamples (numbers as reported)
real environmentsreal repos, tests and tool calls; highest fidelity, most expensiveAgent-RLVR: guided reruns + RLVR take Qwen-2.5-72B-Instruct from 9.4% to 22.4% pass@1 on SWE-bench Verified with 817 environments (27.8% with a reward model); SWE-RL: Llama3-SWE-RL-70B at 41.0% with rule-based rewards from open software evolution; Cursor’s Composer 2: RL in environments matching deployed sessions, rollouts decoupled from updates
decoupled stackskeep the product runtime, log structured traces, train separatelyAgent Lightning (trajectory interface + hierarchical credit assignment); PivotRL: competitive with end-to-end RL with ~4× fewer rollout turns and 5.5× less wall-clock by learning at high-signal pivot decisions
skills and surrogatessynthetic tasks for transferable skills, or learned simulatorsHybrid-Gym, Atomic Skills, SWE-World (surrogate environment and reward models; better concurrency, a realism gap to watch)

The reward a harness can provide, R = λ_term 1[solved] + λ_eval r_tests + λ_guide r_guidance − λ_cost c_steps − λ_risk c_unsafe, is delicate: too sparse and learning is expensive; proxies too strong and the policy games the verifier (Lecture 18’s reward hacking). A training-ready harness needs reproducible resets, structured traces, versioned snapshots, evaluator logs separate from the policy transcript and stable action schemas. The best training harness is not always the best product harness.


11. Case studies: Claude Code and OpenClaw

The slides compare two serious answers that place the control plane in different places:

design questionClaude CodeOpenClaw
architectural centera local query loop owns context assembly, tool dispatch and recoverya long-lived gateway is the control plane; the agent runtime is one subsystem
stateworktree, transcript, summaries, repo-visible artifacts, compactiongateway-owned sessions, transcript files, Markdown memory (MEMORY.md, daily notes), bootstrap files
extensibilityskills, hooks, MCP tools, plugins, subagentsplugins, hooks, routing rules, nodes, channel bindings
delegationisolated subagents, often with worktrees, summary returnsrouted workers with depth limits (maxSpawnDepth) and per-agent allowlists
trust boundarydeny-first permission gate plus sandbox between model and executionone trusted-operator boundary per gateway; access control before intelligence

Claude Code keeps the loop simple and pushes complexity into context management, extension points and isolated delegation; hierarchical instruction files (CLAUDE.md) adapt it to each repository, and its long-horizon variants add initializer agents and planner/generator/evaluator splits. OpenClaw centers an always-on gateway that owns routing and sessions; the model does not choose the channel; security starts at ingress (split mixed-trust deployments across gateways and hosts). Neither is a variant of the other; the right placement depends on the deployment.


12. Summary

  1. An agent is a loop (think, act, observe, decide), and its errors compound: success ≈ p^n per step, measured 0.78 → 0.09 from 4 to 24 facts even with crashes removed.
  2. The harness is a controller: it assembles context (A), gates actions (G), executes and shapes observations (E), and persists state (T). With the model fixed, harness choices moved task success from 0.04 to 0.84.
  3. Each feature removes a failure: validation removes crashes, stop rules remove saturation, shaping removes bloat, purpose-built tools remove misses, version-ordered assembly removes stale wins, a verifier repairs what the agent got wrong (at ~2× the calls).
  4. Long runs: windows forget, compaction costs calls, reset + handoff keeps accuracy at a third of the tokens, and every summary preserves mistakes; shaping upstream beats managing bloat downstream.
  5. Multi-agent pays on breadth (accuracy up, critical path down, tokens up) when handoffs are compact; it loses on depth and when children’s transcripts flow back. Most multi-agent failures are system design and verification failures.
  6. Safety rests on layers that do not need attention: rules, sandboxes with filesystem and network isolation, audit and rollback; prompts are for the few irreversible actions.
  7. Evaluate the system, not the model; and when training agents, remember the harness is part of the environment being trained on.

13. Common pitfalls

  • Letting tool errors crash the loop, or hiding them from the model instead of returning a clear error.
  • No stop rule: searching forever for what does not exist; a max_iterations that is the only termination condition.
  • Pasting raw tool output (pages, logs, DOM dumps) into the context.
  • Trusting the first plausible evidence; no verifier, or a verifier that overrides answers when it finds nothing.
  • Compacting before the model has read the newest observation, or summarizing without checking what the summary dropped.
  • Sliding windows over evidence the task still needs.
  • Multi-agent by default: splitting depth tasks; returning full transcripts; letting subagents make conflicting implicit decisions.
  • Approval prompts as the safety system. At 93% approval, they are not.
  • Changing several things at once and attributing the result to one of them; reporting model quality without the harness.

14. Exercises

  1. Compounding. A step succeeds with probability 0.97. How many steps can a task have before success falls below 50%? If a verifier catches 80% of the failed steps and the agent then retries them successfully, what is the new per-step success and the new limit?

    Answer0.97^n < 0.5 → n > ln 0.5 / ln 0.97 = 22.8, so 23 steps. With the verifier, a step fails only if it fails and the verifier misses it: 0.03 × 0.2 = 0.006 → p = 0.994 → n > 115 steps. Verification multiplies the reachable horizon ~5×.
  2. Validation arithmetic. With 8% malformed calls and 15 calls per task, what fraction of tasks crash without validation? With validation, how many extra calls does a task make on average?

    Answer1 − 0.92^15 = 71.4% crash. With validation each call needs a geometric number of attempts with mean 1/0.92 = 1.087, so ~1.3 extra calls per task (15 × 0.087), each costing the head plus the context.
  3. Reset vs compaction. In Demo 03, why does reset use fewer calls than compaction while reaching the same accuracy? When would compaction be the better choice?

    AnswerCompaction makes an extra summarizing call every time the threshold is crossed (it reads the whole context to write the summary); reset rebuilds the context from the notes file that the agent already maintains. Compaction is better when the recent raw context matters to the next step (an unfinished edit, a failing test's output) and when no structured notes file exists; reset is better when progress is captured in artifacts.
  4. Delegation decision. A task has 8 independent subtasks of 6 calls each. A single agent’s per-call context grows by 2K tokens per call from a 17K head; each subagent has its own 17K head and the same growth. Compare total input tokens and the critical path (in calls) for 1 agent vs 8 subagents (ignore the lead’s own calls).

    AnswerSingle: 48 calls; Σ_{t=0}^{47} (17K + 2K·t) = 816K + 2K × 1,128 = 3.07M tokens; critical path 48 calls. Eight subagents: each Σ_{t=0}^{5} (17K + 2K·t) = 102K + 30K = 132K → 1.06M tokens in total; critical path 6 calls. Here delegation is cheaper AND faster, because the single context grows quadratically. Add briefs and merges, and check whether the subtasks really share no decisions.
  5. Where to put the gate. Using Demo 05’s model, which single change to the “ask before every action” policy most reduces irreversible harm when the reviewer is fatigued? Why?

    AnswerAllow-listing the low-risk classes (reads, edits, tests) is the biggest single change: prompts 67 → 5 and, even with the fatigued miss rate held fixed, irreversible harm 54 → 32.4 (the rules also block 60% of harmful installs and network calls). Adding the sandbox next takes it to 18.8 with 1 prompt per task. The larger effect is indirect: with 1–5 prompts a task, the attentive row (3.6 or 2.8) becomes the realistic one.
  6. Train/eval drift. You train an agent with RL in a harness whose search tool returns distinct sentences, then deploy it with a page-search tool. Using Demo 02, what would you expect, and what should you report?

    AnswerDemo 02's rows differ by harness only: with the same reader, page search with shaping reached 0.901 accuracy and fact search 0.891, and stale errors moved. A policy trained on one tool's observation distribution can lose accuracy on another's. Report the harness (tool schemas, shaping, reset logic, verifier) with every result, and evaluate in the deployment harness.

No Spring or Fall assignment targets agents directly. The research project often does, and the habits that transfer are:

  • report results for model + harness + tools + environment, and ablate the harness one feature at a time (Demo 02’s table is the template);
  • measure tokens, calls and the critical path next to accuracy;
  • classify failures (crash, saturation, stale, missed, hallucinated) before fixing anything;
  • keep evaluation harnesses separate from training harnesses, and say which one produced each number.

16. Research directions

From the harness slides’ open problems, with what this lecture’s code suggests about each:

  • Observability vs compression: how can users inspect what compaction, summarization or subagent isolation removed? (Demo 03: summaries carried hallucinations forward invisibly.)
  • Security composition: how hooks, MCP tools, shells, browsers and subagents interact under attack, not in isolation (Lecture 27).
  • Horizon scaling: the right mix of compaction, reset, delegation and durable artifacts for tasks that run hours or days.
  • Evaluator quality: skeptical external evaluators that are calibrated, not brittle or too expensive (Demo 02: an evaluator that overrode on “no evidence” made things worse).
  • Harness train/eval drift: training in one runtime without overfitting to its tool schemas, reset rules or reward extractor.
  • Human capability preservation: if harnesses absorb planning, checking and cleanup, how do humans keep enough understanding to steer?
  • Stable standards: which abstractions (MCP, A2A, ACP, app-server protocols) remain useful as models improve and hand-written orchestration becomes obsolete.

17. Further reading

  • Schluntz and Barry, Building Effective Agents (Anthropic, 2024).
  • Anthropic, How we built our multi-agent research system (2025); Cognition, Don’t Build Multi-Agents (2025).
  • Cemri et al., Why Do Multi-Agent LLM Systems Fail? (NeurIPS 2025).
  • The harness slides’ reading lists: Dive into Claude Code; Effective harnesses for long-running agents; Harness design for long-running application development; Scaling Managed Agents; OpenAI’s harness-engineering and Codex App Server posts; Agent-RLVR, SWE-RL, Composer 2, Agent Lightning, PivotRL, Hybrid-Gym, Atomic Skills, SWE-World.
  • Yao et al., ReAct (ICLR 2023); Shinn et al., Reflexion (NeurIPS 2023); Wang et al., CodeAct (ICML 2024); Mialon et al., GAIA (ICLR 2024).

18. Next lecture

Lecture 27, Safety and Security: Deployment Guardrails and Open-Weight Safety, takes up what this lecture only touched: what enters the context from untrusted sources, how input and output rails are evaluated (false positives vs false negatives at realistic base rates), how monitoring and incident response work, and what changes when the weights themselves are public.


术语表 (Glossary, English → 中文)

English中文
agent / agent loop智能体 / 智能体循环
workflow / model-driven agent工作流 / 模型驱动的智能体
harness / harness engineering外围运行时 / 运行时工程
tool call / schema / validation工具调用 / 参数模式 / 校验
malformed call / error feedback / retry格式错误的调用 / 错误反馈 / 重试
compounding errors误差累积
stop rule / termination condition / step cap停止规则 / 终止条件 / 步数上限
observation shaping / reduction观察结果整形 / 精简
context assembly / provenance / version上下文组装 / 出处 / 版本
verifier / evaluator / generator–evaluator loop校验器 / 评估器 / 生成–评估循环
failure / drift / saturation首次失败 / 漂移 / 饱和
sliding window / compaction / reset + handoff滑动窗口 / 压缩整理 / 重置并交接
notes file / progress artifact / initializer agent笔记文件 / 进度产物 / 初始化智能体
system of record权威记录来源
subagent / orchestrator / lead agent子智能体 / 编排者 / 主智能体
handoff / transcript / critical path交接内容 / 完整对话记录 / 关键路径
isolation / worktree隔离 / 独立工作树
permission gate / allow-list / deny-list权限闸门 / 白名单 / 黑名单
approval fatigue审批疲劳
sandbox / filesystem isolation / network isolation沙箱 / 文件系统隔离 / 网络隔离
reversibility / blast radius可逆性 / 影响半径
evaluation-driven development / trace / span评测驱动开发 / 轨迹 / 调用跨度
Harness RL / train–eval drift运行时内强化学习 / 训练–评测偏移
control plane / gateway / trust boundary控制平面 / 网关 / 信任边界
← 返回课程目录