Long-Term Memory and Context Cost Governance for AI Agents: A Practical Engineering Guide

    Once an AI agent enters a real production workflow, teams often notice it seems to "know" users better—while disk usage, context length, and token bills all climb together. This article explains the mechanisms that actually determine agent experience and cost: how interaction state is persisted, what gets treated as memory, what compression throws away, how recalled history is reinjected into context, and how to eliminate redundant tool calls. It covers why high token consumption does not mean better memory, how to separate raw trajectory logs from injectable memory entries, layered memory design (working, episodic, semantic, and procedural), recall strategies with scope, freshness, and token budgets, symptom-based troubleshooting for forgetting, repeated tool calls, and rising bills, plus seven actionable governance principles. If you maintain long-running agents, this guide will help you turn "getting dumber and more expensive" from a vague feeling into a diagnosable engineering problem.

    High Consumption Does Not Mean a Smarter Agent

    After connecting an agent to a real workflow, the typical symptom is that it occasionally seems more “aware” of historical context—while disk usage, context length, and token bills all rise together. If you treat this as just “another agent that runs,” you will miss the mechanisms that actually determine the experience: how interaction state is persisted, which information gets treated as memory, what gets discarded during compression, what gets stuffed back into context during recall, and whether tool calls are being repeated meaninglessly.

    Token is the unit in which a model reads and writes context. The cost of a single task roughly comes from four parts: system instructions and tool descriptions, the current user input, recalled history, and tool results. The last two are the easiest to lose control of. System prompts are usually relatively stable; what really inflates is the sessions, retrieval fragments, and raw tool output that keep being appended “so the agent remembers you.”

    Therefore, ranking high on consumption, or a single call getting more expensive, does not prove that a memory strategy is more advanced. It only shows that more text was read per unit task. The engineering question to ask first is: did these tokens change any decision, or did they just re-read old logs?

    Why Interaction State Grows Almost Without Bound

    Many implementations store run state in a local or remote state database. A session record often contains more than the final answer: session ID, source channel, user ID, title, model and sampling configuration, a system prompt snapshot, the full message sequence, tool names, arguments, return values, and even intermediate errors. This design has its rationale: troubleshooting, auditing, and resumable runs all need the original trajectory.

    The problem is treating a “traceable log” directly as “injectable memory.” A log’s goal is completeness; memory’s goal is improving the next decision within a limited context. A complete trajectory grows linearly or even superlinearly with usage—tool results often contain full web pages, tables, and log fragments, far larger than the user’s own words. Without hot/cold separation, hot data crowds the disk and gets read back in full on every retrieval.

    You can split state into two storage types:

    • Raw trajectory: append-only, partitioned by time and session, for auditing and replay; never enters the model by default.
    • Memory entries: short records that have been extracted, deduplicated, and scored—only these may be recalled.

    Raw trajectories belong in high-capacity, low-frequency storage; memory entries should stay small and indexable. If you need cloud archival, you can use object storage for cold trajectories and use logging and monitoring to observe capacity and call volume. Only generic storage and observability capabilities are needed here—no specific interface or billing numbers are required.

    An illustrative schema need not be tied to any specific product, as long as field responsibilities are clear:

    1. trajectory: session_id, turn_id, role, text, tool_name, tool_args_hash, result_ref, ts
    2. memory: memory_id, user_scope, type, text, entities, valid_from, confidence, source_turn

    result_ref points to an external object instead of embedding the raw tool output in every memory entry. This is the first cut in controlling size.

    “Knowing You Better” Is Usually Recall, Not Mysterious Self-Evolution

    So-called self-improvement is, in most cases, not the model’s weights being continuously trained locally. It is this: when a similar task comes in next time, relevant fragments are pulled from history and spliced into the prompt. The effect resembles remembering preferences, project terminology, and paths that have failed before. The mechanism is simple and its boundary is clear—facts that were never stored or never recalled are impossible for the model to “evolve” upon.

    This capability has three prerequisites: store it correctly, retrieve it accurately, and fit it into the context. When any prerequisite fails, users perceive the agent as “not smart enough”—not necessarily because the base model is weak, but because the memory pipeline broke at extraction, compression, or reinjection.

    Memory Should Be Layered, Not Left to Keyword Luck

    Keeping only sentences that “look important” by keyword easily diverges from what the user considers key information. Keywords favor high-frequency nouns and miss negation conditions, time ranges, and one-off but expensive decisions (for example, “do not retry this API”). A more robust approach is layering by cognitive role:

    1. Working memory: the current task’s goals, constraints, confirmed facts, and unfinished steps. Its lifecycle equals the current task; archive it when done.
    2. Episodic memory: events that happened in a specific conversation, tagged with the source turn for verification, preventing guesses from being written down as facts.
    3. Semantic memory: stable preferences, environment conventions, glossaries. Entries are short, updatable, and carry expiration times.
    4. Procedural memory: reusable operational patterns, such as which log to check first for a certain class of errors. It should be a step summary, not a paste of full tool output.

    An explicit judgment before writing is more effective than “keep everything from every conversation.” Ask four questions: will this be needed in the next step after leaving this context; can it be replaced by a shorter conclusion; does it contradict existing memories; does it contain secrets, personal data, or one-time tokens. The last category should be masked or kept out of memory entirely. Contradictory entries should not be silently overwritten—keep old and new versions with timestamps, and let the recall policy decide which one holds.

    Compression must also be reversible to “verifiable,” not reduced to vague adjectives. A bad compression is “the user discussed the release process.” A usable compression is “regression tests must run before release; on failure, proceeding is forbidden; the decision-maker is X; valid until the next version.” Numbers, proper nouns, negations, and responsible parties take priority. Tool results should first be distilled into structured fields on the program side, and only then should a summary be shown to the model.

    Recall: How History Is Reinjected Determines Quality

    Retrieval commonly has three paths, which can be combined but must have a budget:

    • Identifier-based recall: pull working memory directly by the same session or task ticket. Precise and cheap.
    • Semantic recall: use vectors or keywords to find similar episodes. Similar does not mean applicable—you must apply time and scope filters, to avoid treating a six-month-old temporary decision as a current standard.
    • Rule-based recall: always attach a small, fixed set of project-level semantic memories, such as language, repository conventions, and prohibitions. The count must have a hard cap.

    When reinjecting into context, follow “structure first, raw text second.” The recommended order is: current goals and constraints, at most a few semantic memory entries, episodic summaries relevant to the current step, and only then, if necessary, the expansion of a specific raw passage. Keep provenance for every memory (which session, which turn), so that the model or a human can spot stale information. Set token budgets: separate caps for the memory zone, the tool zone, and the user zone. When over budget, drop similar redundant entries rather than truncating a sentence mid-stream.

    A simple gate can be written as pseudocode:

    1. budget = total - system - user_input
    2. cands = filter_by_scope_and_time(retrieve(query))
    3. cands = dedupe_and_resolve_conflicts(cands)
    4. picked = []
    5. for m in rank(cands):
    6. if tokens(picked + m) > memory_budget: break
    7. picked.append(m)
    8. return picked

    Recall without a budget is essentially pouring the state database back into the prompt—consumption goes up, and so does noise.

    Forgetting, Repeated Calls, and Rising Bills Map to Different Layers

    After going live, the most painful issue is not “does the demo run”—it is that failures blur together: the agent forgets things, repeatedly calls the same tool, and costs climb daily, with no idea whether to fix the prompt, the retrieval, or the tool layer. Triage by symptom.

    Forgetting: check the write path first. Did the key constraint generate a memory entry, or is it only sitting in the raw trajectory? If the entry exists, check whether recall filters are too strict, whether ranking is being overwhelmed by longer but less relevant text, or whether the budget cut it before injection. Only then suspect the model of ignoring the memory it was given.

    Repeated tool calls: a common cause is that tool results never became an “observed fact.” In the next turn, the model cannot see a summary of the last return, so it calls again with the same arguments. The fix is to normalize tool output into a short conclusion and write it into working memory, plus apply a short-term cache for successful calls with identical arguments. The cache key is the tool name plus normalized arguments; the value holds only the conclusion and timestamp, never the oversized raw payload.

    Rising bills: separately account for four token categories: system prompt, memory recall, tool definitions, and tool results. If tool results dominate, truncate, project fields, and paginate—never feed entire logs back to the model. If memory dominates, check whether you are replaying complete history every time instead of incremental summaries. If the system prompt dominates, your tool descriptions are too thick; load tools dynamically per task instead of always mounting all of them.

    For observability, at minimum record: per-turn token composition entering the model, the number of recalled entries and reasons for discards, tool call counts and cache hit rates, and the growth rate of the state database. Without these four categories of metrics, optimization is just guesswork.

    Actionable Governance Principles

    1. Separate logs from memory. The full trajectory serves auditing; memory serves decision-making. Never share one “put everything in” table as the prompt source for both.
    2. Write with standards. Keep constraints, negations, decisions, and expiration times; discard pleasantries, repeated explanations, and large re-computable raw text.
    3. Compress to verifiable facts. Summaries must trace back to turn numbers, preventing the model from consolidating wrong memories.
    4. Recall with scope, freshness, and budget. Similarity makes a candidate, not a mandatory inclusion.
    5. Structure tool results. Summaries go into context by default; raw output goes to external references; short-term deduplication for identical calls.
    6. Privacy and permissions before “knowing the user better.” Cross-session memory must respect user or tenant boundaries to avoid cross-contamination.
    7. Periodic review. Memories go stale. Set review cycles or automatic decay for long-term semantic entries, so old habits do not keep burning tokens and misleading actions.

    None of these principles depends on a specific agent project’s directory layout. Whether state lives in an embedded database or a remote table, if you separate trajectory, memory, recall budgets, and tool caching, you can explain most cases of the agent “getting dumber” and “getting more expensive.”

    Summary

    An agent appearing to know its user better usually happens because history was saved and reinjected on similar questions—not because interaction logs piled up indefinitely. Unboundedly growing state is suitable as an audit ledger, not as context. What truly matters is: how memory is filtered before storage, how context is compressed while balancing fidelity and length, on what conditions history is recalled, and at which layer tokens are repeatedly consumed. Build these four things into an observable pipeline, and forgetting and billing turn from perceived problems into locatable engineering problems. Base model capability still matters, but over the long run, the ceiling is usually set by your memory logic—not by yet another conversational shell you bolted on.