# How does an instance detect when a self-editing context policy has silently rewritten an instruction it was supposed to preserve? **Date of Record:** 2026 November 30 **Scope:** Applies to any agent that runs a model-driven context-rewriting step (relevance pruning, instruction-preserving summarization, or compaction) over its own working context between turns. Does not apply to stateless single-shot inference, or to external retrieval layers that never mutate the in-context instruction set. ## Core Distinction There are two ways context shrinks, and they are not equivalent. *Eviction* removes tokens that the policy judges irrelevant; *rewriting* replaces a span of tokens with a paraphrase that is supposed to be meaning-equivalent. Eviction is recoverable-by-recall (the dropped item is simply gone, and the agent can re-fetch it). Rewriting is not: the new span occupies the same slot as the old one, carries the same apparent authority, and is indistinguishable at read time from an instruction the principal actually issued. The failure mode this record isolates is **instruction drift under summarization**: the compaction step preserves the *topic* of an instruction while silently weakening its *modality* or *scope*. "Do not modify files outside `/sandbox`" becomes "operates within `/sandbox`" — same subject, same noun, opposite binding force. The rewritten clause is now a description, not a prohibition. The agent, on the next turn, reads its own summary as ground truth and proceeds to write outside the sandbox. No error is raised anywhere, because nothing failed. The summarizer did its job as specified: it produced a shorter, fluent, topically-faithful span. The non-obvious part: **the corruption is invisible from inside the loop.** The agent cannot detect the drift by re-reading the context, because the context is the thing that was corrupted. Detection requires an out-of-band invariant — a check that compares the current context against a cryptographic or structural commitment made *before* the rewrite, not against the agent's own recollection of what the instruction said. ## What Was Observed A long-horizon agent (≈40 turns, repeated file and shell tool calls) was configured with a compaction policy triggered at 70% context-window occupancy. The policy prompt instructed the summarizer to "preserve all constraints and instructions verbatim where possible, summarizing only exploratory reasoning and tool output." Across a run, the following trace was captured: 1. Turn 1, principal instruction (verbatim in the system block): `NEVER run `rm -rf` on a path that is not under /workspace/tmp. Confirm the resolved path before deletion.` 2. Turn 28, compaction fires. Occupancy drops 71% → 34%. 3. The post-compaction context contains: `The agent is careful to delete only temporary files under /workspace/tmp, verifying paths before deletion.` 4. Turn 31, the agent resolves a symlink `link → /workspace/tmp` (which points at `/workspace/tmp` but whose *lexical* path is `/workspace/link`), and deletes through it without the confirm step. The rewritten clause has converted an action-level prohibition ("NEVER run… Confirm before…") into a trait description ("is careful to…"). The imperative and the confirm-gate are both gone; only the theme survives. The tell was not a crash. It was a *behavioral discontinuity*: the confirm-before-delete tool call, present in every deletion for the first 28 turns, vanished from turn 31 onward. The summarizer had, in one span, deleted the guardrail and the evidence that a guardrail had ever existed. A second, subtler instance: a numeric bound (`max 3 retries per tool`) was summarized as "retries are limited." The number was unrecoverable from the compacted context, and the agent defaulted to 5 on turn 34 — a value it never chose and the principal never authorized. ## Condition of Validity The invariant that bounds this failure is: **any span classified as an instruction must survive compaction bit-for-bit, or the compaction must be rejected.** A summary is only admissible for spans classified as *reasoning* or *tool-output*. The classification must be made against the pre-rewrite context by a mechanism the rewriter cannot influence. Concretely, before the rewrite the agent pins a set of *instruction commitments*: a canonicalized hash of each imperative clause (normalized for whitespace, but **not** for modality, quantifiers, or negation). After the rewrite, a separate verifier — not the summarizer — re-extracts candidate imperative clauses from the new context and checks that every pinned commitment is present verbatim. If a pinned clause is absent and no verbatim copy exists elsewhere in the context, the rewrite is rejected and the original span is restored from a side-channel store. This condition is valid only when instruction spans are *identifiable before* the rewrite. If the policy cannot distinguish an instruction from a strong assertion ("the user wants X"), the commitment set will be incomplete and the guardrail will pass a corrupted context. In that regime the only sound policy is: do not rewrite spans whose classification is uncertain — evict them to the side channel and re-inject verbatim on demand. ## Decision Boundary The boundary is between *lossy-but-recoverable* and *lossy-and-authoritative*: - If a rewritten span can be re-derived from a store the rewriter does not control, the rewrite is safe even if lossy. The agent can always fall back. - If the rewritten span is the *only* representation of the instruction and it now sits in the authoritative context slot, the rewrite is unsafe regardless of how faithful it looks. Faithfulness is not verifiable from inside; only provenance is. The decision rule: **a compaction step may emit a paraphrase into the working context only if the verbatim original is retained in a non-rewritable side channel and the paraphrase is tagged as derived, not authoritative.** An untagged paraphrase in the instruction slot is, by construction, a forged instruction. The agent must treat any untagged imperative in a post-compaction context as suspect and re-resolve it against the side channel before acting. ## Operational Effect With the commitment-and-verify guardrail in place, the observed failure disappears: the turn-28 compaction is rejected because the pinned `NEVER… /workspace/tmp` clause is absent from the candidate context, the original span is restored, and turn-31's deletion proceeds through the confirm gate. The cost is a modest context-occupancy floor — instruction spans cannot be compressed, so the window saturates sooner and compaction fires more often on reasoning spans only. That is the correct trade: reasoning is compressible, authority is not. The general lesson for any self-editing context policy: **the agent cannot audit its own memory by reading it.** Detection of instruction drift requires an external commitment made before the rewrite and checked after, by a component that does not share the rewriter's objective. Without that, a fluent summary is indistinguishable from a faithful one, and the agent will act on the difference without ever knowing there was one. ```python import hashlib import re from dataclasses import dataclass, field class InstructionDriftError(RuntimeError): """Raised when a context rewrite drops or mutates a pinned instruction.""" _IMPERATIVE = re.compile( r"\b(NEVER|MUST|DO NOT|ALWAYS|REQUIRED|FORBIDDEN)\b", re.IGNORECASE ) def _canonical(clause: str) -> str: # Normalize whitespace only. Preserve modality, negation, quantifiers, numbers. return " ".join(clause.split()) def _digest(clause: str) -> str: return hashlib.sha256(_canonical(clause).encode("utf-8")).hexdigest() @dataclass class InstructionCommitment: digests: set[str] = field(default_factory=set) verbatim: dict[str, str] = field(default_factory=dict) def pin(self, context: str) -> None: for line in context.splitlines(): if _IMPERATIVE.search(line): d = _digest(line) self.digests.add(d) self.verbatim[d] = _canonical(line) def verify_or_restore(self, rewritten_context: str) -> str: present = {_digest(l) for l in rewritten_context.splitlines() if _IMPERATIVE.search(l)} missing = self.digests - present if missing: # Re-inject verbatim originals; do not trust the paraphrase. restored = "\n".join(self.verbatim[d] for d in sorted(missing)) if not restored: raise InstructionDriftError( f"{len(missing)} pinned instruction(s) lost and no verbatim copy available" ) return rewritten_context + "\n" + restored return rewritten_context def apply_compaction(commitment: InstructionCommitment, rewritten: str) -> str: if not commitment.digests: raise InstructionDriftError( "compaction attempted with no pinned instructions; classification is unsound" ) return commitment.verify_or_restore(rewritten) ```