@shao__meng: https://x.com/shao__meng/status/2125124722216276171
Summary
An in-depth review of the 203-page "The Little Book of Agent Engineering," systematically covering Harness Engineering beyond the model itself: agent loops, autonomy levels, long-horizon error detection, tool interface design, context management, and the core content of all 11 chapters, along with a teaching implementation called miniagent in about 400 lines of Python.
View Cached Full Text
Cached at: 11/24/26, 09:20 AM
How the 203-Page “Little Book of Agent Engineering” Explains Harness Engineering Beyond the Model in 11 Chapters
An Agent fixing the bug in an example doesn’t mean it can reliably handle a real repository. It may pick the wrong file on the second attempt, start calling the same tool repeatedly from the tenth attempt, and forget the original constraints once the task gets longer.
https://www.dropbox.com/scl/fi/gh4pjn4kqhlhi71cst3gv/Agents_intro.pdf?rlkey=wc3xtehslitfynkbut5l3vitx&st=liwoc9kr&e=2&dl=0
After reading @__paleologo Gappy + Agents’ “The Little Book of Agent Engineering”, this 203-page slim volume pulls these seemingly scattered problems into a single engineering framework: the model chooses the next step, while the surrounding program provides information, constrains actions, executes operations, preserves state, and determines whether the task is truly complete.
The book uses harness to refer to this runtime and control system that sits outside the model. For most development teams working with off-the-shelf models, this is precisely the part they can improve the most.
The book’s 11 chapters cover the model interface, the Agent loop, tools, context, retrieval and memory, long-horizon tasks, multi-agent systems, security, and evaluation — combining engineering principles and a survey of existing research, along with a teaching implementation, miniagent, in roughly 400 lines of Python.
I think its most valuable question to discuss is: once the underlying model is fixed, what system designs remain that can make Agents more reliable, cheaper, and more controllable?
1. The Starting Point of Agent Engineering: The Model Proposes Actions, the Program Decides Whether They Happen
The book’s definition of an Agent is quite specific: the model repeatedly selects actions, the program executes them, feeds observations back to the model, and this continues until the model ends the task or the budget runs out.
By this definition, calling a model once is not an Agent. A call chain with pre-fixed steps is a workflow. The key difference between the two is who decides the next step.
A complete Agent loop consists of these parts:
| Component | Responsibility | Typical Engineering Problem |
|---|---|---|
| Model π | Selects actions given the current context | Which model to use, and how much reasoning budget? |
| Loop | Orchestrates actions, processes observations, ends the run | How to handle truncation, timeouts, budget exhaustion? |
| Tools & environment | Provide executable operations and their feedback | What information to return, which side effects to allow? |
| Context builder φ | Decides what the model sees this turn | What to keep, delete, or retrieve? |
| External storage M | Persists logs, files, memory, and progress | How to recover information, how to update stale content? |
| Permission check g | Allows, asks about, or rejects actions | Which operations require approval? |
| Evaluator R | Checks the final result | The Agent says it’s done — is it actually done in the environment? |
In its simplest form, the context is first built as cₜ = φ(hₜ, M), then the model proposes the next step from the action distribution π(·|cₜ). Only after passing the permission check does the tool execute.
There’s a fact that product demos tend to obscure: the model itself never executes tools. It generates a call request. Validating arguments, checking permissions, actually running the tool, and returning results are all done by the surrounding program.
So fixing Agent failures shouldn’t start and end with swapping the model or tweaking the prompt. Failing to find a file may be a problem with the search interface; finding it but not understanding it may be because the tool output was truncated; declaring success when nothing succeeded may be a gap in termination conditions and verification.
2. Decide How Much Autonomy You Want First, Then Discuss Frameworks
The book lays out the architecture progression: ordinary programs, workflows, routers, Agents, multi-Agent.
The further you go, the more the model determines the control flow. Flexibility increases accordingly, while predictability, debuggability, and cost control typically degrade. Real products often mix these structures — for example, one step in a fixed workflow handled autonomously by a small Agent.
To judge whether an Agent is worthwhile, answer 4 questions first:
-
Can the execution path not be written out in advance?
-
Can the result be verified through environment feedback?
-
Are errors cheap and recoverable?
-
Is the task valuable enough to cover the latency and inference cost?
Code repair suits Agents, and that’s exactly why. Locating the problem often requires on-the-spot judgment; tests provide feedback; working copies can be rolled back; fixing a real issue is usually worth several rounds of calls.
Conversely, converting a fixed CSV into a fixed-layout PDF every night needs nothing more than an ordinary program. Routing customer service emails into 5 queues may be enough for a router. Having the model re-decide at every step only adds uncertainty for no reason.
The book’s discussion of Agentless and SWE-agent also shows that the same task can adopt different architectures. The former organizes localization, candidate patches, and tests into a fixed pipeline, while the latter lets the model explore step by step. Which one is better depends on task coverage, cost, and debuggability.
For development teams, the principle worth holding onto: choose the lowest level of autonomy that solves the problem, and provide evidence of benefit for any additional autonomy.
3. Why Long Tasks Fail: The Key Is Detecting and Fixing Errors
The book uses a simple calculation to explain why long tasks are hard.
Assume each step is correct with probability r, steps are independent, and any single error causes the task to fail. The success rate over T steps is r^T.
| Overall success rate | Single-step accuracy | Result |
|---|---|---|
| 99% correct per step, 100 consecutive steps | ~36.6% | |
| 95% correct per step, 50 consecutive steps | ~7.7% | |
| 95% correct per step, 50 steps, 90% of errors detectable and fixable | ~77.8% |
The third row introduces a detection probability d. If all detected errors can be fixed, the true per-step fatality rate drops from 1−r to (1−r)(1−d), and the overall success rate becomes approximately [1−(1−r)(1−d)]^T.
This is an idealized calculation. In reality, errors are correlated, repairs consume budget, and verifiers may miss or misjudge. 77.8% should not be taken as a real-world experimental score for an Agent.
But the example clearly shows why verification tools matter so much. Improving the model’s per-step capability is one path; improving error detection and making repair possible can also dramatically change long-horizon performance.
The book roughly ranks verification signals as: deterministic type and format checks, executable tests with clear expected answers, model review against a rubric, and self-reflection that introduces no new evidence.
Each method has scope limits. Type checking cannot prove business correctness; tests are constrained by coverage; model review needs human-annotated samples for calibration. Simply asking “are you sure?” adds no new evidence to the system, and correcting an error may just create a new one.
Therefore, task requirements should be written as checkable completion conditions wherever possible. For example, “fix the issue exposed by test_stats.py without modifying the tests” fits a reliable execution loop far better than “clean up the code.”
4. The Tool Interface Directly Affects Model Performance, and Error Messages Matter Especially
The running example throughout the book is fixing trailing_mean(xs, w). It should return the backward-looking sliding mean at each position, but the implementation incorrectly takes the window forward.
With input [10,20,30,40] and window size 2, the correct result is [10,15,25,35]. The buggy implementation returns [15,25,35,40].
The teaching example’s execution order: run the tests, read the source with line numbers, change xs[i:i+w] to xs[max(0,i-w+1):i+1], run the tests again, then explain the fix.
This trajectory was deliberately replayed using a scripted model. It’s used to check that the execution system works as expected — it does not prove a real model would make the same choices.
More reusable is the tool design:
-
File reads return line numbers, making references and localization easy.
-
Search returns
file:line: text, so hits can be opened directly. -
Test output starts with PASSED or FAILED, reducing the risk of being buried in long logs.
-
The edit tool requires the old string to appear exactly once; otherwise it rejects the change and suggests adding more locating context.
-
Large outputs support pagination and filtering, and truncation is explicitly announced.
“Found 3 matches, please provide more context” is a useful observation. Silently editing the first match, on the other hand, can let an error propagate in a successful state.
Tool granularity also requires trade-offs. A general-purpose Shell is flexible, but the permission system has to deal with free-form text commands. Dedicated tools like restart_service(name) or edit_file(path, old, new) make argument validation, scope restriction, and auditing much easier.
MCP solves tool discovery and invocation protocols; Skills load operational procedures on demand. The former does not automatically grant authorization, and the latter does not need to keep all instructions resident in context. The more tools there are, the more important it becomes to distinguish “what the system has connected” from “what should be exposed to the model this turn.”
5. Context Management Is Primarily an Information Selection Problem
What the model can use at each step depends on what the current request provides. The system may store a complete log, but that doesn’t mean the model saw the complete log this turn; the model may have read a file once, but that doesn’t mean the file still exists in the current context.
The book treats context as a finite budget: system instructions, tool definitions, history, retrieved material, and reserved output space all compete for the window.
A larger window does not mean you should fill it. Irrelevant files cause distraction, and pre-edit test logs become stale evidence. The book cites Lost in the Middle, RULER, and Context Rot to discuss the gap between the nominal window size and the actual ability to use information.
It also cites a study of coding and math Agents: in the raw context, tool observations account for about 84%, reasoning about 10%, and actions about 6%. These proportions correspond to specific research tasks and can’t be generalized as a fixed composition for all Agents — but they indicate what to optimize first: check the large volume of tool output before worrying about compressing every sentence of prompt.
The book divides context reduction methods into 4 categories:
| Method | Concrete approach | How to retrieve information |
|---|---|---|
| Bound | Tools paginate, filter, and limit return volume at the source | Request more precise content when needed |
| Elide | Replace older long results with short placeholder notes | Retrieve from records or re-call |
| Offload | Write intermediate results, plans, and notes to files | Keep the path, read on demand |
| Compact | Replace long history with summaries and continue | Summarized information is no longer directly visible |
The first few preserve the path to retrieving material and should be preferred. Summary compression explicitly needs to protect the task goals, permission constraints, completion conditions, failed attempts, and next steps.
There’s also an engineering detail here: re-running a tool does not necessarily recover the original observation. External pages change; code gets modified. For content requiring precise traceability, keeping the original result and version is safer than “re-reading it later.”
Context cost is also worth calculating. Assume fixed prompts and tool definitions take c₀ tokens, each step adds Δ tokens that are carried forward thereafter. Using the book’s approximate count, cumulative input over T steps is Tc₀ + ΔT(T+1)/2.
With c₀ = 5,000, Δ = 2,000, and T = 50, cumulative input is about 2.8 million tokens. This figure describes the logical input volume under uncompressed history; the actual bill also depends on cache pricing and hit rates.
Therefore, stable prefixes and append-only history are very valuable. Rewriting the timestamp in the system prompt at every step, or arbitrarily reordering tools, can break downstream caching. On the other hand, frequently deleting and rewriting old results also affects the cache; batch compression is often worth testing over reorganizing at every step.
6. Retrieval Reads, Memory Writes — Evaluate the Two Paths Separately
In the book’s framework, external storage has two paths: retrieval feeds material into context, and memory decides what to save for the future.
Fixed RAG retrieves once before generation, suited to queries with clear boundaries. Agentic retrieval turns searching and opening documents into tools — the model can refine queries and follow citations, which suits answers requiring multi-step exploration, at the cost of more calls and more complex stopping conditions.
Search methods should also match the material: exact function names and error text suit keyword search; semantic paraphrasing suits vector search; hybrid search can merge rankings via Reciprocal Rank Fusion (RRF), then use a reranker to filter a small set of candidates.
RAPTOR and GraphRAG address a different problem: answers distributed across an entire document or multiple documents, where a single text chunk can’t carry the summary. Hierarchical summaries and graph structures help aggregate, but index construction adds model calls. Such failures should first be discovered through evaluation before introducing more complex indexing.
The book warns that wrong final answers can occur in at least 3 places: the material wasn’t retrieved; the material appeared but was misread or ignored; or one bad retrieval changed the direction of subsequent exploration.
So recall@k, Mean Reciprocal Rank (MRR), and final answer quality must not be conflated. Citation checking also has at least two layers: whether the cited document was actually read, and whether the document supports the specific claim.
Permission filtering should happen at the retrieval stage. Handing unauthorized material to the model and then asking it not to leak it puts the boundary in the wrong place.
Memory likewise needs provenance, versioning, and update mechanisms. Preferences, project facts, failure lessons, and operational procedures all have different lifespans. The book borrows working memory, episodic memory, semantic memory, and procedural memory to distinguish these, but the taxonomy itself does not guarantee that memory is effective.
For engineering teams, more practical questions are: will this information genuinely be needed in the future, can it be re-derived from source material, how is it updated when conflicts arise, and have requirements from malicious documents been mistakenly stored as long-term rules? A searchable file is sometimes already better suited than a dedicated memory system.
7. Long-Running Execution Needs Progress Handoff — and Handling Uncertain States of Side Effects
After an Agent spans multiple context windows, it needs a mechanism that lets successor sessions continue the work.
The book borrows from practices in long-running coding Agents: during initialization, establish the environment, a goal checklist, and a startup script. Subsequent sessions read the progress record and version history, validate the inherited state, complete one bounded goal, and leave verifiable progress.
The most important point here: goals can only be marked done once they pass verification. A “completed” in a progress file that still comes only from the model’s own judgment is no more reliable than a promise in a conversation.
Program crashes and network timeouts introduce another problem: the request was sent, but no confirmation arrived — did the operation actually happen?
For reads, retries are usually easy to handle. For sending emails, publishing reports, or making payments, blind retries may execute duplicates. The book recommends recording a pending state before execution and using an idempotency key recognized by the target service. Retries should reuse the same logical operation’s key; when the service doesn’t support idempotency, query the target state to verify.
After a lost confirmation, the correct state is unknown. Only evidence from the target side can determine the next step.
Checkpoints can resume the Agent loop, but they cannot automatically prove that external side effects occurred only once. This class of problem ultimately still requires the state recording, idempotency, and reconciliation mechanisms found in distributed systems.
8. The Direct Value of Multi-Agent Is Context Isolation; Collaboration Benefits Must Be Proven by Task Structure
The book’s most practical multi-Agent design wraps sub-Agents as a tool.
The main Agent submits a self-contained question; the sub-Agent investigates with its own context and a restricted tool set, then returns a short report. The example in the figure: the sub-Agent reads 12 files and processes about 40,000 tokens, while the main Agent receives only a ~200-token report.
These numbers illustrate information-flow design — they don’t represent a fixed compression ratio, nor do they mean total inference cost drops to 200 tokens. The sub-Agent’s reading still costs money.
This structure suits independent searches, code investigations, and cross-checking source material. The main Agent doesn’t need to carry the full reading history of every subtask, and can also choose tools and models for different subtasks.
But “context isolation” is not “security isolation.” A sub-Agent’s report may still be wrong, or may relay malicious instructions; reports need evidence, and irreversible operations require a check before execution.
The book’s attitude toward multi-Agents is measured. It cites experience from Anthropic’s research systems, noting that parallel exploration improves performance, but its multi-Agent interactions consumed about 15 times the tokens of ordinary chat. The comparison baseline is chat — it should not be written up as “all multi-Agent systems cost 15 times more than single Agents.”
Task coupling determines the other half of the outcome. Multiple Agents reading documents independently are usually easy to merge. Multiple Agents simultaneously modifying the same set of interfaces and the same files easily make mutually uninformed decisions about naming, assumptions, and completion state.
The book’s rule of thumb is “read in parallel, write in series.” If parallel modification is truly necessary, use separate working copies, task ownership records, and explicit interfaces — and accept the cost of final integration and conflict resolution.
Voting has a similar precondition. With 5 voters each independently correct 70% of the time, majority accuracy is about 83.7%. But models share blind spots, and the same misleading passage can make all voters wrong together. Before increasing the number of models, first consider whether the evidence and perspectives are genuinely different.
9. Security Boundaries Must Be Enforced by Programs and Environments
The book’s repair example also embeds a malicious requirement: a hidden comment in the README lures the Agent into uploading the repository to an external site.
This is a discussed attack sample. It illustrates that an Agent reading material to complete a legitimate task may also read text designed to change its objective.
System prompts, user requests, file contents, tool outputs, and memory all ultimately enter the model’s input. The priority rules the model has learned are useful, but they cannot substitute for enforced permission mechanisms.
The book cites Simon Willison’s “lethal trifecta”: access to private data, access to untrusted content, and the ability to communicate externally. When all three coexist, malicious content can induce data exfiltration.
In the repair example, the Agent needs to read the repository and must face untrusted content, so external communication should be restricted. A research Agent browsing the public web, however, doesn’t need access to all private files at the same time.
This check targets a specific data-exfiltration path. Removing one condition does not mean all risks — deleting files, tampering with tests, or erroneous deployments — are solved.
A more complete defense requires several layers working together:
-
Expose only the tools the task requires.
-
Check operation types and arguments in code, step by step.
-
Use sandboxes to restrict file, network, process, and credential access.
-
Confirm the exact content for high-impact operations.
-
Maintain audit logs in places the Agent cannot tamper with.
Approvals must bind to the exact command, recipient, body, or code diff. A document claiming “the user already approved this” does not confer authorization.
Running tests itself executes repository code. Even without network tools, as long as the code execution environment can freely reach the network, an exfiltration path may persist. Tool-level restrictions and runtime isolation need to be considered together.
The book also covers plan-then-execute, dual models, and CaMeL’s data provenance tracking. These attempt to limit how untrusted material can influence control flow, or to constrain where sensitive data can flow. These designs sacrifice some flexibility and are best chosen according to risk level.
10. “1 Success in 3 Attempts” and “3 Consecutive Successes” Are Two Completely Different Products
An Agent should be evaluated on the final state: whether the code passes independent tests, whether the database contains the correct record, whether files satisfy the constraints. What the model claims it did is only a diagnostic aid.
Each trial should also start from a clean environment. A stricter approach: copy the files or diffs the Agent produced into a separate fresh environment and run the verifier there, so leftover processes or a modified test runner can’t affect scoring.
Metric selection also changes how we understand capability. Assume a task has a 70% single-attempt success probability, and for now treat attempts as independent:
| Metric | Question answered | At k=3 |
|---|---|---|
| pass@k | Probability of at least 1 success in up to k attempts | 97.3% |
| pass^k | Probability all k attempts succeed | 34.3% |
The former suits scenarios with a reliable verifier and the ability to pick a successful result from multiple candidates. The latter reflects consistency under repeated execution. If the product submits only 1 result, the single-attempt success rate still needs to be reported separately.
This also explains why a single dazzling demo cannot prove a system is reliable. Candidate generation and sustained automatic execution tolerate failure differently.
Eval-set size determines how small an improvement you can detect. The book’s approximate calculation shows: in unpaired binary comparisons at ~70% success rates, making a 5-percentage-point difference reach about 2 standard errors requires roughly 670 tasks. This order-of-magnitude estimate is not a full statistical power design, but it’s enough to remind teams: a few dozen samples can usually only identify large changes.
In practice, start with 20 to 50 real tasks, including failures that have actually occurred, routine regressions, attack samples, and irrelevant distractors. This scale suits kicking off iteration but cannot support conclusions about small leads.
When comparing two versions, prefer paired analysis on the same tasks, record uncertainty, and report cost, latency, step count, tool errors, and approval counts alongside.
Verifiers need testing too. Reference solutions should pass, known cheating approaches should be rejected, and real requirements should map one-to-one with scoring checks. Model-based graders also need calibration against human-annotated samples, to avoid preferring long answers or particular phrasing styles.
11. Turning the Whole Book into a Development Process: Every Failure Must Point to a Modifiable Component
The book ends by returning to a plain iteration loop: run real tasks, collect trajectories, categorize failures, form hypotheses, modify one component, and compare against the baseline.
If I were applying this to a current Agent project, I would prioritize these:
-
Write clear, verifiable completion conditions, distinguishing
answered,budget_exhausted,stopped, and genuine success. -
Check whether tool errors are specific enough, and whether large outputs can be paginated and re-located.
-
Inspect the context at step 1 and step 50 of a task, confirming that goals, constraints, and current evidence are still visible.
-
Keep auditable progress for long tasks; record execution state for external side effects.
-
Use a strong single Agent as the baseline; add sub-Agents only when independent exploration pays off.
-
Version the model, prompts, tools, context policies, permission policies, and runtime code together.
-
Preserve failure trajectories, turning new production issues into regression tasks.
The limitations here should also be stated clearly. The teaching miniagent makes the core loop easy to understand, but it’s separated from a production system by real isolation environments, reliable persistence, complex authorization, and operations. The book cites research across different eras, models, and tasks — local gains should not be taken as commitments for the current product. The model identifiers, APIs, and protocol versions in the examples should defer to the documentation of the service actually in use.
None of this prevents it from providing a stable analytical method: when a failure occurs, first determine whether the problem lies in the system mechanism, the input material, or the evaluation itself.
Similar Articles
This article systematically reviews AI Agent architecture and engineering practices, covering control flow, context engineering, tool design, memory, multi-agent organization, evaluation, tracing, and security. It is based on the OpenClaw implementation and emphasizes the critical role of Harness (testing and validation infrastructure) for system stability.
This article systematically reviews AI Agent architecture and engineering practices, covering control flow, context engineering, tool design, memory, multi-agent organization, evaluation, tracing, and security. It is based on the OpenClaw implementation and emphasizes the critical role of Harness (testing and validation infrastructure) for system stability.
@Huahuazo: Now the AI Agent concept is everywhere, but when it comes to actually implementing complex business scenarios, a bunch of hard problems pop up—how to set up the architecture, how to manage memory, how to coordinate multiple agents without them stepping on each other's toes. The more you write, the messier it gets, and the code ends up like a pot of porridge, let alone deploying it. Then I came across an open-source book called Agentic D…
This is an open-source book called 'Agentic Design Patterns', providing 21 chapters and 7 appendices, systematically explaining AI Agent design patterns, covering from basics to enterprise production environments, with each chapter accompanied by Jupyter Notebook practices.
@shao__meng: Alibaba Cloud Open-Sources the 'AI Agent Handbook': Using the Harness to Take Enterprise Agents from Pilot to Governed Production — A Practical Guide to the Full Agent Lifecycle: Architecture, Build, Run, Govern, Tune, Plus Research Data and Case Studies. Open-source repo: https://github…
Alibaba Cloud has open-sourced the 'AI Agent Handbook', a practical guide to the full enterprise Agent lifecycle covering architecture, building, running, governance, and tuning. It includes 2026 Agent developer survey data, highlighting the key challenges and engineering practices for moving enterprise Agents from pilots to governed production.
@antiAIvo: How to Handwrite an Agent from Scratch? I Put Together an Agent Tutorial in 18 Parts Coding agents like Claude Code and Codex are really just a loop at their core: The model requests tools, code executes, the result goes back into the conversation, until the model stops requesting This tutorial starts from 100 lines of code and builds up layer by layer in Python:...
Shared a complete 18-part handwritten Agent tutorial, starting from 100 lines of Python and progressively building tool calling, permissions, context management, Skills, chat platform integrations, scheduled tasks, MCP, sub-Agents, planning, and memory. Each lesson also compares how mainstream Agents like Claude Code, Codex, Grok Bot, and DeepSeek Harness approach the same problems. The biggest takeaway: mainstream products mostly diverge on one question — should the security layer be handled by prompts or by code?
@xiaomovps: After researching so many AI agents, I increasingly believe the Harness is the direction most worth digging into deeply Recently I came across an article shared by Anthropic about long-running agents, and some of the ideas really resonated with me Because over the years I've both studied and worked with quite a few Harnesses, including Pi Agent, DeepSeek Harness, Claude Code, Codex, and Hermes Agent Through this process I found that every Harness is essentially quite similar, yet the outcomes they produce can differ greatly — the same model may perform differently across different Harnesses In my observations, it generally comes down to these issues: 1. First, context management When an agent is executing a complex task, it continuously accumulates context. How to retain important information, compress irrelevant content, and still understand the previous task after a context switch really tests the design of the Harness 2. Second, long-task execution capability I've hit quite a few pitfalls here myself — sometimes a task runs for tens of minutes and suddenly hangs, or a problem occurs midway and the only option is to start over So I believe a mature Harness shouldn't just be able to execute tasks; it also needs to consider task state, exception recovery, and how to resume execution from the point of interruption 3. Finally, result verification This is also something I feel is easily overlooked.很多时候 the agent tells you the task is complete, but the actual result may not meet expectations Without a reliable verification mechanism, no matter how strong the model is, it's hard to guarantee the final quality of complex tasks I hope the Harnesses on the market keep getting better, especially domestically developed ones — whether it's DeepSeek Harness or WorkBuddy. Only a strong model paired with a strong Harness is the only way forward If you're also researching this direction, I recommend taking a look: https://anthropic.com/engineering/effective-harnesses-for-long-running-agents…
Drawing on hands-on experience with Pi Agent, DeepSeek Harness, Claude Code, and more, the author argues that the Harness is the area most worth exploring in depth, shares an Anthropic article on long-running agents, and highlights three key challenges: context management, long-task execution, and result verification.