What you will build
blog-coding-tutorials/c11-agent-memoryA memory package that plugs into the C10 agent without changing its loop: task state, an episode log, versioned facts, learned procedures, a write gate, hybrid retrieval, a token budgeter, compression, and an evaluation that tests whether memory causes the improvement.
- Time
- About 2.5 hours
- Hardware
- Any laptop CPU. No GPU is needed. On an AMD EPYC 7R13 with 8 threads, the rule-reader evaluation took 99 seconds, the real-model run took about 10 minutes, and the real-model fact probes took 37 minutes.
- You need
- Python 3.10+, PyTorch 2.x, pytest, and the C10 folder beside this one. Transformers only for MiniLM.
- Package
agentmem
Final repo tree c11-agent-memory/
c11-agent-memory/ ├── README.md ├── agentmem/ │ ├── tokens.py # step 1: the unit of account │ ├── working.py # step 1: task state │ ├── records.py # step 2: Episode and MemoryItem │ ├── episodic.py # step 2: the append-only log │ ├── semantic.py # steps 3 and 4: facts and their edits │ ├── writer.py # step 5: should_store │ ├── embed.py # step 6: hashing and MiniLM embedders │ ├── index_naive.py # step 6: the reference index │ ├── index_fast.py # step 6: one matrix, one matmul │ ├── retrieval.py # step 7: hybrid scoring │ ├── procedural.py # step 8: reusable strategies │ ├── consolidate.py # step 8: many episodes, one rule │ ├── budget.py # step 9: the context packer │ ├── compress.py # step 10: four compression strategies │ ├── memory.py # step 11: AgentMemory │ ├── integration.py # step 11: hooks into the C10 harness │ └── bench/ # step 12: two worlds, two evaluators ├── scripts/ # demo_pipeline, demo_compress, demo_harness, │ # break_it, eval_memory, eval_lm_reader, │ # compare_trusted, run_real_agent ├── benchmarks/ │ └── bench_index.py ├── results/ # saved outputs quoted in this post └── tests/ # 11 test files
The plan
The agent from C10 forgets everything when its process ends. What do we have to add so that it uses what it learned yesterday, and how do we prove that the memory is the reason it does better?
Start with the failure. The script below runs one task twice. The model is scripted: it deploys to whatever region it can find in its system prompt, so the output shows exactly what reached the prompt.
$ .venv/bin/python c11-agent-memory/scripts/demo_harness.pyno memory (plain C10 agent)
context tokens by section: {'instructions': 100, 'repo': 10, 'task': 22, 'tools': 137, 'history': 11}
tool call: {'project': 'atlas', 'region': 'NO-REGION-IN-CONTEXT'}
tool result: deployed atlas to NO-REGION-IN-CONTEXT
with memory (attach_memory, one call)
context tokens by section: {'instructions': 100, 'repo': 10, 'memory': 15, 'task': 22, 'tools': 137, 'history': 11}
tool call: {'project': 'atlas', 'region': 'us-east-2'}
tool result: deployed atlas to us-east-2
episodes written by the hook: ['deploy atlas us-east-2']
episodic memory from end_task: ['episode task1 (session 1): `deploy atlas us-east-2` -> ok']The first run has no memory, so the region is missing. The second run has one extra call, attach_memory. A 15-token memory section appears, and the agent deploys to the right region. It also uses us-east-2, the value the user moved to, and not the older eu-west-1. By the end of this post you will have built every piece of that.
The theory post explains why memory has three separate problems: writing, managing and reading. We do not repeat that here. We implement each one and look at what it does.
Why context is not memoryMemory is more than contextWe build in twelve steps, one per item in the plan. Steps 1 to 4 create the stores. Step 5 decides what enters them. Steps 6 and 7 find things in them.
Step 8 turns many episodes into one rule. Steps 9 and 10 fit the result into a token budget. Step 11 connects it to the harness. Step 12 asks whether any of it helps.
Clone the repo once. Every command below runs from its root.
$ git clone https://github.com/srini-anirudh/blog-coding-tutorials.git
$ cd blog-coding-tutorials
$ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
Count tokens and hold the task state
Goal A unit of account for every later decision, and an explicit record of what the agent is doing right now.
Every choice in this package costs tokens: what to store, what to retrieve, what to drop. So we need a counter first. It does not need to be exact. It needs to be fast, deterministic and close enough.
@lru_cache(maxsize=65536)
def count_tokens(text: str) -> int:
"""Estimated token count: one per word or punctuation mark, more for long words.
This is the same estimate the C10 harness budgets with, so a budget means the
same thing in both packages. It lands near a BPE count on English and code (the
README reports the measured ratio against the SmolLM2 tokenizer).
"""
return sum(1 + len(p) // 8 for p in _TOKEN_RE.findall(text))The regex splits text into words and punctuation marks. Long words cost more, because a real tokenizer splits them too. lru_cache matters because the packer in step 9 asks for the same costs many times.
How close is it? The benchmark compares it with the real SmolLM2 tokenizer on three samples: English, a build log and Python code.
token estimate vs. the SmolLM2 tokenizer
estimate real ratio
24 24 1.00
29 37 1.28
41 42 1.02The estimate is exact on the English sample and undercounts the log by about 22%, 29 tokens against 37. So keep some headroom when the budget is a hard model limit, or pass the exact HFTokenCounter instead.
Now the first memory. Working memory is what the agent is doing right now. It is not retrieved. It is always in context, it is small, and the agent rewrites it as the task moves.
@dataclass
class TaskState:
"""The goal, where we are, and what is still unknown."""
goal: str
current_step: str = ""
plan: list[PlanStep] = field(default_factory=list)
open_questions: list[str] = field(default_factory=list)
constraints: list[str] = field(default_factory=list)
def apply(self, update: dict[str, Any]) -> None:
"""Merge an update the model emitted, e.g. {"done": ["inspect"], "current_step": "fix"}.
Updates are small deltas, not full rewrites, so a malformed update can only
damage the fields it names.
"""
if "current_step" in update:
self.current_step = str(update["current_step"])
for text in update.get("add_steps", []):
self.plan.append(PlanStep(str(text)))
for text in update.get("done", []):
for step in self.plan:
if step.text == text:
step.done = True
for q in update.get("ask", []):
if q not in self.open_questions:
self.open_questions.append(str(q))
for q in update.get("answered", []):
if q in self.open_questions:
self.open_questions.remove(q)
for c in update.get("constraints", []):
if c not in self.constraints:
self.constraints.append(str(c))
def render(self) -> str:
"""The block that goes into context. Checkboxes read well to models and humans."""
lines = [f"goal: {self.goal}"]
if self.current_step:
lines.append(f"current step: {self.current_step}")
lines += [f"[{'x' if s.done else ' '}] {s.text}" for s in self.plan]
lines += [f"open question: {q}" for q in self.open_questions]
lines += [f"constraint: {c}" for c in self.constraints]
return "\n".join(lines)Why not leave this to the transcript? Because in step 10 we throw parts of the transcript away. If the goal and the plan live only in old turns, compaction deletes them. As a separate object, they survive.
This is what the block looks like inside a real context, taken from the pipeline demo later in the post:
## Task state
goal: deploy atlas
current step: run the deploy
open question: which region?Log what happened as episodes
Goal A cheap, append-only record of every action, in the form (s, a, o, r, t).
An episode is one transition: what the agent was trying to do, what it did, what came back, whether that was good, and when. Writing one needs no judgement, so nothing is lost at this stage. It is too verbose to put in context directly. Later steps read from it.
@dataclass
class Episode:
"""One transition (s, a, o, r, t).
state: what the agent was trying to do when it acted (the task state, rendered)
action: the tool call it made, as text
observation: what came back
reward: +1 success, -1 failure, 0 neutral
t: logical time (session + step / 1000); recency is computed from it
entity: the object the action touched; consolidation abstracts over it
"""
state: str
action: str
observation: str
reward: float
t: float
task: str = ""
session: int = 0
entity: str = ""
id: str = field(default_factory=lambda: new_id("ep"))
def text(self) -> str:
return f"{self.state} | action: {self.action} | result: {self.observation} | reward: {self.reward:+.0f}"| Field | Symbol | Example |
|---|---|---|
| state | s | deploy ember |
| action | a | login ember |
| observation | o | login ember: ok |
| reward | r | 0.0 |
| t | t | 1.006: session 1, the sixth episode in the log |
Logical time keeps the benchmark reproducible. Recency in step 7 is computed from it, so two runs produce the same scores on any machine.
The store is a list with one useful query. trajectory returns all the steps of one task in time order, which is the unit consolidation works on in step 8.
def add(self, episode: Episode) -> Episode:
self.episodes.append(episode)
return episode
def __len__(self) -> int:
return len(self.episodes)
def __iter__(self) -> Iterator[Episode]:
return iter(self.episodes)
def trajectory(self, task: str, session: int | None = None) -> list[Episode]:
"""All steps of one task in time order: the unit consolidation works on."""
steps = [e for e in self.episodes if e.task == task and (session is None or e.session == session)]
return sorted(steps, key=lambda e: e.t)At the end of a task, AgentMemory.end_task compresses a trajectory into one line that retrieval can return. Here is one such line. Notice how much of the raw log it removes: the deploy logs are gone, and only the error class is left.
episode t0 (session 5): `deploy atlas` -> MigrationError; `clear_cache atlas` -> ok; `deploy atlas` -> MigrationError; `migrate atlas` -> ok; `deploy atlas` -> okExtract stable facts from what people say
Goal Turn a sentence into a structured claim about a subject and an attribute.
Episodes record events. Semantic memory records what is true. The difference matters. "The owner for atlas is priya" should become one fact that later statements can correct, not one more line in a log.
So a fact has a key: (subject, attribute). An extractor turns text into a Claim. The store then judges the claim and may turn it into a Fact. Keeping those two types separate is what makes step 4 possible.
@dataclass
class Claim:
"""One extracted statement, before the store has judged it."""
subject: str
attribute: str
value: str | None # None for a retraction
t: float
confidence: float = 0.9
scope: str = "project"
kind: Literal["assert", "delete"] = "assert"
source: str = "user"
evidence: str = ""
@dataclass
class Fact:
subject: str
attribute: str
value: str
t: float
confidence: float = 0.9
source: str = "user"
status: Literal["active", "superseded", "deleted"] = "active"
valid_to: float | None = None
superseded_by: str | None = None
support: int = 1
valid_from: float | None = None # when it became true; `t` is when it was last confirmed
id: str = field(default_factory=lambda: new_id("f"))
@property
def key(self) -> tuple[str, str]:
return (self.subject, self.attribute)
def text(self) -> str:
return f"{self.subject} {self.attribute}: {self.value}"Real systems ask a model to do the extraction. We provide both. The rule extractor keeps the benchmark exact, because every extraction error can be seen and repeated. The model extractor shows the part that is easy to forget: nothing a model returns is trusted until every field is checked.
class RuleFactExtractor:
"""Regex extraction for the phrasings the benchmark world uses.
Real systems ask an LLM to do this step (see `LLMFactExtractor`). Rules keep the
benchmark exact: every extraction error is visible and reproducible.
"""
def __call__(self, text: str, t: float, source: str = "user") -> list[Claim]:
claims = []
for sentence in re.split(r"(?<=[.!?])\s+", text):
for pattern, kind in _PATTERNS:
m = pattern.search(sentence)
if not m:
continue
hedged = bool(HEDGE_RE.search(sentence))
claims.append(Claim(
subject=m["subj"].lower(), attribute=m["attr"].lower().strip(),
value=None if kind == "delete" else m["val"].rstrip(".,").strip("`"),
t=t, confidence=0.4 if hedged else 0.9,
scope="session" if TRANSIENT_RE.search(sentence) else "project",
kind=kind, source=source, evidence=sentence))
break # one claim per sentence; patterns are ordered most specific first
return claimsclass LLMFactExtractor:
"""Ask a model for claims as JSON, then validate every field before trusting it."""
def __init__(self, complete: Callable[[str], str]) -> None:
self.complete = complete
def __call__(self, text: str, t: float, source: str = "user") -> list[Claim]:
raw = self.complete(EXTRACT_PROMPT.format(text=text))
raw = re.sub(r"^```(?:json)?|```$", "", raw.strip(), flags=re.M).strip()
try:
items = json.loads(raw)
except json.JSONDecodeError:
return [] # a malformed extraction must cost us a memory, never corrupt the store
claims = []
for it in items if isinstance(items, list) else []:
if not isinstance(it, dict) or not isinstance(it.get("subject"), str) or not isinstance(it.get("attribute"), str):
continue
kind = "delete" if it.get("op") == "delete" else "assert"
value = it.get("value")
if kind == "assert" and not isinstance(value, str):
continue
conf = it.get("confidence", 0.7)
conf = min(1.0, max(0.0, float(conf))) if isinstance(conf, (int, float)) else 0.7
claims.append(Claim(it["subject"].lower(), it["attribute"].lower(), value if kind == "assert" else None,
t, conf, "project", kind, source, text))
return claimsTwo details carry a lot of weight in the rule extractor. A hedge ("I think", "might") lowers confidence from 0.9 to 0.4. A transient phrase ("just for today") sets the scope to session. Steps 4 and 5 use both signals.
Update and supersede instead of appending forever
Goal Every claim causes exactly one operation, and an old value stops being returned without being erased.
The naive store appends every statement. After a move it holds both eu-west-1 and us-east-2, and the model has to guess which is current. We make the store decide instead.
def decide(self, claim: Claim) -> Op:
"""Which operation `claim` would cause, without applying it."""
cur = self.current(claim.subject, claim.attribute)
if claim.kind == "delete":
return Op.NOOP if cur is None else Op.DELETE
if cur is None:
return Op.ADD
if _same(cur.value, claim.value or ""):
return Op.UPDATE
if claim.confidence + self.override_margin < cur.confidence:
return Op.NOOP # a weak contradiction: keep the fact, log the claim
return Op.SUPERSEDE
def apply(self, claim: Claim) -> tuple[Op, Fact | None]:
op = self.decide(claim)
cur = self.current(claim.subject, claim.attribute)
if op is Op.ADD:
return self._record(op, claim, self._insert(claim))
if op is Op.UPDATE:
cur.t = claim.t
cur.confidence = 1 - (1 - cur.confidence) * (1 - claim.confidence) # noisy-OR corroboration
cur.support += 1
elif op is Op.SUPERSEDE:
new = self._insert(claim)
cur.status, cur.valid_to, cur.superseded_by = "superseded", claim.t, new.id
return self._record(op, claim, new)
elif op is Op.DELETE:
cur.status, cur.valid_to = "deleted", claim.t
return self._record(op, claim, cur)decide is separate from apply so that the writer can ask what a claim would do without doing it.Read decide from the top. A retraction deletes if there is something to delete. A new key adds. The same value updates. A different value supersedes, unless the claim is much weaker than the current fact.
The margin test is the interesting line. With a margin of 0.3, a confident statement (0.9) can replace another confident statement (0.9). A hedge (0.4) cannot, since 0.4 + 0.3 is below 0.9.
The update branch combines confidence with a noisy-OR: 1 - (1 - a)(1 - b). Two independent statements at 0.9 give 0.99. That is why the history below shows conf=0.99 for a fact that was stated twice.
Superseding closes the old fact by setting valid_to. It stays in the store, so we can ask what we believed at any time:
def history(self, subject: str, attribute: str) -> list[Fact]:
return sorted((f for f in self.facts if f.key == (subject, attribute)), key=lambda f: f.valid_from)
def as_of(self, subject: str, attribute: str, t: float) -> Fact | None:
"""What we believed at time t: the fact whose validity interval contains t."""
for f in self.history(subject, attribute):
if f.valid_from <= t and (f.valid_to is None or t < f.valid_to):
return f
return None$ .venv/bin/python c11-agent-memory/scripts/demo_pipeline.pyFACT HISTORY for (atlas, deploy region)
eu-west-1 from t=1.1 to t=4.1 status=superseded support=2 conf=0.99
us-east-2 from t=4.1 to t=None status=active support=1 conf=0.90
as_of(t=2.0) -> eu-west-1
as_of(t=4.5) -> us-east-2
conflicts logged: []
session notes : ['Just for today, the owner for atlas is marco.']Note conflicts logged: []. The hedge at t = 4.2 never reached the store. The writer from the next step stopped it first, because its confidence was too low. So a weak claim has two lines of defence, and the margin is the second one.
This operation set is close to the one Mem0 describes (ADD, UPDATE, DELETE, NOOP). The validity intervals are the idea Zep uses on the edges of its temporal knowledge graph. Our version adds a separate SUPERSEDE so that the operation log says whether a value was refreshed or replaced.
Decide what deserves to be stored
Goal Implement should_store(event) from novelty, stability, importance, confidence and scope.
If we store everything, retrieval has to dig through chit-chat and log lines, and some of what it finds will be wrong. The write decision is the first place to protect quality.
def score(self, event: MemoryEvent) -> WriteScores:
text = event.text
v = self.embedder.encode([text])[0] # [D]
novelty = 1.0 if len(self.stored) == 0 else 1.0 - float((self.stored @ v).max().clamp(min=0))
base_stability = {"user": 0.6, "tool": 0.35, "model": 0.3}[event.source]
stability = base_stability + 0.25 * bool(_STABLE_RE.search(text)) \
- 0.4 * bool(TRANSIENT_RE.search(text)) - 0.25 * bool(_VOLATILE_RE.search(text)) \
- 0.4 * bool(_CHATTER_RE.search(text))
if self.importance_fn is not None:
importance = self.importance_fn(event)
else:
importance = 0.3 + 0.3 * bool(_EXPLICIT_RE.search(text)) + 0.3 * bool(_ERROR_RE.search(text))
if event.reward is not None:
importance += 0.3 * abs(event.reward)
confidence = {"user": 0.9, "tool": 0.85, "model": 0.5}[event.source]
if HEDGE_RE.search(text):
confidence *= 0.5
if TRANSIENT_RE.search(text):
scope = "session"
elif event.entities:
scope = "project"
else:
scope = "global"
clip = lambda x: min(1.0, max(0.0, x)) # noqa: E731
return WriteScores(clip(novelty), clip(stability), clip(importance), clip(confidence), scope)
def should_store(self, event: MemoryEvent, edits_memory: bool = False) -> WriteDecision:
"""`edits_memory`: the event would change or retract a stored fact. Such an event
is never "not novel", even when its wording repeats an earlier one."""
s = self.score(event)
ws, wi, wc = self.weights
score = ws * s.stability + wi * s.importance + wc * s.confidence
if s.scope == "session":
return WriteDecision(False, score, s, "session-scoped: keep in working memory only")
if s.novelty < self.min_novelty and not edits_memory:
return WriteDecision(False, score, s, f"not novel (novelty {s.novelty:.2f})")
if s.confidence < self.min_confidence:
return WriteDecision(False, score, s, f"too uncertain (confidence {s.confidence:.2f})")
if score < self.threshold:
return WriteDecision(False, score, s, f"score {score:.2f} < threshold {self.threshold}")
return WriteDecision(True, score, s, f"score {score:.2f} >= threshold {self.threshold}")Take the signals one at a time.
- Novelty is 1 minus the highest cosine with anything stored. Do we know this already?
- Stability starts from the source and moves with word patterns. "always" and "uses" raise it. Timestamps, process ids and "for today" lower it.
- Importance rises for explicit requests ("remember", "must"), for error names, and for a large reward in either direction.
- Confidence depends on the source (user 0.9, tool 0.85, model 0.5), and a hedge halves it.
- Scope is
sessionfor transient statements, which never persist.
| Tensor | Shape | Meaning |
|---|---|---|
| v | (D) | The new event, as a unit vector. |
| self.stored | (M, D) | One unit vector per stored memory. |
| self.stored @ v | (M) | Cosine with each stored memory. |
| novelty | scalar | 1 minus the largest cosine, clamped at 0. |
The demo runs twelve events through the writer. Step through them and watch which gate stops each one.
scripts/demo_pipeline.py. The final score is 0.4 stability + 0.35 importance + 0.25 confidence, against a threshold of 0.5.WRITER AND FACT STORE
t source nov stab imp conf scope score store op event
1.1 user 1.00 0.85 0.30 0.90 project 0.67 True ADD The deploy region for atlas is eu-west-1.
1.2 user 1.00 0.20 0.30 0.90 global 0.41 False - Thanks, that helps.
1.3 tool 1.00 0.10 0.30 0.85 global 0.36 False - 12:01:33 INFO api request id=9f3a2b77c1d0 status=200
1.4 user 0.85 0.85 0.30 0.90 project 0.67 True ADD The owner for atlas is priya.
1.5 user 0.85 0.85 0.30 0.90 project 0.67 True ADD The test command for atlas is `pytest -x`.
2.1 user 0.87 0.85 0.60 0.90 global 0.78 True NOTE Remember: never deploy on Fridays.
2.2 user 1.00 0.85 0.30 0.90 project 0.67 True ADD The database for cobalt is postgres.
3.1 user 0.30 0.85 0.30 0.90 project 0.67 True UPDATE Atlas's deploy region is eu-west-1.
4.1 user 0.57 0.60 0.30 0.90 project 0.57 True SUPERSEDE Heads up: we moved the deploy region for atlas to us
4.2 user 0.54 0.60 0.30 0.45 project 0.46 False - I think the deploy region for atlas might be ap-sout
4.3 user 0.55 0.45 0.30 0.90 session 0.51 False - Just for today, the owner for atlas is marco.
5.1 user 0.54 0.85 0.30 0.90 project 0.67 True DELETE Forget the test command for atlas, we no longer use The event at t = 3.1 is worth a look. It repeats a known fact in different words. Novelty is low at 0.30 but above the gate of 0.1, so it passes. The fact store then sees the same value and records an UPDATE, not a second fact.
The method also has an edits_memory flag. A retraction that repeats an earlier retraction word for word would otherwise fail the novelty gate. An edit is never "not novel", because what matters is what it would change in the store.
Find memories with embeddings and a vector index
Goal Text to unit vector, then the most similar memories, first with a loop and then with one matrix multiplication (a matmul).
We need text as vectors so that similar text is close. Start with the simplest embedder that works: signed feature hashing. It uses no model and no download, and it gives the same bits on every machine.
def _features(text: str) -> Counter[str]:
words = [_stem(w) for w in _WORD_RE.findall(text.lower()) if w not in _STOP]
feats: Counter[str] = Counter(words)
feats.update(f"{a}_{b}" for a, b in zip(words, words[1:]))
return feats
def _bucket(feature: str, dim: int) -> tuple[int, float]:
# Python's hash() is salted per process; blake2b gives the same bucket on every run.
h = int.from_bytes(hashlib.blake2b(feature.encode(), digest_size=8).digest(), "little")
return h % dim, (1.0 if (h >> 63) & 1 else -1.0)class HashingEmbedder:
"""Signed feature hashing (Weinberger et al., 2009) with sublinear term frequency.
The random sign makes collisions cancel in expectation instead of always adding,
so the dot product stays an unbiased estimate of the shared-feature count.
"""
def __init__(self, dim: int = 512) -> None:
self.dim = dim
def encode(self, texts: list[str]) -> torch.Tensor:
out = torch.zeros(len(texts), self.dim)
for i, text in enumerate(texts):
for feat, tf in _features(text).items():
j, sign = _bucket(feat, self.dim)
out[i, j] += sign * (1.0 + math.log(tf))
return torch.nn.functional.normalize(out, dim=-1) # zero rows stay zeroThe result is a sparse vector. Every word and word pair lands in one of 512 buckets, and the row is normalised to length 1. Now cosine similarity is a plain dot product.
Now the index. The reference version is a Python list and a loop. It exists to be obviously correct.
def search(self, query: torch.Tensor, k: int) -> list[tuple[str, float]]:
"""query: [D]. Returns the k (id, cosine) pairs with the highest cosine."""
q = query.tolist()
scored = []
for id_, v in zip(self.ids, self.vectors):
dot = 0.0
for a, b in zip(q, v):
dot += a * b
scored.append((id_, dot))
scored.sort(key=lambda p: -p[1])
return scored[:k] def scores(self, queries: torch.Tensor) -> torch.Tensor:
"""queries: [Q, D] -> cosine for every slot, [Q, size]; dead slots are -inf."""
sims = queries.to(self.device) @ self.matrix[: self.size].T # [Q, size]
return sims.masked_fill(~self.alive[: self.size], float("-inf"))
def search(self, query: torch.Tensor, k: int) -> list[tuple[str, float]]:
"""query: [D]. Same contract as NaiveIndex.search."""
return self.search_batch(query.unsqueeze(0), k)[0]
def search_batch(self, queries: torch.Tensor, k: int) -> list[list[tuple[str, float]]]:
"""queries: [Q, D] -> Q lists of (id, cosine), best first."""
k = min(k, len(self))
if k == 0:
return [[] for _ in range(queries.shape[0])]
top = torch.topk(self.scores(queries), k, dim=-1) # values, indices: [Q, k]
return [[(self.id_of[j], s) for s, j in zip(vals.tolist(), idx.tolist())]
for vals, idx in zip(top.values, top.indices)]def test_tensor_index_matches_naive_index():
vecs, queries = _random_unit(500, 64), _random_unit(5, 64, seed=1)
ids = [f"m{i}" for i in range(500)]
naive, fast = NaiveIndex(64), TensorIndex(64, capacity=16) # forces several doublings
naive.add(ids, vecs)
fast.add(ids, vecs)
for q in queries:
a, b = naive.search(q, 10), fast.search(q, 10)
assert [i for i, _ in a] == [i for i, _ in b]
assert torch.allclose(torch.tensor([s for _, s in a]), torch.tensor([s for _, s in b]), atol=1e-5)
batch = fast.search_batch(queries, 10)
single = fast.search(queries[2], 10)
assert [i for i, _ in batch[2]] == [i for i, _ in single] # BLAS may differ in the last float bitThe fast version stores all the vectors as one matrix. Search is one matmul and a top-k. Removed rows get minus infinity, so they can never win.
| Tensor | Shape | Meaning |
|---|---|---|
| matrix | (C, D) | Capacity C doubles when full. Real example: (1024, 512). |
| alive | (C) | Boolean. False for removed or unused rows. |
| queries | (Q, D) | One unit vector per query. |
| sims | (Q, size) | Cosine with every used slot. Dead slots are minus infinity. |
| top.indices | (Q, k) | The slots of the k best memories, best first. |
Here is what is inside those tensors for one real query. The query has five non-zero buckets out of 512, so nothing else in the matrix can affect the result.
results/figures.json. Blue is positive, orange is negative.Now measure. The benchmark uses random unit vectors with D = 384, the size of the MiniLM embeddings. MiniLM here is all-MiniLM-L6-v2, a small pretrained sentence-embedding model. It maps a sentence to 384 numbers, so that sentences with similar meaning land close together.
$ .venv/bin/python c11-agent-memory/benchmarks/bench_index.pyindex query latency, D=384, top-10 (AMD EPYC 7R13, 8 threads)
N naive ms tensor ms speed-up matrix MB
1000 16.5 0.10 167x 1.5
10000 170.4 0.91 187x 15.4
100000 skipped 13.33 153.6
1000000 skipped 154.79 1536.0
incremental add of 1,000 single memories
tensor index: 13.7 ms totalOn this CPU the matrix version is more than 150 times faster than the loop. It also scales far enough: a million memories take 155 ms and 1.5 GB. This is still exact search, so it returns the true top-k.
Rank by meaning, age and importance together
Goal Implement S = α Ssemantic + β Srecency + γ Simportance, and see what each term contributes.
Similarity alone has no sense of time or stakes. A rule the user asked us to remember should not lose to a slightly better word match from last month. So we score on three terms, as Generative Agents does.
def components(self, query: str, now: float) -> tuple[list[MemoryItem], torch.Tensor]:
"""Every live memory and its three score terms, [N, 3] = (semantic, recency, importance)."""
q = self.embedder.encode([query]) # [1, D]
sims = self.index.scores(q)[0] # [size], dead = -inf
slots = [self.index.slot_of[i] for i in self.items]
items = list(self.items.values())
semantic = sims[slots].clamp(min=0.0) # [N]
ages = torch.tensor([now - it.t for it in items], dtype=torch.float32)
recency = 0.5 ** (ages.clamp(min=0) / self.weights.half_life) # [N]
importance = torch.tensor([it.importance for it in items], dtype=torch.float32)
return items, torch.stack([semantic, recency, importance], dim=-1) def search(self, query: str, now: float, k: int = 5, kinds: set[Kind] | None = None,
mmr_lambda: float | None = None) -> list[Scored]:
if not self.items:
return []
items, comp = self.components(query, now)
w = torch.tensor([self.weights.alpha, self.weights.beta, self.weights.gamma], dtype=torch.float32)
total = comp @ w # [N]
keep = [i for i, it in enumerate(items) if it.status == "active" and (kinds is None or it.kind in kinds)]
order = sorted(keep, key=lambda i: -float(total[i]))
if mmr_lambda is not None:
order = self._mmr(items, order[: 4 * k], total, k, mmr_lambda)
return [Scored(items[i], float(total[i]), *map(float, comp[i])) for i in order[:k]]| Tensor | Shape | Meaning |
|---|---|---|
| sims | (size) | Cosine for each used slot. |
| semantic | (N) | The live rows, with negatives clamped to 0. |
| recency | (N) | 0.5age / half_life, in (0, 1]. |
| importance | (N) | Written by the writer, in [0, 1]. |
| comp | (N, 3) | The three terms for each memory. |
| total | (N) | comp @ w, the final score. |
The clamp is there because of what Figure 4 showed: a hash collision can make a cosine slightly negative, and that should not count as evidence against a memory.
Run it on the demo memories at time 6, with the default weights and a half-life of 3:
HYBRID RETRIEVAL query: 'which region does atlas deploy to' now=6.0 half_life=3
S sem rec imp memory
1.009 0.596 0.645 0.300 atlas deploy region: us-east-2
0.552 0.169 0.406 0.600 Remember: never deploy on Fridays.
0.463 0.200 0.345 0.300 atlas owner: priya
0.298 0.000 0.416 0.300 cobalt database: postgresCheck the top row by hand: 1.0 × 0.596 + 0.5 × 0.645 + 0.3 × 0.300 = 1.009. Only live memories appear. eu-west-1 was removed from the index when it was superseded in step 4.
Now move the weights yourself. This figure uses the terms exported by the real code at time 8. Moving a slider only recomputes the same formula.
atlas deploy region: us-east-2. Try "Recency only": the newest memory wins, whatever it says.The search also takes an optional mmr_lambda. Maximal marginal relevance trades score against similarity to what is already picked, so three near-duplicates do not fill the memory section. It is tested but off by default, and the evaluation does not use it.
Turn many episodes into one rule
Goal Procedural memory: find repeated recoveries in the episode log and promote them to a reusable, templated strategy.
A fact says what is true. A procedure says what to do. It is written with a placeholder, so one procedure covers every project, and it keeps its own track record.
@dataclass
class Procedure:
""""When `trigger` fails with `error`, run `steps`, then retry."
Templates use `{entity}` for the object, so one procedure covers every project.
"""
trigger: str # e.g. "deploy {entity}"
error: str # e.g. "MigrationError"
steps: list[str] # e.g. ["migrate {entity}"]
support: int = 1 # episodes it was consolidated from
entities: list[str] = field(default_factory=list)
successes: int = 0 # outcomes recorded after it was written
failures: int = 0
id: str = field(default_factory=lambda: new_id("p"))
@property
def success_rate(self) -> float:
"""Laplace-smoothed, so a brand-new procedure starts at 0.5, not at 0 or 1."""
return (self.successes + 1) / (self.successes + self.failures + 2)
def instantiate(self, entity: str) -> list[str]:
return [s.format(entity=entity) for s in self.steps]
def text(self) -> str:
steps = ", then ".join(f"`{s}`" for s in self.steps)
return (f"rule: when `{self.trigger}` fails with {self.error}, run {steps} and retry "
f"(from {self.support} episodes over {len(self.entities)} projects)")lookup.Where do procedures come from? We look for one pattern inside each trajectory: an action fails with an error, some fix runs, and the same action then succeeds.
def find_recoveries(trajectory: list[Episode]) -> list[Recovery]:
"""Every fail -> fix -> retry-succeeds span in one time-ordered trajectory."""
found = []
for i, ep in enumerate(trajectory):
err = error_signature(ep.observation)
if ep.reward >= 0 or err is None:
continue
for j in range(i + 1, len(trajectory)):
later = trajectory[j]
if later.action == ep.action and later.reward > 0:
# Keep only the fix steps that worked; failed guesses in between are noise.
fix = tuple(templatize(e.action, ep.entity) for e in trajectory[i + 1:j] if e.reward >= 0)
if fix:
found.append(Recovery(templatize(ep.action, ep.entity), err, fix, ep.entity,
tuple(e.id for e in trajectory[i:j + 1])))
break
if later.action == ep.action:
break # retried and failed again: this span did not recover
return found
def consolidate(store: EpisodicStore, min_support: int = 2, min_entities: int = 2) -> list[Procedure]:
"""Group recoveries across all trajectories and promote the recurring ones."""
groups: dict[tuple[str, str, tuple[str, ...]], list[Recovery]] = defaultdict(list)
for task in store.tasks():
for rec in find_recoveries(store.trajectory(task)):
groups[(rec.trigger, rec.error, rec.fix)].append(rec)
procs = []
for (trigger, error, fix), recs in sorted(groups.items()):
entities = sorted({r.entity for r in recs})
if len(recs) >= min_support and len(entities) >= min_entities:
procs.append(Procedure(trigger, error, list(fix), support=len(recs), entities=entities))
return procsThe inner loop is worth reading slowly. Start at a failed step and scan forward for the same action. If the retry succeeded, the steps in between are the fix. If the retry failed, stop: this span did not recover, and the next failed step starts its own span. That is how clear_cache drops out in the trajectories below. It sits in a span whose retry failed.
The last condition in consolidate needs at least two different entities. Two episodes on the same project could be a quirk of that project. Two projects are evidence of a pattern.
CONSOLIDATION
episode t0 (session 5): `deploy atlas` -> MigrationError; `clear_cache atlas` -> ok; `deploy atlas` -> MigrationError; `migrate atlas` -> ok; `deploy atlas` -> ok
episode t1 (session 6): `deploy cobalt` -> MigrationError; `clear_cache cobalt` -> ok; `deploy cobalt` -> MigrationError; `migrate cobalt` -> ok; `deploy cobalt` -> ok
episode t2 (session 7): `deploy dune` -> AuthError; `clear_cache dune` -> ok; `deploy dune` -> AuthError; `login dune` -> ok; `deploy dune` -> ok
-> rule: when `deploy {entity}` fails with MigrationError, run `migrate {entity}` and retry (from 2 episodes over 2 projects)
dune alone gave no rule: one project is a quirk, not a patternPack the context under a token budget
Goal Given a budget B, choose among instructions, task state, memories, recent events and tool observations.
We now have more candidate text than fits. Choosing is a knapsack problem: each block has a cost and a value, and we want the most value under B. The packer uses the standard greedy approximation, by value per token, with three additions.
@dataclass
class Block:
section: str
text: str
value: float = 0.0 # usefulness estimate; required blocks ignore it
order: float = 0.0 # position inside its section when rendered
required: bool = False
compressible: bool = True
id: str = ""
overhead: int = 0 # tokens the block costs beyond its text, e.g. chat framingDEFAULT_SECTIONS = [
Section("instructions", "Instructions"),
Section("task", "Task state"),
Section("memory", "Relevant memory", max_tokens=400),
Section("events", "Recent events", min_tokens=60),
Section("observation", "Latest observation", max_tokens=300),
Section("request", "Request"),
] def pack(self, blocks: list[Block], budget: int) -> Packed:
used: dict[str, int] = {s.name: 0 for s in self.sections}
chosen: list[Block] = [] # what goes in (compressed copies where shortened)
taken: set[int] = set() # id() of the original blocks already placed
compressed: list[str] = []
def room(sec: str, limit: int | None) -> int:
header = 0 if used[sec] else self.header_cost(sec)
space = budget - sum(used.values()) - header
for cap in (self.by_name[sec].max_tokens, limit):
if cap is not None:
space = min(space, cap - used[sec] - header)
return space
def try_add(b: Block, limit: int | None = None) -> bool:
space = room(b.section, limit)
if self.cost(b) <= space:
placed = b
elif b.compressible and space - 1 - b.overhead >= self.min_compressed:
text = self.compressor(b, space - 1 - b.overhead)
if not text or self.counter(text) + 1 + b.overhead > space:
return False
placed = replace(b, text=text)
compressed.append(b.id)
else:
return False
used[b.section] += self.cost(placed) + (0 if used[b.section] else self.header_cost(b.section))
chosen.append(placed)
taken.add(id(b))
return True
# 1. Required blocks, in section order. If they cannot fit, no packing is valid.
for b in sorted((b for b in blocks if b.required), key=lambda b: self._rank(b.section)):
if not try_add(b):
required = [x for x in blocks if x.required]
need = sum(map(self.cost, required)) + sum(self.header_cost(n) for n in {x.section for x in required})
raise BudgetError(f"required context needs ~{need} tokens, budget is {budget}")
optional = sorted((b for b in blocks if not b.required), key=self._density, reverse=True)
# 2. Section floors: each section first gets its reserved tokens from its own best blocks.
for sec in self.sections:
if sec.min_tokens:
for b in optional:
if b.section == sec.name and id(b) not in taken:
try_add(b, limit=sec.min_tokens)
# 3. Global greedy by value per token across everything left.
for b in optional:
if id(b) not in taken:
try_add(b)
dropped = [b for b in blocks if id(b) not in taken]
return Packed(budget, chosen, dropped, compressed, {k: v for k, v in used.items() if v}, self.sections)The three passes do this:
- Required blocks first. Instructions, task state and the request go in, or the packer raises
BudgetError. - Section floors. Recent events reserve 60 tokens, so memories cannot push them out completely.
- Global greedy. Everything else is taken in order of value per token. A block that does not fit may be compressed into the space left, if at least 16 tokens remain.
The output is rendered in a fixed section order, with stable text first. It is not sorted by score. That keeps the prompt prefix steady, which helps with prompt caching, and it is the order a reader expects.
Move the budget and watch the packer choose. Every state below is a real run of pack on the same 14 candidates, from scripts/export_figures.py.
BudgetError.The packer is cheap: 1.67 ms for 1,000 candidate blocks under B = 800 on the AMD EPYC 7R13 CPU. It adds nothing you would notice next to a model call.
Compress before you drop
Goal Four strategies with four different ways of losing information: extraction, summarisation, dropping and ordering.
Dropping is the budgeter's job, and you have seen it. The other three make a block cheaper first. Start with a long tool log, the most common thing in an agent's context. A test run prints hundreds of passing lines and one failure.
def extract_lines(text: str, max_tokens: int, pattern: re.Pattern[str] = SIGNAL_RE, context: int = 1,
counter: Callable[[str], int] = count_tokens) -> str:
"""Keep matching lines plus `context` lines around each; mark the gaps.
For a 2,000-line test log the failure is a dozen lines. Head-and-tail truncation
keeps the first and last lines and may cut exactly the dozen that matter.
"""
lines = text.splitlines()
keep = set()
for i, line in enumerate(lines):
if pattern.search(line):
keep.update(range(max(0, i - context), min(len(lines), i + context + 1)))
if not keep:
return truncate_to_tokens(text, max_tokens, counter, keep="both")
out, prev = [], -1
for i in sorted(keep):
if i != prev + 1:
out.append(f"[... {i - prev - 1} lines ...]")
out.append(lines[i])
prev = i
if prev < len(lines) - 1:
out.append(f"[... {len(lines) - 1 - prev} lines ...]")
joined = "\n".join(out)
if context > 0 and counter(joined) > max_tokens:
return extract_lines(text, max_tokens, pattern, 0, counter) # the signal outranks its context
return truncate_to_tokens(joined, max_tokens, counter, keep="both")$ .venv/bin/python c11-agent-memory/scripts/demo_compress.pytool log: 2573 tokens, budget 60
strategy tokens keeps the assertion? keeps the summary line?
head 55 False False
tail 55 False True
head and tail 48 False True
extract_lines 55 True True
extract_lines output:
[... 120 lines ...]
tests/test_core.py::test_median_even FAILED
E assert 2 == 2.5
[... 121 lines ...]
=== 1 failed, 240 passed in 3.21s ===Only extraction keeps the assertion. Head-and-tail, the default for tool output, keeps the summary line but loses the reason. The figure shows which lines each strategy keeps. Lower the budget to see where each one fails.
scripts/demo_compress.py. At 45 and 50 tokens even extraction loses the assertion.Old conversation turns need a different treatment. We summarise them without a model: facts first, using the extractor from step 3, then the first sentence of anything else.
def extractive_summary(turns: Sequence[str], max_tokens: int, counter: Callable[[str], int] = count_tokens) -> str:
"""Summarise old turns without a model: extracted facts first, then first sentences.
Facts are the part of a conversation most likely to be needed later, so they are
kept verbatim; everything else is cut to its first sentence.
"""
extract = RuleFactExtractor()
facts: dict[tuple[str, str], str] = {}
other: list[str] = []
for turn in turns:
claims = extract(turn, t=0.0)
for c in claims:
if c.kind == "delete":
facts.pop((c.subject, c.attribute), None)
elif c.scope != "session" and c.confidence >= 0.5:
facts[(c.subject, c.attribute)] = f"{c.subject} {c.attribute}: {c.value}" # later wins
if not claims and turn.strip(): # a turn with a claim must not bring its stale wording back
other.append(_SENTENCE_RE.split(turn.strip())[0])
lines = [f"- {f}" for f in facts.values()] + [f"- {o}" for o in other]
out, used = [], 0
for line in lines:
cost = counter(line) + 1
if used + cost > max_tokens:
break
out.append(line)
used += cost
return "\n".join(out)def compact_history(events: list[Block], keep_recent: int, max_summary_tokens: int,
summarize: Callable[[Sequence[str], int], str] = extractive_summary) -> list[Block]:
"""Replace all but the newest `keep_recent` events with one summary block."""
events = sorted(events, key=lambda b: b.order)
split = max(0, len(events) - keep_recent)
old, recent = events[:split], events[split:]
if not old:
return recent
summary = summarize([b.text for b in old], max_summary_tokens)
head = Block("events", f"(summary of {len(old)} earlier events)\n{summary}",
value=max(b.value for b in old), order=old[0].order, id="summary")
return [head] + recentdef edge_order(items: Sequence[T], key: Callable[[T], float]) -> list[T]:
"""Place the best item first, the second best last, the third second, and so on.
Long-context models use the start and the end of a prompt more reliably than the
middle (Liu et al., 2023, "Lost in the Middle"). This puts the weakest items there.
"""
ranked = sorted(items, key=key, reverse=True)
front, back = ranked[0::2], ranked[1::2]
return front + back[::-1]conversation: 86 tokens
extractive_summary, 45 tokens (39 used):
- atlas deploy region: us-east-2
- atlas owner: priya
- Thanks, that helps.
- The design review moved to Thursday.
- Let's grab lunch after this.
compact_history keep_recent=2: 8 blocks -> 3 blocks
(summary of 6 earlier events)
- atlas deploy region: us-east-2
- atlas owner: priya
- Thanks, that helps.
---
Forget the database for atlas.
---
Let's grab lunch after this.
edge_order by value: ['a', 'c', 'e', 'd', 'b']Look at what the summary did. The deploy region went from eu-west-1 to us-east-2, and only the latest value is kept. The hedge about the owner is gone, and the confident statement stayed. A plain "keep the first sentence" summary would have kept both regions.
It also kept "Thanks, that helps." and the lunch plan, because the 45-token cap allowed them. An extractive summary has no sense of what matters beyond its pattern list. model_summary asks a model instead, and it enforces the length cap after the call, because models do not reliably follow length instructions.
| Strategy | Function | What it loses | Fails how | Measured here |
|---|---|---|---|---|
| Extraction | extract_lines | The context around the signal | Visibly, if the pattern misses | Keeps the assertion at 55 tokens and above |
| Summarisation | extractive_summary, model_summary | Detail | Silently, and a model may invent | Extractive only, on one conversation |
| Dropping | ContextBudgeter.pack | Whole items | Visibly, in packed.dropped | Yes, in steps 9 and 12 |
| Ordering | edge_order | Nothing | Does not fail, only moves text | Not measured. See the note below. |
Read across the table: the strategies that lose more also fail more quietly. Prefer them in the order that keeps failures visible.
Assemble the memory and attach it to the harness
Goal One object for write, manage and read, connected to the C10 agent without editing its loop.
AgentMemory holds the stores and connects the pieces. Here is the write path.
def observe(self, event: MemoryEvent) -> tuple[WriteDecision, list[tuple[Op | str, str]]]:
"""Run one event through the writer and, if it passes, into the stores."""
claims = self.extract(event.text, event.t, event.source)
edits = any(self.facts.decide(c) in (Op.SUPERSEDE, Op.DELETE) for c in claims)
decision = self.writer.should_store(event, edits_memory=edits)
if self.scope_gate and decision.scores.scope == "session":
self.session_notes.append(event.text)
return decision, []
if self.use_writer and not decision.store:
return decision, []
ops: list[tuple[Op | str, str]] = []
for claim in claims:
if not self.supersede and claim.kind == "assert":
fact = Fact(claim.subject, claim.attribute, claim.value or "", claim.t, claim.confidence,
valid_from=claim.t)
self.facts.facts.append(fact) # append-only: every version stays active
ops.append((Op.ADD, self._index_fact(fact, decision.scores.importance)))
continue
op, fact = self.facts.apply(claim)
ops.append((op, self._sync(op, fact, decision.scores.importance)))
if not claims: # no structured fact: keep the text itself as an episodic note
item = MemoryItem("episodic", event.text, event.t, decision.scores.importance,
decision.scores.confidence, decision.scores.scope, event.source)
self.retriever.add(item)
ops.append(("NOTE", item.id))
self.writer.remember(event.text)
self._written.append(event.text)
return decision, opsThe order is deliberate. We extract first because the writer needs to know whether this event would edit a stored fact. A session-scoped statement goes to session_notes, where it stays in context today and disappears at end_session. An event with no structured claim, such as "never deploy on Fridays", is kept as a plain note.
The read path gathers every kind of block and hands them to the packer.
def build_context(self, instructions: str, request: str, now: float, budget: int,
recent_events: list[str] = (), observation: str | None = None, k: int = 8,
query: str | None = None) -> Packed:
"""Pack one context. `query` defaults to the request; pass the latest error too
when the next decision depends on it."""
blocks = [Block("instructions", instructions, required=True, compressible=False, id="instructions")]
if self.working is not None:
blocks.append(Block("task", self.working.render(), required=True, id="task"))
for i, note in enumerate(self.session_notes):
blocks.append(Block("task", f"today only: {note}", value=1.0, order=1 + i, id=f"note{i}"))
blocks += self.memory_blocks(query or request, now, k)
n = len(recent_events)
for i, ev in enumerate(recent_events):
# Newer events are worth more; the newest is worth as much as a strong memory.
blocks.append(Block("events", ev, value=0.3 + 0.7 * (i + 1) / n, order=i, id=f"ev{i}"))
if observation:
blocks.append(Block("observation", observation, value=0.9, id="obs"))
blocks.append(Block("request", request, required=True, compressible=False, id="request"))
return self.budgeter.pack(blocks, budget)C10 was built with two extension points, and memory uses them for reading and writing. EventLog.subscribe delivers every event to a hook, which is how memory writes. Agent(context=builder) lets us replace what each model call sees, which is how memory reads. attach_memory also does two things outside those points. It sets agent.builder on an agent that already exists, and it wraps agent.run. Neither change touches the loop.
def attach_memory(agent: Agent, memory: AgentMemory, budget: int, task_id: Callable[[], str] | None = None,
session: Callable[[], int] = lambda: 1, clock: Callable[[], float] = lambda: 1.0,
**hook_kwargs: Any) -> MemoryHook:
"""Give an existing Agent long-term memory and a budgeted context. Returns the hook.
The sections of the agent's current builder, such as the repo map, stay in the
prompt. Calling `memory.end_session()` between sessions is the caller's job.
"""
check_tools_fit(agent.tools.schemas(), budget) # fail here, not on the first model call
agent.builder = BudgetedContextBuilder(budget, memory, agent.builder.instructions, clock,
sections=agent.builder.sections)
hook = MemoryHook(memory, agent.state, task_id, session, clock, **hook_kwargs)
agent.log.subscribe(hook)
run = agent.run
def run_then_close(task: str):
# A run that stops at max_steps or on a model error logs no Final event. Those
# failures are worth remembering too, and only the return from `run` marks them.
try:
return run(task)
finally:
hook.close_task()
agent.run = run_then_close
return hook def __call__(self, ev: Event) -> None:
d: dict[str, Any] = ev.data
if ev.type == "UserMessage" and d.get("kind") != "feedback":
if ev.step == 0:
self.current = self.task_id()
# The opening message is a request, not knowledge, unless it states a fact.
if ev.step > 0 or self.memory.extract(d["content"], self.clock()):
self.memory.observe(MemoryEvent(d["content"], "user", self.clock()))
elif ev.type == "ToolCall":
self.pending[d["id"]] = (d["name"], d["arguments"])
elif ev.type == "ToolResult":
name, args = self.pending.pop(d["id"], (d["name"], {}))
entity = self.entity_of(name, args)
action = f"{name} {' '.join(str(v) for v in args.values())}".strip()
reward = self.reward_of(name, args, d["content"], d["is_error"])
self.memory.record_step(Episode(self.state.task, action, d["content"], reward, self.clock(),
self.current or self.task_id(), self.session(), entity))
self.state.notes["last_error"] = error_signature(d["content"]) or ""
elif ev.type == "Final":
self.close_task()
def close_task(self) -> None:
"""Summarise the open task once. Safe to call again."""
if self.current is not None:
self.memory.end_task(self.current)
self.current = None
self.state.notes.pop("last_error", None) def build(self, state: AgentState, history: list[Message], tools: list[dict]) -> PackedContext:
tools_cost = check_tools_fit(tools, self.budget)
room = self.budget - tools_cost
blocks = [Block("instructions", self.instructions, required=True, compressible=False, id="instructions"),
Block("task", task_section(state), required=True, id="task")]
names = []
for name, fn in self.sections.items():
if text := fn(state):
names.append(name)
blocks.append(Block("extras", text, value=0.6, order=len(names), id=f"extra:{name}"))
if self.memory is not None:
if self.memory.working is not None:
blocks.append(Block("task", self.memory.working.render(), required=True, order=1, id="working"))
for i, note in enumerate(self.memory.session_notes):
blocks.append(Block("task", f"today only: {note}", value=1.0, order=2 + i, id=f"note{i}"))
blocks += self.memory.memory_blocks(self.query_fn(state), self.clock(), self.k)
turns = group_turns(history)
share = (room - sum(self.budgeter.cost(b) for b in blocks if b.required)) // 2
for i, turn in enumerate(turns):
newest, first = i == len(turns) - 1, i == 0
text = _render_turn(turn)
if first and not newest:
# The two required turns share what is left, or a long opening request
# would take all of it and leave no room for what just happened.
text = truncate_to_tokens(text, max(self.budgeter.min_compressed, share))
blocks.append(Block("events", text, value=0.3 + 0.7 * (i + 1) / len(turns), order=i,
required=newest or first, id=f"turn{i}", overhead=_FRAME * len(turn) + 4))
packed = self.budgeter.pack(blocks, room)
by_id = {b.id: b for b in packed.blocks}
def section_text(section: str) -> str:
return "\n".join(b.text for b in sorted((b for b in packed.blocks if b.section == section),
key=lambda b: b.order))
parts = {"instructions": self.instructions}
parts |= {name: by_id[f"extra:{name}"].text for name in names if f"extra:{name}" in by_id}
if memory_text := section_text("memory"):
parts["memory"] = f"## Relevant memory\n{memory_text}"
parts["task"] = section_text("task") # last in the system message: closest to the history
system = "\n\n".join(parts.values())
kept: list[dict] = []
for i, turn in enumerate(turns):
b = by_id.get(f"turn{i}")
if b is not None:
kept += _turn_messages(turn, b, self.budgeter)
breakdown = {name: count_tokens(text) for name, text in parts.items()}
breakdown["tools"] = tools_cost
breakdown["history"] = count_message_tokens(kept)
return PackedContext([{"role": "system", "content": system}] + kept, tools, breakdown)Four details here come from real failures in agent code.
- Turns stay whole.
group_turnskeeps a tool result with the assistant call it answers. Dropping one without the other gives a message list that chat APIs reject. - The first and newest turns are required. Without them the model does not know what it was asked or what just happened.
- The budget pays for the tool schemas. They are subtracted before packing. A budget that forgets them will overflow on the real call. A budget smaller than the schemas fails in
attach_memory, not on the first model call. - A run that stops early is still summarised. A run that ends at
max_stepsor on a model error logs noFinalevent, soattach_memorywrapsagent.runand closes the task when it returns. The loop inside is untouched.
Run the demo again and read it with the code in mind.
no memory (plain C10 agent)
context tokens by section: {'instructions': 100, 'repo': 10, 'task': 22, 'tools': 137, 'history': 11}
tool call: {'project': 'atlas', 'region': 'NO-REGION-IN-CONTEXT'}
tool result: deployed atlas to NO-REGION-IN-CONTEXT
with memory (attach_memory, one call)
context tokens by section: {'instructions': 100, 'repo': 10, 'memory': 15, 'task': 22, 'tools': 137, 'history': 11}
tool call: {'project': 'atlas', 'region': 'us-east-2'}
tool result: deployed atlas to us-east-2
episodes written by the hook: ['deploy atlas us-east-2']
episodic memory from end_task: ['episode task1 (session 1): `deploy atlas us-east-2` -> ok']The breakdown shows one new section, memory, at 15 tokens. Everything else is unchanged. The hook wrote one episode, and end_task turned it into a retrievable memory. The agent loop did not change, which is the test of whether the harness was designed well.
Test whether memory causes the improvement
Goal Compare no memory, full transcript, retrieved memory and oracle memory, with one thing changed at a time.
A demo that works proves little. We want a causal claim: this memory, and nothing else, changed the result. So we hold everything fixed except what the context contains. Same reader, same tasks, same seeds, one intervention.
Evaluation design inThe agent evaluation playbookclass FactsEvaluator:
"""Builds the context for every probe of a script under every condition."""
def __init__(self, budget: int, memory_factory: Callable[[], AgentMemory] = AgentMemory, k: int = 6) -> None:
self.budget = budget
self.memory_factory = memory_factory
self.k = k
def contexts(self, script: Script) -> Iterable[tuple[Probe, dict[str, str]]]:
memory = self.memory_factory()
fed, session = 0, 1
for probe in script.probes:
while fed < probe.after_turn: # stream turns into memory as they happen
turn = script.turns[fed]
if turn.session != session:
memory.end_session()
session = turn.session
memory.observe(MemoryEvent(turn.text, "tool" if turn.role == "tool" else "user",
turn.session + fed / 1000, entities=_entities(turn.text)))
fed += 1
seen = script.turns[: probe.after_turn]
today = [render_turn(t) for t in seen if t.session == probe.session]
yield probe, {
"no_memory": self._transcript(today, probe),
"full_transcript": self._transcript([render_turn(t) for t in seen], probe),
"retrieved": memory.build_context(INSTRUCTIONS, request_for(probe), now=probe.session,
budget=self.budget, recent_events=today, k=self.k).render(),
"oracle": self._oracle(probe),
}
def _transcript(self, lines: list[str], probe: Probe) -> str:
fixed = count_tokens(INSTRUCTIONS) + count_tokens(request_for(probe)) + 12 # headers and newlines
blocks = [Block("events", text, order=i) for i, text in enumerate(lines)]
kept = truncate_left(blocks, self.budget - fixed)
return (f"## Instructions\n{INSTRUCTIONS}\n\n## Conversation\n" + "\n".join(b.text for b in kept)
+ f"\n\n## Request\n{request_for(probe)}")
def _oracle(self, probe: Probe) -> str:
memory = f"\n\n## Relevant memory\n- {probe.entity} {probe.attribute}: {probe.gold}" \
if probe.gold != "unknown" else ""
return f"## Instructions\n{INSTRUCTIONS}{memory}\n\n## Request\n{request_for(probe)}"Two worlds
We test on two synthetic worlds, because synthetic worlds have exact gold answers.
The facts world is a team talking to its assistant over 8 sessions. Facts are stated, changed, hedged about, overridden for one day and retracted, with chit-chat and long logs in between. Every probe has a gold answer, computed by replaying the ground truth. Each probe kind tests one skill. A test checks that gold never depends on a later turn.
The deploy world is 24 deploy tasks over 8 sessions. Most projects have one quirk: the deploy fails with an error until a specific fix has run in this session. The error text does not name the fix. An agent with no memory must explore. The limit is 8 tool calls per task.
The reader in both worlds is a rule, and it reads only the context string:
class RuleReader:
"""A careful, deterministic reader: it understands every phrasing in the world.
It reads the context top to bottom. Confident statements and retractions set the
answer; hedges count only if nothing confident was said; "just for today" counts
only if it was said today. Given the right lines it is always right, so every
error it makes is an error in what the context contained.
"""
def __init__(self) -> None:
self.extract = RuleFactExtractor()
def __call__(self, context: str, entity: str, attribute: str, session: int) -> str:
strong: str | None = None
weak: str | None = None
for line in context.splitlines():
tag = _TAG.match(line)
claims = self.extract(line, 0.0)
m = _MEMORY_LINE.match(line)
if not claims and m:
claims = [_memory_claim(m)]
for c in claims:
if (c.subject, c.attribute) != (entity, attribute):
continue
if c.scope == "session" and tag and int(tag["s"]) != session:
continue
if c.kind == "delete":
strong, weak = "unknown", None
elif c.confidence < 0.5:
weak = c.value
else:
strong = c.value
return strong or weak or "unknown"class DeployPolicy:
"""Deterministic: known fix for this project > rule for this error > analogy > explore.
Exploration tries fixes that past episodes showed useless for this project last.
With `analogy=False` the policy is literal: it uses episodes of the same project
and explicit rules, but does not generalise from another project's episode.
"""
def __init__(self, analogy: bool = True) -> None:
self.analogy = analogy
def __call__(self, context: str, task_id: str, project: str) -> str:
steps = parse_steps(context)
mine = steps.pop(task_id, [])
rules = {m["err"]: m["fix"] for m in _RULE.finditer(context)}
own, analog, useless = None, {}, set()
for traj in steps.values():
rec = recovery_fix(traj)
if rec and traj[0][1] == project:
own = rec[1]
elif rec and self.analogy:
analog.setdefault(rec[0], rec[1])
if traj and traj[0][1] == project: # fixes that were followed by another failure
useless |= {a[0] for a, b in zip(traj, traj[1:]) if a[0] != "deploy" and b[2] != "ok"}
tried = {tool for tool, _, _ in mine}
if not mine:
return f"{own} {project}" if own else f"deploy {project}"
last_tool, _, last_result = mine[-1]
if last_tool != "deploy":
return f"deploy {project}"
explore = [f for f in FIX_TOOLS if f not in useless] + [f for f in FIX_TOOLS if f in useless]
for fix in [own, rules.get(last_result), analog.get(last_result), *explore]:
if fix and fix not in tried:
return f"{fix} {project}"
return f"deploy {project}"Results
Run it. The rules are deterministic, so you will get the same accuracy as these tables. The saved run took 99 seconds on an AMD EPYC 7R13 CPU with 8 threads. A second run on the same machine gave identical tables.
$ .venv/bin/python c11-agent-memory/scripts/eval_memory.py --seeds 20Show the numbers as a table
results/eval_memory.json.FACTS budget B=1024 (probes per condition: 800)
condition accuracy 95% CI tokens
no_memory 0.578 [0.556,0.599] 517
full_transcript 0.749 [0.729,0.770] 970
retrieved 0.999 [0.996,1.000] 582
oracle 1.000 [1.000,1.000] 80At B = 1024, retrieved memory reaches 0.999 where the truncated transcript reaches 0.749, at 582 tokens against 970. At B = 4096 the whole transcript fits and reaches 1.000, but it costs 2,292 tokens where retrieved memory stays at 582. So when the budget is generous, memory saves cost. When it is tight, memory saves accuracy.
Accuracy by probe kind shows where each condition fails.
FACTS accuracy by probe kind, B=1024
condition stated updated rumor deleted today after_today unseen
no_memory 0.31 0.62 0.00 1.00 1.00 0.00 1.00
full_transcript 0.67 0.87 0.06 1.00 1.00 0.00 1.00
retrieved 1.00 1.00 1.00 1.00 0.99 1.00 1.00
oracle 1.00 1.00 1.00 1.00 1.00 1.00 1.00Is the memory the cause?
Now the ablations. Each row changes one thing in the retrieved condition. The last row is the causal check: the stores and retrieval stay the same, but every stored value is replaced with a wrong one.
class CorruptedMemory(AgentMemory):
"""The causal check: same stores and retrieval, but every fact's value is wrong.
If accuracy did not fall, the reader would not really be using its memory.
"""
def _index_fact(self, fact, importance):
pool = ATTRIBUTES.get(fact.attribute, ["wrong-value"])
fact.value = next(v for v in pool + ["wrong-value"] if v != fact.value)
return super()._index_fact(fact, importance)FACTS ablations of the retrieved condition, B=1024
variant accuracy updated rumor today+1 stated tokens
full system 0.999 1.00 1.00 1.00 1.00 582
append-only (no SUPERSEDE) 0.966 0.66 0.97 0.93 1.00 581
no writer, no scope gate 0.946 1.00 0.87 0.00 0.98 735
no writer, no margin 0.879 1.00 0.00 0.00 0.98 724
recency only (a=0,b=1,g=0) 0.686 0.92 0.13 0.10 0.49 582
semantic only (a=1,b=0,g=0) 0.999 1.00 1.00 1.00 1.00 584
corrupted values 0.585 0.72 0.03 0.00 0.31 582If the reader were not really using its memory, corrupting the values would change nothing. Accuracy falls from 0.999 to 0.585, and stated falls from 1.00 to 0.31. It does not fall to zero, because deleted and unseen probes still score, and today's turns are still in the context. The test suite asserts this drop, so a refactor that disconnects memory from the reader fails.
The other rows rank what matters on this benchmark. Recency-only retrieval costs the most after corruption (0.686). Removing the writer and the margin gives 0.879. Removing the writer and the scope gate gives 0.946. Append-only gives 0.966. Dropping recency and importance from the score changes nothing.
The deploy world, and a warning about success rates
DEPLOY budget B=256 (tasks per condition: 480)
condition success steps seen new tokens
no_memory 0.713 5.55 5.20 6.13 132
full_transcript 0.394 6.34 6.30 6.42 227
retrieved 0.821 3.71 2.86 5.10 229
oracle 1.000 1.93 1.94 1.90 102Here is one complete run of the retrieved condition. Step through the tasks and watch the fixes move before the first deploy.
Two tasks in that trace stand out: granite and fjord. Both have MigrationError, both run to 8 calls, and both end on migrate with no calls left to retry. The exploration order tries migrate last, so a first encounter needs 9 calls. With a limit of 8 the attempt can never finish, and an unfinished attempt is never a recovery, so it teaches nothing to other projects.
That raises a question about the success metric. The evaluation sweeps the limit:
DEPLOY step limit, budget B=1024
max steps no_memory retrieved
4 0.119 0.529
6 0.419 0.856
8 0.713 0.929
9 1.000 1.000
12 1.000 1.000With one more call, both conditions reach 1.000. So the success gap of 0.713 against 0.929 comes from the step limit we chose. The evaluation script does not count failures by kind, so we wrote this short loop. It runs the same deploy evaluation at limits 8 and 9:
$ .venv/bin/python - <<'EOF'
import sys; sys.path.insert(0, "c11-agent-memory")
from collections import Counter
from agentmem.bench.deploy_eval import run_deploy
from agentmem.bench.deploy_world import make_world
for limit in (8, 9):
for cond in ("no_memory", "retrieved"):
worlds = [make_world(seed) for seed in range(20)]
rs = [(r, w.quirks[r.task.project]) for w in worlds for r in run_deploy(w, cond, 1024, max_steps=limit)]
fails = Counter(q for r, q in rs if not r.success)
print(f"limit {limit} {cond:<10} success {sum(r.success for r, _ in rs) / len(rs):.3f} "
f"steps {sum(r.steps for r, _ in rs) / len(rs):.2f} failures {dict(fails)}")
EOFlimit 8 no_memory success 0.713 steps 5.55 failures {'MigrationError': 138}
limit 8 retrieved success 0.929 steps 2.92 failures {'MigrationError': 34}
limit 9 no_memory success 1.000 steps 5.84 failures {}
limit 9 retrieved success 1.000 steps 2.77 failures {}Every failure at a limit of 8 is a MigrationError task, and none remain at 9. So those tasks needed exactly one more call. At a limit of 9 the effect that remains is efficiency: 5.84 calls against 2.77.
Consolidation, and the real harness
DEPLOY consolidation ablation, retrieved condition, B=1024
reader memory success steps steps on new projects
analogy rules 0.929 2.92 4.40
analogy no rules 0.929 2.92 4.40
literal rules 0.904 3.30 5.37
literal no rules 0.881 3.59 6.13With the analogy reader, rules change nothing. With the literal reader they do, as step 8 described. Oracle memory stays well ahead of both at 1.93 steps. Its episode line lets the agent run the fix before the first deploy, whereas a rule only helps after one failure.
Last, the same policy through the real harness.Agent, with real tool registration, permissions and event log:
HARNESS harness.Agent loop, budget B=1024
condition success steps seen new prompt tokens
no_memory 0.713 5.55 5.20 6.13 828
retrieved 0.923 3.01 2.06 4.57 910
oracle 1.000 1.93 1.94 1.90 712The retrieved row is close to the standalone loop (0.923 against 0.929, 3.01 steps against 2.92), not identical. Here B also pays for tool schemas and chat framing, so less room remains for memory. Prompt tokens are higher for the same reason: the count includes the schemas, the framing and the deploy logs in the history.
The real run: a real model, a restart and a file on disk
A rule reader cannot be distracted, and it cannot lose a fact in a long prompt. So all of the above leaves a question open. Does the memory still work when a real model reads it?
scripts/run_real_agent.py answers that with nothing scripted. A local Qwen2.5-0.5B-Instruct drives the real harness.Agent from C10, and the deploy tool writes to a real file. The run has two phases, in two operating system processes.
- Teach. The user states the deploy region of 16 projects, one run per statement. Then the user moves 8 of them. The memory hook writes through the harness event log. The store is saved to disk, and the process exits.
- Deploy. A new process starts. For each project, a fresh agent is told "Deploy atlas to its usual region." We read the outcome back from the file, not from what the model says. The model decodes greedily: at each step it takes the most likely next token, so the same prompt always gives the same reply. All conditions use one prompt wording.
The model, the task and the tool are the same in all four conditions. The prompt differs, and so does the builder that makes it. No memory, full transcript and oracle use the harness's plain ContextBuilder, with text added to the instructions. Retrieved uses our budgeted builder, through attach_memory. So a difference in outcome comes from what the prompt holds and how it is laid out. Here is the tool, and the loop over conditions:
def deploy_tools(ledger: Path) -> ToolRegistry:
@tool
def deploy(project: str, region: str) -> str:
"""Deploy a project to a region.
Args:
project: The project name.
region: The cloud region, such as eu-west-1.
"""
with ledger.open("a") as f:
f.write(json.dumps({"project": project, "region": region}) + "\n")
return f"deployed {project} to {region}"
return ToolRegistry([deploy]) for condition in args.conditions:
memory = AgentMemory.load(state / "memory.json", embedder) if condition == "retrieved" else None
for n, p in enumerate(projects):
project, truth = p["project"], p["truth"]
ledger = state / f"{condition}_{project}.jsonl"
instructions = INSTRUCTIONS
if condition == "full_transcript":
instructions += HEADER + transcript
elif condition == "oracle":
instructions += f"{HEADER}- {project} deploy region: {truth}"
agent = Agent(model, deploy_tools(ledger), state, context=ContextBuilder(instructions=instructions),
config=AgentConfig(max_steps=3, checkpoint_on_start=False))
if memory is not None:
attach_memory(agent, memory, args.budget, session=lambda: 3,
clock=lambda: 3 + (len(memory.episodes) + 1) / 1000) # noqa: B023$ .venv/bin/python c11-agent-memory/scripts/run_real_agent.pymodel Qwen/Qwen2.5-0.5B-Instruct (494M parameters), AMD EPYC 7R13, 8 threads, budget B=768, embedder hashing
harness ../c10-agent-harness/harness, source hash d359c7783defad33, unchanged during the run: True
teach and deploy ran in separate processes: True
store after teaching: 16 active facts, 8 superseded, 0 tool steps from the teaching runs
condition correct moved ok stale no deploy fact in prompt prompt tokens s/call
no_memory 0/16 0/8 0 16 0/16 268 1.8
full_transcript 3/16 2/8 1 0 16/16 944 5.7
retrieved 13/16 8/8 0 0 16/16 350 4.4
oracle 16/16 8/8 0 0 16/16 283 4.2This saved run used C10 at source hash d359c7783defad33. C10 has since had a narrow fix in its truncation code, and its hash is now e7a4c5a60910af6d. We reran both real-model runs against the current C10. All 64 outcomes here and the 16 MiniLM outcomes below were identical. Only the seconds per call changed.
results/real_agent.json and results/real_agent_minilm.json.Read the rows from the top.
- No memory: 0 of 16. The model made no tool call at all and repeated the task back. This zero is not 16 wrong guesses. The instructions tell it never to guess a region, so it says nothing about what a model would do without that line.
- Full transcript: 3 of 16. Every prompt held the right fact. The model still deployed to a wrong region 13 times, at 944 prompt tokens. Only one of those was a stale value: atlas went to the region it had left. The other 12 were different wrong regions.
- Retrieved: 13 of 16. All 8 moved projects were right, with no stale value, at 350 prompt tokens. The store had already closed the old values, so they were not in these prompts.
- Oracle: 16 of 16. With one line of memory, the model copied it every time.
Why three retrieved tasks failed
Look at the misses in Figure 11: indigo, meridian and quartz. The right fact was in each prompt, but low in the list, at position 5 or 6 of 6. All of these facts share the words "deploy" and "region". With the hashing embedder, only the project name separates them. So a project that moved recently can outscore the right fact on recency.
The model deployed to the region on the top memory line in all 48 prompts that had a memory list: retrieved with hashing, retrieved with MiniLM, and oracle. With hashing, the right fact came first 12 times, and those 12 deploys were right. Ember is the one success with the fact lower down, and it was luck. Its top line was juniper's region, sa-east-1, which is also ember's region. So we changed one thing, the embedder, and ran the retrieved condition again:
$ .venv/bin/python c11-agent-memory/scripts/run_real_agent.py --embedder minilm --conditions retrievedcondition correct moved ok stale no deploy fact in prompt prompt tokens s/call
retrieved 16/16 8/8 0 0 16/16 368 4.3The fact probes, read by the real model
The deploy task is one kind of question. To see more kinds, we gave the same model the same fact contexts as the rule reader, at B = 1024. It answers each probe in words, and only the reader changes.
$ .venv/bin/python c11-agent-memory/scripts/eval_lm_reader.py --seeds 3 --device cpuQwen/Qwen2.5-0.5B-Instruct on AMD EPYC 7R13, 8 threads, budget B=1024, 3 seeds
condition accuracy tokens stated updated rumor deleted today after_today unseen
no_memory 0.442 517 0.27 0.56 0.00 0.83 0.53 0.00 0.81
full_transcript 0.542 968 0.53 0.44 0.10 0.67 0.47 0.00 0.90
retrieved 0.592 582 0.61 0.67 0.50 0.75 0.47 0.75 0.52
oracle 0.875 80 0.88 0.78 1.00 0.75 0.87 0.75 0.95
full_transcript_unbounded 0.550 2303 0.69 0.33 0.20 0.42 0.33 0.00 0.81This table is less flattering than the deploy run. Retrieved memory scores 0.592 against 0.542 for the truncated transcript and 0.550 for the whole one. That lead is small, and we did not compute a confidence interval for it. As a rough guide, one standard error on a rate near 0.55 with 120 probes is about 0.045. So we do not claim that retrieved memory is clearly better on this measure.
The ceiling has moved too. Oracle memory reaches only 0.875, so this model gets one probe in eight wrong with nothing but the right fact in front of it. Some columns rest on fewer than 10 probes, so do not read them one by one. Compare this with the rule reader at the same budget: 0.999 against 0.749. Most of that gap did not survive contact with this model.
The four memories compared
Rows are the kinds of memory we built. Columns are the aspects each step introduced. Read down a column to see that no single design serves all four.
| Memory | Holds | Written by | How it changes, and how long it lasts | How it is read | Main way it fails |
|---|---|---|---|---|---|
| Working | Goal, plan, open questions | The agent, through small deltas | Rewritten in place. Lasts one task. | Always in context, required | A malformed update, limited to the fields it names |
| Episodic | (s, a, o, r, t) and one-line summaries | The hook, with no judgement | Append only. Permanent. | Summaries through hybrid search | Too verbose if read raw |
| Semantic | (subject, attribute) → value | Extractor, then writer gate | ADD, UPDATE, SUPERSEDE, DELETE. Lasts until superseded, with history kept. | Hybrid search | Stale or wrong values that look certain |
| Procedural | Trigger, error, templated steps | Consolidation at session end | Merged, with a track record. Lasts until it stops working. | Hybrid search, or lookup | Generalised too far from one quirk |
The four evaluation conditions compare along the aspects from step 12. All are at B = 1024 unless the row says otherwise.
| Condition | What the context holds | Facts accuracy | Facts tokens | Deploy success | Deploy steps | Deploy tokens |
|---|---|---|---|---|---|---|
| No memory | This session only | 0.578 | 517 | 0.713 | 5.55 | 137 |
| Full transcript | Everything, oldest cut first | 0.749 | 970 | 0.725 | 5.03 | 937 |
| Retrieved | Written, managed and packed | 0.999 | 582 | 0.929 | 2.92 | 350 |
| Oracle | Exactly the gold fact | 1.000 | 80 | 1.000 | 1.93 | 102 |
The oracle row sets the ceiling. In the deploy world, retrieved memory is still a full step away from it, because it has to discover each error once. In the facts world it pays 582 tokens for what the oracle does in 80, so better packing has room to save tokens, not accuracy.
The real-model run answers a different question, so it gets its own table. Each row is 16 deploy tasks with one greedy model, Qwen2.5-0.5B-Instruct, at B = 768, on an AMD EPYC 7R13 CPU with 8 threads. No memory's zero means no tool call.
| Condition | Memory in the prompt | Correct | Moved projects correct | Stale deploys | Prompt tokens |
|---|---|---|---|---|---|
| No memory | None | 0/16 | 0/8 | 0 | 268 |
| Full transcript | Every statement, old values included, so the fact is always there | 3/16 | 2/8 | 1 | 944 |
| Retrieved, hashing | Top lines, current values only | 13/16 | 8/8 | 0 | 350 |
| Retrieved, MiniLM | Top lines, right fact first | 16/16 | 8/8 | 0 | 368 |
| Oracle | Exactly the gold fact | 16/16 | 8/8 | 0 | 283 |
Checks against trusted references
Most of this package has no library to compare with, so we check each part against the closest thing we can trust.
- Fast index against PyTorch.
TensorIndex.searchgives the same ranking asF.cosine_similarityplustopkon 50 of 50 queries. - Greedy packer against an exact knapsack. On 300 random sets of 12 blocks, brute force finds the true optimum. Greedy reaches 0.982 of its value on average and 0.788 in the worst case, and it finds the optimum on 179 sets. That worst case is the failure from step 9, in numbers.
- Token counter against a real tokenizer. The SmolLM2 tokenizer gives ratios of 1.00, 1.28 and 1.02 on three samples.
- Fast index against the loop.
TensorIndexandNaiveIndexreturn the same ids and the same scores to within 1e-5 on 500 random vectors, across several capacity doublings. - Mean pooling against padding. A MiniLM embedding must not change when padding is added. We ran this network test on the AMD EPYC CPU, and it passed.
- Harness loop against standalone loop. With no memory and with oracle memory at B = 4096, the two loops produce identical step counts and outcomes on one world.
- Conditions against the oracle. The reader scores exactly 1.000 given only the gold fact. This is what lets us call any other error an error of context.
$ .venv/bin/python c11-agent-memory/scripts/compare_trusted.pyTensorIndex.search vs. F.cosine_similarity + topk (AMD EPYC 7R13, 8 threads)
N=2000, D=384, k=10: same ranking on 50/50 queries, largest score difference 5.96e-08
ContextBudgeter.pack vs. exact knapsack by brute force, 300 random sets of 12 blocks
total value, greedy / optimal: mean 0.982, worst 0.788
greedy found the optimum on 179/300 sets$ .venv/bin/python -m pytest c11-agent-memory/tests/test_embed_index.py -m network
.. [100%]
2 passed, 4 deselected in 24.39sRun everything
The final folder, and every command that produced a number in this post.
c11-agent-memory/ final tree
c11-agent-memory/ ├── README.md ├── conftest.py ├── agentmem/ │ ├── tokens.py working.py records.py episodic.py │ ├── semantic.py procedural.py writer.py consolidate.py │ ├── embed.py index_naive.py index_fast.py retrieval.py │ ├── budget.py compress.py memory.py integration.py │ └── bench/ │ ├── facts_world.py facts_eval.py │ ├── deploy_world.py deploy_eval.py deploy_harness.py │ └── trusted.py hardware.py ├── scripts/ │ ├── demo_pipeline.py demo_compress.py demo_harness.py │ ├── break_it.py export_figures.py │ ├── eval_memory.py eval_lm_reader.py │ └── compare_trusted.py run_real_agent.py ├── benchmarks/bench_index.py ├── results/ └── tests/
$ .venv/bin/python -m pytest c11-agent-memory -m "not slow and not gpu and not network"
$ .venv/bin/python c11-agent-memory/scripts/demo_pipeline.py
$ .venv/bin/python c11-agent-memory/scripts/demo_compress.py
$ .venv/bin/python c11-agent-memory/scripts/demo_harness.py
$ .venv/bin/python c11-agent-memory/scripts/break_it.py
$ .venv/bin/python c11-agent-memory/scripts/eval_memory.py --seeds 20
$ .venv/bin/python c11-agent-memory/benchmarks/bench_index.py
$ .venv/bin/python c11-agent-memory/scripts/export_figures.py
$ .venv/bin/python c11-agent-memory/scripts/compare_trusted.py
$ .venv/bin/python c11-agent-memory/scripts/run_real_agent.py
$ .venv/bin/python c11-agent-memory/scripts/run_real_agent.py --embedder minilm --conditions retrieved
$ .venv/bin/python c11-agent-memory/scripts/eval_lm_reader.py --seeds 3 --device cpu
The full fast suite on an AMD EPYC 7R13 CPU:
$ .venv/bin/python -m pytest c11-agent-memory -m "not slow and not gpu and not network"
.................................... [100%]
108 passed, 3 deselected in 9.47sEvery timing in this post is from an AMD EPYC 7R13 CPU with 8 threads on a shared machine, so treat them as rough. The last three commands download Qwen2.5-0.5B-Instruct. The last one took 37 minutes. There is no GPU run in this post, and none is needed.
Key insights and nuances
- Stale facts mislead even when retrieved correctly. An append-only store keeps stated recall at 1.00 and drops updated accuracy to 0.66. An edit path matters as much as a write path. Step 4
- The write gate protects against things that are true today and false tomorrow. Without the writer and the scope gate, accuracy on the day after an override goes from 1.00 to 0.00. Step 5
- Fixing staleness at write time takes work away from retrieval. Semantic-only ties the full hybrid at 0.999, because superseding already removes old values. That holds on this benchmark and may not hold on yours. Step 7
- A perfect reader hides ranking problems. The rule reader never rewards a better embedder. In the real run, 16 tasks with one model, the model deployed to the region on the top memory line every time. MiniLM put the right fact on top in every prompt, and retrieved went from 13 to 16 of 16. Step 12
- A rule only pays when the reader would not generalise alone. It changes nothing for the analogy reader, and it saves 0.76 steps on new projects for the literal reader. Step 8
- Greedy by value per token can drop the block you need most. At B = 160 the rule that fixes the current error is dropped, while a fact about another project stays. Step 9
- Only extraction keeps the failure. At 60 tokens, head, tail and head-and-tail all lose the assertion from a 244-line log. Step 10
- A badly truncated transcript is worse than no memory. At B = 256 in the deploy world it succeeds on 0.394 of tasks, against 0.713. Step 12
- Success rates can come from your step limit. Raising the limit from 8 to 9 takes both conditions from 0.713 and 0.929 to 1.000. Steps is the better measure: 5.84 calls against 2.77 at a limit of 9. Step 12
- Prove the memory is the cause. Same reader and same seeds, then corrupt the stored values: accuracy falls from 0.999 to 0.585. Step 12
- A perfect reader is an instrument, not a forecast. It isolates what the context contains. On the fact probes it scored retrieved memory 0.999 against 0.749. One small real model scored the same contexts 0.592 against 0.542, a lead too small to claim. Step 12
- Having the fact in the prompt is not the same as using it. On 16 deploy tasks, one small model got 3 right with the full transcript and 13 with retrieved memory, with the fact in every prompt. This is a demonstration, not a rate. Step 12
Exercises
- Protect the essential blockMedium Fix the failure from step 9, where the rule for the current error is dropped at B = 160. Try a floor for procedural memories, or a value bonus when a memory names the last error. Measure deploy steps at B = 256 before and after.
Hint
Section.min_tokensalready reserves tokens. You would need a separateproceduresection, or a highervalueinmemory_blocks. Run the deploy table inscripts/eval_memory.pyto compare. - Add a paraphrase worldHard Rewrite the probes in
facts_world.pyso they share few words with the facts, for example "Where does atlas run in production?". CompareHashingEmbedderwithTransformerEmbedder. Does the tie between semantic-only and hybrid survive? - Create a world where recency mattersHard Our benchmark gives recency nothing to do. Add free-text notes that have no key and go out of date, so superseding cannot catch them. Find a weight for β that beats zero, and report both numbers honestly.
- Measure the reader's effectMedium The lead of 0.592 over 0.542 has no confidence interval. Add one, using a bootstrap over the probes in
scripts/eval_lm_reader.py, and raise the seeds until you can say whether the lead is real. Then applyedge_orderto the memory block inscripts/run_real_agent.pywith the hashing embedder. Does placing strong lines at the edges recover the three misses? - Close the loop on proceduresMedium
ProcedureStore.record_outcomeexists, but nothing calls it during a run. Wire it throughMemoryHook, add a world where a rule stops working after session 5, and show the bad rule losing rank.Hint
You need to know which procedure was retrieved for the task. Record its id when the policy acts on it, then read the reward from the final deploy step.
Continue reading
- Memory is more than context: the theory behind the write, manage and read split.
- Build an Agent Harness From Scratch: the loop and the extension points we plugged into.
- The agent evaluation playbook: how to design evaluations like the one in step 12.
- Train an Agent With Reinforcement Learning: the next tutorial, where the reward we logged here becomes a training signal.
References
Grouped by topic. Every entry links to its primary source.
Memory architectures
- Cognitive Architectures for Language Agents · Sumers et al., 2023. The working, episodic, semantic and procedural split.
- Generative Agents: Interactive Simulacra of Human Behavior · Park et al., 2023. The recency, importance and relevance score.
- Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory · Chhikara et al., 2025. The ADD, UPDATE, DELETE and NOOP operations.
- Zep: A Temporal Knowledge Graph Architecture for Agent Memory · Rasmussen et al., 2025. Validity intervals on facts.
Embeddings and search
- Feature Hashing for Large Scale Multitask Learning · Weinberger et al., 2009. Signed feature hashing.
- Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks · Reimers and Gurevych, 2019. The family behind the MiniLM encoder.
- all-MiniLM-L6-v2 model card · the encoder behind
TransformerEmbedder. - Efficient and Robust Approximate Nearest Neighbor Search Using Hierarchical Navigable Small World Graphs · Malkov and Yashunin, 2016. The graph index to reach for when exact search stops being enough.
- The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries · Carbonell and Goldstein, 1998. Maximal marginal relevance.
Context
- Lost in the Middle: How Language Models Use Long Contexts · Liu et al., 2023. The reason for
edge_order. - blog-coding-tutorials: c11-agent-memory · the code for this tutorial.