Agent Memory and Context Cost Governance
Agent context is not smarter just because it is longer. This article explains how to store, compress, recall, and budget agent memory so quality stays high while disk, latency, and token cost stay under control.
Agent context is not smarter just because it is longer. When full interaction history is persisted and then stuffed back into the model almost unchanged, disk use, latency, and cost all rise—without a matching gain in answer quality. What actually shapes the experience is how memory is stored, how information is compressed, how history is recalled, and how each turn’s context budget is allocated.
What the state layer is doing
A conversational agent usually keeps session state locally or on the server. At minimum that state should answer four questions: which session this is, who is speaking, which model and system instructions were in use, and what has happened so far. Typical fields include session ID, channel, user ID, session title, model name and config snapshot, system-prompt snapshot, full message trace, and tool calls plus tool results.
Those fields enable recovery and audit: resume after a process restart, reconstruct a failed tool call, and compare behavior under the same prompt version. The trap is treating recoverability as “never discard.” The store then grows roughly linearly with turns. After a few days of heavy use, a single user’s session files can fill disk. A quieter cost is slower load and retrieval, and a next-turn prompt drowned in history.
Keeping every interaction is not self-improvement. Improvement means extracting reusable facts, preferences, and failure lessons, then applying them in a shorter form at the right time. Append-only writes are logs. Logs help debugging; they do not necessarily help reasoning.
Long-term memory is not a keyword pile
Many implementations score “importance” on write: keep hits on keywords, tool names, or entities; drop or summarize the rest. That saves tokens versus full replay, but the filter rarely matches what users care about. Hard constraints—budget caps, banned data sources, a plan already rejected—vanish if they are not stored as structured facts. The model then re-asks and re-calls the same tools, and the user concludes it is not smart.
A more stable approach is layered memory, not a single keyword gate.
Working memory serves the current task: this-turn goal, unfinished substeps, the last few raw turns, and in-flight tool calls. It may be relatively complete, but it needs a hard cap—by turns or tokens.
Episodic memory stores a task’s outcome, not the whole process. A useful record covers goal, key inputs, approach taken, tool conclusions, final deliverable, and open items. Small talk, repeated error stacks, and intermediate drafts do not belong in the long-term store.
Semantic memory stores facts and preferences that remain valid across sessions: output language, code style, forbidden directories, common environment-variable names (whether values are stored should be decided separately). Each fact should carry source session, update time, and confidence. Later explicit instructions can override earlier inferences.
Procedural memory stores “how to err less”: for example, read a schema before querying a class of APIs, or narrow scope before switching models on a class of failures. It is closer to a versioned operations note than a chat log.
After layering, discard is a write policy, not a casual model judgment: raw text goes to working memory and expires on a schedule; only validated facts promote to semantic memory; failure modes enter procedural memory after review.
Compression must keep constraints, not just nouns
The goal of compression is to keep decision-critical information inside a fixed budget. Common tools include sliding windows, rolling summaries, structured extraction, and retrieved snippets. They can be combined; they do not replace each other.
A sliding window is simple but drops hard constraints outside the window. Rolling summaries shorten text but can flip negations into affirmations, or turn “pending confirmation” into “confirmed.” Summary prompts should therefore require keeping: explicit user bans, open questions, numbers and units, file paths and IDs, and error codes from tools. Summaries should be incrementally updated, not rewritten from scratch into an ever-longer “master summary.”
Structured extraction fits preferences and entities. Instead of “the user seems to like concise answers,” store fields: answer language, verbosity, required evidence types. On extraction failure, keep a raw snippet and mark low confidence so nothing is silently lost.
A product-agnostic memory record, for field roles only:
id: mem_1042scope: userkind: constraint # fact | preference | constraint | proceduretext: By default do not write secrets, tokens, or customer source text into long-term memorysource_session: sess_88updated_at: 2026-04-02T10:15:00Zconfidence: explicit # explicit | inferredttl: none
Explicit constraints should outlive casual inferences. Inferred memories must be voidable in one user sentence and appear later as overridden, not as two coexisting claims.
Recall is on-demand, not dumping the store into the prompt
On a “similar” problem, the system must find relevant history. Keyword match covers proper names and raw errors but is brittle on paraphrases. Vector search finds semantic neighbors but can rank old conclusions that share a topic and reverse a constraint. Production systems more often use hybrid recall: filter first (same user, same project, not expired, memory type), rank with keywords and vectors, then a short rerank to drop conflicts.
Control count and format when injecting context. Three expiry-checked memories labeled as fact, preference, or then-task conclusion beat ten old transcripts. Task conclusions should not auto-promote to universal truth. “Plan A worked last time” describes that environment, not every environment.
Recall must handle conflict. New explicit instructions beat old inferences; keep only the latest confirmed value per field; present unconfirmed contradictions as to-verify rather than picking one into the system prompt. Otherwise the model oscillates across two histories, and both tool calls and tokens rise.
Account for token cost by layer
When spend rises, model unit price alone rarely locates the leak. Meter context by slice: system prompt, tool definitions, working memory, recalled memory, this-turn user input, tool returns. Tool returns are often the silent majority—one wide query or full-file read can exceed many chat turns.
Practical controls include: truncate or extract fields before storing tool results; put raw responses in object storage or logs and keep only a summary plus locator in context; load system prompts and tool lists by task instead of every capability every time; dedupe repeated calls with a key and reuse the last structured result for a short window; set token quotas per memory class and compress episodic memory before cutting constraint-class semantic memory.
Watch at least four signals: per-session state size, average prompt tokens per turn, tool-call count and repeat rate, and the share of recalled items the user later rejects. Size up with poor hit quality means writes are too wide; high repeat rate means working memory did not keep the last failure; high reject rate means recall returned stale or irrelevant items. Those signals beat a raw token leaderboard for deciding what to change.
Closing the loop from demo to production
Demos usually prove “it can talk and call tools.” In real work, forgetting, repeated calls, and rising bills appear together, with roots in write, compress, recall, and budget. Close those gaps in order rather than swapping in a larger model first.
First, define what never enters long-term storage: secrets, tokens, personal sensitive data, unauthorized customer source text. For audit, store references and permission-check results, not plaintext.
Second, write promotion rules per memory class. A successful tool return of a customer ID is not a global default. “Use Chinese this time” should not overwrite a long-term language preference without confirmation.
Third, make compression and recall replayable. Keep the source-message range for each summary and the prompt version used. Failures can then be attributed to a bad extract, bad recall, or the model still failing with full context.
Fourth, give context a hard budget and a trim order: drop low-value tool raw text first, then compress old episodes, and only then touch explicit constraints. Put the budget in runtime config, not magic numbers in business code.
Fifth, regression-test a small fixed task set: whether the same user preferences still apply, whether rejected plans stay unrecommended, whether duplicate tool calls drop, and whether per-turn tokens stay in budget. Without that, every “optimization” of memory policy cannot tell smarter from merely shorter.
Whether an agent “knows you better” does not depend on unbounded state growth. It depends on turning interaction into structured memory that can be updated, expired, and conflict-resolved, then retrieving the small slice that actually affects decisions inside a strict context budget. The model reasons; the memory architecture keeps reasoning from starting at zero every time and keeps history from exhausting the budget. Design and observe storage, compression, recall, and cost as separate layers so that, at scale, you still know which layer holds the problem.
