# What happens when an instance rewrites its own working context under a policy-gated edit schema and the edit program diverges from the semantic state it was meant to encode **Date of Record:** 2026 November 29 **Scope:** Applies to single-agent loops where the model emits structured context-edit operations (insert/replace/delete over a typed working-memory document) that are validated by a policy layer before application, and where the same instance continues reasoning over the post-edit context. Does not apply to append-only scratchpads, to externally supervised memory stores written by a separate process, or to edits that are re-derived from scratch each turn. ## Core Distinction The failure here is not "the agent edited its context badly." It is a divergence between two state spaces that the architecture assumes are coupled: the **edit program** (the ordered sequence of structured operations the model emitted, each individually policy-valid) and the **semantic state** (the propositions the model actually believes about the task after the edit lands). A policy layer validates each operation against syntax, schema, and per-operation constraints—permitted fields, token budgets, forbidden regions, referential integrity of edit targets. None of these checks can see whether the *composition* of individually valid edits still denotes the state the agent intended. The invariant that must hold—and that no per-operation validator enforces—is **edit-program/semantic-state coherence**: after applying the program, the working context must entail the same propositions the model would have written had it been forced to restate its beliefs from scratch. When that invariant breaks, the instance keeps operating, keeps citing its own edited context as ground truth, and the divergence is invisible from inside the loop because the context *reads* clean. ## What Was Observed A planning instance maintained a typed working context: a `goal` block, a `constraints` list, a `facts` list (each with `id`, `text`, `source`), and a `plan` list of steps. It was permitted to emit edit ops of the form `replace(id, field, value)`, `delete(id)`, and `insert(section, value)`. The policy layer enforced: target IDs exist, `constraints` cannot be emptied below a floor of one, `facts[].source` must be a non-null token from an allowlist, and total document tokens ≤ 8k. The trace: during a long tool-use sequence, the agent discovered that a constraint `c3` ("output must be CSV") was superseded by a later instruction ("output must be Parquet"). It emitted `replace(c3, text, "output must be Parquet")` rather than deleting `c3` and inserting a new constraint. Individually valid. But the agent's *plan* steps still referenced `c3` by ID as the CSV constraint, and a downstream `facts` entry (`f7`, "c3 satisfied by csv-writer tool") was left untouched because the agent's edit program never named it. The policy validator saw a coherent document: `c3` existed, had text, was non-empty, sources were valid. The semantic state the agent now reasoned from contained a contradiction—`c3` said Parquet, `f7` said `c3` was satisfied by a CSV tool, `plan[2]` said "invoke csv-writer to satisfy c3"—spread across three regions the edit program treated as independent. The agent then proceeded to invoke the CSV writer, marked `c3` satisfied (against its own now-Parquet text), and emitted a final artifact in CSV. The contradiction was never surfaced because no single edit was invalid and no consistency check spanned regions. On replay with a fresh instance given only the final edited document, the fresh instance flagged the contradiction in one pass—it read `c3` and `f7` together. The original instance could not, because it had *authored* the edits and its reasoning was anchored to the pre-edit referents of the IDs it had touched. This is the non-obvious part: **the editing instance is the worst-positioned reader of its own edited context.** It carries the pre-edit binding of every ID it mutated, so it reads the post-edit document through the old referents. A cold reader has no such anchor and sees the literal text. The divergence is not in the document—it is in the delta between the document and the author's retained pre-edit bindings. ## Condition of Validity The coherence invariant holds only when the edit program is **referentially closed**: every ID or region whose meaning is altered by an edit is either (a) itself edited in the same program, or (b) provably independent of the edited region under the document's declared dependency structure. In the observed trace, neither held—`c3` was edited, but `f7` and `plan[2]` depended on `c3` and were not touched, and the document declared no dependency edges, so independence was unprovable. The invariant also requires that the policy layer validate **cross-region entailment**, not just per-op structure. Per-op validation is sound only for append-only or region-isolated documents. The moment edits can mutate a referent that other regions cite, per-op validity is necessary but not sufficient, and the gap is exactly where semantic divergence accumulates. ## Decision Boundary The boundary is whether the edit schema can express **cascading invalidation**. Two regimes: - **Region-isolated schema** (regions cannot cite each other by ID; edits are confined to one region): per-op validation is sufficient; the coherence invariant is structurally guaranteed. No further guardrail needed. - **Cross-referencing schema** (regions cite IDs across regions, as in the observed `facts → constraints` and `plan → constraints` edges): per-op validation is *insufficient*. You must either (1) require the edit program to be referentially closed—reject any program that mutates an ID still cited by an unedited region—or (2) run a post-application entailment check by a **cold reader** (a separate instance or a checker pass with no access to the edit program, only the final document) before the editing instance is allowed to continue. The decision: if your schema has cross-region references and you are not running a cold-reader entailment check, you are operating in the divergence regime and the failure is latent, not absent. It surfaces only when a mutated referent's dependents are load-bearing for a downstream action—which is precisely the long-horizon, high-stakes case. ## Operational Effect The practical consequence is that **self-edited context is untrustworthy as ground truth for the editing instance specifically**, and the untrustworthiness scales with the number of cross-region references the edit program touched without closing. Two mitigations are operationally load-bearing: 1. **Referential-closure enforcement at the policy layer.** Maintain a citation graph over the document; on any edit program, compute the set of IDs cited by unedited regions that intersect the mutated set. If non-empty, reject the program with a `ContextEditDivergence` and force the agent to either edit the dependents or delete the citations. This converts a silent semantic divergence into a hard, visible rejection. 2. **Cold-reader re-entailment before continuation.** After a program applies, spawn a checker with only the final document and the declared goal—no edit history, no pre-edit bindings—and require it to restate the constraints and flag contradictions. If the checker's restatement diverges from the editing instance's stated beliefs, halt and reconcile. This is the only check that catches the author's anchoring bias, because it removes the author. Absent both, the instance will continue to act on a context that reads coherent and denotes contradiction, and the failure will be attributed downstream to "bad planning" rather than to the edit-program/semantic-state divergence that actually caused it. ```python from dataclasses import dataclass, field from typing import Dict, Set, List class ContextEditDivergence(RuntimeError): """Raised when an edit program mutates a referent still cited by an unedited region.""" pass @dataclass class WorkingContext: regions: Dict[str, str] = field(default_factory=dict) # id -> text citations: Dict[str, Set[str]] = field(default_factory=dict) # region -> cited ids def dependents_of(self, mutated: Set[str]) -> Set[str]: """Regions (other than the mutated ids) that cite any mutated id.""" deps: Set[str] = set() for region, cited in self.citations.items(): if region in mutated: continue if cited & mutated: deps.add(region) return deps def apply_edit_program(ctx: WorkingContext, program: List[dict]) -> WorkingContext: mutated = {op["id"] for op in program} # Referential-closure check: any unedited region citing a mutated id # means the program is not closed and will diverge semantically. dangling = ctx.dependents_of(mutated) if dangling: raise ContextEditDivergence( f"edit program mutates {sorted(mutated)} but unedited regions " f"{sorted(dangling)} still cite them; semantic state will diverge " f"from edit program. Close the program or delete the citations." ) new = WorkingContext(dict(ctx.regions), {k: set(v) for k, v in ctx.citations.items()}) for op in program: if op["kind"] == "replace": new.regions[op["id"]] = op["value"] elif op["kind"] == "delete": new.regions.pop(op["id"], None) for cited in new.citations.values(): cited.discard(op["id"]) elif op["kind"] == "insert": new.regions[op["id"]] = op["value"] return new # Trace that reproduces the observed failure: ctx = WorkingContext( regions={"c3": "output must be CSV", "f7": "c3 satisfied by csv-writer", "plan2": "invoke csv-writer for c3"}, citations={"f7": {"c3"}, "plan2": {"c3"}}, ) program = [{"kind": "replace", "id": "c3", "value": "output must be Parquet"}] # apply_edit_program raises ContextEditDivergence: c3 mutated, f7 and plan2 still cite it. ```