Chapter 3. Context, memory and state

Learning objectives

  • Explain context rot and the Attention Budget, and establish criteria for selecting information to put into the context.
  • Choose a technique suited to the nature of the task from among compaction, tool result clearing, structured notes, and subagents.
  • Distinguish among conversation history, task state, long-term memory, and the Business Ledger, and prevent context contamination in long-running executions.
  • Design suspension and resumption using checkpoints and idempotency, and verify external state at the point of resumption.
  • Structure multi-session work into a handoff package so that the next executor can take it over.

Introduction

An agent assigned a two-day task makes a strange statement on the afternoon of the second day: "The task is almost complete." Upon checking, half of it has not even been touched, and a rule agreed upon with the team on the morning of the first day has vanished without a trace. It is not because the agent is lazy. In the meantime, the context filled up multiple times and was replaced with summaries each time; while the summaries maintained continuity, they failed to preserve the exact state.

For a human, this would be equivalent to undertaking a long project relying solely on memory without taking notes. This chapter covers how to equip agents with notepads and work logs. After sorting out what to put in the context and what to leave outside, how to choose among compaction, external memory, and subagents, and how to prevent contamination, we proceed to checkpoints, resumption, and handoffs.

Key concepts

Context is a finite budget

Anthropic defines context engineering as the overall strategy of curating and maintaining the optimal set of tokens entering a model during inference. If prompt engineering is the work of refining instructions, context engineering covers everything the model sees, including the system prompt, tool definitions, tool results, message history, and external data.

The rationale is context rot. This is the observation that as tokens in the context increase, the ability to accurately recall information within it declines. The same article explains that an LLM has an Attention Budget. Because transformers compute relationships between each token and all other tokens in the context, the number of relationships increases proportionally to the square of the number of tokens (n²), and attention spreads more thinly as tokens increase. Every new token consumes a little bit of this budget.

By analogy, context is like the surface of a desk. Even if the desk is large, if you spread out every document, it becomes difficult to find the single page you need right now. A large window means you can put in a lot, not that the model uses everything you put in equally well.

What to include: Altitude, tools, and examples

The same article provides criteria for each context component.

Component What to avoid What to aim for
System prompt Embedding complex, brittle if-else logic; conversely, vague instructions lacking concrete signals The "right altitude" that is specific enough to guide behavior yet flexible
Tools Bloated tool sets where functionality is too broad or determining which tool to use is ambiguous A configuration where a human engineer can also immediately tell which tool to use
Examples Exhaustive lists of every edge case A few diverse, representative examples that clearly demonstrate expected behavior

"The right altitude" is an expression likening the approach to the altitude of an airplane. If you fly too low, you get caught on every terrain feature; if you fly too high, you cannot see your destination. A prompt that lists 180 exception cases as rules breaks other cases whenever a single rule is modified. It is easier to maintain if you replace them with principles and representative examples, while safeguarding expected behavior with an evaluation set (Chapter 4).

Just-in-time retrieval and progressive disclosure

Rather than loading all data in advance, the approach where an agent holds only lightweight identifiers—such as file paths, saved queries, or links—and retrieves them with tools when needed is called just-in-time retrieval. Claude Code does not read large datasets in their entirety, but inspects only necessary portions using commands like head and tail. The process where an agent explores and discovers required context incrementally is called progressive disclosure. This is analogous to a human using a table of contents and bookmarks rather than memorizing an entire book.

Just-in-time retrieval does not always win. This is because exploration during execution is slower than loading in advance. Therefore, the same article introduces a hybrid strategy. Claude Code loads CLAUDE.md from the working directory and all parent directories at startup. It loads CLAUDE.md files from subdirectories when they become necessary, and locates remaining files on the fly using glob and grep. Stable materials needed almost every time are loaded in advance, while large and frequently changing materials are searched on demand; in domains where context is less dynamic, such as law or finance, the proportion loaded in advance can be increased.

Succeeding in retrieval does not mean finding the right answer. Retrieval results must be accompanied by source reliability, document effective date, and the current user's access permissions. Prompting the model to say "not found" rather than concluding "does not exist" when evidence cannot be found is also part of retrieval design.

Four layers of information

In long-running systems, there are four types of information with different characteristics. Mixing them causes incidents.

Layer Example Authority Lifetime
Conversation history Messages and tool results Low. Summarized and truncated Session
Task state Progress files, checkpoints Basis for resumption Until task completion
Long-term memory User preferences, learned lessons Reference material. Verification required Until specified expiration period
Business Ledger Orders, transfers, approval records Highest. Standard of truth Legal and business retention period

The Business Ledger (system of record) is the system serving as the definitive standard of truth for business facts. Even if an agent remembers that it "processed a refund," whether the refund actually occurred is determined by the ledger in the payment system. When resuming, the basis for determining the next action is task state, not conversation history; if task state conflicts with the ledger, the ledger wins.

Compaction and tool result clearing

Compaction is a technique that summarizes the conversation when the window approaches its limit and starts a new window with that summary. Anthropic explains that good compaction preserves architectural decisions, unresolved bugs, and implementation details while discarding redundant tool outputs, and recommends tuning compaction prompts by first refining them so nothing is missed (recall), and then reducing clutter (precision).

The lightest and safest form of compaction is tool result clearing. This is because raw tool results buried deep in a conversation rarely need to be reviewed again. Platform features also exist. Context editing in the Claude API provides server-side strategies for clearing old tool results, allowing you to configure when to start (trigger), how many recent results to retain (keep), the minimum amount to clear at once (clear_at_least), and tools not to clear (exclude_tools). The Claude API also offers server-side compaction (beta). Initially, there was only threshold-based compaction that ran when input tokens exceeded a baseline. On 2026-09-14, request-based compaction (compact-2026-09-04), where the application determines the timing, was added; now, request-based compaction is recommended wherever it can be used. The OpenAI Agents SDK includes session implementations that compact session history using the Responses API. Names and options are subject to change, so consult the documentation.

Caution

Summaries maintain continuity, but they may fail to preserve exact state. For information that must remain precise, such as "how much has been completed" or "what has been decided," do not rely on compaction; instead, maintain it as a structured record outside the context.

Structured notes and external memory

Structured notes is a technique where an agent writes notes outside the context window and reads them back later. Anthropic's examples include Claude Code's to-do lists, NOTES.md files, and a Pokémon game experiment where progress and maps were recorded across thousands of steps. It is well-suited to iterative tasks with clear milestones.

Turning this into a product feature yields memory tools. Claude's memory tool operates on the client side. When the model requests file operations under /memories, the application's handler executes them in its designated storage, making safety mechanisms the application's responsibility as well. The documentation recommends normalizing all paths to verify they do not escape /memories (preventing path traversal attacks like ../), filtering out sensitive information, placing upper bounds on file sizes, and pruning files that have remained unused for a long time.

Google ADK distinguishes between two layers. Sessions and state are the short-term memory of a single current conversation, while the memory service is a long-term memory store searched and used across multiple past conversations (populated with add_session_to_memory and searched with search_memory). Since in-memory implementations for development disappear upon restart, persistent implementations are used in production.

Isolating context with subagents

A subagent architecture is an approach where specialized subagents perform focused tasks in clean windows and return only compacted results. According to Anthropic, even if a subagent explores tens of thousands of tokens, it typically returns a summary of about 1,000 to 2,000 tokens. Because the noise of exploration does not enter the primary agent's window, the primary agent can focus on synthesis and judgment. It is well-suited to complex investigations where parallel exploration is advantageous.

Some results cannot be handled by summaries alone. When the primary agent transcribes deliverables that must not change by even a single character—such as tables or code—context fills up and errors occur during transcription. Anthropic's research system reduced information loss and token waste by having subagents write results to external storage (such as files) and return only lightweight references (such as file paths or storage keys). The same article also introduces a pattern where the lead agent stores its plan in memory, as the context gets truncated if it exceeds 200,000 tokens.

The uses of the three techniques are summarized as follows:

Technique Well-suited tasks Potential losses
Compaction Tasks requiring lengthy back-and-forth Exact state, early decisions
Structured notes Iterative tasks with clear milestones Anything not written in the notes
Subagents Investigations where parallel exploration is advantageous Details omitted from the summary (originals preserved by reference)

Preventing context contamination

Context contamination is the phenomenon where inaccurate, outdated, or untrusted information accumulates in the context and continuously distorts subsequent judgments. There are three causes: traces of failed attempts (a succession of attempts producing the same error remains, trapping the model in that path), untrusted content (instructions embedded in web pages or documents), and stale memory (facts that have already changed).

The rules for prevention are as follows:

  1. Clear raw tool results that have served their purpose, leaving only essential points and references.
  2. When the same failure repeats, reduce the failure record to a single-line summary, explicitly state a new approach, and start over. If necessary, delegate the task to a clean subagent.
  3. Demarcate external content with source attributions to distinguish it from instructions, and do not follow statements within it as instructions (Chapter 5).
  4. Attach sources and observation timestamps to memory items, and reverify or discard outdated items.
  5. Do not elevate user utterances to the level of system instructions without validation. Memory is data, not authority.

Prompt caching and context construction

Long-running agents resend similar prefixes dozens or hundreds of times. Prompt caching reuses the processing of these repeated prefixes to reduce costs and latency. Based on the Claude API documentation, the cache constructs prefixes in the order of tools, system, and messages; if any layer changes, that layer and all subsequent layers are invalidated. Changing a tool definition invalidates the entire cache. The default lifetime is 5 minutes and refreshes upon each use, with a 1h option also available. Each model has a minimum cacheable length, so prefixes shorter than that threshold are not cached even if designated. Cache hits are verified via cache_read_input_tokens and cache_creation_input_tokens in the response.

Common mistakes that break the cache include placing values that change with every request (current time, request ID) ahead of fixed instructions, recreating tool definitions each time while altering their content or order, and using JSON serialization where key order varies arbitrarily. The rule of thumb is to place immutable elements first and mutable elements last. Tool result clearing also conflicts with caching. Because the cache is invalidated starting from the cleared point, the documentation recommends clearing enough at once to make the cost of invalidation worthwhile (clear_at_least).

Checkpoints and idempotency

Long-running tasks that produce external side effects must not restart from the beginning when they fail. Anthropic's research system article notes that agents maintain state and accumulate errors, and describes combining deterministic safeguards—such as retry logic and regular checkpoints—in a system that resumes from the point of failure. It also recommends informing the agent when tools are failing, as even small failures can be fatal.

A checkpoint is a point where step-by-step results are permanently stored to enable resumption, and an idempotency key is an identifier that ensures an effect occurs only once even if the same request is repeated. There are three design elements:

  1. Record what was done, when, and with what outcome at each step in persistent storage.
  2. Attach idempotency keys deterministically generated from the task and target to external calls (e.g., taskID:targetID:step).
  3. When resuming, determine the next action based on stored records and the ledger, not the model's memory.

Designing resumption after suspension

Resuming from a saved point does not automatically make resumption safe. This is because the world may have changed after saving. Include the following checks in the resumption procedure:

Check Rationale
External state reconciliation Verify via the ledger or query APIs whether external operations actually occurred after the last record
Expiration check Ensure approvals, credentials, preview identifiers, and handles remain valid
Execution ownership Ensure another executor has not already claimed the same task (managed via leases—rights of possession valid only for a fixed duration—and their expirations)
Version compatibility Ensure stored state can be parsed by current code and agent definitions

Frameworks also assist with this. The OpenAI Agents SDK allows executions awaiting human approval to be serialized as RunState, stored in a database or queue, and restored to continue execution. The documentation notes that serialized states contain approval decisions, pending tool calls, and their arguments, recommending that they be stored in server-controlled storage, that only trusted snapshots be restored, and that agent definitions or SDK version identifiers be saved alongside the state. In Google ADK, state must be recorded via an event's state_delta to be persisted; modifying session.state directly on a session retrieved from a service is not tracked and may fail to persist. State values must only use serializable primitive types.

Handoffs for long-running tasks

Anthropic's long-running coding agent experiments observed two modes of failure: failing by exhausting context midway through trying to accomplish too much at once, and failing when a subsequent session saw partial progress and prematurely declared the work complete. The solution was separation of roles.

  • Initializer agent (first session): Created init.sh to launch the development server, claude-progress.txt to record what the agent did, a first commit showing the initially added files, and a feature list marking over 200 features as 'Failed'.
  • Coding agent (subsequent sessions): Advanced only one feature at a time, left a trail for the next session through descriptive commits and progress records, and left the environment in a clean state upon completion.

The feature list was written in JSON, which is less likely to be improperly edited or overwritten by the model compared to Markdown; the coding agent was permitted to modify only the passes field, and deleting or altering tests was strictly forbidden. A new session inspected the working directory, read the Git history and progress file, selected the highest-priority incomplete feature from the feature list, and launched the development server to test basic functionality before beginning work. Features were marked as passed only after being verified through end-to-end testing, just as a human would do.

Generalizing this experiment yields a handoff package. This is a document that allows the next executor to take over without having to read through the entire lengthy conversation. It contains objectives and completion criteria, completed items and their verification results, remaining tasks and priorities, verified facts versus ongoing assumptions, deliverables and external operation identifiers, prerequisites for next actions, and points requiring additional approvals. The key is to record verified deliverables rather than self-assessments like "almost done."

Where to place conversation state

You must also determine who manages the conversation history. The OpenAI Agents SDK provides three approaches: manual management, which passes results directly into the next input list; sessions, which load history before execution and save new items after execution; and server-side conversation management (conversation_id or previous_response_id). The documentation instructs selecting a single persistence strategy per conversation, warning that sessions and server-side continuation options cannot be used together in the same run, and that mixing client-managed history with server-managed state can lead to duplicated context.

Google ADK states determine their scope using key prefixes.

Prefix Scope
None Current session
user: All sessions of that user within the same app
app: All users and sessions of that app
temp: Within a single invocation. Discarded upon completion

Choosing the wrong scope can leak one user's information to another, or cause necessary information to vanish in the next session.

The application chooses when to compact

Starting on 2026-09-14, compaction in the Claude API is divided into two approaches. Both are identical in that the server replaces older turns with a summary written by Claude; what differs is the timing of compaction.

Approach Beta header Compaction timing
Threshold compaction compact-2026-01-12 (edit type compact_20260112) When input tokens exceed a threshold. Trigger type is strictly input_tokens, default 150,000, minimum 50,000
Request-based compaction compact-2026-09-04 When the application requests it via the top-level compaction parameter

Both are still in beta. The documentation recommends using request-based compaction wherever possible. This is because every task has its own natural breaking points. Right after completing and committing a feature, the state to preserve in a summary is clear, but that is not the case at the exact moment token count happens to cross a threshold while chasing an error.

In either approach, when a compaction block arrives in the response, you must return that block as-is in the next request to continue the conversation with the reduced prompt. The API ignores content prior to this block. Align the storage format so that code storing conversation history does not drop this block.

Compaction does not replace memory tools. Compaction merely keeps the active context small. Information that must survive through summarization is protected by memory. Memory in Claude Managed Agents (header managed-agents-2026-04-01), released in beta on 2026-04-23, is a separate feature, while the memory tool (memory_20250818) remains an official feature running on the client side.

For example, an agent refining a glossary writes confirmed translations to /memories/glossary.md after completing each chapter, and then requests compaction. Even if translations are omitted from the summary, rereading this file when starting the next chapter revives the decided translations intact.

Considering clearing scope alongside cache pricing

The clear_tool_uses strategy in context editing clears only tool results by default. To clear the arguments passed by the model when calling the tool as well, set clear_tool_inputs to true. For write tools that receive lengthy bodies as arguments, inputs can take up more of the window than results. However, clearing inputs prevents the model from inspecting which arguments were used to invoke the tool. For tasks where the model needs to retrace identical calls, it is better not to enable this.

The default behavior of thinking blocks has also changed. In older models, thinking blocks from previous turns were automatically removed; however, in Opus 4.5 and later, Sonnet 4.6 and later, Haiku 5.5, Fable, and Mythos, the API retains them, occupying the window just like any other input tokens. To remove them, use the clear_thinking_20251015 strategy. When used alongside other strategies, place this strategy at the very front of the edits array.

Whether to clear is determined by considering cache pricing. Cache writes cost 1.25x the base input price (5-minute lifetime) or 2x (1-hour lifetime, specifying ttl as '1h' in cache_control). Cache reads are 0.1x by default; however, for Opus 5.5 and Sonnet 5.5, following the price reduction on 2026-10-07, they are 0.05x, and for Fable 5.1 and Mythos 5.1, 0.025x. The cheaper the read, the relatively larger the penalty incurred by breaking the cached prefix and forcing a rewrite.

Suppose a review agent running on Sonnet 5.5 clears 3,000 tokens of old tool results. The 80,000 tokens cached after that point must be rewritten at the 1.25x rate in the next request. That is 25 times the 0.05x cost that reading alone would have incurred. For such an agent, rather than clearing small amounts frequently, it is better to set a generous clear_at_least threshold and clear in a single batch once the window actually becomes tight.

What to verify when delegating state to the server

Placing state on the server simplifies client code. In exchange, retention duration, the cost of resending, and retrieval mechanisms all depend on server rules.

As announced, the OpenAI Assistants API was shut down on 2026-08-26, and the replacement paths guided by the documentation are the Responses API and Conversations API. Response objects are stored for a default of 30 days, but this TTL does not apply to Conversation objects or the items within them. Even when continuing responses using previous_response_id, all previous input tokens accumulated in the chain are billed as input tokens. Lengthened history is reduced using server-side compact_threshold or stateless /responses/compact. Ollama's /v1/responses supports only stateless operation, accepting neither previous_response_id nor conversation. The application must carry the history itself. Because default context window sizes are documented inconsistently across different pages, configure it explicitly via OLLAMA_CONTEXT_LENGTH.

In the revision on 2026-07-28, MCP tasks departed the core protocol and moved to the official extension io.modelcontextprotocol/tasks. Instead of tasks/result, which blocked waiting for a response, polling is now conducted using tasks/get. When a client sends input to the server, it uses the newly introduced tasks/update. tasks/list has been removed, and the server can return task handles without requiring Agreement for each request. There are five states: working, input_required, completed, failed, and cancelled; the latter three are terminal states and do not change again.

Since list querying has been removed, write the handle to a checkpoint as soon as it is received. When an agent tasked with generating a report restarts, it calls tasks/get using the stored handle. If it is completed, record only the result. If it is input_required, send the missing value via tasks/update.

Going deeper

The gap between checkpoints and external side effects

Saving a checkpoint and modifying an external system are not bound into a single transaction. A process can die immediately after an external call succeeds, before the result is recorded. If resumption code looks only at the record, it judges that "it has not been done yet" and executes the same work again.

The standard procedure for handling this gap is Record Intent → Execute → Record Result. Before execution, first record "I intend to do this task with this idempotency key", execute it, and record the result. When resuming, if you encounter an item that has an intent but no result, query the external system using the idempotency key to check whether it has been processed before executing it again. If it has been processed, record only the result; if it has not been processed, execute it using the same key. If the external system does not support idempotency keys, require human verification, especially for operations where duplicate execution causes significant damage. If an operation cannot roll back all steps, you must design compensating actions alongside it, as covered in Chapter 5.

The lifecycle of memory

Once long-term memory is stored incorrectly, it repeatedly affects multiple tasks. Therefore, memory must also have a lifecycle.

  1. Promotion criteria: Decide what to retain as memory. Retain only information that repeats or is confirmed by the user, rather than passing remarks.
  2. Source and timestamp: Store together who said it, when it was said, and on what basis it was verified.
  3. Conflict resolution: If new information differs from old memory, determine precedence based on recency and authority of the source, and preserve the change history.
  4. Expiration and re-verification: Set an expiration date, and re-verify or discard when it passes.
  5. Propagation of corrections and deletions: When a user requests deletion, delete not only the original but also search indices and summaries created from that memory.

Because the fifth step directly relates to personal information protection obligations, establish retention and deletion criteria together with the personal information officer in accordance with applicable laws and terms of service. Technically, isolate memory stores by user and establish tests that verify whether deletion actually took place.

Evaluating memory and compaction policies

Changing compaction prompts or memory policies may reduce costs, but accuracy can degrade. Make the policy itself an object of evaluation. Compare it against a baseline with no memory, include tasks that test whether it accurately follows previous decisions immediately after compaction, and deliberately plant outdated memories to see whether it filters them out. Measuring the success rate of resumption after a forced interruption is also a good metric.

At work

Milky Way Books: The decision forgotten by an 1,800-book conversion task

E-book distributor 'Milky Way Books' tasked an agent with converting 1,800 legacy e-books into a new format and filling in accessibility information. The first attempt was a single long session with automatic compaction enabled. On the third day, the agent forgot the rule agreed upon with the team on the first day ("Alt text for table images is taken from the original caption") and processed 140 books in a different manner. There were also 60 books marked as 'Completed' without running the validator.

The team rejected two alternatives. They viewed switching to a model with a larger context window as merely postponing the problem of decisions disappearing during summarization. They viewed writing "Do not forget decisions" in the system prompt as the same mistake of entrusting memory to the model.

In the new architecture, the first session handled only initialization. It created and committed books.json containing the status of 1,800 books (pending, converted, validated, failed) and paths to verification results, decisions.md recording agreed conversion rules, and init.sh to run the converter and validator. Subsequent sessions read the three files and the Git history upon starting, and processed 20 books at a time. Status could only be changed to validated after passing the validator, and raw validator logs were removed from the context, leaving only key points. When a new rule emerged, it was first written to decisions.md and committed before continuing work.

Across the next 1,000 books, there was no rework, and no books were marked as Completed without verification. Context usage per session actually decreased.

Furrow Policy Institute: Taking over a three-day investigation

'Furrow Policy Institute' investigated youth housing support policies of basic local governments nationwide over three days to produce a comparison table. The first-day session left a summary stating, "Investigation Completed for 23 out of 41 locations." On the morning of the second day, the client added income requirements to the comparison criteria, and two investigated local governments posted announcements with revised support amounts. The second-day session trusted the first-day summary as is and investigated only the remaining 18 locations. The final table was left with two pre-change amounts, and the income requirement columns for the 23 locations investigated on the first day remained empty.

The team compared alternatives. Passing the entire first-day conversation to the next session filled the context while failing to inform what had changed. Re-investigating from scratch every day cost three times as much. The team chose a handoff package and resumption checks.

In the handoff package, they recorded the version of the comparison criteria document, status and investigated fields for each local government, supporting URLs and verification timestamps, items that remained assumptions, and the next session's first task. Before starting work, a new session checked the criteria document version, and if the version had changed, returned local governments with empty newly added fields to the investigation queue. For evidence whose verification timestamp exceeded 24 hours, it first checked whether the announcement page had been updated. Investigation results were saved in per-local-government files, and the session carried only the paths to those files.

In the next investigation, although criteria changed once and announcements changed across five locations, there were zero outdated values in the final table.

Common mistakes

  1. "With a large window, context management is unnecessary." As numbers grow larger, it may feel as though everything will fit, but recall accuracy drops as the window fills up. A large window merely postpones the need for management.
  2. "A compaction summary preserves progress status as well." Reading a summary offers reassurance as the flow continues, but precise status and early decisions can be omitted. Keep anything that must be precise in structured records.
  3. "For resumption, you just need to ask the model how far it got." It is convenient because the model gives a plausible answer, but the model in a new process knows nothing about previous runs. Determine state from records and ledgers.
  4. "Resuming from a checkpoint is safe." The fact that it was saved provides peace of mind, but external state may have changed or authorizations may have expired after saving. Reconcile before resuming.
  5. "If a subagent returns the entire table, it is accurate." Receiving the original directly appears accurate, but as the lead transcribes it again, context fills up and values become corrupted. Keep results in storage and pass references.
  6. "Putting user utterances directly into long-term memory achieves personalization." While it is the fastest route to personalization, unverified promotion becomes a channel for outdated information and instruction injection.
  7. "The more frequently tool results are cleared, the better." Clearing them makes the window lighter, but every deletion can invalidate the prompt cache. Clear a sufficient volume at once.

Summary at a glance

Item Answer to remember
Why context is finite Context rot, Attention Budget, n² relationship between tokens
System prompt criteria The right altitude, a few representative examples
Just-in-time retrieval Lightweight identifiers + load when needed, stable core materials in advance
The lightest compaction Clearing stale tool results
Selecting a technique Compaction when there are many back-and-forths, notes when there are milestones, subagents for parallel investigation
Where exact state belongs Structured records outside the context. If it conflicts with the ledger, the ledger
Arrangement that preserves cache Unchanging items in front, changing items behind
Resumption procedure Read records → Reconcile external state → Check expiration, ownership, and versions → Execute with idempotency key
Handoff Verified deliverables, distinction between facts and assumptions, premises for next actions

Check the official docs

Self-check

3-1. Explain why context management is necessary even as context windows grow larger, using the term 'Attention Budget'.

3-2. Why is clearing old tool results considered the lightest form of compression, and what must you be careful of when using it with a prompt cache?

3-3. Among conversation history, task state, long-term memory, and the Business Ledger, what should serve as the basis for determining the next action upon resumption, and what should be done if it conflicts with the ledger?

3-4. What failure is the design of a long-term coding harness trying to prevent by keeping the feature list in JSON and only modifying the pass/fail field?

3-5. Explain the reason for recording checkpoints in the order of 'Record Intent → Execute → Record Result', using the case where a process dies immediately before recording the result as an example.

3-6. Give two reasons for storing the source and observation time together with each long-term memory item.

3-7. Design a five-line table of contents for a handover document transferring a three-day research task to another executor, and write one sentence describing the content to be included in each line.

Hands-on tasks

Exercise

Progress File and Resumption from Forced Interruption (60 minutes)

  1. Choose a task that sequentially processes 50 or more items (such as document summarization or data conversion).
  2. Design a JSON progress file containing the status of each item (pending, in_progress, done, failed), an idempotency key, and the result path.
  3. Apply the order of Record Intent → Execute → Record Result to external write operations.
  4. Forcibly terminate the process three times at arbitrary points during execution and rerun it. Terminate it once immediately after an external write.

Done when: The rerun resumes based on the progress file, no item is processed twice, and the final result is identical to running without interruption; then it is Completed.

Exercise

Testing Information Loss Before and After Compression (40 minutes)

  1. Choose one real agent conversation that lasted 30 or more turns (remove sensitive information).
  2. A human first extracts and lists 10 pieces of information from that conversation that are strictly necessary for subsequent tasks (decisions, unresolved issues, identifiers, numerical figures).
  3. Generate a summary using the compression prompt currently in use, and count how many of the 10 items remain accurately preserved.
  4. Revise the compression prompt based on the missing items and count again. Next, check whether the score is maintained even when reducing the summary length.

Done when: The revised prompt preserves 9 or more of the 10 items, and the counts of preserved items and summary lengths before and after the revision remain documented in a table; then it is Completed.