Skip to content
ImagineWorld

Sessions and Memory

node_idnode-book_agentic-spec-driven-development_chapter-08-sessions-and-memory
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleSessions and Memory
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Talking to AI feels like a conversation. Underneath, it is anything but. To steer AI well, you need a deeper understanding of how the conversation actually works. This chapter looks at the machinery.

Chapter 3’s All Talk, No Memory covered the round trip — every turn ships the whole conversation to the model; the model is stateless; the agent holds the context. The agent assembles a payload: the conversation so far, the tools the model can use, your latest prompt, plus any standing project materials the agent always includes. It sends the payload, reads the response, performs any action the model asked for, and starts the next turn the same way. Here, you need that mechanism for one purpose: to understand what a session is.

A session is the conversation you have with AI from the moment you open a new chat until the moment you close it. This chapter discusses sessions in the scope of your project — chats outside a project are one-offs, useful for small unrelated tasks. Each session starts with a clean context containing your project’s CLAUDE.md along with the standard overhead. From there, the context grows on every turn — your prompts, AI’s responses, files the agent pulled in, tool results. The growing context is what keeps the conversation cohesive: it acts as AI’s short-term memory. That memory lives while you stay in the same session.

The growing context is also where sessions get into trouble.

Imagine you opened the session from Chapter 3 and worked with AI to name a dog. You picked Bramble. Then, while staying in the same session, you switched topics — say, to drafting an executive summary for a new project. All the Biscuit, Rumble, and Bramble messages are still in the context. They ride along with every new turn — taking up space, costing tokens, contributing nothing. The model processes them every time, even though they have zero relevance to the executive summary.

The cost is worse than wasted tokens. The old conversation is not sitting there doing nothing

— it shapes the model’s responses, even on a completely different topic.

Remember how the model works. Every turn, it reads the entire conversation from scratch. It does not know which parts are “old business” and which are “new business.” It processes all of it as one continuous input. The assumptions, framing, and mindset from the earlier conversation bleed into the new one. And the damage can go far beyond tone.

Here is a concrete example. Say you spent a session drafting the public marketing page for a small business — a landing page, a list of services, a contact form anyone can submit. You went back and forth with AI over many turns. The conversation was full of phrases like “the visitor lands on the page,” “anyone can submit the form,” “no login required.” Dozens of messages all grounded in the idea that the visitor is an anonymous public user.

Then without starting a new session, you ask AI to draft the admin interface — the page where the business owner edits content, reviews submitted contact forms, and manages the listed services.

The model has just spent an entire conversation steeped in open-access, public-facing logic. That framing is everywhere in the context. So the model builds the admin interface the same way. No login check. No role verification. Customer email addresses and phone numbers from the contact form, displayed to whoever opens the page. The model does not flag this as a problem, because throughout the session, open access was not a problem — it was the design choice.

Now imagine the same request in a fresh session. No public-page history. No open-access framing in the context. Just CLAUDE.md and your request:

Draft the admin interface where the business owner manages content and reviews
contact-form submissions.

The model immediately treats this as a protected area. It adds authentication. It checks the user’s role. It restricts access to sensitive data. These are obvious steps — and the model takes them because nothing in the context tells it otherwise.

The old conversation did much worse than just waste tokens. It suppressed the model’s security instincts. It created an environment where leaving the door unlocked felt normal, because every previous message in the session had the door wide open. The model cannot separate relevant context from leftover noise. Everything in the conversation shapes the output — including assumptions you stopped thinking about ten turns ago.

The same pattern shows up outside engineering. A session that crafted a friendly, customer-facing letter will draft a complex business contract in the same friendly tone — and skip the protective clauses the contract needs. A session that simplified a consent form for research participants will flatten the technical protocol the researchers follow. Whatever framing dominates the session dominates the output, no matter what you ask next.

Here is a mental model that helps. Imagine you manage an execution team handling many different areas of work — product design, content, pricing, legal language, technical architecture. Now imagine you need to discuss five different topics with the team. Would you cram all five into a single marathon meeting, or hold separate meetings — one per topic, each focused, each with only the relevant context on the table? The question is rhetorical.

AI is your team. A chat session is your meeting. When you switch topics without starting a new session, you are running a marathon meeting where every previous discussion is still spread out on the table. The model reads all of it, every turn, and cannot tell which notes belong to the current topic and which are leftovers. Keep this picture in mind when working with AI. One topic, one session. When the subject changes, start a new meeting. And turn the zero-residual-memory property into an advantage: a fresh session truly starts clean, in a way no human team can manage.

But interference is not the only problem with a growing context. There are two more: the context window and context rot.

Every LLM has a context window — the maximum amount of text it can process in a single call. Think of it as a blackboard: large, but with edges. Eventually it fills up.

When that happens, the agent needs a remedy. There are two approaches in common use — silent forgetting and compacting — and neither is perfect.

Silent forgetting is the older of the two approaches. When the conversation exceeds the context window, the agent drops the oldest messages. No warning. No error. The model keeps responding, but it has lost access to the earlier parts of the conversation. Instructions and decisions you typed at the start of the session are gone. The model does not know they ever existed. AI starts making wrong moves and gets worse with every turn. The closest analogy is a rapidly progressing case of dementia.

This is worse than a clean failure. If the system threw an error — “context limit reached, please start a new session” — at least you would know what happened.

Compacting is the newer approach. If you ever see a “compacting” message on screen, that is the agent trying to be smarter about the problem. Instead of dropping old messages outright, the agent intervenes before the window fills up. The agent takes the older part of the conversation, sends it to an LLM, and asks for a summary. The summary then replaces the original conversation history. From then on, the model receives the summary plus the recent messages — not the conversation itself, but a condensed version that has lost much of the nuance. It gets vaguer, makes wrong assumptions, and forgets things you just told it. The closest human analogy is a heavy case of brain fog.

If you see a compacting message, take it as a signal: you overused the session and should have started a fresh one earlier. Better practice — do not wait for symptoms. Start a new session every time the subject changes; you should be doing that anyway, as explained earlier.

Even within the context window, the model does not handle every part equally well. Quality […]s long before the window fills up — researchers call this “context rot.” The model’s […]n span is often much shorter than the window’s advertised size. Claude Opus 4.7 has […]ion-token context window but performs reliably only up to around 200,000 tokens. […]ll window, performance drops to about 89% on single-fact retrieval and about 56% when an answer requires combining several facts from across the context (measured in independent needle-in-a-haystack tests).

The main cause is uneven attention. A student reading a blackboard with a hundred lines focuses on what is near the top and near the bottom; the middle gets less attention. Language models behave the same way: more weight at the beginning (primacy bias) and the end (recency bias), less in the middle (the “lost in the middle” effect).

AI agents are built around this shape. Project rules and other standing materials load at the very beginning of the context, where primacy gives them extra weight (so the rules apply on every turn). Your most recent message lands at the end, where recency does the same (so the latest instruction is heard). What ends up in the middle gets less attention — and in a long conversation, that middle can hold details the model needs but quietly misses. Another kind of brain fog, from a different cause.

The practical fix is the chapter’s recurring advice: keep sessions short.

So far, the back-and-forth has been simple: you type, the model responds, you type again. But modern AI agents do more than talk. They edit files, search the web, run commands. How does that work if the model can only produce text?

The model itself cannot do any of those things. It cannot edit a file. It cannot open a browser. It cannot run a script. All it can do is write text. But it can write a very specific kind of text

— a tool call. A tool call is a structured note that says: “I need to perform this action with these parameters.” The agent — the same program that holds your conversation history — reads the note, hands the action off to a tool (an installable piece of software that does the real work), and sends the result back to the model as the next message in the conversation. Tools are the model’s hands in the world.

The model asks. The agent does. The result comes back. The model reads it and decides what to do next. This loop continues until the task is done.

Here is a simple example. Say you have a file called greeting.md that contains a typo, and you ask AI to fix it.

TurnConversation
You: “Fix the typo in greeting.md”
1Sent to LLM: all project rules “Fix the typo in greeting.md”
LLM thinks: I need to know what’s in the file first. Let’s read it.
LLM response: requesting tool call: read greeting.md.
Agent: calls the tool to read greeting.md
Read Tool: reads greeting.mdreturns “Helo, world!”
2Sent to LLM: all project rules “Fix the typo in greeting.md.” requesting tool call — read greeting.md tool result: “Helo, world!”
LLM thinks: Now that I know the context of the file, I see the typo. Let’s fix it.
LLM response: requesting tool call: edit greeting.md - replace “Helo” with “Hello”.
Agent: calls the tool to edit greeting.md
Edit Tool: replaces “Helo” with “Hello” in greeting.mdreturns OK
3Sent to LLM: all project rules “Fix the typo in greeting.md” requesting tool call — read greeting.md tool result: “Helo, world!” requesting tool call — edit greeting.md, replace “Helo” with “Hello” tool result: OK.
LLM thinks: Is there anything left to do?
LLM response: DONE. “The typo is now fixed.”
Agent: Wrapping up.
Displayed: “The typo is now fixed.”

You typed one message, and one message was displayed back. But internally, the agent called two tools, and the LLM was called three times. The messages sent to the LLM were far longer than you might expect — yet the agent kept up a perfect illusion of simplicity.

The illusion comes with a cost. Every tool call and every tool result stays in the context — file contents, search results, and edit confirmations all accumulate. By turn 3 of the example, the LLM is receiving the original prompt plus the full exchanges from turns 1 and 2. In a tool-heavy session, the context grows fast. The remedy? You guessed it — start new sessions whenever practical.

By now the case for keeping sessions short is settled: context windows fill up, context rot sets in, tool calls bloat the context fast, and the token bill grows with every turn. Every fresh session is a clean sheet, and that is what makes the advice work. But the same clean sheet also wipes out everything decided in the previous session. Its choices, rationale, vocabulary — gone. The next session starts from nothing.

The problem compounds when more than one person works on the same project. Most AI agents run locally on your computer, and the sessions they open are bound to that computer and to you. Your teammate’s agent runs on their own machine. Their sessions are private to them; yours are private to you. The team has no shared picture — each person operates from a different conversation history, and nothing reconciles them.

Both gaps — between your sessions, and between you and your teammates — point to the same need: a way to preserve and share what matters.

Modern agents offer built-in memory features; some come as installable skills. These features carry information across sessions and load it back when relevant. They work — but as black boxes. You cannot be sure what they recorded and what they skipped. Project memory needs tighter control. This book takes a different approach: make memory an explicit part of the project, with files and rules you can see.

File memory is what you have been building from the start — even before it had a name. intake.md is a memory file. The Intake Logging rule is memory on autopilot: AI records every word you say without you doing anything. The File Registry is the index that organizes it all — linking each topic in the project to the file that holds the relevant memory.

As the project grows, you will add more memory files. A commercial contract ends up with a decisions log capturing the reasoning behind each clause, a glossary of defined terms, and a file that tracks the deal points and the rationale for each carve-out. A research protocol ends up with a decisions log tracking changes to the inclusion criteria, a controlled vocabulary for clinical terms, and a file describing the consent flow with the rationale for each step. Each of these files holds the memory the project needs to keep. None lives inside a chat session.

This approach has three properties that matter. First, it is explicit. You can open any file and see exactly what AI knows. There is no hidden state, no opaque summary generated behind the scenes. Second, it is auditable. You can track changes to the files with version control. You can see when a decision was recorded, what it replaced, and who made it. Third, it is agent-neutral. Plain Markdown files work with every AI system. If you switch agents tomorrow your memory files come with you.

Explicit does not mean manual. The same rule mechanism you have used throughout the book — write a rule once, let AI apply it on every relevant turn — is what automates memory. You decide how aggressive the automation is. A rule like “every time the user changes an inclusion criterion, append it to the decisions log” fully automates that piece of memory. A rule like “AI MUST propose every memory update and wait for approval before writing” keeps you in the loop on every change. Most projects mix the two. What sets this apart from add-on memory skills is not the level of automation — those skills automate the same way. It is that the rules are yours: written in CLAUDE.md, visible, editable, and yours to tune as you learn what the project needs.

To verify a memory arrangement works, test it. Open one session and create content that should land in your memory files — through your explicit action or through a rule firing automatically. Open a second session and ask AI what it knows about that content. Instruct AI to answer using only the files registered in the project: no web search, no training knowledge, no guessing. Compare what AI says with what should be there. For full confidence, open the memory files directly and check their contents. If the answer is wrong or missing, the arrangement needs work.

To get the most out of AI when designing a specification, give AI the fullest picture you can of what you want. Requirements never arrive that way. They arrive as incomplete, single-angle views — a set of user stories from interviews, a list of security requirements drafted by a different group on a different day, a regulatory checklist from a compliance pass. The more angles you record, the more accurate the picture AI sees when it begins to design. One clarification: the data model, the architecture, the user interface are not requirements — they are parts of the specification, grounded in the requirements.

Geometry makes the point concrete. Suppose you have two photographs of a solid object you cannot see directly. One — taken from the side — shows a rectangle. The other — taken from above — shows a circle. Neither picture by itself tells you what the object is; you can only guess. Together the two pictures tell you the object is a cylinder. Each photograph is a projection of the object onto one plane, and the shape emerges from combining the projections.

Memory files in a project work the same way. Each file captures the project from a particular angle. Where several angles cover the same subject, AI is grounded. Where only one angle does, AI guesses about the rest. Where none does, AI fabricates.

Triangulation is the discipline of recording the same underlying subject from several angles on purpose. You may have heard the word in another context — pinpointing a radio transmitter from multiple receivers, or locating a mobile phone via cell towers and GPS. The mechanism is the same: several independent observations, each from a different vantage point, converge on what no single observation could determine. You hand AI several thin files, each describing the subject from a different angle, and the angles converge on what you mean.

Take a booking platform. The user stories file captures what people want to do — search, book, cancel. The security requirements file lists what the system must defend against — payment fraud, account takeover, data exposure. The regulatory checklist identifies which compliance requirements apply — data privacy rules, accessibility standards, mandatory refund windows in the EU. Three angles, one product. Now ask AI to design the cancellation flow. The flow has to honor what users want (cancel without calling support), defend what security demands (verify identity before processing the refund), and comply with what regulations require (the mandatory refund window). Three angles converge on a single design. Without one of them, AI is guessing.

The same shape applies elsewhere — refining a clinical study procedure grounded in the inclusion criteria, the existing visit schedule, and the safety plan; drafting a contract clause grounded in the counterparty’s risk profile, industry precedent, and the company’s insurance coverage.

One caution: triangulation is not a license to multiply files. The principle is different views, not more files. Two files capturing the same view of the same subject duplicate each other, and duplication causes drift — covered in Chapter 12.

Your project has more than one memory file. Maybe the reason is triangulation — you captured the project from several angles, each angle in its own file. Maybe it is plain convenience — you split memory by topic, by feature, or by team member — because one fat file is hard to navigate, review, or update concurrently. Either way, every time you record a new fact, you have to decide which file it belongs in. While the files are few, the decision is light. As they multiply — three become five, five become ten — the routing becomes its own job.

The challenge: write a durable rule that hands the routing to AI.

A starting shape: when you instruct AI to record a project fact, AI identifies which file the fact belongs in by reading each file’s Description in the File Registry from Chapter 6. If one file matches, AI records it there. If the fact covers distinct angles that belong in different files, AI splits the fact and records each angle in the appropriate file. If no file covers it cleanly, or several files match, AI asks you which file the fact belongs in — or whether to start a new file.