What should an AI agent be allowed to write to its memory? Less than it wants to. A write policy sits between "the agent decided to remember something" and the store. It does four things: rejects what shouldn't be stored, merges duplicates, supersedes outdated facts, and gives short-lived memories an expiry date. Without one, memory gets worse the longer you use it, and you won't notice until the agent confidently repeats last month's staging port.
Most agent memory work goes into retrieval: better embeddings, hybrid search, reranking. But retrieval can only return what was written, and the most common memory failures I see are write-side. The same fact is stored five times with slightly different wording. An old fact and its correction sit side by side. A "halfway through the auth migration" note keeps getting recalled three months after the migration shipped. A token pasted into a chat gets saved as a "fact".
This post builds a small write gate in plain Python (stdlib only, SQLite), runs it, and then maps each rule onto what a hosted memory layer gives you.
preference, decision, fact, task), and an unknown kind is refused. Typing a memory forces the agent to decide what it's saving, and the kind sets the expiry.seen counter instead of adding a row. Repeated memories crowd out everything else in a top-k result.key), the old row is marked superseded and stops being returned. It isn't deleted, so you can still audit what the agent believed and when.
Plus a fifth rule that's really about scope: dedup and supersede only within one scope (a repo, a user, a team). "Use pnpm" in repo A says nothing about repo B.
import re, sqlite3, time
TTL_DAYS = {"preference": None, "decision": None, "fact": 90, "task": 7}
SECRET = re.compile(r"(sk-[A-Za-z0-9]{16,}|ghp_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|password\s*[:=])", re.I)
STOP = {"the", "a", "an", "is", "are", "to", "on", "in", "of", "we", "use", "for", "and"}
def tokens(text):
return {t for t in re.findall(r"[a-z0-9_]+(?:[./-][a-z0-9_]+)*", text.lower()) if t not in STOP}
def jaccard(a, b):
return len(a & b) / len(a | b) if a | b else 0.0
def anchors(toks):
return {t for t in toks if re.search(r"[0-9./-]", t)}
def same_fact(a, b):
return anchors(a) == anchors(b) and jaccard(a, b) >= 0.8
class MemoryStore:
def __init__(self, path=":memory:"):
self.db = sqlite3.connect(path)
self.db.execute("""CREATE TABLE IF NOT EXISTS mem (
id INTEGER PRIMARY KEY, scope TEXT, kind TEXT, key TEXT, text TEXT,
created REAL, expires REAL, superseded_by INTEGER, seen INTEGER DEFAULT 1)""")
def active(self, scope, now=None):
now = now or time.time()
return self.db.execute(
"SELECT id, kind, key, text, seen FROM mem WHERE scope=? AND superseded_by IS NULL "
"AND (expires IS NULL OR expires > ?) ORDER BY id", (scope, now)).fetchall()
def write(self, scope, kind, text, key=None, now=None):
now = now or time.time()
if kind not in TTL_DAYS:
return ("rejected", f"unknown kind {kind!r}")
if SECRET.search(text):
return ("rejected", "looks like a credential")
new = tokens(text)
for mid, _, mkey, mtext, _ in self.active(scope, now):
if key and mkey == key:
if jaccard(new, tokens(mtext)) == 1.0:
break # same key, same content: fall through to dedup below
nid = self._insert(scope, kind, key, text, now)
self.db.execute("UPDATE mem SET superseded_by=? WHERE id=?", (nid, mid))
return ("superseded", f"#{mid} -> #{nid}")
for mid, _, _, mtext, _ in self.active(scope, now):
if same_fact(new, tokens(mtext)):
self.db.execute("UPDATE mem SET seen=seen+1 WHERE id=?", (mid,))
return ("deduped", f"matches #{mid}")
return ("stored", f"#{self._insert(scope, kind, key, text, now)}")
def _insert(self, scope, kind, key, text, now):
ttl = TTL_DAYS[kind]
expires = now + ttl * 86400 if ttl else None
cur = self.db.execute(
"INSERT INTO mem (scope, kind, key, text, created, expires) VALUES (?,?,?,?,?,?)",
(scope, kind, key, text, now, expires))
return cur.lastrowid
Two details matter more than they look:
anchors() blocks false merges.
from memory_write_gate import MemoryStore
DAY = 86400
t0 = 1_800_000_000 # fixed clock so the run is reproducible
store = MemoryStore()
repo = "repo:acme/api"
writes = [
("fact", "Staging DB runs on port 5432", "staging-db-port"),
("preference", "Use pnpm, not npm, in this repo", "package-manager"),
("fact", "The staging DB runs on port 5432.", None),
("task", "Halfway through migrating auth middleware to v2", "auth-migration"),
("fact", "Staging DB moved to port 5433", "staging-db-port"),
("fact", "CI token is ghp_abcdefghijklmnopqrstuvwx", None),
("note", "random thought", None),
]
for kind, text, key in writes:
status, detail = store.write(repo, kind, text, key=key, now=t0)
print(f"{status:<10} {detail:<24} {text}")
print("\nactive today:")
for row in store.active(repo, now=t0):
print(" ", row)
print("\nactive in 8 days:")
for row in store.active(repo, now=t0 + 8 * DAY):
print(" ", row)
stored #1 Staging DB runs on port 5432
stored #2 Use pnpm, not npm, in this repo
deduped matches #1 The staging DB runs on port 5432.
stored #3 Halfway through migrating auth middleware to v2
superseded #1 -> #4 Staging DB moved to port 5433
rejected looks like a credential CI token is ghp_abcdefghijklmnopqrstuvwx
rejected unknown kind 'note' random thought
active today:
(2, 'preference', 'package-manager', 'Use pnpm, not npm, in this repo', 1)
(3, 'task', 'auth-migration', 'Halfway through migrating auth middleware to v2', 1)
(4, 'fact', 'staging-db-port', 'Staging DB moved to port 5433', 1)
active in 8 days:
(2, 'preference', 'package-manager', 'Use pnpm, not npm, in this repo', 1)
(4, 'fact', 'staging-db-port', 'Staging DB moved to port 5433', 1)
The rephrased duplicate was merged into #1, then the port correction superseded #1, so the stale port is gone from both the live view and any later dedup match. The credential and the untyped note never reached the store, and the task note expired on its own after a week.
The tests pin the behaviour that's easy to break when someone "improves" the matcher later:
from memory_write_gate import MemoryStore, tokens, jaccard
T = 1_800_000_000
def test_near_duplicate_with_different_port_is_not_merged():
a = "Run the integration tests against the staging database on port 5432 before merging"
b = "Run the integration tests against the staging database on port 5433 before merging"
assert jaccard(tokens(a), tokens(b)) >= 0.8 # plain similarity would merge them
s = MemoryStore()
assert s.write("repo:x", "fact", a, now=T)[0] == "stored"
assert s.write("repo:x", "fact", b, now=T)[0] == "stored"
def test_keyed_update_supersedes_and_hides_old():
s = MemoryStore()
s.write("repo:x", "fact", "Staging DB runs on port 5432", key="db-port", now=T)
assert s.write("repo:x", "fact", "Staging DB moved to port 5433", key="db-port", now=T)[0] == "superseded"
assert [r[3] for r in s.active("repo:x", now=T)] == ["Staging DB moved to port 5433"]
def test_scopes_do_not_dedup_across_repos():
s = MemoryStore()
s.write("repo:a", "preference", "Use pnpm, not npm", now=T)
assert s.write("repo:b", "preference", "Use pnpm, not npm", now=T)[0] == "stored"
def test_task_memory_expires():
s = MemoryStore()
s.write("repo:x", "task", "Halfway through auth migration", now=T)
assert len(s.active("repo:x", now=T + 6 * 86400)) == 1
assert len(s.active("repo:x", now=T + 8 * 86400)) == 0
bash
$ pytest -q test_memory_write_gate.py
.... [100%]
4 passed in 0.01s
If you use a hosted or self-hosted memory layer instead of your own table, check which of these rules it covers and which you still have to enforce in your own code. Using the open-source HydraDB as an example, since that's what I've been building on:
id that acts as an upsert key, so re-ingesting staging-db-port (upsert is on by default) replaces the old memory instead of adding a second one. Picking good keys is still on you. An upsert replaces the old memory, so if you want the audit trail from rule 4, keep the old version in your own log.infer. infer: true, raw conversation is treated as signal and HydraDB extracts the durable preference or fact. With infer: false, an already-structured memory is stored verbatim. A write gate like the one above produces structured memories, so collection. kind in schema metadata so you can filter on it with equals. I didn't find a TTL field in the docs, and metadata filters don't do ranges. So store expires_at in additional_metadata, list memories periodically and delete the expired IDs ( DELETE /context with type: "memory"). At query time, recency_bias (0.4 unless you change it) favours newer content, but that only ranks old memories lower. It doesn't remove them.hydra-ignore. If you write memories through your own code, run something like SECRET above first.
Other memory layers make different choices. Mem0 uses an LLM at write time to decide whether a new memory adds, updates or deletes an existing one. Zep's graph marks a fact invalid when a newer one contradicts it. Before you trust a long-running agent to any of them, check whether it dedups, supersedes and expires, and which of those you still have to do yourself.
Rarely, and not as the first option. Superseding keeps an audit trail of what the agent believed and when, which is what you need when debugging a bad action. Hard-delete for privacy requests, credentials that slipped through, and expired task notes.
Start strict (Jaccard ≥ 0.8 or a high cosine cutoff) and require identifier tokens to match exactly. A missed merge costs a little context space. A false merge loses a fact. Log near-misses just under the threshold and look at them before loosening it.
Set expiry per kind, not globally. Preferences and decisions shouldn't expire on a timer; they should be replaced when they change. Environment facts can get weeks to months. Task progress should get days.
Yes. Consolidation is a background job that merges and summarizes what's already stored. A write policy runs inline and stops most of the mess from being stored in the first place. You can run both, but the write policy is cheaper and much easier to test.