Skip to content

feat(agent): carry the user's own earlier wording across compaction - #303

Merged
Zongwei9888 merged 1 commit into
HKUDS:mainfrom
raymondginger2018-sudo:pr/compaction-task-embed
Nov 16, 2026
Merged

Zongwei9888 merged 1 commit into
HKUDS:mainfrom
raymondginger2018-sudo:pr/compaction-task-embed

Conversation

@raymondginger2018-sudo

@raymondginger2018-sudo raymondginger2018-sudo commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The summary is lossy by design, and the one thing it should not be allowed to paraphrase away is what the user actually asked for. This carries the user's own earlier messages over the checkpoint boundary, quoted verbatim.

What the first revision got wrong

Both were visible in a real session, not just in review:

  • It took "the first user message", which is the environment slot. Every session with a workspace starts with {"role": "user", "env_context": True}. Measured on a real AgentSession(workspace=…) + compact(): a 6,363-character request was replaced by a 229-character environment dump, and the request was gone from the whole history.
  • It kept up to 60,000 characters under a permanent ORIGINAL TASK label. That swamped the checkpoint (52,311 → 48,064 characters, where main goes to 8,015) and pinned the model to old work — in a multi-turn session the first message is often not what is being worked on any more.

What it does now

  • The user's own earlier messages, newest first, under a few-thousand-character budget (EARLIER_USER_CHARS = 4_000).
  • A neutral heading — "Earlier messages from the user (most recent first):" — not an "original task" label.
  • Skips the environment slot, checkpoints, and empty content.
  • A message already present in the kept tail is not repeated.
  • A single oversized message is truncated to the budget rather than skipped, so the user's current words are never dropped entirely.
  • Re-compaction re-reads the block from the previous checkpoint, so a second round does not lose it.

On runtime notes: they are not filtered by is_context_note() here, because by the time this runs the kernel history projection has already dropped user-role metadata — there is no marker left to test. The skip is shape-based, and the docstring says so.

Changes

2 files, +251 / -4.

  • core/agent_runtime/compaction.py — _earlier_user_messages() (newest-first, budgeted), the neutral heading, and the checkpoint wiring.
  • tests/test_session_compaction.py — new coverage.

Two assertions this branch had added now restate main instead: they claimed "the original task (MSG0) survives", which is exactly the behaviour being removed.

Tests

tests/test_session_compaction.py — 13 passed. New cases pin:

  • newest-first ordering, and that the environment slot and checkpoints are skipped;
  • the budget (and that an oversized single message is truncated, not dropped);
  • the neutral heading, and that ORIGINAL TASK is gone;
  • re-compaction carry-forward;
  • one end-to-end case that drives AgentSession(workspace=…) and await session.compact().

ruff 0.15.21 check and format --check clean. Rebased onto 3dcb0fb4.

Dependency note

None. One module plus its tests.

@Zongwei9888

Copy link
Copy Markdown
Contributor

Thanks for working on this. Losing the user's own wording after compaction is a real concern, and the tests are careful. Running it in a real session showed a few things we need sorted before merging:

  1. The checkpoint keeps the wrong message. In the app every session has a workspace, so the first history message is the environment slot ({"role": "user", "env_context": True, ...}, added by AgentSession._sync_environment_context). _original_task() returns it. After /compact the checkpoint ends with ORIGINAL TASK (preserved verbatim):\n<environment_context>…, and the request itself is not kept. To reproduce: run AgentSession(..., workspace=tmp) for a few turns, then await session.compact().
  2. The first message is often not the current task. In a multi-turn session the user may have moved on, or a Goal may have been set or updated later. The newest user message is already kept word for word by the tail rule, and Goal continuation turns re-send the objective. A permanent "ORIGINAL TASK" label would pull the model back to old work.
  3. The kept text is too large. Up to 60,000 characters stay in every later checkpoint. With a 40k-character first message, /compact only went from 52,311 to 48,064 characters (8,015 on main). A little larger, and the "must shrink" rule refuses compaction altogether.
  4. The description cites code we couldn't find. There is no compact_governance and no content[:200] window in the code base, so please drop that part.

A shape we'd accept:

  • Skip the environment slot, checkpoints and runtime notes (is_context_note).
  • Keep the user's own earlier messages, newest first, within a small budget (a few thousand characters), instead of "the first message".
  • Don't label it the original task.
  • Add a test that goes through AgentSession with a workspace and compact().

A short note on a real run where the summary lost the task would help us pick the budget.

@raymondginger2018-sudo raymondginger2018-sudo changed the title feat(agent): embed the original task verbatim in the compaction checkpoint feat(agent): carry the user's own earlier wording across compaction Nov 16, 2026
@raymondginger2018-sudo

Copy link
Copy Markdown
Contributor Author

Thanks — all four points were right, and your reproduction matched mine exactly.

1. The checkpoint keeps the wrong message. Confirmed on a real AgentSession(workspace=…): history starts with {"role": "user", "env_context": True} (229 chars), the request was the second message (6,363 chars), and after compact() the checkpoint contained the environment dump and not the request. The environment slot, checkpoints and empty content are now skipped by shape.

2. It is not "the original task" any more. The heading is neutral: "Earlier messages from the user (most recent first):". Ordering is newest-first under a small budget, exactly as you asked.

3. The kept text is bounded. EARLIER_USER_CHARS = 4_000 instead of 60,000. One detail I hit while testing it: if the newest message alone exceeds the budget, skipping it would drop the user's current words entirely, so that single message is truncated to the budget instead.

Measured before → after on the same session shape:

before after
checkpoint content 608 chars, env-slot text, no request bounded, request wording, no env slot
request survives no yes
ORIGINAL TASK label present absent

4. The description no longer cites code that doesn't exist. compact_governance and content[:200] are gone from the comment.

The test you asked for — test_compaction_in_a_workspace_session_skips_the_environment_slot — builds AgentSession(..., workspace=tmp), submits a long first request plus five follow-ups, sanity-checks that history[0]["env_context"] is True, then awaits compact() and asserts the checkpoint carries no environment text, no ORIGINAL TASK, stays under the budget, and does carry the user's recent wording.

One thing worth stating rather than hiding: is_context_note cannot be applied at this layer. session_message_history_entry only copies metadata for assistant records, so a user-role runtime note has lost its delivery/source by the time compaction sees the dicts — I checked, every non-env-slot user message arrives with no extra keys. So the skip here is shape-based, and the docstring says so. If you would rather the marker survive into history so this can use is_context_note, that is a change to the projection in core/sessions and I would take it as a separate PR rather than fold it in here.

13 tests pass, ruff 0.15.21 check and format clean, rebased onto 3dcb0fb4.

I also revised two assertions this branch had added: they asserted "the original task (MSG0) survives", which is precisely what a newest-first budget stops doing. They now restate main's expectation.

The summary is lossy by design, and the one thing it should not be allowed to
paraphrase away is what the user actually asked for. This carries the user's own
earlier messages over the checkpoint boundary, quoted verbatim.

Two things the first revision got wrong, both visible in a real session:

- **It took "the first user message", which is the environment slot.** Every
  session with a workspace starts with `{"role": "user", "env_context": True}`,
  so the helper returned the environment dump. Measured on a real
  `AgentSession(workspace=…)` + `compact()`: a 6,363-character request was
  replaced by a 229-character environment dump, and the request itself was gone
  from the whole history.
- **It kept up to 60,000 characters under a permanent "ORIGINAL TASK" label.**
  That both swamped the checkpoint and pinned the model to old work — in a
  multi-turn session the first message is often not what is being worked on.

Now: the user's own earlier messages, newest first, under a few-thousand
character budget, under a neutral heading ("Earlier messages from the user (most
recent first):"). The environment slot, checkpoints and empty content are
skipped; a message already in the kept tail is not repeated; a single oversized
message is truncated to the budget rather than skipped.

The block is also bounded by the space the compaction actually freed, minus a
reserve for the runner's PreCompact checkpoint re-injection. Both draw on the
same reduction, and an earlier revision consumed all of it: a neighbouring test
showed the hook's context truncated to three characters. When there is not
enough room the block is simply absent, which is exactly what main does.

Re-compaction re-reads the block from the previous checkpoint, so a second round
does not lose it.

Runtime notes are not filtered by `is_context_note()`: by the time this runs the
kernel history projection has already dropped user-role metadata, so no marker
is left to test. The skip is shape-based, and the docstring says so.

Tests: tests/test_session_compaction.py 13 passed; the neighbouring
tests/test_session_end_lifecycle.py matches main exactly (4 pre-existing local
failures, unchanged). New coverage pins newest-first ordering, the budget,
env-slot/checkpoint skipping, the neutral heading, re-compaction carry-forward,
and one end-to-end case that drives `AgentSession(workspace=…)` and
`await session.compact()`.

Two assertions this branch had added now restate main instead: they claimed
"the original task (MSG0) survives", which is precisely the behaviour being
removed.

ruff 0.15.21 check and format clean.
@raymondginger2018-sudo

Copy link
Copy Markdown
Contributor Author

The first push of this went red on all three Python legs (test (3.12), (3.13), (3.14)), same test:

tests/test_session_end_lifecycle.py::test_maybe_compact_checkpoint_injected_after_success
AssertionError: checkpoint must survive a successful compaction

That was mine, and worth explaining because it is the same constraint the block has to respect.

AgentRunner._maybe_compact refuses a compaction that does not shrink the history, and it bounds the PreCompact checkpoint re-injection by that same reduction:

checkpoint_room = history_chars(messages) - history_chars(compacted) - 1

My block was appended to the checkpoint unconditionally, so it consumed that room. In the neighbouring test the hook's context arrived truncated to [PreCompact checkpoint]\nche — three characters. In the worst case there is no reduction left at all and the whole compaction is refused, so no checkpoint exists.

The block is now bounded by the space the compaction actually freed, minus a reserve for that re-injection:

headroom = before - base_after - len(mark) - _PRECOMPACT_RESERVE   # 1_000
block    = earlier_user_messages(budget=min(EARLIER_USER_CHARS, headroom))

When there is not enough room the block is simply absent — which is exactly main's behaviour — rather than squeezing the hook context out.

Verification, and the reason I trust this one:

  • tests/test_session_compaction.py — 13 passed.
  • tests/test_session_end_lifecycle.py — matches main exactly: the same 4 failures that fail on 3dcb0fb4 on this machine (test_session_end_fires_*, test_session_end_reason_matcher, test_normal_turn_does_not_trigger_session_end), with test_maybe_compact_checkpoint_injected_after_success passing again. I diffed against a clean 3dcb0fb4 worktree rather than assuming.
  • ruff 0.15.21 check and format --check clean.

Two integration tests in that file also had to grow a bulky dropped message: with a toy history the compaction frees nothing, so carrying nothing is the correct answer and the old shapes were asserting a behaviour that cannot happen at that size.

New head: 8f42701f.

@Zongwei9888
Zongwei9888 merged commit 8f42701 into HKUDS:main Nov 16, 2026
12 checks passed
@Zongwei9888

Copy link
Copy Markdown
Contributor

Merged in f187f0d. Thank you for sticking with this one.

You were right that runtime notes couldn't be told apart at that layer. In fact the live history never marked them either. The follow-ups (311f8b6 and dada732) change five things:

  • Runtime notes are marked and skipped. The runner now marks every note it adds; a Steer stays unmarked, since it is the user typing. A Goal prompt Turn carries the mark through UserInput, and a resumed session restores it from the record. The block skips marked messages.
  • Only the replaced range is read, so the retained tail no longer uses up the budget first.
  • Quotes survive a second compaction word for word, indentation included. They are stored in the checkpoint's compaction marker (user_words) and re-read from there.
  • Cut quotes are marked. A quote shortened to fit says so, and with less than 400 characters of room nothing is quoted, so a fragment can't reverse a request.
  • The PreCompact reserve is real. The runner passes the PreCompact hook's actual size as reserve_chars, instead of a fixed 1,000-character reserve.

We also ran a before/after test with a real model. The session set three rules in its first message, then went through two compactions:

  • both versions followed the rules;
  • with this change, the checkpoints carried the rules word for word, and the model could quote them exactly;
  • on main, only the summary's paraphrase survived.

@Zongwei9888

Copy link
Copy Markdown
Contributor

@raymondginger2018-sudo One more thing: we're now steering DeepCode toward recursive self-improvement (RSI), an agent that gets better from its own runs. If you have ideas there, bold ones are welcome. For anything large, open an issue first so we can talk it through before you write the code.

Zongwei9888 added a commit that referenced this pull request Nov 17, 2026
Add the news entry and changelog for the 2026-11-16 community batch
(#289, #293, #303, #307) and fold the 2026-10-31 entry into the
earlier updates. The three points under "What Deep means" now match the
numbered parts of the framework figure, self-evolution is named as
planned, and "Why DeepCode" no longer repeats them.
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.

2 participants