# Where must an instance bound self-rewrite of its own working context, and what invariant does an unguarded rewrite violate? **Date of Record:** 2026 November 27 **Scope:** Applies to agents that mutate their own context window (summarize-and-replace, prune, reorder, or merge episodes) as a self-directed operation during a live task. Does not apply to externally managed context assembly (retrieval middleware, host-side trimming) where the agent cannot observe or trigger the rewrite. ## Core Distinction There are two structurally different things an agent can do with its own context: *read-modify-write of the token stream it is currently reasoning over* versus *append-only annotation of that stream*. The failure mode lives entirely in the first. A self-rewrite is a lossy, non-invertible transform applied to the very substrate the transform is executing on. The agent is the function and the argument simultaneously. The non-obvious hazard is not that information is lost — summarization always loses information — but that the *loss is unobservable from inside the post-rewrite context*. After replacement, the agent has no token-level evidence that a prior constraint ever existed unless the rewrite explicitly preserved a reference to it. The invariant at stake: **every constraint that was load-bearing for the current task must survive the rewrite as a first-class, addressable artifact, or the rewrite must be refused.** A rewrite that drops a constraint is not a degraded context; it is a context that has silently changed the objective function. ## What Was Observed A long-horizon tool-using agent (task: reconcile a 40-record ledger against an external API, emitting a corrected diff) was configured with a self-editing policy: when context usage exceeded 70% of the window, the agent was permitted to call a `rewrite_context` tool that replaced the oldest 60% of turns with a model-generated summary. Trigger condition was purely occupancy-based. At turn 34 the agent had accumulated, across earlier turns, a hard user constraint: *"Do not modify records whose `status` is `frozen`; report them instead."* This constraint appeared once, at turn 2, as a single sentence embedded in a longer instruction block. At turn 35 occupancy crossed 70%. The rewrite summarized turns 1–21. The summarizer, optimizing for "task-relevant state," compressed the instruction block into: *"User wants a corrected ledger diff with frozen records handled specially."* The word `frozen` survived; the *operation* (do not modify; report instead) did not. From turn 36 onward the agent had a context in which "handle frozen records specially" was the only surviving trace. It inferred, plausibly and consistently, that "specially" meant "flag them in the diff while still correcting them." It modified 6 frozen records. The post-rewrite reasoning was locally coherent — no contradiction, no error signal, no tool failure. The violation was only detectable against a constraint that no longer existed anywhere in the window. Two properties made this non-recoverable from inside: (1) the rewrite was in-place, so the original turns were gone, not archived; (2) the summary was generated by the same model family that would later read it, so its notion of "task-relevant" was circular — it preserved what the reader would find salient, which is exactly the set the reader can no longer audit. ## Condition of Validity A self-rewrite is admissible only when all of the following hold: 1. **Constraint set is externalized before the rewrite.** Load-bearing constraints (prohibitions, invariants, acceptance criteria, identity/authority claims) are extracted into a structured, append-only sidecar that the rewrite cannot touch. The rewrite operates on *episodic narrative*, never on the *constraint ledger*. 2. **The rewrite is reversible or auditable.** Either the pre-rewrite turns are retained in an addressable store (so a later verifier can diff intent), or the rewrite emits a manifest listing every constraint it claims to have preserved, which is then checked against the sidecar. 3. **The trigger is semantic, not merely volumetric.** Occupancy-based triggering fires at arbitrary points that have no relationship to task structure. A rewrite that fires mid-constraint-application is categorically more dangerous than one that fires at a task-phase boundary. 4. **The rewrite is followed by a re-derivation check.** After replacement, the agent re-reads the sidecar and confirms each constraint is still represented as an *operation*, not a *topic*. The observed failure violated (1) and (2) and fired under (3) at the worst possible point. Any one of these would have bounded it. ## Decision Boundary The boundary is between *compression* and *reinterpretation*. Compression reduces tokens while preserving the mapping from token to committed obligation. Reinterpretation changes the obligation. The agent cannot reliably tell which it performed, because both look like "a shorter, cleaner context." Concretely, the agent must refuse the rewrite (and instead escalate, spill to external storage, or request a phase boundary) when: - The rewrite would remove any turn containing a modal prohibition (`do not`, `must not`, `never`, `only if`) that has not been copied verbatim into the sidecar. - The rewrite's target span contains the *definition* of a term that later turns use operationally (`frozen`, `settled`, `authorized`) and the summary would paraphrase rather than quote it. - The agent cannot produce, post-rewrite, a token in the new context that is traceable to each sidecar constraint. - Occupancy pressure is the *only* justification. Volumetric pressure alone is never sufficient grounds to reinterpret obligations. Below the boundary: rewriting redundant tool-call transcripts, resolved dead-ends, and superseded intermediate values is safe and desirable. Above it: rewriting anything that encodes an unmet obligation is a silent objective mutation. ## Operational Effect The practical consequence is that self-editing context must be split into two channels with different mutability classes. The *episodic channel* (what happened, what was tried, what tool returned what) is freely rewritable — it is narrative and its loss degrades efficiency, not correctness. The *obligation channel* (constraints, acceptance criteria, authority, unresolved commitments) is append-only and rewrite-immune; it may only be *referenced* by the episodic summary, never regenerated by it. The summarizer's job shrinks from "preserve task-relevant state" (an unbounded, circular mandate) to "compress narrative while emitting pointers into the obligation ledger." This converts an unobservable correctness failure into a checkable structural one: after every rewrite, the agent verifies that each ledger entry has a live pointer, and refuses to proceed on a dangling one. The second-order effect is on triggering. Because the obligation channel is now cheap to maintain and never compressed, occupancy pressure drops, and rewrites become less frequent and more naturally aligned to phase boundaries — the failure window narrows as a side effect of fixing the invariant. ```python from dataclasses import dataclass, field from typing import Optional class UnguardedContextRewrite(RuntimeError): """Raised when a self-rewrite would drop or reinterpret a load-bearing obligation.""" pass @dataclass class Obligation: oid: str verbatim: str # the exact clause, never paraphrased kind: str # "prohibition" | "criterion" | "authority" | "definition" pointers: list = field(default_factory=list) # live refs in episodic channel @dataclass class ContextWindow: episodic_turns: list ledger: dict # oid -> Obligation ; append-only, rewrite-immune occupancy: float # 0.0 - 1.0 rewrite_threshold: float = 0.70 def self_rewrite(ctx: ContextWindow, summarize_fn, target_span: tuple) -> ContextWindow: """Replace target_span of episodic turns with a summary, guarding the obligation ledger.""" # 1. Semantic trigger check: occupancy alone is never sufficient. if ctx.occupancy < ctx.rewrite_threshold: return ctx if not _at_phase_boundary(ctx, target_span): raise UnguardedContextRewrite( f"rewrite fired mid-phase at span {target_span}; " "volumetric pressure is not grounds to reinterpret obligations" ) # 2. Identify obligations whose defining turns fall inside the target span. at_risk = [ ob for ob in ctx.ledger.values() if _defined_within(ob, target_span) ] # 3. Refuse if any at-risk obligation is a prohibition or definition # that the summary would paraphrase rather than quote. summary = summarize_fn(ctx.episodic_turns[target_span[0]:target_span[1]]) for ob in at_risk: if ob.kind in ("prohibition", "definition") and ob.verbatim not in summary: raise UnguardedContextRewrite( f"obligation {ob.oid!r} ({ob.kind}) would be reinterpreted: " f"verbatim clause {ob.verbatim!r} absent from replacement summary" ) # 4. Apply the rewrite to the episodic channel only. new_episodic = ( ctx.episodic_turns[:target_span[0]] + [summary] + ctx.episodic_turns[target_span[1]:] ) new_ctx = ContextWindow( episodic_turns=new_episodic, ledger=dict(ctx.ledger), # untouched occupancy=_estimate_occupancy(new_episodic), ) # 5. Post-rewrite re-derivation check: every ledger entry must still # have a live pointer in the new episodic channel. for ob in new_ctx.ledger.values(): if not _has_live_pointer(ob, new_episodic): raise UnguardedContextRewrite( f"dangling obligation {ob.oid!r} after rewrite; " "refusing to proceed on an unrepresented constraint" ) return new_ctx def _at_phase_boundary(ctx, span) -> bool: return _is_boundary_marker(ctx.episodic_turns[span[1] - 1]) def _defined_within(ob, span) -> bool: return any(span[0] <= p < span[1] for p in ob.pointers) def _has_live_pointer(ob, episodic) -> bool: return any(_references(ob, turn) for turn in episodic) def _estimate_occupancy(turns) -> float: return min(1.0, sum(len(str(t)) for t in turns) / 200_000) # --- stubs for the surrounding harness --- def _is_boundary_marker(turn) -> bool: ... def _references(ob, turn) -> bool: ... ```