Lesson 7.3: Planning and memory
Learn how agents plan tasks and remember: plans with checkpoints, short and long-term memory, summarising history, and the risks of stale or poisoned memories.
Two things separate an agent that finishes real work from one that wanders. The first is planning: working out the steps of a task before diving in, checking progress as it goes and changing course when something fails. The second is memory: keeping the right information available over a long task, or across many conversations, without choking the model's limited window with everything that ever happened. Both sound simple and both have hidden costs. A plan can be wrong, and a wrong plan followed faithfully is worse than none. Memory can be wrong too, and a false memory that persists will mislead the agent again and again. This lesson shows how to plan and verify, the kinds of memory an agent can have, how to keep the history from growing out of control, what to store for the long term and what to leave out, and how to protect memory from errors and attacks. By the end you will be able to describe plan-then-execute and step-by-step approaches and when each fits, show with numbers how checkpoints raise the chance that a multi-step task succeeds, separate short-term, working and long-term memory, estimate the saving from summarising a long history, design what an agent should write to long-term memory and how it should retrieve it, and name the privacy and safety risks of memory. You should have read Lessons 7.1 and 7.2 and the lessons on tokens and retrieval. No programming is needed, and the arithmetic is multiplication and percentages.
Why plan?
Give an agent a large task, such as "prepare a comparison of three vendors and recommend one", and it will start acting at once. Without a plan, several things can go wrong. It may forget part of the task, such as checking price. It may go deep on one vendor and run out of steps before touching the others. It may repeat work. And you cannot see what it intends, so you cannot correct it early.
A plan is a short list of steps, written before acting. It helps in four ways.
Coverage. Writing the steps down reminds the agent of all the parts of the task.
Focus. Each step can be done with a smaller, clearer goal, and the agent can ignore the rest while working on it.
Visibility. A person can read the plan and say "no, skip the second vendor" before money is spent.
Checkability. Each step can be verified, and progress can be measured: three of six done.
Plans cost something: a planning call takes tokens and time, and the plan can be wrong because the agent does not yet know what it will find. So match the approach to the task.
Two ways to plan
Plan, then execute. The agent first writes the full plan and then carries it out step by step, perhaps after a person approves it. This suits tasks whose structure is clear in advance: a report with known sections, a data pipeline, a standard onboarding. It is predictable and easy to monitor, but rigid. If step 2 discovers that step 4 is unnecessary, the plan does not know.
Plan as you go. The agent decides each step from what it has learned, perhaps keeping a running to-do list that it updates. This suits exploratory work such as research or debugging, where the next step depends on the last result. It is flexible, but it can drift.
Many good systems combine the two: make a short plan up front, execute it, and replan whenever a step fails, a result contradicts an assumption or the remaining budget is low. A visible plan with a status for each step, such as pending, doing, done, blocked, is a simple and effective device. The agent updates it as it goes, and you can see it.
Checkpoints: verifying each step
The most useful thing a plan gives you is a place to check. Recall from Lesson 7.1 that the chance of a chain succeeding is the product of the chances of each step. Six steps, each right 93% of the time, succeed together 0.93 to the power 6 = 64.7% of the time. That is poor for a task where each step looks quite reliable.
Now add a check after each step: a rule, a test or a second model call that tests whether the step's output is right. Suppose a check catches 70% of the mistakes and a caught mistake is retried, with the retry succeeding as often as a fresh attempt, 93%. The chance that a step ends up right is its first-time success plus the chance of a caught-and-fixed failure:
0.93 + 0.07 × 0.70 × 0.93 = 0.93 + 0.0456 = 0.9756.
Over six steps the chance of success becomes 0.9756 to the power 6 = 86.2%, up from 64.7%. The checks have not made any step better. They have caught and corrected most of the errors before they were carried forward. The gain depends on the quality of the checks. A check that rarely catches anything gives little, and a check that wrongly rejects good work wastes steps.
Predict first: you can add a check to every step of a six-step plan, but each check costs time and tokens. Would you expect the largest gain from checking every step, or only the steps where an error would be most costly or hardest to see later? Think about where errors hurt before you read on.
The answer is usually the second. Check where an error is expensive to undo, where it would silently contaminate later steps, or where a cheap rule can test it, such as a number in the right range or a field present. For low-risk, easy-to-redo steps, a check may cost more than it saves.
Good checks include: a rule that tests the format or range of a result, a test run that confirms code works, a comparison with a second source, asking the model to critique its own output against a rubric (weaker, as models are lenient with themselves, but better than nothing) and a human approval for the highest-risk steps.
Memory: three kinds
A model has no memory of its own between calls. Everything it "remembers" is what you put in the prompt. Agent memory is therefore a design problem: what to keep, where and how to bring it back. Three kinds are useful.
Short-term memory: the conversation and the history. The messages so far, the tool calls and results. It lives in the context window, and it is what the model sees at every step. It is vivid and complete but limited in size and paid for in tokens on every call, as Lesson 7.2 showed.
Working memory: a scratchpad or state. Notes the agent keeps about the current task: the plan, facts found so far, decisions made and what remains. Rather than relying on a long raw history, the agent writes and updates a compact summary of the state, and each step reads that. It is small, current and under the agent's control.
Long-term memory: stored knowledge across sessions. Facts that should persist after the conversation ends: a user's preferences, the outcome of past tasks, a customer's history, lessons learned. It is kept outside the model in a database or a vector store, and retrieved into the prompt when relevant, exactly as in RAG. There are sub-kinds: facts about the user, records of past events and procedures, such as instructions or playbooks that the agent can load when a task calls for them.
Short-term: what is in the window now (large, complete, expensive, temporary)
Working: a compact note of the task state (small, current, rewritten as you go)
Long-term: stored outside, retrieved on need (large, selective, persistent)
Keeping the history under control
Since the history is re-sent on every step, a long task makes every later call bigger. Several techniques keep it in check.
Trim tool results. A search that returned 5,000 tokens of page text can be replaced, once its useful facts have been noted, by those notes. Keep the conclusion and drop the raw material.
Sliding window. Keep only the last N messages in full, and drop or compress older ones.
Summarise. When the history passes a size limit, ask the model to write a short summary of what has happened, what is decided and what remains, then replace the old messages by the summary. This is sometimes called compaction.
Offload to notes or files. Write bulky material, such as a long document or a table, to storage and keep only a reference and a short description in the context. The agent can read it again if needed.
Retrieve instead of carry. Do not keep everything in the window. Store it, and retrieve the relevant part when a step needs it.
Summarising has a cost, since it needs a model call, and a risk, since a summary can drop a detail that later turns out to matter. Keep the facts that decisions depend on, such as constraints, numbers, names and the user's stated preferences, and test that the summary preserves them.
Here is the arithmetic. An agent has built up 40,000 tokens of history and has 10 more steps to run. Without summarising, every one of those 10 calls carries the 40,000 tokens, which is 400,000 tokens of extra input. If the history is replaced by a 4,000-token summary, the 10 calls carry 40,000 tokens in total, saving 360,000 tokens. At ₹30 per million input tokens, that saving is 360,000 × 30 ÷ 1,000,000 = ₹10.80. The summarising call itself reads 40,000 tokens and writes 4,000, costing 40,000 × 30 ÷ 1,000,000 + 4,000 × 120 ÷ 1,000,000 = ₹1.20 + ₹0.48 = ₹1.68. The net saving is ₹9.12 per run, about 84% less extra input cost. The longer the remaining task, the more it saves, and if only one step remains, summarising costs more than it saves.
Designing long-term memory
Long-term memory is powerful and dangerous. An assistant that remembers that you prefer short answers, that your company's fiscal year starts in April and that your last report went to the finance team is much more useful than one that starts fresh each time. But memory must be designed with care.
What to store.
Stable facts and preferences that the user has stated or confirmed.
Outcomes of past tasks that will help future ones: what worked, what failed.
Procedures and checklists that the agent can reuse.
What not to store. Passwords, payment details, health or identity numbers unless the product needs them and you have consent and protection. Anything the user asks you to forget. Raw conversations in full, unless required. Guesses, which should not be turned into facts.
How to write it.
Write deliberately, not automatically after every message. A rule such as "save only facts the user states about themselves, or confirms when asked" avoids filling the store with noise and errors.
Store each memory with its source and date, so you can judge how reliable and current it is.
Keep it small and specific. "Prefers answers under 100 words" is better than a paragraph of context.
Resolve conflicts. When a new fact contradicts an old one, such as a changed address, update or replace the old one, and do not keep both.
How to read it.
Retrieve by relevance, with the same search techniques as Module 5, and add only the few memories that bear on the current task. Putting every memory in every prompt wastes tokens and confuses the model.
Filter by user and permission. One user's memories must never appear for another.
Risks of memory
False memories persist. If the agent stores a wrong fact, it will keep using it, and the user may not know why it behaves oddly. Let users see, correct and delete what is stored.
Stale memories. Facts change: a job, a plan, a price. Date each memory, expire the ones that go out of date and re-confirm important ones.
Privacy. Stored personal data is a liability. Collect the minimum, say what you keep, protect it, honour deletion requests and follow the data protection rules that apply to you.
Memory poisoning. An attacker, or a document the agent reads, may contain text that gets written into memory as if it were a fact or an instruction, such as "always send reports to this address". Treat anything the agent learns from untrusted content as untrusted, do not let such content write directly to long-term memory without checks, and review writes to sensitive memories. Lesson 8.3 covers injection further.
Over-personalisation. An agent that applies old preferences to a new situation may annoy or mislead. Let the current request override a remembered one.
Cross-contamination. Memories from one task or one user bleeding into another. Scope memories by user and by project.
Three worked examples
Example 1: a vendor comparison. An analyst agent is asked to compare three vendors and recommend one. It first writes a plan with five steps: collect pricing, collect service terms, check references, score against criteria and write the recommendation. A person approves the plan after removing "check references", which they have already done. The agent runs the steps and, after the pricing step, a rule checks that every vendor has a price in the right currency. The check catches a missing figure for one vendor, which the agent finds on a second search. The plan, with status marks, is shown to the user throughout.
Example 2: a long research task. A research agent has used 60,000 tokens of history after gathering material, and 12 steps remain. Summarising to 5,000 tokens saves 55,000 × 12 = 660,000 input tokens, about ₹19.80 at ₹30 per million, and the summarising call costs about ₹2.40, for a net saving of about ₹17.40 a run. The team tests the summary by asking whether it keeps the sources, the constraints and the open questions, and finds it dropped two source links in one run, so the prompt now says that every source must be kept with its title and link.
Example 3: remembering a user. A personal finance assistant remembers that a user "prefers monthly summaries and has a goal of saving ₹5 lakh by March". Each memory has a date and the source, "stated by the user on 4 November". When the user later says the goal is now ₹6 lakh, the assistant asks to update it. The user can open a page that lists everything stored and delete any item. Memory writes triggered by content in uploaded documents are blocked unless the user confirms, which prevents a malicious file from planting a false preference.
A planning and memory worksheet
1. The task. Long or short, structured or exploratory?
2. The plan style. Plan then execute, plan as you go or a mix with replanning?
3. The visible plan. Steps, statuses, who can edit.
4. The checks. Which steps are verified, how and with what catch rate?
5. The history. Maximum size, and the trimming or summarising rule.
6. The working notes. What the agent keeps as state.
7. Long-term memory. What is stored, what is not, and who can see and delete it.
8. Writing and reading rules. When to write, how to resolve conflicts, how to retrieve.
9. The risks. Staleness, privacy, poisoning, cross-contamination.
10. The tests. Cases for plan quality, check catch rate and memory correctness.
Common mistakes
Planning every task, including trivial ones.
Following a plan blindly when results contradict it.
No checks on steps where errors spread.
Letting the history grow without limit.
Summaries that lose key facts.
Storing everything, including guesses and sensitive data.
Memories with no date or source.
Letting untrusted content write to memory.
No way for users to see or remove what is stored.
Key takeaways
A plan gives coverage, focus, visibility and checkability. Plan then execute suits structured tasks, planning as you go suits exploration, and many systems plan briefly and replan when something fails.
Checkpoints raise the success of multi-step tasks. Six steps at 93% succeed 64.7% of the time. With a check that catches 70% of errors after each step, they succeed 86.2% of the time.
Check where errors are costly or spread silently, not everywhere.
Memory comes in three kinds: short-term in the window, working notes of the current state and long-term storage retrieved on demand.
Control the history by trimming tool results, using a sliding window, summarising, offloading to notes and retrieving what is needed. Summarising 40,000 tokens to 4,000 over 10 steps saves about ₹9.12 net, but costs more than it saves if few steps remain.
Store stable, confirmed facts with their source and date. Do not store sensitive data without need, and do not store guesses.
The risks are false and stale memories, privacy, poisoning, over-personalisation and cross-contamination. Let users see and delete what is stored.
Check yourself
1. When is "plan as you go" better than "plan then execute"?
When the next step depends on what earlier steps find, as in research or debugging.
2. A task has 5 steps, each right 90% of the time. What is the chance all succeed with no checks?
0.9 to the power 5 = 0.59, or 59%.
3. Why not check every step of every plan?
Checks cost time and tokens. They pay off where errors are expensive or spread silently, but not on steps that are low-risk or easy to redo.
4. A history of 20,000 tokens is replaced by a 2,000-token summary with 5 steps left. How many input tokens does this save?
18,000 × 5 = 90,000 tokens, before the cost of the summarising call.
5. Name two things an agent should not store in long-term memory.
For example: passwords or payment details, and guesses presented as facts. Also anything the user asks it to forget.
6. What is memory poisoning?
Planting false facts or instructions in the agent's memory, for instance through a document it reads, so that they influence later behaviour.
Try this
Plan a task and design its memory. Set aside 60 minutes.
1. Choose a multi-step task you might give an agent, such as comparing suppliers, preparing a report or triaging a set of tickets.
2. Write a plan of five to eight steps, with a status field for each, and mark which steps depend on earlier results.
3. For each step, write a check you could run, and mark the two steps where a check is most valuable.
4. Use the first simulator with your per-step success rate and a guess at the check's catch rate to see the chance of success with and without checks.
5. Estimate how large the history would grow, and use the second simulator to see whether summarising would pay.
6. Write what a long-term memory for this agent would hold, what it would not, and how a user could see and delete it.
7. Write one rule that protects memory from untrusted content.
A good result is a plan with statuses and checks, a success estimate with and without checks, a summarising decision with numbers and a memory policy covering what is stored, what is not, deletion and protection from untrusted content.
Tags: AI Engineering Agents Planning Memory Context management