Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-runtime): keep the recent context window when a summary fails

vastsadeea1939bd35
diff --git a/apps/desktop/test/context-compaction.test.mjs b/apps/desktop/test/context-compaction.test.mjs
index c12d741c6..b92087c6c 100644
--- a/apps/desktop/test/context-compaction.test.mjs
+++ b/apps/desktop/test/context-compaction.test.mjs
@@ -34,6 +34,7 @@ const [
subagentContext,
contextBudget,
delegationHistory,
+ compactionTail,
] = await Promise.all([
read("../../../packages/shared/src/protocol.ts"),
readSharedTypesSource(),
@@ -56,6 +57,7 @@ const [
read("../../../packages/agent-runtime/src/subagent-context.ts"),
read("../../../packages/agent-runtime/src/context-budget.ts"),
read("../../../packages/agent-runtime/src/delegation-history.ts"),
+ read("../../../packages/agent-runtime/src/compaction-tail.ts"),
]);
test("context compaction is wired through protocol v11 and the manual IPC path", () => {
@@ -93,7 +95,11 @@ test("the hard boundary is enforced by the host, with a model-side escape hatch"
assert.match(runtime, /prepareNextTurnWithContext/);
assert.match(runtime, /budget\.tokens >= budget\.hardLimit/);
assert.match(runtime, /CONTEXT_COMPACTION_FAILED: unable to create a checkpoint/);
- assert.match(runtime, /checkpoint truncated: this message crossed the retained context budget/);
+ assert.match(runtime, /CHECKPOINT_TRUNCATION_MARKER/);
+ assert.match(
+ compactionTail,
+ /checkpoint truncated: this message crossed the retained context budget/,
+ );
assert.match(runtime, /pendingOverflow/);
assert.match(runtime, /runCompaction\(\s*"overflow",\s*true,\s*"active_turn",?\s*\)/);
assert.match(runtime, /fallback: "retained_tail"/);
@@ -292,14 +298,33 @@ test("every compaction announces itself once, on top of the specific toasts", ()
});
test("a failed compaction checkpoint still restores a non-empty context", () => {
- // A retained-tail fallback must not persist an empty tail on a completed
- // turn: with no real summary to carry the boundary, an empty tail restores
- // as an empty context after a runtime rebuild (model switch / restart) —
- // the session reads as if it had just started (#224).
+ // A retained-tail fallback must not persist an empty tail: with no real
+ // summary to carry the boundary, an empty tail restores as an empty context
+ // after a runtime rebuild (model switch / restart) — the session reads as if
+ // it had just started (#224). It must not persist one user line either: a
+ // failed summary is the only record of the range behind it, so the tail is the
+ // recent window itself (#827).
+ assert.match(runtime, /const retainedTail = this\.fallbackRetainedTail\(/);
+ assert.match(
+ runtime,
+ /return selectRecentTail\(\s*preparation\.messagesToSummarize,/,
+ );
+ assert.match(compactionTail, /export function selectRecentTail\(/);
+ assert.match(compactionTail, /export function replayRetainedTail\(/);
+ assert.match(
+ compactionTail,
+ /COMPACTION_RETAINED_TAIL_SHAPE = "recent_window"/,
+ );
+ // The shape marker is what keeps a rebuild from narrowing the window back to
+ // one user message, so the read gate has to test it.
assert.match(
runtime,
- /const retainedTail =\s*preparation\.retainedTail\.length > 0\s*\? preparation\.retainedTail\s*: selectRetainedUserMessages\(/,
+ /details\.retainedTailShape === COMPACTION_RETAINED_TAIL_SHAPE/,
);
+ // Only a range the planner cannot split falls back at all; a prompt that is
+ // merely too large is summarized in chunks (#827).
+ assert.match(runtime, /private planSummaryRequests\(/);
+ assert.match(runtime, /private async generateChunkedCompaction\(/);
assert.match(
runtime,
/fallback: "retained_tail" satisfies ContextCompactionFallback,/,
diff --git a/docs/adr/0049-context-compaction-failure-recovery.md b/docs/adr/0049-context-compaction-failure-recovery.md
index 65c512d57..ea426e7d9 100644
--- a/docs/adr/0049-context-compaction-failure-recovery.md
+++ b/docs/adr/0049-context-compaction-failure-recovery.md
@@ -8,7 +8,8 @@
is no background build left to discard, and the `fresh_window` family issues
no summary request, so this path cannot trigger there) / ADR 0282 (the
summary request retries transient failures and the preflight guard sizes
- the serialized prompt, with one reduced pass, before this fallback runs)
+ the serialized prompt, with one reduced pass, before this fallback runs) /
+ ADR 0301 (the fallback keeps the real recent window rather than one user
## Context
diff --git a/docs/adr/0282-compaction-summary-retry-and-sizing.md b/docs/adr/0282-compaction-summary-retry-and-sizing.md
index 4c5006897..bc8f4d369 100644
--- a/docs/adr/0282-compaction-summary-retry-and-sizing.md
+++ b/docs/adr/0282-compaction-summary-retry-and-sizing.md
@@ -5,6 +5,8 @@
- Deciders: PI-Desktop runtime maintainers
- Amends: ADR 0049 (decision 1, the preflight guard; the "retry indefinitely"
rejection stands), D203 / ADR 0064 (the summary family only)
+- Amended by: ADR 0301 (a prompt that still does not fit after the reduced pass
+ is summarized in chunks; only a range the planner cannot split falls back)
- Related: issue #543 · PR #554 (superseded) ·
[03-runtime/02-agent-runtime](../spec/03-runtime/02-agent-runtime.md) ·
[03-runtime/01-ipc-protocol](../spec/03-runtime/01-ipc-protocol.md) ·
diff --git a/docs/adr/0301-compaction-fallback-recent-window-and-chunked-summary.md b/docs/adr/0301-compaction-fallback-recent-window-and-chunked-summary.md
new file mode 100644
index 000000000..8a8e37026
--- /dev/null
+++ b/docs/adr/0301-compaction-fallback-recent-window-and-chunked-summary.md
@@ -0,0 +1,102 @@
+# ADR 0301: A failed compaction keeps the recent window, and an oversized summary is chunked
+
+- Status: Accepted for implementation
+- Date: 2026-09-22
+- Amends: ADR 0049 (the retained tail is the recent window, not one user
+ message; a prompt that does not fit is chunked rather than skipped) / ADR 0282
+ (the reduced pass is no longer the last attempt before the fallback)
+- Related: issue #827 · ADR 0064 (the `fresh_window` family, unchanged) ·
+ [03-runtime/02-agent-runtime](../spec/03-runtime/02-agent-runtime.md)
+
+## Context
+
+ADR 0049 decided that an automatic compaction failure installs a deterministic
+retained-tail checkpoint, and described that checkpoint as preserving "the
+recent provider-valid message tail". ADR 0282 then made the runtime retry a
+failed summary and reduce an oversized prompt once before the fallback ran.
+
+The shipped contract was narrower than either record promised. The Codex-shaped
+reshape of a preparation folds the split-turn prefix and pi's recent tail back
+into `messagesToSummarize`, then rebuilds the tail as at most the latest user
+message, and a rebuild of a stored checkpoint narrowed the tail again. On the
+third automatic compaction of a reported session — whose summary request failed
+with no provider usage — the checkpoint therefore kept one user sentence, and
+about 168 messages (3 user / 34 assistant / 131 tool) left the next model
+request. The model no longer knew the decisions, paths, or unfinished work of
+the turn it was continuing, while the transcript on disk and the UI row stayed
+intact: the session looked healthy and behaved as if amnesiac.
+
+Two further limits produced the same symptom. A summary prompt that still did
+not fit after the single reduced pass was skipped instead of summarized, so a
+budget failure cost the range entirely; and the checkpoint recorded
+`usage: null` with no reason, leaving the next report unable to distinguish a
+budget failure from a provider failure.
+
+## Decision
+
+A retained-tail fallback retains the real recent window: the newest contiguous
+messages of the compacted range, every role, bounded by the keep-recent target
+and by what the safe budget leaves once the carried-forward summary and the
+recovery notice are paid for. It records `details.retainedTailShape` as
+`recent_window`, and a checkpoint without that marker — every successful
+checkpoint, and every record written before the marker existed — still
+normalizes to its latest user message, so a restart cannot restore a sequence of
+executable-looking old requests. The fallback drops the assistant messages pi
+drops from the rebuilt context anyway (error, aborted, deferred) and any tool
+result whose tool call is not in the window, because a provider rejects a result
+whose call is missing. An `active_turn` fallback also keeps the active task's
+user message ahead of the window when the window itself cannot hold it, so a
+continuation never loses its goal.
+
+A budget too small for one prompt no longer skips the model. The range is split
+into contiguous chunks that each fit the request budget — at most 16 requests,
+each carrying the previous chunk's summary through pi's update-the-summary
+prompt, with the range's file list appended on the last one — so the checkpoint
+still covers every message behind its boundary, and the summary reports the
+summed usage of the requests that produced it. Only an empty range, or one past
+that request bound, still falls back on budget grounds.
+
+The fallback records `details.failureReason` from a closed vocabulary —
+`no_new_history`, `summary_budget`, `summary_provider`, `checkpoint_oversized` —
+instead of provider error text, which ADR 0049 keeps out of the persisted
+record.
+
+## Consequences
+
+- A failed summary no longer costs the active turn: the degradation is bounded
+ by the same recent-context budget a successful checkpoint respects.
+- A fallback checkpoint is larger than it was, and so is the continuation
+ request it authorizes. The window is capped by the keep-recent target and by
+ the room the carried summary leaves, so the guard still applies.
+- A summary of a very large range costs several provider requests and reports
+ their summed usage. That is the intent: the alternative was no summary.
+- Provider validity is unchanged: a retained tail never carries an orphaned tool
+ result or an unanswered tool call.
+- Manual `/compact` keeps its fail-fast contract, the `fresh_window` family
+ still carries an empty tail, and no setting, protocol field, or persisted
+ record schema changed.
+
+## Alternatives
+
+### Keep the one-user-message tail and rely on the carried summary
+
+Rejected: the failed summary is the carried one, so the range after it has no
+representation at all. That is the reported defect, not a smaller version of it.
+
+### Retain the window only for `active_turn`
+
+Rejected: a completed turn that fails loses the same delta, and the window ends
+on a finished assistant message, so it reads as history rather than as a pending
+request — which is what the older normalization guarded against.
+
+### Summarize an oversized range by concatenating partial summaries with no
+second request per chunk
+
+Rejected: each chunk needs its own request regardless, and any merge step either
+costs another request or leaves several sections that disagree. Chaining pi's
+update-the-summary prompt converges on one summary for the whole range.
+
+### Raise the hard limit or keep skipping the shot summary
+
+Rejected: the failure is the summarizer's, not the window's, and the guard is
+what keeps the next request inside the provider limit.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index fa77d818c..d2a79cc6a 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -329,6 +329,7 @@ Each ADR includes:
| 0298 | [The app ships no fonts](0298-remove-bundled-fonts.md) | Accepted (D598; amends ADR 0083 / D232) |
| 0299 | [Subagent context budget and delegate compaction](0299-subagent-context-budget.md) | Accepted for implementation (amends ADR 0064; extends ADR 0062 / ADR 0279) |
| 0300 | [Host-owned encrypted portable configuration sync](0300-host-owned-encrypted-portable-configuration-sync.md) | Accepted for implementation |
+| 0301 | [A failed compaction keeps the recent window, and an oversized summary is chunked](0301-compaction-fallback-recent-window-and-chunked-summary.md) | Accepted for implementation (issue #827; amends ADR 0049 / ADR 0282) |
| turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted |
| provider-display-order | [Provider display order](provider-display-order.md) | Accepted |
| registry-header-variable-spelling | [Remote header variables accept the registry's `{name}` spelling](registry-header-variable-spelling.md) | Proposed |
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 95dda728a..747f0b330 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -404,10 +404,11 @@ For every pi loop turn:
4. at or above the hard boundary, or when the model called `new_context`,
compaction runs synchronously before the next provider request. In the
summary family, generation is mandatory; the runtime preflights the summary
- input against the model window and skips a request that cannot fit. An
- automatic summary failure first attempts a deterministic retained-tail
- checkpoint, while manual compaction still reports
- `CONTEXT_COMPACTION_FAILED`
+ input against the model window, reduces it once, and then splits a range that
+ still does not fit into chunks that each do, so a prompt too large for one
+ request is summarized by several (ADR 0301). An automatic summary failure
+ first attempts a deterministic retained-tail checkpoint, while manual
+ compaction still reports `CONTEXT_COMPACTION_FAILED`
5. successful generation or deterministic recovery first appends the
checkpoint through host-core, then installs its summary plus the applicable
retained tail as the runtime context for the next provider request; a
@@ -421,15 +422,29 @@ without persisting anything or changing the active checkpoint; installation
re-estimates, appends through host-core, updates the active checkpoint, and
emits `compaction_end`. The blocking path composes the two back to back.
-**What survives a checkpoint.** The model context after a compaction is the
-summary plus, at most, one **user** message; assistant and tool messages are
-dropped from model context and remain in the visible transcript. pi's
+**What survives a checkpoint.** A successful checkpoint leaves the model context
+as the summary plus, at most, one **user** message; assistant and tool messages
+are dropped from model context and remain in the visible transcript. pi's
`prepareCompaction` still chooses the cut point, so its turn-boundary and
split-turn handling are preserved, but the runtime then folds the split-turn
prefix and the recent tail back into the summary input, so the summary covers
the whole compacted range and nothing crosses the boundary uncovered.
-The retention mode is selected from the lifecycle that requested compaction:
+A **retained-tail fallback** is the exception, because no summary covers its
+range: it keeps the real recent window — the newest contiguous messages of the
+compacted range, every role, bounded by the keep-recent target and by what the
+safe budget leaves once the carried-forward summary and the recovery notice are
+paid for — and records `details.retainedTailShape` as `recent_window`, so a
+rebuild replays that window instead of narrowing it back to one user message
+(ADR 0301, issue #827). It drops the assistant messages pi drops from the
+rebuilt context anyway (error, aborted, deferred) and any tool result whose tool
+call is not in the window, because a provider rejects a result whose call is
+missing. An `active_turn` fallback also keeps the active task's user message
+ahead of the window when the window itself cannot hold it, so the continuation
+never loses its goal.
+
+The retention mode is selected from the lifecycle that requested compaction. It
+decides what a *successful* checkpoint leaves behind:
- An `active_turn` checkpoint is created while the provider must continue the
current task after a tool result, a `toolUse` turn, or overflow recovery. It
@@ -441,16 +456,25 @@ The retention mode is selected from the lifecycle that requested compaction:
a new user prompt, or for manual compaction. It carries no naked historical
user messages. The summary is authoritative for completed work, and the next
user prompt is the only new task after the checkpoint.
+- A retained-tail fallback carries its recent window in both modes, because the
+ alternative is an empty context; the mode still decides whether it has to
+ keep the active task's user message as well.
- The `fresh_window` family remains the deliberate no-summary exception from
ADR 0064 and always carries an empty tail.
-The retained-tail mode is stored in the checkpoint's opaque `details` field so
-restart preserves the same task boundary. Checkpoints written before this
-field existed are normalized to their latest user message only. Dropping an
-assistant message also drops its tool calls, so no orphaned tool call can reach
-the provider. The retained tail is re-estimated with the summary before
-persistence and before continuation, so an oversized request still cannot pass
-the guard.
+The retained-tail mode and shape are stored in the checkpoint's opaque `details`
+field, so a restart preserves the same task boundary and the same treatment of
+the tail. A checkpoint without the shape marker — every successful checkpoint,
+and every record written before the marker existed — is normalized to its latest
+user message only, so a restart cannot restore a sequence of
+executable-looking old requests. Dropping an assistant message also drops its
+tool calls, and the fallback drops the results of calls it did not keep, so no
+orphaned tool call or unmatched result can reach the provider. The retained tail
+is re-estimated with the summary before persistence and before continuation, so
+an oversized request still cannot pass the guard. A fallback also records
+`details.failureReason` — `no_new_history`, `summary_budget`,
+`summary_provider`, or `checkpoint_oversized` — a closed vocabulary rather than
+provider error text, which can carry endpoint details.
**Two compaction families.** Both run the same lifecycle — budget
re-estimation, host-core append, `compaction_end`, transcript row, warning:
@@ -482,7 +506,10 @@ derived from the model window as 20% of the hard budget clamped to
8,000–64,000 tokens, then capped at half the hard budget; it decides where the
boundary falls, not what survives it. The active-user retention limit is 20,000
tokens, capped at half the hard budget so retention alone cannot fill a small
-window and leave the summary no room. None of these values are configurable.
+window and leave the summary no room. A fallback's window is capped by 25% of
+the hard budget and by the room the carried-forward summary and the recovery
+notice leave, so recovery cannot install a checkpoint the guard rejects. None of
+these values are configurable.
**Estimate calibration (D606).** Every threshold above is compared against one
number, and that number is corrected against what requests actually cost. pi's
@@ -519,10 +546,16 @@ Stop); deterministic failures such as quota or auth return at once. The
preflight guard sizes the prompt pi actually serializes — tool results already
capped — rather than the raw messages, and when that prompt still exceeds the
window it tries exactly one reduced input (tool results cut to a short prefix,
-thinking dropped, no message removed) before giving up on the summary (ADR
-0282). If normal compaction still fails during an automatic threshold or
+thinking dropped, no message removed). If even that input does not fit, the range
+is split into contiguous chunks that each do: at most 16 requests, each carrying
+the previous chunk's summary through pi's update-the-summary prompt, with the
+range's file list appended on the last one, and the checkpoint reports the summed
+usage of the requests that produced it. A budget therefore decides how many
+requests a summary takes, not whether the model is asked at all (ADR 0301); only
+an empty range, or one past that request bound, still gives up on the summary
+(ADR 0282). If normal compaction still fails during an automatic threshold or
overflow recovery, the runtime persists a short recovery checkpoint with the
-previous summary (when available) and an aggressively bounded applicable tail.
+previous summary (when available) and the bounded recent window described above.
The complete transcript remains durable and visible, while the next model
request receives only that recovery checkpoint and applicable tail. The
lifecycle event marks this as `fallback: "retained_tail"`, and the checkpoint's
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index 4cc7e2031..d80ab0b25 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -6595,3 +6595,29 @@ that was sitting at the bottom — including after the turn had finished.
by `apps/desktop/test/default-model-display.test.mjs` and
`apps/desktop/test/image-generation-default.test.mjs`, with
`provider-model-config.test.mjs` asserting the add branch consults them.
+
+## 2026-09-22 — A failed compaction keeps the recent window (D613, issue #827)
+
+- An automatic compaction whose summary request failed installed a
+ retained-tail checkpoint that carried at most the latest user message, and a
+ rebuild narrowed a stored checkpoint's tail the same way. A long turn
+ therefore reached the next model request as one user sentence: the reported
+ session lost roughly 168 messages (3 user / 34 assistant / 131 tool) between
+ two checkpoints while the transcript on disk and the UI row stayed intact.
+- The fallback now retains the real recent window — the newest contiguous
+ messages of the compacted range, every role, bounded by the keep-recent
+ target and by what the carried summary and the recovery notice leave — and
+ marks it with `details.retainedTailShape`, so a rebuild replays it. A
+ checkpoint without the marker (every successful checkpoint, and every record
+ written before it existed) still normalizes to the latest user message. An
+ `active_turn` fallback also keeps the active task's user message when the
+ window cannot hold it, the fallback drops the assistant messages pi drops
+ anyway and any tool result whose call is not in the window, and
+ `details.failureReason` records `no_new_history` / `summary_budget` /
+ `summary_provider` / `checkpoint_oversized` instead of provider error text.
+- A summary prompt that is still too large after the single reduced pass is no
+ longer skipped: the range is split into contiguous chunks that each fit, at
+ most 16 requests, each carrying the previous chunk's summary, and the
+ checkpoint reports the summed usage of the requests that produced it. Only an
+ empty range, or one past that request bound, still falls back on budget
+ grounds. See ADR 0301, `03-runtime/02-agent-runtime.md`, ADR 0049, ADR 0282.
diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
index 026d712c1..740a69fd0 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -305,7 +305,8 @@ pi 0.84.4+ 只在循环将要在同一次运行中开启另一个助手回合时
4. 处于或高于硬边界,或者当模型名为 `new_context` 时,
压缩在下一个提供程序请求之前同步运行。在
在 summary 系列中,生成摘要是强制的;运行时会拿摘要输入对照模型窗口做
- 预检,并跳过放不下的请求。自动摘要失败时先尝试一个确定性的保留尾部
+ 预检、缩减一次,再把仍放不下的范围切成若干分片分别摘要,因此超出单次请求的
+ 提示由多次请求完成(ADR 0301)。自动摘要失败时先尝试一个确定性的保留尾部
检查点,而手动压缩仍然报告
`CONTEXT_COMPACTION_FAILED`
5. 成功生成或确定性恢复首先追加
@@ -321,14 +322,24 @@ pi 0.84.4+ 只在循环将要在同一次运行中开启另一个助手回合时
重新估计,通过 host-core 附加,更新活动检查点,以及
发出 `compaction_end`。阻塞路径将两者背靠背组成。
-**在检查点中幸存下来的内容。** 压缩后的模型上下文是
+**在检查点中幸存下来的内容。** 成功检查点留下的模型上下文是
摘要以及最多一条**用户**消息;助手和工具消息是
从模型上下文中删除并保留在可见的转录本中。圆周率
`prepareCompaction` 仍然选择切点,因此其回合边界和
保留分割回合处理,但运行时会折叠分割回合
前缀和最近的尾部返回到摘要输入中,因此摘要涵盖
整个紧凑的范围内,没有任何东西跨越边界而未被覆盖。
-保留模式由请求这次压缩的生命周期决定:
+
+**保留尾部回退**是例外,因为没有摘要覆盖它负责的范围:它保留真实的近期窗口——
+压缩范围内最新的连续消息,包含所有角色,上限为 keep-recent 目标,以及在
+携带摘要与恢复提示之后安全预算剩余的空间——并把
+`details.retainedTailShape` 记录为 `recent_window`,使重建时回放整个窗口,
+而不是收窄回一条用户消息(ADR 0301,issue #827)。它会丢弃 pi 本来就会从
+重建上下文中移除的助手消息(error、aborted、deferred),以及工具调用不在窗口内的
+工具结果,因为提供商拒绝调用缺失的结果。`active_turn` 回退还会在窗口本身装不下时,
+把当前任务的用户消息放在窗口之前,因此续写不会丢失目标。
+
+保留模式由请求这次压缩的生命周期决定;它决定一次**成功**检查点留下什么:
- 当提供商必须在工具结果、`toolUse` 回合或溢出恢复后继续当前任务时,使用
`active_turn`;仅保留压缩范围内最新的用户消息,最多为下面的保留限额;
@@ -338,13 +349,19 @@ pi 0.84.4+ 只在循环将要在同一次运行中开启另一个助手回合时
- 在终止回合边界、发送新用户提示之前或手动压缩时,使用
`completed_turn`;保留尾部为空。摘要是已完成工作的权威内容,检查点后的
下一条用户提示是唯一的新任务。
+- 保留尾部回退在两种模式下都携带近期窗口,因为替代方案是空上下文;
+ 模式仍然决定它是否还要保留当前任务的用户消息。
- `fresh_window` 系列仍是 ADR 0064 规定的无摘要例外,并始终携带空尾部。
-`retainedTailMode` 存储在检查点不透明的 `details` 中,因此重启会保留同一任务
-边界。没有该字段的旧检查点会归一化为只保留最新的用户消息。放弃助理
-消息也会丢弃其工具调用,因此没有孤立的工具调用可以到达
-提供商。保留的尾部用持久化之前的摘要重新估计
-并且在继续之前,所以超大的请求仍然无法通过警卫。
+`retainedTailMode` 与尾部形状存储在检查点不透明的 `details` 中,因此重启会保留
+同一任务边界与同样的尾部处理方式。没有形状标记的检查点——包括每个成功检查点,
+以及标记出现之前写入的记录——仍会归一化为只保留最新的用户消息,因此重启无法
+恢复一串看起来可执行的旧请求。放弃助理消息也会丢弃其工具调用,回退还会丢弃
+它没有保留的调用所对应的结果,因此没有孤立的工具调用或不匹配的结果可以到达
+提供商。保留的尾部用持久化之前的摘要重新估计,并且在继续之前再次估计,
+所以超大的请求仍然无法通过警卫。回退还会记录 `details.failureReason`——
+`no_new_history`、`summary_budget`、`summary_provider` 或 `checkpoint_oversized`——
+一个封闭词表,而不是可能带有端点细节的提供商错误文本。
**两个压缩系列。** 两者运行相同的生命周期 - 预算
重新估计、host-core 追加、`compaction_end`、转录本行、警告:
@@ -375,7 +392,9 @@ Headroom 是 16,384 个代币储备底线的最大值,模型最大输出
8,000–64,000 个代币,然后上限为硬预算的一半;它决定了在哪里
边界倒塌了,而不是幸存下来的东西。活动用户消息保留限制为
20,000 个代币,上限为硬预算的一半,因此仅靠保留无法填补
-小窗口,没有留下摘要的空间。这些值都不是
+小窗口,没有留下摘要的空间。回退窗口的上限是硬预算的 25%,以及在
+携带摘要与恢复提示之后剩余的空间,因此恢复无法安装一个会被警卫拒绝的检查点。
+这些值都不是
可配置。
**估算校准(D606)。** 上述每个阈值都对着同一个数字比较,而该数字会按请求的真实开销校正。pi 的 `estimateContextTokens`
@@ -393,9 +412,14 @@ Headroom 是 16,384 个代币储备底线的最大值,模型最大输出
(3 次重试,2s/4s/8s 退避,Stop 可取消);配额、鉴权等确定性失败立即返回。
预检守卫按 pi 实际序列化的提示(工具结果已截断)估算大小,而不是按原始消息;
若该提示仍超出窗口,会恰好尝试一次缩减输入(工具结果截为短前缀、去掉思考块、
-不删除任何消息),之后才放弃摘要(ADR 0282)。如果在自动阈值或溢出期间正常压缩仍然失败
-恢复时,运行时会与之前的恢复检查点保持一个简短的恢复检查点
-摘要(如果可用)和一个适用的积极限制尾部。的
+不删除任何消息)。若连缩减后的输入也放不下,就把范围切成若干连续分片,使每片都能放下:
+最多 16 次请求,每次通过 pi 的 update-the-summary 提示携带上一片的摘要,
+该范围的文件列表只追加在最后一次请求上,检查点报告这些请求的用量总和。
+因此预算决定一次摘要需要多少次请求,而不是决定是否调用模型(ADR 0301);
+只有空范围或超过该请求上限的范围才会放弃摘要(ADR 0282)。
+如果在自动阈值或溢出恢复期间正常压缩仍然失败,
+运行时会持久化一个简短的恢复检查点,携带之前的摘要(如可用)
+以及上面描述的受限近期窗口。的
完整的转录本保持持久且可见,而下一个模型请求
仅接收恢复检查点和尾部。生命周期事件标记
这作为 `fallback: "retained_tail"`,检查点的 mark 也携带同样的 `fallback`,
diff --git a/packages/agent-runtime/src/agent-messages.ts b/packages/agent-runtime/src/agent-messages.ts
index 4cc33d226..9b2e947d4 100644
--- a/packages/agent-runtime/src/agent-messages.ts
+++ b/packages/agent-runtime/src/agent-messages.ts
@@ -5,7 +5,7 @@
* shape, so the conversions live here instead of being duplicated per loop.
*/
-import type { JsonValue } from "@earendil-works/pi-agent-core";
+import type { AgentMessage, JsonValue } from "@earendil-works/pi-agent-core";
import type { Usage } from "@earendil-works/pi-ai";
import type { MessageUsage } from "@pi-desktop/shared";
@@ -138,3 +138,56 @@ export function assistantContent(content: unknown): AssistantContent {
}
return { text, thinking, hasText, hasThinking };
}
+
+/**
+ * Bound `text` to `maxChars`, keeping both ends and naming the cut in the
+ * middle. Compaction uses this wherever a message has to fit a budget it
+ * cannot: the survived text stays readable and the marker says why it is
+ * shorter.
+ */
+export function truncateTextWithMarker(
+ text: string,
+ maxChars: number,
+ marker: string,
+): string {
+ if (text.length <= maxChars) return text;
+ if (maxChars <= marker.length) return marker.trim().slice(0, maxChars);
+ const retainedChars = maxChars - marker.length;
+ const headChars = Math.ceil(retainedChars * 0.75);
+ const tailChars = retainedChars - headChars;
+ return `${text.slice(0, headChars)}${marker}${
+ tailChars > 0 ? text.slice(-tailChars) : ""
+ }`;
+}
+
+/**
+ * Bound every text block of one message so the message's total text is at most
+ * `maxChars`. Blocks without text (tool calls, images) are kept, so a truncated
+ * message is still a provider-valid message with its tool calls intact.
+ */
+export function truncateMessageText(
+ message: AgentMessage,
+ maxChars: number,
+ marker: string,
+): AgentMessage {
+ const content: unknown = (message as { content?: unknown }).content;
+ if (typeof content === "string") {
+ const text = truncateTextWithMarker(content, maxChars, marker);
+ return text === content ? message : ({ ...message, content: text } as AgentMessage);
+ }
+ if (!Array.isArray(content)) return message;
+ let remaining = maxChars;
+ let changed = false;
+ const blocks = content.map((block) => {
+ if (!isRecord(block) || typeof block.text !== "string") return block;
+ if (block.text.length <= remaining) {
+ remaining -= block.text.length;
+ return block;
+ }
+ changed = true;
+ const text = truncateTextWithMarker(block.text, Math.max(1, remaining), marker);
+ remaining = 0;
+ return { ...block, text };
+ });
+ return changed ? ({ ...message, content: blocks } as AgentMessage) : message;
+}
diff --git a/packages/agent-runtime/src/compaction-summary-input.test.ts b/packages/agent-runtime/src/compaction-summary-input.test.ts
index 4556b4d8c..2adf69d45 100644
--- a/packages/agent-runtime/src/compaction-summary-input.test.ts
+++ b/packages/agent-runtime/src/compaction-summary-input.test.ts
@@ -1,12 +1,21 @@
import { describe, expect, it } from "vitest";
-import type { AgentMessage } from "@earendil-works/pi-agent-core";
import {
+ estimateTokens,
+ type AgentMessage,
+} from "@earendil-works/pi-agent-core";
+import {
+ addSummaryUsage,
+ compactionSummaryInputLimit,
COMPACTION_REDUCED_TOOL_RESULT_CHARS,
+ COMPACTION_SUMMARY_MAX_CHUNKS,
COMPACTION_SUMMARY_MAX_RETRIES,
+ COMPACTION_SUMMARY_PROMPT_SAFETY_TOKENS,
COMPACTION_SUMMARY_RETRY_BASE_MS,
COMPACTION_SUMMARY_RETRY_POLICY,
estimateSummaryPromptTokens,
+ planSummaryChunks,
reduceSummaryInput,
+ SUMMARY_CHUNK_TRUNCATION_MARKER,
type CompactionSummaryInput,
} from "./compaction-summary-input.js";
@@ -174,3 +183,137 @@ describe("reduceSummaryInput", () => {
).toBeLessThan(1_000);
});
});
+
+describe("compactionSummaryInputLimit", () => {
+ it("leaves the summary its own output allowance and the prompt template", () => {
+ const limit = compactionSummaryInputLimit({
+ hardLimit: 100_000,
+ requestHeadroom: 20_000,
+ modelMaxTokens: 8_000,
+ });
+
+ expect(limit).toBe(
+ 120_000 - 8_000 - COMPACTION_SUMMARY_PROMPT_SAFETY_TOKENS,
+ );
+ });
+
+ it("caps the output allowance at the model's own output budget", () => {
+ const limit = compactionSummaryInputLimit({
+ hardLimit: 1_000_000,
+ requestHeadroom: 200_000,
+ modelMaxTokens: 8_192,
+ });
+
+ expect(limit).toBe(1_200_000 - 8_192 - COMPACTION_SUMMARY_PROMPT_SAFETY_TOKENS);
+ });
+});
+
+describe("planSummaryChunks", () => {
+ const options = { summaryInputLimit: 10_000, reserveTokens: 1_000 };
+
+ it("splits a range into contiguous chunks that each fit the request budget", () => {
+ const messages = Array.from({ length: 40 }, (_, index) =>
+ toolResult("t".repeat(2_000), `tool-${index}`),
+ );
+
+ const chunks = planSummaryChunks(input(messages), options);
+
+ expect(chunks).toBeDefined();
+ expect(chunks!.length).toBeGreaterThan(1);
+ // Contiguous and complete: concatenating the chunks reproduces the range in
+ // order, so every message the checkpoint files behind its boundary is
+ // summarized by exactly one request.
+ expect(chunks!.flat()).toEqual(messages);
+ for (const chunk of chunks!) {
+ expect(
+ estimateSummaryPromptTokens(input(chunk, { previousSummary: "s".repeat(4_000) })),
+ ).toBeLessThanOrEqual(options.summaryInputLimit);
+ }
+ });
+
+ it("keeps a range that already fits as one chunk", () => {
+ const messages = [user("read the log"), toolResult("short output")];
+
+ expect(planSummaryChunks(input(messages), options)).toEqual([messages]);
+ });
+
+ it("truncates a single message that is larger than a chunk instead of dropping it", () => {
+ const messages = [user("u".repeat(200_000))];
+
+ const chunks = planSummaryChunks(input(messages), options);
+
+ expect(chunks).toHaveLength(1);
+ expect(chunks![0]).toHaveLength(1);
+ const text = (chunks![0]![0] as { content: Array<{ text: string }> }).content[0].text;
+ expect(text).toContain(SUMMARY_CHUNK_TRUNCATION_MARKER.trim());
+ expect(text.length).toBeLessThan(200_000);
+ expect(chunks![0]![0]!.role).toBe("user");
+ });
+
+ it("plans nothing for an empty range", () => {
+ expect(planSummaryChunks(input([]), options)).toBeUndefined();
+ });
+
+ it("refuses a range that would need more requests than the bound allows", () => {
+ const tiny = { summaryInputLimit: 100, reserveTokens: 0 };
+ const messages = Array.from({ length: COMPACTION_SUMMARY_MAX_CHUNKS + 4 }, (_, index) =>
+ user(`request ${index} ${"x".repeat(200)}`),
+ );
+
+ expect(planSummaryChunks(input(messages), tiny)).toBeUndefined();
+ });
+
+ it("splits a range with known-token messages by the same budget the guard uses", () => {
+ const messages = Array.from({ length: 12 }, (_, index) =>
+ user(`note ${index} ${"y".repeat(1_000)}`),
+ );
+ const perMessage = Math.ceil(estimateTokens(messages[0]!));
+
+ // Four messages' worth of budget, less the planner's margin: three fit.
+ const chunks = planSummaryChunks(input(messages), {
+ summaryInputLimit: perMessage * 4,
+ reserveTokens: 0,
+ });
+
+ expect(chunks!.map((chunk) => chunk.length)).toEqual([3, 3, 3, 3]);
+ });
+});
+
+describe("addSummaryUsage", () => {
+ const usage = (input: number, output: number) => ({
+ input,
+ output,
+ cacheRead: 1,
+ cacheWrite: 2,
+ totalTokens: input + output,
+ cost: { input: 0.1, output: 0.2, cacheRead: 0.3, cacheWrite: 0.4, total: 1 },
+ });
+
+ it("adds the requests one chunked summary took", () => {
+ const total = addSummaryUsage(usage(10, 5), usage(20, 7));
+
+ expect(total).toEqual({
+ input: 30,
+ output: 12,
+ cacheRead: 2,
+ cacheWrite: 4,
+ totalTokens: 42,
+ cost: { input: 0.2, output: 0.4, cacheRead: 0.6, cacheWrite: 0.8, total: 2 },
+ });
+ });
+
+ it("keeps an optional field only when a request reported it", () => {
+ const withReasoning = { ...usage(1, 1), reasoning: 4 };
+
+ expect(addSummaryUsage(undefined, usage(1, 1))).not.toHaveProperty("reasoning");
+ expect(addSummaryUsage(withReasoning, usage(1, 1))).toMatchObject({
+ reasoning: 4,
+ });
+ });
+
+ it("returns whichever side exists", () => {
+ expect(addSummaryUsage(undefined, usage(1, 1))).toEqual(usage(1, 1));
+ expect(addSummaryUsage(usage(1, 1), undefined)).toEqual(usage(1, 1));
+ expect(addSummaryUsage(undefined, undefined)).toBeUndefined();
+ });
+});
diff --git a/packages/agent-runtime/src/compaction-summary-input.ts b/packages/agent-runtime/src/compaction-summary-input.ts
index 924a08018..012701b87 100644
--- a/packages/agent-runtime/src/compaction-summary-input.ts
+++ b/packages/agent-runtime/src/compaction-summary-input.ts
@@ -1,10 +1,13 @@
import {
convertToLlm,
+ estimateTokens,
serializeConversation,
type AgentMessage,
type CompactionPreparation,
} from "@earendil-works/pi-agent-core";
-import type { RetryPolicy } from "@earendil-works/pi-ai";
+import type { RetryPolicy, Usage } from "@earendil-works/pi-ai";
+import { truncateMessageText } from "./agent-messages.js";
+import { DEFAULT_MAX_TOKENS } from "./provider-binding.js";
/**
* Sizing and retry policy for the automatic summary request (ADR 0282).
@@ -15,7 +18,10 @@ import type { RetryPolicy } from "@earendil-works/pi-ai";
* so a session whose bulk was tool output looked several times larger than the
* prompt it would actually send and was routed to retained-tail recovery
* without ever asking the model (issue #543). These helpers size the prompt the
- * way pi builds it, and shrink the input one bounded step before giving up.
+ * way pi builds it and shrink the input one bounded step — and when even that
+ * still does not fit, they split the range into chunks that each do, so the
+ * budget decides how many requests a summary takes rather than whether the
+ * model is asked at all (issue #827).
*/
/**
@@ -42,6 +48,28 @@ export const COMPACTION_SUMMARY_RETRY_POLICY: RetryPolicy = {
export const COMPACTION_REDUCED_TOOL_RESULT_CHARS = 500;
const REDUCED_TOOL_RESULT_SUFFIX = "\n\n[... tool output truncated for the summary request]";
+/**
+ * Tokens held back from the window for the summary prompt template itself, on
+ * top of the model's own output allowance. The preflight guard and the chunk
+ * planner both subtract it, so their budgets cannot disagree.
+ */
+export const COMPACTION_SUMMARY_PROMPT_SAFETY_TOKENS = 2_048;
+/**
+ * Upper bound on the summary requests one checkpoint may issue. A range needing
+ * more than this is not a compaction any more; it falls back.
+ */
+export const COMPACTION_SUMMARY_MAX_CHUNKS = 16;
+/**
+ * Share of a chunk's budget the planner fills. A chunk is sized from
+ * `estimateTokens`, while the request carries pi's serialized form — per-message
+ * role labels and separators the raw estimate does not count — so the margin
+ * keeps every planned request inside the window it was planned for.
+ */
+export const COMPACTION_SUMMARY_CHUNK_MARGIN = 0.9;
+/** Appended when a single message alone exceeds one chunk's budget. */
+export const SUMMARY_CHUNK_TRUNCATION_MARKER =
+ "\n\n[message truncated: the summary request budget could not carry it whole]";
+
export type CompactionSummaryInput = Pick<
CompactionPreparation,
@@ -114,3 +142,126 @@ function boundToolResultText(text: string): string {
if (text.length <= COMPACTION_REDUCED_TOOL_RESULT_CHARS) return text;
return text.slice(0, COMPACTION_REDUCED_TOOL_RESULT_CHARS) + REDUCED_TOOL_RESULT_SUFFIX;
}
+
+/**
+ * Output allowance one summary request gets: the smaller of 80% of the request
+ * headroom and the model's own output budget. pi makes the same computation
+ * when it caps the summary request, so the chunk planner and the guard agree.
+ */
+export function compactionSummaryOutputBudget(input: {
+ requestHeadroom: number;
+ modelMaxTokens?: number;
+}): number {
+ return Math.min(
+ Math.floor(input.requestHeadroom * 0.8),
+ Math.max(1, Math.round(input.modelMaxTokens || DEFAULT_MAX_TOKENS)),
+ );
+}
+
+/**
+ * Tokens the summary prompt may carry inside this window. A prompt at or above
+ * it cannot be sent with room for the summary itself, so the guard rejects it —
+ * and the chunk planner splits the range so every chunk stays below it.
+ */
+export function compactionSummaryInputLimit(input: {
+ hardLimit: number;
+ requestHeadroom: number;
+ modelMaxTokens?: number;
+}): number {
+ return Math.max(
+ 1,
+ input.hardLimit +
+ input.requestHeadroom -
+ compactionSummaryOutputBudget(input) -
+ COMPACTION_SUMMARY_PROMPT_SAFETY_TOKENS,
+ );
+}
+
+/**
+ * Split a summary input into contiguous chunks that each fit the request
+ * budget, so a range too large for one prompt is still summarized instead of
+ * skipped (issue #827).
+ *
+ * Every chunk is summarized by its own request and each request carries the
+ * summary of the chunk before it — pi's update-the-summary prompt — so the chain
+ * ends on one summary covering the whole range. `reserveTokens` is the room the
+ * running summary and the previous summary may take in a chunk's prompt.
+ *
+ * Returns undefined when the range cannot be split: it is empty, or it would
+ * need more than {@link COMPACTION_SUMMARY_MAX_CHUNKS} requests. A single
+ * message larger than the budget is truncated rather than dropped, so no message
+ * ever leaves the summary's scope.
+ */
+export function planSummaryChunks(
+ input: CompactionSummaryInput,
+ options: { summaryInputLimit: number; reserveTokens: number },
+): AgentMessage[][] | undefined {
+ const range = [
+ ...input.messagesToSummarize,
+ ...(input.isSplitTurn ? input.turnPrefixMessages : []),
+ ];
+ if (range.length === 0) return undefined;
+ const budget = Math.max(
+ 1,
+ Math.floor(
+ (options.summaryInputLimit - Math.max(0, options.reserveTokens)) *
+ COMPACTION_SUMMARY_CHUNK_MARGIN,
+ ),
+ );
+ const chunks: AgentMessage[][] = [];
+ let current: AgentMessage[] = [];
+ let tokens = 0;
+ for (const message of range) {
+ const cost = Math.max(1, Math.ceil(estimateTokens(message)));
+ if (current.length > 0 && tokens + cost > budget) {
+ chunks.push(current);
+ if (chunks.length >= COMPACTION_SUMMARY_MAX_CHUNKS) return undefined;
+ current = [];
+ tokens = 0;
+ }
+ current.push(
+ cost > budget
+ ? truncateMessageText(message, budget * 4, SUMMARY_CHUNK_TRUNCATION_MARKER)
+ : message,
+ );
+ tokens += Math.min(cost, budget);
+ }
+ if (current.length > 0) chunks.push(current);
+ return chunks.length > 0 ? chunks : undefined;
+}
+
+/**
+ * Sum the provider usage of the requests that produced one summary. pi reports
+ * one usage object per request and a chunked summary spends several, so the
+ * checkpoint — and the cost the context inspector shows — carries the total of
+ * the requests the summary actually took.
+ */
+export function addSummaryUsage(
+ total: Usage | undefined,
+ next: Usage | undefined,
+): Usage | undefined {
+ if (!next) return total;
+ if (!total) return next;
+ const cacheWrite1h = total.cacheWrite1h ?? next.cacheWrite1h;
+ const reasoning = total.reasoning ?? next.reasoning;
+ return {
+ input: total.input + next.input,
+ output: total.output + next.output,
+ cacheRead: total.cacheRead + next.cacheRead,
+ cacheWrite: total.cacheWrite + next.cacheWrite,
+ ...(cacheWrite1h === undefined
+ ? {}
+ : { cacheWrite1h: (total.cacheWrite1h ?? 0) + (next.cacheWrite1h ?? 0) }),
+ ...(reasoning === undefined
+ ? {}
+ : { reasoning: (total.reasoning ?? 0) + (next.reasoning ?? 0) }),
+ totalTokens: total.totalTokens + next.totalTokens,
+ cost: {
+ input: (total.cost?.input ?? 0) + (next.cost?.input ?? 0),
+ output: (total.cost?.output ?? 0) + (next.cost?.output ?? 0),
+ cacheRead: (total.cost?.cacheRead ?? 0) + (next.cost?.cacheRead ?? 0),
+ cacheWrite: (total.cost?.cacheWrite ?? 0) + (next.cost?.cacheWrite ?? 0),
+ total: (total.cost?.total ?? 0) + (next.cost?.total ?? 0),
+ },
+ };
+}
diff --git a/packages/agent-runtime/src/compaction-tail.test.ts b/packages/agent-runtime/src/compaction-tail.test.ts
new file mode 100644
index 000000000..f93653a37
--- /dev/null
+++ b/packages/agent-runtime/src/compaction-tail.test.ts
@@ -0,0 +1,289 @@
+import { describe, expect, it } from "vitest";
+import {
+ estimateTokens,
+ type AgentMessage,
+} from "@earendil-works/pi-agent-core";
+import {
+ CHECKPOINT_TRUNCATION_MARKER,
+ COMPACTION_RETAINED_TAIL_SHAPE,
+ isRetainedTailMessage,
+ replayRetainedTail,
+ selectRecentTail,
+ stripDanglingToolCalls,
+ truncateMessageToTail,
+} from "./compaction-tail.js";
+
+const usage = {
+ input: 1,
+ output: 1,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 2,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+};
+
+/** Tokens pi charges one message, so a budget assertion never guesses. */
+const tokensOf = (message: AgentMessage) => Math.ceil(estimateTokens(message));
+
+function user(body: string, timestamp = 1): AgentMessage {
+ return { role: "user", content: [{ type: "text", text: body }], timestamp };
+}
+
+function assistant(
+ body: string,
+ options: { timestamp?: number; stopReason?: string } = {},
+): AgentMessage {
+ return {
+ role: "assistant",
+ content: [{ type: "text", text: body }],
+ api: "openai-completions",
+ provider: "local",
+ model: "local-model",
+ usage,
+ stopReason: options.stopReason ?? "stop",
+ timestamp: options.timestamp ?? 2,
+ } as AgentMessage;
+}
+
+function toolCallAssistant(
+ id: string,
+ body = "reading",
+ options: { timestamp?: number; stopReason?: string } = {},
+): AgentMessage {
+ return {
+ role: "assistant",
+ content: [
+ { type: "text", text: body },
+ { type: "toolCall", id, name: "Read", arguments: { path: "a.ts" } },
+ ],
+ api: "openai-completions",
+ provider: "local",
+ model: "local-model",
+ usage,
+ stopReason: options.stopReason ?? "toolUse",
+ timestamp: options.timestamp ?? 3,
+ } as AgentMessage;
+}
+
+function toolResult(id: string, body: string, timestamp = 4): AgentMessage {
+ return {
+ role: "toolResult",
+ toolCallId: id,
+ toolName: "Read",
+ content: [{ type: "text", text: body }],
+ isError: false,
+ timestamp,
+ };
+}
+
+const body = (chars: number) => "x".repeat(chars);
+
+describe("selectRecentTail", () => {
+ it("keeps the newest messages that fit the tail budget", () => {
+ const messages = [
+ user(body(400), 1),
+ assistant(body(400), { timestamp: 2 }),
+ user(body(400), 3),
+ assistant(body(400), { timestamp: 4 }),
+ user(body(400), 5),
+ assistant(body(400), { timestamp: 6 }),
+ ];
+ const budget = tokensOf(messages[3]!) + tokensOf(messages[4]!) + tokensOf(messages[5]!);
+
+ const tail = selectRecentTail(messages, budget);
+
+ expect(tail).toEqual(messages.slice(3));
+ expect(tail.map((message) => message.role)).toEqual([
+ "assistant",
+ "user",
+ "assistant",
+ ]);
+ });
+
+ it("keeps the newest message even when it alone exceeds the budget", () => {
+ const messages = [
+ user(body(400), 1),
+ assistant(body(20_000), { timestamp: 2 }),
+ ];
+
+ const tail = selectRecentTail(messages, 50);
+
+ expect(tail).toHaveLength(1);
+ expect(tail[0]!.role).toBe("assistant");
+ const text = (tail[0] as { content: Array<{ text: string }> }).content[0]!.text;
+ expect(text).toContain(CHECKPOINT_TRUNCATION_MARKER.trim());
+ expect(text.length).toBeLessThan(20_000);
+ });
+
+ it("keeps the active turn's goal when the window cannot hold it", () => {
+ const messages = [
+ user("continue the long migration", 1),
+ assistant(body(20_000), { timestamp: 2 }),
+ ];
+
+ const tail = selectRecentTail(messages, 50, { latestUserGoal: true });
+
+ expect(tail.map((message) => message.role)).toEqual(["user", "assistant"]);
+ expect((tail[0] as { content: unknown }).content).toEqual([
+ { type: "text", text: "continue the long migration" },
+ ]);
+ });
+
+ it("never retains a tool result whose tool call is outside the window", () => {
+ // The budget carries the newest result only, so its call is not retained
+ // either: a provider rejects a result whose call is missing.
+ const messages = [
+ toolCallAssistant("call-1", body(20_000), { timestamp: 2 }),
+ toolResult("call-1", "ok"),
+ ];
+
+ const tail = selectRecentTail(messages, tokensOf(messages[1]!) + 1);
+
+ expect(tail.some((message) => message.role === "toolResult")).toBe(false);
+ expect(tail).toHaveLength(1);
+ expect(tail[0]!.role).toBe("assistant");
+ });
+
+ it("drops an errored assistant message and the results it produced", () => {
+ // pi removes an errored assistant message from the rebuilt context, taking
+ // its tool calls with it, so its results must not be retained.
+ const messages = [
+ toolCallAssistant("call-1", "half a turn", { timestamp: 2, stopReason: "error" }),
+ toolResult("call-1", "partial output"),
+ user("a later request", 4),
+ ];
+
+ const tail = selectRecentTail(messages, 10_000);
+
+ expect(tail.map((message) => message.role)).toEqual(["user"]);
+ });
+
+ it("keeps its own newest message when pruning would empty the tail", () => {
+ const messages = [
+ toolCallAssistant("call-1", body(20_000), { timestamp: 2 }),
+ toolResult("call-1", "ok"),
+ ];
+
+ const tail = selectRecentTail(messages, 400);
+
+ expect(tail).toHaveLength(1);
+ expect(tail[0]!.role).toBe("assistant");
+ expect((tail[0] as { content: unknown[] }).content).toEqual([
+ {
+ type: "text",
+ text: expect.stringContaining(CHECKPOINT_TRUNCATION_MARKER.trim()),
+ },
+ ]);
+ });
+
+ it("returns an empty tail when only tool results remain", () => {
+ // Neither a bare result nor a bare tool call is a message a provider
+ // accepts, so there is nothing this path can keep.
+ const messages = [toolResult("call-1", "ok"), toolResult("call-2", "ok", 5)];
+
+ expect(selectRecentTail(messages, 20)).toEqual([]);
+ });
+});
+
+describe("truncateMessageToTail", () => {
+ it("bounds every text block and keeps the tool call identity", () => {
+ const message = toolCallAssistant("call-1", body(4_000));
+
+ const truncated = truncateMessageToTail(message, 100) as unknown as {
+ content: Array<{ type: string; text?: string; id?: string }>;
+ };
+
+ expect(truncated.content).toHaveLength(2);
+ expect(truncated.content[0]!.text!.length).toBeLessThan(4_000);
+ expect(truncated.content[1]).toMatchObject({ type: "toolCall", id: "call-1" });
+ });
+});
+
+describe("stripDanglingToolCalls", () => {
+ it("keeps the text and drops the calls of an assistant message", () => {
+ const stripped = stripDanglingToolCalls(toolCallAssistant("call-1")) as unknown as {
+ content: unknown[];
+ };
+
+ expect(stripped.content).toEqual([{ type: "text", text: "reading" }]);
+ });
+
+ it("leaves a message with no tool call untouched", () => {
+ const message = assistant("done");
+
+ expect(stripDanglingToolCalls(message)).toBe(message);
+ });
+});
+
+describe("replayRetainedTail", () => {
+ it("replays a persisted window in order", () => {
+ const window = [
+ user("continue", 1),
+ toolCallAssistant("call-1", "reading", { timestamp: 2 }),
+ toolResult("call-1", "file contents"),
+ ];
+
+ expect(replayRetainedTail(JSON.parse(JSON.stringify(window)))).toEqual(window);
+ });
+
+ it("rejects entries that are not model messages", () => {
+ const value = [
+ { role: "user", content: [{ type: "text", text: "kept" }], timestamp: 1 },
+ { role: "system", content: "not part of a tail" },
+ { role: "toolResult", content: [{ type: "text", text: "no call id" }] },
+ "not a message",
+ null,
+ ];
+
+ expect(replayRetainedTail(value)).toEqual([
+ { role: "user", content: [{ type: "text", text: "kept" }], timestamp: 1 },
+ ]);
+ });
+
+ it("drops a result whose call is missing from the recorded window", () => {
+ const value = [
+ toolResult("call-9", "orphan"),
+ user("continue", 2),
+ ];
+
+ expect(replayRetainedTail(value)).toEqual([user("continue", 2)]);
+ });
+
+ it("restores a missing timestamp so pi can file the message", () => {
+ const replayed = replayRetainedTail([
+ { role: "user", content: [{ type: "text", text: "kept" }] },
+ ]);
+
+ expect(replayed).toEqual([
+ { role: "user", content: [{ type: "text", text: "kept" }], timestamp: 0 },
+ ]);
+ });
+
+ it("returns undefined when the stored value is not a tail", () => {
+ expect(replayRetainedTail(undefined)).toBeUndefined();
+ expect(replayRetainedTail("two user lines")).toBeUndefined();
+ });
+});
+
+describe("isRetainedTailMessage", () => {
+ it("accepts the roles a tail carries", () => {
+ expect(isRetainedTailMessage(user("a"))).toBe(true);
+ expect(isRetainedTailMessage(assistant("a"))).toBe(true);
+ expect(isRetainedTailMessage(toolResult("call-1", "a"))).toBe(true);
+ });
+
+ it("rejects anything the provider would not accept as context", () => {
+ expect(isRetainedTailMessage({ role: "custom", content: "x" })).toBe(false);
+ expect(isRetainedTailMessage({ role: "user" })).toBe(false);
+ expect(isRetainedTailMessage({ role: "user", content: 42 })).toBe(false);
+ expect(isRetainedTailMessage(null)).toBe(false);
+ });
+});
+
+describe("the tail shape marker", () => {
+ it("names the window a rebuild replays in full", () => {
+ // `retainedTailForContext` narrows a tail to one user message unless the
+ // checkpoint recorded this exact value, so it is a persisted contract.
+ expect(COMPACTION_RETAINED_TAIL_SHAPE).toBe("recent_window");
+ });
+});
diff --git a/packages/agent-runtime/src/compaction-tail.ts b/packages/agent-runtime/src/compaction-tail.ts
new file mode 100644
index 000000000..ad6fdf26e
--- /dev/null
+++ b/packages/agent-runtime/src/compaction-tail.ts
@@ -0,0 +1,252 @@
+/**
+ * The retained tail a *failed* compaction installs, and the shape marker that
+ * tells a later rebuild to replay it verbatim.
+ *
+ * A successful checkpoint summarizes the whole range behind its boundary and
+ * retains at most the latest user message (`codexShapedPreparation`). A
+ * retained-tail fallback has no fresh summary at all, so its tail is the only
+ * thing carrying the range forward — and a single user sentence left the model
+ * with none of the decisions, paths, or unfinished work of the turn it was
+ * continuing (issue #827, which is ADR 0049's "recent provider-valid message
+ * tail" read literally).
+ *
+ * The fallback therefore retains the real recent window: the newest contiguous
+ * run of messages in the compacted range, every role, under a token budget, and
+ * marks the checkpoint with {@link COMPACTION_RETAINED_TAIL_SHAPE} so a restored
+ * checkpoint replays that window instead of narrowing it back to one user
+ * message (see `retainedTailForContext`). Records written before the marker
+ * existed keep the old one-user-message normalization.
+ *
+ * Deliberately dependency-light, like `context-budget.ts`: token estimation is
+ * pi-agent-core's, the record guard and the text bounding are the shared
+ * helpers, and nothing here imports `runtime.ts`, so this module can never form
+ * a cycle with it.
+ */
+
+import {
+ estimateTokens,
+ type AgentMessage,
+} from "@earendil-works/pi-agent-core";
+import { isRecord, truncateMessageText } from "./agent-messages.js";
+
+/**
+ * `details` marker for a tail holding the real recent window rather than the
+ * one-user-message list older checkpoints stored.
+ */
+export const COMPACTION_RETAINED_TAIL_SHAPE = "recent_window";
+
+/** Appended when one message alone exceeds the tail budget. */
+export const CHECKPOINT_TRUNCATION_MARKER =
+ "\n\n[checkpoint truncated: this message crossed the retained context budget]\n\n";
+
+/**
+ * Roles a retained tail may carry. Anything else in the range is skipped: a
+ * tail is replayed straight into the model context, so only messages the
+ * runtime produced belong in it.
+ */
+const RETAINED_TAIL_ROLES = new Set(["user", "assistant", "toolResult"]);
+
+/** Assistant stop reasons pi drops from the rebuilt model context. */
+const DROPPED_STOP_REASONS = new Set(["error", "aborted", "deferred"]);
+
+function messageTokens(message: AgentMessage): number {
+ return Math.max(1, Math.ceil(estimateTokens(message)));
+}
+
+/**
+ * Bound one message to a token budget by truncating its text blocks. Tool calls
+ * and tool results keep their identity, so a truncated message is still a
+ * provider-valid message.
+ */
+export function truncateMessageToTail(
+ message: AgentMessage,
+ maxTokens: number,
+): AgentMessage {
+ return truncateMessageText(
+ message,
+ Math.max(64, Math.floor(Math.max(1, maxTokens)) * 4),
+ CHECKPOINT_TRUNCATION_MARKER,
+ );
+}
+
+/** Content blocks of a message, whatever shape its role uses. */
+function contentBlocks(message: AgentMessage): unknown[] {
+ const content: unknown = (message as { content?: unknown }).content;
+ return Array.isArray(content) ? content : [];
+}
+
+/** Tool-call ids produced by the assistant messages of `messages`. */
+function assistantToolCallIds(messages: AgentMessage[]): Set<string> {
+ const ids = new Set<string>();
+ for (const message of messages) {
+ if (message.role !== "assistant") continue;
+ for (const block of contentBlocks(message)) {
+ if (!isRecord(block)) continue;
+ const { type, id } = block;
+ if (type === "toolCall" && typeof id === "string") ids.add(id);
+ }
+ }
+ return ids;
+}
+
+/**
+ * Drop tool results whose tool call is not in `messages`. pi removes errored,
+ * aborted, and deferred assistant messages from the rebuilt context, taking
+ * their tool calls with them, and a provider rejects a result whose call is
+ * missing — so the tail cannot keep a result the window no longer explains.
+ */
+function pruneOrphanToolResults(messages: AgentMessage[]): AgentMessage[] {
+ const owned = assistantToolCallIds(messages);
+ return messages.filter(
+ (message) =>
+ message.role !== "toolResult" ||
+ (typeof message.toolCallId === "string" && owned.has(message.toolCallId)),
+ );
+}
+
+/** pi keeps an assistant message only when its stop reason is replayable. */
+function isReplayableAssistant(message: AgentMessage): boolean {
+ if (message.role !== "assistant") return true;
+ return !DROPPED_STOP_REASONS.has(
+ (message as { stopReason?: string }).stopReason ?? "",
+ );
+}
+
+/** Whether a persisted value is a message a tail can replay. */
+export function isRetainedTailMessage(value: unknown): value is AgentMessage {
+ if (!isRecord(value)) return false;
+ if (typeof value.role !== "string" || !RETAINED_TAIL_ROLES.has(value.role)) {
+ return false;
+ }
+ if (typeof value.content !== "string" && !Array.isArray(value.content)) {
+ return false;
+ }
+ if (value.role === "toolResult") return typeof value.toolCallId === "string";
+ return true;
+}
+
+/**
+ * Replay a persisted tail. Structural validation is not cosmetic: a record is
+ * opaque JSON by the time it comes back from the host, and a malformed entry
+ * would reach the provider as a context message.
+ */
+export function replayRetainedTail(value: unknown): AgentMessage[] | undefined {
+ if (!Array.isArray(value)) return undefined;
+ const messages = value.filter(isRetainedTailMessage).map((message) => {
+ const timestamp = (message as { timestamp?: unknown }).timestamp;
+ return typeof timestamp === "number" && Number.isFinite(timestamp)
+ ? message
+ : ({ ...message, timestamp: 0 } as AgentMessage);
+ });
+ return pruneOrphanToolResults(messages.filter(isReplayableAssistant));
+}
+
+function findLatestUserIndex(messages: AgentMessage[]): number {
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const message = messages[index];
+ if (message?.role === "user" && isRetainedTailMessage(message)) return index;
+ }
+ return -1;
+}
+
+/**
+ * Strip the tool calls of an assistant message. Only the last-resort single
+ * message needs this: an assistant whose results are not retained cannot keep
+ * the calls they answer, or the provider rejects the context.
+ */
+export function stripDanglingToolCalls(message: AgentMessage): AgentMessage {
+ const blocks = contentBlocks(message);
+ if (
+ message.role !== "assistant" ||
+ blocks.length === 0 ||
+ !blocks.some((block) => isRecord(block) && block.type === "toolCall")
+ ) {
+ return message;
+ }
+ const content = blocks.filter(
+ (block) => !(isRecord(block) && block.type === "toolCall"),
+ );
+ return { ...message, content } as AgentMessage;
+}
+/**
+ * The message a last-resort tail carries. A provider accepts neither a tool
+ * result nor an unanswered tool call on its own, so this is a user message or
+ * assistant text; `latestUserGoal` decides which one comes first.
+ */
+function soleReplayableMessage(
+ messages: AgentMessage[],
+ options: { latestUserGoal?: boolean },
+): AgentMessage | undefined {
+ const roles: AgentMessage["role"][] = options.latestUserGoal
+ ? ["user", "assistant"]
+ : ["assistant", "user"];
+ for (const role of roles) {
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const message = messages[index]!;
+ if (message.role !== role || !isReplayableAssistant(message)) continue;
+ return role === "assistant" ? stripDanglingToolCalls(message) : message;
+ }
+ }
+ return undefined;
+}
+
+/**
+ * The newest contiguous run of `messages` that fits `maxTokens`.
+ *
+ * Always retains the newest replayable message — truncating it when one message
+ * alone exceeds the budget — so a fallback can never install an empty tail.
+ * With `latestUserGoal` (an `active_turn` fallback) the active task's user
+ * message is kept as well, ahead of the window, because the point of the tail is
+ * that the provider can continue the turn it was in the middle of.
+ */
+export function selectRecentTail(
+ messages: AgentMessage[],
+ maxTokens: number,
+ options: { latestUserGoal?: boolean } = {},
+): AgentMessage[] {
+ const budget = Math.max(1, Math.floor(maxTokens));
+ let start = messages.length;
+ let tokens = 0;
+ while (start > 0) {
+ const candidate = messages[start - 1]!;
+ if (!isRetainedTailMessage(candidate) || !isReplayableAssistant(candidate)) {
+ start -= 1;
+ continue;
+ }
+ const cost = messageTokens(candidate);
+ // The newest message is always kept; every older one has to fit.
+ if (tokens + cost > budget && start < messages.length) break;
+ tokens += cost;
+ start -= 1;
+ }
+
+ let window = messages
+ .slice(start)
+ .filter(isRetainedTailMessage)
+ .filter(isReplayableAssistant);
+ if (options.latestUserGoal && !window.some((message) => message.role === "user")) {
+ const latestUserIndex = findLatestUserIndex(messages);
+ if (latestUserIndex >= 0) {
+ window = [
+ truncateMessageToTail(
+ messages[latestUserIndex]!,
+ Math.floor(budget / 2),
+ ),
+ ...window,
+ ];
+ }
+ }
+ const tail = pruneOrphanToolResults(
+ window.map((message) =>
+ messageTokens(message) > budget
+ ? truncateMessageToTail(message, budget)
+ : message,
+ ),
+ );
+ if (tail.length > 0) return tail;
+ // A truncated window can prune down to nothing when its only message was a
+ // tool result whose call fell outside the budget. The checkpoint still has to
+ // restore something the provider accepts, so keep one message of its own.
+ const solo = soleReplayableMessage(messages, options);
+ return solo ? [truncateMessageToTail(solo, budget)] : [];
+}
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index c7ff7917a..2658c7a32 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -8881,3 +8881,314 @@ describe("context estimate calibration", () => {
});
});
});
+
+describe("compaction fallback retention (#827)", () => {
+ function messageEntry(
+ id: string,
+ parentId: string | null,
+ message: unknown,
+ seq: number,
+ ) {
+ return {
+ type: "message" as const,
+ id,
+ seq,
+ parentId,
+ timestamp: Date.parse("2026-09-21T18:00:00Z") + seq * 1_000,
+ message,
+ };
+ }
+
+ function userNote(text: string, timestamp: number) {
+ return { role: "user", content: [{ type: "text", text }], timestamp };
+ }
+
+ function assistantNote(text: string, timestamp: number) {
+ return { ...assistantMessage({ content: [{ type: "text", text }] }), timestamp };
+ }
+
+ /**
+ * `toolName` is what pi's file-operation extraction matches on, and it knows
+ * the lowercase names: a chunk test that asserts the file list has to use one.
+ */
+ function toolStep(ids: string[], timestamp: number, toolName = "Read") {
+ return {
+ ...assistantMessage({
+ content: ids.map((id, index) => ({
+ type: "toolCall" as const,
+ id,
+ name: toolName,
+ arguments: { path: `large-${index}.txt` },
+ })),
+ stopReason: "toolUse",
+ }),
+ timestamp,
+ };
+ }
+
+ function toolOutput(toolCallId: string, text: string, timestamp: number) {
+ return {
+ role: "toolResult" as const,
+ toolCallId,
+ toolName: "Read",
+ content: [{ type: "text" as const, text }],
+ isError: false,
+ timestamp,
+ };
+ }
+
+ function appendedCheckpoint(host: { call: ReturnType<typeof vi.fn> }) {
+ const call = host.call.mock.calls.find(
+ ([method]) => method === "session.appendCompaction",
+ );
+ return (call?.[1] as any)?.compaction;
+ }
+
+ function failingSummary(runtime: DesktopAgentRuntime) {
+ return vi.spyOn(runtime as any, "generateCompaction").mockResolvedValue({
+ ok: false,
+ error: {
+ code: "summarization_failed",
+ message: "provider terminated the summary request",
+ },
+ });
+ }
+
+ function replayedMessages(runtime: DesktopAgentRuntime) {
+ return (runtime as any).agent.state.messages.filter(
+ (message: any) => message.role !== "system",
+ );
+ }
+
+ it("keeps the real recent window when an automatic summary fails", async () => {
+ const host = { call: vi.fn().mockResolvedValue(undefined) };
+ const runtime = createRuntime({ host });
+ (runtime as any).fullEntries = [
+ messageEntry("user-1", null, userNote("start the migration", 1), 0),
+ messageEntry("assistant-1", "user-1", assistantNote("I mapped the schema.", 2), 1),
+ messageEntry("assistant-2", "assistant-1", toolStep(["tool-1"], 3), 2),
+ messageEntry(
+ "tool-1",
+ "assistant-2",
+ toolOutput("tool-1", "CREATE TABLE projects (id TEXT)", 4),
+ 3,
+ ),
+ messageEntry("user-2", "tool-1", userNote("now rename the column", 5), 4),
+ ];
+ failingSummary(runtime);
+
+ await expect(
+ (runtime as any).runCompaction("threshold", false, "active_turn"),
+ ).resolves.toBe(true);
+
+ const checkpoint = appendedCheckpoint(host);
+ expect(checkpoint.details).toMatchObject({
+ fallback: "retained_tail",
+ failureCode: "CONTEXT_COMPACTION_FAILED",
+ failureReason: "summary_provider",
+ retainedTailMode: "active_turn",
+ retainedTailShape: "recent_window",
+ retainedTailCount: 5,
+ });
+ // The whole window survives, not the one latest user line: the earlier
+ // decision, the tool output, and the in-flight request all outlive the
+ // failed summary.
+ expect(checkpoint.retainedTail.map((message: any) => message.role)).toEqual([
+ "user",
+ "assistant",
+ "assistant",
+ "toolResult",
+ "user",
+ ]);
+ expect(checkpoint.summary).toContain(COMPACTION_FALLBACK_MARKER);
+ // A failed summary must not tell the model that one leftover user line is
+ // the source of truth for the whole continuation.
+ expect(checkpoint.summary).not.toContain("source of truth");
+
+ const replayed = replayedMessages(runtime);
+ expect(replayed.map((message: any) => message.role)).toEqual([
+ "compactionSummary",
+ "user",
+ "assistant",
+ "assistant",
+ "toolResult",
+ "user",
+ ]);
+ expect(
+ replayed
+ .filter((message: any) => message.role === "toolResult")
+ .map((message: any) => message.content[0].text),
+ ).toEqual(["CREATE TABLE projects (id TEXT)"]);
+ await runtime.dispose();
+ });
+
+ it("restores the same window for a completed turn without inventing a request", async () => {
+ const host = { call: vi.fn().mockResolvedValue(undefined) };
+ const runtime = createRuntime({ host });
+ (runtime as any).fullEntries = [
+ messageEntry("user-1", null, userNote("start the migration", 1), 0),
+ messageEntry("assistant-1", "user-1", assistantNote("I mapped the schema.", 2), 1),
+ messageEntry("assistant-2", "assistant-1", toolStep(["tool-1"], 3), 2),
+ messageEntry(
+ "tool-1",
+ "assistant-2",
+ toolOutput("tool-1", "CREATE TABLE projects (id TEXT)", 4),
+ 3,
+ ),
+ messageEntry(
+ "assistant-3",
+ "tool-1",
+ assistantNote("The migration is complete: 3 files changed.", 5),
+ 4,
+ ),
+ ];
+ failingSummary(runtime);
+
+ await expect((runtime as any).runCompaction("threshold", false)).resolves.toBe(
+ true,
+ );
+
+ const checkpoint = appendedCheckpoint(host);
+ const replayed = replayedMessages(runtime);
+ expect(replayed.map((message: any) => message.role)).toEqual([
+ "compactionSummary",
+ "user",
+ "assistant",
+ "assistant",
+ "toolResult",
+ "assistant",
+ ]);
+ // The window ends on the finished assistant message, so nothing in it reads
+ // as a request the next task still has to answer (#563, #224).
+ expect(replayed.at(-1).role).toBe("assistant");
+ await runtime.dispose();
+ });
+
+ it("summarizes a range no single prompt can carry instead of skipping it", async () => {
+ const constrained: RuntimeProviderConfig = {
+ ...provider,
+ modelConfig: {
+ ...provider.modelConfig!,
+ contextWindow: 32_000,
+ maxTokens: 4_096,
+ },
+ };
+ const runtime = createRuntime({ provider: constrained });
+ const resultCount = 600;
+ (runtime as any).fullEntries = [
+ messageEntry(
+ "old-user",
+ null,
+ { role: "user", content: "inspect the repository", timestamp: 1 },
+ 0,
+ ),
+ messageEntry(
+ "carrier",
+ "old-user",
+ toolStep(
+ Array.from({ length: resultCount }, (_, index) => `tool-${index}`),
+ 2,
+ "read",
+ ),
+ 1,
+ ),
+ ...Array.from({ length: resultCount }, (_, index) =>
+ messageEntry(
+ `tool-${index}`,
+ index === 0 ? "carrier" : `tool-${index - 1}`,
+ toolOutput(`tool-${index}`, "r".repeat(2_000), 3),
+ index + 2,
+ ),
+ ),
+ ];
+ const generate = vi
+ .spyOn(runtime as any, "generateCompaction")
+ .mockImplementation(async () => ({
+ ok: true,
+ value: {
+ summary: `part ${generate.mock.calls.length}`,
+ tokensBefore: 80_000,
+ usage: {
+ input: 10,
+ output: 5,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 15,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ details: { readFiles: ["large-0.txt"], modifiedFiles: [] },
+ },
+ }));
+
+ const build = await (runtime as any).buildCheckpoint(
+ new AbortController().signal,
+ "active_turn",
+ );
+
+ expect(build.ok).toBe(true);
+ const calls = generate.mock.calls.map(([preparation]: any[]) => preparation);
+ expect(calls.length).toBeGreaterThan(1);
+ expect(calls.length).toBeLessThanOrEqual(16);
+ // Every request after the first carries its predecessor's summary, so the
+ // chain converges on one summary for the whole range.
+ expect(calls[0].previousSummary).toBeUndefined();
+ for (let index = 1; index < calls.length; index += 1) {
+ expect(calls[index].previousSummary).toBe(`part ${index}`);
+ }
+ // Coverage: the chunks are contiguous and together carry every message, so
+ // nothing leaves the context without the summary covering it.
+ const summarized = calls.flatMap(
+ (preparation: any) => preparation.messagesToSummarize,
+ );
+ expect(summarized).toHaveLength(resultCount + 2);
+ expect(summarized[0].content).toBe("inspect the repository");
+ expect(
+ summarized.filter((message: any) => message.role === "toolResult"),
+ ).toHaveLength(resultCount);
+ // The range's file operations ride on the last request only, so pi appends
+ // the file list to the installed summary exactly once.
+ expect(calls[0].fileOps.read.size).toBe(0);
+ expect(calls.at(-1)!.fileOps).toBe((build as any).preparation.fileOps);
+ // One checkpoint, not a fallback: the model still summarized the range.
+ const checkpoint = (build as any).checkpoint;
+ expect(checkpoint.summary).toBe(`part ${calls.length}`);
+ expect(checkpoint.usage).toMatchObject({ totalTokens: 15 * calls.length });
+ expect(checkpoint.details).toMatchObject({
+ strategy: "summary",
+ retainedTailMode: "active_turn",
+ readFiles: ["large-0.txt"],
+ });
+ expect(checkpoint.details.fallback).toBeUndefined();
+ await runtime.dispose();
+ });
+
+ it("records why a fallback had to run", async () => {
+ const host = { call: vi.fn().mockResolvedValue(undefined) };
+ const runtime = createRuntime({ host });
+ (runtime as any).fullEntries = [
+ messageEntry("user-1", null, userNote("continue the migration", 1), 0),
+ ];
+
+ await expect(
+ (runtime as any).recoverCompactionFailure(
+ (runtime as any).entriesWithCompaction(),
+ (runtime as any).contextBudget(
+ (runtime as any).liveSessionContext().messages,
+ ),
+ "threshold",
+ false,
+ undefined,
+ "Compaction summary input exceeds the safe model budget",
+ "active_turn",
+ "summary_budget",
+ ),
+ ).resolves.toBe(true);
+
+ expect(appendedCheckpoint(host).details).toMatchObject({
+ failureReason: "summary_budget",
+ retainedTailMode: "active_turn",
+ retainedTailShape: "recent_window",
+ });
+ await runtime.dispose();
+ });
+});
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index d9a19eb80..7e307dc30 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -122,6 +122,7 @@ import {
timestampMs,
toJsonObject,
toJsonValue,
+ truncateTextWithMarker,
usageFromPi,
usageToPi,
} from "./agent-messages.js";
@@ -144,7 +145,6 @@ import {
createExtensionAgentModels,
createProviderModels,
DEFAULT_CONTEXT_WINDOW,
- DEFAULT_MAX_TOKENS,
providerRequestKey,
type RuntimeProviderConfig,
} from "./provider-binding.js";
@@ -205,10 +205,20 @@ import {
} from "./opencode-session-headers.js";
import { withCompactionRequestHeaders } from "./compaction-request.js";
import {
+ addSummaryUsage,
+ compactionSummaryInputLimit,
+ compactionSummaryOutputBudget,
COMPACTION_SUMMARY_RETRY_POLICY,
estimateSummaryPromptTokens,
+ planSummaryChunks,
reduceSummaryInput,
} from "./compaction-summary-input.js";
+import {
+ CHECKPOINT_TRUNCATION_MARKER,
+ COMPACTION_RETAINED_TAIL_SHAPE,
+ replayRetainedTail,
+ selectRecentTail,
+} from "./compaction-tail.js";
import {
mergeProviderHeaders,
providerHeadersEqual,
@@ -565,9 +575,18 @@ function formatDelegationResults(
includedDelegationIds,
};
}
-const COMPACTION_FALLBACK_KEEP_RECENT_RATIO = 0.25;
const COMPACTION_FALLBACK_MAX_SUMMARY_CHARS = 12_000;
-const COMPACTION_SUMMARY_PROMPT_SAFETY_TOKENS = 2_048;
+/**
+ * Room held back from a fallback's tail for the recovery notice the checkpoint
+ * appends after the carried-forward summary.
+ */
+const COMPACTION_FALLBACK_NOTICE_TOKENS = 512;
+/**
+ * Share of the safe budget a failure's retained window may occupy. The window
+ * is bounded by the keep-recent target as well, so it never carries more
+ * history than a successful checkpoint would (`fallbackRetainedTail`).
+ */
+const COMPACTION_FALLBACK_KEEP_RECENT_RATIO = 0.25;
export const COMPACTION_FALLBACK_MARKER =
"[automatic context recovery: older context was omitted after summary generation failed]";
/** Stored in place of a carried-forward summary when a fallback had none. */
@@ -595,6 +614,15 @@ function stripCompactionFallbackNotice(
}
return carried;
}
+
+/**
+ * File operations for a summary chunk that must not re-append the checkpoint's
+ * file lists: the last chunk carries the real ones, so a chained summary names
+ * each file once.
+ */
+function emptyFileOps(): CompactionPreparation["fileOps"] {
+ return { read: new Set(), written: new Set(), edited: new Set() };
+}
/** Path-scoped rules are best-effort and must not stall a file tool turn. */
export const PATH_INSTRUCTION_RESOLUTION_TIMEOUT_MS = 2_000;
const PATH_SCOPED_INSTRUCTION_TOOLS = new Set([
@@ -678,8 +706,6 @@ function pathInstructionScope(path: string): string {
return slash >= 0 ? normalized.slice(0, slash) || "/" : ".";
}
-const CHECKPOINT_TRUNCATION_MARKER =
- "\n\n[checkpoint truncated: this message crossed the retained context budget]\n\n";
/**
* Appended for one automatic re-run after a turn that produced nothing the
* user can see. Two shapes were observed: a wholly empty response, and a
@@ -1008,12 +1034,26 @@ type CheckpointBuildSuccess = {
preparation: ShapedPreparation;
};
+/**
+ * Why a checkpoint had to fall back, recorded on the fallback's `details` so a
+ * later report says more than `usage: null` does (issue #827). Deliberately a
+ * closed vocabulary: provider error text can carry endpoint details, and ADR
+ * 0049 keeps it out of the persisted record.
+ */
+type CompactionFailureReason =
+ | "no_new_history"
+ | "summary_budget"
+ | "summary_provider"
+ | "checkpoint_oversized";
+
type CheckpointBuildFailure = {
ok: false;
entries: Entry[];
budget: ContextBudget;
preparation?: ShapedPreparation;
message: string;
+ /** Recorded on the fallback checkpoint when this failure recovers to one. */
+ failureReason?: CompactionFailureReason;
tokensBefore?: number;
/**
* False when the failure must be reported as-is instead of falling back to a
@@ -1035,11 +1075,29 @@ function compactionRetentionMode(details: unknown): CompactionRetentionMode {
: "active_turn";
}
+/**
+ * The messages a stored checkpoint replays as real context after its summary.
+ *
+ * A checkpoint that recorded {@link COMPACTION_RETAINED_TAIL_SHAPE} keeps the
+ * whole window it stored: it is a failed compaction's only record of the range
+ * behind it, so narrowing the tail back to one user message would reinstate
+ * exactly the amnesia the window fixes (#827). Records written before that
+ * marker existed — and every successful checkpoint — keep the older
+ * normalization: at most the latest user message, and none at all once the turn
+ * is complete, so a restart cannot restore a sequence of executable-looking old
+ * requests.
+ */
function retainedTailForContext(
value: unknown,
details?: unknown,
): AgentMessage[] | undefined {
if (!Array.isArray(value)) return undefined;
+ if (
+ isRecord(details) &&
+ details.retainedTailShape === COMPACTION_RETAINED_TAIL_SHAPE
+ ) {
+ return replayRetainedTail(value) ?? [];
+ }
const messages = value
.filter(isRecord)
.filter((message) => message.role === "user") as unknown as AgentMessage[];
@@ -1277,17 +1335,9 @@ function appendToolProgress(current: string, chunk: string): string {
}`;
}
+/** Bound a checkpoint message's text, naming the cut the way pi's tail does. */
function truncateTextForCheckpoint(text: string, maxChars: number): string {
- if (text.length <= maxChars) return text;
- if (maxChars <= CHECKPOINT_TRUNCATION_MARKER.length) {
- return CHECKPOINT_TRUNCATION_MARKER.trim().slice(0, maxChars);
- }
- const retainedChars = maxChars - CHECKPOINT_TRUNCATION_MARKER.length;
- const headChars = Math.ceil(retainedChars * 0.75);
- const tailChars = retainedChars - headChars;
- return `${text.slice(0, headChars)}${CHECKPOINT_TRUNCATION_MARKER}${
- tailChars > 0 ? text.slice(-tailChars) : ""
- }`;
+ return truncateTextWithMarker(text, maxChars, CHECKPOINT_TRUNCATION_MARKER);
}
/**
@@ -6250,11 +6300,23 @@ Delegation rules:
};
}
+ /**
+ * Build the checkpoint a failed compaction installs: the summary it was
+ * carrying forward, a recovery notice, and the real recent window of the range
+ * it could not summarize (ADR 0049, issue #827).
+ *
+ * The window, not the notice, is what makes this checkpoint usable: with no
+ * fresh summary it is the only thing carrying the range forward, so the
+ * continuation text names it as the tail of the turn instead of presenting one
+ * leftover user line as the whole job.
+ */
private createFallbackCheckpoint(
preparation: ShapedPreparation,
throughMessageId: string,
maxSummaryChars: number,
retentionMode: CompactionRetentionMode,
+ budget: ContextBudget,
+ failureReason: CompactionFailureReason,
): ContextCompactionRecord {
const previousSummary = preparation.previousSummary
? boundedText(
@@ -6264,29 +6326,20 @@ Delegation rules:
: COMPACTION_FALLBACK_NO_SUMMARY;
const continuation =
retentionMode === "active_turn"
- ? "The provider is continuing the active turn. Use the one retained latest user request as the source of truth for that continuation."
- : "The previous turn is complete. Treat this summary as historical context; the next user message is the only new task to execute.";
+ ? "The provider is continuing the active turn: the recent messages carried below are the tail of that turn and the carried summary is the older history. Continue the work they describe."
+ : "The previous turn is complete. Treat this summary and the recent messages below as historical context; the next user message is the only new task to execute.";
const summary = [
previousSummary,
COMPACTION_FALLBACK_MARKER,
"The automatic summary request did not complete. Older messages before this checkpoint are omitted from the next model request.",
`The complete transcript remains available in the session. ${continuation}`,
].join("\n\n");
- // A completed-turn checkpoint normally retains no naked user messages, but
- // an empty tail plus a carried-forward (or absent) summary leaves the next
- // model request with nothing before the boundary: after a runtime rebuild
- // — model switch, restart — the session restores as if it had just started.
- // Fall back to the newest user messages under the same budget so the
- // failure path still restores a bounded, non-empty context (#224).
- const retainedTail =
- preparation.retainedTail.length > 0
- ? preparation.retainedTail
- : selectRetainedUserMessages(
- preparation.messagesToSummarize.filter(
- (message): message is UserMessage => message.role === "user",
- ),
- preparation.settings.keepRecentTokens,
- );
+ const retainedTail = this.fallbackRetainedTail(
+ preparation,
+ budget,
+ maxSummaryChars,
+ retentionMode,
+ );
return this.createCheckpoint(
{
...preparation,
@@ -6299,12 +6352,50 @@ Delegation rules:
...this.checkpointDetails(preparation),
fallback: "retained_tail" satisfies ContextCompactionFallback,
failureCode: "CONTEXT_COMPACTION_FAILED",
+ failureReason,
retainedTailMode: retentionMode,
+ // The shape tells a rebuild to replay the whole window. Without it a
+ // restored checkpoint narrows the tail back to one user message, which
+ // is the defect this window exists to fix (#827).
+ retainedTailShape: COMPACTION_RETAINED_TAIL_SHAPE,
+ retainedTailCount: retainedTail.length,
...this.retainedReasoningForCheckpoint(preparation),
},
);
}
+ /**
+ * The recent window a fallback retains. Bounded by the keep-recent target so a
+ * failure never carries more history than a successful checkpoint would, and
+ * by what the safe budget leaves once the carried-forward summary and the
+ * recovery notice are paid for — `persistCheckpoint` re-estimates the installed
+ * context, and an oversized fallback would fail the run outright.
+ */
+ private fallbackRetainedTail(
+ preparation: ShapedPreparation,
+ budget: ContextBudget,
+ maxSummaryChars: number,
+ retentionMode: CompactionRetentionMode,
+ ): AgentMessage[] {
+ const summaryTokens = Math.ceil(maxSummaryChars / 4);
+ const available = Math.max(
+ 1,
+ budget.hardLimit - summaryTokens - COMPACTION_FALLBACK_NOTICE_TOKENS,
+ );
+ const target = Math.max(
+ 1,
+ Math.min(
+ budget.keepRecentTokens,
+ Math.floor(budget.hardLimit * COMPACTION_FALLBACK_KEEP_RECENT_RATIO),
+ ),
+ );
+ return selectRecentTail(
+ preparation.messagesToSummarize,
+ Math.min(target, available),
+ { latestUserGoal: retentionMode === "active_turn" },
+ );
+ }
+
/**
* The recovery path retains less than a normal checkpoint: its summary is a
* carried-forward one rather than a fresh one, so the retained messages are
@@ -6329,37 +6420,44 @@ Delegation rules:
);
}
+ /**
+ * Tokens one summary prompt may carry for this model window. The preflight
+ * guard and the chunk planner have to agree on it, so it is computed once here
+ * from the shared formula.
+ */
+ private summaryInputLimit(budget: {
+ hardLimit: number;
+ requestHeadroom: number;
+ }): number {
+ return compactionSummaryInputLimit({
+ hardLimit: budget.hardLimit,
+ requestHeadroom: budget.requestHeadroom,
+ modelMaxTokens: this.model.maxTokens,
+ });
+ }
+
private compactionSummaryWouldExceedBudget(
preparation: ShapedPreparation,
budget: { hardLimit: number; requestHeadroom: number },
): boolean {
- const contextWindow = budget.hardLimit + budget.requestHeadroom;
- const modelOutputBudget = Math.min(
- Math.floor(budget.requestHeadroom * 0.8),
- Math.max(1, Math.round(this.model.maxTokens || DEFAULT_MAX_TOKENS)),
- );
- const summaryInputLimit = Math.max(
- 1,
- contextWindow -
- modelOutputBudget -
- COMPACTION_SUMMARY_PROMPT_SAFETY_TOKENS,
+ // The summary covers the whole boundary range, so its input is the context
+ // that tripped the hard limit. This sizes the prompt the way pi serializes
+ // it — tool results already capped — rather than the raw messages, which
+ // overstated tool-heavy sessions by several times and skipped summaries that
+ // would have fit (#543). A prompt this large is now summarized in chunks
+ // rather than skipped (#827); only the planner can still send the turn to
+ // retained-tail recovery.
+ return (
+ estimateSummaryPromptTokens(preparation) >= this.summaryInputLimit(budget)
);
- // The summary now covers the whole boundary range, so its input is the
- // context that tripped the hard limit. On a window whose headroom leaves
- // less room for the summary request than the hard limit allows, this is the
- // guard that routes the turn to retained-tail recovery instead. It sizes
- // the prompt the way pi serializes it — tool results already capped —
- // rather than the raw messages, which overstated tool-heavy sessions by
- // several times and skipped summaries that would have fit (#543).
- return estimateSummaryPromptTokens(preparation) >= summaryInputLimit;
}
/**
* Fit the summary input under the provider budget. The full input is tried
* first; when it is too large, one reduced pass (tool results cut to a short
- * prefix, thinking dropped) is tried before giving up. The reduced input
- * still covers every message the checkpoint files behind its boundary, so
- * nothing is silently dropped from the summary's scope (ADR 0282).
+ * prefix, thinking dropped) is tried before giving up. The reduced input still
+ * covers every message the checkpoint files behind its boundary, so nothing is
+ * silently dropped from the summary's scope (ADR 0282).
*/
private fitSummaryInputToBudget(
preparation: ShapedPreparation,
@@ -6375,6 +6473,30 @@ Delegation rules:
return reduced;
}
+ /**
+ * Plan the summary requests for a range no single prompt can carry: the
+ * reduced input when one exists, split into contiguous chunks that each fit.
+ * Returns undefined when the range cannot be planned, which is the only budget
+ * failure that still routes a turn to retained-tail recovery (#827).
+ */
+ private planSummaryRequests(
+ preparation: ShapedPreparation,
+ budget: { hardLimit: number; requestHeadroom: number },
+ ): AgentMessage[][] | undefined {
+ const reduced = reduceSummaryInput(preparation) ?? preparation;
+ const reserveTokens = Math.max(
+ Math.ceil((preparation.previousSummary?.length ?? 0) / 4),
+ compactionSummaryOutputBudget({
+ requestHeadroom: budget.requestHeadroom,
+ modelMaxTokens: this.model.maxTokens,
+ }),
+ );
+ return planSummaryChunks(reduced, {
+ summaryInputLimit: this.summaryInputLimit(budget),
+ reserveTokens,
+ });
+ }
+
private async persistCheckpoint(
checkpoint: ContextCompactionRecord,
reason: ContextCompactionReason,
@@ -6465,6 +6587,7 @@ Delegation rules:
preparation: ShapedPreparation | undefined,
failureMessage: string,
retentionMode: CompactionRetentionMode,
+ failureReason: CompactionFailureReason = "summary_provider",
): Promise<boolean> {
if (reason === "manual") {
this.emitCompactionFailure(
@@ -6506,6 +6629,8 @@ Delegation rules:
),
),
retentionMode,
+ budget,
+ failureReason,
);
const persisted = await this.persistCheckpoint(
checkpoint,
@@ -6547,6 +6672,53 @@ Delegation rules:
);
}
+ /**
+ * Summarize a range whose prompt does not fit the provider window, however far
+ * it was reduced. Each chunk is one pi summary request — same prompt, retry
+ * policy, and headers as the single-pass path — and each carries the summary of
+ * the chunk before it, so the chain converges on one summary covering every
+ * message the checkpoint files behind its boundary. Only the last chunk is given
+ * the range's file operations, so the file list is appended to the summary
+ * exactly once.
+ */
+ private async generateChunkedCompaction(
+ preparation: ShapedPreparation,
+ chunks: AgentMessage[][],
+ signal: AbortSignal,
+ ): Promise<Awaited<ReturnType<typeof compact>>> {
+ let summary = preparation.previousSummary;
+ let usage: Usage | undefined;
+ let details: unknown;
+ for (const [index, messages] of chunks.entries()) {
+ const last = index === chunks.length - 1;
+ const step = await this.generateCompaction(
+ {
+ ...preparation,
+ messagesToSummarize: messages,
+ turnPrefixMessages: [],
+ isSplitTurn: false,
+ previousSummary: summary,
+ fileOps: last ? preparation.fileOps : emptyFileOps(),
+ },
+ signal,
+ );
+ if (!step.ok) return step;
+ summary = step.value.summary;
+ usage = addSummaryUsage(usage, step.value.usage);
+ if (last) details = step.value.details;
+ }
+ return {
+ ok: true,
+ value: {
+ summary: summary ?? "",
+ tokensBefore: preparation.tokensBefore,
+ usage,
+ retainedTail: preparation.retainedTail,
+ details: toJsonValue(details),
+ },
+ };
+ }
+
/**
* Produce a checkpoint without touching the session: no persistence, no
* `activeCompaction` mutation, no events. Keeping generation separate from
@@ -6574,6 +6746,7 @@ Delegation rules:
message: preparation.ok
? "No new context is available to compact"
: preparation.error.message,
+ failureReason: "no_new_history",
recoverable: true,
};
}
@@ -6583,7 +6756,13 @@ Delegation rules:
}
const summaryInput = this.fitSummaryInputToBudget(preparation.value, budget);
- if (!summaryInput) {
+ // No single prompt fits. The range is summarized in chunks instead of giving
+ // up on the model: only a range that cannot be planned at all — empty, or
+ // needing more requests than the planner allows — still falls back (#827).
+ const chunks = summaryInput
+ ? undefined
+ : this.planSummaryRequests(preparation.value, budget);
+ if (!summaryInput && !chunks) {
return {
ok: false,
entries,
@@ -6591,13 +6770,20 @@ Delegation rules:
preparation: preparation.value,
tokensBefore: preparation.value.tokensBefore,
message: "Compaction summary input exceeds the safe model budget",
+ failureReason: "summary_budget",
recoverable: true,
};
}
let result: Awaited<ReturnType<typeof compact>>;
try {
- result = await this.generateCompaction(summaryInput, signal);
+ result = summaryInput
+ ? await this.generateCompaction(summaryInput, signal)
+ : await this.generateChunkedCompaction(
+ preparation.value,
+ chunks!,
+ signal,
+ );
} catch (error) {
return {
ok: false,
@@ -6606,6 +6792,7 @@ Delegation rules:
preparation: preparation.value,
tokensBefore: preparation.value.tokensBefore,
message: error instanceof Error ? error.message : String(error),
+ failureReason: "summary_provider",
recoverable: !signal.aborted,
};
}
@@ -6617,6 +6804,7 @@ Delegation rules:
preparation: preparation.value,
tokensBefore: preparation.value.tokensBefore,
message: result.error.message,
+ failureReason: "summary_provider",
recoverable: result.error.code !== "aborted",
};
}
@@ -6730,6 +6918,7 @@ Delegation rules:
build.preparation,
"The checkpoint did not reduce context below the safe request budget",
retentionMode,
+ "checkpoint_oversized",
);
}
@@ -6759,6 +6948,7 @@ Delegation rules:
build.preparation,
build.message,
retentionMode,
+ build.failureReason ?? "summary_provider",
);
}
return await this.installCheckpoint(build, reason, willRetry, retentionMode);