Make `clai2` `/compact` shrink a history just over its protected tail, and report honest savings

Merged
MP
2mo ago
+82-19

/compact could make the conversation bigger. One report read Compacted 186 messages down to 187; about 0 tokens saved.

Cause

/compact runs the plugin's chain with keep_tokens=protected_tokens (50,000 by default). When the history is only a little over 50,000 estimated tokens, harness find_token_cutoff places the cut at message 1. SummarizingCompaction then summarizes only the first request and also keeps that first user prompt verbatim (preserve_first_user_message). The result is a summary, the same first prompt, and the 185 untouched messages: 187 messages and more tokens than before. The plugin committed any result that differed from the input, and clamped negative savings to 0. A history of one prompt, 92 tool rounds, and a final answer at 50,127 estimated tokens reproduces it exactly.

Changes

  • /compact protects min(protected_tokens, half the history's estimated tokens), so it always has an older half to summarize or drop. Automatic compaction keeps the full protected_tokens tail; its trigger and chain are unchanged.
  • /compact commits the result only when it has fewer estimated tokens. Otherwise it keeps the history and says Nothing to compact: compacting would not make the conversation smaller. This covers a summary longer than what it replaces. It also covers an empty or one-message history, which never reaches the summarizer. The old "the last 50,000 tokens are always kept" message is gone, because /compact no longer leaves a history unchanged just because it fits in the tail.
  • The report gives savings against the total: Compacted 186 messages down to 95; about 24,976 of 50,127 tokens saved.
  • The protected_tokens description, the README's "Compacting the conversation" section, and the PLUGINS.md compaction paragraph describe the cap and the no-shrink case.

No setting, stored value, or schema changes.

Verification

  • New test_compact_shrinks_a_history_just_over_the_protected_tail (summarization and truncation) uses the 186-message, 50,127-token history. It fails on main (186 → 187) and passes here: under 100 messages, about half the tokens saved, and an exact report. New test_compact_keeps_the_history_when_the_summary_is_no_smaller checks that an oversized summary is discarded and the history is left as it was. Existing tests now use replies long enough for a summary to be smaller.
  • tests/clai2: 3454 passed and 4 skipped under -n auto. Four subprocess startup tests timed out at 15 s on a cold local .venv and passed on rerun. Branch coverage of builtin_plugins/compaction.py is 100%.
  • ruff format --check, ruff check, and pyright on the changed files are clean.
  • tmux, uv run clai2 -m test with an isolated XDG_CONFIG_HOME: /compact keep the detail printed Compacted 8 messages down to 4; about 31,001 of 41,409 tokens saved.

Checklist

Prepared with Claude Opus 5.5.