Cheat sheets

Context Engineering and Agent Memory

Budget the window, order the context, page memory in and out, fuse memory stores and persist agent state.

  • Concepts and terms
  • Tasks and commands
  • Annotated code
  • Diagrams
  • Comparisons
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

The context window budget#

fits or truncatesSystem prompt~500 tokens,goes firstTooldefinitions~2K-8K tokensRetrievedcontext~2K-10K tokensConversationhistory~2K-20K tokensFew-shotexamples~1K-3K tokensUser query~100-500 tokens,goes lastGenerationbudget~2K-8K tokensmodelContextwindow128K tokensfits or truncatesSystem prompt~500 tokens, goes firstTool definitions~2K-8K tokensRetrieved context~2K-10K tokensConversationhistory~2K-20K tokensFew-shot examples~1K-3K tokensUser query~100-500 tokens, goeslastGeneration budget~2K-8K tokensmodelContext window128K tokens

Numbers that matter#

Lost in the middle
85-90% accuracy with the document first or last. 60-70% at position 10 of 20.
Low zone
positions 40-70% of the context lose 10-20% accuracy.
Curated beats dumped
a 10K token context often beats a dumped 100K token context.
Tool cost
50-200 tokens per tool. 50 tools at 150 tokens is 7,500 tokens.
Tool pruning
cuts tool tokens by 60-80%.
History
50 turns at 200 tokens is 10,000 tokens.
Summary
100 tokens replace 10 turns that took 2,000 tokens.
Token estimate
word count times 1.3 in count_tokens.

Assemble context per query#

1Classifierclassify_intent(query) counts keyword hits perintent. No hit gives ["code"].2Tool selectorselect_tools(query, token_budget=2000) keepstools whose category matches.3Retrieverscore_relevance(query, documents) scores wordoverlap. Docs below threshold drop out.4Reorderreorder_lost_in_middle(items, scores) puts thebest items first and last.5HistoryConversationManager summarizes the oldest 2turns while history is over the cap.6BudgetContextBudget truncates each component to itscap and to the space left.

ContextEngine.assemble#

budget = ContextBudget(max_tokens=128000, generation_reserve=4000)
budget.allocate("system_prompt", self.system_prompt, max_tokens=1000)
tools, tool_tokens = select_tools(query, token_budget=2000)
budget.allocate("tools", tool_text, max_tokens=2000)
budget.allocate("retrieved_context", doc_text, max_tokens=3000)
budget.allocate("conversation_history", history_text, max_tokens=5000)
budget.allocate("user_query", query, max_tokens=500)query goes last
print(budget.report())tokens and percent per component

Memory tool surface#

CommandWhat it does
core_memory_append(section, text)Writes to a pinned section of the prompt
core_memory_replace(section, old, new)Edits a pinned section
archival_memory_insert(text)Writes to the searchable external store
archival_memory_search(query, top_k)Pages facts back into the next turn
conversation_search(query)Scans past turns, evicted turns too
block_append(label, text)Adds text to a memory block
block_replace(label, old, new)Edits a memory block
block_summarize(label)Condenses a block near its limit

Defaults#

SettingDefaultNote
max_tokens128000Minus generation_reserve 4000
max_history_tokens5000Summarize old turns above it
token_budget2000Cap for tool definitions
Relevance threshold0.05The docs version uses 0.1
max_messages4MemGPT main context. Older messages go to evicted
Block limit300Characters. near_limit fires at 0.8
w_relevance0.6w_importance 0.2, w_recency 0.2
recency_halflife_s86400.0Recency is 0.5 per half-life

Questions#

Bigger window, no memory?
128k-window baselines still miss long-horizon facts that a 4k-window agent with external memory catches.
Why sleep-time compute?
Primary turns do not wait. The sleep agent can use a stronger, slower model.
Why three stores?
A single store is wrong for two of three query classes.
How does fusion rank?
A weighted sum of relevance, importance and recency. Weights change per product.
What goes in repo memory?
Task id, touched files, assumptions, blockers, next action. Not raw chat transcripts.

Memory designs side by side#

FactorMemGPT two tiersLetta blocksMem0 hybridRepo memory
StoresMain context plus archivalCore, recall, archivalVector, KV, graphJSON files under a schema
WriteMemory tool callBlock tools and sleep-time rewritesadd(text, user_id, metadata) to all threeValidate, then atomic write
Readarchival_memory_searchCore blocks stay in the promptsearch(query, user_id) fuses scoresLoad and validate
Stale factsConsolidation, invalidationSleep-time agent invalidatesOld edge marked invalid, not deletedschema_version refuses unknown files
Main riskMemory rot, poisoningBlock bloat, silent driftEmbedding drift, graph explosionPartial writes
Use it whenData is larger than the windowSome facts must stay in the promptQueries mix similarity, lookup, relationsState must outlive the chat

Tasks in code#

TaskCode
Create a blockcreate(label, description, limit=300)
Test a block for summaryblock.near_limit()
Consolidate off the critical pathsleep.run(contradictions=[...])
Soft delete a stale factself.archival.invalidate(record.rid)
Write to all three storesmem.add(text, user_id=..., kv_triples=...)
Fused, scoped searchmem.search(query, user_id=..., top_k=3)
Persist state safelyatomic_write(path, content)
Refuse a bad writemgr.commit(state) raises SchemaError

Memory server project#

CommandWhat it does
python3 scripts/project_test.py memory-server --init <dir>Creates your workspace. A fresh starter fails
python3 scripts/project_test.py memory-server --all --path <dir> --strictGrades all four stages
node cli.ts --data-dir memory-data --put samples/memory.jsonAppends revision 1 of cache-policy
node cli.ts --data-dir memory-data --query "cache policy"Searches the docs namespace
node cli.ts --data-dir memory-data --put samples/memory-updated.json --revision 1Appends revision 2. Revision 0 again is a conflict
node cli.ts --data-dir memory-data --history cache-policy --html history.htmlPrints all revisions and writes a comparison table
node cli.ts --data-dir memory-data --serve --port 8788Serves REST and MCP. Set MEMORY_TOKEN first

Troubleshooting#

SymptomCauseFix
Model ignores a fact in the middleLost in the middleKey facts first, query last. Repeat the key point at the end
Tools fill the windowEvery tool sent on every callClassify intent and prune tools
Retrieval drowns in stale factsMemory rotConsolidate and invalidate in a sleep pass
Agent obeys an old injected noteMemory poisoningTreat retrieved memory as untrusted text
Agent recalls but cannot citeCitation lossStore session ID and turn ID with each write
Block hits its capBlock bloatSummarize before the write that crosses the cap
One user sees another user's factsScopes mixedPick one scope for each write
Session resumes on corrupt stateNon-atomic writeTemp file, fsync, os.replace