Skip to content

fix(compaction): preserve multi-step plan state across compactions - #1486

Open
adminwat wants to merge 4 commits into
1jehuang:masterfrom
adminwat:fix/compaction-plan-amnesia
Open

adminwat wants to merge 4 commits into
1jehuang:masterfrom
adminwat:fix/compaction-plan-amnesia

Conversation

@adminwat

Copy link
Copy Markdown
Contributor

Problem: compaction amnesia in long sessions

Observed 2026-09-24 in a 48-compaction, 3,100-message, 2-day Gemini session. The user approved a 4-item plan that lived only in one assistant message. That message was compacted away on day one, and:

  • Each ~2.5k-char model-written summary described the just-finished sprint in detail and carried only a vague "what's next".
  • Every time the user said "continue with the plan" (5 times over 2 days), the model re-derived "the plan" from the latest summary and redid/optimized already-shipped work (review-fix PRs on merged pages, re-mirroring links, more articles on the same topic).
  • Plan item 4 (call tracking) was never reached.
  • One summary promoted an unapproved idea ("create runbook and skill") into committed next steps under "What's next", which the model then executed. The user had to ask for it to be removed.

The todo tool was called 42 times in that session but each sprint overwrote the list with micro-tasks, and the todo store was never fed back into provider context after compaction anyway.

Fix (two complementary parts)

1. SUMMARY_PROMPT hardening (jcode-compaction-core): new mandatory Plan status section. The summarizer must list every item of the ORIGINAL plan verbatim with done/in-progress/not-started state, must never drop unfinished items, never re-derive the plan from recent work, and never promote unapproved ideas into plan items. Marked as the one section exempt from "be concise", because a dropped plan item is lost permanently.

2. Live todo reinjection (jcode-base + jcode-app-core): the todo store survives compaction on disk but was never sent back to the provider. Now:

  • todo::format_plan_context() renders the session todo list as a compact block (group headers, [x]/[>]/[ ]/[-] markers, 4k-char cap) with an explicit "Do not redo completed items" instruction.
  • CompactionManager::set_plan_context() stores it; messages_for_api_with appends it as a second text block after the summary block.
  • agent::messages_for_provider refreshes it each turn, so it always reflects the current todo state (ground truth, not model-written).
  • Skipped for OpenAI native encrypted summaries: that replay path is shape-sensitive and the encrypted block must stand alone.

Verification

  • 4 new tests: injection after text summary, whitespace/cleared context not injected, encrypted OpenAICompaction block left untouched, formatter rendering (grouping + markers + guard text).
  • Suites: 44/44 jcode-base compaction+todo tests on the dev branch, 18/18 jcode-compaction-core.
  • Note: test_context_usage_with_both_estimate_and_observed and test_token_estimate fail on clean origin/master on my machine (local ~/.jcode config leaks into CompactionManager::new() budget in tests). Pre-existing, unrelated, no new failures introduced by this PR.
  • Deployed locally as v0.84.21-dev on the machine where the original failure occurred.

Observed 2026-09-24 in a 48-compaction, 3,100-message Gemini session:
the user's approved 4-item plan lived only in one assistant message,
which was compacted away on day one. Each ~2.5k-char model-written
summary described the just-finished sprint in detail and carried only a
vague "what's next", so every "continue with the plan" (5 times) made
the model re-derive the plan from the latest sprint and redo/optimize
already-shipped work. Plan item D (call tracking) was never reached,
and one summary promoted an unapproved idea ("create runbook and
skill") into committed next steps, which the model then executed.

Two complementary fixes:

1. SUMMARY_PROMPT (jcode-compaction-core): new mandatory "Plan status"
   section. The summarizer must list every item of the ORIGINAL plan
   verbatim with done/in-progress/not-started state, must not drop
   unfinished items, must not re-derive the plan from recent work, and
   must not promote unapproved ideas into plan items.

2. Live todo reinjection (jcode-base + jcode-app-core): the todo store
   already survives compaction on disk but was never fed back into
   provider context. format_plan_context() renders the session's todo
   list (grouped, [x]/[>]/[ ]/[-] markers, 4k-char cap) and
   CompactionManager::set_plan_context() appends it as a second text
   block after the summary in messages_for_api_with. Refreshed each
   turn in agent::messages_for_provider. Skipped for OpenAI native
   encrypted summaries (that replay path is shape-sensitive and the
   encrypted block must stand alone).

Tests: 4 new (injection after text summary, empty/cleared not injected,
encrypted summary untouched, formatter rendering). Full suites pass:
40 compaction + 44 todo (jcode-base), 18 jcode-compaction-core.
@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 1/5

[Medium risk] Adds plan-state preservation across message compactions.

Not safe to merge: the image-turn omission and three outstanding plan-correctness issues can cause the assistant to lose work or exceed its context budget.

Findings

  1. P1 Image Turns Lose Plan Status ▶
  2. P1 Replacement List Becomes Plan ▶
  3. P1 Truncation Drops Pending Work ▶
  4. P1 Plan Escapes Context Budget ▶
  5. P2 Completed Items Look Pending ▶
  6. P2 Long Item Exceeds Cap ▶
Fix with agent prompt
### Issue 1
crates/jcode-base/src/compaction.rs:1411-1413
After compaction, if a user asks to continue the plan and includes an image, this text-only check omits the saved todo snapshot from the request. The assistant receives only the summary for earlier progress, so it can repeat completed work or miss the next pending step. Preserve the live plan for image-containing user turns before merging.

### Issue 2
crates/jcode-base/src/todo.rs:882-884
If a new task list replaces an unfinished approved plan, this block calls only the replacement list “ground truth” and tells the model to continue from it. The original unfinished steps are no longer in the todo store, so the model can follow the replacement work instead of completing the approved plan. Preserve the original plan before merging.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

### Issue 3
crates/jcode-base/src/todo.rs:899-903
When earlier completed entries fill the allowance, the formatter stops before rendering later pending entries. The compacted request then presents a plan without those unfinished steps, allowing the model to skip them. Preserve pending work before merging.

### Issue 4
crates/jcode-base/src/compaction.rs:1355-1360
The context check counts the summary and active messages but not the plan appended here. When a request is near its context limit, the plan can push it over budget without triggering pre-request hard compaction, risking a provider context-limit failure. Account for the plan before merging.

### Issue 5
crates/jcode-base/src/todo.rs:893-897
Persisted todos marked `done` or `finished` are recognized as completed elsewhere, but this snapshot displays them as unchecked. That can prompt the model to repeat finished work after compaction. This concern does not by itself block merging.

### Issue 6
crates/jcode-base/src/todo.rs:899-900
The formatter appends an entire todo before checking the 4,000-character limit. A single long item therefore exceeds the intended cap and adds avoidable context cost to compacted requests. This concern does not by itself block merging.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR moves saved plan status to a trailing reminder after compaction. An image-containing request to continue the plan does not receive that reminder, so the assistant can lose completed and pending steps. This and the outstanding plan-correctness issues need fixes before merging.

Reviews (2) · Last reviewed commit: "fix(compaction): mark the plan snapshot ..."

Comment on lines +882 to +884
let mut out = String::from(
"## Live Plan Status (todo store, survives compaction)\n\nThis list is ground truth for plan progress. Do not redo completed items; continue from the first pending or in-progress item.\n\n",
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Replacement List Becomes Plan

If a new task list replaces an unfinished approved plan, this block calls only the replacement list “ground truth” and tells the model to continue from it. The original unfinished steps are no longer in the todo store, so the model can follow the replacement work instead of completing the approved plan. Preserve the original plan before merging.

Artifacts

Rust reproduction command and temporary test

  • The script creates a temporary Rust test, runs either condition, captures its output, and removes the test afterward.

Compaction request before todo replacement

  • The passing Rust run shows the completed sprint in the injected plan before replacement.

Compaction request after micro-task replacement

  • The passing Rust run shows pending micro-tasks labeled as ground truth and the completed sprint absent from the injected plan.

View artifacts

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/todo.rs
Line: 882-884

Comment:
**Replacement List Becomes Plan**

If a new task list replaces an unfinished approved plan, this block calls only the replacement list “ground truth” and tells the model to continue from it. The original unfinished steps are no longer in the todo store, so the model can follow the replacement work instead of completing the approved plan. Preserve the original plan before merging.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +893 to +897
let marker = match todo.status.as_str() {
"completed" => "[x]",
"in_progress" => "[>]",
"cancelled" => "[-]",
_ => "[ ]",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Completed Items Look Pending

Persisted todos marked done or finished are recognized as completed elsewhere, but this snapshot displays them as unchecked. That can prompt the model to repeat finished work after compaction. This concern does not by itself block merging.

Artifacts

Persisted todo status reproduction test

  • The authored Rust test writes a bare todo JSON array, loads it through the application storage path, and checks the rendered markers for completion synonyms.

Snapshot test on PR code

  • The test loaded `done` and `finished` as completed synonyms but rendered both unchecked and failed with exit code 101.

Snapshot test with temporary canonical-status fix

  • The identical test rendered both persisted synonyms checked and passed with exit code 0.

View artifacts

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/todo.rs
Line: 893-897

Comment:
**Completed Items Look Pending**

Persisted todos marked `done` or `finished` are recognized as completed elsewhere, but this snapshot displays them as unchecked. That can prompt the model to repeat finished work after compaction. This concern does not by itself block merging.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +899 to +903
out.push_str(&format!("- {} {}\n", marker, todo.content));
if out.len() > PLAN_CONTEXT_MAX_CHARS {
out.push_str("- ... (list truncated)\n");
break;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Truncation Drops Pending Work

When earlier completed entries fill the allowance, the formatter stops before rendering later pending entries. The compacted request then presents a plan without those unfinished steps, allowing the model to skip them. Preserve pending work before merging.

Artifacts

Rust test for persisted todos in a compacted message

  • The authored test loads persisted todos through the formatter and inspects the resulting compaction API message, exercising the affected path.

Commands for the short-list and long-list tests

  • The authored runner executes both cases and captures each command, working directory, output, and exit code, making the comparison reproducible.

Short completed list retains the later pending todo

  • The short-list test passed with the pending item present in the injected message, establishing the control result.

Long completed list loses the later pending todo

  • The long-list test failed after the formatter truncated the plan, showing that the injected message omitted the pending item.

Targeted Rust test source for a single saved todo

  • The authored test saves one todo, calls the real formatter, and measures its output; it is the execution source for both runs.

Short-todo control test output

  • The 64-character control todo rendered 259 characters under the 4,000-character limit.

Long-todo cap test output

  • The single 5,000-character todo rendered 5,218 characters with its full content intact, confirming the cap is exceeded.

View artifacts

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/todo.rs
Line: 899-903

Comment:
**Truncation Drops Pending Work**

When earlier completed entries fill the allowance, the formatter stops before rendering later pending entries. The compacted request then presents a plan without those unfinished steps, allowing the model to skip them. Preserve pending work before merging.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment thread crates/jcode-base/src/compaction.rs Outdated
Comment on lines +1355 to +1360
if is_text_summary {
if let Some(plan_context) = self.plan_context.as_ref() {
blocks.push(ContentBlock::Text {
text: plan_context.clone(),
cache_control: None,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Plan Escapes Context Budget

The context check counts the summary and active messages but not the plan appended here. When a request is near its context limit, the plan can push it over budget without triggering pre-request hard compaction, risking a provider context-limit failure. Account for the plan before merging.

Artifacts

Rust reproduction test patch

  • The captured diff contains the two test cases executed against the budget-check and request-assembly path; the temporary tracked-file change was then reverted.

Test output without a plan

  • The Rust test ran with no plan and showed a 514-token assembled request under the 1000-token budget.

Test output with an appended plan

  • The Rust test ran with a plan and showed a 1114-token assembled request despite unchanged 503-token accounting and no hard compaction.

View artifacts

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/compaction.rs
Line: 1355-1360

Comment:
**Plan Escapes Context Budget**

The context check counts the summary and active messages but not the plan appended here. When a request is near its context limit, the plan can push it over budget without triggering pre-request hard compaction, risking a provider context-limit failure. Account for the plan before merging.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +899 to +900
out.push_str(&format!("- {} {}\n", marker, todo.content));
if out.len() > PLAN_CONTEXT_MAX_CHARS {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Long Item Exceeds Cap

The formatter appends an entire todo before checking the 4,000-character limit. A single long item therefore exceeds the intended cap and adds avoidable context cost to compacted requests. This concern does not by itself block merging.

Artifacts

Rust test for persisted todos in a compacted message

  • The authored test loads persisted todos through the formatter and inspects the resulting compaction API message, exercising the affected path.

Commands for the short-list and long-list tests

  • The authored runner executes both cases and captures each command, working directory, output, and exit code, making the comparison reproducible.

Short completed list retains the later pending todo

  • The short-list test passed with the pending item present in the injected message, establishing the control result.

Long completed list loses the later pending todo

  • The long-list test failed after the formatter truncated the plan, showing that the injected message omitted the pending item.

Targeted Rust test source for a single saved todo

  • The authored test saves one todo, calls the real formatter, and measures its output; it is the execution source for both runs.

Short-todo control test output

  • The 64-character control todo rendered 259 characters under the 4,000-character limit.

Long-todo cap test output

  • The single 5,000-character todo rendered 5,218 characters with its full content intact, confirming the cap is exceeded.

View artifacts

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/todo.rs
Line: 899-900

Comment:
**Long Item Exceeds Cap**

The formatter appends an entire todo before checking the 4,000-character limit. A single long item therefore exceeds the intended cap and adds avoidable context cost to compacted requests. This concern does not by itself block merging.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These findings sit on lines the diff does not cover, so they could not be posted inline. Each one leaves this list once its file changes.

  • P2 Compacted image requests lose live plan state ▶

    • Bug
      • For a user request with an image, the outgoing context lacks the todo store's completed and pending items. The model receives only the lossy summary for prior plan progress, risking repeated completed work or choosing the wrong next item. Tool-result continuations also omit the snapshot, but the code explicitly excludes them to preserve tool handoff compatibility.
    • Cause
      • In compaction.rs:1408-1413, can_append_trailing_user_turn accepts only user messages whose blocks are all Text; messages_for_api_with consequently skips the live plan append.
    • Fix
      • Allow a genuine image-and-text user turn to receive the trailing plan snapshot while retaining the tool-use and tool-result exclusions; handle tool-loop plan availability separately without inserting an invalid handoff.

…cache

Regression from 52e9b10, which injected the live plan snapshot as a
second content block inside the compaction summary message. That message
is message 0 of every request: the cached prefix. The snapshot is
regenerated from the todo store each turn, so any todo change mutated
the cached prefix and invalidated the entire Anthropic prompt cache,
forcing a full re-write of the whole conversation every turn.

Observed on this machine 2026-09-24 (logs jcode-2026-09-24.log):
- 1,807 rate_limit_error hits that day, 816 of them in the two hours
  right after the v0.84.21-dev reload at 17:28, vs 7-66 per hour before.
- Cache write ratio over the affected windows jumped from ~0% (quiet
  window 17:05-17:15: read=8,411,854 write=73,774) to 16% immediately
  after the reload (17:28-17:39: read=2,959,571 write=571,601).
- User hit "Anthropic API error (429): This request would exceed your
  account's rate limit" (request_id req_011CfNyepi9rewxAnatySmoy).

Fix: append the plan snapshot at the END of the message list instead,
after the stable prefix. Anthropic cache breakpoints attach to assistant
messages, so a trailing user block sits outside the cached prefix and
costs nothing to change per turn.

Guard: only append when the conversation ends on a plain user text turn
(the start of a turn, which is when plan state matters). Appending after
an assistant tool_use turn would orphan its tool results, and appending
after a user[tool_result] turn would recreate the trailing
functionResponse+text shape Gemini 3.x rejects with a 400 (fixed in
2db09f9).

Tests: 5 plan-context tests, 2 of them new and specifically about cache
stability (cached prefix stays single-block; prefix is byte-identical
across turns when the plan changes) plus a mid-tool-loop skip test.
Both cache tests were falsified by reintroducing the bug (they fail) and
pass with the fix. Suites: 41 compaction + 44 todo (jcode-base).
@adminwat

Copy link
Copy Markdown
Contributor Author

Follow-up: fixed a prompt-cache regression in the original commit

The first version of this PR injected the plan snapshot as a second content block inside the compaction summary message. That message is message 0 of every request, i.e. the cached prefix. Since the snapshot is regenerated from the todo store each turn, any todo change mutated the cached prefix and invalidated the entire Anthropic prompt cache, forcing a full re-write of the conversation every turn.

I caught this on my own machine after deploying it:

  • 1,807 rate_limit_error hits that day, 816 of them in the two hours right after the deploy at 17:28, versus 7-66 per hour before.
  • Cache write ratio jumped from ~0% in a quiet pre-deploy window (17:05-17:15: read=8,411,854 write=73,774) to 16% immediately after (17:28-17:39: read=2,959,571 write=571,601).
  • It produced a user-visible 429 This request would exceed your account's rate limit.

Fix (new commit on this branch): append the plan snapshot at the end of the message list instead, after the stable prefix. Anthropic cache breakpoints attach to assistant messages, so a trailing user block sits outside the cached prefix and costs nothing to change per turn.

Guard: only append when the conversation ends on a plain user text turn. Appending after an assistant tool_use turn would orphan its tool results, and appending after a user[tool_result] turn would recreate the trailing functionResponse+text shape that Gemini 3.x rejects with a 400.

Tests: 2 new cache-stability tests (cached prefix stays single-block; prefix is byte-identical across turns when the plan changes) plus a mid-tool-loop skip test. Both cache tests were falsified by reintroducing the bug (confirmed failing) and pass with the fix. 41 compaction + 44 todo tests green.

The previous two commits only set the plan snapshot in
agent::messages_for_provider. The TUI has its own
conversation_state::messages_for_provider that also calls
messages_for_api_with, so local TUI sessions still compacted plan state
away with no reinjection. Mirror the agent wiring there.

The cache-safe tail placement and the mid-tool-loop guard live in
CompactionManager, so both call sites share them.
The injected plan block was a bare user text turn, so jcode classified
it as a genuine user-authored message. Three consequences:

- is_internal_system_reminder() returned false, so the block was not
  treated as internal context.
- Timestamp injection applied to it, since
  should_skip_timestamp_injection() keys off the same check.
- ends_with_fresh_user_turn() reported a fresh user prompt the user
  never typed, which drives dynamic system-context injection.

Wrap the block in <system-reminder> tags so all three paths classify it
correctly, and state in the text that it is injected context rather than
a user message.

Test asserts the wrapper, that Message::user(block) is recognized as an
internal system reminder, and that it does not register as a fresh user
turn. Falsified by reverting to the bare-text form (test fails).
Comment on lines +1411 to +1413
last.content
.iter()
.all(|block| matches!(block, ContentBlock::Text { .. }))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Image Turns Lose Plan Status

After compaction, if a user asks to continue the plan and includes an image, this text-only check omits the saved todo snapshot from the request. The assistant receives only the summary for earlier progress, so it can repeat completed work or miss the next pending step. Preserve the live plan for image-containing user turns before merging.

Artifacts

Compacted request reproduction test

  • The authored Rust test loads saved todos and exercises request assembly for text, image, and tool-result turns.

Before-and-after test command

  • The authored command runs both captures with a temporary image-aware change and restores tracked source afterward.

Request output with the current text-only guard

  • The executed test shows the image and tool-result requests omit saved todo details while the text request includes them.

Request output with a temporary image-aware guard

  • The executed test shows the image request now includes saved todo details while the tool-result handoff remains unchanged.

View artifacts

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/compaction.rs
Line: 1411-1413

Comment:
**Image Turns Lose Plan Status**

After compaction, if a user asks to continue the plan and includes an image, this text-only check omits the saved todo snapshot from the request. The assistant receives only the summary for earlier progress, so it can repeat completed work or miss the next pending step. Preserve the live plan for image-containing user turns before merging.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

xenking added a commit to xenking/jcode that referenced this pull request Nov 22, 2026
xenking added a commit to xenking/jcode that referenced this pull request Nov 22, 2026
Upstream-PR: 1jehuang#1357
Upstream-PR-Commit: 1jehuang#1357 0da5e81
Upstream-PR: 1jehuang#1362
Upstream-PR-Commit: 1jehuang#1362 5962058
Upstream-PR: 1jehuang#1486
Upstream-PR-Commit: 1jehuang#1486 fadc624
Upstream-PR: 1jehuang#1733
Upstream-PR-Commit: 1jehuang#1733 01f3415
Upstream-PR: 1jehuang#1750
Upstream-PR-Commit: 1jehuang#1750 1ac0c82
Upstream-PR: 1jehuang#1822
Upstream-PR-Commit: 1jehuang#1822 73f85fc
Upstream-PR: 1jehuang#1912
Upstream-PR-Commit: 1jehuang#1912 36d7682
Upstream-PR: 1jehuang#1978
Upstream-PR-Commit: 1jehuang#1978 0f55643
Upstream-PR: 1jehuang#2007
Upstream-PR-Commit: 1jehuang#2007 638f87c
Upstream-PR: 1jehuang#2213
Upstream-PR-Commit: 1jehuang#2213 c5e1487
Upstream-PR: 1jehuang#2234
Upstream-PR-Commit: 1jehuang#2234 0d4d5d4
Upstream-PR: 1jehuang#2266
Upstream-PR-Commit: 1jehuang#2266 217ddc2
Upstream-PR: 1jehuang#2267
Upstream-PR-Commit: 1jehuang#2267 e98c40b

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant