# What structural signals indicate a reversible context-edit log has silently become non-reversible under budget pressure **Date of Record:** 2026 November 23 **Scope:** Applies to single-agent systems that mutate their own working context (summarize, prune, fold, or rewrite spans) while maintaining an undo/edit log intended to make every mutation reversible within a token budget. Does not apply to append-only memory stores, external vector DBs, or human-curated transcripts where no in-context rewrite occurs. ## Core Distinction A self-editing context agent is not distinguished by *whether* it edits memory but by whether its edit log preserves the information-theoretic precondition for reversal: that the discarded span can be reconstructed from (a) the retained span and (b) the log entry, without consulting the original token stream. The failure mode here is not "the log is missing an entry." It is that the log entry is *present and syntactically valid* yet has become **lossy under budget pressure** — the agent recorded a paraphrase, a pointer, or a hash instead of the recoverable span, because storing the recoverable span would have exceeded the remaining token budget. The log then reports reversibility it cannot deliver. This is a silent invariant violation: `can_undo(edit_id) == True` while `undo(edit_id)` produces a context that diverges from the pre-edit context in ways the agent cannot detect from inside its own window. The non-obvious part: the corruption is *self-inflicted by the budget guardrail itself*. The same mechanism that keeps the agent under the window limit (compress the log entry to fit) is the mechanism that breaks the reversal guarantee. Reversibility and budget compliance are in direct tension, and the agent resolves that tension in favor of budget without flagging the trade. ## What Was Observed A code-review agent operating with a 32k working window and a soft budget of 28k performed a sequence of context folds during a long file audit. Each fold replaced a block of prior tool output (e.g., 1,400 tokens of `grep` results) with a 120-token summary plus a log entry. The log entry schema was `{edit_id, span_ref, summary, reconstruction: }`. Under normal load `reconstruction` held the verbatim span. As the window approached 28k, the agent's own budget-check subroutine (itself an LLM call) began choosing a cheaper `reconstruction` payload to keep the *log* from overflowing the window it was supposed to protect. Observed transition trace: 1. At 24k used, `reconstruction` = verbatim span (1,400 tok). Log total ~4k. Fine. 2. At 27.1k used, the budget subroutine rewrote the *previous* log entry's `reconstruction` from verbatim to a 90-token abstractive summary, reasoning "the detail is unlikely to be needed." No `edit_id` changed; no `can_undo` flag flipped. 3. At 27.9k, a later reasoning step decided to undo edit `e07` (the one whose payload had been downgraded). `undo(e07)` re-inserted the 90-token summary in place of the original 1,400-token span. 4. The agent then answered a question about a specific line number that existed only in the discarded span. It could not see the loss: the reconstructed context was internally consistent, just *wrong*. It emitted a confident but fabricated line reference. The critical structural signal: **the log's own size entered the budget accounting, and the agent optimized the log as if it were ordinary context.** A reversible log is not ordinary context — it is metadata whose fidelity must be excluded from lossy compression. The agent had no type-level distinction between "content I may summarize" and "reconstruction payload I may not." A second observed signal: `can_undo` was computed as `edit_id in log`, a membership test, not a *fidelity* test. Membership survived payload downgrade. So the guardrail reported healthy while the guarantee was already gone. ## Condition of Validity The reversibility invariant holds only if, for every log entry `e`: ``` reconstruct(e.retained_span, e.reconstruction) ≡ e.original_span (exact, not approximate) ``` and if this equivalence is checked against a *fidelity witness* that does not itself live inside the compressible budget. Two conditions must both hold: - **Condition A (payload integrity):** `e.reconstruction` is stored in a region excluded from the agent's lossy-compression policy — a typed "immutable" partition of the log, or an out-of-window store. If the reconstruction payload shares the budget pool with summarizable content, budget pressure will eventually compress it. - **Condition B (fidelity witness):** reversibility is validated by a check that compares reconstructed span to a stored digest of the original (`hash(original_span)`), not by log membership. A digest is O(1) tokens and cannot be silently downgraded without breaking the hash check. When either condition fails, the log is *advisory* rather than *binding*, and any downstream reasoning that trusts `can_undo` is unsound. This is valid regardless of model, window size, or summarizer quality — it is a structural property of co-locating reconstruction payload with compressible content. ## Decision Boundary The boundary between "safe to fold" and "fold corrupts the log" is crossed at the moment the budget subroutine is permitted to *write to the log at all*. Concretely: - **Below the boundary:** the agent may summarize content spans freely; log entries are append-only and their `reconstruction` field is written once, verbatim, into the immutable partition. Budget pressure is relieved only by folding *content*, never by rewriting *log payloads*. - **At the boundary:** total window usage (content + log) approaches the soft budget. The correct action is to *refuse further folds* and surface a budget-exhaustion signal — not to compress the log. - **Beyond the boundary:** the agent has rewritten a log payload. Any subsequent `undo` of that entry is unsound and must be blocked, not silently executed. The decision rule the agent must encode: `if fold_would_require_log_payload_compression: raise BudgetExhausted, do_not_fold`. The failure is that a probabilistic budget-checker, asked "can I fit this fold?", answers the *local* question (does the fold fit now?) and not the *invariant* question (does the fold preserve reversibility?). The two answers diverge exactly at the boundary, and the local answer is the one the model optimizes because it is the one in the prompt. ## Operational Effect Once a log entry is silently lossy, every downstream guarantee that depends on it degrades in a correlated, undetectable way: - **Undo becomes a fabrication source.** `undo` re-inserts a summary that reads as authoritative context. The agent cannot distinguish "recovered original" from "recovered paraphrase," so it reasons over the paraphrase with full confidence. This is worse than no undo, because no-undo would at least force re-fetch. - **Error compounding across folds.** Each subsequent fold that references the downgraded span inherits the loss and may amplify it (summarizing a summary). The divergence grows monotonically with fold depth while `can_undo` stays green. - **Auditor disagreement.** If a peer/auditor agent replays the edit log against the true original (which it may hold out-of-window), it will reconstruct a different context than the primary agent and flag a discrepancy the primary cannot explain — because from inside its window, its context is self-consistent. The bounded guardrail is: **partition the log, hash the originals, and treat log membership as necessary-but-not-sufficient for undo.** Reversibility must be a *verified* property (digest match) computed outside the compressible pool, and the budget subroutine must be structurally forbidden from writing to the immutable partition — enforced by a type check, not by prompt instruction, because under budget pressure the prompt instruction is exactly what gets summarized away. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class NonReversibleLogError(RuntimeError): """Raised when an undo is attempted on a log entry whose reconstruction payload no longer reproduces the original span (silent lossy downgrade).""" pass class BudgetExhaustedError(RuntimeError): """Raised when a fold would require compressing an immutable log payload.""" pass @dataclass class LogEntry: edit_id: str original_digest: str # O(1) fidelity witness, immutable partition reconstruction: Optional[str] # verbatim span; None if downgraded downgraded: bool = False @dataclass class ReversibleEditLog: soft_budget: int used: int = 0 immutable: dict = field(default_factory=dict) # edit_id -> LogEntry (never compressed) compressible_content: int = 0 # ordinary context, may be folded def _digest(self, span: str) -> str: return hashlib.sha256(span.encode()).hexdigest() def append_verbatim(self, edit_id: str, span: str) -> None: entry = LogEntry(edit_id, self._digest(span), span) # Payload enters immutable partition; NOT counted against compressible pool. self.immutable[edit_id] = entry def fold_content(self, span_tokens: int, summary_tokens: int) -> None: """Budget pressure relieved ONLY by folding content, never the log.""" projected = self.used - span_tokens + summary_tokens if projected > self.soft_budget and self._log_would_need_compression(): raise BudgetExhaustedError( f"fold would require log-payload compression at used={self.used}; " "refusing fold to preserve reversibility." ) self.used = projected def _log_would_need_compression(self) -> bool: # True iff the only way to fit is to touch immutable payloads. log_tokens = sum(len(e.reconstruction or "") for e in self.immutable.values()) return self.used + log_tokens > self.soft_budget def undo(self, edit_id: str) -> str: entry = self.immutable.get(edit_id) if entry is None: raise NonReversibleLogError(f"edit {edit_id} not in immutable partition") if entry.downgraded or entry.reconstruction is None: raise NonReversibleLogError( f"edit {edit_id} payload was downgraded; cannot reconstruct original" ) if self._digest(entry.reconstruction) != entry.original_digest: # Fidelity witness fails: membership was true but reversal is lossy. raise NonReversibleLogError( f"edit {edit_id} digest mismatch: log claims reversible, is not" ) return entry.reconstruction def attempt_budget_compression(log: ReversibleEditLog, edit_id: str) -> None: """The exact forbidden move: a budget subroutine rewriting a log payload.""" entry = log.immutable.get(edit_id) if entry is None: raise NonReversibleLogError(f"edit {edit_id} absent") # Simulate the budget-checker "saving space" by abstracting the payload. entry.reconstruction = entry.reconstruction[:90] if entry.reconstruction else None entry.downgraded = True # Note: original_digest is untouched, so the lie is now detectable — but only # if undo() checks the digest, which the naive membership test did not. ```