The Agentic AI Codex
Ch 13 · Memory & Context Engineering
Chapter 13 · The longer game

Memory & Context Engineering

A million-token window doesn't mean a million tokens of memory. Context engineering is the discipline of getting the right tokens — and only those — in front of the model at each step. It is the difference between an agent that "remembers you" and one that gaslights itself every turn.

13.1 · The four kinds of memory

MemoryBorrowed fromIn LLM-land
Working / short-termThe chat windowThe running messages array
Episodic"What happened on Tuesday"Per-conversation logs, summaries
Semantic"Facts about the world"Vector store of distilled facts
Procedural"How to do things"Skills / scripts / reusable plans

13.2 · Three memory layers for an agent

Layer 1
Hot window
→ Layer 2
Episodic summaries
→ Layer 3
Long-term store
  • Layer 1 — hot window: last N turns verbatim. Cheap, accurate, ephemeral.
  • Layer 2 — episodic summaries: older turns compressed into a few hundred tokens.
  • Layer 3 — long-term: vector store of distilled facts, files, and procedures, queried by relevance.

13.3 · Summarisation strategies

StrategyHowWhen
Rolling summaryEvery N turns, compress oldest into a paragraph; keep recent verbatim.Most chat agents.
HierarchicalSummarise summaries: paragraph → page → chapter.Long-running research agents.
Topic-bucketedCluster turns by topic, summarise each bucket.Mixed-topic assistants.
Selective verbatimKeep "milestone" turns whole; summarise the rest.Project / code agents.
Summarisation is lossy
Every compression step deletes nuance. Build agents that also persist raw transcripts to disk so you can re-summarise with a different lens later.

13.4 · Semantic memory — facts that survive sessions

When the user says "I prefer metric units", store a compact fact:

{ "user_id": 42, "fact": "prefers metric units", "scope": "user", "ts": 1736700000 }

Embed and index these facts; at each new turn, retrieve the top-K relevant ones and prepend them as a tiny "what we know about this user" block. This is exactly how durable memory works in Claude Code, ChatGPT memory, and Cursor.

Save / forget rules

  • Save: roles, preferences, project context, repeated corrections, durable goals.
  • Don’t save: passwords, transient state, one-off facts, conversation summaries (those are episodic).
  • Always allow the user to see, edit, and delete their memories.

13.5 · Procedural memory — agents that learn skills

Procedural memory stores how-to: a reusable plan, a successful command, a fixed bug recipe. Two patterns:

  • Skills library: store named plans (e.g. "deploy-frontend"); the agent can invoke them by name.
  • Trajectory cache: when a task succeeds, save the trajectory; for similar tasks later, prepend it as a hint.

13.6 · Context engineering — the seven rules

  1. Top-and-bottom placement — models attend best to the start and end. Put critical info there.
  2. One topic per turn — multiple unrelated topics in one prompt degrade quality.
  3. Sticky system prompt — put it once at the top; don't repeat it.
  4. Cache the prefix — keep the stable part above, the changing part below, to maximise cache hits.
  5. Cite explicitly — for retrieved passages, number them; ask the model to cite by number.
  6. Truncate the middle — if you must drop tokens, drop from the middle, not the ends.
  7. Audit the trace — every prompt change should be reviewable; store traces with run IDs.

13.7 · Why forgetting matters

An agent that "remembers everything" remembers your typos, your bad ideas, your stale plans. Memory needs a decay function:

  • Time-based — drop facts not used in 90 days.
  • Frequency-based — keep the top 200 facts by recency × usage.
  • User-pinned — never decay items the user explicitly stars.

13.8 · The memory tools every agent should have

save_memory(text, scope)

Add a fact with a clear scope (user, project, conversation).

recall(query)

Retrieve top-K facts for a query.

list_memories(scope)

Show the user everything we know about them.

forget(id)

Hard delete a memory item.

13.9 · Self-check

Q1 · Your agent forgets things across sessions. The missing layer is…
Working memory
Episodic summary
Semantic (long-term)
Tool memory
Q2 · Your context window keeps overflowing. Best first move?
Upgrade to a 1M context model
Add rolling summarisation of older turns
Increase temperature
Switch vector DB