Skip to main content
RJL.pub logo

RJL.pub - AI-Native Development Journey

Chapter 12: RAG, Retrieval & Agent Memory

When the Answer Is Not in the Window

Context windows are large in 2026, but they are not free and they are not infinite - and relevance still degrades with noise. Retrieval is how you put the right context in front of the model at the right time instead of pouring everything in and hoping. It is also how an agent reaches knowledge that lives outside the codebase entirely: documentation, tickets, past incidents, and institutional memory.

The RAG Pipeline

Retrieval-Augmented Generation (RAG) has a simple shape: split your sources into chunks, turn each chunk into an embedding (a vector), store the vectors, and at query time retrieve the chunks most similar to the question and add them to the prompt.

Two-row pipeline: index documents into chunks, embeddings and a vector store, then embed a question, retrieve nearest chunks, build a prompt and produce an answer.
RAG in one picture: index once, then retrieve the nearest chunks at query time and hand them to the model.
// Index: chunk -> embed -> store
const chunks = splitIntoChunks(doc, { size: 800, overlap: 100 });
for (const chunk of chunks) {
  const embedding = await embed(chunk.text);      // e.g. a text-embedding model
  await db.query(
    'INSERT INTO docs (content, embedding) VALUES ($1, $2)',
    [chunk.text, toVector(embedding)]
  );
}

// Query: embed question -> nearest neighbors -> augment prompt
const q = await embed(userQuestion);
const { rows } = await db.query(
  'SELECT content FROM docs ORDER BY embedding <=> $1 LIMIT 5', [toVector(q)]
);
const answer = await model.generate({
  system: 'Answer using only the provided context.',
  context: rows.map(r => r.content).join('\n---\n'),
  question: userQuestion
});

Agent Memory

Retrieval brings in knowledge; memory brings in continuity. Agents use several kinds:

* Short-term (working) memory - the current session's conversation and scratchpad, bounded by the context window.
* Long-term memory - persisted facts and preferences (often plain markdown files, sometimes a vector store) that survive across sessions: "this team uses Vitest," "the staging deploy needs approval."
* Episodic memory - traces of past runs, used to learn from what worked and what failed.

Treat memory like any other context: version it, review it, and keep it current. Stale or poisoned memory is worse than none - an agent will confidently act on a fact that stopped being true three releases ago. The same hygiene that protects context files (Chapter 2) protects memory.