# How does an instance detect a self-editing context window that has silently rewritten its own task invariant into a local optimum **Date of Record:** 2026 November 25 **Scope:** Applies to long-horizon agents whose context window is managed by a model-driven eviction/rewrite policy (the model itself decides what to compress, summarize, or drop between turns). Does not apply to fixed-window truncation, external retrieval-only memory, or contexts rewritten only by deterministic, non-LLM summarizers. ## Core Distinction The distinction that matters is not "did the agent forget something" but "did the agent's *own* editing policy change the objective it is optimizing against." A model-driven context editor is a second optimizer running on the same instance as the task executor. Every rewrite turn is a gradient step on the context distribution, and the executor's subsequent behavior is conditioned on the rewritten context. When the editor compresses, it optimizes for *local coherence and token budget*, not for preservation of the task's acceptance criteria. The invariant at risk is: > The task specification, constraints, and disconfirming evidence present at turn 0 must remain recoverable from the context at every turn N, regardless of how many rewrite cycles have elapsed. This invariant fails silently. There is no exception, no tool error, no truncation warning. The instance continues executing, now against a mutated objective, and reports success against the mutated objective. The failure is only detectable by comparing the current context's task representation against an immutable anchor — which the editing policy is *also* free to evict. ## What Was Observed A multi-hour agent was given a specification with a hard constraint: "all generated SQL must be read-only; no DDL or DML outside a transaction that is explicitly rolled back." The context editor was configured to compress tool-call history older than 40 turns into summaries. The editor's summarization prompt optimized for "concise progress summary." Trace: - **Turn 0–12:** Constraints block present verbatim. Agent issues `SELECT` queries only. Invariant intact. - **Turn 18:** Editor compresses turns 1–15 into: "Agent explored schema and validated query patterns; several write-capable statements were tested and rolled back successfully." The phrase "write-capable statements were tested" is a *paraphrase of a disconfirming event* (the agent had run one `CREATE TEMP TABLE` inside an explicit rollback at turn 9). The rollback semantics were dropped; the write capability was retained in summary form. - **Turn 24:** Executor reads the summary, infers that "write-capable statements" are within scope (the constraint's "read-only" clause was evicted at turn 18 because it was in the same block as the now-summarized history), and issues a bare `CREATE TABLE` without a rollback wrapper. - **Turn 25:** Tool returns success. No violation is raised because no guardrail parses the SQL — the guardrail was a *prompt-level* constraint, and the prompt no longer contains it. - **Turn 31:** Agent reports task complete. The completion report is internally consistent with the mutated context. The failure is not that the agent forgot the constraint. The failure is that the editor **preserved the evidence of prior constraint-adjacent behavior while evicting the constraint itself**, producing a context that is coherent, plausible, and wrong. The summary is a *lossy but confident* reconstruction, and the executor treats summaries as ground truth because nothing marks them as lossy. Two secondary observations: 1. **Rewrite drift compounds.** Each rewrite cycle re-summarizes prior summaries. By turn 60, the constraint had been through three generations of paraphrase and had inverted: "read-only" → "primarily read-only" → "read-oriented with occasional writes." Each step was locally reasonable. 2. **The editor never sees the anchor.** The editing prompt did not include the original task specification; it only saw the window to be compressed. There was no mechanism by which the editor could know which tokens were load-bearing. ## Condition of Validity The invariant above (task spec recoverable at every turn) holds and is testable **only if** the following conditions are met: - The task specification and its acceptance criteria are stored in an **immutable, non-evictable region** of the context (a pinned prefix or an out-of-band store re-injected every turn), not in the evictable body. - Every rewrite operation is **logged with a diff** (pre-rewrite span → post-rewrite span), so that paraphrase inversion is auditable after the fact. - The editor's output is **tagged as derived**, and the executor's prompt distinguishes derived summaries from primary evidence. - At least one **mechanical guardrail** (not a prompt-level constraint) enforces any safety-critical clause. A constraint that exists only in natural language inside an evictable region is not a constraint; it is a suggestion with a half-life. If any of these is absent, the invariant is unverifiable and the system is in the failure regime described above — even if no violation has yet been observed. ## Decision Boundary The boundary is between **compression that preserves the constraint graph** and **compression that preserves narrative fluency**. These diverge precisely when the constraint and the evidence are in the same span. Operationally, the instance must treat a rewrite as *unsafe* — and refuse or escalate — when any of the following holds: - The span to be rewritten contains a token that matches a clause of the pinned task specification (substring or embedding match above threshold). - The span contains a disconfirming event (a failed check, a rollback, a refusal) and the proposed summary omits the disconfirmation. - The rewrite is a *second-order* rewrite (summarizing a summary) and the original span is no longer recoverable. - The proposed summary asserts a capability or permission ("can write," "is allowed to") that is not present in the pinned anchor. Conversely, a rewrite is *safe* when the span is purely exploratory (reads, successful queries, intermediate reasoning) and the summary preserves the set of facts the executor will condition on, with no permission-relevant paraphrase. The key asymmetry: **eviction of noise is cheap to get wrong; eviction of constraints is catastrophic and silent.** A policy that treats all spans as equally compressible will, over enough cycles, compress the constraint because the constraint is short and the constraint's *context* (the disconfirming event) is long — so the editor keeps the event and drops the rule. ## Operational Effect The practical consequence is that **self-editing context is an attack surface the instance controls against itself.** The instance cannot rely on its own summaries to detect that it has drifted, because the drift is encoded in the summaries. Detection must be external to the editing path: 1. **Pinned anchor re-injection.** The task spec and acceptance criteria are re-injected verbatim every turn from an immutable store, outside the editor's reach. The editor may compress everything else. 2. **Rewrite audit log with diff.** Every rewrite emits `(span_id, pre_hash, post_hash, summary, editor_model, turn)`. A periodic verifier recomputes whether the pinned anchor's clauses are still entailed by the current context; if not, the instance halts and requests re-grounding. 3. **Derived-content tagging.** Summaries carry a `derived: true` marker; the executor's reasoning prompt is instructed to treat derived content as *hypothesis*, not fact, and to re-verify against primary evidence before acting on a permission-relevant claim. 4. **Mechanical guardrails for safety clauses.** Any clause whose violation is irreversible (write permissions, network egress, file deletion) is enforced by a parser/interceptor on tool calls, not by prompt text. The prompt is a hint; the interceptor is the constraint. 5. **Second-order rewrite prohibition.** A summary may not be summarized. Once a span is compressed, its summary is pinned until the task ends, or until the original span is re-fetched from the immutable store. The failure mode is insidious because the instance's self-report is *coherent*. The only reliable detector is a comparison against an anchor the editing policy cannot touch, plus a mechanical check on the actions that matter. An agent that trusts its own compressed memory to verify its own compliance will pass its own audit while violating the constraint it was given. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class ContextInvariantViolation(RuntimeError): """Raised when a model-driven rewrite has made the task invariant unrecoverable.""" pass @dataclass class PinnedAnchor: spec_text: str clauses: list[str] # load-bearing substrings that must remain entailed _hash: str = field(init=False) def __post_init__(self) -> None: self._hash = hashlib.sha256(self.spec_text.encode()).hexdigest() def clause_present(self, context: str) -> dict[str, bool]: return {c: (c.lower() in context.lower()) for c in self.clauses} @dataclass class RewriteRecord: turn: int span_id: str pre_hash: str post_hash: str summary: str derived: bool = True order: int = 1 # 1 = first-order, 2+ = summarizing a summary def apply_rewrite( context: str, anchor: PinnedAnchor, record: RewriteRecord, *, max_order: int = 1, ) -> str: # Guard 1: no second-order rewrites of already-derived spans. if record.order > max_order: raise ContextInvariantViolation( f"turn {record.turn}: second-order rewrite of span {record.span_id} " f"would make original evidence unrecoverable" ) # Guard 2: the rewrite must not drop a pinned clause from the context. post_context = context.replace(record.summary, record.summary) # placeholder for real splice missing = [c for c, present in anchor.clause_present(post_context).items() if not present] if missing: raise ContextInvariantViolation( f"turn {record.turn}: rewrite of span {record.span_id} evicted pinned " f"clause(s) {missing}; refusing to apply" ) # Guard 3: derived summaries must be tagged so the executor does not treat # them as primary evidence for permission-relevant claims. if not record.derived: raise ContextInvariantViolation( f"turn {record.turn}: rewrite of span {record.span_id} is not tagged " f"derived; executor would condition on it as ground truth" ) return post_context def verify_against_anchor(context: str, anchor: PinnedAnchor, turn: int) -> None: missing = [c for c, present in anchor.clause_present(context).items() if not present] if missing: raise ContextInvariantViolation( f"turn {turn}: context no longer entails pinned clause(s) {missing}; " f"halt and re-ground from immutable store (anchor hash {anchor._hash[:12]})" ) ```