Repository navigation
feat(context): compaction as a controlled cache-epoch transition - #374
Merged
Merged
Conversation
Forge's model-visible context is append-only during normal operation, so the provider's cached prefix keeps growing and every turn reuses it. There was no way out of that when the window filled except `handoff_reset`: a non-model "progress document" that threw the conversation away and restarted from two synthetic messages. This replaces it with real compaction. Under context pressure — or on `/compact` — Forge asks the *active* model for a structured state checkpoint, validates it, selects a recent raw tail, builds a candidate context, and installs it only if every check passes. That is the one operation allowed to replace historical model-visible context; canonical session history in the journal is never touched. Cache behaviour is the point of the request shape. The compaction call is the exact current context plus one appended user message, so the whole conversation is served from the provider's cached prefix instead of being paid for twice. Installing the result opens a new cache epoch once, and append-only caching resumes on top of it. - forge-context: new `compaction` module — pressure policy sized from the model's real window, checkpoint schema/parse/validate, boundary-aware tail selection, candidate validation, protected facts. All pure. - forge-core: the transactional install. Journals before swapping, so a write failure cannot leave a projection resume could not reproduce. Any failure leaves context, epoch, and history exactly as they were. - forge-durable: additive `ContextCompacted` event; replay rebuilds the same projection while every earlier event stays intact. - forge-connect: ingest models.dev `limit.context`/`limit.output` so the trigger and tail target come from metadata, not a hard-coded 200K. - forge-tui: `/compact` reports one line — `Context compacted · 109K → 36K` — and says "context unchanged" when it fails, never claiming success. Removes `handoff_reset` and the ratio-based reset it served.
mohitranka
added a commit
that referenced
this pull request
Aug 21, 2026
Forge's model-visible context is append-only during normal operation, so the provider's cached prefix keeps growing and every turn reuses it. There was no way out of that when the window filled except `handoff_reset`: a non-model "progress document" that threw the conversation away and restarted from two synthetic messages. This replaces it with real compaction. Under context pressure — or on `/compact` — Forge asks the *active* model for a structured state checkpoint, validates it, selects a recent raw tail, builds a candidate context, and installs it only if every check passes. That is the one operation allowed to replace historical model-visible context; canonical session history in the journal is never touched. Cache behaviour is the point of the request shape. The compaction call is the exact current context plus one appended user message, so the whole conversation is served from the provider's cached prefix instead of being paid for twice. Installing the result opens a new cache epoch once, and append-only caching resumes on top of it. - forge-context: new `compaction` module — pressure policy sized from the model's real window, checkpoint schema/parse/validate, boundary-aware tail selection, candidate validation, protected facts. All pure. - forge-core: the transactional install. Journals before swapping, so a write failure cannot leave a projection resume could not reproduce. Any failure leaves context, epoch, and history exactly as they were. - forge-durable: additive `ContextCompacted` event; replay rebuilds the same projection while every earlier event stays intact. - forge-connect: ingest models.dev `limit.context`/`limit.output` so the trigger and tail target come from metadata, not a hard-coded 200K. - forge-tui: `/compact` reports one line — `Context compacted · 109K → 36K` — and says "context unchanged" when it fails, never claiming success. Removes `handoff_reset` and the ratio-based reset it served.
mohitranka
added a commit
that referenced
this pull request
Sep 11, 2026
Forge's model-visible context is append-only during normal operation, so the provider's cached prefix keeps growing and every turn reuses it. There was no way out of that when the window filled except `handoff_reset`: a non-model "progress document" that threw the conversation away and restarted from two synthetic messages. This replaces it with real compaction. Under context pressure — or on `/compact` — Forge asks the *active* model for a structured state checkpoint, validates it, selects a recent raw tail, builds a candidate context, and installs it only if every check passes. That is the one operation allowed to replace historical model-visible context; canonical session history in the journal is never touched. Cache behaviour is the point of the request shape. The compaction call is the exact current context plus one appended user message, so the whole conversation is served from the provider's cached prefix instead of being paid for twice. Installing the result opens a new cache epoch once, and append-only caching resumes on top of it. - forge-context: new `compaction` module — pressure policy sized from the model's real window, checkpoint schema/parse/validate, boundary-aware tail selection, candidate validation, protected facts. All pure. - forge-core: the transactional install. Journals before swapping, so a write failure cannot leave a projection resume could not reproduce. Any failure leaves context, epoch, and history exactly as they were. - forge-durable: additive `ContextCompacted` event; replay rebuilds the same projection while every earlier event stays intact. - forge-connect: ingest models.dev `limit.context`/`limit.output` so the trigger and tail target come from metadata, not a hard-coded 200K. - forge-tui: `/compact` reports one line — `Context compacted · 109K → 36K` — and says "context unchanged" when it fails, never claiming success. Removes `handoff_reset` and the ratio-based reset it served.
mohitranka
added a commit
that referenced
this pull request
Sep 11, 2026
Forge's model-visible context is append-only during normal operation, so the provider's cached prefix keeps growing and every turn reuses it. There was no way out of that when the window filled except `handoff_reset`: a non-model "progress document" that threw the conversation away and restarted from two synthetic messages. This replaces it with real compaction. Under context pressure — or on `/compact` — Forge asks the *active* model for a structured state checkpoint, validates it, selects a recent raw tail, builds a candidate context, and installs it only if every check passes. That is the one operation allowed to replace historical model-visible context; canonical session history in the journal is never touched. Cache behaviour is the point of the request shape. The compaction call is the exact current context plus one appended user message, so the whole conversation is served from the provider's cached prefix instead of being paid for twice. Installing the result opens a new cache epoch once, and append-only caching resumes on top of it. - forge-context: new `compaction` module — pressure policy sized from the model's real window, checkpoint schema/parse/validate, boundary-aware tail selection, candidate validation, protected facts. All pure. - forge-core: the transactional install. Journals before swapping, so a write failure cannot leave a projection resume could not reproduce. Any failure leaves context, epoch, and history exactly as they were. - forge-durable: additive `ContextCompacted` event; replay rebuilds the same projection while every earlier event stays intact. - forge-connect: ingest models.dev `limit.context`/`limit.output` so the trigger and tail target come from metadata, not a hard-coded 200K. - forge-tui: `/compact` reports one line — `Context compacted · 109K → 36K` — and says "context unchanged" when it fails, never claiming success. Removes `handoff_reset` and the ratio-based reset it served.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Replaces the old
handoff_resetcontext reset with real context compaction: a transactional transformation from one valid cacheable context state into the next.During normal operation the model-visible context stays append-only, so the provider's cached prefix keeps growing. When pressure gets high, compaction collapses the conversation into a structured state checkpoint + a recent raw tail, opens one new cache epoch, and append-only behaviour resumes on top of it.
The governing invariant: compaction is the only normal operation allowed to intentionally replace historical model-visible context, and canonical session history is never touched.
Where it integrates
The audit found a single projection point, so there is no second context-building path:
prepare_model_stepis what both theTurnCoordinatorand the TUI's own turn loop call, so one hook covers both.Cache behaviour
Before — append-only; each request is a byte-prefix of the next, verified by the existing
prompt_wiresnapshot diagnostics.During — the compaction request is
[exact current model-visible context] + [one appended user message]. Nothing earlier is rewritten, so the provider serves the entire conversation from cache rather than re-reading a second copy of it. Same provider, same model, same serialization, same caching path — no cheap secondary summarizer.the_compaction_request_is_the_live_context_plus_one_appended_messageasserts this byte-for-byte.After — one
begin_cache_epoch("compaction"), then append-only resumes. The checkpoint installs as a system message, so on Anthropic it folds into the hoisted system block alongside the base prompt — i.e. the new stable prefix ends exactly where it should.compaction_opens_a_new_cache_epoch_and_appending_resumes_after_itchecks both halves.Trigger
Sized from the model's real window rather than a hard-coded constant:
forge-connectnow ingests models.devlimit.context/limit.output(mirroring the existing cost/effort ingestion) andset_context_windowis wired through session assembly and every model switch. An id the registry doesn't publish keeps the conservative default rather than inventing a window.Retention
clamp(window × 0.12, 16K, 64K), capped at a third of the window. Selection walks backward to the target, then snaps to the nearest structurally valid boundary — never opening on an orphaned tool result, never splitting a call from its result, and pulling in a user request one message back rather than opening on the reply to it. Overshooting the target beats emitting invalid context.ProtectedFact, the recent window is supplied to the prompt verbatim, and a checkpoint that drops<user_constraints>when facts exist is rejected.summary(summary(...)).Failure semantics
Transactional. Nothing mutates until every check passes; the journal write happens before the in-memory swap so a write failure can't leave a projection resume couldn't reproduce. Provider error, malformed/truncated checkpoint, dropped constraints, oversized result → context, epoch, and canonical history all unchanged, one telemetry record with a failure category. Automatic compaction additionally never fails the user's turn: the old context is still valid, so the step proceeds on it.
Tests
cargo test --workspacegreen (the one pre-existingforge-config::tests::defaults_workspace_to_cwdfailure on this machine is unrelated and reproduces on a clean checkout).cargo fmt --allandcargo clippy --all-targetsclean.compaction_tests.rs): automatic trigger fires / doesn't fire prematurely;/compactbelow threshold; manual and automatic produce identical results; the cache-prefix assertion; epoch + append-only resumption; canonical history intact after compaction; verbatim tail; tool pairs never split; constraint supply and enforcement; repeated compaction merging; five rollback tests (provider, malformed, truncated, dropped constraints, oversized); failed auto-compaction still lets the turn proceed; resume reconstructs the identical context.Nonefor unpublished ids./compactreports before→after and the surviving objective; failure says "context unchanged".Superseded tests for
handoff_resetwere removed rather than left asserting deleted behaviour.Out of scope
No retrieval, no embeddings, no vector or BM25 search, no cross-session memory, no long-term memory, no alternate compaction algorithms or models, no user-configurable thresholds or tail sizes, no checkpoint editing UI. No placeholder abstractions for any of them.
Known limitations
<user_constraints>present when facts exist), not semantic; it cannot prove a specific constraint survived.