AI AgentsAI Agent Execution & Lifecycle
How do AI agents compact completed work to manage context?
Question 270 of 280 · Updated
On this page
- 1. What should survive compaction?
- 2. A practical compaction workflow
- 3. Beginner-friendly numerical example
- 4. Use a structured summary
- 5. Compaction versus tool clearing and persistent memory
- 6. When should an agent compact?
- 7. Failure scenarios and prevention
- 8. Engineering trade-offs
- 9. Measure compaction quality
- 10. A safe compaction algorithm
- Key takeaway
Long-running AI agents accumulate user messages, plans, tool outputs, decisions, and intermediate work. Carrying every old detail into every model request increases token cost and can bury important current information. Context compaction reduces this active history to a smaller, structured state so the agent can continue without repeatedly sending the full transcript.
This lesson focuses on compacting completed work and conversation history for a continuing task. It is distinct from the earlier Q227–Q263 sequence on durable multi-agent memory compaction, which addresses stored memory records, distributed workers, replication, scheduling, retention, and recovery. It also differs from simply deleting old tool output: compaction summarizes useful information that may not be exactly reproducible.
1. What should survive compaction?#
A useful compacted state preserves:
- Objective and acceptance criteria: what the user wants and what counts as done.
- Constraints and permissions: safety rules, scope limits, deadlines, and actions that are not authorized.
- Completed work: actions performed and their verified outcomes.
- Decisions: chosen approaches and reasons important alternatives were rejected.
- Evidence anchors: exact identifiers, paths, versions, error codes, measurements, timestamps, and source references.
- Open work: unfinished steps, dependencies, blockers, and the next action.
- Uncertainty: assumptions and hypotheses that have not been verified.
Completed work is not automatically disposable. A completed migration may establish the schema version required by the next step. A finished investigation may contain the key finding needed for a final decision. The goal is to preserve the smallest accurate state that supports the next decision—not merely to keep unfinished tasks.
2. A practical compaction workflow#
- Choose a safe boundary. Prefer a completed task, research phase, resolved incident step, or explicit milestone. Avoid compacting while a tool call or transaction has an unknown outcome.
- Separate facts from interpretation. Tool-confirmed results are facts; model conclusions are conclusions; untested ideas remain hypotheses.
- Extract task state. Capture objective, constraints, completed actions, decisions, evidence, open items, and next action.
- Remove redundancy. Drop repeated messages, verbose tool output, irrelevant intermediate reasoning, and details that can be safely retrieved again.
- Preserve exact anchors. Keep IDs, file paths, commit hashes, schema versions, error codes, numeric values, and references when later steps depend on them.
- Validate the summary. Check that acceptance criteria, safety constraints, critical facts, and unfinished work survived.
- Persist before switching. Store the new summary and verify it before replacing the active context. Keep a source checkpoint according to retention policy.
- Resume and monitor. Continue from the compacted state, retrieve exact source material when needed, and record omissions or corrections.
If the agent cannot tell whether a detail is safely disposable, preserve a source pointer or retain the detail until the task is complete.
3. Beginner-friendly numerical example#
Imagine a customer-support agent handles one complex ticket over 40 tool-assisted turns. Its conversation has grown to 48,000 tokens:
- 12,000 tokens of repeated policy and customer context.
- 18,000 tokens of large search results and tool payloads.
- 10,000 tokens of completed troubleshooting and repeated explanations.
- 8,000 tokens of decisions, verified findings, constraints, and remaining work.
After confirming that the troubleshooting phase is complete, the agent compacts the history into a 4,000-token state summary and retains the last 2,000 tokens of recent messages.
The next request now carries about 6,000 tokens instead of 48,000: 42,000 fewer tokens, an illustrative 87.5% reduction in that context snapshot.
The summary might preserve:
- Ticket ID SUP-8421; customer cannot complete a card payment.
- Verified: provider returned error P-17 for expired authorization.
- Completed: checked account status, ruled out duplicate charge, reproduced failure in staging.
- Decision: request a fresh authorization; do not retry the expired token.
- Constraint: never expose full card details in logs or summaries.
- Open: send approved reauthorization steps and verify one successful payment.
- Next action: send approved instructions; wait for confirmation before closing.
Repeated search results and explanations are omitted. The exact ticket ID, error code, verified findings, security constraint, and next step remain because they affect future actions.
The reduction alone does not prove success. If the summary drops the fact that a duplicate charge was already ruled out, the next agent may repeat work or make a poor recommendation. Evaluate compaction by task continuity, not compression ratio alone.
4. Use a structured summary#
A useful compacted state can follow this pattern:
- Task identity and objective.
- Acceptance criteria.
- Constraints and permissions.
- Completed actions with outcomes and evidence references.
- Decisions and rationale.
- Open items, blockers, and dependencies.
- Uncertainties and unverified assumptions.
- Next action.
- Source checkpoint and summary version.
For example, a payment-ticket summary should distinguish “authorization request attempted” from “payment confirmed.” It should store the provider response reference rather than inventing a successful outcome. Structured fields make exact IDs and required constraints easier to validate than a vague paragraph such as “we investigated the issue; continue from here.”
5. Compaction versus tool clearing and persistent memory#
These techniques solve related but different problems:
- Tool-result clearing: removes large, re-fetchable tool outputs while retaining a record that the call occurred. If a search or file read can safely be repeated, clearing may be cheaper and lossless.
- Context compaction: summarizes conversation history, decisions, and progress when useful information is spread across many turns and cannot be reduced to simply rerunning tools.
- Persistent memory or notes: writes selected knowledge to external storage so it survives beyond the current context window or session.
- Retrieval: fetches exact source details when the summary contains a pointer but not enough evidence to act.
A robust agent can combine them: clear an old large API response after extracting required facts, compact the conversation at a milestone, and save a durable project note for decisions that must survive across sessions.
Do not use a lossy summary as the only copy of legal, financial, security, or other high-stakes evidence. Preserve authoritative records and retrieve them when exact wording or provenance matters.
6. When should an agent compact?#
Useful triggers include:
- Context reaches a configured token threshold.
- A large research or tool-intensive phase finishes.
- A deliverable is completed and acknowledged.
- The agent is about to begin a large refactor, migration, or incident-response phase.
- The task changes and earlier discussion is no longer relevant.
- A long-running workflow is about to hand off to another agent.
A fixed threshold is easy to operate but may trigger at an awkward moment. A purely model-decided trigger is flexible but needs guardrails. A practical hybrid uses a token threshold as a safety backstop and allows compaction at explicit task boundaries.
Do not compact merely because a timer elapsed. Avoid it during an unresolved tool call, partially completed transaction, active approval, or state transition whose outcome is unknown.
7. Failure scenarios and prevention#
Critical constraint disappears. The summary retains the goal but drops “do not retry expired payment tokens.” The next agent repeats a prohibited action. Make safety constraints mandatory fields and validate their presence before switching context.
An attempt is summarized as a verified result. A tool call times out, but the summary says “payment succeeded.” Preserve the distinction between attempted, returned, and independently verified outcomes, with evidence references.
Identifiers are corrupted. A ticket ID, commit hash, or error code changes during summarization. Keep identifiers in structured fields and compare them with source state; never rely on paraphrased machine identifiers.
Open work is lost. The summary says “investigation complete” but omits pending customer confirmation. Require explicit open-item, blocker, and next-action sections.
A stale summary overwrites newer work. A background compaction job finishes after the agent has added new messages. Use conversation version numbers or checkpoint sequence IDs. Apply a summary only if its source version is current; otherwise merge or regenerate it.
Repeated compaction compounds omissions. A summary is summarized again and gradually loses nuance. Retain source checkpoints, version summaries, and periodically regenerate from authoritative events for high-impact tasks rather than recursively summarizing only the previous summary.
Sensitive data survives. A raw tool result contains a secret that is copied into the compacted state. Apply redaction and data-minimization rules before summarization, then scan the summary before storing it.
Summary generation fails. Do not delete old context first. Generate, validate, and persist the summary; only then switch the active context pointer. If any step fails, continue from the original context or recover from the last valid checkpoint.
8. Engineering trade-offs#
- Compression ratio versus fidelity: shorter summaries reduce token cost but can omit edge cases. Optimize for successful continuation, not the smallest summary.
- Automatic versus explicit compaction: thresholds protect against overflow; explicit checkpoints preserve task boundaries. A hybrid is usually easier to control.
- Prose versus structured state: prose is flexible; structured fields make constraints, identifiers, and open work easier to validate. Use both where appropriate.
- Retain transcript versus discard it: retaining source improves recovery but costs storage and creates privacy/retention obligations. Apply access controls to both transcript and summary.
- Summarize versus retrieve: summaries are fast for continuity; retrieval is safer for exact details. Keep source references and fetch them when precision matters.
- Synchronous versus background compaction: synchronous compaction is simple but pauses the agent; background compaction can reduce foreground delay but adds versioning and merge complexity.
- Model-generated versus deterministic extraction: models synthesize decisions and relationships; code reliably preserves IDs, timestamps, counters, and explicit state. Use deterministic extraction for exact metadata and model summarization for semantic condensation.
9. Measure compaction quality#
Monitor more than tokens saved:
- Compression ratio: tokens after compaction divided by tokens before.
- Continuation success: percentage of tasks completed correctly after compaction.
- Critical fact retention: whether required constraints, identifiers, decisions, and evidence survive.
- Regression rate: errors or repeated work attributable to missing or distorted context.
- Recovery rate: ability to reconstruct details from checkpoints or source references.
- Latency and cost: summarization overhead compared with saved input tokens and reduced retries.
- Staleness: how often a compacted result is rejected because its source context changed.
Build evaluations from real task traces. Seed long sessions with known facts, constraints, and unresolved items; compact them; then test whether the next agent step behaves correctly. Include cases where a critical constraint appears only once or is buried in a tool result.
10. A safe compaction algorithm#
compact_context(conversation, task_state):
checkpoint = capture_version_and_open_operations()
assert no_unresolved_state_transition(checkpoint)
summary = extract(
objective, constraints, verified_facts, decisions,
completed_work, open_items, uncertainties,
next_action, evidence_references
)
summary = remove_redundancy_and_redact_sensitive_data(summary)
validate_required_fields(summary)
validate_identifiers_against_sources(summary)
validate_open_items_and_safety_constraints(summary)
if source_version_changed(checkpoint):
merge_or_regenerate_summary()
else:
persist_versioned_summary(summary)
switch_context_to(summary + recent_messages)
retain_source_checkpoint_per_policy()
measure_continuation_quality()The critical safety property is that old context is not discarded until the new summary is validated and durably available.
Key takeaway#
AI agents compact completed work by preserving the objective, constraints, verified outcomes, decisions, evidence pointers, unresolved items, and next action—while removing repeated or safely retrievable detail. Use natural task boundaries, versioned checkpoints, structured validation, and source references. A good compacted context is not merely shorter; it lets the agent continue correctly without forgetting what matters.
References
- 1.Effective context engineering for AI agentsanthropic.com
- 2.Compactionplatform.claude.com
- 3.Context engineering: memory, compaction, and tool clearingplatform.claude.com
- 4.Context Engineering – Short-Term Memory Management with Sessionsdevelopers.openai.com
- 5.Autonomous context compressionlangchain.com
- 6.Context Management for Deep Agentslangchain.com
Related questions
Explore other topics:Large Language ModelsRetrieval-Augmented GenerationMLOps