Skip to content

feat(agent): evidence-backed compaction strategies, and retire the legacy path - #715

Merged
huichen merged 115 commits into
mainfrom
feat/compaction-evidence-strategies
Sep 18, 2026
Merged

huichen merged 115 commits into
mainfrom
feat/compaction-evidence-strategies

Conversation

@huichen

@huichen huichen commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator

What this is

Evidence-backed work on context compaction: it measures the two retention strategies against
the deployed algorithm and two pinned external policies, changes the runtime where the
measurement showed it was wrong, and retires the legacy compaction path.

114 commits, 75 files, +12 982 / −2 301. It is large and it mixes concerns that would
normally be separate PRs — see Should this be split? below, and say so if you want it
carved up.

The measurement

Two experiments, each with a report under docs/internals/compaction/, each reproducible from
scripts/compaction_experiment/.

Closed book (report) —
five retention strategies on six frozen chains (24 boundaries, 178 questions), at the runtime's
own call shape: registry window, effective_max_tokens, set_request_budget with the
session's prompt and real tools, production's trigger. Every arm is forced to compact so the
table measures retention rather than the trigger.

Arm Recall Median projection Compaction (cached) Per turn Break-even
summarized 147/178 (83%) 12 113 tok 0.53 0.000480 61 turns
deterministic 127/178 (71%) 9 945 tok 0 0.000394 immediate
opencode 83/178 (47%) 5 152 tok 0.99 0.000204 110 turns
main @ 7e268efe 68/178 (38%) 3 418 tok 0.83 0.000135 91 turns
codex 68/178 (38%) 1 706 tok 0.42 0.000068 46 turns

The deployed algorithm keeps about a third of what the runtime default keeps, and cost per
point of recall runs ~3× worse. Real-session half: 76% vs 30%. No false positives anywhere.

Open book (report) — does
the model recover what compaction dropped, given the archive is still reachable?

Recall Tool calls
closed baseline 147/178 (82.6%) 0
tools + production prompt, no instruction 148/178 (83.1%) 0
…with the guidance rewritten to be affirmative 149/178 (83.7%) 0
…with the exam wording stripped of "the record" 145/178 (81.5%) 0
…with an explicit verification instruction and one forced call 166/178 (93.3%) 100

Answer: retrieval does not happen on its own. Three prompt variants, 54 cases, zero calls.
27 of the 178 values sit in the archive and are never looked for, identically in all three;
the required variant recovers 20 of those 28 by searching. So the gap is behavioural, not a
capability a wording can unlock — and since a page of guidance only ever described a capability
the model already had, the guidance is gone.

Runtime changes

  • The recall guidance is removed (agent/src/agent/history_recall.rs deleted, with the
    flag that existed to gate it). A session's system prompt is its own and no longer changes
    when a checkpoint is committed. The retrieval CLI is retained in full.
    This is a breaking change in the sense that every existing session's cached prefix
    invalidates once, and that nothing now tells a model the history CLI exists.
    Worth a look in review: the earlier guidance had the side effect of naming the session id.
    A model must now name it itself, which is what a session faces anyway, but it is a real
    behavioural consequence of removing the section.
  • Trigger at 80% of the window with no absolute cap — the old 256 000 ceiling meant a 1M
    window compacted at 26%; effective ceiling is now 128K of expanded history.
  • Checkpoint schema 3 only. The reader no longer accepts older schemas; retired A-era rows
    are carried through untouched rather than reinterpreted.
  • The legacy A implementation is deleted — entry points, serialiser, chunking, emergency
    summary, and the orphaned Go-compatibility API with its 22 tests.
  • Two algorithms are named for what they do: deterministic-evidence-v1 and
    summarized-evidence-v1, replacing the C/C3 labels.
  • A manual /compact now sends the session's system prompt, not the bare base prompt.

Also in here

  • New: history query as a production feature — history_query.rs (literal, bounded,
    session-scoped, thinking excluded), the two RPC commands, and future session history search|get.
  • Experiments: scripts/compaction_experiment/ is a new directory. It is the surviving
    two experiments — 114 superseded scripts and 14 protocol documents were deleted, and the
    839-line A/B/C/M harness was reduced to the three functions the survivors used.
  • Docs: the compaction guides moved under docs/internals/compaction/, plus the two
    reports. session-history.md moved to docs/guide/.

Verification

  • cargo fmt --all --check, cargo clippy -p future-agent -p future-cli -p future-rpc --all-targets -- -D warnings: clean, 0 errors.
  • cargo test: future-agent 1779, future-cli 733 (+11 bin), future-rpc 116 — all
    passing. (future-cli's bin.rs agent-singleton flake appeared once and passes on re-run;
    it is documented as pre-existing in .future/memory/testing-gotchas.md and is unrelated to
    this branch.)
  • scripts/test_s2_compaction.py --binary target/debug/future: PASS 124 checks. This one
    caught a genuine breakage — it still asserted the guidance this branch removes — which is
    fixed in the last commit.
  • scripts/compaction_experiment/verify_request_shape.py: 15 checks, offline — the prompt is
    the session's own, does not change across a checkpoint, the tool definitions from the probe
    and the executor agree, future session history is present and usable, and the executor
    refuses a path outside the case and a tool production does not install.
  • run_open_book.py --smoke: exercises the archive end to end with no model call.
  • scripts/check-docs.py: 21 findings → 4, all four pre-existing under mobile/docs/ and
    untouched here.

Should this be split?

Three separable pieces, if you would rather review them independently:

  1. Runtime — trigger, schema, naming, legacy deletion, guidance removal, manual-compact
    prompt. (agent/, cli/, packages/rpc/)
  2. History query as a feature — the CLI and the two RPC commands.
  3. Experiments and docs — scripts/compaction_experiment/ and the reports.

As one PR the squash-merge produces a single commit describing all three, which loses the
distinction. I am happy to split it if that is preferred; the commit history is already
grouped along those lines.

Reviewer notes

  • The cache-cost columns are modelled, not measured. The runs' own cache counters are
    contaminated (arms prime each other, and a later run reuses a prefix an earlier one left),
    so the report prices every arm at a fixed 98% hit anchored to one production measurement of
    99.8%, and says so.
  • The open-book +19 is an upper bound, not a production result. It exists only in a variant
    where the exam itself requires verification, which production does not do. Every place it
    appears is labelled.
  • Isolation is partial and the report says so. Production's file tools accept an absolute
    path without consulting the rule-based denials, so the harness bounds them with
    allowed_roots; shell is not bounded the same way and 18 calls in the recorded run reached
    paths outside the case. Nothing reached an answer, but check traces/ before quoting.
  • --main-commit is now required on the closed-book run: a binary path does not identify the
    code it was built from, and an unlabelled main column rots as the release moves.

…ummary

Compaction now commits C's projection (protected user and assistant originals,
deterministic evidence index, recent tail) plus a model-written handoff summary
that receives the previous summary, so facts accumulate across successive
compactions instead of being rewritten each time.

- evidence.rs: stage()/finalize() split, so the synchronous C path and the
  summary path share planning and evidence selection
- evidence.rs: the summary budget is at most a third of what the evidence budget
  can spare, so a tight budget yields no summary rather than an unusable index
- durable.rs: admission is split from computation; the strategy participates in
  the idempotency key so a summarised and an unsummarised run never replay each
  other's receipt
- durable.rs: a failed summary falls back to plain C instead of failing the
  compaction; the fallback is reported and logged
- run_loop.rs: automatic and provider-limit compaction use the summarised path
- manual compaction in rpc/session.rs stays deterministic (its worker thread has
  no async runtime) and is unchanged

Tests: the old tripwire asserting automatic compaction never summarises encoded
the superseded contract and is replaced by two cases, one proving the summary is
consulted exactly once and both halves are committed, one proving a failing
summary still yields a usable deterministic checkpoint.
…marises too

The summary now reads the live conversation as real messages with the instruction
appended last, instead of a flattened evidence string, and reuses the agent's own
system prompt. Providers cache on the request prefix, so reusing the turns the
session already sent lets the request be served from cache (measured 99.9% on a
258K-token prefix, about 48x cheaper than the same input sent cold), while a
flattened request shares no prefix and is billed in full every time. This also
fixes what the summary reads: the live conversation, not a deterministic index of it.

Manual compaction (the /compact command and "future session compact") now summarises
as well. Its worker is a plain thread with no async runtime, so the sync entry point
drives the async core on a temporary current-thread runtime; the summary is only
attempted when a provider is reachable, and a failure still falls back to
deterministic C.

prepare_with_journal is removed: the summarised entry point with provider=None is its
exact equivalent, and keeping both left the deterministic one dead outside tests.

Tests updated where they encoded the superseded contract: providers identify a
summary request by its trailing instruction rather than by the summariser system
prompt, and the manual path asserts one summary call followed by a replay that asks
for nothing.
…its tests

Follow-up to the entry-point removal: with nothing able to reach the legacy A
algorithm, keep it as `#[cfg(test)]` would have left ~450 lines and 22 tests in
the repository for no reader but themselves. Delete both.

Gone: `prepare` / `prepare_deterministic`, `summarize_with_replan`,
`summarize_fold`, `summary_chunk_budget`, `take_next_chunk`,
`split_to_token_budget`, `call_summary_model`, `call_summary_model_bounded`,
`valid_summary`, `emergency_summary`, `collect_file_operation`, `join_or_none`,
the `Strict` serialization mode and the three summary-fold reserve constants.
Tests deleted with them: the fold, the chunking, the emergency summary, the
strict replan, the legacy retry arms and `prepare_deterministic`.

Tests whose *subject* is still production behaviour were ported rather than
dropped, so the coverage does not walk out with the code:

* eleven `plan()` / boundary tests now call `prepare_evidence`
  (manual-aggregate rules, the unattended-prompt guard, the downshift window
  check, the checkpoint-marker-lookalike case, the small-window rule);
* the twelve `summary_model_*` tests now drive `call_summary_model_with_messages`,
  which is what C3's summary request actually goes through — they cover the
  shared event handling, so they were worth keeping;
* assertions that inspected the legacy *request* (its output cap, its message
  array, its provider call count) are replaced by the C-path equivalents: the
  committed algorithm, the protected originals in the projection, the evidence
  index. A C compaction makes no model call at all, so "the provider was asked
  once" was not a meaningful claim for it.

Two tests moved to the production path for the same reason earlier:
`legacy_semantic_checkpoint_recovers_originals_before_s2_upgrade` (the read-side
compatibility this machine's five `semantic-v1` checkpoints depend on) now runs
through `prepare_evidence`.

Test count 1830 -> 1808, all passing. The shipped binary still contains none of
the deleted names (`nm -C target/debug/future`), and `docs/compaction-prompts.md`
now says outright that the page is a record of the retired path, not of a
callable API.
The economic trigger was `min(floor(W * 0.8), 256000)`. The cap only bound windows
above 320K, and on a 1M-token model it held the trigger at 256K — a quarter of the
window — so sessions compacted with three quarters of their capacity unused. Drop
the cap; the trigger is now simply 80% of the declared window.

Nothing else needed to change: `effective_trigger` already clamps to
`W - O - margin`, so a model whose output reservation leaves less input room than
80% keeps its real limit. For a 1M-token window with a 384K output reservation
that clamp is ~639K, which is the practical trigger (up from 256K). Smaller
windows are unaffected: 128K still triggers at 102 400.

Two consequences worth stating:

* the compaction that fires now summarises a much larger live conversation. That
  request reuses the turn's prefix and is normally cache-served, but a cold cache
  means paying for the whole prefix in one call;
* `reserve_tokens` is part of the durable idempotency key, so keys derived from
  the old trigger no longer match and a session may compact once more than it
  otherwise would. The policy genuinely changed, so that is the correct outcome.

`tests/test_s2_compaction.py` needed fixing to stay valid, and while there it
turned out to be stale independently of this change: it classified a summary
request by the legacy A marker ("context summarization agent" in the system
prompt), which C3 never sends — C3 reuses the *session's* prompt. Every summary
request was therefore counted as an ordinary one, shifting the fixture's scripted
turns and failing from `6a83a34a` onwards (verified by running the script against
the unmodified tree: same assertion, same line). It now classifies by C3's
appended instruction, asserts that the summary request carries the session's own
prompt and tool definitions (the property a substituted prompt would break), and
rejects that request with a non-retryable status so the deterministic fallback is
what gets committed — the usage and checkpoint assertions are unchanged. The
fixture history grows to 36 tool results (~867K estimated tokens) to cross the
new trigger; PASS: 119 checks.
The previous commit described the trigger clamp abstractly and the commit message
guessed "~639K". The actual value for this machine's 1M-token models is
613 952 = 1 000 000 - 384 000 - 2 048, and the same window declaring a 16K output
ceiling triggers at 800 000 (unclamped). State both, with the arithmetic.
`MAX_EXPANDED_HISTORY` is the budget the protected assistant originals compete
for (user originals are never dropped). It was 64 000, and the previous commit
let sessions grow to 613 952 tokens before compacting instead of 256 000 — so
histories can now reach a size where that ceiling binds.

Measured on all 45 sessions of a real Agent database, running the production
planner with no model call:

  * nothing is being demoted today. Both builds produce identical projections
    (45/45), and the retention note never appears. So this is headroom, not a fix
    for an observed loss — worth saying plainly, because the earlier framing
    ("64K is already at the entrance") overstated it.
  * the largest session (634K tokens of history) fitted with **281 tokens to
    spare** at 64 000: its projection used 63 719 of the 64 000 target, which is
    the same 281-token margin as the assistant budget
    (`output_room = 64 000 - 14 335 = 49 665` against 49 384 kept). One more small
    assistant reply would have started demoting.

At 128 000 that session's assistant budget becomes 113 665 instead of 49 665, and
the ceiling still yields to capacity on smaller windows via `min(ceiling,
(limit - fixed) * 3/4)`: 82 176 on a 128K window, 96 768 on 262K.

The two tests that verified this mechanism hard-coded a 300 000-character
original, which was "bigger than 64K" but is smaller than 128K, so they now size
that fixture from the constant (`oversized_original_len`) and keep asserting the
mechanism rather than a number.

Trade-off, as with the trigger change: the projection is the stable context resent
every turn. A very large session can now retain up to ~128K of history instead of
~64K, so its per-turn input grows by that much (priced through the prefix cache).
The paragraph said the old checkpoint "remains readable" and that C rebuilds
evidence rather than recursing into A's summary, which leaves the question this
answers — is the old checkpoint skipped, and does that cost another compaction?
— to inference. It is not skipped:

* `project_prompt_context` re-projects every user/assistant original in the covered
  range from the intact journal and clears the protected marker, so the new
  algorithm can select them again;
* `plan` then refuses to move coverage behind the checkpoint already in the
  projection (`cut = max(cut, checkpoint_index + 1)`), so the old summary falls
  inside the new covered range and is replaced;
* `protected_entry_ids` is re-derived over the whole range rather than inherited,
  which is why retention usually improves rather than degrades.

The cost is one extra summary call for that session — once, not per turn, since
the next checkpoint is written by the current algorithm and no longer qualifies
for the legacy path. `legacy_without_cutoff` (the released string protocol, whose
covered prefix old versions deleted) is the exception: nothing to recover, so the
old summary is carried forward instead.

Verified against the production functions: with a checkpoint rewritten to
`semantic-v1` / empty `protected_entry_ids`, the projection handed to the planner
is `[u1, a1] + [old checkpoint] + [u2, a2]` and the committed result is
`deterministic-s2-evidence-v1` with `protected_entry_ids = [u1, a1, u2, a2]` and a
cutoff past the old one — the sentinel text of the old summary is gone.
Only schema 3 and the two current algorithms exist now. A checkpoint written by a
retired algorithm is no longer recognised: `latest_context_checkpoint` skips it,
`project_prompt_context` sees no boundary and projects the session's own journal in
full, and the next compaction re-covers that history with the current algorithm.
The retired row stays in the journal as an inert entry that nothing reads, so it can
neither shrink nor expand a prompt.

Removed, per the earlier discussion of what this costs:

* the legacy-recovery branch that re-projected covered originals and cleared their
  anchor marker so a new checkpoint could re-select them;
* `legacy_without_cutoff` (the released string protocol: `legacy_string_checkpoint`,
  `legacy_checkpoint`, and the projection's marker-skipping cutoff branch);
* schema-2 acceptance in `compaction_entry_to_checkpoint`, which also drops the
  `unwrap_or("v2")` default — `algorithm_version` is now required;
* the same acceptance in `fork` (a retired-schema row is carried through untouched:
  nothing reads it, so nothing can dangle) and in legacy import validation (it is
  imported as an ordinary entry).

One latent bug fixed on the way: `checkpoint_to_entry` derived `schema_version` from
`protected_entry_ids.is_empty() || algorithm.contains("-s2-")`, and
`c3-sticky-summary-v1` contains neither, so a C3 checkpoint that protected nothing was
written as schema 2 — and would have been rejected by this very change. It now always
writes schema 3 with the list present.

Behaviour on the four sessions in this machine's database that hold A-era
checkpoints, run through the production planner: all four re-compact with the current
algorithm, retaining 171 / 20 / 10 / 4 protected originals and no demotions. Cost is
one request whose input is the full journal (normally prefix-cached, since the turn
just sent it) and one extra summary call each, once.

Tests updated rather than dropped where the subject survives: the retired-schema cases
now assert non-recognition, fork's drop cases use the current schema, and the import
test keeps its dangling-range coverage while a new one records that a retired-schema
row imports inert. Three tests whose only subject was the removed mechanism are gone.
… API

Answering "are only two algorithms left": they are not. Besides the two that write
checkpoints, `compaction::compact(Vec<Message>, &CompactOptions)` was still present —
a third, older strategy with its own cut-point heuristics and char-based estimation,
kept for compatibility with the Go implementation this module was ported from. It has
no caller anywhere in the workspace (the 200-odd `compact(` hits are
`ServerSession::compact`), and the same is true of everything only it reached:

  compact, compact_from, should_compact, find_valid_cut_points, find_cut_point,
  adjust_cut_for_tool_context, extract_file_operations, estimate_context_tokens,
  CompactOptions, CompactionResult

Gating the entry point off made the compiler call `adjust_cut_for_tool_context` and
`compact_from` dead, which is what confirmed the cluster's extent. `estimate_tokens`
and `estimate_text_tokens` stay: the surviving `projected_token_cost` uses them. The
module doc no longer claims Go compatibility; it names the two real strategies.

Tests go with their subject (22 of them). Test count 1804 -> 1782, all passing.
`ALGORITHM` / `ALGORITHM_STICKY` and their persisted values
`deterministic-s2-evidence-v1` / `c3-sticky-summary-v1` encoded history rather than
behaviour: "s2" and "c3" are experiment arm labels, "sticky" describes how the
summary is written (each receives the previous one) rather than what it is for, and
a bare `ALGORITHM` read as if there were only one. The pair differs by exactly one
thing — whether a model writes the handoff summary — so the names now say that:

  ALGORITHM_DETERMINISTIC   "deterministic-evidence-v1"
  ALGORITHM_SUMMARIZED      "summarized-evidence-v1"

and the "sticky" identifiers become "handoff", which is what the prompt template and
the docs already called the summary:

  STICKY_HEADER            -> HANDOFF_SUMMARY_HEADER
  STICKY_SUMMARY_TOKENS    -> HANDOFF_SUMMARY_TOKENS
  sticky_summary()         -> write_handoff_summary()
  prepare_with_sticky_summary()      -> prepare_with_handoff_summary()
  prepare_with_journal_summarized()  -> prepare_with_journal_and_summary()

The evidence index header loses the arm label too ("Deterministic C evidence index"
-> "Deterministic tool-evidence index"), including in the two headers whose first
sentence states whether a summary follows. Prose that said "plain C" or "strategy C"
now names the strategy.

Consequences worth stating:

  * `algorithm_version` values change for newly written checkpoints. Existing
    schema-3 checkpoints (the only schema read) keep working and simply report the
    old string — nothing validates the value on read.
  * the values participate in the durable idempotency key, so a session that
    compacts after this will not replay a receipt written before it. One extra
    compaction per session, at most.
  * the C / C3 shorthand stays in the experiment docs, because the recorded
    measurements use it; the main document now carries a table mapping the two
    names to those arms.

The experiment scripts (`test_s2_compaction.py`, `four_arm_rerun.py`,
`c3_e2e.py`, `c3_composition.py`) match the header and the values, so they would
otherwise have failed; their assertions are updated with it.
…, with the deployed arm

The earlier closed-book runs drove the Rust arms with a simulated 128K window, no output
reservation and no request budget. That is a usable matched-size retention comparison, but
it is not what production computes, and it never exercised the deployment's own trigger.

`abc_strategy_probe.rs` calls the two current entry points the way the runtime does:

* the window comes from the model registry and the output reservation from
  `effective_max_tokens` — on this model 1 000 000 and 384 000, so the economic trigger is
  613 952;
* `set_request_budget` runs at the call site with the session's system prompt and the real
  tool definitions. Omitting it leaves `fixed_input_tokens` and `output_reserve_tokens` at
  zero, which raises the effective limit and compacts later than production — the first
  version of this driver made exactly that mistake;
* both prompts the runtime derives are built through `history_recall::system_prompt`
  (public now, so a driver cannot drift by re-implementing the text): the budget prompt
  always reserves the recall guidance, the outgoing one carries it only once a checkpoint
  exists;
* trigger and phase default to an ordinary pre-turn compaction, and `--print-limits`
  reports the registry numbers so the harness schedules against production's own values.

`abc_main_probe.rs` adds the **deployed algorithm** as an arm by building inside a checkout
of the released branch and calling that checkout's own entry point and budget rules. It
replaces `abc_compaction_arm.rs`, which called the now-removed `prepare_semantic` and
cannot build against this branch.

`production_shape_rerun.py` reports the axes the question needs, because no single one is
the answer: recall, projection size, compression ratio against the shared input, and
compaction cost kept separate from scoring cost. It runs both ways — `--force-compaction`
uses Manual, which bypasses the economic trigger, so every arm compacts at every boundary
and the comparison is post-compaction against post-compaction. Without it the Rust arms
often never compact (6 of 24 boundaries on this model) and their quality column would
describe the trigger rather than the retention policy.

Also fixes a boundary bug this exposed: `four_arm_rerun.schedule` pair-checks its chunk
boundaries but appends the forced scored cuts unchecked, so two real-session cuts landed
inside a call/result pair and the shared normalizer refused the segment. `safe_cuts` moves
each cut back to a pair-complete, message-complete endpoint, as the fidelity protocol
always required.

`capture_shape.py` records the system prompt and tool definitions of a real turn from an
isolated agent, since a frozen session's prompt is rebuilt per turn from its working
directory and cannot be replayed.

Results and their limits are in docs/compaction-abc-experiment.md; the protocol is
scripts/abc_experiment/PRODUCTION_SHAPE_PROTOCOL.md.
The cost column was the ledger's charge, which is the cold price: these runs do not
reproduce the production prefix, so nothing is cache-served. Production does not pay that —
on this model a cache read costs 0.02 CNY per 1M tokens against 1.0 for fresh input, 50×
cheaper — and whether a strategy can use it is decided at token 0, by its system prompt.

Eligibility, recorded in `CACHE_ELIGIBLE` with its reason beside it:

* `summarized` — yes: it passes the session's own system prompt and tool definitions and the
  live conversation as real messages. The deployed path measured 99.8 % cache read in
  production, which is what the 0.98 stand-in is anchored to.
* Codex — yes: it reuses its base instructions.
* `main` — no: it substitutes its own `SUMMARY_SYSTEM_PROMPT` constant.
* OpenCode — no: it sends a dedicated compaction system prompt.

`report.json` now carries a `cache_cost` block pricing every arm at those rates, plus the
per-turn cost of the projection it decided to send — the recurring cost a smaller projection
buys down, and the one a one-off compaction figure hides. `--print-limits` reports the
registry's rates so the model tracks the code instead of hard-coding them, and the model-free
strategy is seeded at zero rather than omitted, which read as "unknown" rather than "free".

What it changes (fair run, 24 boundaries, 1 compaction + 100 turns):

  arm             recall  proj tok  cold    cached  per turn  total
  summarized        83%   12,503    7.98    0.53    0.00050   0.58
  deterministic     71%   10,233    0      0       0.00041   0.04
  codex             38%    1,821    7.64    0.42    0.00007   0.43
  opencode          47%    5,372    0.99    0.99    0.00021   1.01
  main              38%    4,027    0.83    0.83    0.00016   0.84

The cache inverts the ranking: cold, `summarized` is the most expensive strategy in the set;
cache-served it is cheaper than the deployed algorithm while answering 45 points more. Per
point of recall the deployment is ~3× worse (0.0221 against 0.0070).

Two structural findings the pricing exposed, both verified in the recorded checkpoints:

* the deployed arm does **not** re-read the originals. After its first checkpoint
  `covered_from` is the previous checkpoint's entry id, so each summary folds "previous
  summary + new range" forward. That is why its requests carry 11× fewer input tokens
  (695 775 against 7 762 538) — and also why its recall is 38 %.
* a private system prompt costs it ~5× on compaction: priced at the same hit rate its own
  requests would come to 0.16 CNY instead of 0.83. What forfeits the cache is choosing a
  bespoke summariser prompt, not the amount of text sent.

The runs' own cache counters are not evidence for any of this and the protocol says so: the
arms prime each other, and one recorded batch showed a 100 % hit on a prefix an earlier
aborted run had left in the provider's cache.

Also fixes a reporting bug in `abc_main_probe.rs`: it never incremented its call counter, so
every main-arm artifact claimed `model_requests: 0`. Counts only; the ledger's usage and
charges come from the provider.
… costs

Two requests, and the second one caught an error of mine.

**Structure.** The docs root held six content docs; the compaction five
(`compaction.md`, `-abc-experiment`, `-development`, `-prompts`, `-retrieval-mechanisms`)
and `session-history.md`. `internals/` already groups per-module working docs by
subdirectory (`desktop/`, `mobile/`, `tui/`), so the compaction cluster goes to
`internals/compaction/` and `session-history.md` to `guide/`, which is where the index
already listed it. The docs root is now just the two READMEs.

That also fixed a real inconsistency: the three developer docs were listed under
"Archives" in the index while being current, not historical. They are now one
`compaction/` bullet under Internals. All relative links were rewritten for the new depth
(verified: every relative link under `docs/` resolves; the only two the checker flags are
pre-existing false positives in an archive file where a `docs/*.md` glob appears in prose).

**Why `deterministic` is not zero.** The table conflated two different quantities.
Compaction cost is what *building* the projection costs, once; per-turn cost is what
*carrying* it costs on every later turn. A model-free strategy has the first at exactly 0 —
its `calls`, `prompt` and `completion` are all zero and it is priced at 0.0000 in both
columns — and the second above zero, because its projection is smaller than the raw
history, not absent. Its 0.04 CNY is entirely 100 turns × the 0.000406 CNY of re-sending
10 233 tokens.

The table now says so, and adds the baseline that makes the per-turn column readable: the
no-compaction history (median 249 142 tokens, 0.009866 CNY/turn cache-served), which every
arm's per-turn figure is a 20–135× reduction on. `report.json` carries the same baseline and
a `per_turn_vs_no_compaction` ratio.

**A claim I had to retract.** Writing that section up, I first stated compaction "pays for
itself in about a turn and a half". That was wrong by an order of magnitude and is now
measured: the one-off compaction needs **43–103 turns** to repay (56 for `summarized`, 85
for the deployment, 43 for Codex). Compacting is a net cost for a short session; what it
buys is recall and context headroom, not money. The docs say that instead, and the report
now carries a `breaks even after` figure so the claim is checkable.

Two derived ratios were also recomputed rather than left at their earlier roundings: the
handoff summary costs ~12× more per point of recall than not summarising (0.0070 against
0.00057), and the deployment ~3× more than `summarized` (0.0221 against 0.0070).
…two summary results

Cleanup pass over the compaction document set. Net -155 lines, and one factual
correction that matters more than the rest.

**Deleted `compaction-prompts.md` (+zh).** It documented the retired legacy A path in
detail — the fold, the chunking, the emergency summary, the serialiser, the per-chunk call
accounting — for a path no caller can reach. The parts that are still live (the fallback
system prompt, the appended instruction and template) live in code, and duplicating a
constant in prose only invites drift. The live mechanism is now described in `compaction.md`
under "The summary request".

**The summary's contribution is not a constant, and the docs said it was.** `compaction.md`
claimed every exam "fails to find a benefit: closed-book scores are identical with and
without it", and the ablation section concluded "the model summary does not contribute
content on any measurement available here". Both were true at the 128K shape and are false at
the production shape I measured in the previous commit: there `deterministic` contained
130/178 values and scored 127, `summarized` contained 151 and scored 147.

The two are consistent, and both documents now say so: how much the summary adds depends on
how much of the examined material the projection already retains. At 128K the deterministic
projection alone covered 130/178 (73%) so the summary was a strict subset and added nothing;
at the production shape the same 130 were covered and the summary added values on top. They
are endpoints of one variable that neither run varies deliberately, which is the experiment
this document still lacks.

**Removed history and redundancy elsewhere:** the C/C3-naming-explained-inline paragraph,
"an earlier cap of 256 000 only made large windows compact early", "up from 256 000", "it
does not call A to learn how long a summary would have been", the retired-A pointers in the
developer guide and the index, and the two "previously the manual path sent the bare base
prompt" asides. `compaction.md` and `compaction-development.md` now use
`deterministic`/`summarized` throughout with one naming note; the experiment and retrieval
docs keep `C`/`C3` because their recorded tables and artifacts are labelled that way, and
each states the mapping. The 128K cost table no longer re-argues that cold figures are an
artefact — the production run prices that properly.

**One stale comment in the code**, which is where my own error came from: `stage()`'s doc said
"the reservation is at most a third of what the evidence budget can spare", describing the
behaviour the code below it had already replaced — the allowance is `min(W/16, 4096) + 512`,
added *beside* the evidence budget so a summary never shrinks the index. Corrected, and I
verified the doc's claim of `min(2048, W/8)` on small windows against `plan()` while I was
there.

Also fixed the harness README's arm table, which still listed the retired A/B/C/M arms and
called `C` the current default.
Per review: the report should carry the exact `main` commit, drop out-of-repo links
and the historical C3 naming, not import the older run's material, and keep only the
closed-book result — open book will be rewritten separately.

**Pinned the deployed arm.** `main` is `origin/main` @ **`7e268efe`**, built in a detached
worktree of that commit; the table and the text both say so, with a note to re-check
`git log -1 origin/main` before quoting the numbers. The harness could not record this —
a binary path does not identify the code it was built from — so `--main-commit` is now a
required argument and lands in the manifest. Both completed runs' manifests are backfilled
with the commit they measured, which closes a real reproducibility gap: an unlabelled `main`
column rots silently as the released branch moves.

**Removed the older run's content** rather than carrying it forward: the 128K closed-book
table, the 128K ablation, the continuation exam, the compression-pressure sweep, the
composition breakdown and "why C is only slightly ahead". Those belong to the earlier
protocols, which are still in the tree as the historical record. What survives is the
production-shaped closed-book run, and the report is 236 lines against 795.

That deletion costs one thing worth naming: the summary's contribution was previously
argued from the 128K ablation's "adds 0 values". The report now states it from *this* run —
130 of 178 values in the deterministic projection against 151 in the summarised one — and
says plainly that the figure is conditional on how much history the projection must drop,
which neither run varies deliberately.

**Open book is gone**, sections and all, as requested.

**C3 naming is gone** from every live doc, not just the report: `compaction.md`,
`compaction-development.md` and both retrieval guides now use `deterministic` /
`summarized`, and the mapping notes that explained the old labels are removed because the
report no longer uses them. Historical protocol files and `docs/archives/` keep the arm
labels their recorded artifacts use; the index says not to rewrite those.

**Also fixed a median bug in the harness**, which my previous commit had propagated into the
docs: `xs[len(xs) // 2]` takes the upper-middle element rather than the median, so it
disagreed with the `statistics.median` used elsewhere. Corrected figures, all from the same
runs: median projection 12 113 (was 12 503) for `summarized`, 3 418 (was 4 027) for `main`,
and the no-compaction baseline 232 777 tokens (was 249 142 — the earlier number came from the
same bug, and my "correction" of it last commit was wrong in the other direction). Derived
ratios were recomputed from the corrected values: break-even 46–110 turns, per-turn
reduction 19–136×, cost per point of recall 0.0070 / 0.0112 / 0.0220 for
`summarized` / Codex / `main`.

Links: every markdown link in these documents resolves inside the repository, and there are
no external URLs to strip. Anchors were checked too.
The open-book arms measured an adaptation, not the product. Three substitutions had
crept in, and each is now removed at its source rather than patched at the call site.

**The prompt.** The exam sent the examiner's own text as the system prompt
(`b.SYSTEM`), so the model never saw the prompt a session sends. It now sends
`history_recall::system_prompt` verbatim — the captured base prompt plus the recall
guidance the runtime appends once a checkpoint exists. New `--print-request-shape` on
`abc_strategy_probe` emits it, and `production_shape.RequestShape` fetches it, so the
text is the Rust function's output rather than a transcription that can drift.

**The tool names.** `recall_guidance` extracted the guidance from `history_recall.rs`
by regex and then rewrote it: "use the existing shell tool" became "use these read-only
adapters of the native Future history CLI", and the two `future session history ...`
commands became `history_search(query=...)` / `history_get(entry_id=...)` — tools no
product exposes. `autonomous_open_exam.schemas` then offered exactly those invented
tools. Both substitutions are gone: the guidance is passed through unmodified, and the
Future arms take their definitions from `coding_tools()`. Without a shape they now
refuse rather than quietly falling back to the adapters.

**The dispatch.** Tool calls ran through `future_call`, an adapter implementing the
invented pair. They now run through `abc_future_shell_probe`, which looks the name up in
production's `coding_tools()` and calls that handler, so the arms execute exactly the
capability the runtime has — and refuse any name outside it.

One safety consequence, handled rather than hidden: `read`/`write`/`edit` resolve an
absolute path as-is and do not consult the rule-based denials (`run_read` reads whatever
it is given), so offering production's whole tool set without a boundary would let a
replay read sibling fixtures. The executor now takes `allowed_roots` and refuses any path
outside them, for every tool. That is harness isolation on top of production handlers,
which is what the existing `denied_reads` comment already claimed and what `shell` got
from the OS sandbox but the file tools never did.

Verification, offline and without model calls:
  * `verify_production_shape.py` — 18 checks: the prompt is byte-identical to the Rust
    output and carries the guidance; the guidance names the real commands and the shell
    tool and contains no renamed adapter; both sources agree on the tool definitions;
    the executor serves a real call, refuses a path outside the roots, admits an explicit
    root, and rejects a tool production does not install.
  * `verify_guided_production_shape.py` — 14 checks on the guided path, including that
    base + guidance reproduces the production system prompt exactly.
  * `test_recall_guidance.py` asserted the substitutions (`history_search(query=` must
    appear, `--session` must not); it now asserts the opposite and that a Future arm
    without a shape raises. `test_autonomous_open.py` passes a shape.

Two smaller fixes found on the way: `guided_base` prepended its own separator to guidance
that already carries production's, leaving four newlines where a session has two; and
`Guidance` read every source eagerly, so a Future-only run required the Codex and
OpenCode checkouts — reads and derivations are now lazy.

`native_open_exam.py` is fully converted (production prompt, tools and dispatch).
`autonomous_open_exam`, `guided_open_exam`, `full_history_exam` and
`history_trigger_calibration` now take `--shape-probe --base-prompt` and use production's
prompt and tools, but they reuse frozen artifacts from earlier runs, so their recorded
results must be regenerated before they can be quoted.
`open_one_arm.py` runs one arm's open-book exam end to end against a production-shaped
closed run: read that arm's frozen projection, build the request with production's system
prompt and tool definitions, let the model call those tools, execute the calls through
production's handlers against an isolated archive of the same history, and score the answer
the way the closed run did. `--smoke` validates the whole path with no model call, and
`--require-retrieval` adds the verification instruction and forces one tool call.

Run for `summarized` against `v4-forced` (18 cases, no report document written; the runner
keeps only its ledger, traces and per-case results):

  closed book                                       147/178 (82.6%)
  tools available, no instruction to verify         148/178 (83.1%)
  verification required, tools actually used        166/178 (93.3%)

Two findings that matter more than the delta.

**The model does not retrieve unless told to.** In all 18 autonomous cases it called no
tool at all and answered from the projection, so that variant is a closed-book run with an
unused tool list — the +1 is noise. This reproduces the nonuse behaviour the repository
already recorded; it means "open book" is a property of the exam, not of the tools being
present. All the gain comes from the required variant, and the production prompt and tool
availability by themselves account for none of it.

**The +19 is real but needed checking.** Every one of the 28 recovered values was traced to
the tool call that produced it: all 28 came from `future session history search/get` against
the isolated archive, none from a host file. The gain is therefore attributed to history
retrieval rather than to a fixture leak. (My first attribution pass said the opposite; it
mis-parsed `arguments`, which is a JSON string rather than an object.)

**A real isolation gap, demonstrated.** Production's file tools resolve an absolute path
as-is and never consult the rule-based denials, so the executor now bounds them with
`allowed_roots` — that check blocked one `read` here. `shell` is not bounded by it: 18 shell
calls named a path outside the case and 14 returned non-trivial output from the operator's
own filesystem, including the real `~/.future`. None of it reached an answer, but a replay
that can read the host can be contaminated and can expose data, so the protocol's existing
"not a global read-isolation guarantee" caveat is now a measured fact rather than a warning.

Cost 0.50 CNY for both variants. One case regressed (real-stream-0, 12 -> 10).
The guidance made searching the exception and then discouraged it: "Only when exact earlier
requirements ... are missing, use the existing shell tool" followed by "do not search merely
because compaction occurred". The tested model read that as licence to answer from the
projection and never search.

This rewrites it around absence-of-evidence: the visible conversation is a partial
projection, something missing from it may exist only in the original records, and when the
answer turns on an exact value the projection does not show, the records are to be searched
before the answer is reported as unknown or omitted as unverifiable. Every scope, safety and
anti-replay rule is kept, and the anti-spam rule becomes "a targeted search is expected and
cheap; reloading the history wholesale is not" rather than "do not search".

**It did not change behaviour.** Measured on the closed-book chain set with the exam sending
nothing but production's prompt and tools (no exam-side instruction, no forced tool choice),
18 cases per run:

  guidance v1 (before)      0 tool calls in 18 cases   +1 value over closed
  guidance v2 (this change) 0 tool calls in 18 cases   +2 values over closed

The value breakdown is identical where it matters: 27 of the 178 examined values are absent
from the projection and were never searched for, in both runs. The capability is not in
question — the same model, given a verification instruction and one forced call, recovered 20
of those 28 by searching the archive. What the wording does not supply is the motivation to
look at all, in an exam that presents a candidate list and asks for recognition.

So this is a wording improvement on its own merits, not a measured one, and it should be kept
or dropped on those grounds. It is worth knowing either way: two rounds of prompt
strengthening moved nothing, which points at the trigger rather than the text.

Cost of the change to know about: the guidance is part of the system prompt, so every existing
session's cached prefix invalidates once when this ships.
…rted calls

Adds `--exam-wording v2`, which removes three things from the question that presuppose the
projection is the whole story: "The conversation above is the record" (against the guidance's
own "partial projection"), "appeared in that conversation" (treating what is visible as the
universe), and "If you cannot check a value, leave it out" (presupposing you cannot check).
The candidate list and its order are preserved verbatim, and `--closed-reprobe` re-scores the
frozen closed projections under the same wording so a wording change is checked against a
matched baseline rather than the stored one.

Result: the wording hypothesis is refuted. Closed is unchanged (147/178 under both wordings,
so the instrument did not get easier), and open stays at zero tool calls in 18 of 18 cases —
the third prompt-side variant to do so.

  closed v1 (baseline)                    147/178  82.6%   0 tool calls
  closed under wording v2                 147/178  82.6%   0
  open: guidance v1 + wording v1          148/178  83.1%   0
  open: guidance v2 + wording v1          149/178  83.7%   0
  open: guidance v1 + wording v2          145/178  81.5%   0
  open: + explicit verify instruction     166/178  93.3%   100

The v2-wording score is the clean re-run. The first attempt read 138 and is not quoted: I
aborted the harness mid-call, the ledger correctly refused a silent retry, and the case that
had been retried answered with 4 values where it had 11.

`--retry-unsettled` is the explicit escape hatch that made the re-run possible: it marks the
aborted row `interrupted` (reservation kept as spend, the documented convention), logs it, and
re-executes. The ledger's refusal to retry silently is correct and stays the default.

Also drops a leftover `del rng, ledger` from an earlier edit that crashed the first resume.
The runtime no longer adds an `Archived conversation recall` section after a checkpoint. A
session's system prompt is its own, unchanged for the whole session. The retrieval CLI stays:
`future session history search` / `get`, its two RPC commands, and the entry references the
journal already puts in search and read results.

Why: three prompt variants over 54 open-book cases produced zero retrieval calls. The
guidance made searching the exception and then discouraged it, so it was rewritten to lead
with "absence from the visible context is not evidence" — the same model, in the same exam,
still answered from the projection every time, leaving 27 of 178 values unlooked-for while
the archive held them. Round 5 of the open-book experiment recovered 20 of those 28 by
searching, so the gap is behavioural, not a capability the wording can unlock. The reasoning
generalises past that experiment: the section only ever described a capability the model
already had, and describing a capability more firmly is not what makes a model use it.

Measured, and recorded in docs/internals/compaction/compaction-open-book-experiment.md.

Two consequences worth the diff:

* **The prompt is now constant across a checkpoint**, which is strictly better for provider
  prefix caching. It used to grow, so the request budget had to reserve the growth in advance
  and the summary request had to reproduce it exactly or lose the prefix. `run_loop.rs` no
  longer computes a separate budget prompt, and both it and `rpc/session.rs` simply send the
  session's prompt. A test now asserts the prompt does not change across a checkpoint instead
  of asserting two call sites agree on one string.
* **Nothing tells the model the CLI exists.** That is the point, but it means discovery depends
  on the session's own prompt or the model's own initiative. `verify_production_shape.py`
  checks the CLI is still present and usable, since the prompt no longer advertises it.

Deleted: `agent/src/agent/history_recall.rs` and the `history_recall_allowed` flag that existed
only to gate it. `abc_strategy_probe --print-request-shape` keeps reporting both pre- and
post-checkpoint states so a harness can assert they are identical.
…er them

`scripts/abc_experiment/` had accumulated 136 files across a dozen superseded
protocols. Only two experiments survive as reports, so this keeps their dependency
closure and retires the rest, in a directory named for what it contains.

Kept, and renamed to say what they are:

  scripts/compaction_experiment/
    run_closed_book.py, run_open_book.py       the two entry points
    harness.py, arms.py, strategies.py         shared base, arm definitions, external rules
    exam.py, transport.py                      questionnaire and its scoring; SSE/IO helpers
    request_shape.py, verify_request_shape.py  production's prompt and tools, and their check
    native_*.py, opencode_fidelity.mjs         archive, tool execution and SDK replay
    capture_shape.py, freeze_sessions.py       input preparation
    released_probe.rs, provenance.json         the deployed-arm driver; transcription sources
    README.md, CLOSED_BOOK_PROTOCOL.md, OPEN_BOOK_PROTOCOL.md

Deleted: 114 script files, 14 protocol documents, three Rust probes (`abc_c_probe`,
`abc_c3_probe`, and the `abc_compaction_arm` they drove) and the 839-line A/B/C/M
harness, of which the surviving experiments used three functions — now `transport.py`.

The Rust examples drop the `abc_` prefix too: `compaction_probe`,
`production_tool_executor`, `model_bridge`. The reports are `compaction-closed-book-
experiment.md` and `compaction-open-book-experiment.md`, so the name a reader meets in a
report is the name of the file that produced it.

Reports now carry their own reproduction commands, and each protocol documents the flags
that change what is measured — in particular that `--require-retrieval` is not a production
behaviour and that `--closed-reprobe` is the control for a wording change.

Both companion docs are checked, not asserted: `verify_request_shape.py` runs offline and
fails if the prompt stops being the session's own, if the tool definitions from the probe and
the executor disagree, if `future session history` disappears, or if the executor stops
refusing a path outside the case. `run_open_book.py --smoke` then exercises the archive end
to end for one chain with no model call. Both were run after the move.

`check-docs.py` goes from 21 findings to 4, all four pre-existing under `mobile/docs/` and
untouched by this branch; the three experiment docs are whitelisted beside it, which required
adding them to the test's copy of the whitelist, since the checker fails on an entry that does
not exist.
The filenames now correspond; the headings did not. Both open with the same stem and answer
their own question in the line below.
`test_s2_compaction.py` asserted the guidance I removed two commits ago: one
`## Archived conversation recall` section per turn, naming the session literally. With the
section gone those assertions fail, the fixture returns 500, and the smoke fails at
"normal response completed" — a real breakage of this branch, caught by the pre-PR pass.

It now asserts what replaced it, on every request including the summary one: the system
prompt is the session's own and is byte-identical across a session's requests, and the
retired section is absent. That is the invariant the runtime now guarantees, and it is the
one a provider's prefix cache depends on — the old per-turn guidance was exactly what made
the summary request and the turn it belongs to share a prefix only by careful imitation.

The scripted fixture still drives `future session history search` / `get` itself, so the
rest of the smoke — S2 at the >80% trigger, schema 3, protected references, the exact
model-call count, restart persistence — is unchanged and still meaningful.

124 checks, up from 119: the prompt-stability check runs on every request rather than being
counted once.
@huichen

huichen commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed review findings 1, 3 and 4 in 0a78d9b. Finding 2 (summary request budgeting) is intentionally unchanged as requested.

  • Propagate summary cancellation rather than committing a deterministic fallback checkpoint, with a final interrupt check before finalization.
  • Remap generated evidence entry IDs and the coverage cutoff when forking. Preserve excerpts, verbatim notes and model handoff text; reject dangling evidence references.
  • Persist manual-summary token/cache/cost totals together, including charged failed/cancelled/retried attempts. Durable replays do not charge twice.

Added 7 tests and expanded the existing usage test: cancellation/no checkpoint, two-generation fork history lookup after reload, preservation of historical text, dangling references, atomic metadata updates, restart/replay accounting, and charged retries/failures.

Validation on Rust 1.97.0: cargo fmt -p future-agent --check; cargo clippy -p future-agent --all-targets -- -D warnings; cargo test -p future-agent (1786 unit + 46 integration passed; existing ignored tests unchanged).

No merge or auto-merge requested.

@huichen
huichen merged commit 9f928e1 into main Sep 18, 2026
22 of 24 checks passed
@huichen
huichen deleted the feat/compaction-evidence-strategies branch September 18, 2026 01:41
huichen added a commit that referenced this pull request Sep 20, 2026
…731)

The projector treated only `schemaVersion === 2` checkpoints as durable
in-turn markers. #715 moved the agent to schema 3, so every automatic
mid-turn checkpoint was reclassified as an exchange boundary: the open
exchange was flushed and the assistant/tool entries that followed it
belonged to no user message, which `turnFromAcc` drops. Reopening a
conversation showed it stopping at the "上下文已压缩" divider with the
rest of the reply — and the tool results paired across the checkpoint —
missing, even though the journal still had them and the run had
completed normally.

Gate on "v2 or newer" instead of a literal version, so a future schema
bump cannot silently drop a turn again, and keep v1 destructive
summaries as boundaries. Covered on both clients: the mobile timeline
tests now run the in-turn case for schema 2 *and* 3, and a new desktop
projection test pins the segments around a v3 mid-turn checkpoint.

The screenshot harness gains a `compact-resume` scenario per platform
(`?compactHistory=1`) whose `eval` assertions fail if the text after the
divider is missing, so the regression cannot come back unnoticed.
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