Memory Write, Recall and Forgetting Policies

A memory that keeps everything becomes noise. Write rules for what enters, what comes back and what leaves.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Beginner Why an agent should forget

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.

Candidatesomething said or observed
Write gateallowed, reliable, reusable?
Activerecalled when relevant
Consolidatedmerged, superseded
Removedexpired or deleted
Every memory should have an entrance rule and an exit.

Types and lifetimes

TypeExampleTypical lifetimeUpdate style
Stated preferenceShort written answersUntil changed, reviewed yearlyReplace
Fact about the workProject uses fiscal weeksMonths, with review dateReplace, keep history
Event (episodic)Export failed on TuesdayWeeks, or summarizedAppend
ProcedureSteps that fixed the exportWhile still validVersioned, reviewed
Task stateWaiting for approvalUntil the task endsOverwrite

These lifetimes are starting points to adjust to your purpose and legal duties.

Intermediate Write and recall policies

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?

ExplicitThe user says "remember this". Clear consent, captures little.
Agent toolThe model calls a save tool. Flexible, needs a gate behind it.
Background extractionA later job mines transcripts. No delay, easy to overreach.

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.

Inferred traits deserve special care

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

TriggerWhat loadsCaution
Start of every sessionSmall core profile and open tasksKeep it tiny
Each user turnItems relevant to the messageNeeds a score floor
Agent decides to searchWhatever it asks for within scopeIt may forget to ask
Before a risky actionRelated constraints and approvalsMust 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.

Expert Consolidation, forgetting and tuning

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.

OperationExampleSafeguard
MergeThree notes saying the same preferenceKeep the links to originals
SupersedeNew office replaces oldMark old inactive, record why
GeneralizeSeveral failures become one known issueRequire several independent events
SummarizeA long project history into key pointsMark as derived, never raise trust
PruneUnused low-importance itemsReport 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.

MechanismReversible?Use for
DecayYesReducing noise
SupersedeYes, history keptChanged facts
ArchiveYes, outside recallAudit needs within retention limits
ExpiryNo after cleanupTime-bound information
User deletionNoRequests 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.

SignalSuggests
Users correct the agent oftenWrites too eager or supersession broken
Agent asks again for known factsWrites too strict or recall too weak
Irrelevant details appear in answersNo score floor or too many items
Store grows without limitNo expiry or consolidation
Old values resurfaceDerived 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

Illustrative example: policy for an internal helper

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 messageWrite decisionEffect on later recall
Day 1: "Keep your answers short."Store as a stated preferenceIncluded in the small core profile
Day 1: "Here is the error log."Do not store the log; keep it for this taskGone when the task ends
Day 8: "The export problem was a date format."Store as a resolved issue with the fixRecalled 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 allowsNever presented as a current team
Day 40: "Long explanations are fine for design topics."Refine the preference with a conditionBoth parts shown together
Day 41: "Forget what I said about the export."Delete the issue note and derived textAbsent 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

Next steps