With compression.prepare_ahead, compress() re-planned the tail cut and threw the
completed background summary away whenever the fresh cut landed before the
summary's boundary (the no-LLM prune made tail rows cheaper, tool-group
alignment moved the cut), then wrote a second summary inline while the user
waited. That breaks the one-summary rule: once the background summary exists it
is used, and everything after its boundary is the tail.
The splice check no longer consults the fresh cut at all. A summary is still
discarded only when the messages it covers changed (rewind, shape change, other
session, moved head). The pass planned its own window with a full tail, so the
tail is never empty. The now-unreachable inside_tail reason leaves the
(unreleased) prepared-compaction metric contract.
Maintainer ruling on the prepared-compaction design, plus the review findings
(ours and Greptile's) on #144684:
- One pass per compaction. The extension passes (a new summary call every ~8k
tokens of growth) and the "stale after one tail budget" check are gone: the
summary splices at its own boundary and every message after it, however
many, stays verbatim in the tail. No second summary is ever paid for.
- The splice check compares message structure, not text: role, tool call
ids/names, tool result ids, plus the durable message_uid where both sides
carry one. Plugins that rewrite text in place (redaction, pre-compaction
notes) no longer throw the summary away; a dropped/inserted message or a
rewind into the window (new message_uids) still misses. This also settles
the fingerprint gap on input_text/output_text parts: text is not compared.
- A pass that recovered on the main model after the summary model failed now
hands that over on a splice, as an inline call would: summary_model goes
sticky to the main model, and the "configured compression model failed"
warning reaches the user. The attempt telemetry carries the pass's aux call
(model, tokens, duration, fallback) and a new prepared_summary flag.
- The first compaction that needs memory-provider context stops further
passes for the agent; each would have been discarded and paid twice.
- Turn-end passes are skipped for cron runs and delegated children, whose
sessions end with the turn.
Rebasing #120603 onto main lost a line in the conflict resolution: main's
summary success path (86bf8886c2 / 4f134d4c37) resets the sustained-overload
budget, but the extracted _record_summary_success() did not. Two overload
aborts, then a healthy summary whose compaction is refused (would-grow), left
the strikes armed, so one isolated overload later escalated straight to the
destructive fallback. The helper now clears terminal failures with the shared
helper and restarts the overload budget, exactly as main does.
The overload tests move to tests/agent/test_context_compressor_overload.py
(unchanged) so the new case fits the test-file size cap.
_compress_window moves unchanged, with _plan_compaction_window and the
prepared-summary splice (_take_prepared_summary), into CompactionWindowMixin
in agent/context_compressor_window.py: the window that compress() and the
prepared-compaction pass both plan now lives in one place, and
context_compressor.py stays under its file-size ratchet. config_defaults
comments in the compression section are tightened to keep that file at its
cap. The pre-existing summary catch-all in _generate_summary gets a health
waiver: the ratchet re-flags it only because the success block above it was
extracted into _record_summary_success.
- A candidate only splices when the messages between its boundary and the
fresh tail cut fit in one more tail budget; a staler candidate misses and
compaction summarizes inline.
- The preparation band is 12% of threshold_tokens, not of the context
window, so a small absolute trigger on a large window no longer starts a
pass on every turn.
- bind_session_state() discards the candidate and any running pass when it
binds a different session id (/resume, /branch); same-session rebinds
keep it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With compression.prepare_ahead (default false), once the provider-reported
prompt size is within 12% of the context window below the compaction
trigger, the turn loop starts a background pass before a tool batch runs
and at turn end. The pass plans the same window compress() plans and runs
the same summariser on a copy of the compressor and of the window rows.
The pass itself never rewrites the live transcript, system prompt or
prompt cache; the transcript keeps growing normally meanwhile.
At the next automatic threshold compaction, compress() splices the
finished candidate when the head boundary is unchanged, its boundary is no
later than the fresh tail cut, and the transcript up to that boundary is
unchanged (ignoring what the no-LLM prune rewrites). Messages after the
candidate boundary stay outside the summarized region and go through the
existing tail handling. Everything else, including a pass that has not
finished, manual/focus compaction, overflow recovery and memory-provider
summary context, compacts inline as before. A running pass is never
waited on and loses the right to publish once compaction or a session
boundary overtakes it. A failed pass backs off further passes without
touching the live failure cooldown.
State is per compressor and in memory only. Plugin context engines, Codex
app-server, native Responses compaction, micro-compaction and
background-review forks are not prepared. With the flag off no state is
created and compress() takes its existing path.
Phases 1-2 of compress() (prune old tool results, drop blank echoes, pick
the head/middle/tail boundaries) move into _plan_compaction_window so a
second caller can plan exactly the same window. No behaviour change.
With auxiliary.compression on a dead endpoint (connection refused, quota), call_llm's own
recovery ladder answers the summary with the main agent model. The compressor only saw a
successful response, so the "configured compression model failed" warning never fired and
attempt telemetry read method=llm_summary, fallback_used=false: the user never learns their
compression endpoint is down. The compressor's own main-model fallback (#116472) already
reports both; only the ladder's recovery was invisible.
The ladder now records the route that failed and why in the caller's route_info when a
fallback candidate answers, and the compressor treats that like its own fallback: telemetry
fallback_used=true (failure_class aux_model_fallback) for any fallback route, and the
existing user warning plus method=aux_fallback_main when the main model answered (the
warning names the main model, so a configured fallback_chain entry gets telemetry only).
Live, real AIAgent._compress_context with auxiliary.compression on a closed port and a
reachable main model: base compacts with no warning and fallback_used=false; head shows
"Configured compression model 'slow-summarizer' failed, so Hermes summarised with your main
model instead" once and fallback_used=true, method=aux_fallback_main on both compactions.
The tail-cut walk charged in-transcript handoff rows as protected-tail
candidates, but the handoff scan folds every row up to the newest handoff
into the summary window: none of them can stay in the tail. When the
handoff row alone pushed the transcript over the soft ceiling, the walk
stopped on it and the planned window held only the handoff, so compress()
returned the empty_post_handoff_window structural no-op at every trigger.
Live on main (gemini-2.5-flash, context_length 64000, prepare_ahead off):
a Desktop manual compress, then one automatic compaction (handoff now at
index 0), then four consecutive empty_post_handoff_window no-ops while the
prompt grew 47,085 -> 57,143 -> 66,716 tokens, past the 64k window.
The tail-cut walk now prices rows at or before the newest handoff at zero,
so the cut is decided by the rows that can really stay in the tail and the
window covers the old handoff plus the turns after it. Same scenario on
this branch: the second automatic compaction summarises 17 rows and the
next prompt is 18,156 tokens.
At or below _MIN_SUMMARY_TOKENS (2K) the summary alone fills the trigger, so
no tail size leaves room under it; clamping the 2.5%-of-window term there only
drops recency context (a 1K test trigger on a 256K window merged the handoff
into a tail row). Keep #144177's floor-only clamp in that regime. The lean
budget moves to context_compressor_tail.lean_tail_budget.
Prune-only rules a skill_view stub row (count-protected tail); a later full
compaction keeps that row in its token-budget tail and appended the rule to the
handoff too. Compaction now moves a kept stub's copy onto the handoff, so the
transcript carries exactly one copy while a marker remains.
Follow-up to #144177 (independent review D4).
#144177 capped only the 10K floor at half a configured trigger; the
2.5%-of-window term still kept 25K at 1M, so the tail stayed at 123%/216%/86%
of a 12K/12K/30K trigger on 400K/1M windows and the refusal loop remained.
Clamp the final lean budget instead. Default-config budgets are unchanged on
every window from 16K to 1M (threshold_percent 0.5 already exceeds 5%).
Follow-up to #144177 (independent review D3).
Greptile "History rewrites lose skill guidance": the rule only rode the handoff
built in _assemble_compressed, so two rewrites left [SKILL_PRUNED: markers in
context without the "one reload is enough, ignore older markers" rule:
- prune_tool_results_only turns skill_view results into marker stubs and has no
handoff: the rule now rides the first row it turned into a marker (once per
transcript), and _is_summary_stub ignores that suffix so a later prune leaves
the ruled stub alone;
- anti-growth salvage cut a long handoff to its head, dropping the rule at its
end: the elision now keeps an attached rule.
The prompt trims shrank the CLI system prompt by 531 chars, which moved the
loopback overflow in test_worker_compression_admission / test_journey_compress
_restart_fifo from turn 4 to turn 5. Main fails identically at turn 5 (proved by
shifting the stub's 50,000-char overflow line to 50,300 on an origin/main tree):
with compression.threshold_tokens=12000 on a 64K window the lean tail floor
(10K) kept 11.8K of verbatim tail, so the rebuilt head + summary + tail stayed
over the trigger, the overflow compaction went 9->9 messages and every pre-API
pass refused as "would grow"; the turn died with no post-summary inference.
The lean floor is now min(10K, threshold_tokens * 0.50), the trigger-side twin
of TAIL_MAX_CONTEXT_FRACTION. Default percent triggers never bind it (the
75% small-window floor puts half the trigger above the 20% window cap); only a
configured threshold_tokens or aux ceiling far below the window does.
Maintainer-approved prompt-footprint trims (measured on the Nous endpoint, anthropic/claude-opus-5.5):
All sessions
- The [SKILL_PRUNED] "Skill Safety Rule" (126 tok) left the system prompt: markers only exist after a
compaction, so the compaction handoff now carries the rule whenever a marker survives in the
compacted transcript (context_compressor_tail.with_skill_safety_rule, applied in
_assemble_compressed for LLM and fallback summaries alike). The "## Pruned Skills" block drops
its own parenthetical, which the rule now covers. `hermes sessions repair-prompts` keyed its
"full build" detector on the rule's heading; it now keys on SKILLS_GUIDANCE (present in prompts
built before and after this change).
- The CLI/TUI cron "LOCAL-ONLY" caveat (154 tok) moved from the platform hints into
cronjob_manage's deliver description (a deferred tool: paid only when loaded).
- The Hermes help pointer no longer restates identity ("You run on Hermes Agent (by Nous
Research)") after SOUL.md's "You are Hermes Agent, built by Nous Research."; it now opens "For
help with Hermes Agent itself — ...", which still tells a custom persona what it runs on (22 tok).
One-shot sessions only (-q/--oneshot/-z, and gateway-owned `oneshot` policy sessions)
- No "## Mid-turn user steering" note (253 tok): nobody can steer a one-shot.
- No clarify tool (590 tok): ONESHOT_DISABLED_TOOLSETS is folded into session_disabled_toolsets
(oneshot=...), so the agent tool build, MCP refresh, the tool_search bridge, delegate children and
the gateway's session inventory / tool listings all drop it together. skill_manage stays.
- delegate_task without live control (425 tok): action/subagent_id/message and the
background-delivery paragraph are removed (children are joined inside the call), applied via
toolsets.agent_tool_surface at load and MCP refresh. The one-shot fact is frozen on the agent at
its first tool build so refreshes stay byte-stable.
Interactive tool schemas are byte-identical to main.
* fix(sessions): proactive prune rewrites only the changed rows, in place
A prune edits the content of a few existing messages and never adds, drops or
reorders one, yet every commit went through archive_and_compact, which
archives all active rows and re-inserts the full list: state.db grew by the
whole live transcript per commit (#124102).
SessionDB.rewrite_pruned_rows resolves each changed message to its live row
(_row_id, else its tool call id or tool-call ids, else the single active row
with the same role and stored content), checks the row still holds the
original, inserts one archived twin of the pre-prune row (active=0,
compacted=1, still searchable) and updates the changed columns under the same
id. The prune tries it after the stale-history watermark check and falls back
to archive_and_compact when a row cannot be named exactly or an unwritten
message sits before durable ones.
Fixes#124102
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(sessions): in-place prune twin keeps the live row's display slot
The content UPDATE fires messages_display_identity_update, which nulls
display_identity/display_order on the live row and on its freshly inserted
twin. The lazy backfill then gives the twin its own id as display_order, so
every demoted full body renders at the END of the transcript page, after the
newest user turn (3 x 24 KB bodies below "from desktop" in the probe).
Re-stamp both rows with the pre-update identity and order inside the same
transaction: the page projection shows one row per display_order (the live
stub, in place) and the twin stays a searchable archive. This is the same
stored-identity shape #117824 proposes for the archive writer (#117750), so
the resume projection collapses the pair once that lands.
Review-fix for #124273; one assertion added to the growth invariant
(red on the PR head: 20 page rows for 17 messages).
* fix(sessions): in-place prune keeps each display slot through later compaction and backfill
Review follow-up (ehz0ah): the rewritten live row kept the archived body's
identity, so a later archive_and_compact gave its copy a fresh slot and the
full body resurfaced in the old one. The live row now takes the identity of
what it stores and keeps the slot; the twin and any earlier generation's
copies (all nulled by the identity trigger) are restamped with their own
identity and slot, and the display backfill keeps a row's stored slot when
its stored identity is still correct. The prune pre-fills slots for legacy
rows so it never carries a missing one.
* fix(agent): fail closed when an in-place prune finds the row rewritten
rewrite_pruned_rows raised one PruneRowUnresolvedError for two different
conditions: the row cannot be named (ambiguity — the full writer handles it)
and the row IS named but its stored body changed. The second means another
surface already rewrote this generation, which is what StaleHeldHistory
exists to catch; the in-place prune preserves row ids, so
_archive_watermark_for cannot see it. Returning None there handed the stale
pruned_msgs to archive_and_compact, which archives rows it never compared
and republished the held text over a newer durable edit.
Split the stale case into a PruneRowStaleError subclass and raise
StaleHeldHistory from the in-place helper so the existing handler skips the
pass instead of committing. Ambiguity keeps the fallback.
Replaces the prune-fallback regression with the two cases review asked for:
a changed stored body skips the prune and leaves the newer body active; a
genuine ambiguity over current content still commits through the full writer.
* fix(agent): make an in-place prune visible to the other lease-less writer
rewrite_pruned_rows keeps every row id and activity flag, so the id/activity
staleness gate in held_archive_watermark cannot see that a prune already
committed. A second lease-less surface (micro-compaction) holding the pre-prune
transcript passes the gate and archive_and_compact republishes the pruned-away
bodies over the winner, undoing the prune.
stale_raises now also compares the held bodies against the stored ones via the
new SessionDB.rewritten_held_row_ids, so every lease-less writer sees the
in-place generation change, not just the prune caller that owns the exception.
* fix(state): compare durable row versions, not raw content, in the in-place stale guard
Reviewers on 631c897b converged on one root defect: the stale-write guard compared
raw SQLite bytes against a loaded/normalized view, which both missed real rewrites
and invented phantom ones.
- rewrite_pruned_rows._resolve: the staleness check is now the repo's stored-row CAS
digest (transcript_row_snapshot over a SELECT * row, covering every owned column
including assistant tool_calls arguments) when the held dict carries DB_ROW_SNAPSHOT,
and the loader-lens identity compare (_row_identity, the same representation
_stamp_kept_live_prefix uses) otherwise. Raw storage bytes are never compared
against a loaded view.
- The rewritten row's replacement dict is stamped with the row's new digest, and the
commit runs under _execute_transcript_write so a rollback restores the stamps.
- rewritten_held_row_ids takes full held dicts and applies the same two-leg compare;
only tool/assistant rows (the roles the in-place writer touches) are compared.
- held_archive_watermark(stale_raises=True) checks the durable prefix BEFORE the
ids[-1] is None early return, so an unstamped trailing message caps the watermark
but can no longer suppress version checks for the rows the caller holds exactly.
Closes the P0 stale tool_calls path, the P2 false-stale on freshly resumed
whitespace-padded rows, and the unstamped-tail blind spot (#124102).
* fix(state): gate the lease-less stale check on every role the fallback republishes
The staleness gate behind held_archive_watermark (rewritten_held_row_ids)
compared only tool/assistant held rows, but the fallback it guards —
archive_and_compact, reached whenever the in-place rewrite refuses (an
unwritten message before later durable rows, an unnamed row) — re-inserts
held rows of every model-transcript role verbatim. A user row another view
rewrote in place (set_user_message_content, the repair batch's in-place
rewrite) slipped the gate: the stale pre-edit body was republished active
and the newer edit left with zero active copies.
Compare every model-transcript role (user/assistant/tool); the per-row
comparison (DB_ROW_SNAPSHOT CAS, else the loader-lens identity) is already
role-agnostic. Bookkeeping roles stay excluded — they never reach the
model-facing list. Covers the prune fallback and micro-compaction, the two
lease-less callers of _archive_watermark_for (#124102).
Sabotage-run: reverting the role filter makes
test_a_concurrent_user_edit_stays_active_when_the_prune_falls_back fail
(stale body published); restored, the file is 22/22 green.
* style: use builtin generics in the in-place prune commit annotations
* refactor(compression): split the proactive prune and its commit into topical siblings
The code-health ratchet (CI) flags this PR's own growth: hermes_state_messages.py
(2190 > 2000), agent/context_compressor.py (5911 > its main value 5852) and
agent/conversation_compression.py (4585 > 4564). The remedy the repo prescribes:
move the PR's own code into topical siblings, keeping the facade as the seam.
- agent/context_compressor_prune.py: ProactivePruneMixin (prune_tool_results_only
+ _rewrite_pruned_rows_in_place), bound into ContextCompressor; origin-module
symbols read through _cc() at call time (the micro_compaction.py pattern) so
tests patching agent.context_compressor.X stay effective; logger keeps the
agent.context_compressor name for caplog parity.
- agent/conversation_compression_watermark.py: held_archive_watermark; the origin
module imports it and keeps _held_watermark (its only caller).
- hermes_state_prune_rewrite.py: SessionPruneRewriteMixin (rewrite_pruned_rows +
rewritten_held_row_ids), bound into SessionDB; every SessionDB call site and
test patch seam (db.rewrite_pruned_rows / db.rewritten_held_row_ids) unchanged.
Verified: scripts/check --only health --base origin/main -> 0 blocking; ruff clean;
prune/compaction batches green (test_proactive_prune_restart_safety 22/22,
test_micro_compaction 48/48, five proactive-prune files 25/25). The 4 failures in
test_compaction_prompt_rebuild / test_compression_review reproduce identically on
origin/main (pre-existing).
* fix(state): re-verify held rows inside the full writer's commit transaction
The lease-less stale gate (rewritten_held_row_ids) runs outside the write
transaction, so a second SessionDB connection that rewrites a covered row
AFTER the precheck but BEFORE archive_and_compact's BEGIN IMMEDIATE was
invisible to it: the commit archived the newer row and republished the stale
held text, leaving the newer edit with zero active copies (#124102, review
finding on 8c6da464).
- archive_and_compact takes held_for_cas: the caller's held dicts,
re-verified against the live rows INSIDE the commit's transaction before
any row moves; a mismatch raises HeldRowRewrittenError, which the two
lease-less callers (proactive prune fallback, micro-compaction sync)
treat exactly like StaleHeldHistory - nothing written, the pass is a
no-op and the newer generation keeps the session. The lease path leaves
it None: its lease rules out an overlapping rewrite.
- held_row_mismatches(conn, ...) is the compare lifted out of
rewritten_held_row_ids so both the read-path precheck and the
in-transaction fence share one implementation. It now chunks the id IN
query via _id_chunks (a history past SQLite's host-parameter limit
failed the pass instead of reclaiming) and resolves rows that have no
_row_id but do carry the persist marker + CAS snapshot by their logical
message_uid (idx_messages_session_uid) - the unaddressed live-replay
loader shape, whose rows were previously exempt from the fence entirely.
- regression: test_a_user_edit_landing_after_the_precheck_stays_active_in_the_commit
drives a second SessionDB connection's set_user_message_content at the
archive_and_compact call boundary; sabotage (gate disabled) makes it
fail exactly as the finding predicts.
* refactor(compression): drop the duplicate _held_watermark from the module split
The 8c6da464 sibling extraction left two identical _held_watermark
definitions back to back in agent/conversation_compression.py; Python
silently kept only the second, so editing the first had no effect (dead
code, root AGENTS.md). Remove the added copy.
* refactor(state): split the api_content sidecar writers into a topical sibling
hermes_state_messages.py crossed the FILE_LINES ratchet (2010 > 2000) after
the commit-window fence landed in it. Move set_latest_user_api_content /
set_message_api_content into hermes_state_api_content.py
(SessionApiContentMixin, bound into SessionDB in the same MRO slot): the
two row-addressed api_content sidecar UPDATEs are one topic, no behaviour
change, every call site and test patch seam unchanged.
* fix(state): flatten _archive_and_compact_on_conn onto the caller's transaction after the main merge
Main flattened this helper to run directly on the caller's write connection
(no nested _execute_transcript_write); the merge resolution had kept the old
nested shape, which opened a second BEGIN IMMEDIATE inside the live one and
deadlocked every archive_and_compact. Re-flattened while keeping the #124102
held_for_cas in-transaction CAS fence.
* fix(state): carry the held-row CAS fence through the worker RPC path
RuntimeSessionCompressionMixin.archive_and_compact rejected held_for_cas,
so a worker-side micro-compaction commit raised TypeError inside the mixin's
generic except and silently skipped the whole persist (unstamped marker,
durable transcript left un-compacted). Accept held_for_cas, project it onto
the closed handoff fields plus the persistence marker the CAS compare reads,
validate it in worker_archive, and thread it into
archive_on_connection -> _archive_and_compact_on_conn (#124102).
* test(micro): a stale held generation without row ids aborts the micro-compact
Review follow-up (ehz0ah/greptile-apps, PR #124273): ACP restore and OpenAI
session continuation load through the unaddressed live-replay projection
(get_messages_as_conversation without include_row_ids=True) — the persist
marker, durable message_uid and the stored-row CAS digest, but no _row_id.
held_row_mismatches already resolves that shape by logical message_uid, so
the lease-less fence still sees another surface's in-place prune. Pin it with
the regression both reviewers asked for: after another surface prunes in
place, micro-compaction from that stale no-row-id history is a true no-op —
the pruned stubs stay the only live generation and the pre-prune bodies are
not republished (#124102).
Sabotage: disabling the by-uid branch in held_row_mismatches fails this
test (the sync republishes the stale bodies); restored, 49/49 pass.
Co-authored-by: ehz0ah <ehz0ah@users.noreply.github.com>
* fix(sessions): the uid-resolved stale fence CASes the newest active row
held_row_mismatches resolved an id-less held dict by its logical
message_uid with a bare fetchone(): when a carried or concurrent
compaction has cloned the row back beside its archived twin, one uid
names several active physical rows, and the uid index returns them
oldest-first. The fence then CASed the oldest copy — which still held
the payload the held digest was stamped from — and cleared a held
generation as current although another writer had rewritten the newest
row; the lease-less fallback republished the stale held payload over
that newer generation (#124102).
Resolve with the same newest-active rule as the loader's
_active_logical_message_row (ORDER BY id DESC LIMIT 1). Two
regressions pin it: two active rows sharing a uid where only the
newest was rewritten in place must abort the micro-compact naming the
newest row id, and where only an older duplicate moved the held
digest must stay current.
Review follow-up to greptile-apps' 2026-10-17 P1 on PR #124273.
---------
Co-authored-by: defurniture2025 <301948806+defurniture2025@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: teknium1 <127238744+teknium1@users.noreply.github.com>
Co-authored-by: Austin Pickett <pickett.austin@gmail.com>
Co-authored-by: Austin Pickett <austinpickett@users.noreply.github.com>
Co-authored-by: ehz0ah <ehz0ah@users.noreply.github.com>
The salvaged hook fired from ContextCompressor.compress(), which is not where
a compaction commits: compress_context can still refuse or roll back the
candidate (snapshot stale, commit fence, split failure), the gateway's
/compress runs its own compressor and commits elsewhere, and Codex-native,
micro-compaction and proactive-prune rewrites never call compress() at all.
session_id was also the compressor's bound id, which is stale after rotation.
Fire it from the compaction-record seam (agent/compaction_events.py) that
already sees exactly one committed record per rewrite on every agent path,
and from the gateway session.mutate compress commit. Payload: session_id (the
session holding the compacted transcript), old_session_id, kind, reason,
before/after token estimates, messages_removed. Bounded by
plugins.hook_callback_timeout, since it runs inside the commit window.
Tests trimmed to one invariant (fires once per committed compaction, never
for an aborted one, raising plugin isolated); docs in hooks.md and the
plugin guide.
Fires once after a successful context compaction so plugins/providers
can react (re-inject context, update indices, etc.). Gated on has_hook
for zero-cost when no listener. Observer-only, returns ignored.
A compaction that restates the unfinished request as a standalone user row
sends it unstamped; the next gateway turn reloaded it and stamped it like a
message someone sent, so the request diverged from the cached prefix at that
row exactly as the summary row did. The compressor now marks that row with a
producer-owned display_metadata flag (persisted by SessionDB, popped from
every wire copy) and gateway replay skips the stamp for any compaction
scaffolding; the helpers live in agent/message_metadata.py beside the
persistence-only field set.
Human-pasted header text carries no flag and keeps its timestamp.
Ported (trimmed) from #130909's restatement-provenance commits; the merged
carrier layout already carries _compressed_summary so needs no flag.
Co-authored-by: Yuan Li <dskwelmcy@163.com>
Co-authored-by: Ofir Flaisher <6105216+ofirf@users.noreply.github.com>
Once the replay window dropped an oversized upload, the request relaxed to the
100-image ceiling and the from-scratch per-request decision restored all eight
retired screenshots into already-sent history. The main loop and the summary
request builder now pass a session-keyed set of retired tool-call ids; every
carrier up to the newest previously retired one stays retired.
_image_payload returned (blocks, bytes, sources) where blocks and bytes are
derivable from sources; return the sources list alone and derive both at the
call site. Keeps context_compressor.py under its code-health file cap after
the dimension-gating change, with no facade module.
Part of #133999
Mechanism: `agent/image_eviction_policy.outbound_image_retire_count` retired a
batch of 8 once a request carried more than 20 image blocks, for every provider
and every request. 20 is where Anthropic starts holding EVERY image in the
request to a stricter per-side cap -- it is not a count limit, so crossing it
only constrains a request that actually contains an image over that cap. Hermes
already embeds its own tool images well under it (`vision_analyze` and browser
screenshots at 1568 px, `computer_use` at 1456 px by default), and user uploads
are reserved and never rewritten. So on an all-tool-image request the 21st
screenshot crossed no provider constraint, and the batch retire rewrote a cached
prefix for nothing -- on the preserved-thinking models that also invalidates
every later thinking block (Anthropic's computer-use guidance now says to keep
screenshots at or under 2000 px and NOT to prune them client-side).
Seam: the block ceiling becomes conditional. `outbound_image_retire_count` takes
`many_image_safe` and derives `limit` from `outbound_image_block_limit()`, the
strict 20 unless every image in the request is within `MANY_IMAGE_DIMENSION_LIMIT`
(2000 px). Both passes classify from the same module so the #113517 invariant
holds: `context_compressor.evict_stale_outbound_tool_images` (OpenAI shape,
`image_url`) and `anthropic_message_convert._evict_old_screenshots` (wire shape,
`source.data`). Classification is header-only -- `image_max_side_from_data`
decodes just the leading base64 prefix, never a whole payload -- and fails
closed: a missing, unreadable or non-image source keeps today's strict 20.
`image_dimensions_from_bytes` moves into the policy leaf (which the wire
converter already imports and which must not import `tools/`) and is re-exported
from `tools/computer_use/backend.py`, so the tool layer's min-size guard and the
two send-path passes share one PNG/JPEG header reader.
Repro (real passes, pre-change code): 21 tool results carrying one 1568 px image
each -> `evict_stale_outbound_tool_images` returned 8 rewrites; 30 -> 16. Same
fixtures after the change -> 0, and 0 on the wire pass. A 20-carrier request
plus one 2001 px user upload still retires exactly `IMAGE_EVICTION_BATCH` (8),
byte-identical to before.
Independent review follow-up:
- The deterministic fallback summary re-summarizes Phase-1 stubs, and
_sum_skill_view re-decided the marker from the stub text, so a failed view's
stub gained a reload marker there. A stub now keeps its own verdict (marker
only if it already carries one), and a failed stub keeps FAILED.
- The auto-load describer ended a setup note at its first newline, so a
multiline setup hint leaked into the recovered request. The note now ends
at "]" followed by the blank line that separates generated blocks.
- _collect_ghosted_skill_names mapped every parallel skill_view call on one
assistant row to the row's last skill, so two raw loads listed only one. It
now uses the per-call mapping the lean-tail demotion already had.
- Fallback "User asked" anchors render a /skill turn as typed, like the other
summary sections.
Review follow-up (Greptile, two P2s):
- A failed skill_view stub kept no failure outcome, so a later compaction
counted it as a lost skill and asked the model to reload a skill that never
loaded. The stub now carries " FAILED: <error>" like skills_list and
skill_manage, failed raw payloads and stubs are both skipped when collecting
pruned skills, and the lean tail adds no reload marker to a failed view.
- The auto-load describer took everything after the last directory footer as
the typed request, which included the config, setup-note and supporting-file
blocks _build_skill_message appends after that footer. Those blocks are now
skipped by their fixed openings and endings, so previews, titles and the
compaction quotes show only what the user typed.
The lean Anchor Index harvested identifiers from the whole /skill scaffold, so
the footer's example paths (scripts/foo.js, templates/config.yaml) were listed
as files the session touched. User rows now contribute what the user typed.
Compaction stubbed every skill_view body over 200 chars but only bodies over
5,000 chars got the [SKILL_PRUNED: ...] reload marker, so a small skill (about
a quarter of bundled SKILL.md files) lost its instructions with nothing telling
the model to reload it. Skills loaded inline by /skill, bundles, stacked
invocations and the gateway channel auto-load were invisible to the defence:
no marker, no "## Pruned Skills" entry, and lean mode quoted the first 4K of
the skill body as "the user's actual words" while cutting the request the user
typed after it.
- Every stubbed skill_view result gets the marker; a failed view (success:
false) loaded nothing and stays unmarked.
- _collect_ghosted_skill_names counts any skill_view row in the compacted
region regardless of size (plain stubs from earlier compactions included)
and the skills a scaffold turn carried inline.
- skill_commands.skills_loaded_by_scaffold names those skills from a complete
activation header only, so typed text that starts like one is not matched.
- The lean verbatim user block, the historical task snapshot and the auto
focus render a scaffold turn as typed (/skill do X) via
describe_skill_invocation, the approach @100yenadmin took in #136541.
Two existing assertions pinned the old size gate and are updated per the
maintainer's ruling that small skills must be maintained too.
Co-authored-by: Eva <239388517+100yenadmin@users.noreply.github.com>
No conflicts. Brings in main's reasoning-replay series, holographic memory leaving core
(run_profile_reconcile now imports it through import_provider_module), and the update
main-channel fix.
Compaction pruned every earlier-turn codex_reasoning_items on routes assumed not
to read them (a cost choice, #71058), and the first invalid_encrypted_content
rung deleted foreign-issuer items the failing request never sent, then retried a
byte-identical request. Compaction now drops only shadowed checkpoints, and the
rung strips only unverified items that were actually replayed. The request
builder already filters items per issuer and model on the wire.
salvage_grown_transcript (the anti-growth pass at the compaction commit site)
popped reasoning / reasoning_content / reasoning_details from every assistant
turn but the newest, and pruned every prior-turn codex_reasoning_items, before
the result was committed as canonical history. With replay on by default that
is a permanent continuity loss on exactly the long sessions compaction serves.
Reasoning text is now never a salvage shrink target (tool output and summaries
still are), and codex items follow compress()'s route rule
(route_reads_prior_turn_reasoning).
Teknium ruling: every model's reasoning is replayed wherever the provider can consume it.
Live consumption matrix (api.openai.com, api.x.ai) showed four places Responses routes lost it:
- transports/codex.py: send reasoning.context="all_turns" on api.openai.com for the
gpt-5.4 / 5.5 / 5.6 / 6.x families (table in codex_responses_adapter). gpt-5.4/5.5 default
to current_turn and discard replayed earlier-turn blobs without it. o-series, base
gpt-5-mini/nano and gpt-5.1-5.3 400 on it and are absent from the table; the openai-codex
backend and every other host are unchanged. A 400 naming reasoning.context omits it for
that model for the session and retries once (ahead of the reasoning-mandatory rung, which
would otherwise drop the whole reasoning config).
- context_compressor.py: compaction keeps earlier-turn codex_reasoning_items when the route
reads them (xAI, Meta, all_turns OpenAI models: route_reads_prior_turn_reasoning). The
newest-checkpoint rule (#102374) still applies on every route.
- codex_responses_adapter.py: on api.openai.com a blob minted by a sibling variant of the
same family replays (gpt-5.6-luna -> terra, 5.4 <-> 5.4-mini, 6-astra <-> 6.1-sol all
rendered live); exact-model matching everywhere else.
- turn_recovery.py: the first invalid_encrypted_content rejection now drops only blobs not
stamped by exactly this endpoint+model; the full strip / replay disable runs only when
there is nothing unverified to drop or the narrowed retry fails again.
One conflict: agent/context_compressor.py imports. Main's a62979dc36 dropped the
now-unused _safe_int import; the branch's retryable_user_text import is kept.
Review thread on #136083 (agent/context_compressor.py:36). #135807 moved
`_safe_int` into `agent/context_compressor_telemetry.py` but imported it
back into `context_compressor.py` only so `micro_compaction` could keep
reading `_cc()._safe_int`. AGENTS.md forbids re-export shims for internal
moves: `micro_compaction` now imports it directly.
Overflow recovery calls the automatic gate with `bypass_cooldown=True`, so
the summary-failure cooldown cannot be what blocked it. But
`_compression_block_reason()` always reported the cooldown first, so with a
cooldown also active:
- the attempt record said `blocked:cooldown` while the structural backoff
or the ineffective breaker was the real blocker, and
- `_mark_compression_blocked_transient` marked an `ineffective` block as
transient, so overflow recovery deferred instead of counting toward
exhaustion, which #97488 says must never happen.
`_compression_block_reason` takes the gate's `ignore_cooldown` flag.
`_automatic_compression_gate_blocks` reads the reason once, with the same
flag the gate got (older engines keep the no-argument calls), and returns it;
the transient signal and the blocked attempt record both use that one
reason, so the telemetry module no longer re-derives the guard order.
Three conflicts:
- apps/desktop/electron/updater/checkout-source.test.ts: main's 354fe11d7e is the
same releases/latest fixture fix this branch carried as c300c295c1 (#135944); main's
version (it also drops the unused release-candidates route) is taken.
- agent/context_compressor.py: both sides added one import line; both kept.
- gateway/run_turn.py: main's 4c7ab8b2a0 added trigger="gateway_hygiene" to the hygiene
_compress_context call this branch moved to gateway/run_turn_hygiene.py; the branch side
of run_turn.py is kept and the trigger is carried onto the moved call.
A second concurrent turn on a live session (a background-review fork or
a concurrent gateway turn) runs with Relay instrumentation off, but its
compaction mark fell back to the live session's scope. The mark claimed
the live conversation was compacted when only the fork's throwaway
transcript was, and the reserved compaction name reset the live agent
scope's freshness. That also bypassed the opt-out resolve_execution_context
honors.
_resolve_target now returns nothing when relay_instrumentation_enabled()
is false. Publishing also skips persistence-detached agents
(_persist_disabled, set on background-review forks), as micro-compaction
already does in the turn finalizer.
The proactive prune mark moves from ContextCompressor to its caller in
turn_preflight, the one place that knows the agent. That lets it skip a
fork, name the agent's session (a compressor without a bound session id
used to drop the mark), and measure tokens with the same rough message
estimate the attempt record uses.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit 37e177f1494570303f4a010534273a64760b30d3)
Hermes rewrites a session's history in several ways (batch summary,
deterministic fallback, micro-compaction, proactive tool-result prune,
Codex thread compaction) but never told Relay about any of them. A Relay
consumer could not see what was compacted, why, when, how long it took
or whether it went through compress_context, and Relay never reset
LLM-history freshness after a rewrite, so LLM starts after a compaction
stayed projected to the current user turn.
agent/compaction_events.py builds one flat, content-free
hermes.compaction v1 record per rewrite with closed enums (kind, scope,
official, method, trigger, trigger_class, outcome, failure_class) and an
other fallback, plus the effect counts and timings the attempt record
already carries. agent/relay_compaction.py emits it with the existing
scope.event API on the owning session's scope stack: under the live turn
of the same session, else under the session scope, else not at all.
A committed history or provider rewrite uses Relay's reserved
compaction mark name, which resets freshness for the session's agent
scope; every other outcome is a compaction.attempt mark. Records come
from the single attempt telemetry seam (so blocked, Codex-routed and
aborted attempts are covered), the micro-compaction telemetry record,
the proactive prune commit and Codex-native compactions Hermes observes.
No payload carries message, summary, focus-topic, error or path text,
and publishing never raises into compaction.
The marks are on whenever the Relay runtime is live; Relay exporters are
configured separately, so this adds no outbound path and no config key.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit dc5fd0875e7ec895b7826ee829bfc1b7f082de97)
The content-free attempt record is the one place that says why a
compaction ran and what it did, but it could not answer either question:
- Every automatic caller passed no trigger, so idle, turn-start
threshold, engine preflight, pre-API, post-tool and gateway hygiene
attempts all logged trigger_source=auto. Each call site now passes its
own label; the shared metric still buckets them as auto.
- tokens after, message counts and how the summary was made were
computed and logged as prose but never reached the record. A finished
rewrite now records messages_before/after, tokens_before/after,
tokens_reclaimed (signed; a summary can grow a short transcript),
token_count_method=estimate_rough, method (llm_summary,
aux_fallback_main, deterministic_fallback), items_dropped, and the
tool_results_pruned / reasoning_items_pruned pass counts.
- Attempts that never reached the local compressor returned silently:
the automatic breaker gate (before and under the lease), every Codex
app-server exit, a lease that found the session already rotated, and
an unreadable durable cooldown. Each now logs one record with a
commit_status (blocked, skipped, failed, aborted, committed), a route,
and a class such as blocked:cooldown. These stay out of shared metrics,
which never counted them.
Test doubles for _compress_context gain the trigger keyword the call
sites now pass.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit 1795993d1a01d91dd76e6ec824cb606f8a03b897)
context_compressor.py and conversation_compression.py are both past the
2,000-line cap, so the attempt-telemetry fixes that follow need room in
them. Move code that already has a topical home, unchanged:
- ContextCompressor's per-attempt telemetry methods (_begin_compression_telemetry,
_record_compression_regions, _record_aux_compression_call) and _safe_int
become CompressionTelemetryMixin in agent/context_compressor_telemetry.py.
- The Codex app-server compaction route (_compress_context_via_codex_app_server,
_record_codex_compaction_failure) joins its cooldown lookup in
agent/conversation_compression_codex.py and late-imports the facade's
shared helpers.
No behavior change.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit 91d981495f6baee699316d5e843276b32d6a6b9e)
17 conflicts, all from main's lint sweep (ruff UP007/UP017/UP022/UP028/UP031/UP037/UP041,
FURB188/FURB192); no other main commit touches a conflicted file. Resolution: the branch side
of each file plus main's exact autofix (ruff 0.15.10, main's ruff.strict.toml, --fix
--unsafe-fixes). ruff.strict.toml takes main's copy. The pool-retirement live fixture stays
deleted with the pooled backend this branch retires.
8 conflicts, all from main's lint sweep (#135281 "Harder linter fixes" + the RUF series:
implicit-Optional, unused-unpacked-variable, next(...) for [...][0]). No other main commit touches
a conflicted file. Resolution: the branch side of each file plus main's exact autofix
(ruff 0.15.10, main's ruff.strict.toml, --fix --unsafe-fixes) on it. ruff.strict.toml takes main's
copy (the newly enabled rules). tests/cron/test_bot_chat_delivery_child_env.py stays deleted
(1cc9cb9199 retired its lane).
45 conflicts, all from #135177 (lefthook + `ruff check --fix` over 2,366 files). No other main commit
touches a conflicted file. Resolution: the branch side of each file, then main's exact autofix
(ruff 0.15.10, `--config ./ruff.strict.toml --fix`) on it — rewrites only (typing generics, noqa
drops, import forms), no import removed. tests/cron/test_bot_chat_cli_home.py stays deleted
(1cc9cb9199 retired its lane).
Moved unchanged; context_compressor re-exports it for its many importers
(gateway, TUI, CLI, hermes_state_rewind, tests). Code-health FILE_LINES
ratchet on PR #106742 (context_compressor.py 5960 > 5947).
(cherry picked from commit 35f47492375561342841a49277bcd3aa3b1a18a3)
_fallback_summary_for_window logged "Feasibility skip" and the compress()
comment said "feasibility skip", but the flag is now also set when the
summary model is benched. Say "Pre-LLM summary skip" so the log matches
both causes. Wording only; no test asserts the old text.
record_completed_compaction carried two overlapping comments and logged
"via pre-LLM feasibility skip" although the path now also covers the
benched summary model; the anti-thrash comment still said it drops
"counters" when only the ineffective count is reset. Split the long
streak/skip tuple assignment in the stall-retry path and drop the
`is True` hedge (the flag is always a bool on the built-in compressor).
The mixin already owns _set_fallback_probe_at and the model-config key;
the matching load lived inline in bind_session_state, which forced
context_compressor.py to import the key. Move it to
_load_fallback_probe_at() and make the key private to the mixin module.