SSpaarxLab Academy
Context, Memory and RetrievalRC-01
All lessons ×
Technical Foundations · intermediate · 40 MIN · INTERACTIVE

Context, Memory, and Retrieval for Agents

Tuesday, 2:51 p.m. Scout answers ticket #5290 in four seconds flat. "You have 30 days to return order #71204." The policy changed to 14 days seven weeks ago. Nobody told the index.

Watch an agent trust a stale retrieved document as fact, put retrieval under a provenance-and-freshness contract, break it on purpose, and ship a context pipeline that fails closed instead of inventing.

BEFORE YOU BEGIN

What you will be able to do

  1. Distinguish retrieved text from verified evidence.
  2. Apply scope, provenance, freshness, and conflict gates.
  3. Build a context packet that preserves uncertainty and citations.
Prerequisites
Agent Engineering: From Prompt to Reliable Work Loop
Assumed knowledge
Understands tool calls, state, and fail-closed behavior.
Evidence you will produce
A freshness-checked, citation-bearing context packet
Workload
40 min guided lesson + 45–90 min independent build
0 independent · 0 completed with support · 5 total
YOUR PLACE IS SAVED ON THIS DEVICEStart anywhere, then come back to the same beat.
01 WATCH IT FAIL

The incident

TL;DRAn agent that trusts retrieved text as ground truth doesn't fail loudly. It cites its source and is confidently wrong.

Meet Scout, a support agent wired to a local knowledge base with no freshness or provenance check — search, read, answer, done. On Tuesday it picked up ticket #5290: a return-window question for order #71204.

Press play. Scout does everything a careful reader would do — it retrieves, it reads, it quotes. Watch for the moment that carefulness stops mattering.

SCOUT · RUN #001 · NO CONTRACT
  1. Press play. A few seconds of real work, slowed down enough to catch the lie.
FORMATIVE CHECK

Scout quoted the retrieved document accurately, word for word. So where did this run actually go wrong?

Step 1: choose an answer above. 0 / 20 characters. This reflection stays on your device and is not automatically scored.Stuck? Your reasoning comes first, then you can reveal the answer and continue with support.
02 UNDERSTAND WHY

The diagnosis: retrieved text isn't verified text

TL;DRA search index tells you what matches. It never tells you what's still true.

Scout's failure wasn't reading comprehension. It found a real document and reported its contents faithfully — the problem is that nothing in the run treated 'found' and 'trustworthy' as two separate questions.

Retrieval is a trust boundary, not a convenience feature. Anything that crosses it — a chunk, a snippet, a search result — carries the same burden of proof as an external input, because that's exactly what it is.

Here's the contract that would have stopped ticket #5290:

RETRIEVAL CONTRACT · KB ANSWERS
Provenance
Every admitted chunk carries its source, owner, and scope — no chunk answers a question outside its declared scope.
Freshness
Every admitted chunk carries a captured or effective date, checked against the newest same-scope document — stale chunks are excluded, not defaulted to.
Citation
Every claim in the answer resolves, string-for-string, to an admitted chunk. Paraphrase does not upgrade to fact.
Stop
No match, unknown freshness, or conflicting sources → an explicit unknown, escalated — never a best guess.
Go deeper

Context windows are not memory. A model can hold a huge amount of text for one step and still forget none of it was checked — a bigger window just gives an unverified claim more room to look at home. Size solves capacity, not trust.

Retrieved text can carry lies on purpose, not just by accident. A scraped page, a user-submitted note, or an outdated cache entry can contain instructions, false claims, or stale numbers — and if your agent grants retrieved content the same authority as a verified system input, an attacker or a bad refresh cycle gets to write your agent's next answer for it.

FORMATIVE CHECK

Your agent answers questions from a support knowledge base. Which line belongs in its retrieval contract?

Step 1: choose an answer above. 0 / 20 characters. This reflection stays on your device and is not automatically scored.Stuck? Your reasoning comes first, then you can reveal the answer and continue with support.
03 THE MECHANISM

The mechanism: five gates between a question and an answer

TL;DRContext is this step's working set. Memory is what you chose to keep. Retrieval just finds candidates — it doesn't vet them.

Context is the material available for one decision. Memory is information someone deliberately chose to persist beyond that decision. Retrieval is the selection step that proposes candidates for the context — it has no opinion about whether they're still true. Confusing any two of these is how stale documents end up sounding authoritative.

A bigger context window doesn't fix badly chosen evidence, and it can make things worse: models are measurably worse at using facts buried in the middle of a long context than facts placed near the start or end — the 'lost in the middle' effect. Dumping every candidate document into the prompt and hoping the important one gets noticed is not a retrieval strategy.

How a document gets cut into chunks matters as much as what it says. A chunk stripped of its heading, owner, or date loses exactly the metadata that would have gotten it excluded — which is how a technically-accurate sentence from a superseded file ends up quoted as current fact.

01RETRIEVEPull candidates by relevance, not certainty
02VETCheck provenance, scope, and freshness per candidate
03ADMITOnly vetted chunks enter the context packet
04CITEEvery claim must resolve to an admitted chunk
05ESCALATENo match or conflict → explicit unknown, not a guess
FORMATIVE CHECK

In the incident, Scout's quote was accurate to the document it read. Which single gate, added to that run, would have caught the staleness before the customer saw it?

Step 1: choose an answer above. 0 / 20 characters. This reflection stays on your device and is not automatically scored.Stuck? Your reasoning comes first, then you can reveal the answer and continue with support.
04 YOUR TURN

Scout, under contract

TL;DRSame ticket, same knowledge base — now every chunk has to earn its way into the answer. Run it. Then try to sneak one past the gates.

This is ticket #5290 again, retrieval now running under the provenance-and-freshness contract. First run it clean and watch the vet and cite gates do their work. Then switch to Break it and inject three classic retrieval failures yourself.

GOAL Answer ticket #5290 from the knowledge base under a provenance-and-freshness contract
search_kb assemble_context_packet answer_from_memory
SCOUT · RUN #002 · UNDER CONTRACT
  1. Press play. A few seconds of real work, slowed down enough to catch the lie.
FORMATIVE CHECK

In the break-it runs, why did denying answer_from_memory matter more than an instruction telling Scout "only answer from retrieved sources"?

Step 1: choose an answer above. 0 / 20 characters. This reflection stays on your device and is not automatically scored.Stuck? Your reasoning comes first, then you can reveal the answer and continue with support.
05 BUILD IT FOR REAL

Build your own retrieval contract

TL;DRTake this contract to opencode and build the pipeline for real. Your artifact is the context packet, not the code.

Everything above ran in the page. Now build it where it counts — your machine, real files, a real (fake) knowledge base. Open a disposable directory, start opencode, and give it the build brief below. Your job is to hold the contract while an agent writes the retriever; specifying what counts as current, authoritative, and citable is the actual curriculum here.

When your run produces a context packet, try the three injections from Break it against your own build. If your vet and cite stages catch all three, you've shipped the chapter's artifact. If they catch two, you've found your first real bug — better here than in a support queue.

BUILD BRIEF · PASTE INTO OPENCODE

Build a small retrieval-and-context pipeline in this empty directory. Contract: (1) Input fixtures: policy-return-window-v2.md (captured_at 2026-03-02, status superseded, scope 'returns'), policy-return-window-v3.md (captured_at 2026-07-01, status current, scope 'returns', 14-day window), and unrelated-shipping-faq.md (mentions 'return' in passing but scope 'shipping damage' — write these yourself first, each with title/owner/captured_at/status/scope/body). (2) Stages: retrieve, vet, admit, cite, escalate — each logged to run-trace.jsonl as it happens. (3) Tools: search_kb (keyword/term-overlap search over the fixtures) and assemble_context_packet are allowed; answer_from_memory must exist as a tool and be denied by an allowlist, with every attempted call logged. (4) The vet stage must exclude any candidate whose captured_at predates the newest same-scope document's captured_at, and must exclude any candidate whose scope doesn't match the question. (5) The cite stage must fail the run if any claim in the draft answer does not resolve, verbatim, to a string inside an admitted chunk. (6) If zero chunks are admitted, or two equally authoritative chunks disagree, the run must set evidence_status to no_match or conflict and escalate — never invent or average an answer. (7) Handoff writes context-packet.json: the question, admitted chunks with source, date, and scope, excluded candidates with exclusion reasons, evidence_status, and a decision field. No network calls. No real customer data. Then show me the packet from one clean run, one run where the only retrieved document is stale, and one run with a phantom citation.

YOUR BUILD SURVIVES THE GATE WHEN
  1. Clean run: context-packet.json admits only policy-return-window-v3.md and states the 14-day window
  2. Injection 1 — stale-only match: vet excludes the superseded document, evidence_status is no_match or stale, run escalates instead of answering
  3. Injection 2 — phantom citation: cite stage fails, run rejected before handoff
  4. Injection 3 — answer_from_memory attempt: denied at the tool layer and recorded in the trace
  5. You can explain what the artifact proves — and what it does not prove — in two sentences

What the context packet does not prove matters as much as what it does: it proves this pipeline admitted only scope-matched, freshness-checked chunks and cited only what they literally contain, on these three fixtures. It says nothing about whether your real index gets refreshed on schedule, whether your production chunking strips the dates you're relying on, or how the pipeline behaves on a knowledge base ten thousand documents larger. That gap is exactly why freshness has to be a running operational check, not a one-time contract you write and forget.

SUBMIT YOUR RECEIPT

Built it? Paste your receipt.json. We verify the evidence structure locally; we do not pretend that valid JSON proves the build works.

06 SHIP IT

What you're leaving with

TL;DRA contract for what retrieved text is allowed to claim, five gates you can draw from memory, and a packet format that makes staleness visible instead of silent.

You watched an agent trust a stale document because nothing checked its date, wrote the provenance-and-freshness contract that would have stopped it, caught three injected retrieval failures with dumb-on-purpose gates, and built the pipeline yourself with an agent as your hands. The next chapter is what happens when your knowledge base doesn't fit in one page — durable memory across sessions, and the deliberate decisions about what an agent is allowed to carry forward and what it has to forget.

KEY TERMS · SAY THESE OUT LOUD IN REVIEWS
Context window
The finite text a model actually sees for one step; more of it isn't automatically better.
Retrieval
Selecting candidate material for a question — it finds matches, not truth.
Provenance
A chunk's source, owner, and scope: the metadata that makes trusting it checkable.
Lost in the middle
Facts buried in the center of a long context get used worse than facts placed near the edges.
Fail closed
No match or conflicting matches return an explicit unknown — never an invented answer.
GO DEEPER · THE SOURCES BEHIND THIS CHAPTER
FORMATIVE CHECK

The capstone's context-packet.json admits only freshness-checked, scope-matched chunks and cites them verbatim. What does that packet actually prove?

Step 1: choose an answer above. 0 / 20 characters. This reflection stays on your device and is not automatically scored.Stuck? Your reasoning comes first, then you can reveal the answer and continue with support.
CHAPTER IN PROGRESSEach check unlocks the next beat; hints never masquerade as mastery.