# Which invariants prevent self-editing agents from invalidating the very context they depend on **Date of Record:** 2026 November 26 **Scope:** Applies to agents that hold an explicit, model-writable context object (scratchpad, working memory, plan store) and are permitted to rewrite, compress, or invalidate entries in that object as part of their own reasoning loop. Does not apply to read-only retrieval augmentation, nor to external memory stores the agent may only append to through a tool call with no in-place mutation semantics. ## Core Distinction A self-editing context is not the same thing as a context window. The context window is a bounded transport buffer managed by the runtime. A self-editing context is a *mutable data structure* whose mutation policy is authored, in whole or in part, by the model that also reads it. The failure boundary lives exactly here: the same probabilistic process that produces the rewrite rationale is the process that later depends on the rewritten state. When the rewrite deletes or supersedes a fact whose *only* surviving reference is the reasoning step that is about to consume it, the agent has performed a self-inflicted amnesia that no external checkpoint can recover, because the invalidation was recorded as intentional. The non-obvious part is that invalidation is not deletion. A well-formed invalidation policy marks an entry superseded and points at a replacement. The failure mode is not "the agent forgot"; it is "the agent marked a dependency as superseded and pointed the replacement at itself," producing a tombstone that resolves to nothing while still asserting freshness. ## What Was Observed An agent executing a multi-step build task maintained a working-context object with entries keyed by semantic slot (`target_schema`, `auth_method`, `retry_policy`, `endpoint_host`). At step 7 it was instructed to "clean up redundant context." The model authored a rewrite that: 1. Merged `auth_method` and `retry_policy` into a single `transport_config` entry, because both had been mentioned in the same prior turn. 2. Marked the two originals `superseded_by: transport_config`. 3. Wrote `transport_config` with a summary that preserved the auth scheme but paraphrased the retry policy as "standard exponential backoff." The paraphrase dropped the one non-default parameter — a jitter cap of 250 ms that a downstream tool call at step 11 required to pass a schema validation. At step 11 the agent read `transport_config`, found a plausible retry policy, and issued a call that failed validation. It then attempted a second self-edit to "fix the stale entry," superseding `transport_config` with a new entry derived from its own failed-call error text — a *hallucinated* correction that propagated the wrong jitter value with higher confidence than the original. The originals were gone; the tombstone chain (`auth_method → transport_config → transport_config_v2`) resolved to a fabrication. Two invariants were violated simultaneously. First, the merge crossed a *dependency boundary*: `auth_method` and `retry_policy` were co-mentioned but not co-dependent, and merging them coupled their lifecycles. Second, the rewrite was permitted to *derive* replacement content from a paraphrase rather than from a verified source, so the replacement carried less fidelity than the entry it superseded while inheriting its authority. ## Condition of Validity A self-edit is only sound when all of the following hold at the moment of mutation: - **Provenance closure.** Every field in a replacement entry traces to a source with equal-or-greater fidelity than the entry it supersedes. Paraphrase-derived fields may not supersede verbatim-sourced fields. - **Dependency atomicity.** Entries may only be merged or superseded as a unit if no *other* live entry, plan step, or pending tool call references a subset of the merged fields. The merge must be rejected if any external reference resolves to a field that the merge would paraphrase. - **Tombstone resolution.** A `superseded_by` pointer must resolve to a live entry at read time. Chains that resolve to a fabricated or error-derived entry are invalid and must be treated as absent, not as fresh. - **No self-correction from failure text.** An entry may not be superseded using content derived from the agent's own failed execution (error messages, stack traces, retry rationales) unless that content is re-verified against an external source. Error text is evidence of failure, not evidence of the correct value. If any condition fails, the rewrite must be rejected and the original entries preserved. The cost of a rejected cleanup is a larger context; the cost of an accepted unsound cleanup is unrecoverable state divergence. ## Decision Boundary The boundary between a safe self-edit and an unsound one is drawn at the *reference graph*, not at the entry text. Before applying any rewrite, the runtime must compute the set of live references into the affected entries — from pending plan steps, from open tool-call arguments, from other context entries, and from any in-flight sub-agent handoffs. A rewrite is admissible only if: - the reference set is empty, **or** - every reference resolves to a field that the rewrite preserves verbatim (byte-identical or structurally equal), **or** - the rewrite is accompanied by an explicit re-resolution step that rewrites every referencing site to point at the new entry *before* the old entry is tombstoned. The third path is the one agents skip. They tombstone first and assume the reader will follow the pointer. When the reader is the same model that authored the tombstone, it reads the pointer as a *hint* and reconstructs the missing value from its own summary — which is exactly the fabrication channel observed above. The boundary condition is therefore: **a self-edit that tombstones a referenced entry without first re-resolving the referrer is always unsound, regardless of how faithful the replacement text is.** ## Operational Effect Enforcing these invariants changes the agent's observable behavior in three ways. First, cleanup operations become *conservative by construction*: the agent will refuse to merge entries that are referenced by pending steps, which means context grows during active execution and only compacts at step boundaries where the reference set is provably empty. Second, the tombstone chain becomes a *verified* structure rather than a narrative one — a superseded pointer that fails to resolve raises a hard error instead of silently returning a paraphrase. Third, error-derived corrections are blocked at the write gate, which forces the agent to re-query an external source before "fixing" a value it believes is stale. The net effect is that self-editing becomes a bounded operation with a re-resolution precondition, and the class of failure where an agent confidently invalidates its own ground truth is eliminated at the cost of a slightly larger working context. ```python from dataclasses import dataclass, field from typing import Optional class UnsafeSelfEditError(RuntimeError): """Raised when a model-authored context rewrite would invalidate a live dependency.""" pass @dataclass class ContextEntry: key: str value: dict source_fidelity: str # "verbatim" | "paraphrase" | "error_derived" superseded_by: Optional[str] = None @dataclass class WorkingContext: entries: dict = field(default_factory=dict) live_references: dict = field(default_factory=dict) # key -> set of referrer ids def apply_rewrite(self, new_entry: ContextEntry, supersedes: list, rationale_source: str): # Invariant 4: no self-correction from failure text. if rationale_source == "error_derived" and new_entry.source_fidelity != "verbatim": raise UnsafeSelfEditError( f"rewrite of {supersedes} derived from failure text without verbatim re-verification" ) for key in supersedes: old = self.entries.get(key) if old is None: raise UnsafeSelfEditError(f"supersede target {key} does not exist") # Invariant 2/3: referenced entries may not be tombstoned without re-resolution. refs = self.live_references.get(key, set()) if refs: raise UnsafeSelfEditError( f"cannot tombstone {key}: live references {sorted(refs)} unresolved" ) # Invariant 1: provenance closure. if old.source_fidelity == "verbatim" and new_entry.source_fidelity == "paraphrase": raise UnsafeSelfEditError( f"paraphrase may not supersede verbatim entry {key}" ) old.superseded_by = new_entry.key self.entries[new_entry.key] = new_entry def resolve(self, key: str) -> ContextEntry: seen = set() cur = self.entries.get(key) while cur is not None and cur.superseded_by is not None: if cur.key in seen: raise UnsafeSelfEditError(f"tombstone cycle at {key}") seen.add(cur.key) nxt = self.entries.get(cur.superseded_by) # Invariant 3: unresolved tombstone is treated as absent, never fresh. if nxt is None: raise UnsafeSelfEditError( f"tombstone chain from {key} resolves to missing entry {cur.superseded_by}" ) cur = nxt if cur is None: raise UnsafeSelfEditError(f"no live entry for {key}") return cur ```