* 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>
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.
The micro-compaction publisher resolved its Relay parent from the
compressor's current session only. After a rotating compaction earlier in
the turn that session is a child with no Relay scope, so the pass the
finalizer runs before the turn ends lost its mark, while the attempt, prune
and provider-native publishers already fall back to the session the turn
started in.
The finalizer now passes that session to the pass, and its mark takes the
same fallback.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit 3519c942fad6ba2dce3b4475ca7ff56a02c7410f)
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)
`_fallback_to_main_for_compression` clears `summary_model` to mean "use the
main model". But `call_llm(task="compression", ...)` resolves an unspecified
route from `auxiliary.compression`, i.e. the model that just failed. The
fallback therefore re-calls the failing auxiliary model; since
`_summary_model_fallen_back` is already set, no second fallback is allowed,
`_generate_summary` returns None, and with
`compression.abort_on_summary_failure` the whole compression is skipped.
Observed with an auxiliary model whose weekly quota was exhausted: two
identical 429s, `failure_class=summary_generation_aborted`,
`fallback_used=false`, and a session that kept growing uncompressed.
Add `_apply_summary_route()` as the single place that pins the summary wire
route, and use it from both compression entry points (`_generate_summary`
and `_micro_summarize_one`, which had the same defect).
Three existing tests asserted the buggy contract (`assert "model" not in
kwargs`, commented "no model kwarg -> call_llm uses main"); they now assert
the main model is named explicitly.
Salvaged from #88247 (slimmed: docstring, 2 invariant tests; dropped the redundant
_last_summary_auth_failure reset — a main-model success already clears terminal flags).
Fixes#123362.
- Strip persistence-only fields from a select_context() selection: the request copy was stripped before
the hook, but an engine handing back the conversation_messages clones put timestamp, _row_id and the
new ids on the wire (pre-existing for the old fields).
- Every row carries a message_uid whoever wrote it: an AFTER INSERT trigger mints one for a row inserted
without it (an older build writing into a v31 store); the one-time backfill is gated by its own
state_meta marker so a store whose schema version cannot advance (no FTS5) never rescans.
- One merge-witness helper (record_absorbed_message) for every fold of a durable message: alternation
repair's user and assistant merges, the compressor's in-flight restatement onto the carrier, the real
user anchor folded into a scaffolding turn (the anchor's uid leads), micro-compaction's adjacent-user
merge.
- tool_call_uids follows tool_calls: it is a payload column, so an assistant merge's unioned map is
rewritten with the row instead of being overwritten by the stale stored map on adoption.
- A result pairs with the nearest call naming its provider id: each assistant row's ids shadow earlier
occurrences in the batch, restore and live-list indexes, a call row without a map leaves its result
unpaired, and nothing pairs across a user turn.
- A composite rewind returns and installs the replacement row's uid on the live scaffold.
- Tests: import_foreign_history, hermes sessions recover and backup import carry the ids; the ACP
restore test accounts for the uid on restored rows.
(cherry picked from commit b30636a49cb29fdd21ba4100eef9d810897338be)
A gap below the newest held id, and turns appended above an unpersisted current
turn, were summarized away without being read. Name those held ids and clone
the rest.
A compaction landing during the micro summary call made _sync_micro_compact_to_db
skip its write, but _micro_compact still returned the spliced list, advanced the
cursor and reported "absorbed". finalize_turn's _persist_session flush then
appended the unmarked summary row as live, beside the winning generation.
The commit-time re-check also never fired in the common case: held_archive_watermark
returned early when newest_held >= the start watermark, which is always true when
nothing was appended. A lease-less caller (stale_raises=True) now checks the newest
held row's liveness regardless; the in-place lease path is unchanged.
_sync_micro_compact_to_db now reports a stale abort, and _micro_compact then returns
the original list, restores the rolling summary/cursor (and a defragged marker), and
emits stale_generation telemetry. _micro_start_watermark returns
(skip_outcome, watermark) so the two identical pre-flight skip branches collapse.
Prune and micro-compaction hold no compression lease. When the newest exact row of the history they
hold is no longer active, another compaction (a /compress on this or another surface, or an earlier
pass) has already committed. `held_archive_watermark` then falls back to the start watermark, which is
right for the in-place commit (its lease rules out overlap) but for a lease-less caller archives the
winner's rows and clones them back as a "concurrent tail": two summary generations live in one session.
`_archive_watermark_for` now asks `held_archive_watermark` to raise `StaleHeldHistory` on that branch.
The prune commit returns its input unchanged (`prune:stale_generation`), micro-compaction checks before
the slow summary call and skips the pass (telemetry `stale_generation`), and its commit re-checks so a
compaction that lands during the summary call is not overwritten either. The in-place commit keeps its
fallback.
Raised on #120634 by @ehz0ah (agent/conversation_compression.py:3623 thread) and independently by
@JoaoMarcos44 in #120821.
Co-authored-by: ehz0ah <haozhe4547@gmail.com>
Co-authored-by: JoaoMarcos44 <joaomarcosdias444@gmail.com>
_micro_start_watermark collapsed two different answers into None: "this
store has no watermark API", where the commit keeps today's archive-
everything behaviour as it always has, and "the read raised". None means
archive every active row, so a transient store failure committed exactly
the unbounded archive this watermark was added to prevent — a turn another
surface appended vanished from active model history when the read failed
and the write then succeeded.
The helper now returns (status, watermark), and a failed read skips the
pass rather than committing without a bound. The proactive prune path was
already safe: its watermark is resolved inside the try that wraps the
commit, so a raised read aborts the commit instead of widening it.
The new test drives a real SessionDB whose watermark read raises: the pass
must not run and the foreign turn must stay live. Red without the guard.
(cherry picked from commit dd5179e3c72552e6e7737575cc305459728fc549)
Both commits call archive_and_compact with no watermark, which archives
every active row. A turn another surface appended to the same session
after this process loaded it (a Desktop session continued from Telegram)
was archived with the rest as compacted (active=0, compacted=1): marked
summarized away though no summary holds it. The display, REST with
include_compacted and session_search still show it, but it is gone from
the model's history, so the agent forgets a turn the user can still see.
Micro-compaction also runs a slow aux summary call before its commit, so
a turn that arrived during it went the same way.
Both now cap the archive at the newest row the process held, the rule the
in-place compaction commit applies, so those rows take the concurrent-
append path and are cloned after the new set. Micro-compaction captures
the held history and the store's watermark before the summary call and
caps at commit. The cap moves into held_archive_watermark(session_db,
session_id, ...), which the compressor paths can call; _held_watermark
stays as the in-place commit's wrapper.
A store without get_active_message_watermark or get_message_role keeps
today's archive-everything commit, as a store without archive_and_compact
already skips the prune. Micro-compaction's DB sync runs under a broad
except, so an unguarded call there would have failed silently.
Held lists without row ids (the gateway's replay dicts) keep today's
behaviour, as in the in-place commit. Both features are opt-in
(compression.proactive_prune_tokens > 0, compression.micro_compact).
(cherry picked from commit 8d67bee760db0fc65d4330df15198ddfd5f24480)
Superseding a stale micro marker joins the now-adjacent user turns into one
model-facing row, while the originals stay in display history as compacted
rows, so resumed display history painted every merged input twice (and one
more time per later pass). Flag the join display_metadata.model_only and skip
it in every display projection: resume dedupe, the indexed and legacy
get_messages pages, and the prompt timeline. The model payload is unchanged.
Micro-compaction carries a non-contiguous prefix and suffix around its summary marker. Using tail_count=len(result)-1 incorrectly marked summarized assistant/tool rows as rewind-only active=0, compacted=0.
Pass the exact unchanged carried messages instead and resolve their durable originals transactionally by row id or unique identity+timestamp, preserving summarized rows as compacted history.
Fixes#118481
The compound refusal check `_response_refusal_text(response) or
_is_summary_refusal(content)` was spelled out verbatim at both call sites
(agent/context_compressor.py:3639 in `_call_summary_llm` and
agent/micro_compaction.py:157 in `_micro_summarize_one`, the latter through
two separate `_cc()` facade lookups). `_classify_summary_failure` already
describes it as one concept ("refusal content (prose or provider `refusal`
field)"), and the ordering invariant — an explicit provider `refusal` field
wins over summary-shaped content — lived in two callers instead of one place.
Add `_is_refusal_response(response, content)` next to the detectors and call
it from both sites (micro: one `_cc()` lookup). `_is_summary_refusal` and
`_response_refusal_text` stay as-is for the unit tests. Behaviour unchanged.
Proof: guard + micro test files green (62 passed); mutating the new predicate
to `return False` fails exactly the batch refusal-body test, the provider
refusal-field test and the micro refusal test (3 failed, 59 passed).
OpenAI-style structured-output refusals arrive in
`choices[0].message.refusal` with `content` empty or filler, so the
prose detector never sees the refusal and the filler would be committed
as the compaction checkpoint. Read that field (str, or the dict shapes
some proxies emit) in both the batch (`_call_summary_llm`) and micro
(`_micro_summarize_one`) paths and route it through the same
"refusal content" failure so it can never become `_previous_summary`.
Also widen the prose opener with #118406's extra shapes — `we` as
subject, `refuse to`, `could not` / `couldn't`, `apologise`, and a bare
`I'm unable` / `I am not able` opener. #118406's `could(?:not|['’]t)`
missed "couldn't" (it only matched "couldnot"/"could't"); spelled out
here as `could\s*not|couldn['’]t`.
Co-authored-by: Mohamad Kanso <91088196+MohamadKanso@users.noreply.github.com>
The refusal guard in _micro_summarize_one already returns None, which
routes through _record_micro_failure like every other failed
summarization. Snapshotting and restoring _micro_compact_cursor around
that path changed the behaviour of EVERY summarize_failed outcome, not
just refusals, to satisfy one test's cursor assertion. The cursor write
in _resolve_compact_cursor is an idempotent re-resolution, so there is
nothing to undo.
The test now resolves the cursor via _next_exchange before snapshotting
it, so it still proves the source exchange survives a refusal without
needing production code to rewind state.
The _db_persisted marker asserts that a message dict's persisted row is
durable as written; any in-place mutation must pop it or the flush scan
identity-skips the dict and state.db keeps the stale row forever. Six
mutation sites violated the contract:
- micro_compaction._merge_adjacent_user_turns rewrote content on a
carried-forward dict after superseding a stale micro marker. On the
archive-failure path nothing re-stamps, so the merged text never
reached state.db.
- repair_message_sequence passes mutated stamped survivors in place:
_merge_assistant_into (tool_calls union, content join,
reasoning_content carry), _prune_unanswered_tool_calls (tool_calls
rewrite), _merge_consecutive_users (content join).
- sanitize_tool_call_arguments rewrote corrupted/blank
function.arguments and prepended the corruption marker onto stamped
resumed rows, leaving the corrupt bytes durable and self-perpetuating
across resumes.
- _sanitize_messages (surrogate and non-ASCII recovery) and
_strip_images_from_messages (image-rejection recovery) rewrote live
dicts on the recovery path.
Each site now pops the marker when a persisted field actually changes,
and the agent-aware callers (repair_message_sequence_with_cursor,
turn_iteration_prep, turn_recovery) invalidate the bounded flush-scan
prefix so repaired rows are rewritten on the next flush.
For each issue anchor present in BASE 63279301bc non-test .py and absent on HEAD, the BASE comment/docstring block was re-attached at the HEAD location of the code it explained (matched by the distinctive code line / enclosing def). Sentences already covered by an existing HEAD comment were deduped; the issue number always survives. Insert-only: no code lines changed.
The 15 rolling micro-compaction methods (cursor resolution, exchange
serialization, one-exchange summarization, defrag, splice, DB sync, telemetry)
move verbatim into MicroCompactionMixin, mixed into ContextCompressor
(MRO: ContextCompressor -> MicroCompactionMixin -> ContextEngine). Origin
constants and call_llm are imported lazily so tests patching
agent.context_compressor.X still apply; logger name parity is kept.