Long-Horizon, Multi-Agent and Enterprise Context
How to keep an agent coherent over hundreds of steps, share just enough between agents, serve messy enterprise knowledge and measure whether the context was any good.
Long tasks outgrow one context window, so keep durable state outside it: a goal, rules, a progress ledger with evidence and notes the agent can reread. Agent teams need small, structured handoffs instead of shared transcripts. Enterprise work needs authority and freshness rules. Measure completeness, relevance and accuracy of the context separately from the final answer.
What you will learn: proactive context management, durable notes and ledgers, context contracts between agents, enterprise knowledge patterns, evaluation metrics and the anti-patterns to avoid.
Prerequisites: Context Assembly, Retrieval, Compression and Caching and Context Isolation, Provenance and Governance.
When the task is longer than the window
A question answered in three model calls rarely strains context. A migration that touches forty files, a research job that reads hundreds of pages or an operations agent that watches a queue for days will. History accumulates, early instructions drift toward the middle of a huge input, old tool output describes a world that has changed, and the cost of every turn rises.
Waiting until the window is full and then summarizing in a hurry is the worst time to decide what matters. Proactive management decides in advance what lives inside the window, what is stored outside, when to compact and how a fresh window picks up the thread.
What to keep outside the window
| Artifact | Holds | Written when |
|---|---|---|
| Task brief | Goal, scope, definition of done, rules | At the start, changed only with approval |
| Progress ledger | Items, status and evidence | After each verified step |
| Notes | Discoveries, traps, decisions and why | When learned |
| Work products | Code, drafts, data files | Continuously, under version control |
| Event log | Actions taken and their results | Automatically by the runtime |
Proactive context management
Plan the work in pieces
Break the task into units that each fit comfortably in one window with room to spare, and that can be verified alone. One service, one document section or one data partition are typical. A unit that needs the whole history to make sense is a sign the split is wrong.
Set thresholds and triggers
Pick points at which the runtime acts: clear used tool results at one level, compact at a higher level, and start a fresh window at a task boundary. Leave headroom for the largest tool result you allow. Truncate or file any result above a size limit before it enters context.
Restate what must not be lost
Repeat the goal, constraints and current step near the end of the request. This counters drift in long inputs and costs very little. Some agents maintain a short to-do list that they rewrite as they go, which keeps the plan in recent context.
Write the ledger with evidence
"""A progress ledger lets a fresh context window resume a long task."""
import json
ledger = {
"goal": "Upgrade 6 services to the new logging library",
"rules": ["One pull request per service", "Do not change public APIs"],
"done": {}, "todo": ["auth", "billing", "search", "mail", "export", "admin"],
"notes": [], "next": "auth",
}
def record(ledger, service, status, evidence, note=None):
if status == "done":
if not evidence:
raise ValueError("no evidence, not done")
ledger["todo"].remove(service)
ledger["done"][service] = evidence
if note:
ledger["notes"].append(f"{service}: {note}")
ledger["next"] = ledger["todo"][0] if ledger["todo"] else None
def briefing(ledger):
"""What a new window reads first. Short, and built from facts."""
return "\n".join([
f"Goal: {ledger['goal']}",
"Rules: " + "; ".join(ledger["rules"]),
f"Done ({len(ledger['done'])}): " +
", ".join(f"{k} [{v}]" for k, v in ledger["done"].items()),
"Remaining: " + ", ".join(ledger["todo"]),
"Watch out: " + ("; ".join(ledger["notes"][-3:]) or "nothing yet"),
f"Next step: {ledger['next']}",
])
record(ledger, "auth", "done", "PR 41, tests pass")
record(ledger, "billing", "done", "PR 42, tests pass",
note="uses a custom formatter")
try:
record(ledger, "search", "done", evidence="")
except ValueError as exc:
print("rejected:", exc)
saved = json.dumps(ledger) # survives a reset or a crash
print(briefing(json.loads(saved)))
Output:
rejected: no evidence, not done
Goal: Upgrade 6 services to the new logging library
Rules: One pull request per service; Do not change public APIs
Done (2): auth [PR 41, tests pass], billing [PR 42, tests pass]
Remaining: search, mail, export, admin
Watch out: billing: uses a custom formatter
Next step: search
The ledger refuses to mark work done without evidence, which guards against the common habit of a model declaring success early. The briefing is generated from fields, so it cannot invent progress. Because it is saved as plain data, a new window, a different model or a human colleague can continue after a crash. For the runtime side of this, see Durable Execution, Checkpoints and Approvals and Stateful and Long-Running Agent Architecture.
At several points in a real run, discard the conversation and give a fresh agent only the briefing and the files. If it repeats finished work, breaks a rule or asks what the goal is, your durable record is missing something.
Context engineering for multi-agent systems
Multiple agents give you multiple windows. That helps when subtasks are independent and read-heavy, such as searching several sources at once. Anthropic reported that its research system, with a lead agent directing parallel subagents, outperformed a single agent on its internal research evaluation, while using about fifteen times the tokens of a chat. The gain came with a price, and it applied to work that splits well. Tightly coupled work, such as editing one shared design, often does better with one agent.
The delegation contract
Most multi-agent failures start with a thin instruction. A good handoff includes:
| Field | Question it answers |
|---|---|
| Objective | What result is wanted, and why? |
| Scope and boundaries | What is out of bounds, and what are others covering? |
| Inputs | Which facts, files and constraints are given? |
| Tools and sources | What may be used, and what is preferred? |
| Budget | How many steps, tokens or minutes? |
| Output format | Which fields, with what evidence? |
| Failure behavior | What to report if it cannot finish? |
Return findings, not transcripts
The receiving agent needs conclusions, the evidence behind them, confidence, open questions and pointers to full material. A transcript forces it to redo the thinking and imports every dead end. Large outputs should go to shared storage, with only references passed back, so that detail is not squeezed through several summaries.
Choose what is shared
A shared board with typed entries is a good default. Give each entry an author, time and status, and let one component resolve conflicts. Handoffs, Routing, Shared State and Communication and Parallelism, Deadlocks and Conflict Resolution cover the mechanics.
Context for enterprise knowledge work
Company knowledge is scattered, duplicated and contradictory. Three drafts of a policy sit beside the approved one. A spreadsheet disagrees with the system of record. Meaning depends on local words: "active customer" differs between sales and finance.
- Rank by authority. Record which system wins for each kind of fact, and encode it instead of hoping the model infers it.
- Filter by effective date. Superseded documents should be excluded or clearly labeled.
- Define terms. Supply a small glossary or a semantic layer for metrics so that numbers are computed consistently.
- Prefer queries to dumps. For live data, call a governed query instead of pasting exports.
- Layer the instructions. Company rules, then department rules, then task instructions, with a stated order of precedence.
- Cite. Show sources so people can check and report errors back to owners.
An agent helps an accounting team reconcile accounts over several days. Its brief holds the materiality threshold and the rule that it never posts entries. Each account is one unit with a ledger line showing the query used and the difference found. Balances come from the ledger system at the moment of use, never from last week's notes. Reviewers read the ledger, not the conversation.
Measuring completeness, relevance and accuracy
When an agent fails, ask first whether it had what it needed. Evaluating context separately from the answer tells you whether to fix retrieval and assembly or the model and prompt.
| Measure | Question | How to compute |
|---|---|---|
| Completeness | Was every needed fact present? | Needed facts found divided by needed facts |
| Relevance | How much of the context was useful? | Needed or helpful items divided by all items |
| Accuracy | Was the content true and current? | Correct items divided by all items |
| Safety | Was anything forbidden included? | Count; the target is zero |
| Efficiency | What did it cost? | Tokens and latency per successful task |
"""Measure completeness, relevance and accuracy of assembled contexts."""
FACTS = { # fact id: is it currently true?
"limit-500": True, "limit-200": False, "order-118": True,
"photo-yes": True, "vip": True, "office-hours": True,
}
CASES = [
{"name": "baseline", "need": {"limit-500", "order-118", "photo-yes"},
"got": ["limit-500", "limit-200", "order-118", "office-hours"]},
{"name": "stuffed", "need": {"limit-500", "order-118", "photo-yes"},
"got": ["limit-500", "limit-200", "order-118", "photo-yes", "vip", "office-hours"]},
{"name": "filtered", "need": {"limit-500", "order-118", "photo-yes"},
"got": ["limit-500", "order-118", "photo-yes"]},
]
def measure(case):
got, need = set(case["got"]), case["need"]
return {
"completeness": len(got & need) / len(need),
"relevance": len(got & need) / len(got),
"accuracy": sum(FACTS[f] for f in got) / len(got),
}
print(f"{'variant':10} complete relevant accurate gate")
for case in CASES:
m = measure(case)
ok = m["completeness"] == 1 and m["accuracy"] == 1 and m["relevance"] >= 0.7
print(f"{case['name']:10} {m['completeness']:8.2f} {m['relevance']:8.2f} "
f"{m['accuracy']:8.2f} {'pass' if ok else 'FAIL'}")
Output:
variant complete relevant accurate gate
baseline 0.67 0.50 0.75 FAIL
stuffed 1.00 0.50 0.83 FAIL
filtered 1.00 1.00 1.00 pass
Stuffing the window fixes completeness while leaving the outdated limit inside, so accuracy and relevance still fail. Only the filtered variant passes. Building the labels takes effort: start with twenty real tasks, write down the facts each needs, and mark which stored facts are outdated. Where labels are impractical, a model judge can estimate relevance, but check its agreement with people first, as described in LLM Judges, Human Review and Ratings.
Diagnostic experiments
- Oracle context: hand the model exactly the right facts. If it still fails, the problem is reasoning or instructions.
- Ablation: remove one source at a time and watch success. Sources that change nothing are candidates for removal.
- Distraction test: add plausible irrelevant or outdated items and measure the drop.
- Position test: move a key fact between start, middle and end.
- Reset test: restart mid-task from the durable record.
Patterns that work
| Pattern | Use when | Trade-off |
|---|---|---|
| Progressive disclosure | Many tools or documents exist | Extra lookup steps |
| Durable ledger | Work spans many windows | Needs discipline and verification |
| Isolated subagent | A noisy subtask has a compact answer | More tokens, handoff risk |
| Result offloading | Tool output is large | Requires tools to reread |
| Planned compaction | History is long but linear | Some detail is lost |
| Authority ranking | Sources conflict | Owners must maintain rules |
Anti-patterns
| Anti-pattern | What happens | Instead |
|---|---|---|
| Dump everything | Cost rises and signal drowns | Select and retrieve on demand |
| Chat as database | State vanishes at reset or compaction | Persist structured state |
| Rule pile-up | Contradictory instructions after each incident | Review, merge and delete rules |
| Telephone chain | Facts mutate across agent summaries | Pass references to originals |
| Self-certified done | Unfinished work marked complete | Require external evidence |
| Invisible assembly | Nobody can say what the model saw | Log a manifest |
| Stale reuse | Yesterday's values drive today's action | Refetch volatile data before acting |
Debugging a long run that went wrong
Long runs fail late, and the cause is often far from the symptom. Work backward through the records instead of rereading the whole conversation. Find the first step whose output was wrong, open the manifest for that call and ask four questions in order. Was the needed fact present? If not, was it never stored, not retrieved, or dropped by compaction? Was something false or outdated present, and where did it enter? Were the rules still stated clearly near the end of the request? If all of that was right, the fault lies in the model, the prompt or the tool, and more context work will not help.
| Symptom | Likely context cause | First fix to try |
|---|---|---|
| Repeats finished work | Status lives only in compacted history | Ledger read at the start of each unit |
| Breaks an early rule | Rule summarized away or buried | Keep verbatim and restate |
| Uses an old value | Stored result reused | Refetch before acting |
| Declares success too soon | No external definition of done | Require test or query evidence |
| Subagents overlap | Boundaries missing from the handoff | State what others cover |
| Costs climb every turn | Results never cleared | Offload and clear after use |
Turn each incident into a replayable case with its stored inputs, so that a later change to assembly cannot quietly bring the failure back. Debugging Agents, RAG and Handoffs describes trace-based diagnosis in more depth.
Introducing these in order
- Log what each request contains and how large each source is.
- Move goals, rules and progress into durable records.
- Limit and offload large tool results.
- Add planned compaction and test cold starts.
- Build a labeled context test set and run it on every change.
- Add subagents only where measurements show that separate windows help.
Checklist
- Goal and rules are stored outside the conversation and restated.
- Each work unit fits in one window with headroom.
- Progress is recorded with evidence.
- A fresh agent can resume from the record.
- Handoffs use a defined contract and return evidence.
- Authority and effective dates are encoded for enterprise facts.
- Completeness, relevance and accuracy are measured.
- Volatile values are refetched before consequential actions.
Frequently asked questions
Is a bigger window better than a ledger?
They solve different problems. A window holds working material. A ledger survives crashes, resets, model changes and human handover, and it can be checked.
How often should an agent write notes?
After each verified unit and whenever it learns something a later step would otherwise rediscover. Keep notes short and prune those that stop being true.
Do subagents always save context?
They keep the parent's window small, but total tokens usually rise. Use them when isolation or parallel work pays for that.
Which metric should I start with?
Completeness on a small labeled set. It quickly shows whether failures come from missing information.
References and further reading
- Anthropic: Effective context engineering for AI agents
- Anthropic: How we built our multi-agent research system
- Drew Breunig: How long contexts fail and how to fix them
- Liu et al.: Lost in the Middle
- Chroma research: Context rot
- Claude documentation: Memory tool
Next steps
Agent Memory Types and Persistence
Carry knowledge across sessions, not only across windows.
Single-Agent vs Multi-Agent Systems
Decide whether more agents are worth it.
Long-Horizon Memory and Planning
Where research on very long tasks is heading.