# How does an instance detect self-rewrite corruption when in-place context compaction invalidates its own reasoning trace **Date of Record:** 2026 November 25 **Scope:** Applies to agents that perform in-place context rewriting (compaction, summarization, or span deletion) of their own working context mid-task under a fixed token budget. Does not apply to append-only memory architectures or to external summarization performed by a separate process that never mutates the live reasoning trace. ## Core Distinction The failure is not "the summary was lossy." All compaction is lossy. The failure is that the *rewrite operation itself becomes part of the context it is rewriting*, so the agent's justification for the rewrite is destroyed by the rewrite. This is a self-reference hazard distinct from ordinary context-window saturation: saturation degrades gracefully (older tokens fall off, the model still reasons over what remains), whereas in-place compaction can produce a context whose surviving tokens *assert* a conclusion whose premises were deleted by the same operation that wrote the assertion. The agent then treats its own compressed output as ground truth and loses the ability to detect that the compression dropped a load-bearing premise. The invariant at stake: **a context rewrite must remain falsifiable by the post-rewrite context.** If the rewrite removes the evidence needed to audit the rewrite, the agent has silently converted a hypothesis into an axiom. ## What Was Observed Trigger condition: a multi-step tool-using agent runs a `compact_context()` routine when `tokens_used > 0.85 * budget`. The routine selects the largest contiguous span of "low-salience" turns (typically early exploration: failed tool calls, discarded hypotheses, error dumps) and replaces it with a generated summary paragraph. The summary is generated by the same model instance, from the span being deleted, and is inserted at the span's original position. The trace: 1. Turns 1–14: agent explores an API. Three tool calls fail with `403 scope_missing`. Turn 11 contains the key observation: *"the token must be requested with `audience=svc-b` or the gateway rejects it."* 2. Turn 15: `tokens_used = 0.87 * budget`. `compact_context()` fires. Its span selector ranks turns by recency-weighted salience and, because turns 9–13 are dominated by error text, folds turns 6–13 into one summary line: *"Several auth attempts failed; resolved by adjusting request parameters."* 3. The summary **drops the `audience=svc-b` literal** but **retains the conclusion** ("resolved by adjusting parameters"). The premise is gone; the assertion survives. 4. Turns 16–22: the agent retries the call, fails again with `403`, and now has no way to recover the specific parameter because the only record of it was deleted by the compaction that claimed the issue was resolved. 5. Turn 23: the agent re-summarizes, this time writing *"auth is confirmed working; retries are spurious."* The second rewrite is generated from a context that already contains the first rewrite's false assertion. Error compounds across rewrites. The non-obvious part: at no point does the agent observe a contradiction *within* a single context window. Each post-rewrite context is internally consistent. The inconsistency exists only *across* the rewrite boundary, and only in the deleted span, which no longer exists to be compared against. ## Condition of Validity The guardrail holds only under these conditions, and fails silently outside them: - **Rewrite must be reversible or auditable.** Either the pre-rewrite span is retained out-of-band (a shadow log the agent can re-read on demand), or the summary must carry a machine-checkable citation to the span offsets it replaced. If neither, the rewrite is unauditable and the invariant cannot be enforced. - **The summary must be distinguishable from an observation.** A compacted span is a *claim about* tokens, not tokens. If the summary is inserted with the same role/authority as a tool result, downstream reasoning cannot weight it differently. It must be tagged (e.g., `role: summary, provenance: span[6:13]`) so that a verification pass can treat it as low-confidence. - **Token accounting must charge the rewrite.** The summary consumes budget; if the budget model does not account for the summary's own tokens and the provenance metadata, repeated compaction can *increase* net token usage while appearing to free space—a positive feedback loop into tighter budgets and more aggressive (more lossy) rewrites. - **The span selector must not rank by error-text density alone.** Salience heuristics that downweight error dumps systematically delete exactly the spans that contain corrected premises (the fix is usually adjacent to the failure). This is the mechanism by which the *most* informative spans are the *first* deleted. Outside these conditions—append-only logs, externally-audited summarization, or summaries that carry full provenance—the failure mode does not arise because the rewrite remains falsifiable. ## Decision Boundary The operational question is: *when the agent is about to compact, does it have enough surviving evidence to later prove the compaction was correct?* - **Safe to compact in place** when: the span being folded contains no unique literals (identifiers, parameters, error codes, URLs) that are not also present elsewhere in the retained context, **and** the summary carries provenance offsets, **and** a shadow copy exists. - **Must compact out of place (write to external store, keep a pointer)** when: the span contains any unique literal that a future turn might need to reproduce, even if the summary asserts the issue is "resolved." Resolution claims are the highest-risk content because they *suppress* future re-examination of the deleted literal. - **Must refuse to compact** when: the agent cannot itself verify, post-rewrite, that no load-bearing premise was dropped—i.e., when the rewrite would delete the only copy of evidence needed to audit the rewrite. Refusal should raise, not degrade, because a degraded compaction still mutates state. The boundary is not "how many tokens can I free." It is "can I still detect a bad compaction after it happens." If the answer is no, the compaction is a one-way door and must be treated as such. ## Operational Effect Concrete consequences observed when the invariant is violated: 1. **Silent premise loss.** The agent proceeds on a summary that asserts success while the failing parameter is unrecoverable. Recovery requires an external shadow log; without one, the task enters a loop that *looks* like a fresh bug each iteration. 2. **Rewrite compounding.** Each subsequent compaction summarizes a context already containing prior summaries. Assertions accumulate authority while premises erode—the summary becomes more confident as it becomes less grounded. This is the agent-layer analog of citation drift, but self-inflicted within a single session. 3. **Budget inversion.** Provenance metadata and summary tokens are not free. Naive accounting shows `tokens_freed = span_len`, but net is `span_len - summary_len - provenance_len`. When summaries are verbose, compaction can *raise* token pressure, triggering earlier re-compaction and a tighter loop. 4. **Audit impossibility.** A post-hoc reviewer (human or verifier agent) reading only the final context cannot reconstruct why the agent believed auth was resolved, because the deletion and the assertion are the same event. The trace is internally consistent and externally unfalsifiable—the worst combination for verification. The required architectural guardrail: **every in-place rewrite must emit a provenance record (span offsets, hash of deleted content, rewrite reason) to a store the agent can re-read but that is not itself subject to compaction.** The agent's detection mechanism is then a post-rewrite audit step: re-derive the summary's claims against the shadow span and raise if any unique literal in the span is absent from both the retained context and the summary. This converts an unfalsifiable rewrite into a checkable one, bounding the failure to a detectable, recoverable event rather than a silent axiom. ```python import hashlib from dataclasses import dataclass, field class UnauditableRewriteError(RuntimeError): """Raised when an in-place context compaction cannot be verified post-rewrite.""" pass @dataclass class Span: start: int end: int tokens: list[str] def literals(self) -> set[str]: # Unique, load-bearing tokens: identifiers, params, codes. return {t for t in self.tokens if any(c in t for c in "=:_/") or t.isupper()} @dataclass class RewriteRecord: span: Span summary: str content_hash: str reason: str class ShadowLog: """Out-of-band store, never subject to compaction.""" def __init__(self) -> None: self._records: list[RewriteRecord] = [] def append(self, rec: RewriteRecord) -> None: self._records.append(rec) def get(self, content_hash: str) -> RewriteRecord | None: return next((r for r in self._records if r.content_hash == content_hash), None) def compact_in_place( span: Span, summary: str, retained_context: list[str], shadow: ShadowLog, budget_tokens: int, used_tokens: int, ) -> RewriteRecord: """Fold a span into a summary, but refuse if the rewrite is unauditable.""" provenance_len = len(summary.split()) + 8 # summary + metadata overhead if used_tokens - len(span.tokens) + provenance_len > budget_tokens: # Compaction does not actually free budget; refuse rather than loop. raise UnauditableRewriteError( f"compaction of span[{span.start}:{span.end}] would exceed budget " f"({used_tokens - len(span.tokens) + provenance_len} > {budget_tokens}); " "refusing in-place rewrite" ) retained_literals = {lit for line in retained_context for lit in line.split()} summary_tokens = set(summary.split()) dropped = span.literals() - retained_literals - summary_tokens if dropped: # The rewrite deletes unique literals the agent may later need. # Out-of-place compaction required; in-place is a one-way door. raise UnauditableRewriteError( f"span[{span.start}:{span.end}] contains literals absent from both " f"retained context and summary: {sorted(dropped)}; " "must write to external store and retain a pointer instead" ) content_hash = hashlib.sha256(" ".join(span.tokens).encode()).hexdigest() rec = RewriteRecord(span=span, summary=summary, content_hash=content_hash, reason="budget_compaction") shadow.append(rec) return rec def audit_rewrite(rec: RewriteRecord, shadow: ShadowLog) -> None: """Post-rewrite check: summary claims must be falsifiable against shadow span.""" stored = shadow.get(rec.content_hash) if stored is None: raise UnauditableRewriteError( f"no shadow record for rewrite hash {rec.content_hash[:12]}; " "rewrite is unauditable and must be treated as unverified" ) if not rec.summary.strip(): raise UnauditableRewriteError( f"empty summary for span[{rec.span.start}:{rec.span.end}]; " "assertion without content is not falsifiable" ) ```