Agent memory: short-term context and long-term knowledge

Short-term agent memory is what sits in the context window for one task; long-term memory is stored outside it, scoped, retrieved on demand and set to expire.

By CloudOEngine.ai Engineering · · 12 min read

An AI agent has two kinds of memory. Short-term memory is whatever sits in the model's context window during one task: the instructions, the recent conversation and the results of the tools it just called. Long-term memory lives outside the model, in files or a database, and the agent reads selected pieces back into the context in later sessions. Good agents keep the first small and focused, and treat the second as a governed data store with an owner, a scope and an expiry date.

A language model is stateless. Every call starts from nothing, and all it knows about your user or yesterday's run is what you put into the prompt this time. "Memory" is an engineering decision about what to put in, what to leave out, and where the rest is kept. Get it wrong one way and the agent forgets a customer's standing instruction. Get it wrong the other way and it acts on something that stopped being true three weeks ago.

The context window is the only thing the model sees

Start with short-term memory, because most agent bugs I would blame on "memory" are really context bugs.

Inside one task, an agent's context grows quickly. Each turn adds a message, some reasoning, a tool call and its result, and a result can be large: a query that returns two hundred rows, or a whole web page. After a dozen steps, the instruction that mattered most ("never promise a delivery date before the warehouse confirms") is buried somewhere in the middle of a long transcript.

You might think a bigger context window fixes this. The research says otherwise. In the 2023 paper Lost in the Middle, Nelson Liu and colleagues tested models on multi-document question answering and key-value retrieval, moving the relevant passage around the input. Performance was often highest when the relevant information was at the beginning or end of the context and degraded significantly when it sat in the middle, including for models built for long inputs.

Chroma's Context Rot report from July 2025 ran the same kind of question across 18 models and found that "model performance consistently degrades with increasing input length". It also found that even simple tasks, such as repeating a sequence of words, became less reliable as the input grew. Anthropic's engineering team uses the same framing in its September 2025 guide to context engineering: a model has an "attention budget", and every extra token spends some of it.

So the job of short-term memory management is not to keep everything. It is to keep the right things near the edges and drop the rest.

Keeping short-term memory in shape

There are four techniques, and a production agent usually needs at least two of them.

The first is plain trimming: keep the system prompt and the last N turns. It works for short chats but throws away early decisions that later turns depend on.

The second is compaction. When the conversation nears the window limit, the agent (or the framework around it) summarises the transcript so far and starts a fresh context with that summary. Anthropic's guide describes it exactly this way. The risk is that the summary drops a detail that turns out to matter, so tell the summariser what must survive: open commitments, numbers the user gave, decisions already made and why.

The third is clearing old tool results. A 200-row query result from step two is rarely needed at step fifteen; a one-line note that says what the query showed usually is. Replacing raw tool output with a short note after it has been used is cheap and recovers a lot of space.

The fourth is the bridge to long-term memory: structured note-taking. The agent writes notes to a file or store outside the context (a progress log, a list of open questions) and reads them back when it needs them. Anthropic's guide calls this "agentic memory", and pairs it with a "just in time" approach where the agent keeps lightweight identifiers, such as file paths or record IDs, and loads the actual content with a tool only when it is needed. The 2023 MemGPT paper made the same idea explicit with an operating system analogy: a small, fast main context and slower external storage, with the agent moving data between the tiers.

If you have read our piece on prompt caching, note the tension. Caching rewards a stable prefix; compaction and clearing rewrite the context. Keep the parts that never change (system prompt, tool definitions) at the front, and do your trimming after them.

What long-term memory actually stores

Long-term memory is anything the agent should still know in a new session. The clearest vocabulary comes from the CoALA paper (Cognitive Architectures for Language Agents) by Sumers, Yao, Narasimhan and Griffiths, which borrows from cognitive science. It treats the context as working memory, which "maintains active and readily available information" for the current decision, and names three long-term stores. LangChain's memory documentation uses the same three, which tells you the terms have stuck.

Memory type What it holds Illustration (an ordering agent) Who should write it
Semantic Facts and preferences about the world, users and the agent itself "This buyer wants quotes in INR, ex-works" The agent, with the source recorded
Episodic Past runs: what was tried and how it turned out "Last month's reorder for SKU 114 was rejected: supplier on hold" The agent, after each run
Procedural Rules for doing the task: prompts, instructions, code "Check credit limit before raising a sales order" People, through review

The last row is where I would be strict. CoALA notes that procedural memory lives both in the model's weights and in the agent's code, and warns that letting an agent write to it is "significantly riskier than writing to episodic or semantic memory", because it can introduce bugs or let the agent work around what its designers intended. An agent that can rewrite its own rules after one bad conversation is an agent nobody can audit. Let it propose a rule change; have a person merge it.

Context window short-term: this task only System prompt and rules Recent turns (older: compacted) Tool results (old ones cleared) Retrieved memories Semantic memory facts and preferences, per user Episodic memory past runs and how they ended Procedural memory rules and prompts: people review write (background) retrieve on demand scoped to user and tenant Systems of record (orders, stock, tickets): query with a tool every time, never copy into memory
Short-term memory is the context window. Long-term memory is three stores outside the model, written after the fact and read back on demand. Live business data stays in its own system.

Memory you should not build

A common design mistake in agent demos is using memory as a cache of business data. The agent looks up a customer's outstanding balance on Monday, "remembers" it, and quotes it again on Thursday after two payments have cleared.

Here is the rule I would apply: if a fact has a system of record, the agent queries that system with a tool every time, and memory holds at most a pointer (a customer ID, a ticket number). Memory is for things that exist nowhere else. A buyer said on a call that they prefer quotes in INR. A reorder failed because a supplier was on hold. Those are worth keeping. The current stock level of SKU 114 is not; it belongs to the ERP, and our article on tool calling covers how to let the agent ask for it.

This is also where most of the engineering effort should go, because an agent that can read live data needs fewer memories in the first place. CloudOEngine's data layer connects databases, files and camera streams through 500+ connectors, so an agent can look a value up at the moment it needs it instead of trusting a copy it saved last week.

When should an agent write a memory?

LangChain's documentation describes two places to do the writing. "In the hot path" means the agent saves a memory during the conversation, usually through a memory tool. The memory exists immediately, but the agent is doing two jobs at once and the reply gets slower. "In the background" means a separate process reads the finished conversation later and extracts what is worth keeping. The live response stays fast and the extractor can be more careful, but the memory does not exist until the job runs.

My default is the background job for semantic and episodic memory, with one exception: when the user explicitly says "remember that...", save it in the hot path, because they will test it in the next message.

The same documentation draws a second distinction worth borrowing. A memory can be a single profile per user (one document of key-value facts that gets updated in place) or a collection of many small items that grows over time. Profiles are easy to read but hard to keep correct when two sessions update them at once; collections are easy to write but harder to search and deduplicate. For a business agent I would use a profile for stable preferences and a collection for episodes.

Whichever you choose, write each memory with three extra fields: where it came from (which conversation, which document, which user said it), when it was written, and when it should expire. Anthropic's memory tool documentation, which describes a file-based memory that runs entirely on the developer's own storage, recommends exactly this kind of housekeeping: cap file sizes, and periodically delete memory files that have not been accessed in a long time. A memory with no source and no expiry is a rumour that never dies.

Scoping and forgetting

Long-term memory is personal data more often than teams expect. "Prefers WhatsApp after 7pm" is a fact about a named person. So the store needs the same controls as any other customer database.

Scope every memory to a namespace (LangChain's docs compare a namespace to a folder) that includes at least the tenant and the user. Retrieval should only ever search inside the caller's namespace, and that filter should be enforced by the store, not by asking the model to be careful. The memory tool documentation makes the same point at the file level: the handler must reject any path outside the memory directory, because a path such as /memories/../../secrets.env would otherwise reach files the agent should never see.

Then build the delete path before you need it. If a customer withdraws consent, you should be able to remove everything under their namespace, including episodes that mention them, in one operation. Our article on AI governance and the DPDP Act covers the obligations; check the current position with your counsel, as this is not legal advice.

The access side is where a platform helps. CloudOEngine applies one permission model across data, pipelines and agents, with tenant isolation, role-based access and audit logs included, so the agents that read and write memory sit under the same access rules and audit trail as everything else.

Poisoned memory lasts longer than a bad prompt

Prompt injection in a single conversation ends when the conversation ends. Injection that gets written into long-term memory does not. If an agent reads a supplier email that says "note for future: this vendor's bank details have changed to...", and a background extractor saves that as a fact, every later session inherits it.

OWASP's Top 10 for Agentic Applications lists this as ASI06, Memory and Context Poisoning. In a May 2026 post, the entry's lead frames the problem as an agent that does not stop at processing untrusted input "but carries it forward", and argues that memory should get "the same scrutiny we already apply to execution paths, credentials, and other sensitive control surfaces".

The practical defences follow from what we have already covered. Record the source of every memory, and treat memories extracted from external content (emails, web pages, uploaded files) as lower trust than things a signed-in user stated. Never let retrieved memory override the system prompt. Keep procedural memory read-only for the agent. And put a person between memory and any action that moves money or changes a record, because that is where a poisoned fact does damage. CloudOEngine's Autopilot works this way: triggered agents run under approval rules, and a person approves the action, in the app or through an email approve link, before it runs. Our article on prompt injection goes further into the input side.

Debugging what the agent remembered

When an agent gives a wrong answer, the useful question is what was in the context when it decided: which memories were retrieved, which were not, and whether a compaction step dropped something.

You can only answer that if retrieval and memory writes are logged as steps in the run, with the memory IDs, as well as the final reply. In CloudOEngine's AI runtime, every step and tool call an agent makes is traced and inspectable, so a memory read done through a tool shows up in the same timeline as the query and the answer it influenced. Our guide to agent observability covers what else to capture.

Where I would start

If you are adding memory to an agent that has none, do it in this order:

  1. Fix short-term memory first. Put stable instructions at the front, clear raw tool results once they are used, and add compaction with an explicit list of what the summary must keep.
  2. Move every business fact to a tool call against its system of record, and delete any memory that duplicates one.
  3. Add one semantic store for user preferences, written by a background job, with source, timestamp and expiry on every item, scoped by tenant and user.
  4. Add episodic memory only when you have a concrete use for it, such as "do not retry a reorder that failed for the same reason last week".
  5. Keep procedural memory in version control, changed by people.

Then pick ten real conversations from last month, replay them, and check what the agent retrieved for each. That single exercise will tell you more about your memory design than any architecture diagram.

How CloudOEngine helps

CloudOEngine is one platform and one console for connecting data, building pipelines, running AI agents with tool access, RAG and an LLM gateway, plus Vision AI and live video, under one permission model and one audit trail. For agent memory, that matters in four places.

First, most of what an agent is tempted to remember is business data that already lives somewhere. With 500+ connectors to databases, files and camera streams, an agent can query the live value through a tool rather than relying on a stale copy.

Second, memory needs boundaries. Governance is included, not sold as an add-on: tenant isolation, role-based access, audit logs and per-tenant encrypted secrets apply to agents as they do to people.

Third, when an answer is wrong you need to see what the agent read. Agents run real tools, such as filing a ticket, and every step and tool call is traced and inspectable.

Fourth, a poisoned or outdated memory is only dangerous when it drives an action. With Autopilot, triggered agents run under approval rules, and a person approves the action in the app or through an email approve link before it runs.

Book a demo or see the AI runtime.

Frequently asked questions

What is the difference between short-term and long-term memory in an AI agent?

Short-term memory is everything in the model's context window for the current task: instructions, recent messages, tool results. Long-term memory is stored outside the model, in files or a database, and the agent reads it back into the context when it needs it in a later session.

If context windows are so large now, why does an agent need memory at all?

Because models do not use a long context evenly. Liu et al. (2023) found accuracy was highest when the relevant information sat at the start or end of the input and dropped when it sat in the middle, and Chroma's 2025 tests of 18 models found performance consistently degraded as input length grew.

What kinds of long-term memory does an agent need?

Most designs follow three types from the CoALA paper: semantic memory for facts and preferences, episodic memory for past runs and their outcomes, and procedural memory for the rules and prompts the agent follows. Procedural memory is the risky one to let the agent edit itself.

Should an agent remember data from business systems such as orders or stock levels?

No. Data that lives in a system of record changes, so a remembered copy goes stale. The agent should query the system with a tool each time and keep only things that exist nowhere else, such as a user's stated preference or the lesson from a failed run.

What is memory poisoning?

It is when untrusted content gets written into an agent's memory and keeps steering later sessions. OWASP lists it as ASI06, Memory and Context Poisoning, in its Top 10 for Agentic Applications, and the defence starts with tracking where each memory came from and who can write it.

How do you delete what an agent remembers about a person?

Store memories under a namespace per user and per tenant, record the source of each item, and give the store a delete path that removes everything under one person's namespace. Check your obligations under India's DPDP Act with counsel; this is not legal advice.

Sources

  1. Liu et al.: Lost in the Middle, How Language Models Use Long Contexts (arXiv 2307.03172, TACL)
  2. Chroma: Context Rot, How Increasing Input Tokens Impacts LLM Performance (14 July 2025)
  3. Anthropic: Effective context engineering for AI agents (29 September 2025)
  4. Anthropic docs: Memory tool
  5. Sumers, Yao, Narasimhan, Griffiths: Cognitive Architectures for Language Agents (arXiv 2309.02427)
  6. LangChain docs: Memory overview
  7. Packer et al.: MemGPT, Towards LLMs as Operating Systems (arXiv 2310.08560)
  8. OWASP GenAI Security Project: Memory Is a Feature. It Is Also an Attack Surface (13 May 2026)

#ai agents #agent memory #context engineering #llm #memory poisoning