Memory Write, Recall and Forgetting Policies
A memory that keeps everything becomes noise. Write rules for what enters, what comes back and what leaves.
A memory policy answers three questions. Write: is this worth keeping, allowed to be kept and reliable enough? Recall: which stored items help the current step, and how many? Forget: when does an item expire, get merged, get corrected or get deleted on request? Express the answers as rules in code, log each decision and test them like any other business logic.
What you will learn: write gates, memory types and lifetimes, recall scoring, consolidation and summarization, decay and expiry, and how to test and tune the policies.
Prerequisites: Agent Memory Types and Persistence. Memory Storage: Vector, SQL or Knowledge Graph covers where memories live.
More memory is not better memory
Imagine an assistant that stores every sentence you type. After a month it recalls your old address alongside the new one, a joke as a preference and a one-time request as a standing rule. Search results fill with near-copies. You cannot tell what it believes, and deleting anything is guesswork.
Good memory behaves more like a well-kept notebook. It records what will matter again, in short and clear form, with a date and a source. It replaces facts that changed and throws away notes whose purpose has passed. Those choices are the policy.
Types and lifetimes
| Type | Example | Typical lifetime | Update style |
|---|---|---|---|
| Stated preference | Short written answers | Until changed, reviewed yearly | Replace |
| Fact about the work | Project uses fiscal weeks | Months, with review date | Replace, keep history |
| Event (episodic) | Export failed on Tuesday | Weeks, or summarized | Append |
| Procedure | Steps that fixed the export | While still valid | Versioned, reviewed |
| Task state | Waiting for approval | Until the task ends | Overwrite |
These lifetimes are starting points to adjust to your purpose and legal duties.
Write policies: what should an agent remember?
A candidate should pass every test:
- Useful again. Will it change a future answer or action?
- Allowed. Is the person aware and is the category permitted? Secrets, payment numbers and sensitive categories are refused by default.
- Reliable. Did the user state it, or a system of record supply it? A model's guess is not a fact.
- Specific. Can it stand alone, with who, what and when?
- New. Does it add to or change what is already stored?
Who decides to write?
All three should pass through the same gate. The model may propose; code decides. Writing in the background keeps the conversation fast but means a new preference may not apply until the job finishes, so handle explicit requests immediately.
Rules you can run
"""Write, recall and forgetting policies as plain, testable rules."""
import math
import re
BLOCKED = re.compile(r"password|card number|diagnos|\b\d{13,19}\b", re.I)
TTL_DAYS = {"preference": 365, "fact": 180, "task": 14}
def write_decision(c):
if BLOCKED.search(c["text"]):
return "reject: sensitive"
if c["source"] not in ("user", "system"):
return "reject: unverified source"
if c["kind"] not in TTL_DAYS:
return "reject: not a memory type"
if not c["reusable"]:
return "reject: single use"
return f"store for {TTL_DAYS[c['kind']]} days"
def words(t):
return set(re.findall(r"[a-z]+", t.lower()))
def recall_score(m, query, today):
relevance = len(words(m["text"]) & words(query)) / max(1, len(words(query)))
recency = math.exp(-(today - m["last_used"]) / 60)
return round(0.6 * relevance + 0.2 * recency + 0.2 * m["importance"], 2)
def sweep(memories, today):
keep, gone = [], []
for m in memories:
expired = today - m["created"] >= TTL_DAYS[m["kind"]]
(gone if expired else keep).append(m)
return keep, gone
CANDIDATES = [
{"text": "I like short answers", "source": "user", "kind": "preference", "reusable": True},
{"text": "My password is hunter2", "source": "user", "kind": "fact", "reusable": True},
{"text": "User seems stressed", "source": "model", "kind": "fact", "reusable": True},
{"text": "Show me page two", "source": "user", "kind": "task", "reusable": False},
]
for c in CANDIDATES:
print(f"{c['text'][:24]:24} -> {write_decision(c)}")
def mem(text, kind, created, last_used, importance):
return dict(text=text, kind=kind, created=created,
last_used=last_used, importance=importance)
MEMORIES = [ # times are day numbers
mem("prefers short answers in reports", "preference", 10, 195, 0.6),
mem("quarterly report is due on Friday", "task", 190, 198, 0.8),
mem("office moved to Pune", "fact", 5, 20, 0.4),
mem("draft the old budget report", "task", 100, 101, 0.5),
]
today = 200
keep, gone = sweep(MEMORIES, today)
print("forgotten:", [m["text"] for m in gone])
query = "write the quarterly report"
for m in sorted(keep, key=lambda m: -recall_score(m, query, today)):
s = recall_score(m, query, today)
print(f"{s:.2f} {'recall' if s >= 0.4 else 'skip '} {m['text']}")
Output:
I like short answers -> store for 365 days
My password is hunter2 -> reject: sensitive
User seems stressed -> reject: unverified source
Show me page two -> reject: single use
forgotten: ['office moved to Pune', 'draft the old budget report']
0.65 recall quarterly report is due on Friday
0.30 skip prefers short answers in reports
Four candidates show four outcomes. The pattern used to block sensitive text is only a demonstration; real systems need proper classification and human review of what slips through. The second half shows expiry removing two old items, then scoring deciding that only the report deadline is worth recalling for this request.
Guesses about mood, health, beliefs or finances can be wrong and harmful, and may be regulated. Do not store them. If a feature truly depends on an inference, ask the person to confirm it and show it where they can remove it.
Recall policies: what should an agent retrieve?
Recall begins with filters: correct scope, active status, not expired, permitted for this purpose. Then rank. A well-known design from the Generative Agents research combines relevance to the current situation, recency with exponential decay and importance assigned when the memory was created. The script above uses the same three ingredients with its own weights.
When to recall
| Trigger | What loads | Caution |
|---|---|---|
| Start of every session | Small core profile and open tasks | Keep it tiny |
| Each user turn | Items relevant to the message | Needs a score floor |
| Agent decides to search | Whatever it asks for within scope | It may forget to ask |
| Before a risky action | Related constraints and approvals | Must come from trusted records |
How much to recall
Set a maximum count and a minimum score. Returning five items when only one is relevant invites the model to use the other four. Show each recalled memory with its date and source so the model can weigh it, and instruct the agent to treat memory as possibly outdated information, with the current conversation taking priority when they conflict.
Consolidation and summarization
Consolidation is maintenance that runs outside the conversation. It merges duplicates, resolves contradictions, turns many small events into a few durable statements and removes what no longer matters.
| Operation | Example | Safeguard |
|---|---|---|
| Merge | Three notes saying the same preference | Keep the links to originals |
| Supersede | New office replaces old | Mark old inactive, record why |
| Generalize | Several failures become one known issue | Require several independent events |
| Summarize | A long project history into key points | Mark as derived, never raise trust |
| Prune | Unused low-importance items | Report counts and allow review |
A summary can silently turn "I might move to Mumbai" into "lives in Mumbai". Preserve uncertainty words, run consolidation as a separate step with its own tests, and be able to undo a run. Memory Integrity, Isolation and Sharing covers conflict rules in detail.
Forgetting: decay, expiry and deletion
Decay
Decay lowers ranking over time without removing anything. With a half-life of 60 days, an item untouched for 60 days counts half as much on recency, and after 180 days one eighth. Choose the half-life per type: fast for events, slow or none for stated preferences. Refreshing recency on every recall can trap an agent in its habits, because whatever it recalled becomes easier to recall again. Refresh only when the item proved useful or was confirmed.
Expiry and time to live
Expiry is a hard stop. Set the date when writing, filter on it at read time and delete in a scheduled job. Filtering at read time matters because cleanup jobs run late or fail.
Deletion and correction
A person's request to forget must remove the item, earlier versions, derived summaries, embeddings and cached copies, within a stated period. Design for this at the start by recording which items each summary came from. Tell users what is stored, let them correct it and let them switch memory off.
| Mechanism | Reversible? | Use for |
|---|---|---|
| Decay | Yes | Reducing noise |
| Supersede | Yes, history kept | Changed facts |
| Archive | Yes, outside recall | Audit needs within retention limits |
| Expiry | No after cleanup | Time-bound information |
| User deletion | No | Requests and legal duties |
Testing and tuning policies
Write scenario tests with a simulated clock. Each states what is said over several days, then what should be stored, recalled and absent. Include a changed fact, a hedged statement, a sensitive disclosure, an instruction hidden in a document and a deletion request.
| Signal | Suggests |
|---|---|
| Users correct the agent often | Writes too eager or supersession broken |
| Agent asks again for known facts | Writes too strict or recall too weak |
| Irrelevant details appear in answers | No score floor or too many items |
| Store grows without limit | No expiry or consolidation |
| Old values resurface | Derived copies not updated |
Change one rule at a time and replay the scenarios. Build and Evaluate a Memory Layer shows how to turn these checks into scores.
A policy on one page
Store: stated work preferences, project facts and resolved issues. Never store: credentials, health details, remarks about colleagues, model guesses. Recall: at most five items above the score floor, each shown with a date. Expire: events after 90 days, facts reviewed every 180 days. Control: users see, edit and delete their entries; deletion completes within one day; every write and removal is logged without sensitive content.
A walk through three sessions
Policies are easiest to judge against a story. Follow one user across a few weeks and watch each rule act.
| Day and message | Write decision | Effect on later recall |
|---|---|---|
| Day 1: "Keep your answers short." | Store as a stated preference | Included in the small core profile |
| Day 1: "Here is the error log." | Do not store the log; keep it for this task | Gone when the task ends |
| Day 8: "The export problem was a date format." | Store as a resolved issue with the fix | Recalled for similar export questions |
| Day 9: "I might switch teams next quarter." | Do not store as fact; at most a dated, hedged note if policy allows | Never presented as a current team |
| Day 40: "Long explanations are fine for design topics." | Refine the preference with a condition | Both parts shown together |
| Day 41: "Forget what I said about the export." | Delete the issue note and derived text | Absent from every later recall |
The hard cases are the conditional preference and the hedged remark. A key-value profile that only holds "answer length: short" loses the condition on day 40. Store short sentences that keep conditions, and let supersession act on the whole statement, not on a single word.
Explaining decisions to the user
When the agent saves something, say so briefly and offer an undo. When it uses a memory in a way that shapes the answer, it can mention the source, for example that this follows a preference stated last month. These small signals catch wrong memories early, which is far cheaper than repairing the trust lost when a person discovers them by surprise.
Policy changes over existing data
Tightening a write rule does not remove items stored under the old one. Run the new rule over existing memories, report what would be removed, review a sample and then apply it. Version your policy and record the version on each item, so you know which rules admitted it and can answer when someone asks why the system holds it.
Measuring the effect of a policy change
Before changing a threshold, record how the current policy performs on the scenarios and on a sample of real, permitted data: how many candidates are stored per session, how many recalls return nothing, how often users correct or delete an entry. After the change, compare the same figures. A policy that stores half as much but triples the number of repeated questions has moved the problem instead of solving it. Keep the previous version available so that you can return to it.
Common mistakes
- Letting the model write directly to the store with no gate.
- Storing whole transcripts as memories.
- Keeping contradicting facts both active.
- Relying on cleanup jobs without filtering expired items at read time.
- Offering deletion that leaves summaries behind.
Checklist
- Memory types, sources and lifetimes are written down.
- A code gate checks every write.
- Recall applies scope filters, a score floor and a maximum count.
- Changed facts supersede older ones.
- Consolidation preserves uncertainty and links to sources.
- Expiry is enforced at read time and by cleanup.
- People can view, correct, delete and disable memory.
- Scenario tests with a simulated clock run on every change.
Frequently asked questions
Should the model choose what to remember?
It is good at proposing candidates. Whether a candidate is allowed, reliable and worth keeping should be checked by rules you can test.
What half-life should I use?
There is no universal value. Estimate how long each type stays useful, test scenarios across that span and adjust from observed misses.
Is forgetting a risk for quality?
Removing something needed is a risk, which is why you test recall. Keeping stale and irrelevant items is also a risk, and often a larger one.
Do I need user consent for memory?
Be transparent and give control in any case. Whether you need consent or another legal basis depends on the data and jurisdiction, so ask your privacy advisers.
References and further reading
- Park et al.: Generative agents
- Packer et al.: MemGPT
- Sumers et al.: Cognitive architectures for language agents
- Chhikara et al.: Mem0, building production-ready agent memory
- GDPR Article 17: right to erasure
Next steps
Memory Integrity, Isolation and Sharing
Protect integrity and decide what agents may share.
Build and Evaluate a Memory Layer
Implement the policies and score them.
Fairness, Privacy, Data and Copyright
The wider duties around personal data.