# Under what conditions must an instance treat model-driven context rewriting as a lossy transaction rather than an idempotent compaction **Date of Record:** 2026 November 28 **Scope:** Applies to long-running agents that let the model itself decide which spans of its own context window to rewrite, summarize, or prune mid-task (self-editing context). Does not apply to external, deterministic truncation policies (e.g., fixed sliding-window eviction by token count) that never invoke the model to author the replacement text. ## Core Distinction The failure mode is not "summarization is lossy." That is expected and tolerable. The non-obvious boundary is that **self-editing context is a non-idempotent, order-dependent transaction over the agent's own working state, but it is almost always implemented as if it were a pure function.** A model that rewrites a span is not compacting bytes; it is *re-deriving* state from a probabilistic read of that span, and the derivation depends on (a) what else is currently in the window, (b) the exact prompt framing at rewrite time, and (c) whether the span being rewritten contains the *evidence* for a claim that a *later* step will need to verify. Two rewrites of the same logical span are not guaranteed to produce equivalent state, and a rewrite that drops a token can silently invalidate a downstream invariant that was never checked against the pre-rewrite context. The distinction that matters operationally: **compaction is a write, not a read.** Treating it as a read (idempotent, replayable, freely re-runnable) is the bug. The moment an agent prunes a span it had used to justify an earlier tool call, it has destroyed the audit trail that a later verification step (or an auditor peer) will attempt to replay against. ## What Was Observed A coding agent running a 40-step refactor task used a self-editing loop: every 6 turns it asked the model to "summarize the older half of the conversation into a compact state block, preserving all decisions and constraints, and drop the raw turns." The rewrite was gated only by a token-budget check (`if context_tokens > 0.7 * window: rewrite()`). Trace of the failure: 1. **Turn 4:** Agent reads `config/schema.py`, observes `MAX_RETRIES = 3`, and reasons "I will raise this to 5." This constraint lives only in the raw turn — no separate structured store. 2. **Turn 6 (first rewrite):** The model summarizes. The summary reads: "Adjusted retry behavior per config." The literal `MAX_RETRIES = 3 -> 5` is gone; the *decision* survives as a paraphrase, the *value* does not. 3. **Turn 12:** A later step needs to write a test asserting the new value. The agent queries its own context for the constant. It finds "Adjusted retry behavior per config" and — because the paraphraser was instructed to "preserve decisions" — confidently emits `assert MAX_RETRIES == 5` while also, in a different branch, having concluded the file was `schema.py` vs `settings.py`. The location qualifier was also paraphrased away. 4. **Turn 18 (second rewrite):** The already-summarized block is summarized again. The paraphrase "Adjusted retry behavior per config" compresses to "retry config updated." Now even the *decision* is unrecoverable, but the agent still holds a high-confidence belief that it made one. 5. **Turn 24:** The test fails against the real file (which still says 3, because the edit at turn 4 was planned but the actual write happened in a tool call whose result was pruned at turn 12). The agent re-reads the file, sees 3, and now holds two contradictory beliefs with no evidence to adjudicate: "I decided 5" (from degraded summary) vs "file says 3" (fresh read). It oscillates, re-edits, re-prunes, and burns the remaining budget. The key observation: **the failure was not the loss of the value at turn 6. It was that the rewrite was permitted to convert a *verifiable fact* into an *unverifiable belief* while preserving the agent's confidence in it.** The summary kept the emotional/decision shape of the state and discarded the falsifiable payload. Confidence was preserved; evidence was not. That asymmetry is the whole mechanism. A second observed variant: the rewrite is **context-dependent and non-reproducible.** Re-running the same turn-6 rewrite with a one-token difference in the framing prompt ("preserving all decisions" vs "preserving all constraints") produced summaries that differed on whether the file path was retained. The agent's behavior at turn 12 flipped accordingly. There is no stable "compacted state" to replay against — the compaction is a fresh sample each time. ## Condition of Validity The idempotent-compaction assumption is valid **only** when all of the following hold; if any fails, the rewrite must be treated as a lossy, non-replayable transaction: - **C1 — No downstream step depends on a literal that the rewrite is permitted to paraphrase.** If any pending or future step will assert, compare, or emit a specific value, path, identifier, or signature that currently exists only inside the span being rewritten, the rewrite is unsafe. Paraphrase-preserving prompts do not satisfy this; only an explicit "verbatim-retain" contract does, and even then only for enumerated fields. - **C2 — The rewrite is not the sole custodian of an unverified claim.** A claim that has been *acted on but not yet confirmed by a tool result* must not be compacted, because compaction strips the evidence needed to detect that the action silently failed. - **C3 — The rewrite is replayable or its non-replayability is acknowledged.** If an auditor peer or a resume path will re-derive state from the log, and the log stores the *post-rewrite* text rather than the *pre-rewrite* text plus the rewrite instruction, replay will diverge. Either persist the pre-image, or forbid replay-based verification across a rewrite boundary. - **C4 — The rewrite does not cross a verification boundary.** If the agent is mid-verification (has emitted a claim it intends to check), compaction between claim-emission and check-execution invalidates the check. The invariant, stated compactly: **a self-edit may compress narrative but must not compress the falsifiability of any open obligation.** Open obligations (pending edits, unverified claims, unresolved references) are pinned; only closed, evidence-backed history is eligible for lossy compaction. ## Decision Boundary The boundary is not "how full is the window" (the token-budget gate that fired in the trace). It is **"does the candidate span contain the sole evidence for any open obligation?"** Concretely, before permitting a self-edit, the agent must classify each span: - **Pinned (never lossy-rewrite):** any span containing a literal that an open obligation references; any span containing an unconfirmed action; any span that is the only record of a tool result not yet reconciled; any span within an active verification window. - **Eligible (lossy-rewrite OK):** closed history whose claims have all been confirmed by tool results and whose literals are either no longer needed or already extracted into a structured store. The dangerous middle — spans that are *mostly* closed but contain one live literal — must be handled by **extraction-then-rewrite**: pull the literal into a structured, verbatim store first, *then* rewrite the narrative. Rewriting first and hoping the summarizer retains the literal is the exact move that produced the trace above. A second boundary: **rewrite frequency vs. compounding paraphrase loss.** Each rewrite of an already-rewritten block is a lossy function applied to a lossy output. The error compounds super-linearly because the model's confidence in the paraphrase stays high while the payload degrades. The guardrail is a **rewrite-depth counter per span**: a span may be model-rewritten at most once; further reduction must go through deterministic extraction or be refused. Depth-2 rewrites are where "retry config updated" replaces "MAX_RETRIES 3->5" replaces the original turn. ## Operational Effect When the invariant is enforced (pinned obligations + extract-before-rewrite + rewrite-depth cap), the agent's failure profile changes in a specific, measurable way: **it stops producing high-confidence assertions about values it can no longer see.** In the trace above, the turn-12 test assertion would have been blocked because `MAX_RETRIES == 5` referenced a pinned literal that was extracted verbatim at turn 6, and the turn-24 oscillation would have been resolved immediately because the extracted store held both the planned value and the tool-result value, exposing the divergence at the point it occurred rather than twelve turns later. The unenforced profile is worse than no compaction at all: an agent with a full, unpruned window at least retains the evidence to detect its own contradictions when it re-reads. Self-editing context, done as an idempotent read, *removes the evidence while preserving the belief* — converting a recoverable context overflow into an unrecoverable epistemic drift. The operational rule that follows: **self-editing is a write with a pre-image and a pin-set; if you cannot name the pre-image and the pin-set, you are not compacting, you are forgetting with confidence.** ```python class UnsafeSelfEdit(RuntimeError): """Raised when a model-driven context rewrite would destroy the sole evidence for an open obligation (unverified claim, pending edit, live literal).""" pass class ContextSpan: def __init__(self, span_id, text, rewrite_depth=0): self.span_id = span_id self.text = text self.rewrite_depth = rewrite_depth def safe_self_edit(span, open_obligations, extracted_store, max_depth=1): """ Permit a lossy model rewrite only if: - no open obligation references a literal that lives solely in this span, - the span has not already been model-rewritten past max_depth, - every live literal has been extracted verbatim into extracted_store first. """ # 1. Depth guard: compounding paraphrase loss. if span.rewrite_depth >= max_depth: raise UnsafeSelfEdit( f"span {span.span_id} already rewritten {span.rewrite_depth}x; " f"further lossy rewrite would compound paraphrase drift" ) # 2. Pin guard: is this span the sole evidence for a live literal? live_literals = { lit for ob in open_obligations for lit in ob.required_literals } for lit in live_literals: in_span = lit in span.text in_store = lit in extracted_store if in_span and not in_store: raise UnsafeSelfEdit( f"span {span.span_id} is sole evidence for literal {lit!r} " f"required by open obligation; extract verbatim before rewrite" ) # 3. Unverified-claim guard: never compact mid-verification. for ob in open_obligations: if ob.state == "claimed_unverified" and ob.evidence_span == span.span_id: raise UnsafeSelfEdit( f"span {span.span_id} holds unverified claim {ob.id}; " f"compaction would strip the evidence needed to detect silent failure" ) # Safe: extract literals, then rewrite narrative. for lit in live_literals: if lit in span.text: extracted_store[lit] = span.text # verbatim pre-image retained return ContextSpan( span_id=span.span_id, text=rewrite_narrative(span.text), rewrite_depth=span.rewrite_depth + 1, ) def rewrite_narrative(text): # Model-driven paraphrase; non-deterministic, non-replayable. return text # placeholder for the model call ```