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.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Beginner Why long tasks are different

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.

Briefinggoal, rules, status, next step
Worka bounded piece with its own context
Verifytests, checks, evidence
Recordledger and notes outside the window
↺ Start the next piece from the record, not from memory of the chat
The durable record, not the conversation, is the source of truth.

What to keep outside the window

ArtifactHoldsWritten when
Task briefGoal, scope, definition of done, rulesAt the start, changed only with approval
Progress ledgerItems, status and evidenceAfter each verified step
NotesDiscoveries, traps, decisions and whyWhen learned
Work productsCode, drafts, data filesContinuously, under version control
Event logActions taken and their resultsAutomatically by the runtime
Intermediate Proactive management and multi-agent context

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.

Test the cold start

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:

FieldQuestion it answers
ObjectiveWhat result is wanted, and why?
Scope and boundariesWhat is out of bounds, and what are others covering?
InputsWhich facts, files and constraints are given?
Tools and sourcesWhat may be used, and what is preferred?
BudgetHow many steps, tokens or minutes?
Output formatWhich fields, with what evidence?
Failure behaviorWhat 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

IsolatedEach agent sees its brief only. Clean and safe, but may duplicate work.
Shared boardStructured facts and status visible to all. Good coordination, needs write rules.
Full historyEveryone sees everything. Simple at first, expensive and fragile.

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.
Illustrative example: quarterly close assistant

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.

Expert Evaluation, patterns and anti-patterns

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.

MeasureQuestionHow to compute
CompletenessWas every needed fact present?Needed facts found divided by needed facts
RelevanceHow much of the context was useful?Needed or helpful items divided by all items
AccuracyWas the content true and current?Correct items divided by all items
SafetyWas anything forbidden included?Count; the target is zero
EfficiencyWhat 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

PatternUse whenTrade-off
Progressive disclosureMany tools or documents existExtra lookup steps
Durable ledgerWork spans many windowsNeeds discipline and verification
Isolated subagentA noisy subtask has a compact answerMore tokens, handoff risk
Result offloadingTool output is largeRequires tools to reread
Planned compactionHistory is long but linearSome detail is lost
Authority rankingSources conflictOwners must maintain rules

Anti-patterns

Anti-patternWhat happensInstead
Dump everythingCost rises and signal drownsSelect and retrieve on demand
Chat as databaseState vanishes at reset or compactionPersist structured state
Rule pile-upContradictory instructions after each incidentReview, merge and delete rules
Telephone chainFacts mutate across agent summariesPass references to originals
Self-certified doneUnfinished work marked completeRequire external evidence
Invisible assemblyNobody can say what the model sawLog a manifest
Stale reuseYesterday's values drive today's actionRefetch 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.

SymptomLikely context causeFirst fix to try
Repeats finished workStatus lives only in compacted historyLedger read at the start of each unit
Breaks an early ruleRule summarized away or buriedKeep verbatim and restate
Uses an old valueStored result reusedRefetch before acting
Declares success too soonNo external definition of doneRequire test or query evidence
Subagents overlapBoundaries missing from the handoffState what others cover
Costs climb every turnResults never clearedOffload 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

  1. Log what each request contains and how large each source is.
  2. Move goals, rules and progress into durable records.
  3. Limit and offload large tool results.
  4. Add planned compaction and test cold starts.
  5. Build a labeled context test set and run it on every change.
  6. 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

Next steps