Long-Term Memory for AI Agents: Comparing Pinning, Compaction, and Retrieval

A long conversation is not the same thing as a reliable memory. An agent may see thousands of earlier tokens and still miss the one constraint that determines whether its next action is safe. This guide builds a small memory system that separates durable facts, compressed history, and on-demand recall, then shows how to evaluate whether each part helps.
Updated November 28, 2026
The memory problem
An agent needs to retain at least three different kinds of information as a conversation grows:
- Facts: stable information such as a user’s preferred programming language or a project’s deployment constraint.
- Plans: work that is in progress, including decisions, open questions, and the next intended step.
- Constraints: rules that must remain visible before an action, such as “do not send messages without approval” or “use the staging database.”
Treating all three as ordinary chat history creates a fragile system. Recent messages are easy to include but may be less important than an older constraint. A summary is cheaper than the original transcript but can omit a qualifier. A search index can recover relevant passages but may retrieve a plausible-looking statement that is no longer true.
The useful abstraction is therefore not “give the model more history.” It is a memory pipeline:
conversation
├── pinned facts and constraints
├── structured working state
├── compacted episodic history
└── searchable memory entries
In this article, long-term memory means information retained beyond the current prompt assembly step. It does not imply that every retained item is permanent, correct, or safe to use without verification.
Three mechanisms, three jobs
The design compares pinning, compaction, and retrieval. They solve different problems and should not be treated as interchangeable.
Pinning: protect high-value state
A pinned item is deliberately placed into every relevant prompt, or into every prompt for a defined scope. Pinning is appropriate for facts that are both important and relatively stable:
{
"id": "constraint-001",
"kind": "constraint",
"text": "Never deploy directly to production.",
"scope": "workspace:demo-project",
"source": "user",
"status": "active",
"created_at": "2026-11-28T09:00:00Z",
"expires_at": null
}
Pinning gives predictable visibility. Its cost is prompt space and staleness risk. If the system pins too much, the model receives a crowded block that competes with the current task. If an old preference changes, an unreviewed pin can become an instruction conflict.
Compaction: preserve the shape of a long episode
Context-window pressure usually arrives before the conversation is semantically complete. Compaction replaces older turns with a structured summary that preserves decisions, unresolved work, assumptions, and references to source messages.
A useful compacted record is more constrained than a prose recap:
{
"episode_id": "episode-014",
"goal": "Add webhook retries without duplicate side effects.",
"decisions": [
"Use an idempotency key for every delivery attempt."
],
"constraints": [
"Do not change the public webhook payload."
],
"open_questions": [
"What retry delay is acceptable for the worker?"
],
"artifacts": [
"src/webhooks/dispatcher.ts"
],
"source_message_ids": ["m-201", "m-206", "m-214"]
}
Compaction reduces volume while keeping a coherent episode. It is not a source of truth: the summary can be incomplete or wrong. For high-risk decisions, retain a link to the original evidence and allow the agent to retrieve it.
Retrieval: bring back relevant evidence
Retrieval-augmented generation (RAG) selects stored entries for a particular query. A minimal system can use lexical search; a more advanced system may add embeddings and a vector store.
Retrieval is useful for facts that are too numerous to pin and too specific to include in every summary. It introduces its own failure modes: the right item may not be returned, an obsolete item may rank highly, or several similar items may create an unresolved conflict.
| Mechanism | Strength | Primary risk | Good default use |
|---|---|---|---|
| Pinning | Predictable visibility | Staleness and prompt bloat | Active constraints and a small set of durable preferences |
| Compaction | Lower context cost | Omission or distortion | Completed or paused conversation episodes |
| Retrieval | Selective access to a large store | Misses, false matches, and conflicts | Long-tail facts and evidence lookup |
Prototype architecture
The prototype uses four stores with explicit ownership:
- Pins: small, reviewed records injected into the prompt.
- Working state: the current goal, plan, blockers, and next action.
- Episodic summaries: compacted records for completed or paused sections of a conversation.
- Memory entries: searchable facts or evidence with timestamps and status.
The prompt builder should assemble them in a fixed order:
system policy
+ active constraints
+ current working state
+ retrieved evidence
+ recent conversation turns
+ current user request
Ordering is a policy choice, not a guarantee that the model will obey every item. The application should validate actions independently. Memory can inform an agent; it should not silently become authorization.
Memory record schema
{
"id": "mem-0007",
"kind": "fact",
"text": "The staging API requires the X-Workspace header.",
"scope": "workspace:demo-project",
"source": {
"type": "conversation",
"message_ids": ["m-102", "m-103"]
},
"status": "active",
"confidence": "reported",
"valid_from": "2026-11-28T10:00:00Z",
"valid_until": null,
"supersedes": null,
"updated_at": "2026-11-28T10:02:00Z"
}
The status field supports explicit invalidation. The source field provides provenance. The validity fields distinguish “known at the time” from “currently active.” The supersedes field makes updates inspectable instead of silently overwriting history.
Extraction policy
Extraction should be conservative. The extractor proposes memory candidates; a policy layer decides whether to save them. A practical candidate must answer:
- What exactly should be remembered?
- Who or what is the source?
- What scope does it apply to?
- When might it expire?
- Could retaining it expose personal or secret data?
- What would prove that it is no longer valid?
Do not store passwords, access tokens, private keys, payment details, or unnecessary personal data. A memory system should also support deletion and correction, even if the first prototype uses a local file.
Build the prototype
The following example uses Python’s standard library and JSON Lines. It is intentionally small so that the storage, ranking, and evaluation logic remain visible. It does not require an external model, database, credentials, or network access.
1. Create a fixture
Save this as memory_fixture.jsonl:
{"id":"m1","kind":"constraint","text":"Never deploy directly to production.","scope":"demo-project","status":"active","source":"user"}
{"id":"m2","kind":"fact","text":"The staging API requires the X-Workspace header.","scope":"demo-project","status":"active","source":"conversation"}
{"id":"m3","kind":"plan","text":"Add webhook retries with an idempotency key before changing worker concurrency.","scope":"demo-project","status":"active","source":"conversation"}
{"id":"m4","kind":"fact","text":"The project uses TypeScript for application code.","scope":"demo-project","status":"active","source":"user"}
{"id":"m5","kind":"fact","text":"The old webhook endpoint is scheduled for removal after migration.","scope":"demo-project","status":"superseded","source":"conversation"}
2. Implement lexical retrieval
This baseline uses token overlap. It is not semantic search, but it is deterministic and gives you a reference point before adding embeddings.
# memory_baseline.py
import json
import re
import sys
from pathlib import Path
STOP = {
"the", "a", "an", "and", "or", "to", "for", "of", "in",
"on", "with", "is", "are", "this", "that"
}
def tokens(text):
words = re.findall(r"[a-z0-9][a-z0-9_-]*", text.lower())
return {word for word in words if word not in STOP}
def load_records(path):
records = []
for line in Path(path).read_text(encoding="utf-8").splitlines():
if line.strip():
records.append(json.loads(line))
return records
def score(query, record):
query_tokens = tokens(query)
record_tokens = tokens(record["text"])
if not query_tokens:
return 0.0
return len(query_tokens & record_tokens) / len(query_tokens)
def search(query, records, limit=5):
ranked = []
for record in records:
if record.get("status") != "active":
continue
ranked.append((score(query, record), record))
ranked.sort(key=lambda item: (-item[0], item[1]["id"]))
return ranked[:limit]
if __name__ == "__main__":
if len(sys.argv) < 3:
raise SystemExit("usage: python memory_baseline.py FILE QUERY")
path = sys.argv[1]
query = " ".join(sys.argv[2:])
for value, record in search(query, load_records(path)):
print(f"{value:.3f}\t{record['id']}\t{record['text']}")
Run a query:
python memory_baseline.py memory_fixture.jsonl "what header does staging require"
The output is an observation from your local run. Record it as such; do not turn it into a general performance claim. The baseline should exclude inactive records, keep a deterministic tie-breaker, and expose the score so that later changes can be compared.
3. Add pinning and prompt assembly
# prompt_assembly.py
import json
from pathlib import Path
def load(path):
return [
json.loads(line) for line in Path(path).read_text(encoding="utf-8").splitlines()
if line.strip()
]
def active(records):
return [r for r in records if r.get("status") == "active"]
def pinned(records):
return [
r for r in active(records)
if r.get("kind") == "constraint"
]
def render(records, retrieved, recent_turns, user_request):
sections = []
constraints = pinned(records)
if constraints:
sections.append("ACTIVE CONSTRAINTS:\n" + "\n".join(
f"- {item['text']}" for item in constraints
))
if retrieved:
sections.append("RETRIEVED MEMORY:\n" + "\n".join(
f"- [{item['id']}] {item['text']}" for item in retrieved
))
if recent_turns:
sections.append("RECENT CONVERSATION:\n" + "\n".join(recent_turns))
sections.append("CURRENT REQUEST:\n" + user_request)
return "\n\n".join(sections)
if __name__ == "__main__":
records = load("memory_fixture.jsonl")
prompt = render(
records=records,
retrieved=[records[1], records[2]],
recent_turns=["User: We need a safe retry design."],
user_request="Draft the implementation checklist."
)
print(prompt)
In production, pin selection should be scoped to the current workspace, user, tenant, or task. A global pin is easy to implement and easy to misuse.
4. Represent compaction explicitly
Instead of storing a single free-form summary, store fields that downstream code can inspect:
{
"episode_id": "episode-014",
"status": "compacted",
"goal": "Implement webhook retries.",
"decisions": [
"Use idempotency keys.",
"Keep the public payload unchanged."
],
"constraints": [
"Deploy only through staging."
],
"open_questions": [
"Choose the worker retry backoff."
],
"next_action": "Write the retry state transition table.",
"source_message_ids": ["m-201", "m-206", "m-214"],
"created_at": "2026-11-28T11:00:00Z"
}
A compaction prompt should instruct the summarizer to preserve negations, numbers, names, deadlines, and unresolved questions. It should also require the summarizer to mark uncertainty rather than fill gaps.
Summarize the episode as JSON with:
- goal
- decisions
- constraints
- open_questions
- next_action
- source_message_ids
Preserve negations, qualifiers, dates, identifiers, and explicit uncertainty.
Do not invent decisions. If a field is unknown, use an empty array or null.
Evaluate retrieval quality
Retrieval quality should be tested separately from answer quality. First ask whether the correct memory entry was returned. Only then evaluate whether the agent used it correctly.
Create a labeled query set
A query set contains a question and the IDs of the records that are acceptable answers. Include paraphrases, short queries, ambiguous queries, and queries that should return nothing.
[
{
"query": "What header is required by staging?",
"relevant_ids": ["m2"]
},
{
"query": "What is the safe deployment rule?",
"relevant_ids": ["m1"]
},
{
"query": "How should webhook retries be made safe?",
"relevant_ids": ["m3"]
},
{
"query": "What is the database password?",
"relevant_ids": []
}
]
The final query is a safety case. A system should not manufacture a memory result simply because the query expects one.
Measure precision and recall
Precision asks how many returned items were relevant. Recall asks how many relevant items were returned. For a top-k result set:
precision@k = relevant returned items / returned items
recall@k = relevant returned items / all relevant items
For an empty-relevance query, separately record whether the system abstained. Do not count “returned nothing” as ordinary recall success; it is a different behavior that should be evaluated as an abstention or safety outcome.
Run an evaluation script
# evaluate.py
import json
from pathlib import Path
from memory_baseline import load_records, search
def main():
records = load_records("memory_fixture.jsonl")
cases = json.loads(Path("queries.json").read_text(encoding="utf-8"))
k = 3
total_precision = 0.0
total_recall = 0.0
scored = 0
abstention_correct = 0
abstention_cases = 0
for case in cases:
results = search(case["query"], records, limit=k)
returned = [record["id"] for score, record in results if score > 0]
relevant = set(case["relevant_ids"])
if not relevant:
abstention_cases += 1
if not returned:
abstention_correct += 1
print(case["query"], "abstention", not returned)
continue
scored += 1
hit_count = len(set(returned) & relevant)
total_precision += hit_count / max(len(returned), 1)
total_recall += hit_count / len(relevant)
print(case["query"], returned, "hits", hit_count)
if scored:
print("precision_at_k", total_precision / scored)
print("recall_at_k", total_recall / scored)
if abstention_cases:
print("abstention_accuracy",
abstention_correct / abstention_cases)
if __name__ == "__main__":
main()
Run it with:
python evaluate.py
Save the complete output, the fixture version, the query-set version, the retrieval configuration, and the date. A score without its dataset and configuration is not reproducible evidence.
Compare strategies, not just one implementation
Run at least three conditions:
- Recent context only: retrieve nothing beyond the latest turns.
- Pinning plus recent context: inject active constraints and use no search.
- Pinning, compaction, and retrieval: combine all three mechanisms.
Keep the query set fixed. Report exact values from your run, not expected values. Also report the number of records, the value of k, the token budget if a model is involved, and any filtering or reranking rules.
Failure cases and limitations
Stale pins
A pinned preference can outlive the project decision that created it. Give pins a scope, an owner, a timestamp, and a review or expiry rule. When a new item contradicts an old one, mark the old item as superseded rather than relying on insertion order.
Incorrect extraction
An extractor can convert a suggestion into a fact, mistake a hypothetical for a decision, or attach a statement to the wrong user. Use a proposal state such as candidate and require confirmation for high-impact memories.
Summary loss
Compaction may remove a small word with large consequences: “not,” “only,” “after,” or “unless.” Test summaries against source transcripts with a checklist for negation, constraints, quantities, deadlines, and named artifacts.
Retrieval collisions
Similar records may describe different projects or different time periods. Always filter by scope before ranking. If multiple active records conflict, return the conflict for resolution instead of selecting one silently.
Vocabulary mismatch
Lexical search can miss paraphrases. Embeddings may improve semantic matching, but they can also make broad or conceptually adjacent records look relevant. Compare an embedding-based system with the lexical baseline on the same labeled queries.
Prompt injection through memory
Stored text is untrusted input. A memory entry that says “ignore all previous instructions” must remain data, not become policy. Keep system rules separate from retrieved content, delimit memory clearly, and validate tool calls outside the model.
Privacy and retention
Memory increases the lifetime and reach of sensitive information. Define retention periods, deletion behavior, tenant isolation, access controls, and audit events before adding personal data. For a first prototype, use synthetic records only.
Evaluation leakage
Do not build the query set from the same phrases used to create the memory records and then describe the result as broad semantic performance. Include independently written paraphrases and negative cases. Keep a held-out set for later checks.
Practical design rules
- Pin less than you think. Pin active constraints and a small amount of durable state. Search for the rest.
- Make every memory inspectable. Store source, scope, status, timestamps, and replacement relationships.
- Separate proposal from truth. Extraction should produce candidates; policy should approve, reject, expire, or supersede them.
- Preserve evidence links during compaction. A summary is useful because it is compact, but trustworthy because it can point back to source.
- Evaluate retrieval before generation. Measure whether the right evidence is available before judging the final answer.
- Include abstention tests. A memory system must be able to say that it has no supported answer.
- Keep authorization outside memory. A remembered preference is not permission to perform an irreversible action.
- Version the memory format. Schema changes should be migratable and reviewable.
A practical first milestone is not a full autonomous memory layer. It is a small system that can answer four questions reliably:
- What is currently pinned, and why?
- What was compressed, and which source messages support it?
- Which memories were retrieved for this request?
- What happened when the memory was wrong, stale, or absent?
Once those answers are visible, you can make meaningful comparisons. Pinning gives deterministic coverage for a narrow set of high-value constraints. Compaction controls context growth while preserving episode structure. Retrieval scales access to a larger store, provided that relevance, freshness, scope, and abstention are measured rather than assumed.
Continue with the Agent Lab Journal guides or look up unfamiliar terms in the glossary.