Dayward AI
Week 1 · D4About 4 hours

Long-Running Sessions: Compression, Notes and Memory Files, Subagent Isolation and Handoff Summaries

A window will always fill up once a task runs for tens of minutes. Today implement a measurable compression strategy, and draw a clear line between when notes-and-memory-files and when subagent isolation each fit.

Today's goals 0/3

Sign in to tick these off and save your progress.

Today's Goals

  1. Implement a compression strategy, and verify it with the token count before and after plus a key-information retention check
  2. Name which tasks compression, notes-and-memory files, and subagent isolation each suit
  3. Write a handoff summary template, and explain why a subagent should only pass back a summary, not its full process

The first three days all treated things whose per-turn length is essentially controllable. Today treats the last piece: conversation history. Its defining trait is that it only grows, and a task running tens of minutes will inevitably fill the window. Come back when you have read it and tick off the three goals.

Plain-Language Walkthrough

Repacking at a layover

A long trip means a connection. In three hours at the transfer airport, experienced travellers do one thing: open the case and repack it. Clothes worn on the first leg go into the laundry bag and down to the bottom, the boarding pass stub goes in the bin, and the contract needed on the second leg moves to the top. Same case, and most of the usable space is back.

Compaction is that act. When a session nears the window limit, summarize what came before into a shorter passage, replace the original with it, and carry on with the summary.

It differs from yesterday's pruning in one fundamental way, and that difference is what makes it more dangerous: pruning operates on structure, compaction on language. Pruning drops an audit_log field and you know what you dropped and can fetch it back any time. Compaction turns thirty turns of conversation into a three-hundred-word summary, and what got lost was decided by the model, with no marker afterwards to tell you anything was lost at all.

So the entire difficulty of this craft is not how to compact — calling a model to summarize is something anybody can write. The difficulty is proving you did not compact wrongly. In today's lab the compactor has two outputs: a compression ratio and a key-fact survival check. Only the second makes the first mean anything.

So what should be kept and what thrown out, when should compaction fire, and when is compaction simply the wrong answer? One at a time below.

The craft of compaction: what to keep, what to drop, how to verify

Start with the trigger. The most common mistake is triggering by turn count: compact every 20 turns. That rule will fail, because turn count is not proportional to token count — one tool result outweighs twenty turns of small talk. What to watch is the window-occupancy rate.

An implementation you can use as is:

compact.js
// Trigger on occupancy, not turn count: one tool result outweighs twenty turns of small talk
export function shouldCompact(turns, window, threshold) {
  return estimateTokens(turnsToText(turns)) / window >= threshold
}
 
// Splitting: the last keepTurns turns must be kept verbatim.
// Summarize the thing currently in progress and the model instantly loses its referent,
// asking "which order do you mean" on the very next line
export function splitKeepAndFold(turns, keepTurns) {
  const cut = Math.max(0, turns.length - keepTurns)
  return { fold: turns.slice(0, cut), keep: turns.slice(cut) }
}

Next, what the summary should contain. A freeform "please summarize the conversation above" produces a passage that reads smoothly and turns an order number into "the relevant order." Identifiers are what a summary loses most easily, because they are linguistically unimportant and engineeringly everything. So the summary prompt has to do two things: section the output, and demand identifiers be kept verbatim by name. Today uses three sections:

  • Settled conclusions: facts already confirmed that will not change, listed one per line, keeping the original identifiers such as order numbers, amounts, tracking numbers, and policy clause numbers.
  • Open items: what is unfinished and has to be continued.
  • Hard constraints: rules that must not be broken, plus any firm requirement the user stated.

Last comes verification, which is the real point of today. The lab presets four facts that must still be findable after compaction and checks each one afterwards. Under the default configuration 2,199 tokens compact to 701, a ratio of 68.1%, with all four surviving; drop the retained turns from 6 to 1 and the ratio rises to 87.3%, but the fact that the user asked for an answer before 18:00 on Friday disappears outright — because it lives only in the verbatim text of the last few turns, and because it does not look like a conclusion linguistically, so a summarizer will not go fishing for it.

Light compaction first: clear tool results before reaching for a summary

Settle one thing before writing any summary code: much of the time you do not need a summary at all.

Yesterday's profile already showed that history is often not the largest of the four pieces. What actually fills the window in a session is usually the pile of accumulated tool results — and they have an advantage a summary does not: old tool results can simply be deleted, because the model read them long ago and already used them. The raw JSON of an order lookup has no value once the model has said "your order has shipped."

That is light compaction: no model call, no semantic understanding, purely positional replacement of old tool results with a placeholder note. It is cheap, deterministic, reversible (the placeholder keeps the ref), and it loses no linguistic information.

Claude's API turns this strategy into a managed capability: with it enabled, input over a configured threshold automatically clears the earliest tool results, triggering by default at a hundred thousand tokens, retaining the last 3 tool calls, and reporting in the response how many were cleared and how many tokens were saved. It also cooperates with the memory tool — before clearing fires, the model first receives a nudge to write anything still needed into a memory file, and only then does the clearing happen.

So the right order is clear tool results first, and summarize history only if that is not enough. Plenty of people do it the other way because summarizing sounds more sophisticated; but a summary costs an extra model call and carries the risk of losing information, and what it treats is usually not the bulk.

There is also a caching trade-off here that few anticipate: clearing breaks the cached prefix. The cleared tool results sit in the middle of the message sequence, so touching them means everything after has to be written into the cache again. Clearing must therefore be neither too frequent nor too small — the managed capability offers a "clear at least this many tokens before acting" parameter precisely to guarantee that the money this clearing saves outweighs the cost of rebuilding the cache. Set that floor in a hand-written strategy too, or you get a program clearing and rebuilding the cache every turn: a pretty token count and a bigger bill.

Notes and memory files: put state outside the window

Compaction solves "it will not fit in the window," but it has a ceiling: the summary is itself in the window, and given a long enough session, the summary of summaries fills up too.

The other route is writing state outside the window. As it works, the model actively writes important information into files — an open-items list, confirmed facts, the next step — and reads it back when needed. That practice has a name, structured note-taking, also called agent memory.

Its division of labor with compaction is clear:

CompactionNotes and memory files
Where it livesIn the contextIn files outside the context
Who decides what to keepThat one summarizing callThe model, at any point in the process
Can it lose things twiceYes, summaries of summariesNo, the file stays
What it suitsA session running one main threadIterative tasks that resume across sessions

Anthropic published a telling example: a model playing Pokémon kept persistent notes and, thousands of steps in, still maintained exact counts, drew maps, and remembered its long-term strategy — none of which compaction could have preserved, because they are incrementally accumulated state rather than summarizable conclusions. They also turned the capability into a public beta memory tool, letting a model maintain a file-based knowledge base of its own.

The notes route has one more benefit compaction cannot offer: crossing sessions. A compaction's output lives in this session's context and vanishes when the session ends; notes written to a file can be read back next time you start. So for any task done half today and continued tomorrow, notes are not optional but mandatory — otherwise every morning starts by restating yesterday's conclusions, and every restatement loses something.

To decide which route, one question suffices: is this thing's state a conclusion or a ledger? Conclusions can be summarized; a ledger has to go in a file — you cannot summarize a book of transactions into one sentence and still expect it to reconcile.

Subagent isolation: each carries its own suitcase

The third route is more radical: use a different suitcase.

The main agent plans, and when it meets a subtask needing extensive exploration it starts a subagent. The subagent has its own clean context window in which it can burn tens of thousands of tokens searching, trying, and reading files, and when it is done it passes back only a condensed summary to the main thread, typically one or two thousand tokens. The main agent's context gained only those one or two thousand tokens from start to finish, and never saw a word of the tens of thousands in between.

Anthropic's multi-agent research system is built that way: a lead agent sets strategy and dispatches, and several subagents explore in parallel with their own separate context windows. That architecture scored 90.2% higher than a single agent on their internal research evaluation.

But its cost has to be stated plainly, and it is a big number: agent-style applications already use roughly 4 times the tokens of chat, and multi-agent systems roughly 15 times. Subagent isolation does not buy savings; it spends money to keep the main thread's context clean. So its applicability is narrow:

  1. The subtask involves heavy exploration but its output condenses to one page — "find every place in this codebase that calls a given endpoint," say.
  2. The subtasks are independent and can run in parallel — isolation only makes serial subtasks slower and dearer.
  3. The main thread genuinely does not need to see the intermediate process — if the main agent will ask follow-up questions about details, isolation has manufactured an information gap.

Fail any one of the three and use compaction honestly. Do not reach for multi-agent because it sounds more impressive; a 15-times bill is not an abstraction.

What a handoff summary should contain

That one page a subagent passes back determines whether the whole architecture holds up. It is not "summarize what you did" but handoff material that lets the main thread keep making decisions without reviewing the process. The same three sections as compaction suffice, with stricter requirements per section:

handoff.js
// The three sections of a handoff summary: an output contract for the subagent, not a suggestion to it
export const HANDOFF_CONTRACT = `When finished, pass back only these three sections. Do not narrate the process.
 
Settled conclusions: facts you verified that can be relied on directly. Each must carry a source
identifier (file path, order number, URL) so the main thread can re-check it for itself rather than
trusting your paraphrase.
Open items: what you did not finish or lacked permission to do, each stating where it is stuck.
Hard constraints: limits you discovered that the main thread must respect from here on. Write "none"
if there are none; never omit this section.`
 
export function validateHandoff(text) {
  const missing = ['Settled conclusions', 'Open items', 'Hard constraints'].filter(
    (s) => !text.includes(s)
  )
  if (missing.length > 0) throw new Error(`handoff summary is missing sections: ${missing.join(', ')}`)
  return text
}

"Each must carry a source identifier" is the most important line in the whole contract. A conclusion without an identifier cannot be re-checked, leaving the main thread to either believe everything or redo everything, both of which are bad. With identifiers, the main thread can spot-verify the one line it doubts, at a controllable cost.

One last easily overlooked point: the main agent's own plan should also be written outside the window. Late in a long task, once the context is truncated or compacted, the first thing lost is often that initial plan — which is exactly the thing that should never be lost. Writing the plan into a file or memory first is insurance too cheap to skip.

Source Reading

Hands-On Lab

🧪 D4 lab: a compaction strategy

Code location: labs/context-engineering-5days/day-04-compaction-strategy

Acceptance criteria:

  1. MOCK=1 pnpm start prints the occupancy rate first and enters compaction only once the threshold is met; setting the threshold to 0.9 prints that the trigger threshold was not reached and exits.
  2. The compacted context divides visibly into two parts: the three-section prior summary, plus the last several turns kept verbatim.
  3. The compression ratio is printed and lies between 65% and 90%; the reference answer's default configuration gives 68.1%.
  4. All four key-fact survival checks come out ✅ and the script exits 0.
  5. With the retained turns set to 1, the fact about the user's requested deadline turns ❌ and the script exits 1.

This lab's MOCK=1 uses a local extractive summarizer whose shape matches model output, so triggering, splitting, assembling, and checking all genuinely run offline. Put your attention on the fifth criterion: watching a specific fact vanish because of compaction teaches more than reading "compaction loses information" ten times.

  1. Get the solution's MOCK=1 pnpm start running and read the occupancy rate, the compression ratio, and the four survival checks.
  2. Go back to the starter and complete exercise 1's trigger criterion, verifying it refuses to compact with the threshold at 0.9.
  3. Complete exercise 2's splitting so the last 6 turns return verbatim, and watch that final deadline requirement reappear.
  4. Complete exercise 3's three-section summary prompt and exercise 4's survival check, confirming the check genuinely verifies rather than being vacuously true.
  5. Run once with retained turns at 1, note which fact was lost and why it was that one, then think of a change that would rescue it.

Interview Questions

Today's 3 questions are in the question bank below, weighted toward triggering and verifying compaction, how to write external memory, and the design of subagent isolation and handoff summaries. Expand each one and read the analysis before the key points — practicing the derivation beats memorizing bullets. The high-frequency labels for the domestic and overseas markets are there so you can pick by target market.

Checklist and Tomorrow

  • Implement a compression strategy, and verify it with the token count before and after plus a key-information retention check
  • Name which tasks compression, notes-and-memory files, and subagent isolation each suit
  • Write a handoff summary template, and explain why a subagent should only pass back a summary, not its full process
  • Explain why tool results should be cleared before summarizing history is considered
  • All 5 acceptance criteria of the lab pass, including watching one fact vanish to compaction
  • Answer at least 2 of the 3 interview questions without looking at the key points

Tomorrow (D5) we close the loop: turning these four days' techniques into a measurable cycle. You will work out a task's full token bill (including how caching rewrites it, where a counter-intuitive conclusion is waiting), define two utilization metrics, triage against four failure modes, and finish with a context engineering interview deep dive. The first four days taught techniques; tomorrow teaches which technique when — and when to stop.

Interview questions

  • When should you compact the context, and when should you just move to a larger context window?什么时候该压缩上下文,什么时候该直接换一个更大的窗口?
    Common in ChinaCommon overseasIntermediate#compaction#context-rot

    How to reason about it · think before answering

    1. This checks whether you treat the window as capacity and attention as a budget. Answering only that you compact when it does not fit misses half the cases, since plenty of sessions should be compacted while the window is still mostly empty.
    2. Separate the two problems. Not fitting is capacity, and a bigger window fixes it. But a bigger window does not fix context rot: recall degrades as context grows, on a gradient, so a large nominal window is not a promise of stable behavior at that length. Fitting and being used well are different.
    3. Give the test: watch two signals, not one. High window occupancy means compact for capacity. Low occupancy with a low share of actually-useful tokens also means compact, for attention. The second is the one people miss because nothing looks urgent.
    4. Then order the tactics. Compaction is not the first move. Clear stale tool results first, since that needs no model call, is deterministic, and is reversible. Only then summarize history. Doing it the other way costs an extra call and risks losing information while usually treating the smaller bucket.
    5. Expect the follow-up: when is compaction itself not enough? When the state is an accumulating ledger rather than a summarizable conclusion, such as exact tallies, maps, or a long-term plan. Those belong in files outside the window.

    分析过程 · 先想清楚再作答

    1. 这题在考你有没有把窗口当容量、把注意力当预算。只回答「窗口不够就压缩」的人漏掉了一半——很多时候窗口还很空,但已经该压了。
    2. 怎么拆:先把两个问题分开。窗口不够是容量问题,换大窗口确实能解决;但换大窗口解决不了上下文腐烂——上下文越长模型准确回忆的能力越差,这是一条缓坡,标称窗口大不等于在那个长度上表现稳定。所以「装得下」和「用得好」是两件事。
    3. 给判据:看两个指标而不是一个。窗口占用率高就该压(容量问题);占用率不高但有效信息占比很低,也该压(注意力问题)——后者最容易被忽略,因为看起来毫无压力。
    4. 再给顺序上的结论:压缩不是第一手段。先清掉旧的工具结果(不用调模型、确定、可逆),不够再摘要历史。反过来做的人很多,因为摘要听起来更高级,但摘要要多花一次调用、要承担丢信息的风险,而它治的往往不是大头。
    5. 可预期的追问:那什么时候压缩也不够?当状态是渐进积累的账本而不是可总结的结论时——比如精确计数、地图、长期计划。这类东西要写到窗口外面的文件里,不能靠摘要保住。

    Key points

    • Not fitting is capacity and a larger window solves it; context rot is attention and a larger window does not.
    • Two triggers: high window occupancy, or low occupancy with a low share of useful tokens.
    • Clear stale tool results first (no model call, deterministic, reversible), then summarize history.
    • If the state is an accumulating ledger such as tallies, maps, or a plan, use external files instead of compaction.

    答题要点

    • 窗口不够是容量问题,换大窗口能解决;上下文腐烂是注意力问题,换大窗口解决不了。
    • 两个触发信号:窗口占用率高,或占用率不高但有效信息占比很低。
    • 顺序上先清旧工具结果(不调模型、确定、可逆),不够再摘要历史。
    • 如果状态是渐进积累的账本(计数、地图、长期计划),压缩救不了,要写到窗口外的文件里。
  • What does compaction lose most easily, and how do you verify that a given compaction kept what mattered?压缩最容易丢什么?你怎么验证一次压缩没有丢掉关键信息?
    Common in ChinaCommon overseasDeep dive#compaction#verification

    How to reason about it · think before answering

    1. The signal is entirely in the second half. Saying you keep the important parts is empty; interviewers want an executable verification step and evidence it has actually caught something.
    2. Explain why compaction is riskier than trimming. Trimming changes structure: you know which field you removed and you can fetch it back. Compaction changes language: what got dropped is the model's choice, and nothing marks the loss.
    3. Name the fragile categories. First, whatever is currently in flight in the last few turns, which loses its referent the moment it is folded. Second, hard requirements that do not look like conclusions, such as user-stated deadlines, emotional demands, or verbal commitments. Third, identifiers, which summaries happily rewrite from an order number into the relevant order.
    4. Conclusion: preset a list of facts that must remain findable after compaction and check them every time, rejecting the compaction or widening the verbatim window on failure. Support it with three measures: keep recent turns verbatim, give hard requirements their own section in the summary prompt, and demand verbatim preservation of identifiers.
    5. Expect the follow-up asking whether it ever caught you. A concrete case lands best: dropping the verbatim window from six turns to one raised the compression ratio from 68 to 87 percent but silently deleted a user's stated Friday deadline, because it lived only in recent turns and did not read like a conclusion.

    分析过程 · 先想清楚再作答

    1. 这题的区分度全在后半句。谈「要保留重要信息」是空话,面试官想听的是一个可执行的验证机制,以及你有没有真的被它拦下来过。
    2. 怎么拆:先说清压缩为什么比裁剪危险。裁剪动结构,删掉一个字段你知道删了什么、也能取回来;压缩动语言,丢掉了什么是模型决定的,而且丢完不留任何标识。
    3. 点出最脆弱的两类内容:一是最近几轮正在进行的事,一折叠就失去指代对象,模型下一句就会问你说的是哪一单;二是形式上不像结论的硬性要求,比如用户提出的时间点、情绪化诉求、口头承诺——它们在语言上不重要,在业务上是全部。还有一类是标识符,摘要很容易把订单号写成「相关订单」。
    4. 结论给验证机制:预置一组「压缩后必须还能找到」的关键事实,每次压完逐条核对,不通过就拒绝这次压缩或调大保留轮数。三条配套措施是:保留最近若干轮原文、在摘要提示词里让硬性要求单独成段、明确要求逐字保留标识符。
    5. 可预期的追问:你被这个检查拦下来过吗?给一个具体例子最有力,比如把保留轮数从 6 调到 1 时压缩率从 68% 涨到 87%,但「用户要求周五 18:00 前答复」这条直接消失——因为它只活在最近几轮原文里,而且它不像一条结论。

    Key points

    • Compaction is riskier than trimming: structure is recoverable, language loss is silent.
    • Three fragile categories: what is in flight in recent turns, hard requirements that do not look like conclusions, and identifiers.
    • Verification: preset facts that must survive and check each one after every compaction, rejecting it on failure.
    • Support with a verbatim recent window, a dedicated section for hard requirements, and explicit verbatim preservation of identifiers.

    答题要点

    • 压缩比裁剪危险:裁剪动结构可回溯,压缩动语言且丢失无标识。
    • 最容易丢的三类:最近几轮正在进行的事、不像结论的硬性要求、标识符。
    • 验证机制:预置一组必须存活的关键事实,每次压完逐条核对,不通过就不采纳这次压缩。
    • 配套三招:保留最近若干轮原文、硬性要求在摘要里单独成段、要求逐字保留标识符。
  • Why does a subagent return only a summary instead of its full transcript, and how should the lead agent specify the handoff?子代理为什么只回传摘要而不回传全过程?主代理该怎么写交接要求?
    Common in ChinaCommon overseasDeep dive#subagents#handoff#cost

    How to reason about it · think before answering

    1. This tests architectural intent. Saying it saves tokens is only half right, and the lesser half: multi-agent setups are more expensive overall, not cheaper.
    2. State the purpose. Subagent isolation buys a clean main context, not a smaller bill. A subagent can burn tens of thousands of tokens exploring in its own window while the main thread gains only a condensed result of one or two thousand tokens. It is separation of concerns applied to context.
    3. Put the cost on the table, which is where engineering experience shows: agentic applications use roughly four times the tokens of chat, and multi-agent systems roughly fifteen times. So the fit is narrow: heavy exploration with a condensable result, independent parallelizable subtasks, and a main thread that genuinely does not need the intermediate steps. Missing any one, fall back to compaction.
    4. Conclusion: specify a handoff contract of three sections (settled conclusions, open items, hard constraints), with every conclusion carrying a source identifier such as a file path, order id, or URL. Without identifiers the main thread can only trust everything or redo everything; with them it can spot-check the one claim it doubts. Require the constraints section even when empty, or the main thread cannot tell absent from forgotten.
    5. Expect the follow-up about the lead agent's own plan: write it outside the window too, since truncation or compaction late in a long task tends to eat the original plan first.

    分析过程 · 先想清楚再作答

    1. 这题在考架构意图。答「为了省 token」只对了一半,而且是次要的那一半——子代理架构整体上是更贵的,不是更省的。
    2. 怎么拆:先说清目的。子代理隔离买的不是省钱,是主线上下文的干净。子代理可以在自己独立的窗口里烧掉几万 token 反复探索,主线只多了一两千 token 的浓缩结论,中间过程一个字都没进主线。这是关注点分离在上下文层面的落地。
    3. 把代价摆出来,这是最能体现做过工程的地方:Agent 类应用本来就比聊天多用约 4 倍 token,多 Agent 系统约 15 倍。所以适用面很窄——探索量大但产出能浓缩、子任务彼此独立可并行、主线确实不需要看中间过程,三条缺一就该退回压缩。
    4. 结论给交接契约:三段式(已定结论、待办事项、硬约束),且每条结论必须带来源标识(文件路径、订单号、URL)。原因是没有标识的结论不可复查,主线只能全盘相信或全盘重做;带标识之后主线可以只对存疑的那条做定点核实。硬约束那一段没有也要写「无」,不能省略,否则主线分不清是没有还是忘了写。
    5. 可预期的追问:主代理自己的计划怎么办?也该写到窗口外面。长任务后期一旦触发截断或压缩,最先丢的往往就是最初那份计划,而它恰恰最不该丢。

    Key points

    • Isolation buys a clean main context, not savings; multi-agent is more expensive overall.
    • Magnitudes: agents use about four times chat tokens, multi-agent about fifteen times.
    • Fits when exploration is heavy but condensable, subtasks are independent and parallel, and the main thread does not need intermediate steps.
    • Handoff contract in three sections, every conclusion carrying a source identifier, and an explicit none when constraints are empty.
    • Persist the lead agent's plan outside the window, since it is the first casualty of truncation late in long tasks.

    答题要点

    • 隔离买的是主线上下文的干净,不是省钱;多 Agent 整体更贵。
    • 代价数量级:Agent 约为聊天的 4 倍 token,多 Agent 约 15 倍。
    • 适用三条:探索量大且产出可浓缩、子任务独立可并行、主线不需要中间过程;缺一就退回压缩。
    • 交接契约三段式,每条结论必须带来源标识,硬约束段即使为空也要显式写「无」。
    • 主代理自己的计划也要写到窗口外,长任务里它最容易被截断或压缩吃掉。

Comments